def test_build_config(self): config = ConfigParser() self.app.build_config(config) for section, values in DEFAULT_SETTINGS.items(): for k, v in values.items(): if isinstance(v, int): assert config.getboolean(section, k) == v elif isinstance(v, str): assert config.get(section, k) == v else: assert False, "un cas est manquant"
def load_config(): global root, allow_uploads, port config = ConfigParser() config.read('serverconfig.ini') config.setdefaults('main', { 'root': '/sdcard', 'allow_uploads': False, 'port': 11451 }) root = pathlib.Path(config['main']['root']) allow_uploads = config.getboolean('main', 'allow_uploads') port = config.getint('main', 'port')
class UserPrefs(EventDispatcher): ''' A class to manage user preferences for the RaceCapture app ''' DEFAULT_DASHBOARD_SCREENS = ['5x_gauge_view', 'laptime_view', 'tach_view', 'rawchannel_view'] DEFAULT_PREFS_DICT = {'range_alerts': {}, 'gauge_settings':{}, 'screens':DEFAULT_DASHBOARD_SCREENS, 'alerts': {}} DEFAULT_ANALYSIS_CHANNELS = ['Speed'] prefs_file_name = 'prefs.json' def __init__(self, data_dir, user_files_dir, save_timeout=0.2, **kwargs): self._prefs_dict = UserPrefs.DEFAULT_PREFS_DICT self.config = ConfigParser() self.data_dir = data_dir self.user_files_dir = user_files_dir self.prefs_file = path.join(self.data_dir, self.prefs_file_name) self.register_event_type("on_pref_change") self.load() def on_pref_change(self, section, option, value): pass def set_range_alert(self, key, range_alert): ''' Sets a range alert with the specified key :param key the key for the range alert :type string :param range_alert the range alert :type object ''' self._prefs_dict["range_alerts"][key] = range_alert self.save() def get_range_alert(self, key, default=None): ''' Retrives a range alert for the specified key :param key the key for the range alert :type key string :param default the default value, optional :type default user specified :return the range alert, or the default value ''' return self._prefs_dict["range_alerts"].get(key, default) def get_alertrules(self, channel): ''' Retrieve the alert_rules for the specified channel. If the alertrules do not exist for the specified channel, return an empty default AlertRuleCollection :return AlertRuleCollection ''' alertrules = self._prefs_dict['alerts'].get(channel) if alertrules is None: alertrules = AlertRuleCollection(channel, []) self._prefs_dict['alerts'][channel] = alertrules return alertrules def set_alertrules(self, channel, alertrules): self._prefs_dict['alerts'][channel] = alertrules self.save() def set_gauge_config(self, gauge_id, config_value): ''' Stores a gauge configuration for the specified gauge_id :param gauge_id the key for the gauge :type gauge_id string :param config_value the configuration value to set :type config_value string ''' self._prefs_dict["gauge_settings"][gauge_id] = config_value self.save() def get_gauge_config(self, gauge_id): ''' Get the gauge configuration for the specified gauge_id :param gauge_id the key for the gauge :type string :return the gauge configuration ''' return self._prefs_dict["gauge_settings"].get(gauge_id, False) def get_dashboard_screens(self): return copy(self._prefs_dict['screens']) def set_dashboard_screens(self, screens): self._prefs_dict['screens'] = copy(screens) self.save() # Regular preferences below here def get_last_selected_track_id(self): return self.get_pref('track_detection', 'last_selected_track_id') def get_last_selected_track_timestamp(self): return self.get_pref_int('track_detection', 'last_selected_track_timestamp') def get_user_cancelled_location(self): return self.get_pref('track_detection', 'user_cancelled_location') def set_last_selected_track(self, track_id, timestamp, user_cancelled_location='0,0'): self.set_pref('track_detection', 'last_selected_track_id', track_id) self.set_pref('track_detection', 'last_selected_track_timestamp', timestamp) self.set_pref('track_detection', 'user_cancelled_location', user_cancelled_location) self.save() @property def datastore_location(self): return os.path.join(self.data_dir, 'datastore.sq3') def save(self, *largs): ''' Saves the current configuration ''' Logger.info('UserPrefs: Saving preferences') with open(self.prefs_file, 'w+') as prefs_file: data = self.to_json() prefs_file.write(data) def set_config_defaults(self): ''' Set defaults for preferences ''' # Base system preferences self.config.adddefaultsection('help') self.config.adddefaultsection('preferences') self.config.setdefault('preferences', 'distance_units', 'miles') self.config.setdefault('preferences', 'temperature_units', 'Fahrenheit') self.config.setdefault('preferences', 'show_laptimes', 1) self.config.setdefault('preferences', 'startup_screen', 'Home Page') default_user_files_dir = self.user_files_dir self.config.setdefault('preferences', 'config_file_dir', default_user_files_dir) self.config.setdefault('preferences', 'export_file_dir', default_user_files_dir) self.config.setdefault('preferences', 'firmware_dir', default_user_files_dir) self.config.setdefault('preferences', 'import_datalog_dir', default_user_files_dir) self.config.setdefault('preferences', 'send_telemetry', '0') self.config.setdefault('preferences', 'record_session', '1') self.config.setdefault('preferences', 'global_help', True) # Connection type for mobile if is_mobile_platform(): if is_android(): self.config.setdefault('preferences', 'conn_type', 'Bluetooth') elif is_ios(): self.config.setdefault('preferences', 'conn_type', 'WiFi') else: self.config.setdefault('preferences', 'conn_type', 'Serial') # Dashboard preferences self.config.adddefaultsection('dashboard_preferences') self.config.setdefault('dashboard_preferences', 'last_dash_screen', '5x_gauge_view') self.config.setdefault('dashboard_preferences', 'pitstoptimer_enabled', 1) self.config.setdefault('dashboard_preferences', 'pitstoptimer_trigger_speed', 5) self.config.setdefault('dashboard_preferences', 'pitstoptimer_alert_speed', 25) self.config.setdefault('dashboard_preferences', 'pitstoptimer_exit_speed', 55) # Track detection pref self.config.adddefaultsection('track_detection') self.config.setdefault('track_detection', 'last_selected_track_id', 0) self.config.setdefault('track_detection', 'last_selected_track_timestamp', 0) self.config.setdefault('track_detection', 'user_cancelled_location', '0,0') self.config.adddefaultsection('analysis_preferences') self.config.setdefault('analysis_preferences', 'selected_sessions_laps', '{"sessions":{}}') self.config.setdefault('analysis_preferences', 'selected_analysis_channels', ','.join(UserPrefs.DEFAULT_ANALYSIS_CHANNELS)) self.config.adddefaultsection('setup') self.config.setdefault('setup', 'setup_enabled', 1) def load(self): Logger.info('UserPrefs: Data Dir is: {}'.format(self.data_dir)) self.config.read(os.path.join(self.data_dir, 'preferences.ini')) self.set_config_defaults() try: with open(self.prefs_file, 'r') as data: content = data.read() content_dict = json.loads(content) if content_dict.has_key("gauge_settings"): for id, channel in content_dict["gauge_settings"].iteritems(): self._prefs_dict["gauge_settings"][id] = channel if content_dict.has_key('screens'): self._prefs_dict['screens'] = content_dict['screens'] if content_dict.has_key('alerts'): for channel, alertrules in content_dict['alerts'].iteritems(): self._prefs_dict['alerts'][channel] = AlertRuleCollection.from_dict(alertrules) except Exception as e: Logger.error('Error loading preferences, using defaults. {}'.format(e)) def init_pref_section(self, section): ''' Initializes a preferences section with the specified name. if the section already exists, there is no effect. :param section the name of the preference section :type string ''' self.config.adddefaultsection(section) def get_pref_bool(self, section, option, default=None): ''' Retrieve a preferences value as a bool. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default bool :return bool preference value ''' try: return self.config.getboolean(section, option) except (NoOptionError, ValueError): return default def get_pref_float(self, section, option, default=None): ''' Retrieve a preferences value as a float. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default float :return float preference value ''' try: return self.config.getfloat(section, option) except (NoOptionError, ValueError): return default def get_pref_int(self, section, option, default=None): ''' Retrieve a preferences value as an int. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return int preference value ''' try: return self.config.getint(section, option) except (NoOptionError, ValueError): return default def get_pref(self, section, option, default=None): ''' Retrieve a preferences value as a string. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return string preference value ''' try: return self.config.get(section, option) except (NoOptionError, ValueError): return default def get_pref_list(self, section, option, default=[]): """ Retrieve a preferences value as a list. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return list of string values """ try: return self.config.get(section, option).split(',') except (NoOptionError, ValueError): return default def set_pref(self, section, option, value): ''' Set a preference value :param section the configuration section for the preference :type string :param option the option for the section :type string :param value the preference value to set :type value user specified ''' current_value = None try: current_value = self.config.get(section, option) except NoOptionError: pass self.config.set(section, option, value) self.config.write() if value != current_value: self.dispatch('on_pref_change', section, option, value) def set_pref_list(self, section, option, value): """ Set a preference value by list :param section the configuration section for the preference :type string :param option the option for the section :type string :param value the preference value to set :type value list (list of strings) """ try: self.set_pref(section, option, ','.join(value)) except TypeError: Logger.error('UserPrefs: failed to set preference list for {}:{} - {}'.format(section, option, value)) def to_json(self): ''' Serialize preferences to json ''' data = {'range_alerts': {}, 'gauge_settings':{}, 'screens': [], 'alerts': {}} for name, range_alert in self._prefs_dict["range_alerts"].iteritems(): data["range_alerts"][name] = range_alert.to_dict() for id, channel in self._prefs_dict["gauge_settings"].iteritems(): data["gauge_settings"][id] = channel for name, alertrules in self._prefs_dict['alerts'].iteritems(): data['alerts'][name] = alertrules.to_dict() data['screens'] = self._prefs_dict['screens'] return json.dumps(data, sort_keys=True, indent=2, separators=(',', ': '))
if platform.startswith('win'): fname = 'bgm.ini' else: fname = 'bgm_home.ini' CP = ConfigParser(name='BGM') CP.read(fname) gamepath = CP.get('Path', 'gamepath') if not isdir(gamepath): Logger.warn('No Existing Game Path found') gamepath = None else: resource_add_path(gamepath) FORCE_FIT_FORMAT = CP.getboolean('Layout','force_fit_format') def set_force_fit_format(force): CP.set('Layout','force_fit_format',int(force)) CP.write() global FORCE_FIT_FORMAT FORCE_FIT_FORMAT = int(force) def startup_tips(stop): CP.set('Startup','startup_tips',stop) CP.write() USE_PROXY = CP.getboolean('Proxy', 'use_proxy') if USE_PROXY: Logger.info('Using Proxy')
class UserPrefs(EventDispatcher): ''' A class to manage user preferences for the RaceCapture app ''' _schedule_save = None _prefs_dict = {'range_alerts': {}, 'gauge_settings':{}} store = None prefs_file_name = 'prefs.json' prefs_file = None config = None data_dir = '.' user_files_dir = '.' def __init__(self, data_dir, user_files_dir, save_timeout=2, **kwargs): self.data_dir = data_dir self.user_files_dir = user_files_dir self.prefs_file = path.join(self.data_dir, self.prefs_file_name) self.load() self._schedule_save = Clock.create_trigger(self.save, save_timeout) def set_range_alert(self, key, range_alert): ''' Sets a range alert with the specified key :param key the key for the range alert :type string :param range_alert the range alert :type object ''' self._prefs_dict["range_alerts"][key] = range_alert self._schedule_save() def get_range_alert(self, key, default=None): ''' Retrives a range alert for the specified key :param key the key for the range alert :type key string :param default the default value, optional :type default user specified :return the range alert, or the default value ''' return self._prefs_dict["range_alerts"].get(key, default) def set_gauge_config(self, gauge_id, channel): ''' Stores a gauge configuration for the specified gauge_id :param gauge_id the key for the gauge :type gauge_id string :param channel the configuration for the channel :type channel object ''' self._prefs_dict["gauge_settings"][gauge_id] = channel self._schedule_save() def get_gauge_config(self, gauge_id): ''' Get the gauge configuration for the specified gauge_id :param gauge_id the key for the gauge :type string :return the gauge configuration ''' return self._prefs_dict["gauge_settings"].get(gauge_id, False) def get_last_selected_track_id(self): return self.get_pref('track_detection', 'last_selected_track_id') def get_last_selected_track_timestamp(self): return self.get_pref_int('track_detection', 'last_selected_track_timestamp') def set_last_selected_track(self, track_id, timestamp): self.set_pref('track_detection', 'last_selected_track_id', track_id) self.set_pref('track_detection', 'last_selected_track_timestamp', timestamp) @property def datastore_location(self): return os.path.join(self.data_dir, 'datastore.sq3') def save(self, *largs): ''' Saves the current configuration ''' with open(self.prefs_file, 'w+') as prefs_file: data = self.to_json() prefs_file.write(data) def set_config_defaults(self): ''' Set defaults for preferences ''' # Base system preferences self.config.adddefaultsection('help') self.config.adddefaultsection('preferences') self.config.setdefault('preferences', 'distance_units', 'miles') self.config.setdefault('preferences', 'temperature_units', 'Fahrenheit') self.config.setdefault('preferences', 'show_laptimes', 1) self.config.setdefault('preferences', 'startup_screen', 'Home Page') default_user_files_dir = self.user_files_dir self.config.setdefault('preferences', 'config_file_dir', default_user_files_dir) self.config.setdefault('preferences', 'firmware_dir', default_user_files_dir) self.config.setdefault('preferences', 'import_datalog_dir', default_user_files_dir) self.config.setdefault('preferences', 'first_time_setup', '1') self.config.setdefault('preferences', 'send_telemetry', '0') self.config.setdefault('preferences', 'record_session', '1') self.config.setdefault('preferences', 'last_dash_screen', 'gaugeView') self.config.setdefault('preferences', 'global_help', True) if platform == 'android': self.config.setdefault('preferences', 'conn_type', 'Bluetooth') # Dashboard preferences self.config.adddefaultsection('dashboard_preferences') self.config.setdefault('dashboard_preferences', 'pitstoptimer_enabled', 1) self.config.setdefault('dashboard_preferences', 'pitstoptimer_trigger_speed', 5) self.config.setdefault('dashboard_preferences', 'pitstoptimer_alert_speed', 25) self.config.setdefault('dashboard_preferences', 'pitstoptimer_exit_speed', 55) # Track detection pref self.config.adddefaultsection('track_detection') self.config.setdefault('track_detection', 'last_selected_track_id', 0) self.config.setdefault('track_detection', 'last_selected_track_timestamp', 0) self.config.adddefaultsection('analysis_preferences') self.config.setdefault('analysis_preferences', 'selected_sessions_laps', '{"sessions":{}}') def load(self): Logger.info('UserPrefs: Data Dir is: {}'.format(self.data_dir)) self.config = ConfigParser() self.config.read(os.path.join(self.data_dir, 'preferences.ini')) self.set_config_defaults() self._prefs_dict = {'range_alerts': {}, 'gauge_settings':{}} try: with open(self.prefs_file, 'r') as data: content = data.read() content_dict = json.loads(content) if content_dict.has_key("range_alerts"): for name, settings in content_dict["range_alerts"].iteritems(): self._prefs_dict["range_alerts"][name] = Range.from_dict(settings) if content_dict.has_key("gauge_settings"): for id, channel in content_dict["gauge_settings"].iteritems(): self._prefs_dict["gauge_settings"][id] = channel except Exception: pass def get_pref_bool(self, section, option, default=None): ''' Retrieve a preferences value as a bool. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default bool :return bool preference value ''' try: return self.config.getboolean(section, option) except (NoOptionError, ValueError): return default def get_pref_float(self, section, option, default=None): ''' Retrieve a preferences value as a float. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default float :return float preference value ''' try: return self.config.getfloat(section, option) except (NoOptionError, ValueError): return default def get_pref_int(self, section, option, default=None): ''' Retrieve a preferences value as an int. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return int preference value ''' try: return self.config.getint(section, option) except (NoOptionError, ValueError): return default def get_pref(self, section, option, default=None): ''' Retrieve a preferences value as a string. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return string preference value ''' try: return self.config.get(section, option) except (NoOptionError, ValueError): return default def set_pref(self, section, option, value): ''' Set a preference value :param section the configuration section for the preference :type string :param option the option for the section :type string :param value the preference value to set :type value user specified ''' self.config.set(section, option, value) self.config.write() def to_json(self): ''' Serialize preferences to json ''' data = {'range_alerts': {}, 'gauge_settings':{}} for name, range_alert in self._prefs_dict["range_alerts"].iteritems(): data["range_alerts"][name] = range_alert.to_dict() for id, channel in self._prefs_dict["gauge_settings"].iteritems(): data["gauge_settings"][id] = channel return json.dumps(data)
class MainApp(App): def __init__(self, *args, **kwargs): super(MainApp, self).__init__(*args, **kwargs) self.logger = logging.getLogger('kivy.operator.app') if not os.path.isdir("/sdcard/operator"): os.makedirs("/sdcard/operator") self.map = None self.messaging = None self.xmpp_client = None self.user_location_markers = {} self._last_location_update = 0 Window.bind(on_keyboard=self.on_back_btn) self.android_setflag() self.xmpp_config_ok = False self.start = True self.confirmation_popup = Popup() self.lock_btn_presses = [] self.configuration = ConfigParser() self.configuration.read(CONFIG_PATH) self.check_config() def check_config(self): """ Checks to see if the config has the required XMPP fields filled out accordingly. Then, it evaluates the config file to make sure that all fields exist, at least corresponding to the example config file. """ conf = self.configuration if conf.has_section('xmpp'): if all( conf.has_option('xmpp', k) and conf.get('xmpp', k) for k in MANDATORY_XMPP_OPTIONS): self.xmpp_config_ok = True def_conf = ConfigParser() def_conf.read(DEFAULT_CONFIG_PATH) for section in def_conf.sections(): if conf.has_section(section): for option in def_conf.options(section): if not conf.has_option(section, option) or conf.get( section, option) is None: conf.set(section, option, def_conf.get(section, option)) else: conf.add_section(section) for option in def_conf.options(section): conf.set(section, option, def_conf.get(section, option)) self.configuration = conf self.configuration.write() def build(self): self.root = RootWidget() if self.xmpp_config_ok: self.xmpp_client = OperatorXMPPClient( sz_utils.parse_server(self.configuration.get('xmpp', 'server'), 5222), self.configuration.get('xmpp', 'username'), self.configuration.get('xmpp', 'password'), self.configuration.get('xmpp', 'room'), self.configuration.getboolean('xmpp', 'filter')) self.xmpp_client.bind( on_user_location_update=self.on_user_location_update) self.xmpp_client.bind(on_message_receive=self.on_message_receive) self.xmpp_client.bind(on_muc_receive=self.on_muc_receive) else: self.logger.warning( "XMMP config invalid, disabling XMPP operations") self.map = self.root.ids.map_panel_widget.ids.map_widget self.messaging = self.root.ids.message_menu gps.configure(on_location=self.on_gps_location) gps.start() return self.root def on_back_btn(self, window, key, *args): """ To be called whenever user presses Back/Esc Key """ # If user presses Back/Esc Key if key == 27: return self.root.on_back_btn() return False def build_config(self, config): # add default sections here default_sections = ('miscellaneous', 'xmpp') for section in default_sections: if not config.has_section: config.add_section(section) # load the custom configuration ini file custom_config = 'data/settings/config.ini' if os.path.isfile(custom_config): self.logger.info( 'loading custom config: {0}'.format(custom_config)) config.update_config(custom_config, overwrite=False) def build_settings(self, settings): settings.add_json_panel('XMPP', self.configuration, 'data/settings/xmpp.json') settings.add_json_panel('Map', self.configuration, 'data/settings/map.json') def on_message_receive(self, event, msg): self.messaging.on_message_receive(msg) def on_muc_receive(self, event, msg): self.messaging.on_muc_receive(msg) def on_gps_location(self, **kwargs): # kwargs on Galaxy S5 contain: # altitude, bearing, lat, lon, speed if self.start: if self.xmpp_client: self.messaging.get_users() self.start = False if not ('lat' in kwargs and 'lon' in kwargs): return current_time = time.time() if current_time - self._last_location_update < self.configuration.getint( 'miscellaneous', 'gps_update_freq'): return latitude = kwargs.pop('lat') longitude = kwargs.pop('lon') altitude = kwargs.pop('altitude', None) bearing = kwargs.pop('bearing', None) speed = kwargs.pop('speed', None) self.map.update_location((latitude, longitude), altitude, bearing, speed) if self.xmpp_client: self.xmpp_client.update_location((latitude, longitude), altitude, bearing, speed) self._last_location_update = current_time def get_users(self): return self.xmpp_client.get_users() def send_message(self, msg, user): self.xmpp_client.on_message_send(msg, user) def send_muc(self, msg, group): self.xmpp_client.on_muc_send(msg, group) def on_pause(self): return False def on_resume(self): pass def on_stop(self): self.map.save_marker_file() if self.xmpp_client: self.xmpp_client.shutdown() def on_user_location_update(self, _, info): if not self.map.is_ready: self.logger.warning('map is not ready for user marker') return user = info['user'] if user in self.user_location_markers: self.user_location_markers[user].remove() if self.xmpp_client: user_mood = self.xmpp_client.user_moods.get(user, 'calm') icon_color = { 'angry': 'red', 'calm': 'yellow', 'happy': 'green' }.get(user_mood, 'yellow') marker = self.map.create_marker(draggable=False, title=info['user'], position=info['location'], marker_color=icon_color) self.user_location_markers[user] = marker def toast_status(self): return self.configuration.getboolean('xmpp', 'toast_all') def xmpp_log(self, log_type, log): if log_type == 'info': self.xmpp_client.logger.info(log) def prompt_lock_screen(self): """ Popup confirming with the user whether they want to lock the screen. """ confirmation_box = BoxLayout(orientation='vertical') confirmation_box.add_widget( Label(text='Do you want to lock the screen?')) box_int = BoxLayout(orientation='horizontal', spacing=50) affirm_button = Button(text='Yes') affirm_button.bind(on_release=lambda x: self.lock_screen()) dismiss_button = Button(text='Cancel') dismiss_button.bind( on_release=lambda x: self.confirmation_popup.dismiss()) box_int.add_widget(affirm_button) box_int.add_widget(dismiss_button) confirmation_box.add_widget(box_int) self.confirmation_popup = Popup(title='Confirmation', content=confirmation_box, size_hint=(.7, None), size=(500, 500), auto_dismiss=False) self.confirmation_popup.open() @run_on_ui_thread def lock_screen(self): """ Lock the screen by going to a black layout and not allowing input. Will disable after 10 taps. """ self.confirmation_popup.dismiss() flag = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION PythonActivity.mActivity.getWindow().getDecorView( ).setSystemUiVisibility(flag) mb = True for child in self.root.walk(): if hasattr(child, 'name'): if child.name == 'root' and mb: self.removed = child child.parent.remove_widget(child) mb = False self.bl = BoxLayout(orientation='vertical') self.bl.add_widget( Button(size_hint=(1, 1), background_color=[0, 0, 0, 1], on_release=lambda x: self.lock_button())) self.root.add_widget(self.bl) def lock_button(self): """ Registers clicks on the locked screen. Only counts clicks within 10 second gap. """ current_time = time.time() self.lock_btn_presses.append(current_time) while current_time - self.lock_btn_presses[ 0] > self.configuration.getint('miscellaneous', 'lockout_timeout'): del self.lock_btn_presses[0] if len(self.lock_btn_presses) == self.configuration.getint( 'miscellaneous', 'lockout_clicks'): self.root.remove_widget(self.bl) self.root.add_widget(self.removed) self.lock_btn_presses = [] @run_on_ui_thread def android_setflag(self): PythonActivity.mActivity.getWindow().addFlags( Params.FLAG_KEEP_SCREEN_ON) def update_mood(self, mood): if self.xmpp_client: self.xmpp_client.update_mood(mood)
import platform import subprocess import pickle #Initialize config #Need to use Kivy's modified ConfigParser from kivy.config import ConfigParser #We won't call this config so it can't be confused with the App's config later iniconfig = ConfigParser() iniconfig.read('main.ini') lang = iniconfig.get('language','language') debug = iniconfig.getboolean('debugging','debug') requires_avx = iniconfig.getboolean('dependencies','requires_avx') #Initialize locales import gettext def lang_load(lang): if lang == 'en': _ = lambda s:s #If language is English, just return the default string else: lang_translations = gettext.translation('main', localedir = 'locales', languages = lang) lang_translations.install() _ = lang_translations.gettext return _ #load language from config _ = lang_load(lang) print(_("Language Loaded")) #Check for AVX instruction set on CPU - default version of tensorflow requires it import cpufeature
if platform.startswith('win'): fname = 'bgm.ini' else: fname = 'bgm_home.ini' CP = ConfigParser(name='BGM') CP.read(fname) gamepath = CP.get('Path', 'gamepath') if not isdir(gamepath): Logger.warn('No Existing Game Path found') gamepath = None else: resource_add_path(gamepath) FORCE_FIT_FORMAT = CP.getboolean('Layout', 'force_fit_format') def set_force_fit_format(force): CP.set('Layout', 'force_fit_format', int(force)) CP.write() global FORCE_FIT_FORMAT FORCE_FIT_FORMAT = int(force) def startup_tips(stop): CP.set('Startup', 'startup_tips', stop) CP.write() USE_PROXY = CP.getboolean('Proxy', 'use_proxy')
class Settings: def __init__(self): self.Config = ConfigParser() self.Config.add_section('Input') self.Config.add_section('Processor') self.Config.add_section('Output') # default values self.cfgfilename = 'default.conf' self.helpfile = 'doc/PyFSPro_dataflow.jpg' self.numframes = 255 # No. of frames in stack self.color_mode = -1 # Greyscale output self.video_src = 0 # Default camera self.video_width = 1024 self.video_height = 768 self.show_inp = True self.show_out = True self.show_vec = False self.show_help = False # settings for video and image sequence recording self.recordi = False self.recordv = False self.novfile = True self.imgindx = 0 self.output_path = './output/' self.image_dst = self.output_path self.video_dst = self.output_path # switches for image filters and tools self.blr_inp = False self.blr_out = False self.blr_strength = 7 self.equ_inp = 0 self.equ_out = 0 self.dnz_inp = False self.dnz_out = False self.dnz_inp_str = 33 self.dnz_out_str = 33 self.flt_inp = 0 self.flt_out = 0 self.flt_inp_strength = 0 self.flt_out_strength = 0 self.flt_inp_kernel = None self.flt_out_kernel = None self.flip_x = False self.flip_y = False self.inp_kernel = None self.out_kernel = None #self.mode_in = 0 self.mode_prc = 0 #self.mode_out = 0 self.pseudoc = False self.dyn_dark = True self.gain_inp = 1.0 self.gain_out = 1.0 self.offset_inp = 0 self.offset_out = 0 self.vec_zoom = 0.1 self.loop = False self.stb_inp = False self.stb_out = False self.osd_txtline = 2 self.green = (0, 255, 0) self.red = (0, 0, 255) self.blue = (255, 0, 0) self.black = (0, 0, 0) self.colormaps = [ 'AUTUMN', 'BONE', 'JET', 'WINTER', 'RAINBOW', 'OCEAN', 'SUMMER', 'SPRING', 'COOL', 'HSV', 'PINK', 'HOT' ] self.set_defaults() def gettime(self): self.timestring = time.strftime("%Y%m%d-%H%M%S", time.gmtime()) return self.timestring def set_defaults(self): # Section 'Input' self.Config.setdefault('Input', 'video_src', self.video_src) self.Config.setdefault('Input', 'video_width', self.video_width) self.Config.setdefault('Input', 'video_height', self.video_height) self.Config.setdefault('Input', 'loop', self.loop) self.Config.setdefault('Input', 'flip_x', self.flip_x) self.Config.setdefault('Input', 'flip_y', self.flip_y) self.Config.setdefault('Input', 'blr_inp', self.blr_inp) self.Config.setdefault('Input', 'equ_inp', self.equ_inp) self.Config.setdefault('Input', 'dnz_inp', self.dnz_inp) self.Config.setdefault('Input', 'dnz_inp_str', self.dnz_inp_str) self.Config.setdefault('Input', 'flt_inp', self.flt_inp) self.Config.setdefault('Input', 'flt_inp_strength', self.flt_inp_strength) #self.Config.setdefault('Input','mode_in', self.mode_in) self.Config.setdefault('Input', 'gain_inp', self.gain_inp) self.Config.setdefault('Input', 'offset_inp', self.offset_inp) self.Config.setdefault('Input', 'stb_inp', self.stb_inp) # Section 'Processor' self.Config.setdefault('Processor', 'mode_prc', self.mode_prc) self.Config.setdefault('Processor', 'dyn_dark', self.dyn_dark) self.Config.setdefault('Processor', 'blr_strength', self.blr_strength) self.Config.setdefault('Processor', 'numframes', self.numframes) # Section 'Output' self.Config.setdefault('Output', 'video_dst', self.video_dst) self.Config.setdefault('Output', 'image_dst', self.image_dst) self.Config.setdefault('Output', 'recordv', self.recordv) self.Config.setdefault('Output', 'recordi', self.recordi) self.Config.setdefault('Output', 'blr_out', self.blr_out) self.Config.setdefault('Output', 'equ_out', self.equ_out) self.Config.setdefault('Output', 'dnz_out', self.dnz_out) self.Config.setdefault('Output', 'dnz_out_str', self.dnz_out_str) self.Config.setdefault('Output', 'flt_out', self.flt_out) self.Config.setdefault('Output', 'flt_out_strength', self.flt_out_strength) #self.Config.setdefault('Output','mode_out', self.mode_out) self.Config.setdefault('Output', 'gain_out', self.gain_out) self.Config.setdefault('Output', 'offset_out', self.offset_out) self.Config.setdefault('Output', 'color_mode', self.color_mode) self.Config.setdefault('Output', 'pseudoc', self.pseudoc) self.Config.setdefault('Output', 'vec_zoom', self.vec_zoom) self.Config.setdefault('Output', 'stb_out', self.stb_out) def write_config(self, filename): if filename is None: filename = self.cfgfilename self.cfgfile = open(filename, 'w') # Section 'Input' self.Config.set('Input', 'video_src', self.video_src) self.Config.set('Input', 'video_width', self.video_width) self.Config.set('Input', 'video_height', self.video_height) self.Config.set('Input', 'loop', self.loop) self.Config.set('Input', 'flip_x', self.flip_x) self.Config.set('Input', 'flip_y', self.flip_y) self.Config.set('Input', 'blr_inp', self.blr_inp) self.Config.set('Input', 'equ_inp', self.equ_inp) self.Config.set('Input', 'dnz_inp', self.dnz_inp) self.Config.set('Input', 'dnz_inp_str', self.dnz_inp_str) self.Config.set('Input', 'flt_inp', self.flt_inp) self.Config.set('Input', 'flt_inp_strength', self.flt_inp_strength) #self.Config.set('Input','mode_in', self.mode_in) self.Config.set('Input', 'gain_inp', self.gain_inp) self.Config.set('Input', 'offset_inp', self.offset_inp) self.Config.set('Input', 'stb_inp', self.stb_inp) # Section 'Processor' self.Config.set('Processor', 'mode_prc', self.mode_prc) self.Config.set('Processor', 'dyn_dark', self.dyn_dark) self.Config.set('Processor', 'blr_strength', self.blr_strength) self.Config.set('Processor', 'numframes', self.numframes) # Section 'Output' self.Config.set('Output', 'video_dst', self.video_dst) self.Config.set('Output', 'image_dst', self.image_dst) self.Config.set('Output', 'recordv', self.recordv) self.Config.set('Output', 'recordi', self.recordi) self.Config.set('Output', 'blr_out', self.blr_out) self.Config.set('Output', 'equ_out', self.equ_out) self.Config.set('Output', 'dnz_out', self.dnz_out) self.Config.set('Output', 'dnz_out_str', self.dnz_out_str) self.Config.set('Output', 'flt_out', self.flt_out) self.Config.set('Output', 'flt_out_strength', self.flt_out_strength) #self.Config.set('Output','mode_out', self.mode_out) self.Config.set('Output', 'gain_out', self.gain_out) self.Config.set('Output', 'offset_out', self.offset_out) self.Config.set('Output', 'color_mode', self.color_mode) self.Config.set('Output', 'pseudoc', self.pseudoc) self.Config.set('Output', 'vec_zoom', self.vec_zoom) self.Config.set('Output', 'stb_out', self.stb_out) self.Config.write(self.cfgfile) self.cfgfile.close() def read_config(self, filename): if os.path.isfile(filename): self.Config.read(filename) self.video_src = self.Config.get('Input', 'video_src') self.video_width = int(self.Config.get('Input', 'video_width')) self.video_height = int(self.Config.get('Input', 'video_height')) self.loop = self.Config.getboolean('Input', 'loop') self.flip_x = self.Config.getboolean('Input', 'flip_x') self.flip_y = self.Config.getboolean('Input', 'flip_y') self.blr_inp = self.Config.getboolean('Input', 'blr_inp') self.equ_inp = int(self.Config.get('Input', 'equ_inp')) self.dnz_inp = self.Config.getboolean('Input', 'dnz_inp') self.dnz_inp_str = float(self.Config.get('Input', 'dnz_inp_str')) self.flt_inp = int(self.Config.get('Input', 'flt_inp')) self.flt_inp_strength = float( self.Config.get('Input', 'flt_inp_strength')) self.gain_inp = float(self.Config.get('Input', 'gain_inp')) self.offset_inp = float(self.Config.get('Input', 'offset_inp')) self.stb_inp = self.Config.getboolean('Input', 'stb_inp') self.mode_prc = int(self.Config.get('Processor', 'mode_prc')) self.dyn_dark = self.Config.getboolean('Processor', 'dyn_dark') self.blr_strength = int( self.Config.get('Processor', 'blr_strength')) self.numframes = int(self.Config.get('Processor', 'numframes')) self.video_dst = self.Config.get('Output', 'video_dst') self.image_dst = self.Config.get('Output', 'image_dst') self.recordv = self.Config.getboolean('Output', 'recordv') self.recordi = self.Config.getboolean('Output', 'recordi') self.blr_out = self.Config.getboolean('Output', 'blr_out') self.equ_out = int(self.Config.get('Output', 'equ_out')) self.dnz_out = self.Config.getboolean('Output', 'dnz_out') self.dnz_out_str = float(self.Config.get('Output', 'dnz_out_str')) self.flt_out = int(self.Config.get('Output', 'flt_out')) self.flt_out_strength = float( self.Config.get('Output', 'flt_out_strength')) self.gain_out = float(self.Config.get('Output', 'gain_out')) self.offset_out = float(self.Config.get('Output', 'offset_out')) self.color_mode = int(self.Config.get('Output', 'color_mode')) self.pseudoc = self.Config.getboolean('Output', 'pseudoc') self.vec_zoom = float(self.Config.get('Output', 'vec_zoom')) self.stb_out = self.Config.getboolean('Output', 'stb_out') else: print('File ' + str(filename) + ' does not exist.')
def getbool(self, section, option): try: return KivyConfigParser.getboolean(self, section, option) except NoOptionError: self.set(section, option, "off") return False