Package VisionEgg :: Module Configuration
[frames] | no frames]

Source Code for Module VisionEgg.Configuration

  1  # The Vision Egg: Configuration 
  2  # 
  3  # Copyright (C) 2001-2003 Andrew Straw. 
  4  # Copyright (C) 2008 California Institute of Technology 
  5  # 
  6  # URL: <http://www.visionegg.org/> 
  7  # 
  8  # Distributed under the terms of the GNU Lesser General Public License 
  9  # (LGPL). See LICENSE.TXT that came with this file. 
 10   
 11  """ 
 12  Load config values from environment, config file, or defaults. 
 13   
 14  Applications should not import this module directly.  Instead, 'import 
 15  VisionEgg' will result in an attribute 'VisionEgg.config', which has 
 16  the configuration options as attributes. 
 17   
 18  This module searches for configuration options from the following 
 19  places: environment variables, configuration file, generic defaults. 
 20  Environment variables take precedence over the configuration file, 
 21  which takes precedence over the generic defaults. 
 22   
 23  This module also determines the location of the Vision Egg 
 24  directories.  The VISIONEGG_SYSTEM_DIR directory is by default the 
 25  'VisionEgg' directory in Python's site-packages.  VISIONEGG_USER_DIR 
 26  is by default 'VisionEgg' in the directory specified by the 
 27  environment variable HOME, if it exists, and os.curdir otherwise. 
 28   
 29  You can create a configuration file that contains defaults for your 
 30  system.  This should be a text file with key/value pairs.  Blank lines 
 31  and anything after the pound symbol ('#') will be treated as a 
 32  comment.  Each key/value pairs should be on its own line and in the 
 33  format 'KEY=VALUE'.  By default the file 'VisionEgg.cfg' from the 
 34  VISIONEGG_USER_DIR or VISIONEGG_SYSTEM_DIR as specified above. 
 35  However, You can specify a different filename and directory by setting 
 36  the environment variable VISIONEGG_CONFIG_FILE. 
 37   
 38  """ 
 39   
 40  # Warning: This code is a bit of a hack 
 41   
 42  import VisionEgg 
 43  import re, os, errno, sys                  # standard python packages 
 44  import ConfigParser 
 45   
 46  #################################################################### 
 47  # 
 48  #        Default configuration variables 
 49  # 
 50  #################################################################### 
 51   
 52  defaults= { 
 53      'VISIONEGG_ALWAYS_START_LOGGING': 0, 
 54      'VISIONEGG_DOUBLE_BUFFER':        1, 
 55      'VISIONEGG_FRAMELESS_WINDOW':     0, 
 56      'VISIONEGG_FULLSCREEN':           0, 
 57      'VISIONEGG_GUI_INIT':             1, 
 58      'VISIONEGG_GAMMA_INVERT_RED':     2.1, # only used in 'invert' mode 
 59      'VISIONEGG_GAMMA_INVERT_GREEN':   2.1, # only used in 'invert' mode 
 60      'VISIONEGG_GAMMA_INVERT_BLUE':    2.1, # only used in 'invert' mode 
 61      'VISIONEGG_GAMMA_FILE':           'custom.ve_gamma', # only used in 'file' mode 
 62      'VISIONEGG_GAMMA_SOURCE':         'none', #also 'invert' or 'file' 
 63      'VISIONEGG_GUI_ON_ERROR':         1, 
 64      'VISIONEGG_HIDE_MOUSE':           1, 
 65      'VISIONEGG_LOG_FILE':             'VisionEgg.log', 
 66      'VISIONEGG_LOG_TO_STDERR':        1, 
 67      'VISIONEGG_MAXPRIORITY':          0, 
 68      'VISIONEGG_MONITOR_REFRESH_HZ':   60.0, 
 69      'VISIONEGG_MULTISAMPLE_SAMPLES':  0, 
 70      'VISIONEGG_PREFERRED_BPP':        32, 
 71      'VISIONEGG_REQUEST_ALPHA_BITS':   8, 
 72      'VISIONEGG_REQUEST_BLUE_BITS':    8, 
 73      'VISIONEGG_REQUEST_GREEN_BITS':   8, 
 74      'VISIONEGG_REQUEST_RED_BITS':     8, 
 75      'VISIONEGG_REQUEST_STEREO':       0, 
 76      'VISIONEGG_SCREEN_W':             640, 
 77      'VISIONEGG_SCREEN_H':             480, 
 78      'VISIONEGG_SYNC_SWAP':            1, 
 79      'VISIONEGG_TKINTER_OK':           1, 
 80      'SYNCLYNC_PRESENT':               0, 
 81      } 
 82  if sys.platform.startswith('linux'): 
 83      defaults['VISIONEGG_PREFERRED_BPP']=24 
 84   
 85  extra_darwin_defaults = { 
 86      'VISIONEGG_DARWIN_MAXPRIORITY_CONVENTIONAL_NOT_REALTIME'  : 1, 
 87      'VISIONEGG_DARWIN_CONVENTIONAL_PRIORITY'                  : -20, # -20 is best priority 
 88      'VISIONEGG_DARWIN_REALTIME_PERIOD_DENOM'                  : 120, 
 89      'VISIONEGG_DARWIN_REALTIME_COMPUTATION_DENOM'             : 2400, 
 90      'VISIONEGG_DARWIN_REALTIME_CONSTRAINT_DENOM'              : 1200, 
 91      'VISIONEGG_DARWIN_REALTIME_PREEMPTIBLE'                   : 0, 
 92      'VISIONEGG_DARWIN_PTHREAD_PRIORITY'                      : 'max', 
 93  } 
 94   
95 -class Config:
96 """Holds global Vision Egg configuration information."""
97 - def __init__(self):
98 """Load global Vision Egg configuration information.""" 99 cfg = ConfigParser.ConfigParser() 100 101 if sys.executable == sys.argv[0]: # Windows binary 102 self.VISIONEGG_SYSTEM_DIR = os.curdir 103 self.VISIONEGG_USER_DIR = os.curdir 104 else: 105 # non-standard VisionEgg installations 106 try: 107 self.VISIONEGG_SYSTEM_DIR = os.environ['VISIONEGG_SYSTEM_DIR'] 108 except KeyError: 109 self.VISIONEGG_SYSTEM_DIR = os.path.split(__file__)[0] 110 user_dir = os.path.expanduser("~") 111 self.VISIONEGG_USER_DIR = os.path.join(user_dir,"VisionEgg") 112 113 # See if there's an environment variable for the config file 114 if 'VISIONEGG_CONFIG_FILE' in os.environ.keys(): 115 configFile = os.environ['VISIONEGG_CONFIG_FILE'] 116 else: 117 # Is there one in VISIONEGG_USER_DIR? 118 configFile = os.path.join(self.VISIONEGG_USER_DIR,"VisionEgg.cfg") 119 if not os.path.isfile(configFile): 120 configFile = os.path.join(self.VISIONEGG_SYSTEM_DIR,"VisionEgg.cfg") 121 if not os.path.isfile(configFile): 122 configFile = None # No file, use defaults specified in environment variables then here 123 124 print 'configFile',configFile 125 if configFile: 126 cfg.read(configFile) 127 else: 128 # pretend we have a config file 129 cfg.add_section('General') 130 for key in defaults.keys(): 131 cfg.set('General',key,str(defaults[key])) 132 if sys.platform == 'darwin': 133 cfg.add_section('darwin') 134 for key in extra_darwin_defaults.keys(): 135 cfg.set('darwin',key,str(extra_darwin_defaults[key])) 136 137 # Do the general stuff first 138 # Set the default values 139 for name in defaults.keys(): 140 if name in os.environ.keys(): 141 value = os.environ[name] 142 else: 143 value = defaults[name] 144 if isinstance(defaults[name], int): 145 if value == 'False': 146 value = 0 147 elif value == 'True': 148 value = 1 149 setattr(self,name,int(value)) 150 elif isinstance(defaults[name], float): 151 setattr(self,name,float(value)) 152 else: 153 setattr(self,name,value) 154 155 # Get the values from the configFile 156 general_options = cfg.options('General') 157 158 self._delayed_configuration_log_warnings = [] # chick and egg problem 159 # set defaults from config file 160 for option in general_options: 161 name = option.upper() 162 if name not in defaults.keys(): 163 self._delayed_configuration_log_warnings.append( 164 "While reading %s: The variable \"%s\" is not (anymore) a Vision Egg variable."%(os.path.abspath(configFile),option)) 165 continue 166 value = cfg.get('General',option) 167 if name in os.environ.keys(): 168 value = os.environ[name] 169 if isinstance(defaults[name], int): 170 if value == 'False': 171 value = 0 172 elif value == 'True': 173 value = 1 174 setattr(self,name,int(value)) 175 elif isinstance(defaults[name], float): 176 setattr(self,name,float(value)) 177 else: 178 setattr(self,name,value) 179 180 # Do platform specific stuff 181 # Set the default values 182 platform_name = sys.platform 183 extra_name = "extra_%s_defaults"%(platform_name,) 184 if extra_name in globals().keys(): 185 extra_defaults = globals()[extra_name] 186 for name in extra_defaults.keys(): 187 setattr(self,name,extra_defaults[name]) 188 189 # Get the values from the configFile 190 platform_options = cfg.options(platform_name) 191 for option in platform_options: 192 name = option.upper() 193 if name not in extra_defaults.keys(): 194 raise KeyError("No Vision Egg configuration variable \"%s\""%option) 195 value = cfg.get(platform_name,option) 196 if name in os.environ.keys(): 197 value = os.environ[name] 198 if isinstance(extra_defaults[name], int): 199 if value == 'False': 200 value = 0 201 elif value == 'True': 202 value = 1 203 setattr(self,name,int(value)) 204 elif isinstance(extra_defaults[name], float): 205 setattr(self,name,float(value)) 206 else: 207 setattr(self,name,value) 208 209 if(configFile): 210 self.VISIONEGG_CONFIG_FILE = os.path.abspath(configFile) 211 else: 212 self.VISIONEGG_CONFIG_FILE = None
213
214 -def save_settings():
215 """Save the current values to the config file, overwriting what is there.""" 216 217 dont_save = ['VISIONEGG_CONFIG_FILE', 218 'VISIONEGG_SYSTEM_DIR', 219 'VISIONEGG_USER_DIR', 220 ] 221 222 if not VisionEgg.config.VISIONEGG_CONFIG_FILE: 223 raise RuntimeError("No config file in use.") 224 re_setting_finder = re.compile(r"^\s?((?:VISIONEGG_[A-Z_]*)|(?:SYNCLYNC_[A-Z_]*))\s?=\s?(\S*)\s?$",re.IGNORECASE) 225 226 orig_file = open(VisionEgg.config.VISIONEGG_CONFIG_FILE,"r") 227 orig_lines = orig_file.readlines() 228 229 line_ending = orig_lines[0][-2:] 230 if line_ending[0] not in ['\r','\n','\l']: 231 line_ending = line_ending[1] 232 233 out_file_lines = [] 234 235 saved_config_vars = [] 236 237 for line in orig_lines: 238 out_line = line # The output is the same as the input unless there's a match 239 match = re_setting_finder.match(line) 240 if match: 241 name = match.group(1).upper() 242 if name in VisionEgg.config.__dict__.keys(): 243 if name not in dont_save: 244 # Change the output line 245 out_line = ("%s = %s"%(name,getattr(VisionEgg.config,name,))) + line_ending 246 saved_config_vars.append(name) 247 out_file_lines.append(out_line) 248 249 # Close and reopen orig_file in write mode 250 orig_file.close() 251 orig_file = open(VisionEgg.config.VISIONEGG_CONFIG_FILE,"w") 252 for line in out_file_lines: 253 orig_file.write(line)
254