def get_first_sub(self): config = ConfigParser() config.read('mysteryonline.ini') try: return self.sublocations[str(config.get('other', 'last_sublocation'))].name except KeyError: return self.list_sub()[0]
def __init__(self, **kwargs): super(MyConnectDialog, self).__init__(**kwargs) self.register_type('buttons', SettingButtons) self.register_event_type('on_connect') config = ConfigParser() config.setdefaults( 'common', { 'conf_role': 'SERVER', 'conf_transport': 'TLS', 'conf_ip': '192.168.1.220', 'conf_serport': 'COM1' }) config.setdefaults('client', { 'conf_user': '******', 'conf_cert_chain': 'myhome-bundle.crt' }) config.setdefaults('server', { 'conf_serv_cert': 'rootca.crt', 'conf_serv_key': 'secret/rootca.key' }) self.myconfig = config try: config.read("i-spy.myconfig") except: print("No i-spy.myconfig") self.add_json_panel('IO device connect', config, data=json)
def get_config(path=None): """Get a configuration. The path, where a config file is searched, can be given in `path`, a string. If no such argument is passed in, we use results from :func:`get_conffile_locations`. Returns a `kivy.config.ConfigParser` instance. """ conf = ConfigParser() fpscan_path = find_fpscan_binary() conf['DEFAULT'] = { 'waeup_user': '******', 'waeup_passwd': 'grok', 'waeup_url': 'localhost:8080', 'save_passwd': '0', } if fpscan_path is not None: conf['DEFAULT'].update(fpscan_path=fpscan_path) if path is not None: conffile_location = path else: conffile_location = get_conffile_location() conf.read(conffile_location) return conf
def __init__(self, *args, **kwargs): self.callback = kwargs.pop("callback", None) self.pages = kwargs.pop("pages", ["general", "synchronisation", "kivy"]) self.title = "Paramètres" self.size_hint = (0.9, 0.9) config = ConfigParser() config.read(os.path.join(UTILS_Divers.GetRepData(), "config.cfg")) self.settings = Settings() self.settings.register_type('password', SettingPassword) self.settings.register_type('chaine', SettingChaine) if "general" in self.pages: self.settings.add_json_panel("Généralités", config, data=json.dumps(JSON_GENERAL)) if "synchronisation" in self.pages: self.settings.add_json_panel("Synchronisation", config, data=json.dumps(JSON_SYNCHRONISATION)) if "kivy" in self.pages: self.settings.add_kivy_panel() self.settings.interface.menu.close_button.text = "Fermer" self.content = self.settings self.settings.bind(on_close=self.OnBoutonFermer) self.bind(on_dismiss=self.on_dismiss) super(Popup, self).__init__(*args, **kwargs)
def reapply_version(app: MyDevoirsApp) -> Tuple[int, str]: """ Verifie les differents version précendentes :param app: L'instance en cours :return: 0: le fichier n'existe pas 1: la version a du être ajoutée 2: la version existe == version en cours 3: la version existe < version en cours 4: la version existe > version en cours """ cf_file = app.get_application_config() file = Path(cf_file) return_value = 0 file_version = None if file.is_file(): # pragma: no branch config = ConfigParser() try: config.read(cf_file) file_version = config.get("aide", "version") except NoSectionError: return_value = 1 except NoOptionError: return_value = 1 if file_version is not None: if file_version < VERSION: return_value = 3 elif file_version > VERSION: return_value = 4 else: return_value = 2 return return_value, file_version
def right_click(self, inst, touch): if touch.button == 'right': try: if inst.collide_point(touch.x, touch.y): favorite = App.get_running_app().get_fav_chars() favorite.options = characters config = ConfigParser() config.read('mysteryonline.ini') fav_list = str(config.get('other', 'fav_characters').strip('[]')) fav_list = fav_list.replace("'", "") fav_list = fav_list.split(',') fav_list = [x.strip() for x in fav_list] for option in favorite.options: state = 'down' if option in favorite.value and option in fav_list else 'normal' btn = ToggleButton(text=option, state=state, size_hint_y=None, height=50) favorite.buttons.append(btn) for btn in favorite.buttons: if btn.text is characters[inst.name].name: if btn.state == 'normal': btn.state = 'down' else: btn.state = 'normal' favorite.value = [btn.text for btn in favorite.buttons if btn.state == 'down'] favorite.buttons.clear() self.save.is_saved = False self.main_lay.clear_widgets() self.fill_with_chars() except AttributeError: pass
def read_spoiler_sprites(self): try: spoiler_section = self.config['spoiler'] except KeyError: return spoiler_list = [] series = self.extra_series[:] series.insert(0, self.series) config = ConfigParser() config.read('mysteryonline.ini') try: whitelist = config.get('other', 'whitelisted_series') except: for key, s in zip(sorted(spoiler_section), series): spoiler_sprites = spoiler_section[key].split(',') spoiler_list.extend(spoiler_sprites) for sprite_name in spoiler_list: self.spoiler_sprites[sprite_name] = None return whitelist = whitelist.strip('[]') whitelist = whitelist.replace("'", "") whitelist = whitelist.split(',') whitelist = [x.strip() for x in whitelist] for key, s in zip(sorted(spoiler_section), series): if s not in whitelist: spoiler_sprites = spoiler_section[key].split(',') spoiler_list.extend(spoiler_sprites) for sprite_name in spoiler_list: self.spoiler_sprites[sprite_name] = None
def update_panel(self): '''Update the MenuSidebar ''' self.config_parsers = {} self.interface.menu.buttons_layout.clear_widgets() for _file in os.listdir(self.PROFILES_PATH): _file_path = os.path.join(self.PROFILES_PATH, _file) config_parser = ConfigParser() config_parser.read(_file_path) prof_name = config_parser.getdefault('profile', 'name', 'PROFILE') if not prof_name.strip(): prof_name = 'PROFILE' self.config_parsers[ str(prof_name) + '_' + _file_path] = config_parser for _file in sorted(self.config_parsers): prof_name = self.config_parsers[_file].getdefault('profile', 'name', 'PROFILE') if not prof_name.strip(): prof_name = 'PROFILE' self.add_json_panel(prof_name, self.config_parsers[_file], os.path.join( get_kd_data_dir(), 'settings', 'build_profile.json') ) # force to show the first profile first_panel = self.interface.menu.buttons_layout.children[-1].uid self.interface.content.current_uid = first_panel
def update_sub(self, loc): if self.subloc_btn is not None: self.subloc_drop.clear_widgets() fav_subloc = App.get_running_app().get_fav_subloc() config = ConfigParser() config.read('mysteryonline.ini') fav_list = str(config.get('other', 'fav_subloc').strip('[]')) fav_list = fav_list.replace("'", "") fav_list = fav_list.split(',') fav_list = [x.strip() for x in fav_list] for sub in loc.list_sub(): if loc.name + '_' + sub in fav_list and loc.name + '_' + sub in fav_subloc.value: btn = Button( text=sub, size_hint=(None, None), size=(200, 30), background_normal= 'atlas://data/images/defaulttheme/button_pressed', background_down='atlas://data/images/defaulttheme/button') btn.bind( on_release=lambda btn_: self.subloc_drop.select(btn_.text)) self.subloc_drop.add_widget(btn) for sub in loc.list_sub(): if loc.name + '_' + sub not in fav_subloc.value or loc.name + '_' + sub not in fav_list: btn = Button(text=sub, size_hint=(None, None), size=(200, 30)) btn.bind( on_release=lambda btn_: self.subloc_drop.select(btn_.text)) self.subloc_drop.add_widget(btn) self.subloc_btn.text = loc.get_first_sub()
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 on_ready(self, *args): """Called when mainscreen becomes active""" self.msg_input.ready(self) self.left_tab.ready(self) self.ooc_window.ready(self) self.log_window.ready() user_handler = App.get_running_app().get_user_handler() locations = location_manager.get_locations() config = ConfigParser() config.read('mysteryonline.ini') try: user_handler.set_current_loc(locations[str( config.get('other', 'last_location'))]) self.sprite_settings.update_sub(locations[str( config.get('other', 'last_location'))]) except KeyError: user_handler.set_current_loc(locations['Hakuryou']) self.sprite_settings.update_sub(locations['Hakuryou']) App.get_running_app().get_main_screen().log_window.add_entry( "You moved to %s.\n" % user_handler.get_current_loc().name) self.toolbar.set_user(self.user) self.toolbar.create_sfx_dropdown() self.sprite_preview.set_subloc(user_handler.get_chosen_subloc()) char = self.user.get_char() if char is not None: self.on_new_char(char) self.sprite_window.set_subloc(user_handler.get_chosen_subloc()) App.get_running_app().keyboard_listener.bind_keyboard()
def update_panel(self): '''Update the MenuSidebar ''' self.config_parsers = {} self.interface.menu.buttons_layout.clear_widgets() for _file in os.listdir(self.PROFILES_PATH): _file_path = os.path.join(self.PROFILES_PATH, _file) config_parser = ConfigParser() config_parser.read(_file_path) prof_name = config_parser.getdefault('profile', 'name', 'PROFILE') if not prof_name.strip(): prof_name = 'PROFILE' self.config_parsers[str(prof_name) + '_' + _file_path] = config_parser for _file in sorted(self.config_parsers): prof_name = self.config_parsers[_file].getdefault( 'profile', 'name', 'PROFILE') if not prof_name.strip(): prof_name = 'PROFILE' self.add_json_panel( prof_name, self.config_parsers[_file], os.path.join(get_kd_data_dir(), 'settings', 'build_profile.json')) # force to show the first profile first_panel = self.interface.menu.buttons_layout.children[-1].uid self.interface.content.current_uid = first_panel
def __init__(self, **kwargs): super().__init__(**kwargs) settings_config = ConfigParser() settings_config.read('data/settings.ini') if platform == 'win': self.add_json_panel('General', settings_config, 'data/settings/general.json') elif platform == 'android': self.add_json_panel('General', settings_config, 'data/settings/general_android.json')
class LoginScreen(Screen): def __init__(self, screen_name, navigate_to, register_screen): super(LoginScreen, self).__init__() self.conf_parser = ConfigParser() self.conf_parser.read('settings.ini') self.host = self.conf_parser['host_settings']['host_ip'] self.port = self.conf_parser['host_settings']['host_port'] self.navigate_to_screen = navigate_to self.name = screen_name self.register_screen = register_screen self.lower_panel = BoxLayout(orientation='vertical', spacing=5, padding=15) self.add_widget(self.lower_panel) self.username_input = TextInput(size_hint_y=.6, multiline=False) self.password_input = TextInput(size_hint_y=.6, multiline=False) self.login_button = Button(text='Login', on_release=self.login_user, size_hint_y=.6, background_normal='', background_color=[.99, .3, .3, .99]) self.register_button = Button(text='Registration', on_release=self.go_to_registration, size_hint_y=.6, background_normal='', background_color=[.99, .3, .3, .99]) self.status_label = Label() self.lower_panel.add_widget(Label(text='Login', size_hint_y=.6)) self.lower_panel.add_widget(self.username_input) self.lower_panel.add_widget(Label(text='Password', size_hint_y=.6)) self.lower_panel.add_widget(self.password_input) self.lower_panel.add_widget(self.login_button) self.lower_panel.add_widget(self.register_button) self.lower_panel.add_widget(self.status_label) def login_user(self, *args): link = r'http://{}:{}/login/'.format(self.host, self.port) j_data = {} j_data["username"] = self.username_input.text j_data["password"] = self.password_input.text response = requests.post(link, data=j_data) if response.status_code == 200: response_data = response.json() if response_data['state'] == 'ok': self.manager.transition.direction = 'up' self.manager.current = self.navigate_to_screen def go_to_registration(self, *args): self.manager.transition.direction = 'down' self.manager.current = self.register_screen
def GetCharacterIni(configname): config = ConfigParser() config.read("./characters/"+configname) dictionary = {} for section in config.sections(): dictionary[section] = {} for option in config.options(section): dictionary[section][option] = config.get(section, option) return dictionary
def __init__(self, **kwargs): super(ListParam, self).__init__(**kwargs) from kivy.uix.settings import Settings, SettingsWithSpinner, SettingsPanel from kivy.config import ConfigParser print("parammmmmmmm") #json param #graphics conf_graphics = [ #{"type": "title", "title": "Windows"}, { "type": "bool", "title": "Fullscreen", "desc": "Set the window in windowed or fullscreen", "section": "graphics", "key": "fullscreen" } ] #theme conf_theme = [{ "type": "options", "title": "Style", "desc": "Style des fenêtres", "section": "theme", "key": "Style", 'options': ['Light', 'Dark'] }, { "type": "options", "title": "Palette", "desc": "Couleurs des fenêtres", "section": "theme", "key": "Palette", 'options': [ "Red", "Pink", "Purple", "DeepPurple", "Indigo", "Blue", "LightBlue", "Cyan", "Teal", "Green", "LightGreen", "Lime", "Yellow", "Amber", "Orange", "DeepOrange", "Brown", "Gray", "BlueGray" ] }] config = ConfigParser() config.read('config.ini') s = Settings() #s.add_json_panel('My custom panel', config, 'settings_custom.json') #s.add_json_panel('Another panel', config, 'settings_test2.json') s.add_json_panel('Graphics', config, data=json.dumps(conf_graphics)) s.add_json_panel('Theme', config, data=json.dumps(conf_theme)) self.ids.grid_id.add_widget(s)
class TetrisApp(App): def build_config(self, config): config.setdefaults( 'tetris', { "length": 50, "boader": 12, "activity_cols": 12, "activity_rows": 24 } ) config.setdefaults( 'color', { "root_bgclr": "'0.6, 0.6, 0.6'" } ) def build(self): #self.config = Config.get_configparser('app') self.config = ConfigParser(name='tetris_cfg') self.config.read('tetris.ini') #print "app cfg", self.config.filename #parser = ConfigParser.get_configparser('app') #clr = parser.get("color", "root_bgclr").encode("utf-8") clr = self.config.getdefault("color", "root_bgclr", '1,1,1') m = re.search(r'.*?(\d+).*,.*?(\d+).*,.*?(\d+).*', clr) self.root_bgclr_r = float(m.groups()[0])/255 self.root_bgclr_g = float(m.groups()[1])/255 self.root_bgclr_b = float(m.groups()[2])/255 clr = self.config.getdefault("color", "activity_bgclr", '1,1,1') m = re.search(r'.*?(\d+).*,.*?(\d+).*,.*?(\d+).*', clr) self.activity_bgclr_r = float(m.groups()[0])/255 self.activity_bgclr_g = float(m.groups()[1])/255 self.activity_bgclr_b = float(m.groups()[2])/255 # self.length = parser.getint("tetris", "length") # self.activity_rows = parser.getint("tetris", "activity_rows") # self.activity_cols = parser.getint("tetris", "activity_cols") self.anchor_x = self.config.getdefaultint("tetris", "anchor_x", 50) self.anchor_y = self.config.getdefaultint("tetris", "anchor_y", 50) self.length = self.config.getdefaultint("tetris", "length", 50) self.activity_rows = self.config.getdefaultint("tetris", "activity_rows", 24) self.activity_cols = self.config.getdefaultint("tetris", "activity_cols", 12) self.test = self.config.getdefaultint("tetris", "test", 100) logging.debug("[%d] [%d] [%d] [%d]", self.length, self.activity_rows, self.activity_cols, self.test) rootWidget = RootWidget() rootWidget.StartGame() return rootWidget def clear_canvas(self, obj): self.painter.canvas.clear()
def get_sync_server(self): ini = self.root.join('ristomele.ini') if ini.exists(): config = ConfigParser() config.read(str(ini)) host = config.get('server', 'host') port = config.get('server', 'port') return host, port else: return DEFAULT_HOST, DEFAULT_PORT
def fill_rows_with_chars(self, g, grids): chars = list(filter(lambda x: x.series == g, characters.values())) chars = sorted(chars, key=lambda x: x.name) fav = App.get_running_app().get_fav_chars() config = ConfigParser() config.read('mysteryonline.ini') fav_list = str(config.get('other', 'fav_characters').strip('[]')) fav_list = fav_list.replace("'", "") fav_list = fav_list.split(',') fav_list = [x.strip() for x in fav_list] if g == 'Search': for char_name in self.search_results: found_char = self.chars[char_name] btn = CharacterToggle(found_char, group='char', size=[60, 60], text_size=[60, 60], valign='center', halign='center', markup=True) btn.bind(on_touch_down=self.right_click, state=self.character_chosen) if char_name == self.picked_char: btn.state = 'down' grids[g].add_widget(btn) for c in chars: if c.name in fav_list and c.name in fav.value and 'Favorites' in self.value: fav_btn = CharacterToggle(c, group='char', size=[60, 60], text_size=[60, 60], valign='center', halign='center', markup=True) fav_btn.bind(on_touch_down=self.right_click, state=self.character_chosen) if c == self.picked_char: fav_btn.state = 'down' grids['Favorites'].add_widget(fav_btn) if c.series in self.value: btn = CharacterToggle(c, group='char', size=[60, 60], text_size=[60, 60], valign='center', halign='center', markup=True) btn.bind(on_touch_down=self.right_click, state=self.character_chosen) if c == self.picked_char: btn.state = 'down' grids[g].add_widget(btn) fav_list.clear()
class ProjectSettings(Settings): '''Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of project. ''' project = ObjectProperty(None) '''Reference to :class:`desginer.project_manager.Project` ''' config_parser = ObjectProperty(None) '''Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` ''' def load_proj_settings(self): '''This function loads project settings ''' self.config_parser = ConfigParser() file_path = os.path.join(self.project.path, PROJ_CONFIG) if not os.path.exists(file_path): if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) CONFIG_TEMPLATE = '''[proj_name] name = Project [arguments] arg = [env variables] env = ''' f = open(file_path, 'w') f.write(CONFIG_TEMPLATE) f.close() self.config_parser.read(file_path) _dir = os.path.dirname(designer.__file__) _dir = os.path.split(_dir)[0] settings_dir = os.path.join(_dir, 'designer', 'settings') self.add_json_panel('Shell Environment', self.config_parser, os.path.join(settings_dir, 'proj_settings_shell_env.json')) self.add_json_panel('Project Properties', self.config_parser, os.path.join(settings_dir, 'proj_settings_proj_prop.json')) @ignore_proj_watcher def on_config_change(self, *args): '''This function is default handler of on_config_change event. ''' self.config_parser.write() super(ProjectSettings, self).on_config_change(*args)
class ProjectSettings(Settings): '''Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of project. ''' proj_loader = ObjectProperty(None) '''Reference to :class:`desginer.project_loader.ProjectLoader` ''' config_parser = ObjectProperty(None) '''Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` ''' def load_proj_settings(self): '''This function loads project settings ''' self.config_parser = ConfigParser() file_path = os.path.join(self.proj_loader.proj_dir, PROJ_CONFIG) if not os.path.exists(file_path): if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) CONFIG_TEMPLATE = '''[proj_name] name = Project [arguments] arg = [env variables] env = ''' f = open(file_path, 'w') f.write(CONFIG_TEMPLATE) f.close() self.config_parser.read(file_path) _dir = os.path.dirname(designer.__file__) _dir = os.path.split(_dir)[0] settings_dir = os.path.join(_dir, 'designer', 'settings') self.add_json_panel('Shell Environment', self.config_parser, os.path.join(settings_dir, 'proj_settings_shell_env.json')) self.add_json_panel('Project Properties', self.config_parser, os.path.join(settings_dir, 'proj_settings_proj_prop.json')) def on_config_change(self, *args): '''This function is default handler of on_config_change event. ''' self.config_parser.write() super(ProjectSettings, self).on_config_change(*args)
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')
def exec_legacy(arg): try: tmp = arg.split(":") if len(tmp) < 2: raise AssertionError("Error: incorrect service path: " + arg) app_name = tmp[0] app_path = tmp[1] # print "Service: app_name=",app_name," app_path=",app_path setup_logger(app_name) t = threading.Thread(target=alive_worker, args=(30.0, )) t.start() app_dir = os.path.join(mi2app_utils.get_files_dir(), "app") # add this dir to module search path sys.path.append(os.path.join(app_dir, app_path)) app_file = os.path.join(app_dir, app_path, "main.mi2app") Logger.info("Phone model: " + mi2app_utils.get_phone_model()) Logger.info("Running app: " + app_file) # print arg,app_dir,os.path.join(app_dir, arg) namespace = {"service_context": mi2app_utils.get_service_context()} # Load configurations as global variables config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') ii = arg.rfind('/') section_name = arg[ii + 1:] plugin_config = {} if section_name in config.sections(): config_options = config.options(section_name) for item in config_options: plugin_config[item] = config.get(section_name, item) namespace["plugin_config"] = plugin_config gps_provider = GpsListener(on_gps) gps_provider.start() execfile(app_file, namespace) # print app_name, "stops normally" except Exception as e: # Print traceback logs to analysis tb_exc = traceback.format_exc() Logger.error(tb_exc) l = logging.getLogger("mobileinsight_logger") l.error(tb_exc) sys.exit(tb_exc)
class ProjectSettings(Settings): """Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of project. """ project = ObjectProperty(None) """Reference to :class:`desginer.project_manager.Project` """ config_parser = ObjectProperty(None) """Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` """ def load_proj_settings(self): """This function loads project settings """ self.config_parser = ConfigParser() file_path = os.path.join(self.project.path, PROJ_CONFIG) if not os.path.exists(file_path): if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) CONFIG_TEMPLATE = """[proj_name] name = Project [arguments] arg = [env variables] env = """ f = open(file_path, "w") f.write(CONFIG_TEMPLATE) f.close() self.config_parser.read(file_path) settings_dir = os.path.join(get_kd_data_dir(), "settings") self.add_json_panel( "Shell Environment", self.config_parser, os.path.join(settings_dir, "proj_settings_shell_env.json") ) self.add_json_panel( "Project Properties", self.config_parser, os.path.join(settings_dir, "proj_settings_proj_prop.json") ) @ignore_proj_watcher def on_config_change(self, *args): """This function is default handler of on_config_change event. """ self.config_parser.write() super(ProjectSettings, self).on_config_change(*args)
def load_config(self): '''(internal) This function is used for returning a ConfigParser with the application configuration. It's doing 3 things: #. Creating an instance of a ConfigParser #. Loading the default configuration by calling :meth:`build_config`, then #. If it exists, it loads the application configuration file, otherwise it creates one. :return: :class:`~kivy.config.ConfigParser` instance ''' try: config = ConfigParser.get_configparser('app') except KeyError: config = None if config is None: config = ConfigParser(name='app') self.config = config self.build_config(config) # if no sections are created, that's mean the user don't have # configuration. if len(config.sections()) == 0: return # ok, the user have some sections, read the default file if exist # or write it ! filename = self.get_application_config() if filename is None: return config Logger.debug('App: Loading configuration <{0}>'.format(filename)) if exists(filename): try: config.read(filename) except: Logger.error('App: Corrupted config file, ignored.') config.name = '' try: config = ConfigParser.get_configparser('app') except KeyError: config = None if config is None: config = ConfigParser(name='app') self.config = config self.build_config(config) pass else: Logger.debug('App: First configuration, create <{0}>'.format( filename)) config.filename = filename config.write() return config
def get_config(): config = ConfigParser() config.read('config.ini') config.adddefaultsection('game') config.setdefault('game', 'outside_coordinates', True) config.setdefault('game', 'show_pieces', True) config.setdefault('game', 'square_coordinates', False) return config
def check_update(self): """ Check if new update is available """ try: config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') bcheck_update = config.get("mi_general", "bcheck_update") if bcheck_update == "1": import check_update check_update.check_update() except Exception as e: Logger.exception(traceback.format_exc())
def __init__(self, **kwargs): super(ServerSettings, self).__init__(**kwargs) config = ConfigParser() config.read('serverconfig.ini') config.setdefaults('main', { 'root': '/sdcard', 'allow_uploads': False, 'port': 11451 }) s = SettingsWithNoMenu() s.add_json_panel('Server', config, resource_find('settings.json')) s.on_config_change = restart_server self.add_widget(s)
def build(self): sm = AppScreenManager() config = ConfigParser() config.read('plant.ini') screen1 = UserInput(config, name='main') screen1.bind(on_enter=screen1.startdb) screen1.bind(on_leave=screen1.closedb) sm.add_widget(screen1) sm.add_widget(LoginScreen(config, name='login')) return sm
def privacy_check(self): """ Check if new update is available """ try: config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') privacy_agreed = int(config.get("mi_general", "privacy")) if privacy_agreed == 0: import privacy_app privacy_app.PrivacyApp().run() # if privacy_app.disagree_privacy: # self.stop() except Exception as e: Logger.exception(traceback.format_exc())
class PhidgetApp(App): use_kivy_settings = False last_gained_tag = ObjectProperty(force_dispatch=True) # start the RFID Reader thread rfid = Reader() def __init__(self, *args, **kwargs): super(PhidgetApp, self).__init__(*args, **kwargs) self.config = ConfigParser() def build(self): config = self.config.read('phidget.ini') self.title = 'Phidget RFID Test' root = ScreenManager() for x in range(3): root.add_widget(CustomScreen(name='Screen %d' % x)) return root def on_last_gained_tag(self, instance, value): Logger.info('Last Gained Tag: {}'.format(value['employee_type'])) if 1 in value["employee_type"]: # Operator self.root.current = 'Screen 0' if 2 in value["employee_type"]: # Supervisor self.root.current = 'Screen 1' if 3 in value["employee_type"]: # Supervisor self.root.current = 'Screen 2' self.root.current_screen.tag = value["rfid_tag"]
def _on_answer(self, instance, answer): if answer == "yes": config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') config.set("mi_general", "privacy", 1) config.set("NetLogger", "privacy", 1) config.write() self.popup.dismiss() elif answer == "no": # global disagree_privacy # disagree_privacy = 1 config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') config.set("mi_general", "privacy", 1) config.set("NetLogger", "privacy", 0) config.write() self.popup.dismiss()
def setup_logger(app_name): '''Setup the analyzer logger. NOTE: All analyzers share the same logger. :param level: the loggoing level. The default value is logging.INFO. ''' level = logging.INFO config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') if config.has_option('mi_general', 'log_level'): level_config = config.get('mi_general', 'log_level') if level_config == "info": level = logging.INFO elif level_config == "debug": level = logging.DEBUG elif level_config == "warning": level = logging.WARNING elif level_config == "error": level = logging.ERROR elif level_config == "critical": level = logging.CRITICAL l = logging.getLogger("mobileinsight_logger") if len(l.handlers) < 1: # formatter = MyFormatter( # '%(asctime)s %(message)s', # datefmt='%Y-%m-%d,%H:%M:%S.%f') formatter = MyFormatter('%(message)s') streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) l.setLevel(level) l.addHandler(streamHandler) l.propagate = False log_file = os.path.join( mi2app_utils.get_mobileinsight_analysis_path(), app_name + "_log.txt") Logger.info('service: mi log file: ' + log_file) fileHandler = logging.FileHandler(log_file, mode='w') fileHandler.setFormatter(formatter) l.addHandler(fileHandler) l.disabled = False
def loadFromFile(self, file): if file[-3:] != 'ini': self.root.notification('Load', 'wrong file extension') return commands = ConfigParser() commands.read(file) try: for section in commands.sections(): for values in commands.items(section): self.commands.set(section, values[0], values[1]) if section in self.updateSettings.keys(): self.updateSettings[section].update({values[0]:values[1]}) else: self.updateSettings.update({section:{values[0]:values[1]}}) self.root.notification('Load', 'load successful') App.get_running_app().root.ids.settingsLayout.ids.option.setOptions() except: self.root.notification('Load', 'wrong file')
def set_current_user(self): config = ConfigParser() config.read('mysteryonline.ini') user = User(self.username) user_handler = CurrentUserHandler(user) if self.picked_char is not None: user.set_char(self.picked_char) user.get_char().load() else: try: user.set_char(characters[str(config.get('other', 'last_character'))]) user.get_char().load() except KeyError: red_herring = characters['RedHerring'] user.set_char(red_herring) user.get_char().load() App.get_running_app().set_user(user) App.get_running_app().set_user_handler(user_handler)
class DesignerSettings(Settings): '''Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of Kivy Designer. ''' config_parser = ObjectProperty(None) '''Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` ''' def load_settings(self): '''This function loads project settings ''' self.config_parser = ConfigParser() DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME) _dir = os.path.dirname(designer.__file__) _dir = os.path.split(_dir)[0] DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME) if not os.path.exists(DESIGNER_CONFIG): shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG) self.config_parser.read(DESIGNER_CONFIG) self.config_parser.upgrade(DEFAULT_CONFIG) self.add_json_panel('Kivy Designer Settings', self.config_parser, os.path.join(_dir, 'designer', 'settings', 'designer_settings.json')) path = self.config_parser.getdefault( 'global', 'python_shell_path', '') if path == "": self.config_parser.set('global', 'python_shell_path', sys.executable) self.config_parser.write() def on_config_change(self, *args): '''This function is default handler of on_config_change event. ''' self.config_parser.write() super(DesignerSettings, self).on_config_change(*args)
class NewGame(AnchorLayout): app = ObjectProperty(None) config = ObjectProperty(None) settings = ObjectProperty(None) def __init__(self, **kwargs): super(NewGame, self).__init__(**kwargs) self.config = ConfigParser() self.config.read(tttraders_user_conf('tttraders.ini')) self.settings.register_type("int", TTSettingInt) for tab in TradersGame.ConfigTabs: lst = TradersGame.Config[tab] for c in lst: if c.get("key", None): self.config.adddefaultsection(c['section']) self.config.setdefault(c['section'], c['key'], c.get("default", None)) self.settings.add_json_panel(tab, self.config, data=json.dumps(lst))
def on_start(self): """ Método chamado para inicializar o menu inicial :return: nada """ Window.size = (300, 100) config = ConfigParser() # Carrega últimas configurações utilizadas (ou padrões se arquivo não é encontrado) config.read('settings.ini') self.username = config.get('section0', 'key00') self.color = SettingsApp.get_color(config.get('section0', 'key01')) if config.get('section1', 'key10') == "Single": self.is_multiplayer = False else: self.is_multiplayer = True self.match = config.get('section1', 'key11') self.rows = config.getint('section2', 'key20') self.columns = config.getint('section2', 'key21') self.bombs = config.getint('section3', 'key30')
def on_new(self, *args): '''Handler for "New Profile" button ''' new_name = 'new_profile' i = 1 while os.path.exists(os.path.join( self.PROFILES_PATH, new_name + str(i) + '.ini')): i += 1 new_name += str(i) new_prof_path = os.path.join( self.PROFILES_PATH, new_name + '.ini') shutil.copy2(os.path.join(self.DEFAULT_PROFILES, 'desktop.ini'), new_prof_path) config_parser = ConfigParser() config_parser.read(new_prof_path) config_parser.set('profile', 'name', new_name.upper()) config_parser.write() self.update_panel() self.settings_changed = True
class DesignerSettings(Settings): """Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of Kivy Designer. """ config_parser = ObjectProperty(None) """Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` """ def load_settings(self): """This function loads project settings """ self.config_parser = ConfigParser() DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME) _dir = os.path.dirname(designer.__file__) _dir = os.path.split(_dir)[0] if not os.path.exists(DESIGNER_CONFIG): shutil.copyfile(os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME), DESIGNER_CONFIG) self.config_parser.read(DESIGNER_CONFIG) self.add_json_panel( "Kivy Designer Settings", self.config_parser, os.path.join(_dir, "designer", "settings", "designer_settings.json"), ) path = self.config_parser.getdefault("global", "python_shell_path", "") if path == "": self.config_parser.set("global", "python_shell_path", sys.executable) self.config_parser.write() def on_config_change(self, *args): """This function is default handler of on_config_change event. """ self.config_parser.write() super(DesignerSettings, self).on_config_change(*args)
def __init__(self, *args, **kwargs): self.callback = kwargs.pop("callback", None) self.pages = kwargs.pop("pages", ["general", "synchronisation", "kivy"]) self.title = "Paramètres" self.size_hint = (0.9, 0.9) config = ConfigParser() config.read(UTILS_Divers.GetRepData() + "config.cfg") self.settings = Settings() self.settings.register_type('password', SettingPassword) self.settings.register_type('chaine', SettingChaine) if "general" in self.pages : self.settings.add_json_panel("Généralités", config, data=json.dumps(JSON_GENERAL, encoding="utf-8")) if "synchronisation" in self.pages : self.settings.add_json_panel("Synchronisation", config, data=json.dumps(JSON_SYNCHRONISATION, encoding="utf-8")) if "kivy" in self.pages : self.settings.add_kivy_panel() self.settings.interface.menu.close_button.text = "Fermer" self.content = self.settings self.settings.bind(on_close=self.OnBoutonFermer) self.bind(on_dismiss=self.on_dismiss) super(Popup, self).__init__(*args, **kwargs)
class DesignerSettings(Settings): '''Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of Kivy Designer. ''' config_parser = ObjectProperty(None) '''Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` ''' def __init__(self, **kwargs): super(DesignerSettings, self).__init__(*kwargs) self.register_type('list', SettingList) self.register_type('shortcut', SettingShortcut) def load_settings(self): '''This function loads project settings ''' self.config_parser = ConfigParser(name='DesignerSettings') DESIGNER_CONFIG = os.path.join(get_config_dir(), DESIGNER_CONFIG_FILE_NAME) _dir = os.path.dirname(designer.__file__) _dir = os.path.split(_dir)[0] DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME) if not os.path.exists(DESIGNER_CONFIG): shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG) self.config_parser.read(DESIGNER_CONFIG) self.config_parser.upgrade(DEFAULT_CONFIG) # creates a panel before insert it to update code input theme list panel = self.create_json_panel('Kivy Designer Settings', self.config_parser, os.path.join(_dir, 'designer', 'settings', 'designer_settings.json')) uid = panel.uid if self.interface is not None: self.interface.add_panel(panel, 'Kivy Designer Settings', uid) # loads available themes for child in panel.children: if child.id == 'code_input_theme_options': child.items = styles.get_all_styles() # tries to find python and buildozer path if it's not defined path = self.config_parser.getdefault( 'global', 'python_shell_path', '') if path.strip() == '': self.config_parser.set('global', 'python_shell_path', sys.executable) self.config_parser.write() buildozer_path = self.config_parser.getdefault('buildozer', 'buildozer_path', '') if buildozer_path.strip() == '': buildozer_path = find_executable('buildozer') if buildozer_path: self.config_parser.set('buildozer', 'buildozer_path', buildozer_path) self.config_parser.write() self.add_json_panel('Buildozer', self.config_parser, os.path.join(_dir, 'designer', 'settings', 'buildozer_settings.json')) self.add_json_panel('Hanga', self.config_parser, os.path.join(_dir, 'designer', 'settings', 'hanga_settings.json')) self.add_json_panel('Keyboard Shortcuts', self.config_parser, os.path.join(_dir, 'designer', 'settings', 'shortcuts.json')) def on_config_change(self, *args): '''This function is default handler of on_config_change event. ''' self.config_parser.write() super(DesignerSettings, self).on_config_change(*args)
class DuplicatorApp(App): #icon = 'icon.png' title = 'Duplicator - Ultimate 3D Printing App' #use_kivy_settings = False sm = 0 gcode = None ''' def build_config(self, config): config.setdefaults('general', { 'app_background_color': '000000', 'app_width': '640' } ) config.setdefaults('printer', { 'printer_com_port': '/dev/tty.usbmodem1411', 'printer_com_speed': '115200', 'printer_extruder_count': '2', 'printer_heated_bed': '70', 'printer_extruder_1_temp': '220', 'printer_extruder_2_temp': '220', 'printer_bed_temp': '70' } ) ''' def build_settings(self, settings): settings.add_json_panel('General Panel', self.config, join(dirname(__file__),'settings/settings_general.json' ) ) settings.add_json_panel('Printer panel', self.config, join(dirname(__file__),'settings/settings_printer.json') ) settings.add_json_panel('Scanner panel', self.config, join(dirname(__file__),'settings/settings_scanner.json') ) def build(self): self.config = ConfigParser() self.config.read(join( dirname(__file__),'duplicator.ini') ) print( self.config.get('general','app_background_color') ) #if not self.config.has_section("general"): # self.config.add_section("general") self.activeprinter = None self.printer_pause = 0 self.sm = ScreenManager() self.sm.add_widget(MenuScreen(name='Menu')) self.sm.add_widget(PrintScreen(name='Print')) self.sm.add_widget(ScanScreen(name='Scan')) self.sm.add_widget(ShareScreen(name='Share')) self.sm.add_widget(ConfigScreen(name='Config')) self.sm.add_widget(PlaterScreen(name='Plater')) self.sm.add_widget(ViewScreen(name='View')) self.sm.add_widget(FileGcodeLoadScreen(name='FileGcodeLoad')) self.menu_bar = Factory.MenuBar() self.sm.get_screen('Menu').ids.window_layout.add_widget(self.menu_bar) self.menu_bar.ids.short_message.text = 'Duplicator Started\nReady for action.' self.cam1 = cv2.VideoCapture(0) return self.sm def switchtoscreen(self,ScreenName): if ScreenName == 'Menu': self.sm.transition = SlideTransition(direction='left') elif ScreenName == 'FileGcodeLoad': self.sm.transition = SlideTransition(direction='up') else: if(self.sm.current=='FileGcodeLoad'): self.sm.transition = SlideTransition(direction='down') else: self.sm.transition = SlideTransition(direction='right') #print(self.sm.current) print(ScreenName) if(ScreenName != 'FileGcodeLoad') and (self.sm.current!='FileGcodeLoad'): self.sm.get_screen(self.sm.current).ids.window_layout.remove_widget(self.menu_bar) self.sm.get_screen(ScreenName).ids.window_layout.add_widget(self.menu_bar) self.sm.current = ScreenName def connectprinter(self,activeswitch): if activeswitch: self.menu_bar.ids.short_message.text = 'disconnecting....' try: self.activeprinter.disconnect() self.menu_bar.ids.short_message.text = 'Done' self.sm.get_screen('Print').ids.connectprinterswitch.active=0 self.activeprinter = None self.menu_bar.ids.indicator_printer.color = (0,0,0,.3) except: self.menu_bar.ids.short_message.text = 'No printer!' self.sm.get_screen('Print').ids.connectprinterswitch.active=0 self.menu_bar.ids.indicator_printer.color = (1,0,0,1) else: #print(self.sm.get_screen('Print').ids) #print('connecting....') self.menu_bar.ids.short_message.text ='connecting....' try: #self.config.get('printer','printer_com_port'),self.config.get('printer','printer_com_speed') self.activeprinter=printcore('/dev/tty.usbmodem1411','115200') #print('connected') self.menu_bar.ids.short_message.text = 'connected' self.sm.get_screen('Print').ids.connectprinterswitch.active=1 self.sm.get_screen('Print').ids.connectprinterswitch.state = 'down' self.menu_bar.ids.indicator_printer.color = (0,1,0,1) except: self.menu_bar.ids.short_message.text = 'Unable to connect!' #print('Unable to connect!') self.sm.get_screen('Print').ids.connectprinterswitch.active=0 self.sm.get_screen('Print').ids.connectprinterswitch.state = 'normal' self.menu_bar.ids.indicator_printer.color = (1,0,0,1) def homeprinter(self): self.Send('G28') #if self.activeprinter != None: #self.activeprinter.send('G28') def homeX(self): if self.activeprinter != None: self.activeprinter.send('G28 X') def homeY(self): if self.activeprinter != None: self.activeprinter.send('G28 Y') def homeZ(self): if self.activeprinter != None: self.activeprinter.send('G28 Z') def pause(self): if self.activeprinter != None: if self.printer_pause: self.activeprinter.pause() self.sm.get_screen('Print').ids.connectprinterswitch.state = 'normal' else: self.activeprinter.resume() self.sm.get_screen('Print').ids.connectprinterswitch.state = 'down' def emergencyStop(self): if self.activeprinter != None: self.activeprinter.send_now('M112') def send(self,code): if self.activeprinter != None: self.activeprinter.send(code) def move(self,axes,distance): if self.activeprinter != None: self.activeprinter.send('G1 '+axes+' '+distance) def cameraSwitch(self): if(self.sm.get_screen('Scan').ids.camera_button.state=='normal'): #self.sm.get_screen('Scan').ids.scan_camera.play=True #self.sm.get_screen('Scan').ids.scan_camera.resolution=(640, 480) #self.sm.get_screen('Scan').ids.scan_camera.index=0 self.sm.get_screen('Scan').ids.camera_button.color = (1,1,1,1) self.menu_bar.ids.indicator_scanner.color = (1,1,0,1) self.menu_bar.ids.indicator_camera.color = (0,1,0,1) #ret, frame = cam.read() #Clock.schedule_interval(self.camUpdate, 1.0/33.0) else: #self.sm.get_screen('Scan').ids.scan_camera.play=False self.sm.get_screen('Scan').ids.camera_button.color = (0,0,0,1) self.menu_bar.ids.indicator_scanner.color = (1,1,1,.3) self.menu_bar.ids.indicator_camera.color = (1,1,1,.3) def closeSettingsScreen(self): App.close_settings() def printGcodeFile(self): if self.activeprinter != None: if self.gcode != None: self.activeprinter.startprint(self.gcode,0) self.menu_bar.ids.indicator_printer.color = (1,1,0,1) else: self.menu_bar.ids.indicator_printer.color = (0,1,0,1) self.menu_bar.ids.short_message.text = 'No File Loaded!' else: self.menu_bar.ids.indicator_printer.color = (1,1,1,.33) self.menu_bar.ids.short_message.text = 'No Printer Connected!' def reset(self): if self.activeprinter != None: self.activeprinter.reset() def show_gcode_load(self): self.switchtoscreen('FileGcodeLoad') def cancelFileGcodeLoad(self): self.switchtoscreen('Print') def load_gcode(self, path, filename): with open(os.path.join(path, filename[0])) as stream: gcode_string = stream.read() self.sm.get_screen('Print').ids.gcode_file_name.text = filename[0] self.gcode = gcode_string.split('\n') #print(self.gcode.lines) self.switchtoscreen('Print')
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 Program(App, prog_class.ShowPlugin, prog_class.ShowThemesForum, prog_class.ShowSectionsForum, prog_class.ShowSendMailForm, prog_class.ShowTopicsForum, prog_class.ShowListMail, prog_class.ShowFileDetails, prog_class.ShowUploadForm, prog_class.ShowFiles, prog_class.ShowUserProfile, ConnectionToServer): """Функционал программы.""" # Языковая локализация - переменные с префиксом core.string_lang_. # Используются в классах библиотеки programclass. В текущем классе - # без ключевого слова self, так как были импортированы из programdata exec(open("{}/Data/Language/{}.txt".format( core.prog_path, language)).read().replace( "#key_text_color", core.theme_key_text_color.encode("u8")).replace( "#text_color", core.theme_text_color.encode("u8")).replace( "#link_color", core.theme_link_color.encode("u8"))) # TODO: Константа CONST_SCREEN используется модулем kdialog для # вычесления ширины диалогового окна (Window.size[0] / CONST_SCREEN). # size_hint_x для этих целей неуместен. Например, при размере экрана # 600x300 и параметре size_hint_x=.5 окно будет слишком # узким и наоборот - 300x600 и тот же параметр size_hint_x - покажут окно # занимаемое бОльшую плоскость экрана. WIDTH, HEIGHT = Window.size if WIDTH <= HEIGHT: CONST_SCREEN = 1.2 else: CONST_SCREEN = 2 window_text_size = 15 update = None # нет обновлений messages_unread = None # количество новых сообщений open_dialog = False # если True - открыто диалоговое окно number_user = None # номер участника на сайте cookie = None site = "http://m.dimonvideo.ru" previous_screen = None def __init__(self, **kvargs): super(Program, self).__init__(**kvargs) Window.bind(on_keyboard=self.events_program) # Для области видимомти в programclass. self.FadeTransition = FadeTransition self.Screen = Screen self.Clock = Clock # ---------------------------------- self.parsing_xml = parsing_xml self.get_page = get_page self.set_cookie = set_cookie self.Manifest = Manifest self.core = core # ---------------------------------- self.sendmail = sendmail self.setattachtoforum = setattachtoforum # ---------------------------------- self.KDialog = KDialog self.FileChooser = FileChooser self.SelectColor = SelectColor self.CustomSpinner = CustomSpinner self.PageSendMail = PageSendMail self.ScrollButton = ScrollButton self.ThemesForum = ThemesForum self.AboutDialog = AboutDialog self.UploadFiles = UploadFiles self.MessageViewer = MessageViewer self.MailList = MailList self.BugReporter = BugReporter self.ImageViewer = ImageViewer self.customspinner = customspinner self._urllib = _urllib self.traceback = traceback # ---------------------------------- self.clipboard = clipboard # ---------------------------------- self.theme_decorator_window = core.theme_decorator_window def get_application_config(self): return super(Program, self).get_application_config( "{}/program.ini".format(core.prog_path)) def build_config(self, config): config.adddefaultsection("General") config.setdefault("General", "showonstartpage", u"Новости сайта") config.setdefault("General", "language", u"Русский") config.setdefault("General", "showwarning", "1") config.setdefault("General", "resmessages", "1") config.setdefault("General", "authorization", "0") config.setdefault("General", "progresstextsize", "15") config.setdefault("General", "downloadkey", "0") config.setdefault("General", "downloadfolder", {0: 'Downloads', 1: ''}) config.setdefault("General", "user_reg", {"login": "******", "password": "******"}) config.adddefaultsection("Network") config.setdefault("Network", "authoconnect", "0") config.setdefault("Network", "checkattachtoforum", "1") config.setdefault("Network", "loadscr", "0") config.setdefault("Network", "authoupdate", "1") config.adddefaultsection("Mail") config.setdefault("Mail", "messagesread", "1") config.setdefault("Mail", "intervalscanmess", "10") config.adddefaultsection("Theme") config.setdefault("Theme", "theme", "blue_orange") config.setdefault("Theme", "edittheme", "0") config.setdefault("Theme", "createtheme", "0") def build_settings(self, settings): general_settings = open("{}/Data/Settings/general.json".format( core.prog_path)).read() general_data = general_settings % ( core.string_lang_setting_show_on_home_page, core.string_lang_setting_show_on_home_page_title, core.string_lang_setting_show_on_home_page_desc, core.string_lang_setting_news, core.string_lang_setting_show_on_home_page_themes, core.string_lang_setting_language, core.string_lang_setting_language_title, core.string_lang_setting_language_desc, core.string_lang_setting_language_russian, core.string_lang_setting_language_english, core.string_lang_setting_font, core.string_lang_setting_font_title, core.string_lang_setting_font_desc, core.string_lang_setting_download, core.string_lang_setting_download_title, core.string_lang_setting_download_desc) % \ self.downloadfolder[self.downloadkey] network_settings = open("{}/Data/Settings/network.json".format( core.prog_path)).read() network_data = network_settings % ( core.string_lang_setting_connect, core.string_lang_setting_connect_title, core.string_lang_setting_connect_desc, core.string_lang_setting_update, core.string_lang_setting_update_title, core.string_lang_setting_update_desc, core.string_lang_setting_checkattachtoforum_title, core.string_lang_setting_checkattachtoforum_desc, core.string_lang_setting_loadscr_title, core.string_lang_setting_loadscr_desc) mail_settings = open("{}/Data/Settings/mail.json".format( core.prog_path)).read() mail_data = mail_settings % ( core.string_lang_setting_mail, core.string_lang_setting_mail_title, core.string_lang_setting_mail_desc, core.string_lang_setting_mail_interval_title, core.string_lang_setting_mail_interval_desc) theme_settings = open("{}/Data/Settings/theme.json".format( core.prog_path)).read() theme_data = theme_settings % ( core.string_lang_setting_chek_themes, core.string_lang_setting_chek_themes_title, core.string_lang_setting_chek_themes_desc, '", "'.join(os.listdir("{}/Data/Themes".format(core.prog_path))), core.string_lang_setting_edit_themes_title, core.string_lang_setting_edit_themes_desc, core.string_lang_setting_create_themes_title, core.string_lang_setting_create_themes_desc) settings.add_json_panel(core.string_lang_general, self.config, data=general_data) settings.add_json_panel(core.string_lang_internet, self.config, data=network_data) settings.add_json_panel(core.string_lang_mail[:-1], self.config, data=mail_data) settings.add_json_panel(core.string_lang_theme, self.config, data=theme_data) def on_config_change(self, config, section, key, value): """Вызывается при выборе одного из пункта настроек программы.""" def select_callback(*args): file_manager.body.dismiss() self.downloadfolder[1] = file_manager.select_folder config.set("General", "downloadkey", "1") config.set("General", "downloadfolder", str(self.downloadfolder)) config.write() # TODO: обновить описание раздела на путь к выбранной директориии. if key == "downloadkey" and int(value): # "Настройки загрузок" file_manager = \ FileChooser(select_callback=select_callback, filter="folder", title=core.string_lang_select_folder, background_image=self.core.theme_decorator_window, auto_dismiss=False, size=(.85, .9),) elif key == "downloadkey" and not int(value): self.downloadfolder[1] = "" config.set("General", "downloadkey", "0") config.set("General", "downloadfolder", str(self.downloadfolder)) config.write() elif key == "checkattachtoforum": # "Проверка формы аттача" self.checkattachtoforum = int(value) elif key == "progresstextsize": # "Настойка размера шрифта" self.window_text_size = int(value) elif key == "edittheme": # "Правка палитры установленной темы" self.edit_pallete_theme() def on_pause(self): """Ставит приложение на 'паузу' при выхоже из него. В противном случае запускает программу по заново""" return True def build(self): self.title = core.string_lang_title[:-1] # заголовок окна программы self.icon = "Data/Images/logo.png" # иконка окна программы self.use_kivy_settings = False self.config = ConfigParser() self.config.read("{}/program.ini".format(core.prog_path)) self.beep = SoundLoader.load("Data/mess_unread.wav") self.set_variable_from_settings() # Домашняя страница клиента. self.start_screen = \ StartScreen(name_buttons_menu=core.name_buttons_menu, buttons_menu=core.buttons_menu, buttons_group=core.buttons_group, previous="Data/Images/logo.png", title_previous=core.string_lang_title[:-1], title_image="Data/Images/DV.png", overflow_image="Data/Images/overflow_image.png", previous_image="Data/Images/previous_image.png", events_callback=self.events_program) self.screen = self.start_screen Clock.schedule_once(self.read_license, 3) return self.start_screen def edit_pallete_theme(self): print("edit_pallete_theme") def set_variable_from_settings(self): self.messagesread = self.config.getint( "Mail", "messagesread") self.intervalscanmess = self.config.getint( "Mail", "intervalscanmess") self.loadscr = self.config.getint( "Network", "loadscr") self.checkattachtoforum = self.config.getint( "Network", "checkattachtoforum") self.authoupdate = self.config.getint( "Network", "authoupdate") self.authoconnect = self.config.getint( "Network", "authoconnect") self.downloadkey = self.config.getint( "General", "downloadkey") self.downloadfolder = eval(self.config.get( "General", "downloadfolder")) self.window_text_size = self.config.getint( "General", "progresstextsize") self.language = core.select_locale[self.config.get( "General", "language")] self.showonstartpage = self.config.get( "General", "showonstartpage") self.authorization = self.config.getint( "General", "authorization") self.resmessages = self.config.getint( "General", "resmessages") _user_reg = eval(self.config.get( "General", "user_reg")) try: self.user_reg = {"login": _user_reg["login"].decode("hex"), "password": _user_reg["password"].decode("hex")} except TypeError: self.user_reg = {"login": _user_reg["login"], "password": _user_reg["password"]} except AttributeError: # Python 3 self.user_reg = {"login": _user_reg["login"], "password": bytes.fromhex( _user_reg["password"]).decode('utf-8')} def read_license(self, *args): def dialog_answer_handler(*args): """Функция обработки сигналов диалогового окна. type answer: str; param answer: имя нажатой кнопки или введенного текта; """ if len(args) == 1: # нажата кнопка answer = args[0] if answer == core.string_lang_yes: open("{}/README.md".format(core.prog_path), "w").write( re.sub('\[.*?]', '', license).replace("\n\n\n", "\n")) self.open_dialog = False # Устанавливаем подпись на домашней странице клиента - # "Мобильный клиент сайта dimonvideo.ru" self.start_screen.mobile_client_label.text = \ core.string_lang_mobile_client_label # Автоматическое подключение при старте. if self.authoconnect \ and self.user_reg["login"] != "login" \ and self.user_reg["password"] != "password": Clock.schedule_once(self.connect, 0) elif answer == core.string_lang_no: sys.exit(1) else: # нажата ссылка link = args[1] webbrowser.open(link) # Если пользователь уже был авторизирован. if self.authorization or os.path.exists("{}/README.md".format( core.prog_path)): if self.authoconnect and self.user_reg["login"] != "login" and \ self.user_reg["password"] != "password": self.connect() else: self.start_screen.mobile_client_label.text = \ core.string_lang_mobile_client_label else: self.open_dialog = True license = \ core.string_lang_license.replace( "--------------------------------------------------------" "-----------------------", "").split( "[color={}]ОПИСАНИЕ ".format(core.theme_key_text_color))[0] # Спрашиваем, согласен ли пользователь с условиями. self.create_window(callback=dialog_answer_handler, size_x=1.2, text=license, button_ok=core.string_lang_yes, button_no=core.string_lang_no, param="query") def events_program(self, *args): """Вызывается при выборе одного из пунктов меню программы.""" if self.open_dialog: return if len(args) == 2: # нажата ссылка event = args[1].encode("utf-8") else: # нажата кнопка try: _args = args[0] event = _args if isinstance(_args, str) else _args.id except AttributeError: # ввод текста в форму отправки сообщений return #if not self.cookie and event == core.string_lang_item_menu_profile: # self.create_window(core.string_lang_authorization_client) # return # ------------------------------ВОЙТИ---------------------------------- if event == core.string_lang_item_menu_connect: self.connect() # -----------------------------ПРОФИЛЬ--------------------------------- if event == core.string_lang_item_menu_profile: progress = self.create_window(core.string_lang_info_your, param="loaddialog") Clock.schedule_once(lambda *args: self.show_user_profile( progress, self.user_reg["login"]), 0.1) # ----------------------------ACTION BAR------------------------------- elif event == "previous" or event in (1000, 27): self.back_screen() # -----------------------------НАСТРОЙКИ------------------------------ elif event == core.string_lang_item_menu_settings: self.open_settings() # -----------------------------ЛИЦЕНЗИЯ------------------------------- elif event == core.string_lang_item_menu_license: self.create_window( callback=self.show_license, size_x=1.2, text=core.string_lang_license.split( "[color={}]Нажав ".format( core.theme_text_color))[0].replace( "\n--------------------------------------------" "-----------------------------------", ""), button_ok=core.string_lang_on_russian, button_no=core.string_lang_on_english, param="query", dismiss=True) # ----------------------------О ПРОГРАММЕ------------------------------ elif event == core.string_lang_item_menu_about: self.show_about() elif event == core.string_lang_item_menu_exit: sys.exit(0) # ------------------------------ФОРУМ---------------------------------- elif event == "forum": progress = self.create_window(text=core.string_lang_load_topics, param="loaddialog") Clock.schedule_once( lambda *args: self.show_sections_forum( progress, core.api.ROOT_PARTITION_FORUM), 1) # ----------------------ДОБАВИТЬ ФАЙЛ НА СЕРВЕР------------------------ elif event == "upload": self.show_upload_form() # ----------------------------СООБЩЕНИЯ-------------------------------- elif event == "mail": def _show_list_mail(*args): progress = \ self.create_window(text=core.directions[args[0][0].id][1], param="loaddialog") Clock.schedule_once( lambda *arg: self.show_list_mail(progress, args[0]), 2) # Просим авторизацию. if not self.cookie: self.create_window(text=core.string_lang_authorization_client) return # Выводим папки для просмотра и функции для манипуляции с почтой. scroll_mail = \ ScrollButton( events_callback=lambda *args: _show_list_mail(args), button_list=core.sections_mail, dismiss=True, background_image=core.theme_decorator_window) scroll_mail.show(title=core.string_lang_mail) # ----------------------------СТАТЬИ------------------------------- elif event == "articles": progress = self.create_window(text=core.string_lang_load_topics) Clock.schedule_once( lambda *args: self.show_file_details( progress, "articles"), 0.1) # ---------------------------ПЛАГИНЫ-------------------------------- elif event == core.string_lang_plugin: self.show_plugins() # ----------------------------ФАЙЛЫ--------------------------------- elif event == "files": self.show_sections_files() return True def back_screen(self): """Показываем предыдущий и удаляем из списка текущий экран.""" if len(self.screen.screen_manager.screens) != 1: self.screen.screen_manager.screens.pop() self.screen.screen_manager.current = \ self.screen.screen_manager.screen_names[-1] # Устанавливаем имя предыдущего экрана. self.screen.action_previous.title = self.screen.screen_manager.current def create_window(self, text, title=core.string_lang_title, button_ok=None, button_no=None, button_cancel=None, background=core.theme_decorator_window, param="info", callback=p, dismiss=False, size_x=CONST_SCREEN, font_size=window_text_size, password=False): window = KDialog(answer_callback=callback, base_font_size=font_size, background_image=background, size_hint_x=size_x) window.show(title=title, image="Data/Images/loading.gif", text=text, param=param, auto_dismiss=dismiss, text_button_ok=button_ok, text_button_no=button_no, text_button_cancel=button_cancel, password=password) return window def create_text_topics_or_comments(self, text_topics_or_comments, dict_info_topics_or_comments, current_number_page, number_posts, next_answers, flag): """Вызывается из класса ShowTopicsForum и ShowFileDetails для формирования текста страниц форума/комментариев/статей/описания к файлам. :param text_topics_or_comments: сырой текст страницы, полученный от сервера; :param dict_info_topics_or_comments: информация о каждом посте/комментена станице вида {"id": ["12345", ...], "author": ["name_author", ...], "date": ["12345", ...]} :type current_number_page: int; :param current_number_page: выбраная страница; :type numbers_pages_forum: int; :param numbers_pages_forum: количество страниц форума/комментариев; :type next_answers: str; :param type next_answers: "0", "20", "40", "60", ... - вывод следующей двадцатки топиков :type flag: str or None; :param flag: имя раздела, если выводим комментарии к файлу; Returns: (str, str, list): - форматированый текст модулем textmarker.py страницы форума или комментвриев; - строку, пагинатор страниц, маркированую для MarkupLabel; - список ссылок на странице, вида [('адрес_ссылки', 'имя_ссылки'),]; """ _mark_links = [] _next_answers = next_answers _list_topics_or_comments = text_topics_or_comments.split("</text>") list_topics_or_comments = [] text_topics_or_comments = "" online = "" for i, author in enumerate(dict_info_topics_or_comments["author"]): # Парсинг топика/комментария. topic_or_comment_parse, mark_links, mark_links_scr = \ self.parse_text(_list_topics_or_comments[i].decode("cp1251")) _mark_links += mark_links.items() if flag: # для комментариев _time = dict_info_topics_or_comments["date"][i] else: _time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime( int(dict_info_topics_or_comments["date"][i]))) _next_answers += 1 if not flag: # для форума try: if dict_info_topics_or_comments["online"][i] == "0": online = "|[color=#f70000]Offline[/color]|" else: online = "|[color=#00d700]Online[/color]|" except KeyError: # для комментариев online = "" # Если топик пользователя, добавляем пункт "Удалить" и # подсвечивает другим цветом ник. if author == self.user_reg["login"]: author_color = core.theme_key_text_color item_delete = "[color={}][ref=Post_id: {}]{}[/ref][/color]|" \ "".format(core.theme_link_color, dict_info_topics_or_comments["id"][i], core.string_lang_delete) else: author_color = core.theme_link_color item_delete = "" # #1 Author | online | Ответ | Копировать | Удалить # 26.01.16 10:45 # # Текст топика... topic_or_comment_parse = \ "#{} [color={author_color}][ref={author}]{author}[/ref]" \ "[/color] {}|[color={link_color}][ref={answer}-|-{author}" \ "-|-{i}]{answer}[/ref][/color]|[color={link_color}]" \ "[ref={copy}-|-{author}-|-{i}]{copy}[/ref][/color]|" \ "{delete}\n{}\n-------------\n{}\n-------------".format( str(_next_answers), online, _time, topic_or_comment_parse, author=author, answer=core.string_lang_answer, i=str(i), copy=core.string_lang_copy, delete=item_delete, author_color=author_color, link_color=core.theme_link_color) text_topics_or_comments += topic_or_comment_parse list_topics_or_comments.append(topic_or_comment_parse) # Если топиков менбше 20-ти. number_posts = 1 if not number_posts else number_posts current_number_page = 1 if not current_number_page \ else current_number_page # Список для хранения номеров страниц. list_pages = paginator(number_posts, current_number_page) # Формируем нумерацию страниц и помечаем выбраную. build_pages = "" for number_page in list_pages: try: number_page = \ int(number_page.replace("[", "").replace("]", "")) if current_number_page == number_page: color = core.theme_key_text_color else: color = core.theme_link_color except ValueError: color = core.theme_link_color build_pages += \ "[color={}][ref=Page_number: {number_page}]{number_page}" \ "[/ref] ".format(color, number_page=number_page) return text_topics_or_comments, list_topics_or_comments, \ build_pages, _mark_links def refs_callback(self, *args): """Обрабатывает события при клике на страницах корневых разделов тем форума или списка файлов.""" # Выводим следующую страницу тем форума или списка файлов. if "Page_number" in args[0]: callback_load_new_page = args[5] select_number_page = args[0].split(": ")[1] callback_load_new_page(select_number_page) return # Выбран файл из списка на экране или ссылка "Комментариев:" под ним. if not args[1]: select_name_file = args[0] self.load_file_details(None, select_name_file) return try: forum_name = args[0] # "Python" themes_id = args[1][forum_name] # "141", "1728141632" (tid, id) if len(args[2].items()): forum_id = args[2][forum_name] # "id_форума" else: forum_id = themes_id forum_flag = args[3] # "themes" or "topics" forum_id_posts = args[4] # {'1728141632': '9767', ...} self.tid_forum = forum_id # Количество ответов в форуме. try: number_posts = forum_id_posts[themes_id] except KeyError: number_posts = None if forum_flag == "topics": progress = \ self.create_window(text=core.string_lang_load_themes_answer) Clock.schedule_once(lambda *arg: self.show_topics_forum( progress, forum_name, themes_id, 0, int(number_posts) / 20, 1), 1) else: progress = \ self.create_window(text=core.string_lang_load_themes) Clock.schedule_once(lambda *arg: self.show_themes_forum( progress, forum_name, forum_flag, themes_id, core.api.THEMES_FORUM), 1) except KeyError: # Клик на ник пользователя в разделе "Последний ответ". user_name = args[0] self.send_mail_or_show_profile(user_name) def send_mail_or_show_profile(self, user_name, instance_open_mail=None): """Выводит окно с кнопками показа профиля или формы для отправки сообщения выбранного пользователя. type instance_open_mail: <class 'messageviewer.MessageViewer'>; param instance_open_mail: открытое окно с текстом просматриваемого сообщения; """ def _send_mail_or_show_profile(*args): name_button = args[0][0] # "Профиль"/"Сообщение" if name_button == core.string_lang_item_menu_profile: progress = \ self.create_window(text=core.string_lang_info_your) Clock.schedule_once(lambda *arg: self.show_user_profile( progress, user_name, instance_open_mail), 1) elif name_button == core.string_lang_write_message_status: self.send_mail(user_name) self.create_window( callback=lambda *args: _send_mail_or_show_profile(args), param="query", dismiss=True, text=core.string_lang_username.format(user_name), button_ok=core.string_lang_item_menu_profile, button_cancel=core.string_lang_write_message_status) def error_read_page(self, progress=None): if progress: progress.body.dismiss() self.create_window(text=core.string_lang_error_read_page) self.open_dialog = False def get_news(self): """Возвращает текст новостей сайта или False, если их нет.""" news = get_page(core.api.GET_NEWS, self.cookie) if not news: self.error_read_page() return news = core.dict_search_templates["name"].findall(news)[0] if news != "": return news else: if platform != "android": print("Новостей нет!") print("------------------------------------") return False def download_file(self, link_text, link_address): def download_cancel(self, *args): setattr(retrieve_progress_load, "flag", 0) progress_load.body.dismiss() path_to_folder = self.downloadfolder[self.downloadkey] if not os.path.exists(path_to_folder): os.mkdir(path_to_folder) progress_load = \ ProgressLoad(retrieve_callback=retrieve_progress_load, events_callback=download_cancel, text_button_cancel=core.string_lang_button_cancel, text_already_loaded=core.string_lang_already_loaded, text_total_size=core.string_lang_total_size) progress_load.show(link_address, "{}/{}".format(path_to_folder, os.path.split(link_address)[1])) def update_page_on_forum(self, next_answers=0, current_number_page=0, *args): # После добавления/удаления ответа в форум закрываем текущую страницу # и удаляем ее из списка экранов, чтобы с последующим вызовом # функции self.show_topics_forum была выведена обновленая # страница форума с последним ответом. name_forum = args[0] forum_id = args[1] number_posts = args[2] flag = args[3] # если None - обновляем последнюю страницу форума - # добавление нового поста, если True - текущую - удаление поста self.screen.screen_manager.screens.pop() self.screen.screen_manager.current = \ self.screen.screen_manager.screen_names[-1] progress = self.create_window(text=core.string_lang_forum_update) if not flag: # если происходит добавление поста в форум next_answers = number_posts * 20 current_number_page = number_posts if isinstance(flag, str): # раздел файлов, например "articles" flag = flag Clock.schedule_once(lambda *args: self.show_topics_forum( progress, name_forum, forum_id, next_answers, number_posts, current_number_page, flag), 1) def update_program(self): """Проверяет наличие обновлений на сервере github,com. Проверяестя версия программы, версии плагинов, наличие измененных программых файлов.""" if platform != "android": print("Проверка обновлений:") print("------------------------------------") temp_path = "{}/Data/temp".format(core.prog_path) if not os.path.exists(temp_path): os.mkdir(temp_path) update_file = urllib.urlopen( "https://github.com/HeaTTheatR/HeaTDV4A/raw/master/" "Data/uploadinfo.ini").read() open("{}/uploadinfo.ini".format(temp_path), "w").write( update_file) config_update = ConfigParser() config_update.read("{}/uploadinfo.ini".format(temp_path)) info_list_update = [] new_version_program = \ config_update.getfloat("info_update", "new_version_program") updated_files_program = \ eval(config_update.get("info_update", "updated_files_program")) dict_official_plugins_program = \ config_update.items("plugin_update") official_plugins_program = dict(dict_official_plugins_program) install_user_plugins = self.started_plugins current_version_program = __version__ if platform != "android": print("Проверка версии программы ...") print("Проверка актуальности плагинов ...") for plugin in install_user_plugins.keys(): try: info_official_plugin = eval(official_plugins_program[plugin]) if info_official_plugin[plugin]['plugin-version'] > \ install_user_plugins[plugin]['plugin-version']: info_list_update.append(info_official_plugin) if platform != "android": print("Плагин '{}' обновился до версии '{}'!".format( plugin, info_official_plugin[plugin][ 'plugin-version'])) except KeyError: continue if platform != "android": print("Проверка обновлений завершена ...") print("------------------------------------") print() if len(info_list_update) or new_version_program > \ current_version_program: self.update = True if platform != "android": print("Доступны обновления!") print("------------------------------------") print() else: if platform != "android": print("Обновлений нет!") print("------------------------------------") print() def set_password(self): """Установка данных пользователя.""" def write_password(data): _user_reg = {"login": data[0].encode("hex"), "password": data[1].encode("hex")} self.open_dialog = False # Если данные не введены. if _user_reg["login"] == "" or _user_reg["password"] == "": return else: self.config.set("General", "user_reg", _user_reg) self.config.write() self.user_reg["login"] = data[0] self.user_reg["password"] = data[1] registration_form.body.dismiss() self.Clock.schedule_once(lambda *args: self.connect(args), 0.2) self.open_dialog = True registration_form = \ self.create_window(callback=write_password, size_x=self.CONST_SCREEN, text=core.string_lang_input_password, password=True, button_ok=core.string_lang_yes, param="logpass") def parse_text(self, html_text): """Маркировка в тексте ссылок, спойлеров, программного кода. Returns: (str, dict); - отмаркерованый текст страницы; - {'адрес_ссылки': 'имя ссылки', ...}; """ def replace(text): parse_text = text.replace( "** ", "**", 1) parse_text = parse_text.replace( " **", "**", 1) parse_text = parse_text.replace( "-------------", "\n-------------\n") parse_text = parse_text.replace( "======================", "\n======================\n") parse_text = parse_text.replace( "======================", "#-----------SEPARATOR") parse_text = parse_text.replace( "============", "#-----------SEPARATOR") parse_text = parse_text.replace( "<![CDATA[", "") parse_text = parse_text.replace( "{}{}{}".format( core.mark_tag["refs"][0], core.string_lang_show_comments, core.mark_tag["refs"][1]), "-------------\n{}{}{}".format( core.mark_tag["refs"][0], core.string_lang_show_comments, core.mark_tag["refs"][1])) parse_text = parse_text.replace("\t", "").strip() return parse_text text = TextMarker(core.mark_tag["refs"], core.mark_tag["spoiler"], core.mark_tag["code"], core.mark_tag["scr"], core.language_code, html_text) text_with_mark_scr = text.mark_image(html_text.encode("utf-8")) text_with_mark_code = text.mark_code(text_with_mark_scr) text_with_mark_links = text.mark_links(text_with_mark_code) parse_message = html_parser(text_with_mark_links) text_with_mark_spoilers = text.mark_spoilers(parse_message) parse_text = replace(text_with_mark_spoilers) return parse_text, text.dict_link, text.dict_link_scr def set_screen_message_viewer(self, name_screen, text_for_screen, list_links, list_links_scr, build_pages, flag, dict_info=None, events_callback=None, load_scr=True): """Открывает новый экран MessageViewer.""" if not dict_info: dict_info = {} background = "Data/Images/background.png" list_text_button = [self.core.string_lang_answer_on_mail, self.core.string_lang_delete, self.core.string_lang_in_archive] background_code = [0.06666666666666667, 0.0784313725490196, 0.08235294117647059, 1.0] foreground_code = [0.43137254901960786, 0.49019607843137253, 0.5686274509803921, 1.0] border_code = [1.0, 0.7725490196078432, 0.09803921568627451, 1.0] message_viewer = self.MessageViewer( event_callback=events_callback, text_message=text_for_screen, load_scr=load_scr, spoilers_mark_tag=core.mark_tag["spoiler"], code_mark_tag=core.mark_tag["code"], links_mark_tag=core.mark_tag["refs"], scr_mark_tag=core.mark_tag["scr"], message_links=dict(list_links), message_links_scr=list_links_scr, forum=flag, dict_info=dict_info, list_text_button=list_text_button, background_code=background_code, foreground_code=foreground_code, border_code=border_code, size_hint=(.9, .89), number_page=build_pages, background=background, button_add_answer_background_normal="Data/Images/button_blue.png", button_add_answer_background_down="Data/Images/button_orange.png", text_button_add_answer=self.core.string_lang_add_answer_in_forum) if flag != "mail": screen = self.Screen(name=name_screen) screen.add_widget(message_viewer) self.screen.screen_manager.add_widget(screen) self.screen.screen_manager.transition = self.FadeTransition() self.screen.screen_manager.current = name_screen self.screen.action_previous.title = name_screen return message_viewer def scan_new_messages(self, interval): messages = get_page(core.api.NUMBER_UNREAD_MESS, self.cookie) if messages: total_unread_messages = \ core.dict_search_templates["unread"].findall(messages)[0] if int(total_unread_messages) > int(self.resmessages): self.resmessages = total_unread_messages self.alert_new_messages(total_unread_messages) self.config.set("General", "resmessages", total_unread_messages) self.config.write() def alert_new_messages(self, total_unread_messages): self.beep.play() self.create_window(text=core.string_lang_new_messages.format( total_unread_messages)) def show_license(self, *args): def show_license(progress, on_language): text_license = open("LICENSE/GNU_LICENSE_{}.rst".format( core.dict_language[on_language])).read() message = KDialog(underline_color="a6b4bcff", base_font_size=self.window_text_size, background_image=core.theme_decorator_window) message.show(title="GNU_LICENSE:", text=text_license, rst=True, size_rst=(.9, .7)) progress.body.dismiss() if len(args) > 1: # выбраны ссылки в тексте click_link = args[1] webbrowser.open(click_link) return else: on_language = args[0] # кнопки 'На русском/На английском' progress = self.create_window(text=core.string_lang_wait) Clock.schedule_once(lambda *args: show_license(progress, on_language),2) def show_about(self): def events_callback(instance_label, text_link): def answer_callback(answer): if answer in [core.string_lang_click_dimonvideo_redirect, core.string_lang_click_ptyhon_redirect, core.string_lang_click_kivy_redirect]: webbrowser.open(answer.replace("www.", r"http:\\")) if text_link in ["HeaTTheatR", "Virtuos86", "dimy44"]: Clock.schedule_once( lambda *args: self.send_mail_or_show_profile(text_link), 0.1) else: self.create_window( callback=answer_callback, param="query", text=core.text_for_about[text_link]["text"], button_ok=core.text_for_about[text_link]["ok"], button_cancel=core.text_for_about[text_link]["cancel"]) AboutDialog(events_callback=events_callback, background_image=core.theme_decorator_window, name_program=core.string_lang_about_name_program, logo_program="Data/Images/logo.png", info_program=core.info_program)
class cBaseScript(object): ''' basic script class to inherit all scrpts from ''' def __init__(self): self.bIsInit = False self.uMyPath = u'' self.uScriptName = u'' self.uScriptFile = u'' self.iMyVersion = ToIntVersion('1.0.0') self.fOrcaVersion = ToIntVersion('1.0.0') self.uType = u'Generic' self.uSubType = u'Generic' self.aScriptIniSettings = QueryDict() self.oConfigParser = KivyConfigParser() self.uDefaultConfigName = "" self.uConfigFileName = "" self.uSection = "" def RunScript(self, args): ''' Dummy ''' pass def Init(self,oParORCA,uScriptName,uScriptFile): ''' Initializes the script ''' self.bIsInit = True self.uScriptName = uScriptName self.uScriptFile = uScriptFile self.uDefaultConfigName = uScriptName self.uMyPath = AdjustPathToOs(oORCA.uScriptsPath+'/'+self.uScriptName) if not os.path.exists(self.uMyPath): CreateDir(self.uMyPath) oORCA.oTheScreen.oLanguage.LoadXmlFile("SCRIPT", uScriptName) self.uConfigFileName = AdjustPathToOs(self.uMyPath+u'/config.ini') oRepManagerEntry=cRepManagerEntry() oRepManagerEntry.uFileName=uScriptFile if oRepManagerEntry.ParseFromSourceFile(): self.iMyVersion = oRepManagerEntry.oRepEntry.iVersion self.fOrcaVersion = oRepManagerEntry.oRepEntry.iMinOrcaVersion #OrcaVersion defines for what Orca Version the Interface has been developed self.ShowDebug(u'Init') if not FileExists(self.uConfigFileName): self.CreateAndInitializeIniFile() oRepManagerEntry=cRepManagerEntry() oRepManagerEntry.uFileName=uScriptFile if oRepManagerEntry.ParseFromSourceFile(): self.iMyVersion = oRepManagerEntry.oRepEntry.iVersion self.fOrcaVersion = oRepManagerEntry.oRepEntry.iMinOrcaVersion #OrcaVersion defines for what Orca Version the Script has been developed self.ReadConfigFromIniFile(self.uDefaultConfigName) def InitializeSection(self,uSection): ''' Initializes a section in the config.ini file for the script ''' self.ReadConfigFromIniFile(uSection) def CreateAndInitializeIniFile(self): ''' Creates the ini file ''' self.oConfigParser.add_section(self.uDefaultConfigName) self.InitializeSection(self.uDefaultConfigName) self.oConfigParser.write() def LoadConfig(self): ''' loads a config from the ini file ''' self.oConfigParser.filename=self.uConfigFileName if len(self.oConfigParser._sections)==0: if FileExists(self.uConfigFileName): self.ShowDebug(u'Reading Config File') self.oConfigParser.read(self.uConfigFileName) def GetConfigJSONStringforSection(self,uSection): ''' dummy ''' return u'{}' def ReadConfigFromIniFile(self,uConfigName): ''' reads a config from the ini file ''' self.uSection = uConfigName try: SetVar('ScriptConfigSection',uConfigName) self.LoadConfig() oIniDef = json.loads(self.GetConfigJSONStringforSection(uConfigName)) for oLine in oIniDef: uType = oLine.get("type") uKey = oLine.get("key") uDefault = oLine.get("default") if uType == "scrolloptions" or uType == "string": uPre = "u" + uKey self.aScriptIniSettings[uPre]=Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault) elif uType == "numeric" or uType == "numericslider": uPre= "i" + uKey self.aScriptIniSettings[uPre]=ToInt(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault)) elif uType == "numericfloat" : uPre= "f" + uKey self.aScriptIniSettings[uPre]=ToFloat(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault)) elif uType == "bool": uPre = "b" + uKey self.aScriptIniSettings[uPre]=ToBool(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault)) elif uType == "title": pass else: self.ShowError(u'Cannot read config name (base), wrong attribute:'+self.uConfigFileName + u' Section:'+self.uSection+" " +oLine["type"]) except Exception as e: self.ShowError(u'Cannot read config name (base):'+self.uConfigFileName + u' Section:'+self.uSection,e) return def DeInit(self): ''' deinitializes the ini file ''' self.ShowDebug(u'DeInit') def OnPause(self): ''' called by system, if the device goes on pause ''' self.ShowInfo(u'OnPause') def OnResume(self): ''' called by system, if the device resumes ''' self.ShowInfo(u'OnResume') def ShowWarning(self,uMsg): ''' creates a warning debug line ''' uRet=u'Script '+self.uScriptName+u': '+ uMsg Logger.warning (uRet) return uRet def ShowDebug(self,uMsg): ''' creates a debug line ''' uRet=u'Script '+self.uScriptName+u': '+ uMsg Logger.debug (uRet) return uRet def ShowInfo(self,uMsg): ''' creates a info debug line ''' uRet=u'Script '+self.uScriptName+u': '+ uMsg Logger.info (uRet) return uRet def ShowError(self,uMsg,oException=None): ''' creates a error debug line ''' iErrNo = 0 if oException!=None: if hasattr(oException,'errno'): iErrNo=oException.errno if iErrNo is None: iErrNo=12345 uRet=LogErrorSmall (u'Script '+self.uScriptName+u': '+ uMsg + " (%d) " % (iErrNo),oException) return uRet def _ReadConfig(self): ''' reads the config for the settings dialog ''' oConfig = KivyConfigParser() oConfig.read(self.uConfigFileName) return oConfig def ConfigScriptSettings(self,oScriptSetting): ''' for here we need a separate config object ''' self.oConfigParser=self._ReadConfig() oScriptSetting.register_type('buttons' , SettingButtons) oScriptSetting.register_type('numericslider' , SettingNumericSlider) oScriptSetting.register_type('numericfloat' , SettingNumeric) oScriptSetting.register_type('scrolloptions' , SettingScrollOptions) SetVar('ScriptConfigSection',self.uDefaultConfigName) uSettingsJSON=self.GetConfigJSONStringforSection(self.uDefaultConfigName) self.ReadConfigFromIniFile(self.uDefaultConfigName) if uSettingsJSON==u'{}': return self.On_SettingsClose(None) uSettingsJSON=ReplaceVars(uSettingsJSON) oScriptSetting.add_json_panel(self.uDefaultConfigName,self.oConfigParser, data=uSettingsJSON) oScriptSetting.bind(on_close=self.On_SettingsClose) return oScriptSetting def On_SettingsClose(self,instance): ''' Dispatched when the user closes the settings dialog ''' oORCA.DispatchSystemKey('buttonclosesetting_script') return True def ShowSettings(self): ''' shows the settings dialog ''' oORCA.oTheScreen.AddActionToQueue([{'string':'updatewidget','widgetname':'Scriptsettings'}])
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=(',', ': '))
from kivy.factory import Factory from kivy.app import App from kivy.properties import StringProperty from kivy.lang import Builder import csv import os import json app = App.get_running_app() from kivy.config import ConfigParser config = ConfigParser() config.read('myconfig.ini') config.adddefaultsection('pycon2018') config.setdefault('pycon2018', 'register_data_dir', 'data') class ScreenRegister(Factory.Screen): _data = {} '''Holds the data in :attr:`data_file_dir` was processed or not. :attr:`_data` is a :type:`String`, defaults to False. ''' data_file_dir = StringProperty(config.get( 'pycon2018', 'register_data_dir')) '''This is the data dir where the registeration data is stored. All csv files should be present in this folder.
#################### CREDITS AND CONTRIBUTORS ######################## Credits = '''Lithid, TommyTomatoe, GNU/Linux, bruit.all, jesusfreke, Emmanuel Dupuy, Panxiaobo, Google, AOSP, Open Handset Alliance''' # People who have made donations to the project # TODO change list to $10+ only make to the list # If donations list becomes too large Donors = '''Neil Faulkner, Ryan Lincoln, Jose Barrios,\nWard Seabrook, WiLL Morehead, Kenneth Soares''' ######################## Other ###################################### config = ConfigParser() config.read('%s/eds.ini' % Usr) # Custom Button Is a global button defined in eds.kv file # All buttons Should be CustomButton not Button # This will make themes work when themeing eds.kv class CustomButton(Button): pass ####################### GLOBAL FUNCTIONS ############################ # Makes EDS_WORKING dir to hold all users files def mkworking(self): if os.path.exists(EdsWorking) == False: try: os.mkdir(EdsWorking) os.mkdir(Rom)
from Libs.paginator import paginator except Exception: raise Exception(traceback.format_exc()) __version__ = "0.01" if callable(platform): platform = platform() if not os.path.exists("{}/program.ini".format(core.prog_path)) or open( "{}/program.ini".format(core.prog_path)).read() == "": language = "russian" else: config = ConfigParser() config.read("{}/program.ini".format(core.prog_path)) language = core.select_locale[config.get("General", "language")] del config def p(*args): pass class Program(App, prog_class.ShowPlugin, prog_class.ShowThemesForum, prog_class.ShowSectionsForum, prog_class.ShowSendMailForm, prog_class.ShowTopicsForum, prog_class.ShowListMail, prog_class.ShowFileDetails, prog_class.ShowUploadForm, prog_class.ShowFiles, prog_class.ShowUserProfile, ConnectionToServer):
class PlatformApp(App): title = '' icon = 'images/4_pointd.png' use_kivy_settings = False def settings(self, instance): # settings panel if instance.pos[0] == 0: self.btnal.pos = (self.zoom[0], height-self.zoom[1]*1.5) self.btnal.text = '<' self.parent.add_widget(self.ui.al) elif instance.pos[0] == self.zoom[0]: self.btnal.pos = (0, height-self.zoom[1]*1.5) self.btnal.text = '>' self.parent.remove_widget(self.ui.al) def color_choose(self, instance): # colours/tile panel if instance.pos[0] == width-self.zoom[0]/2: self.btnar.pos = (width-self.zoom[0]*1.5, height-self.zoom[1]*1.5) self.btnar.text = '>' self.parent.add_widget(self.ui.ar) elif instance.pos[0] == width-self.zoom[0]*1.5: self.btnar.pos = (width-self.zoom[0]/2, height-self.zoom[1]*1.5) self.btnar.text = '<' self.parent.remove_widget(self.ui.ar) self.ui.ar.clear_widgets() self.ui.ar.add_widget(self.ui.ac) self.grid.refresh_screen() def build(self): self.config = ConfigParser() self.config.read(self.directory + '/' + 'config.ini') self.parent = Widget() self.parent.canvas.clear() self.parent.canvas.add(Color(0, 0, 0)) self.parent.canvas.add(Rectangle(size=(width, height))) self.grid = Platform_draw() self.ui = UI() self.grid.ui = self.ui self.ui.grid = self.grid try: zoom = int(self.config.get('platform', 'zoom')) self.grid.zoom = (zoom, zoom) except: self.grid.zoom = (height/12, height/12) try: gridR = int(self.config.get('colors', 'r')) except: gridR = 0 try: gridG = int(self.config.get('colors', 'g')) except: gridG = 0 try: gridB = int(self.config.get('colors', 'b')) except: gridB = 1 self.grid.gridColor = (gridR/255.0, gridG/255.0, gridB/255.0) self.grid.directory = self.directory self.grid.upper = self self.ui.upper = self self.grid.on_startup() self.ui.on_startup() self.grid.lat, self.grid.longit, self.grid.lines = set_zoom([], self.grid.zoom) self.zoom = self.grid.size #adds the main classes self.parent.add_widget(self.grid) self.parent.add_widget(self.ui) # creates buttons self.btnar = Button(text = '<', pos = (width-self.zoom[0]/2, height-self.zoom[1]*1.5), size=(self.zoom[0]/2, self.zoom[1])) self.btnal = Button(text = '>', pos = (0, height-self.zoom[1]*1.5), size=(self.zoom[0]/2, self.zoom[1])) self.zoom_slider = Slider(orientation = 'horizontal', size = (width - height/3, height/12), pos = (height/6, height-height/12), max = height/6, min = 20, value = self.zoom[1], step = 1) # gives grid a referance to the zoom slider, (for loading) self.grid.zoom_slider = self.zoom_slider self.btnal.bind(on_release = self.settings) self.btnar.bind(on_release = self.color_choose) self.zoom_slider.bind(on_touch_move = self.ui.value_zoom) # adds buttons to screen self.parent.add_widget(self.btnal) self.parent.add_widget(self.btnar) self.parent.add_widget(self.zoom_slider) return self.parent def build_settings(self, settings): settings.add_json_panel('Defaults', self.config, self.directory + '/' + 'settings.json') def on_config_change(self, config, section, key, value): if config is self.config: token = (section, key) if token == ('platform', 'zoom'): new_zoom = (int(value), int(value)) self.grid.lat, self.grid.longit, self.grid.lines = set_zoom(self.grid.lines, new_zoom, self.grid.zoom, self.grid.lat, self.grid.longit) self.grid.zoom = (float(value), float(value)) self.zoom_slider.value = float(value) elif token[0] == 'colors': try: gridR = int(self.config.get('colors', 'r')) except: gridR = 0 try: gridG = int(self.config.get('colors', 'g')) except: gridG = 0 try: gridB = int(self.config.get('colors', 'b')) except: gridB = 1 self.grid.gridColor = (gridR/255.0, gridG/255.0, gridB/255.0) # try: # backR = int(self.config.get('colors', 'rb')) # except: # backR = 0 # try: # backG = int(self.config.get('colors', 'gb')) # except: # back = 0 # try: # backB = int(self.config.get('colors', 'bb')) # except: # backB = 0 # self.parent.canvas.add(Color(backR/255.0, backG/255.0, backB/255.0)) self.grid.refresh_screen()
if PY2: select_locale = {u'Русский': 'russian', 'English': 'english'} else: select_locale = {'Русский': 'russian', 'English': 'english'} prog_path = os.path.split(os.path.abspath(sys.argv[0]))[0] # Если файл настроек отсутствует. if not os.path.exists('{}/program.ini'.format(prog_path)) \ or open('{}/program.ini'.format(prog_path)).read() == '': language = 'russian' theme = 'default' else: config = ConfigParser() config.read('{}/program.ini'.format(prog_path)) theme = config.get('General', 'theme') language = select_locale[config.get('General', 'language')] # языковая локализация # -----------------------УСТАНОВКА ЦВЕТОВОЙ ТЕМЫ--------------------------- config_theme = ConfigParser() config_theme.read("{}/Data/Themes/{theme}/{theme}.ini".format( prog_path, theme=theme)) color_action_bar = eval(config_theme.get("color", "color_action_bar")) color_body_program = eval(config_theme.get("color", "color_body_program")) color_tabbed_panel = eval(config_theme.get("color", "color_tabbed_panel")) separator_color = eval(config_theme.get("color", "separator_color")) background_locations = eval(config_theme.get("color", "background_locations")) theme_text_color = config_theme.get("color", "text_color")
class UserPrefs(EventDispatcher): _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): self._prefs_dict["range_alerts"][key] = range_alert self._schedule_save() def get_range_alert(self, key, default=None): return self._prefs_dict["range_alerts"].get(key, default) def set_gauge_config(self, gauge_id, channel): self._prefs_dict["gauge_settings"][gauge_id] = channel self._schedule_save() def get_gauge_config(self, gauge_id): return self._prefs_dict["gauge_settings"].get(gauge_id, False) def save(self, *largs): with open(self.prefs_file, 'w+') as prefs_file: data = self.to_json() prefs_file.write(data) def set_config_defaults(self): 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', 'first_time_setup', True) self.config.setdefault('preferences', 'send_telemetry', False) self.config.setdefault('preferences', 'last_dash_screen', 'gaugeView') def load(self): print("the data dir " + 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(self, section, option): return self.config.get(section, option) def set_pref(self, section, option, value): self.config.set(section, option, value) self.config.write() def to_json(self): 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)
def _ReadConfig(self): ''' reads the config for the settings dialog ''' oConfig = KivyConfigParser() oConfig.read(self.uConfigFileName) return oConfig
import time import datetime import json # =========================== # Control The Backlight # =========================== def Backlight_Control(light_status): subproces.call('echo 0 > Light.SATUS') # ======================== # Load the Defaults # ======================== config = ConfigParser() config.read('doorbell.ini') CODES = ConfigParser() CODES.read('codes.ini') CODES_DICT = {s:dict(CODES.items(s)) for s in CODES.sections()} NUMBERS = ConfigParser() NUMBERS.read('numbers.ini') NUMBERS_DICT = {s:dict(NUMBERS.items(s)) for s in NUMBERS.sections()} LANGUAGES = ConfigParser() LANGUAGES.read('languages.ini') LANGUAGES_DICT = {s:dict(LANGUAGES.items(s)) for s in LANGUAGES.sections()} # ===========================
class NuBippyApp(App): """ The application Class for Bippy """ def __init__(self, **kwargs): super(NuBippyApp, self).__init__(**kwargs) self.isPopup = False self.show_info = False self.use_kivy_settings = False # load config file # we don't display the settings panel, changes can be made manually to the ini file self.config = ConfigParser() self.config.read('nubippy.ini') # Set the language and load the language file self.language = self.config.get('Language', 'active_language') try: self.lang = json.load(open('res/json/languages/' + self.language + '.json', 'r')) except ValueError as e: print('') print('##################################################################') print('') print('There was an Error loading the ' + self.language + ' language file.') print('') print(str(e)) print('') print('##################################################################') raise SystemExit return def build(self): """ Build the Main Application Window """ # Root widget is a Box Layout self.root = BoxLayout(orientation='vertical') self.infoText = TextInput(readonly=True) self.mainScreenManager = ScreenManager(transition=SlideTransition(direction='left')) # Add the Action Bar self.topActionBar = TopActionBar() self.root.add_widget(self.topActionBar) # Add the Scroll View For displaying Info self.infoScrollView = ScrollView(size_hint_y=None, height=0, border=1) self.infoScrollView.add_widget(self.infoText) self.root.add_widget(self.infoScrollView) #Add the screenManager Builder.load_file('screens/HomeScreen.kv') self.homeScreen = HomeScreen.HomeScreen(self) Builder.load_file('screens/PrivateKeyScreen.kv') self.privateKeyScreen = PrivateKeyScreen.PrivateKeyScreen(self) Builder.load_file('screens/VanityScreen.kv') self.vanityScreen = VanityScreen.VanityScreen(self) Builder.load_file('screens/ResultsScreen.kv') self.resultsScreen = ResultsScreen.ResultsScreen(self) NuBippyApp.mainScreenManager.add_widget(self.homeScreen) NuBippyApp.mainScreenManager.add_widget(self.privateKeyScreen) NuBippyApp.mainScreenManager.add_widget(self.vanityScreen) NuBippyApp.mainScreenManager.add_widget(self.resultsScreen) self.root.add_widget(NuBippyApp.mainScreenManager) return self.root def set_info(self, info): """ Read the info from the <language>.json file and set it as the info text """ self.infoText.text = NuBippyApp.get_string(info) return def toggle_info(self): """ This method toggles the visibility of the 'info' space It also handles the transition animation of the opening and closing """ self.show_info = not self.show_info if self.show_info: height = self.root.height * .3 else: height = 0 Animation(height=height, d=.3, t='out_quart').start(self.infoScrollView) self.topActionBar.infoButton.state = 'normal' def get_currency_code(self, currencyLongName): """ For the given currency long name return the currency abbreviation """ for cur in self.currencies: if cur['longName'] == currencyLongName: return cur['currency'] def reset_ui(self): """ reset the UI to it's original state this is called when the home screen is selected """ self.privateKeyScreen.reset_ui(None) self.vanityScreen.reset_ui(None) return def show_popup(self, title, text): """ display a modal popup. used for error display """ content = BoxLayout(orientation='vertical') content.add_widget(Label(text=text, size_hint=(1, .7))) button = Button(text=self.get_string('OK'), size_hint=(1, .3)) content.add_widget(button) self.popup = Popup(title=title, content=content, auto_dismiss=False, size_hint=(None, None), size=(500, 200)) button.bind(on_press=self.close_popup) self.popup.open() self.isPopup = True return def close_popup(self, instance, value=False): """ Close the warning popup """ self.popup.dismiss() self.isPopup = False return def get_string(self, text): """ return the value for the provided string from the language json file """ try: return_string = self.lang[text] except (ValueError, KeyError): return_string = 'Language Error' return return_string def open_settings(*args): """ override to disable F1 settings panel """ pass
def update_program(self): """Проверяет наличие обновлений на сервере github,com. Проверяестя версия программы, версии плагинов, наличие измененных программых файлов.""" if platform != "android": print("Проверка обновлений:") print("------------------------------------") temp_path = "{}/Data/temp".format(core.prog_path) if not os.path.exists(temp_path): os.mkdir(temp_path) update_file = urllib.urlopen( "https://github.com/HeaTTheatR/HeaTDV4A/raw/master/" "Data/uploadinfo.ini").read() open("{}/uploadinfo.ini".format(temp_path), "w").write( update_file) config_update = ConfigParser() config_update.read("{}/uploadinfo.ini".format(temp_path)) info_list_update = [] new_version_program = \ config_update.getfloat("info_update", "new_version_program") updated_files_program = \ eval(config_update.get("info_update", "updated_files_program")) dict_official_plugins_program = \ config_update.items("plugin_update") official_plugins_program = dict(dict_official_plugins_program) install_user_plugins = self.started_plugins current_version_program = __version__ if platform != "android": print("Проверка версии программы ...") print("Проверка актуальности плагинов ...") for plugin in install_user_plugins.keys(): try: info_official_plugin = eval(official_plugins_program[plugin]) if info_official_plugin[plugin]['plugin-version'] > \ install_user_plugins[plugin]['plugin-version']: info_list_update.append(info_official_plugin) if platform != "android": print("Плагин '{}' обновился до версии '{}'!".format( plugin, info_official_plugin[plugin][ 'plugin-version'])) except KeyError: continue if platform != "android": print("Проверка обновлений завершена ...") print("------------------------------------") print() if len(info_list_update) or new_version_program > \ current_version_program: self.update = True if platform != "android": print("Доступны обновления!") print("------------------------------------") print() else: if platform != "android": print("Обновлений нет!") print("------------------------------------") print()
from sys import platform from kivy.config import ConfigParser from kivy.event import EventDispatcher from kivy.logger import Logger from kivy.metrics import cm from kivy.properties import NumericProperty, ReferenceListProperty, BooleanProperty from kivy.resources import resource_add_path 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)
class DesignerSettings(Settings): """Subclass of :class:`kivy.uix.settings.Settings` responsible for showing settings of Kivy Designer. """ config_parser = ObjectProperty(None) """Config Parser for this class. Instance of :class:`kivy.config.ConfigParser` """ def __init__(self, **kwargs): super(DesignerSettings, self).__init__(*kwargs) self.register_type("list", SettingList) self.register_type("shortcut", SettingShortcut) def load_settings(self): """This function loads project settings """ self.config_parser = ConfigParser(name="DesignerSettings") DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME) _dir = os.path.dirname(designer.__file__) _dir = os.path.split(_dir)[0] DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME) if not os.path.exists(DESIGNER_CONFIG): shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG) self.config_parser.read(DESIGNER_CONFIG) self.config_parser.upgrade(DEFAULT_CONFIG) # creates a panel before insert it to update code input theme list panel = self.create_json_panel( "Kivy Designer Settings", self.config_parser, os.path.join(_dir, "designer", "settings", "designer_settings.json"), ) uid = panel.uid if self.interface is not None: self.interface.add_panel(panel, "Kivy Designer Settings", uid) # loads available themes for child in panel.children: if child.id == "code_input_theme_options": child.items = styles.get_all_styles() # tries to find python and buildozer path if it's not defined path = self.config_parser.getdefault("global", "python_shell_path", "") if path.strip() == "": self.config_parser.set("global", "python_shell_path", sys.executable) self.config_parser.write() buildozer_path = self.config_parser.getdefault("buildozer", "buildozer_path", "") if buildozer_path.strip() == "": buildozer_path = find_executable("buildozer") if buildozer_path: self.config_parser.set("buildozer", "buildozer_path", buildozer_path) self.config_parser.write() self.add_json_panel( "Buildozer", self.config_parser, os.path.join(_dir, "designer", "settings", "buildozer_settings.json") ) self.add_json_panel( "Hanga", self.config_parser, os.path.join(_dir, "designer", "settings", "hanga_settings.json") ) self.add_json_panel( "Keyboard Shortcuts", self.config_parser, os.path.join(_dir, "designer", "settings", "shortcuts.json") ) def on_config_change(self, *args): """This function is default handler of on_config_change event. """ self.config_parser.write() super(DesignerSettings, self).on_config_change(*args)