123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238 |
- """
- Configuration Module.
- This reads the configuration file and conveniently makes the settings available to KCG
- """
- import os
- import sys
- if sys.version_info[:3] < (3,0):
- import ConfigParser as configparser
- else:
- import configparser
-
- import ast
- import sys
- import logging
- install_path = ''
- from PyQt4.QtGui import QColor
- colours = [QColor(44, 62, 80), QColor(39, 174, 96), QColor(0, 112, 192), QColor(192, 57, 43), QColor(41, 128, 185), QColor(142, 68, 173), QColor(22, 160, 133,150), QColor(127, 140, 141)]
- coloursTrans = [QColor(44, 62, 80,100), QColor(39, 174, 96, 100), QColor(190, 128, 8,100), QColor(192, 57, 43,100), QColor(41, 128, 185), QColor(142, 68, 173), QColor(22, 160, 133,150), QColor(127, 140, 141)]
- shiftFMC2 = 0
- def icon_path(iconName):
- return os.path.join(install_path,"icons",iconName)
- def style_path(styleName):
- return os.path.join(install_path,"style",styleName)
- def config_path(filename=""):
- if filename == "":
- return os.path.join(os.path.expanduser("~"),".kcg2")
- return os.path.join(os.path.expanduser("~"),".kcg2", filename)
- from .base import storage
- def working_path(filename=""):
- if filename == "":
- return os.path.join(storage.storage.save_location, storage.storage.subdirname)
- return os.path.join(storage.storage.save_location, storage.storage.subdirname, filename)
- class NoValueException(Exception):
- """
- Simple Exception that gets thrown when no Value was given in the configuration file
- """
- pass
- class MisconfigurationError(Exception):
- """
- Simple Exception to indicate that a misconfiguration was found.
- """
- pass
- def leval(string):
- """
- Wrapper arount ast.literal_eval that throws NoValueException if the value was empty
- :param string:
- :return:
- """
- if string == "":
- raise NoValueException("No value given for option")
- else:
- return ast.literal_eval(string)
- class ConfSection(object):
- """
- Class to handle a section in the configuration.
- """
- def __init__(self, section, settings, config_object, default_config_object=None, log_level=logging.ERROR):
- self._section = section
- self._settings = settings
- self._conf_obj = config_object
- self._def_conf_obj = default_config_object
- self._arg_dict = {}
- self._log_level = log_level
- def feed_arguments(self, arg_dict):
- """
- Feed this section with commandline arguments for this section. The given arguments will
- override the ones in configuration files.
- :param arg_dict: the dictionary for all sections
- :return:
- """
- if self._section in arg_dict:
- self._arg_dict = arg_dict[self._section]
- else:
- self._arg_dict = {}
- def read(self):
- """
- Read and evaluate configuration settings.
- :return:
- """
- error = False
- for conf in self._settings:
-
- if conf in self._arg_dict:
- try:
- globals()[conf] = leval(self._arg_dict[conf])
- continue
- except Exception:
- if self._log_level <= logging.ERROR:
- print("Error in parsing commandline configuration using configuration in config file.")
- if self._conf_obj.has_option(self._section, conf):
- try:
- globals()[conf] = leval(self._conf_obj.get(self._section, conf))
- except NoValueException:
- error = True
- elif self._def_conf_obj is not None:
- if self._log_level <= logging.DEBUG:
- print("Using default configuration value for " + conf)
- globals()[conf] = leval(self._def_conf_obj.get(self._section, conf))
- else:
- #print('error')
- error = True
- return not error
- class Configuration(object):
- """
- Class to handle configuration
- """
- def __init__(self, args=None, log_level=logging.INFO):
- self._args = args
- self._parsed_args = {}
- self.error = False
- self._log_level = log_level
- globals()['config_object'] = self
- globals()['log_level'] = log_level
- if args:
- self.parse_command_line()
- def parse_command_line(self):
- """
- Parses the command line configuration arguments
- :return:
- """
- if ';' in self._args:
- self._args = self._args.split(';')
- else:
- self._args = [self._args]
- for setting in self._args:
- if setting == '':
- continue
- try:
- sec, set = setting.strip().split('->')
- sets, setv = set.split('=')
- section = self._parsed_args.setdefault(sec, {})
- section[sets.strip()] = setv.strip()
- except:
- print("Format of commandline configuration is wrong. Using config file version")
- def read(self):
- """
- This function reads the configuration file and the default config fille (in case the
- user config file does not contain all values) and adds them as parameters to this module
- :return:
- """
- config = configparser.ConfigParser()
- config.optionxform = str
- config.read(config_path("config.cfg"))
- defaultConfig = configparser.ConfigParser()
- defaultConfig.optionxform = str
- defaultConfig.read(os.path.join(os.path.dirname(__file__), "default_config.cfg"))
- Machine_conf = ["bunches_per_turn", "save_header", "tRev"]
- Board_conf = ["working_channels"]
- Ui_conf = ["language", "default_save_location", "default_subdirectory_name", "force_ask", "show_advanced_control", "integrate_single_read", "use_epics"]
- Logging_conf = ["default_log_entries"]
- Misc_conf = ['newPlotLiveIcon', 'newPlotDataIcon', 'timingIcon', 'singleReadIcon',
- 'acquireSettingsIcon', 'startIcon', 'stopIcon', 'logIcon', 'logCommentIcon', 'guiIcon', 'style',
- 'board_detection_method', 'device_list', 'device_names',
- 'num_dummy_boards']
- try:
- machine_c = ConfSection('Machine', Machine_conf, config, defaultConfig, log_level=self._log_level)
- machine_c.feed_arguments(self._parsed_args)
- self.error = True if not machine_c.read() else self.error
- board_c = ConfSection('Board', Board_conf, config, defaultConfig, log_level=self._log_level)
- board_c.feed_arguments(self._parsed_args)
- self.error = True if not board_c.read() else self.error
- ui_c = ConfSection('Ui', Ui_conf, config, defaultConfig, self._log_level)
- ui_c.feed_arguments(self._parsed_args)
- self.error = True if not ui_c.read() else self.error
- logging_c = ConfSection('Logging', Logging_conf, config, defaultConfig, self._log_level)
- logging_c.feed_arguments(self._parsed_args)
- self.error = True if not logging_c.read() else self.error
- misc_c = ConfSection('Misc', Misc_conf, config, defaultConfig, self._log_level)
- misc_c.feed_arguments(self._parsed_args)
- self.error = True if not misc_c.read() else self.error
- # if config.has_section('Misc'):
- # for conf, val in config.items("Misc"):
- # globals()[conf] = leval(val)
- # for conf, val in defaultConfig.items("Misc"):
- # if not conf in globals().keys():
- # globals()[conf] = leval(val)
- except (configparser.NoOptionError, configparser.NoSectionError) as e:
- self.error = True
- print("There was an error parsing configuration: " + str(e))
- def setup(self):
- """
- Check for the user config file and if not exists calls doSetup
- :return:
- """
- if not os.path.isfile(config_path("config.cfg")):
- self.doSetup()
- else:
- self.read()
- def doSetup(self, rerun=False, parent=None):
- """
- Shows the initial config dialog
- :return:
- """
- from .widgets.ConfigSetup import ConfigSetup
- from PyQt4 import QtGui, QtCore
- if not rerun:
- setupConfigApp = QtGui.QApplication([])
- self.setupConfig = ConfigSetup()
- self.setupConfig.show()
- setupConfigApp.exec_()
- if not self.setupConfig.result:
- sys.exit(122)
- else:
- self.setupConfig = ConfigSetup(restart=True)
- self.setupConfig.setWindowModality(QtCore.Qt.ApplicationModal)
- self.setupConfig.show()
- self.error = False
- self.read()
|