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()
class AddCardMenuScreen(Screen): question = "" answer = "" def __init__(self): Screen.__init__(self) self.name = "add" self.config = ConfigParser() self.config.add_section("add") self.config.set("add", "question", "Question") self.config.set("add", "answer", "Answer") self.config.set("add", "make", "action") self.config.add_callback(self.update_qa, section="add", key="question") self.config.add_callback(self.update_qa, section="add", key="answer") self.menu = SettingsWithNoMenu() self.menu.register_type("action", FlashcardAppManager.SettingDoAction) self.menu.add_json_panel("Add a card", self.config, os.path.join(os.path.dirname(__file__), 'add_menu.json')) self.add_widget(self.menu) def update_qa(self, *args): FlashcardAppManager.AddCardMenuScreen.question = self.config.get('add', 'question') FlashcardAppManager.AddCardMenuScreen.answer = self.config.get('add', 'answer')
class EditCardMenuScreen(Screen): question = "" answer = "" nquestion = "" nanswer = "" EditCardMenuConfig = None def update_qa(self, *args): FlashcardAppManager.EditCardMenuScreen.nquestion = self.config.get('edit', 'nquestion') FlashcardAppManager.EditCardMenuScreen.nanswer = self.config.get("edit", "nanswer") def __init__(self): Screen.__init__(self) self.name = "edit" self.config = ConfigParser() self.config.add_section("edit") self.config.set("edit", "question", "Question") self.config.set("edit", "answer", "Answer") self.config.set("edit", "nquestion", "Question") self.config.set("edit", "nanswer", "Answer") self.config.set("edit", "edit", "action") FlashcardAppManager.EditCardMenuScreen.question = self.config.get('edit', 'question') FlashcardAppManager.EditCardMenuScreen.answer = self.config.get('edit', 'answer') FlashcardAppManager.EditCardMenuScreen.nquestion = self.config.get('edit', 'nquestion') FlashcardAppManager.EditCardMenuScreen.nanswer = self.config.get('edit', 'nanswer') self.config.add_callback(self.update_qa, section="edit", key="nquestion") self.config.add_callback(self.update_qa, section="edit", key="nanswer") self.menu = SettingsWithNoMenu() self.menu.register_type("action", FlashcardAppManager.SettingDoAction) self.menu.add_json_panel("Add a card", self.config, os.path.join(os.path.dirname(__file__), 'edit_menu.json')) FlashcardAppManager.EditCardMenuScreen.EditCardMenuConfig = self.config self.add_widget(self.menu) def on_pre_enter(self, *args): FlashcardAppManager.EditCardMenuScreen.question = FlashcardAppManager.deck_widget.deck.get_selected().get_question() FlashcardAppManager.EditCardMenuScreen.answer = FlashcardAppManager.deck_widget.deck.get_selected().get_answer() self.config.set("edit", "question", FlashcardAppManager.EditCardMenuScreen.question) self.config.set("edit", "answer", FlashcardAppManager.EditCardMenuScreen.answer)
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 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 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 Config_GetDefault_Str(*, oConfig: ConfigParser, uSection: str, uOption: str, vDefaultValue: Union[None, bool, str]) -> str: """ Replacement for the kivy function :param oConfig: The configparser object :param uSection: The name of the section :param uOption: The name of the option :param vDefaultValue: The default value :return: The value of an ini setting or the default value """ uDefaultValue: str = u"" if not oConfig.has_section(uSection): oConfig.add_section(uSection) if not oConfig.has_option(uSection, uOption): if vDefaultValue is not None: if type(vDefaultValue) == bool: if vDefaultValue: uDefaultValue: str = u'1' else: uDefaultValue: str = u'0' else: uDefaultValue = vDefaultValue oConfig.set(uSection, uOption, uDefaultValue) return uDefaultValue uRetVal: str = ToUnicode(oConfig.get(uSection, uOption)) return uRetVal
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 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 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 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 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()
def test_build_config(self): config = ConfigParser() self.app.build_config(config) for section, values in DEFAULT_SETTINGS.items(): for k, v in values.items(): if isinstance(v, int): assert config.getboolean(section, k) == v elif isinstance(v, str): assert config.get(section, k) == v else: assert False, "un cas est manquant"
def 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)
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 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())
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 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)
def _create_sub_popup(self, instance, loc): content = BoxLayout(orientation='vertical', spacing='5dp', size_hint_y=None, height=500) content.bind(minimum_height=content.setter('height')) self.popup = popup = ScrollablePopup() 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 option in sorted(self.options): state = 'down' if option in self.value and option in fav_list else 'normal' btn = ToggleButton(text=option, state=state, size_hint_y=None, height=50) self.buttons.append(btn) for subloc in loc.sublocations: if btn.text == loc.name + '_' + subloc: content.add_widget(btn) popup.scroll_lay.add_widget(content) box = BoxLayout(size_hint_y=None, height=dp(50), pos_hint={ 'y': 0, 'x': 0 }) popup.button_lay.add_widget(box) btn = Button(text='Done', size_hint_y=None, height=dp(50)) btn.bind(on_release=self._set_options) box.add_widget(btn) btn = Button(text='Cancel', size_hint_y=None, height=dp(50)) btn.bind(on_release=self._dismiss) box.add_widget(btn) popup.open()
class FoodOptionsApp(App): def __init__(self, **kvargs): super(FoodOptionsApp, self).__init__(**kvargs) self.config = ConfigParser() def build_config(self, config): config.adddefaultsection('General') config.setdefault('General', 'user_data', '{}') def set_value_from_config(self): self.config.read(os.path.join(self.directory, '%(appname)s.ini')) self.user_data = ast.literal_eval(self.config.get( 'General', 'user_data')) def get_application_config(self): return super(FoodOptionsApp, self).get_application_config( '{}/%(appname)s.ini'.format(self.directory)) def build(self): return sm
class MenuScreen(Screen): def __init__(self): Screen.__init__(self) self.name = 'menu' self.config = ConfigParser() self.config.add_section("deck") self.config.add_section("card") self.config.adddefaultsection("menu") self.config.set("deck", "start_studying", 1) self.config.set("deck", "change_deck_mode", "Normal") self.config.set("deck", "show_list", True) self.config.set("deck", "undo", True) self.config.set("deck", "redo", True) self.config.set("card", "add", "") self.config.set("card", "edit", True) self.config.set("card", "remove", True) self.config.add_callback(self.check_deck_locks, "deck", "redo") self.config.add_callback(self.check_deck_locks, "deck", "undo") self.config.add_callback(self.check_card_locks, "card", "edit") self.config.add_callback(self.check_card_locks, "card", "add") self.menu = SettingsWithNoMenu() self.menu.register_type("screen", FlashcardAppManager.SettingNewScreen) self.menu.register_type("action", FlashcardAppManager.SettingDoAction) self.menu.add_json_panel("Flashcards", self.config, os.path.join(os.path.dirname(__file__), 'menu.json')) self.add_widget(self.menu) def check_deck_locks(self, section, key, value): print(self.config.get(section, key)) def check_card_locks(self, section, key, value): print()
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()} # =========================== # Load the Sound Effects # =========================== Sound_Click = SoundLoader.load(config.get('Sounds','Sound_Click')) Sound_Delete = SoundLoader.load(config.get('Sounds','Sound_Delete')) Sound_Error = SoundLoader.load(config.get('Sounds','Sound_Error')) Sound_Door = SoundLoader.load(config.get('Sounds','Sound_Door')) Sound_RingerButton = SoundLoader.load(config.get('Sounds','Sound_RingerButton')) Sound_Ringer = SoundLoader.load(config.get('Sounds','Sound_Ringer')) Sound_Code = SoundLoader.load(config.get('Sounds','Sound_Code')) Sound_System = SoundLoader.load(config.get('Sounds','Sound_System')) Sound_Settings = SoundLoader.load(config.get('Sounds','Sound_Settings')) # =======================
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)): if PY2: language = u'Русский' else: language = 'Русский' theme = 'default' else: config = ConfigParser() config.read('{}/program.ini'.format(prog_path)) theme = config.get('General', 'theme') language = config.get('General', 'language') # языковая локализация old_language = language language = select_locale[language] # -----------------------УСТАНОВКА ЦВЕТОВОЙ ТЕМЫ--------------------------- config_theme = ConfigParser() config_theme.read('{}/data/themes/{theme}/{theme}.ini'.format( prog_path, theme=theme)) alpha = \ get_color_from_hex(config_theme.get('color', 'alpha')) color_action_bar = \ get_color_from_hex(config_theme.get('color', 'color_action_bar'))
class spacebook(MDApp): title = 'spacebook' icon = 'data/images/icon.png' nav_drawer = ObjectProperty() lang = StringProperty('en') def __init__(self, **kvargs): super(spacebook, self).__init__(**kvargs) Window.bind(on_keyboard=self.events_program) Window.soft_input_mode = 'below_target' self.list_previous_screens = ['base'] self.window = Window self.config = ConfigParser() self.manager = None self.window_language = None self.exit_interval = False self.dict_language = literal_eval( open( os.path.join(self.directory, 'data', 'locales', 'locales.txt')).read() ) self.translation = Translation( self.lang, 'Ttest', os.path.join(self.directory, 'data', 'locales') ) def get_application_config(self): return super(spacebook, self).get_application_config( '{}/%(appname)s.ini'.format(self.directory)) def build_config(self, config): config.adddefaultsection('General') config.setdefault('General', 'language', 'en') def set_value_from_config(self): self.config.read(os.path.join(self.directory, 'spacebook.ini')) self.lang = self.config.get('General', 'language') def build(self): self.set_value_from_config() self.load_all_kv_files(os.path.join(self.directory, 'libs', 'uix', 'kv')) self.screen = StartScreen() self.manager = self.screen.ids.manager self.nav_drawer = self.screen.ids.nav_drawer return self.screen def load_all_kv_files(self, directory_kv_files): for kv_file in os.listdir(directory_kv_files): kv_file = os.path.join(directory_kv_files, kv_file) if os.path.isfile(kv_file): if not PY2: with open(kv_file, encoding='utf-8') as kv: Builder.load_string(kv.read()) else: Builder.load_file(kv_file) def events_program(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.nav_drawer.state == 'open': self.nav_drawer.set_state("toggle") self.back_screen(event=keyboard) elif keyboard in (282, 319): pass return True def back_screen(self, event=None): if event in (1001, 27): if self.manager.current == 'base': self.dialog_exit() return try: self.manager.current = self.list_previous_screens.pop() except: self.manager.current = 'base' self.screen.ids.action_bar.title = self.title self.screen.ids.action_bar.left_action_items = \ [['menu', lambda x: self.nav_drawer.set_state("toggle")]] def show_about(self, *args): self.nav_drawer.set_state("toggle") self.screen.ids.about.ids.label.text = \ self.translation._( u'[size=20][b]spacebook[/b][/size]\n\n' u'[b]Version:[/b] {version}\n' u'[b]License:[/b] MIT\n\n' u'[size=20][b]Developer[/b][/size]\n\n' u'[ref=SITE_PROJECT]' u'[color={link_color}]NAME_AUTHOR[/color][/ref]\n\n' u'[b]Source code:[/b] ' u'[ref=REPO_PROJECT]' u'[color={link_color}]GitHub[/color][/ref]').format( version=__version__, link_color=get_hex_from_color(self.theme_cls.primary_color) ) self.manager.current = 'about' self.screen.ids.action_bar.left_action_items = \ [['chevron-left', lambda x: self.back_screen(27)]] def show_license(self, *args): self.nav_drawer.set_state("toggle") if not PY2: self.screen.ids.license.ids.text_license.text = \ self.translation._('%s') % open( os.path.join(self.directory, 'LICENSE'), encoding='utf-8').read() else: self.screen.ids.license.ids.text_license.text = \ self.translation._('%s') % open( os.path.join(self.directory, 'LICENSE')).read() self.manager.current = 'license' self.screen.ids.action_bar.left_action_items = \ [['chevron-left', lambda x: self.back_screen(27)]] self.screen.ids.action_bar.title = \ self.translation._('MIT LICENSE') def select_locale(self, *args): def select_locale(name_locale): for locale in self.dict_language.keys(): if name_locale == self.dict_language[locale]: self.lang = locale self.config.set('General', 'language', self.lang) self.config.write() dict_info_locales = {} for locale in self.dict_language.keys(): dict_info_locales[self.dict_language[locale]] = \ ['locale', locale == self.lang] if not self.window_language: self.window_language = card( Lists( dict_items=dict_info_locales, events_callback=select_locale, flag='one_select_check' ), size=(.85, .55) ) self.window_language.open() def dialog_exit(self): def check_interval_press(interval): self.exit_interval += interval if self.exit_interval > 5: self.exit_interval = False Clock.unschedule(check_interval_press) if self.exit_interval: sys.exit(0) Clock.schedule_interval(check_interval_press, 1) toast(self.translation._('Press Back to Exit')) def on_lang(self, instance, lang): self.translation.switch_lang(lang)
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") theme_text_black_color = config_theme.get("color", "text_black_color")
class FileManager(BaseDialog): """ :Events: `on_tab_switch` Called when switching tabs. `on_tap_file` Called when the file is clicked. `on_tap_dir` Called when the folder is clicked. `on_context_menu` Called at the end of any actions of the context menu, be it copying, archiving files and other actions. `on_open_plugin_dialog` Description. `on_dismiss_plugin_dialog` Description. """ with open( os.path.join(os.path.dirname(__file__), "data", "context-menu-items.json"), encoding="utf-8", ) as data: menu_right_click_items = ast.literal_eval(data.read()) path = StringProperty(os.getcwd()) """ The path to the directory in which the file manager will open by default. :attr:`path` is an :class:`~kivy.properties.StringProperty` and defaults to ``os.getcwd()``. """ context_menu_open = BooleanProperty(False) """ Open or close context menu. :attr:`context_menu_open` is an :class:`~kivy.properties.BooleanProperty` and defaults to `False`. """ path_to_skin = StringProperty() """ Path to directory with custom images. :attr:`path_to_skin` is an :class:`~kivy.properties.StringProperty` and defaults to `''`. """ bg_color = ListProperty() """ Background color of file manager in the format (r, g, b, a). :attr:`bg_color` is a :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ bg_texture = StringProperty() """ Background texture of file manager. :attr:`bg_texture` is a :class:`~kivy.properties.StringProperty` and defaults to `''`. """ _overlay_color = ListProperty([0, 0, 0, 0]) auto_dismiss = False _instance_file_chooser_icon = None def __init__(self, **kwargs): super().__init__(**kwargs) self.ext_files = {} # The object of the currently open tab. self.current_open_tab_manager = None # Open or closed the settings panel. self.settings_panel_open = False # Open or close the theme selection panel in the settings panel. self.settings_theme_panel_open = False # Open or close the dialog of plugin. self.dialog_plugin_open = False # Open or close dialog with search results. self.dialog_files_search_results_open = False self.instance_search_field = None self.config = ConfigParser() self.data_dir = os.path.join(os.path.dirname(__file__), "data") self.config.read(os.path.join(self.data_dir, "settings.ini")) self.register_event_type("on_tab_switch") self.register_event_type("on_tap_file") self.register_event_type("on_tap_dir") self.register_event_type("on_context_menu") self.register_event_type("on_open_plugin_dialog") self.register_event_type("on_dismiss_plugin_dialog") self.theme_cls.bind(theme_style=self.update_background_search_field) if self.path_to_skin and os.path.exists(self.path_to_skin): path_to_directory_exts = os.path.join(self.path_to_skin, "files") for name_file in os.listdir(path_to_directory_exts): self.ext_files[name_file.split(".")[0]] = os.path.join( path_to_directory_exts, name_file) if not self.ext_files: with open( os.path.join(os.path.dirname(__file__), "data", "default_files_type.json"), encoding="utf-8", ) as data: self.ext_files = ast.literal_eval(data.read()) def add_color_panel(self): def set_list_colors_themes(*args): self.settings_theme_panel_open = True if not theme_panel.content.ids.rv.data: for name_theme in palette: theme_panel.content.ids.rv.data.append({ "viewclass": "FileManagerSettingsColorItem", "color": get_color_from_hex(colors[name_theme]["500"]), "text": name_theme, "manager": self, }) # Adds a panel. theme_panel = MDExpansionPanel( icon="palette", content=Factory.FileManagerChangeTheme(), panel_cls=MDExpansionPanelOneLine(text="Select theme"), ) theme_panel.bind( on_open=set_list_colors_themes, on_close=self._set_state_close_theme_panel, ) self.ids.settings.add_widget(theme_panel) # Adds a close button to the settings panel. box = MDBoxLayout(adaptive_height=True) box.add_widget(Widget()) box.add_widget( MDFlatButton( text="CLOSE", on_release=lambda x: self.hide_settings(theme_panel), )) self.ids.settings.add_widget(box) def apply_palette(self): """Applies the color theme from the settings file when opening the file manager window.""" palette = self.config.get("General", "palette") theme = self.config.get("General", "theme") memorize_palette = self.config.getint("General", "memorize_palette") if memorize_palette: self.theme_cls.primary_palette = palette self.theme_cls.theme_style = theme def apply_properties_on_show_settings(self): """Applies the settings from the "settings.ini" file to the checkboxes of items on the settings panel.""" self.ids.settings.ids.tooltip_check.active = self.config.getint( "General", "tooltip") self.ids.settings.ids.memorize_check.active = self.config.getint( "General", "memorize_palette") self.ids.settings.ids.theme_switch.active = ( 1 if self.theme_cls.theme_style == "Dark" else 0) def show_taskbar(self): def on_complete_animation(*args): self.ids.task_spinner.active = True self.ids.lbl_task.opacity = 1 Animation(height=dp(24), d=0.2).start(self.ids.taskbar) Animation(user_font_size=sp(18), d=0.2).start(self.ids.button_expand) anim = Animation(opacity=1, d=0.2) anim.bind(on_complete=on_complete_animation) anim.start(self.ids.task_spinner) def hide_taskbar(self): def on_complete_animation(*args): self.ids.task_spinner.active = False self.ids.lbl_task.opacity = 0 self.instance_search_field.text_field_search_dialog.ids.check_background.active = ( False) self.instance_search_field.text_field_search_dialog.open() Animation(height=0, d=0.2).start(self.ids.taskbar) Animation(user_font_size=sp(1), d=0.2).start(self.ids.button_expand) anim = Animation(opacity=1, d=0.2) anim.bind(on_complete=on_complete_animation) anim.start(self.ids.task_spinner) def show_settings(self, instance_button): """Opens the settings panel.""" self.apply_properties_on_show_settings() Animation( settings_container_y=self.ids.settings.height, d=0.2, ).start(self.ids.settings_container) Animation( _overlay_color=[0, 0, 0, 0.4], d=0.2, ).start(self) self.settings_panel_open = True def hide_settings(self, theme_panel): """Closes the settings panel.""" def hide_settings(interval): Animation(settings_container_y=0, d=0.2).start(self.ids.settings_container) self._set_state_close_theme_panel() if self.settings_theme_panel_open: theme_panel.check_open_panel(theme_panel) Clock.schedule_once(hide_settings, 0.5) Animation( _overlay_color=[0, 0, 0, 0], d=0.2, ).start(self) self.settings_panel_open = False def set_path(self, path): """Sets the directory path for the `FileChooserIconLayout` class.""" self.path = path self.current_open_tab_manager.ids.file_chooser_icon.path = path tab_text = self.get_formatting_text_for_tab(os.path.split(path)[1]) self.current_open_tab_manager.text = tab_text def get_formatting_text_for_tab(self, text): icon_font = fonts[-1]["fn_regular"] icon = md_icons["close"] text = f"[size=16][font={icon_font}][ref=]{icon}[/ref][/size][/font] {text}" return text def add_tab(self, path_to_file): """ Adds a new tab in the file manager. :param path_to_file: The path to the file or folder that was right-clicked. """ tab_text = self.get_formatting_text_for_tab( os.path.split(path_to_file)[1]) tab = FileManagerTab(manager=self, title=tab_text, path=path_to_file) self._instance_file_chooser_icon = tab.ids.file_chooser_icon self.ids.tabs.add_widget(tab) self.current_open_tab_manager = tab self.ids.tabs.switch_tab(tab_text, search_by="title") self.path = path_to_file def remove_tab( self, instance_tabs, instance_tab_label, instance_tab, instance_tab_bar, instance_carousel, ): """Removes an open tab in the file manager. :param instance_tabs: <kivymd.uix.tab.MDTabs object> :param instance_tab_label: <kivymd.uix.tab.MDTabsLabel object> :param instance_tab: <__main__.Tab object> :param instance_tab_bar: <kivymd.uix.tab.MDTabsBar object> :param instance_carousel: <kivymd.uix.tab.MDTabsCarousel object> """ for instance_tab in instance_carousel.slides: if instance_tab.text == instance_tab_label.text: instance_tabs.remove_widget(instance_tab_label) break def create_header_menu(self): """Creates a menu in the file manager header.""" with open( os.path.join(os.path.dirname(__file__), "data", "header_menu.json"), encoding="utf-8", ) as data: menu_header = ast.literal_eval(data.read()) for name_icon_item in menu_header: self.ids.header_box_menu.add_widget( MDIconButton( icon=name_icon_item, user_font_size="18sp", disabled=True if name_icon_item not in ("home", "settings") else False, md_bg_color_disabled=(0, 0, 0, 0), )) self.ids.header_box_menu.add_widget( MDSeparator(orientation="vertical")) self.ids.header_box_menu.add_widget( MDIconButton( icon="cog", user_font_size="18sp", on_release=self.show_settings, )) background_normal = os.path.join( self.data_dir, "images", "bg-field.png" if self.theme_cls.theme_style == "Light" else "bg-field-dark.png", ) self.instance_search_field = FileManagerTextFieldSearch( background_normal=background_normal, background_active=background_normal, manager=self, ) self.ids.header_box_menu.add_widget(Widget()) self.ids.header_box_menu.add_widget(self.instance_search_field) def update_background_search_field(self, instance, value): background_normal = os.path.join( self.data_dir, "images", "bg-field.png" if value == "Light" else "bg-field-dark.png", ) self.instance_search_field.background_normal = background_normal self.instance_search_field.background_active = background_normal def open_context_menu(self, entry_object, type_chooser): """Opens a context menu on right-clicking on a file or folder.""" menu = MDDropdownMenu( caller=entry_object, items=self.get_menu_right_click(entry_object, type_chooser), width_mult=4, background_color=self.theme_cls.bg_dark, max_height=dp(240), ) menu.bind(on_dismiss=self.context_menu_dismiss, ) menu.open() self.context_menu_open = True def tap_on_file_dir(self, *touch): """Called when the file/dir is clicked.""" type_click = touch[0][1].button # "FileChooserList" or "FileChooserIcon". type_chooser = touch[1] # FileThumbEntry object from file_chooser_icon.py file. entry_object = touch[0][0] if type_click == "right" and entry_object.path != "../": self.open_context_menu(entry_object, type_chooser) else: if entry_object.path == "../": entry_object.path = os.path.dirname(self.path) entry_object.collide_point( *touch[0] [1].pos) and self._instance_file_chooser_icon.entry_touched( entry_object, touch[0][1]) if os.path.isdir(entry_object.path): self.set_path(entry_object.path) self.dispatch("on_tap_dir", entry_object.path) else: self.dispatch("on_tap_file", entry_object.path) if hasattr(entry_object, "remove_tooltip"): entry_object.remove_tooltip() def call_context_menu_plugin(self, name_plugin, entry_object): module = importlib.import_module( f"kivymd_extensions.filemanager.libs.plugins.contextmenu") plugin_cls = module.ContextMenuPlugin( instance_manager=self, entry_object=entry_object, ) plugin_cls.main(name_plugin) def tap_to_context_menu_item(self, text_item, entry_object): """ :type entry_object: <kivy.lang.builder.FileThumbEntry object> :type instance_item: <kivymd.uix.menu.MDMenuItemIcon object> :type instance_menu: <kivymd.uix.menu.MDDropdownMenu object> """ for data_item in self.menu_right_click_items: if (list(data_item.items()) and text_item in list(data_item.items())[0]): if "cls" in data_item: self.call_context_menu_plugin(data_item["cls"], entry_object) break if text_item == "Open in new tab": self.add_tab(entry_object.path) self.dismiss_context_menu() def dismiss_context_menu(self): if self.context_menu_open: for widget in Window.children: if isinstance(widget, MDDropdownMenu): widget.dismiss() break def context_menu_dismiss(self, *args): """Called when closing the context menu.""" self.context_menu_open = False def get_menu_right_click(self, entry_object, type_chooser): """Returns a list of dictionaries for creating context menu items.""" menu_right_click_items = [] if type_chooser == "FileChooserIcon": for data_item in self.menu_right_click_items: if data_item: icon = list(data_item.items())[0][0] if icon: viewclass = "FileManagerItem" _txt_left_pad = dp(72) else: viewclass = "OneLineListItem" _txt_left_pad = dp(32) text = list(data_item.items())[0][1] menu_right_click_items.append({ "text": text, "viewclass": viewclass, "icon": icon, "font_style": "Caption", "height": dp(36), "top_pad": dp(4), "bot_pad": dp(10), "divider": None, "_txt_left_pad": _txt_left_pad, "on_release": lambda x=text, y=entry_object: self. tap_to_context_menu_item(x, y), }) if type_chooser == "FileChooserList": menu_right_click_items.append({ "viewclass": "OneLineListItem", "text": "Open in new tab", "font_style": "Caption", "height": dp(36), "divider": None, "top_pad": dp(4), "bot_pad": dp(10), "on_release": lambda x="Open in new tab", y=entry_object: self. tap_to_context_menu_item(x, y), }) return menu_right_click_items def get_icon_file(self, path_to_file): """Method that returns the icon path for the file.""" return self.ext_files.get( os.path.splitext(path_to_file)[1].replace(".", ""), os.path.join(self.path_to_skin, "file.png") if self.path_to_skin else "file-outline", ) def update_files(self, instance_pludin_dialog, path): # FIXME: Unable to update directory. You have to go to a higher level # and go back. self.set_path(os.getcwd()) self.set_path(os.path.dirname(path)) def is_dir(self, directory, filename): return os.path.isdir(os.path.join(directory, filename)) def on_tap_file(self, *args): """Called when the file is clicked.""" def on_tap_dir(self, *args): """Called when the folder is clicked.""" def on_tab_switch(self, *args): """Called when switching tab.""" def on_open_plugin_dialog(self, *args): self.dialog_plugin_open = True def on_dismiss_plugin_dialog(self, *args): self.dialog_plugin_open = False def on_context_menu(self, *args): """ Called at the end of any actions of the context menu, be it copying, archiving files and other actions. """ def on_open(self): """Called when the ModalView is opened.""" self.add_tab(self.path) self.create_header_menu() self.apply_palette() self.add_color_panel() def _on_tab_switch(self, instance_tabs, instance_tab, instance_tab_label, tab_text): self.current_open_tab_manager = instance_tab self.dispatch( "on_tab_switch", instance_tabs, instance_tab, instance_tab_label, tab_text, ) def _set_state_close_theme_panel(self, *args): self.settings_theme_panel_open = False
# 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 "Exceptions!!!" # Print traceback logs to analysis import traceback
class MainApp(MDApp): def __init(self, **kwargs): self.theme_cls.primary_palette = "Blue" self.theme_cls.theme_style = "Dark" self.config = ConfigParser() self.config.read('main.ini') self.timeout = NumericProperty() def build(self): self.settings_cls = MySettings self.icon = 'music.png' build = Builder.load_file('carputer.ky') #build.add_widget(PlayButtons()) #build.add_widget(VolumeSlider()) #build.add_widget(BigScreenInfo()) return build def build_config(self, config): config.setdefaults( "Default", { "resolutions": initialize.current_res(), "fullscreen": 0, "wallpaper": "blackbox.jpg", "startupvolume": 75, "bt_list": "Click to connect...", "notificationtimeout": 2, "themecolor": "blue" }) try: #Get config resolution conf_res = self.config.get('Default', 'resolutions').split('x') confh = int(conf_res[1]) confw = int(conf_res[0]) #Set Resolution Window.size = confw, confh #check Fullscreen fs = self.config.get('Default', 'fullscreen') self.timeout = self.config.get('Default', 'notificationtimeout') if fs == "1": Window.fullscreen = True elif fs == "0": Window.fullscreen = False except: self.timeout = 1 #get current screen resolution x = initialize.current_res().split('x') height = int(x[1]) width = int(x[0]) Window.size = width, height Window.fullscreen = False def on_start(self): s = self.create_settings() self.root.ids.settingsscreen.add_widget(s) def build_settings(self, settings): with settings.canvas.before: settings.canvas.before.clear() with settings.canvas.before: Color(.1, .1, .1, 0.65, mode='rgba') Rectangle(pos=(0, 0), size=(10000, 10000)) data = settings.json_settings settings.add_json_panel("Default", self.config, data=data) def on_config_change(self, config, section, key, value): title = "Settings" self.timeout = config.get('Default', 'notificationtimeout') if key == "startupvolume": self.startupvolume = int(float(value)) message = "Volume changed to {}".format(value) MainThread.snackbar(MainThread, self, title=title, message=message, timeout=self.timeout) MainThread.notify(MainThread, self, title=title, message=message, timeout=self.timeout) if key == "bt_list": message = "Connected to {}".format(value) if key == "resolutions": x = value.split('x') height = int(x[1]) width = int(x[0]) Window.size = width, height if key == "fullscreen": print(value) if value == '1': Window.fullscreen = True else: Window.fullscreen = False if key == "wallpaper": wp = 'data/wallpapers/' + value wpfile = os.getcwd() + "\\data\\wallpapers\\{}".format(value) if os.path.isfile(wpfile): self.root.ids.wallpp.source = wp else: print(wp + " is not a valid background image") if key == "notificationtimeout": title = "Notify" message = "Changed Notify timeout to {} Seconds".format(value) self.timeout = value MainThread.notify(MainThread, self, title=title, message=message, timeout=self.timeout)
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()
__version__ = "0.0.1" select_locale = {u"Русский": "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 = "blue_orange" else: config = ConfigParser() config.read("{}/program.ini".format(prog_path)) theme = config.get("Theme", "theme") language = select_locale[config.get("General", "language")] # языковая локализация # -----------------------УСТАНОВКА ЦВЕТОВОЙ ТЕМЫ--------------------------- config_theme = ConfigParser() config_theme.read("{}/Data/Themes/{theme}/{theme}.ini".format( prog_path, theme=theme)) theme_background_screen = eval(config_theme.get("color", "background_screen")) theme_background_window = eval(config_theme.get("color", "background_window")) theme_text_color = config_theme.get("color", "text_color") theme_key_text_color = config_theme.get("color", "key_text_color") theme_link_color = config_theme.get("color", "link_color") theme_separator_color_window = \ eval(config_theme.get("color", "separator_color_window"))
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)
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): """Функционал программы."""
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) def startup_tips(stop):
class DictionaryApp(App): def __init__(self, **kwargs): super(DictionaryApp, self).__init__(**kwargs) global i, unerwuenscht, invalsettings, status, durchlauf, bu_pfad invalsettings = True self.config = ConfigParser() # Zaehler um anzuzueigen, wie viele Vokabeln in Dict i = 0 status = "main" # Abfragedurchlauf Initialisieren anzahl = "0" durchlauf = 0 # unerwuenschte Zeichen unerwuenscht = "[(?!:;.1234567890)+-]" # switch off Kivy_settings self.use_kivy_settings = False # Directory for Backups if platform == "android": bu_pfad = "/sdcard/backups/voctrainer/" try: if not os.path.exists(bu_pfad): os.makedirs(bu_pfad) except: bu_pfad = "../backups/voctrainer/" os.makedirs(bu_pfad) else: bu_pfad = "../backups/voctrainer/" if not os.path.exists(bu_pfad): os.makedirs(bu_pfad) def build(self): self.root = DictionaryRoot() # init the variables for search-query self.take_from_build_away() self.title = "Voc-Trainer" return self.root # this needs to be separated from def build(); otherwise you get problems when running # from def on_config_change() def take_from_build_away(self): global learn_lang, mother_lang, return_lang, lang_learn, lang_mother, lang_return, invalsettings, dictlist, dateiname, ersatz_pfad # capture error on android self.build_config(self.config) # get values from settingsmenu learn_lang = self.config.get("languages", "learnlanguage") mother_lang = self.config.get("languages", "motherlanguage") return_lang = self.config.get("languages", "returnlanguage") ## load backupfile try: # dateiname bei erstem durchlauf noch nicht konfiguriert --> Error # check language of backupfile if not ersatz_pfad[ersatz_pfad.find("VOC_TR_"):] == dateiname: raise # get data in backupfile open_dict = DateiHandling() # overwrite global variable dictlist dictlist = open_dict.oeffnen(ersatz_pfad) open_dict.schreiben_datei(dateiname, dictlist) ersatz_pfad = "" # reset backuppath except: pass # reset backuppath try: self.config.read("dictionary.ini") # reset path self.config.set("languages", "backuppath", bu_pfad) except: pass # exception handler neccessary because of opening app after having made # backup causes issues try: if self.config.get("languages", "makebackup") == "yes" and len(dictlist) != 0: Backup() except: pass # reset settings self.config.set("languages", "makebackup", "no") # get varibles for search-query lang_learn, lang_mother, lang_return = self.init_variables(learn_lang, mother_lang, return_lang) # check invalide settings self.check_inval_settings() if not invalsettings: # open the requested file, if exists; otherwise create it self.load_dictionary() def load_dictionary(self): global dictlist, lang_learn, lang_mother, lang_return, dateiname # Dictionary importieren und in der Variablen "dictlist" ablegen open_dict = DateiHandling() dateiname = str("VOC_TR_" + lang_learn + "-" + lang_mother + "-" + lang_return + ".txt") #print "Open file:", dateiname dictlist = open_dict.oeffnen(dateiname) # config-preset for our own settings: def build_config(self, config): try: config.read("dictionary.ini") config.set("languages", "backuppath", bu_pfad) except: config.setdefaults( "languages", { "learnlanguage": "Italian", "motherlanguage": "German", "returnlanguage": "English", "backuppath": "../backups/voctrainer/", "makebackup": 0} ) # add our own settings: def build_settings(self, settings): settings.register_type("scrolloptions", SettingScrollOptions) settings.add_json_panel("VOC-Trainer Settings", self.config, data = settings_json) # change variables on settings-change def on_config_change(self, config, section, key, value): global invalsettings, ersatz_pfad # ersatzpfad notwendig, da neuer build_config durchlauf in take_from_build_away ersatz_pfad = self.config.get("languages", "backuppath") self.back_refactor() self.check_inval_settings() self.root.add_widget(DictionaryRoot()) if not invalsettings: self.take_from_build_away() else: return def check_inval_settings(self): global invalsettings # get all three languages: langlist = [self.config.get("languages", "learnlanguage"), self.config.get("languages", "motherlanguage"), self.config.get("languages", "returnlanguage")] # if any language appears more than 1 time --> invalsettings = True for i in langlist: if langlist.count(i) != 1: invalsettings = True return invalsettings = False def init_variables(self, learn_lang, mother_lang, return_lang): # initialize lang_learn depending on settings lang_learn = self.select_lang(learn_lang) lang_mother = self.select_lang(mother_lang) lang_return = self.select_lang(return_lang) return lang_learn, lang_mother, lang_return def select_lang(self, language): # ita - Italian # en - English # de - German # fra - French # es - Spanish # ru - Russian # ro - Romanian # tr - Turkish # ar - Arabic # la - Latin # sv - Swedish # ku - Kurdish if language == "Arabic": lang = "ar" elif language == "English": lang = "en" elif language == "French": lang = "fra" elif language == "German": lang = "deu" elif language == "Italian": lang = "ita" elif language == "Kurdish": lang = "ku" elif language == "Latin": lang = "la" elif language == "Romanian": lang = "ro" elif language == "Russian": lang = "ru" elif language == "Spanish": lang = "es" elif language == "Swedish": lang = "sv" elif language == "Turkish": lang = "tr" return lang def back(self): # setzt i fuer Anzeige der Anzahl der Vokabeln zurueck global i, dateiname, status #### hier muss das Dictionary gespeichert werden #### write_dict = DateiHandling() # das funktioniert, weil diclist.append nur aufgerufen wird, wenn auch muttersprache und englische Vokabel eingegeben wurde!!! # ansonsten ist dictlist unveraendert write_dict.schreiben_datei(dateiname, dictlist) # damit man wieder zum Input zurueck kommt, wenn show von dort aufgerufen wird if status == "from_input": self.back_refactor() self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02) self.root.add_widget(Input_Learn()) elif status == "from_list": self.back_refactor() self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02) self.root.add_widget(List()) elif status == "abfrage": self.back_refactor() self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02) self.root.add_widget(Abfrage()) return else: # Zuruecksetzen des Zaehlers, damit beim erneuten Aufruf wieder die Anzahl der Vokabeln im Dictionary angezeigt wird i = 0 status = "main" self.back_refactor() self.root.add_widget(DictionaryRoot()) def back_refactor(self): self.root.clear_widgets() self.root.canvas.clear() # sonst Fehler mit Hintergrundfarbe self.root.padding = 0 # sonst Fehler def show(self): global voc_learn, edit_learn, edit_mother, edit_en, search, status if status == "input": status = "from_input" elif status == "list": status = "from_list" search = unicode(voc_learn, "utf-8") edit_learn = search edit_mother = ",".join(dictlist[search][0]) edit_en = ",".join(dictlist[search][1]) self.back_refactor() self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02) self.root.add_widget(Edit()) def on_pause(self): return True def on_resume(self): pass # changes the function of the "back" button aka. "esc" to not throw you out of application # when not in main-menu def on_start(self): EventLoop.window.bind(on_keyboard=self.checkback) # checks every key-event if esc-button def checkback(self, window, key, *args): if key == 27: if status != "main": self.back() return True else: return False return
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)
class ConfigScreen(Screen): s = ObjectProperty(None) player_keys = 'left right thrust fire special'.split() def __init__(self, **kw): super(ConfigScreen, self).__init__(**kw) self.config = ConfigParser() self.config.read('config.ini') self._update_players() Clock.schedule_once(self._after_build, 1) def on_leave(self, *args): Screen.on_leave(self, *args) self._update_players() def _update_players(self): for i, p in enumerate(self.players, start=1): self._update_player(i, p) def _update_player(self, i, p): keys = {} for key in self.player_keys: keys[key] = int(self.config.get('player%d' % i, key)) p['keys'] = keys def _after_build(self, dt=None): print(os.path.abspath('.'), os.path.isfile("config.json")) s = self.s s.register_type('button', SettingButtonItem) s.add_json_panel('stuff', self.config, 'config.json') for i in range(1, 6): player = 'player%d' % i j = player + '.json' with open(j, 'wb') as f: f.write( json.dumps([{ "type": "button", "title": a, "desc": "key for applying '%s'" % a, "section": player, "key": a, } for a in self.player_keys], indent=4).encode(encoding='utf_8')) s.add_json_panel(player, self.config, j) def save(self): self.config.write() self.manager.current = 'menu' players = [ { 'name': 'Player1', 'source': 'imgs/DUCK.GIF', #'weapon': 'gun', 'pos': (50, 50), 'r': 1.0, 'g': 1.0, 'b': 0.75, 'rotation': 45 }, { 'name': 'Player2', 'source': 'imgs/DUCK.GIF', #'weapon': 'gun', 'pos': (50, 200), 'r': 1.0, 'g': 0.5, 'b': 0.75, 'rotation': 45 }, { 'name': 'Player3', 'source': 'imgs/DUCK.GIF', #'weapon': 'gun', 'pos': (250, 50), 'r': 0.5, 'g': 0.2, 'b': 0.75, 'rotation': 45 }, { 'name': 'Player4', 'source': 'imgs/DUCK.GIF', #'weapon': 'gun', 'pos': (350, 50), 'r': 0.5, 'g': 0.5, 'b': 0.98, 'rotation': 45 }, { 'name': 'Player5', 'source': 'imgs/DUCK.GIF', #'weapon': 'gun', 'pos': (450, 50), 'r': 1.0, 'g': 0.1, 'b': 0.99, 'rotation': 45 }, { 'name': 'Player6', 'source': 'imgs/DUCK.GIF', #'weapon': 'gun', 'pos': (550, 50), 'r': 0.35, 'g': 0.99, 'b': 0.99, 'rotation': 45 }, ] for p in players: p['size_hint'] = (0.02, 0.02)
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()
from kivy.uix.scrollview import ScrollView from kivy.uix.gridlayout import GridLayout from kivy.uix.slider import Slider from kivy.config import ConfigParser from scripts.EdsNotify import EdsNotify import commands import platform import urllib devices = [] config = ConfigParser() config.read('%s/eds.ini' % Usr) try: get_device = config.get("Source", "device") except: get_device = "none" try: get_branch = config.get("Source", "branch") except: get_branch = "none" try: make_jobs = config.get("Source", "make") except: make_jobs = numprocs try: sync_jobs = config.get("Source", "sync")
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')
def __init__(self, name): """ Initialization function. We will do the following task (in order): 1. Check if the device is rooted 2. Initialize necessary libs required by MobileInsight (e.g., libwireshark) 3. Check if Android's security policy allows MobileInsight to access diagnostic mode. This is mainly caused by SELinux 4. Create necessary folders on SDcard (e.g., /sdcard/mobileinsight/, /sdcard/mobileinsight/log/) 5. Load built-in and 3rd-party plugins (located in /sdcard/mobileinsight/plugins/) 6. Check if the diagnostic mode is enabled 7. Load configurations from the setting panel (configs stored in /sdcard/.mobileinsight.ini) """ super(MobileInsightScreen, self).__init__() self.name = name if not main_utils.is_rooted(): # self.ids.log_viewer.disabled = False # self.ids.run_plugin.disabled = False self.log_error( "MobileInsight requires root privilege. Please root your device for correct functioning.") self.__init_libs() self.__check_security_policy() if not create_folder(): # MobileInsight folders unavailable. Add warnings self.log_error("SDcard is unavailable. Please check.") self.screen.ids.log_viewer.disabled = True self.screen.ids.stop_plugin.disabled = True self.screen.ids.run_plugin.disabled = True self.plugins_list = get_plugins_list() # self.plugins_list.sort() if not self.__check_diag_mode(): self.log_error( "The diagnostic mode is disabled. Please check your phone settings.") # clean up ongoing log collections # self.stop_collection() self.terminal_stop = None self.terminal_thread = None bootup = True #used to shorten long widget names in popup menu shortenLabel = CoreLabel(markup = True, text_size = (Window.width/2.5, None), shorten_from = "right", font_size = 70) #Making and adding widgets to popup menu for name in self.plugins_list: widget = Button(id = name, markup = True, halign = "left", valign = "top", on_release = self.callback, background_normal = "", background_color = self.ids.run_plugin.background_color) widget.text_size = (Window.width/2.25, Window.height/4) self.myLayout.add_widget(widget) app_path = self.plugins_list[name][0] if os.path.exists(os.path.join(app_path, "readme.txt")): with open(os.path.join(app_path, "readme.txt"), 'r') as ff: my_description = ff.read() else: my_description = "no description." #shortening long widget names and making font size shortenedName = shortenLabel.shorten(name) font_size = "60" if Window.width < 1450: font_size = "45" widget.text = "[color=fffafa][size=70]"+ shortenedName + "[/size][size="+ font_size + "]\n"+ my_description+"[/size][/color]" if bootup: self.selectedPlugin = name self.ids.selectButton.text = "Select Plugin" self.ids.run_plugin.text = "Run Plugin: "+self.selectedPlugin bootup = False # register Broadcast Receivers. self.registerBroadcastReceivers() # If default service exists, launch it try: config = ConfigParser() config.read('/sdcard/.mobileinsight.ini') default_app_name = config.get("mi_general", "start_service") launch_service = config.get("mi_general", "bstartup_service") if default_app_name and launch_service == "1": self.start_service(default_app_name) self.ids.run_plugin.text = "Stop Plugin: "+default_app_name except Exception as e: pass
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
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 Barsic(MDApp): title = 'barsic' icon = 'icon.png' nav_drawer = ObjectProperty() action_bar = ObjectProperty() lang = StringProperty('ru') date_from = ObjectProperty() date_to = ObjectProperty() def __init__(self, **kvargs): super(Barsic, self).__init__(**kvargs) Window.bind(on_keyboard=self.events_program) Window.soft_input_mode = 'below_target' self.list_previous_screens = ['base'] self.window = Window self.config = ConfigParser() self.manager = None self.window_language = None self.exit_interval = False self.dict_language = literal_eval( open( os.path.join(self.directory, 'data', 'locales', 'locales.txt')).read() ) self.translation = Translation( self.lang, 'Ttest', os.path.join(self.directory, 'data', 'locales') ) self.date_from = datetime.now().date() self.date_to = self.date_from def get_application_config(self): return super(Barsic, self).get_application_config( '{}/%(appname)s.ini'.format(self.directory)) def build_config(self, config): config.adddefaultsection('General') config.setdefault('General', 'language', 'en') def set_value_from_config(self): self.config.read(os.path.join(self.directory, 'barsic.ini')) self.lang = self.config.get('General', 'language') def build(self): self.set_value_from_config() self.load_all_kv_files(os.path.join(self.directory, 'uix', 'kv')) self.screen = StartScreen() self.manager = self.screen.ids.manager self.nav_drawer = self.screen.ids.nav_drawer self.action_bar = self.screen.ids.action_bar return self.screen def load_all_kv_files(self, directory_kv_files): for kv_file in os.listdir(directory_kv_files): kv_file = os.path.join(directory_kv_files, kv_file) if os.path.isfile(kv_file): if not PY2: with open(kv_file, encoding='utf-8') as kv: Builder.load_string(kv.read()) else: Builder.load_file(kv_file) def events_program(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.nav_drawer.state == 'open': self.nav_drawer.toggle_nav_drawer() self.back_screen(event=keyboard) elif keyboard in (282, 319): pass return True def back_screen(self, event=None): if event in (1001, 27): if self.manager.current == 'base': self.dialog_exit() return try: self.manager.current = self.list_previous_screens.pop() except: self.manager.current = 'base' self.screen.ids.action_bar.title = self.title self.screen.ids.action_bar.left_action_items = \ [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]] def show_about(self, *args): self.nav_drawer.toggle_nav_drawer() self.screen.ids.about.ids.label.text = self.translation._( u'[size=20][b]barsic[/b][/size]\n\n' u'[b]Version:[/b] {version}\n' u'[b]License:[/b] MIT\n\n' u'[size=20][b]Developer[/b][/size]\n\n' u'[ref=SITE_PROJECT]' u'[color={link_color}]Ivan Bazhenov[/color][/ref]\n\n' u'[b]Source code:[/b] ' u'[ref=https://github.com/sendhello/barsic-android-client]' u'[color={link_color}]GitHub[/color][/ref]').format( version=__version__, link_color=get_hex_from_color(self.theme_cls.primary_color) ) self.manager.current = 'about' self.screen.ids.action_bar.left_action_items = \ [['chevron-left', lambda x: self.back_screen(27)]] def show_zones(self, *args): self.nav_drawer.toggle_nav_drawer() self.manager.current = 'zones' self.action_bar.title = 'zones' self.list_previous_screens.append('zones') self.screen.ids.action_bar.left_action_items = [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]] def show_short_report(self, *args): self.nav_drawer.toggle_nav_drawer() self.manager.current = 'short_report' self.action_bar.title = 'short_report' self.list_previous_screens.append('short_report') self.screen.ids.action_bar.left_action_items = [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]] def show_total_report(self, *args): self.nav_drawer.toggle_nav_drawer() self.manager.current = 'total_report' self.action_bar.title = 'total_report' self.action_bar.right_action_items = [['timetable', lambda x: self.screen.ids.total_report.bottom_sheet()]] self.list_previous_screens.append('total_report') self.screen.ids.action_bar.left_action_items = [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]] def show_result(self, *args): self.manager.current = 'result' self.action_bar.title = 'result' self.screen.ids.action_bar.left_action_items = [['chevron-left', lambda x: self.back_screen(27)]] def show_reports(self, *args): self.nav_drawer.toggle_nav_drawer() self.manager.current = 'report' self.action_bar.title = 'report' self.list_previous_screens.append('report') self.screen.ids.action_bar.left_action_items = [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]] # Загрузка параметров из INI-файла self.load_checkbox() def show_parameters(self, *args): self.nav_drawer.toggle_nav_drawer() self.manager.current = 'parameters' self.action_bar.title = 'parameters' self.screen.ids.action_bar.left_action_items = [['chevron-left', lambda x: self.back_screen(27)]] # # Загрузка параметров из INI-файла # self.load_checkbox() def show_license(self, *args): self.nav_drawer.toggle_nav_drawer() if not PY2: self.screen.ids.license.ids.text_license.text = self.translation._('%s') % open( os.path.join(self.directory, 'LICENSE'), encoding='utf-8').read() else: self.screen.ids.license.ids.text_license.text = self.translation._('%s') % open( os.path.join(self.directory, 'LICENSE')).read() self.manager.current = 'license' self.action_bar.title = 'license' self.screen.ids.action_bar.left_action_items = \ [['chevron-left', lambda x: self.back_screen(27)]] self.screen.ids.action_bar.title = self.translation._('MIT LICENSE') def select_locale(self, *args): def select_locale(name_locale): for locale in self.dict_language.keys(): if name_locale == self.dict_language[locale]: self.lang = locale self.config.set('General', 'language', self.lang) self.config.write() dict_info_locales = {} for locale in self.dict_language.keys(): dict_info_locales[self.dict_language[locale]] = \ ['locale', locale == self.lang] if not self.window_language: self.window_language = card( Lists( dict_items=dict_info_locales, events_callback=select_locale, flag='one_select_check' ), size=(.85, .55) ) self.window_language.open() def load_checkbox(self): """ Установка чекбоксов в соответствии с настройками INI-файла """ # self.root.ids.report.ids.split_by_days.active = self.split_by_days # self.root.ids.report.ids.finreport_xls.active = self.finreport_xls # self.root.ids.report.ids.check_client_count_total_xls.active = self.check_client_count_total_xls # self.root.ids.report.ids.check_cashreport_xls.active = self.check_cashreport_xls # self.root.ids.report.ids.check_itogreport_xls.active = self.check_itogreport_xls # self.root.ids.report.ids.agentreport_xls.active = self.agentreport_xls # self.root.ids.report.ids.use_yadisk.active = self.use_yadisk # self.root.ids.report.ids.finreport_google.active = self.finreport_google # self.root.ids.report.ids.finreport_telegram.active = self.finreport_telegram pass def click_date_switch(self): if self.root.ids.report.ids.date_switch.active: self.date_switch = True self.root.ids.report.ids.label_date.text = 'Дата:' self.set_date_to(self.date_from.date() + timedelta(1)) self.root.ids.report.ids.date_to.theme_text_color = 'Secondary' self.root.ids.report.ids.split_by_days.active = False self.root.ids.report.ids.split_by_days.disabled = True self.root.ids.report.ids.split_by_days_text.theme_text_color = 'Secondary' self.change_checkbox('split_by_days', False) self.root.ids.report.ids.finreport_google_text.disabled = False self.root.ids.report.ids.finreport_google.disabled = False else: self.date_switch = False self.root.ids.report.ids.label_date.text = 'Период:' self.root.ids.report.ids.date_to.theme_text_color = 'Primary' self.root.ids.report.ids.split_by_days.disabled = False self.root.ids.report.ids.split_by_days.active = True self.root.ids.report.ids.split_by_days_text.theme_text_color = 'Primary' self.change_checkbox('split_by_days', True) def change_checkbox(self, name, checkbox): """ Изменяет состояние элемента конфигурации и записывает в INI-файл :param name: Имя чекбокса :param checkbox: Состояние active чекбокса """ self.config.set('General', name, str(checkbox)) setattr(self, name, checkbox) self.config.write() if name == 'split_by_days' and not checkbox and not self.root.ids.report.ids.date_switch.active: self.root.ids.report.ids.finreport_google.active = False self.change_checkbox('finreport_google', False) self.root.ids.report.ids.finreport_google.disabled = True self.root.ids.report.ids.finreport_google_text.disabled = True elif name == 'split_by_days' and checkbox: self.root.ids.report.ids.finreport_google_text.disabled = False self.root.ids.report.ids.finreport_google.disabled = False def dialog_exit(self): def check_interval_press(interval): self.exit_interval += interval if self.exit_interval > 5: self.exit_interval = False Clock.unschedule(check_interval_press) if self.exit_interval: sys.exit(0) Clock.schedule_interval(check_interval_press, 1) toast(self.translation._('Press Back to Exit')) def on_lang(self, instance, lang): self.translation.switch_lang(lang) def show_example_alert_dialog(self): if not self.alert_dialog: self.alert_dialog = MDDialog( title="Reset settings?", text="This will reset your device to its default factory settings.", buttons=[ MDFlatButton( text="CANCEL", text_color=self.app.theme_cls.primary_color, ), MDFlatButton( text="ACCEPT", text_color=self.app.theme_cls.primary_color, ), ], ) self.alert_dialog.open()
class Project_Test_APP(App): '''Функционал программы.''' title = 'Project_Test_APP' icon = 'icon.png' nav_drawer = ObjectProperty() theme_cls = ThemeManager() theme_cls.primary_palette = 'Blue' lang = StringProperty('en') def __init__(self, **kvargs): super(Project_Test_APP, self).__init__(**kvargs) Window.bind(on_keyboard=self.events_program) Window.soft_input_mode = 'below_target' self.list_previous_screens = ['base'] self.window = Window self.plugin = ShowPlugins(self) self.config = ConfigParser() self.manager = None self.window_language = None self.exit_interval = False self.dict_language = literal_eval( open(os.path.join(self.directory, 'data', 'locales', 'locales.txt')).read()) self.translation = Translation( self.lang, 'Ttest', os.path.join(self.directory, 'data', 'locales')) def get_application_config(self): return super(Project_Test_APP, self).get_application_config( '{}/%(appname)s.ini'.format(self.directory)) def build_config(self, config): '''Создаёт файл настроек приложения project_test_app.ini.''' config.adddefaultsection('General') config.setdefault('General', 'language', 'en') def set_value_from_config(self): '''Устанавливает значения переменных из файла настроек project_test_app.ini.''' self.config.read(os.path.join(self.directory, 'project_test_app.ini')) self.lang = self.config.get('General', 'language') def build(self): self.set_value_from_config() self.load_all_kv_files( os.path.join(self.directory, 'libs', 'uix', 'kv')) self.screen = StartScreen() # главный экран программы self.manager = self.screen.ids.manager self.nav_drawer = self.screen.ids.nav_drawer return self.screen def load_all_kv_files(self, directory_kv_files): for kv_file in os.listdir(directory_kv_files): kv_file = os.path.join(directory_kv_files, kv_file) if os.path.isfile(kv_file): if not PY2: with open(kv_file, encoding='utf-8') as kv: Builder.load_string(kv.read()) else: Builder.load_file(kv_file) def events_program(self, instance, keyboard, keycode, text, modifiers): '''Вызывается при нажатии кнопки Меню или Back Key на мобильном устройстве.''' if keyboard in (1001, 27): if self.nav_drawer.state == 'open': self.nav_drawer.toggle_nav_drawer() self.back_screen(event=keyboard) elif keyboard in (282, 319): pass return True def back_screen(self, event=None): '''Менеджер экранов. Вызывается при нажатии Back Key и шеврона "Назад" в ToolBar.''' # Нажата BackKey. if event in (1001, 27): if self.manager.current == 'base': self.dialog_exit() return try: self.manager.current = self.list_previous_screens.pop() except: self.manager.current = 'base' self.screen.ids.action_bar.title = self.title self.screen.ids.action_bar.left_action_items = \ [['menu', lambda x: self.nav_drawer._toggle()]] def show_plugins(self, *args): '''Выводит на экран список плагинов.''' self.plugin.show_plugins() def show_about(self, *args): self.nav_drawer.toggle_nav_drawer() self.screen.ids.about.ids.label.text = \ self.translation._( u'[size=20][b]Project_Test_APP[/b][/size]\n\n' u'[b]Version:[/b] {version}\n' u'[b]License:[/b] MIT\n\n' u'[size=20][b]Developer[/b][/size]\n\n' u'[ref=SITE_PROJECT]' u'[color={link_color}]flytrue[/color][/ref]\n\n' u'[b]Source code:[/b] ' u'[ref=https://github.com/flytrue/testapp]' u'[color={link_color}]GitHub[/color][/ref]').format( version=__version__, link_color=get_hex_from_color(self.theme_cls.primary_color) ) self.manager.current = 'about' self.screen.ids.action_bar.left_action_items = \ [['chevron-left', lambda x: self.back_screen(27)]] def show_license(self, *args): if not PY2: self.screen.ids.license.ids.text_license.text = \ self.translation._('%s') % open( os.path.join(self.directory, 'LICENSE'), encoding='utf-8').read() else: self.screen.ids.license.ids.text_license.text = \ self.translation._('%s') % open( os.path.join(self.directory, 'LICENSE')).read() self.nav_drawer._toggle() self.manager.current = 'license' self.screen.ids.action_bar.left_action_items = \ [['chevron-left', lambda x: self.back_screen()]] self.screen.ids.action_bar.title = \ self.translation._('MIT LICENSE') def select_locale(self, *args): '''Выводит окно со списком имеющихся языковых локализаций для установки языка приложения.''' def select_locale(name_locale): '''Устанавливает выбранную локализацию.''' for locale in self.dict_language.keys(): if name_locale == self.dict_language[locale]: self.lang = locale self.config.set('General', 'language', self.lang) self.config.write() dict_info_locales = {} for locale in self.dict_language.keys(): dict_info_locales[self.dict_language[locale]] = \ ['locale', locale == self.lang] if not self.window_language: self.window_language = card(Lists(dict_items=dict_info_locales, events_callback=select_locale, flag='one_select_check'), size=(.85, .55)) self.window_language.open() def dialog_exit(self): def check_interval_press(interval): self.exit_interval += interval if self.exit_interval > 5: self.exit_interval = False Clock.unschedule(check_interval_press) if self.exit_interval: sys.exit(0) Clock.schedule_interval(check_interval_press, 1) toast(self.translation._('Press Back to Exit')) def on_lang(self, instance, lang): self.translation.switch_lang(lang)
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=(',', ': '))
class Settings(object): __slots__ = [ 'cfgfilename', 'background_source', 'max_stacksize', 'color_mode', 'input_channel', 'video_src', 'video_width', 'video_height', 'show_inp', 'show_out', 'show_vec', 'show_z', 'show_help', 'stack_status', 'single_thread', 'show_ihist', 'show_ohist', 'out', 'loop', 'run', 'x_avg', 'y_avg', 'full_avg', 'indzoom', 'indzoominc', 'log', 'logfile', 'loghandle', 'vecx', 'vecy', 'vecoldx', 'vecoldy', 'vecxcenter', 'vecycenter', 'vecxoffset', 'vecyoffset', 'out_xcenter', 'out_xscale', 'out_ycenter', 'out_yscale', 'actuator', 'actuator_parm', 'dout_active', 'override_active', 'joyx', 'joyy', 'joyxaxis', 'joyyaxis', 'joyaaxis', 'joybaxis', 'joyhat', 'joyoldx', 'joyoldy', 'joymaxx', 'joymaxy', 'proc_thread_run', 'proc_fps', 'output_fps', 'recordi', 'recordv', 'imgindx', 'video', 'output_dir', 'image_dst', 'blr_inp', 'blr_out', 'blr_strength', 'equ_inp', 'equ_out', 'dnz_inp', 'dnz_out', 'dnz_inp_str', 'dnz_out_str', 'flt_inp', 'flt_out', 'flt_inp_strength', 'flt_out_strength', 'flt_inp_kernel', 'flt_out_kernel', 'trfilter', 'trslope', 'trtrigger', 'trpre', 'trflt', 'trpref', 'output_file', 'inp_kernel', 'out_kernel', 'flip_x', 'flip_y', 'mode_prc', 'pseudoc', 'dyn_dark', 'gain_inp', 'gain_out', 'offset_inp', 'offset_out', 'stb_inp', 'stb_out', 'vec_zoom', 'green', 'red', 'blue', 'black', 'Config', 'kernels', 'numkernels', 'flt_inp_name', 'flt_out_name', 'rootwidget', 'imagestack', 'disp_image', 'oimage', 'iimage', 'act', 'vecz', 'procthread', 'numframes', 'raspicam', 'timestring', 'cap_prop_frame_width', 'cap_prop_frame_height', 'cap_prop_pos_frames', 'prop_fourcc', 'xorvalue', 'xormask1', 'xormask2', 'mask', 'background', 'actuator_class', 'vectype' ] def __init__(self): self.Config = ConfigParser() self.Config.add_section('Input') self.Config.add_section('Processor') self.Config.add_section('Output') # default values self.cfgfilename = 'default.conf' self.background_source = 'assets/background.png' self.max_stacksize = 255 # Max. No. of frames in stack self.numframes = 128 self.color_mode = -1 # Greyscale output self.input_channel = 0 # Greyscale input self.video_src = 0 # Default camera self.video_width = 1024 self.video_height = 768 self.show_inp = True self.show_out = True self.show_vec = False self.show_z = True self.show_help = False self.stack_status = False self.single_thread = False self.show_ihist = False self.show_ohist = False self.out = None self.background = None self.loop = True self.run = True self.raspicam = False self.xorvalue = False self.xormask1 = None self.xormask2 = None # opencv properties self.cap_prop_frame_width = 3 self.cap_prop_frame_height = 4 self.cap_prop_pos_frames = 1 self.prop_fourcc = 'YUYV' # variables for vector display and actuators self.x_avg = 0 self.y_avg = 0 self.full_avg = 0 self.indzoom = 1 self.indzoominc = 0 self.log = False self.logfile = 'none' self.loghandle = None self.vecx = 0 self.vecy = 0 self.vecoldx = 0 self.vecoldy = 0 self.vecxcenter = 0 self.vecycenter = 0 self.vecxoffset = 0 self.vecyoffset = 0 self.out_xcenter = 0 self.out_ycenter = 0 self.out_xscale = 0 self.out_yscale = 0 self.actuator = False self.actuator_class = 'Paint' self.actuator_parm = '127.0.0.1:9003' self.dout_active = False self.override_active = True self.vectype = 1 # joystick Configuration self.joyx = 0 self.joyy = 0 self.joyxaxis = 2 self.joyyaxis = 3 self.joyaaxis = 0 self.joybaxis = 1 self.joyhat = 0 self.joyoldx = 0 self.joyoldy = 0 self.joymaxx = 32768 self.joymaxy = 32768 # timing settings for processing and display threads self.proc_thread_run = True self.proc_fps = 1.0 / 30.0 self.output_fps = 1.0 / 25.0 # settings for transient filter self.trfilter = False self.trslope = 1 self.trtrigger = 1 self.trpre = 0 self.trflt = 0 self.trpref = 0 # settings for video and image sequence recording self.recordi = False self.recordv = False self.imgindx = 0 self.video = None self.output_file = None self.output_dir = './output/' self.image_dst = self.output_dir # switches for image filters and tools self.blr_inp = False self.blr_out = False self.blr_strength = 7 self.equ_inp = 0 self.equ_out = 0 self.dnz_inp = False self.dnz_out = False self.dnz_inp_str = 33 self.dnz_out_str = 33 self.flt_inp = 0 self.flt_out = 0 self.flt_inp_strength = 0 self.flt_out_strength = 0 self.flt_inp_kernel = None self.flt_out_kernel = None self.flip_x = False self.flip_y = False self.inp_kernel = None self.out_kernel = None self.mode_prc = 0 self.pseudoc = False self.dyn_dark = 4 self.gain_inp = 1.0 self.gain_out = 1.0 self.offset_inp = 0 self.offset_out = 0 self.stb_inp = False self.stb_out = False self.vec_zoom = 0.1 self.green = (0, 255, 0) self.red = (0, 0, 255) self.blue = (255, 0, 0) self.black = (0, 0, 0) self.mask = 0 # self.set_defaults() def gettime(self): self.timestring = time.strftime("%Y%m%d-%H%M%S", time.gmtime()) return self.timestring def write_config(self, filename, widget): if filename is None: filename = self.cfgfilename # Section 'Input' self.Config.set('Input', 'play_mode', widget.playmode_wid.text) self.Config.set('Input', 'video_src', self.video_src) self.Config.set('Input', 'video_width', self.video_width) self.Config.set('Input', 'video_height', self.video_height) self.Config.set('Input', 'video_codec', self.prop_fourcc) self.Config.set('Input', 'input', widget.inp_wid.state) self.Config.set('Input', 'flip_x', widget.flipx_wid.state) self.Config.set('Input', 'flip_y', widget.flipy_wid.state) self.Config.set('Input', 'blr_inp', widget.iblur_wid.state) self.Config.set('Input', 'equ_inp', widget.iequ_wid.text) self.Config.set('Input', 'dnz_inp', widget.idnz_wid.state) self.Config.set('Input', 'dnz_inp_str', self.dnz_inp_str) self.Config.set('Input', 'flt_inp', widget.iflt_wid.text) self.Config.set('Input', 'flt_inp_strength', self.flt_inp_strength) self.Config.set('Input', 'stb_inp', widget.istab_wid.state) self.Config.set('Input', 'gain_inp', widget.igain_wid.value) self.Config.set('Input', 'offset_inp', widget.ioffset_wid.value) self.Config.set('Input', 'color_channel', widget.ichan_wid.text) # Section 'Processor' self.Config.set('Processor', 'mask', widget.mask_wid.text) self.Config.set('Processor', 'mode_prc', widget.proc_wid.text) self.Config.set('Processor', 'dyn_dark', widget.dark_wid.text) self.Config.set('Processor', 'blr_strength', self.blr_strength) self.Config.set('Processor', 'stack_size', widget.stack_wid.value) self.Config.set('Processor', 'ind_zoom', widget.indzoom_wid.value) self.Config.set('Processor', 'dout', widget.dout_wid.state) self.Config.set('Processor', 'vectype', widget.vectype_wid.text) self.Config.set('Processor', 'actuator', widget.actuator_wid.state) self.Config.set('Processor', 'actuator_class', self.actuator_class) self.Config.set('Processor', 'actuator_parm', self.actuator_parm) self.Config.set('Processor', 'override', widget.override_wid.state) # Section 'Output' self.Config.set('Output', 'output', widget.out_wid.state) self.Config.set('Output', 'output_dir', self.output_dir) self.Config.set('Output', 'recorder', widget.recorder_wid.text) self.Config.set('Output', 'blr_out', widget.oblur_wid.state) self.Config.set('Output', 'equ_out', widget.oequ_wid.text) self.Config.set('Output', 'dnz_out', widget.odnz_wid.state) self.Config.set('Output', 'dnz_out_str', self.dnz_out_str) self.Config.set('Output', 'flt_out', widget.oflt_wid.text) self.Config.set('Output', 'flt_out_strength', self.flt_out_strength) self.Config.set('Output', 'stb_out', widget.ostab_wid.state) self.Config.set('Output', 'gain_out', widget.ogain_wid.value) self.Config.set('Output', 'offset_out', widget.ooffset_wid.value) self.Config.set('Output', 'color_mode', widget.colors_wid.text) self.Config.set('Output', 'background_source', self.background_source) self.Config.set('Output', 'osd', widget.osd_wid.state) self.Config.set('Output', 'hud', widget.vec_wid.state) self.Config.set('Output', 'trf_mode', widget.trf_wid.text) self.Config.set('Output', 'trf_trig', self.trtrigger) self.Config.read(filename) self.Config.write() def read_parms(self, filename): if os.path.isfile(filename): self.Config.read(filename) # Section 'Input' self.video_src = self.Config.get('Input', 'video_src') self.video_width = int(self.Config.get('Input', 'video_width')) self.video_height = int(self.Config.get('Input', 'video_height')) self.prop_fourcc = self.Config.get('Input', 'video_codec') self.dnz_inp_str = float(self.Config.get('Input', 'dnz_inp_str')) self.flt_inp_strength = float( self.Config.get('Input', 'flt_inp_strength')) # Section 'Processor' self.blr_strength = int( self.Config.get('Processor', 'blr_strength')) self.actuator_class = self.Config.get('Processor', 'actuator_class') self.actuator_parm = self.Config.get('Processor', 'actuator_parm') # Section 'Output' self.output_dir = self.Config.get('Output', 'output_dir') self.dnz_out_str = float(self.Config.get('Output', 'dnz_out_str')) self.flt_out_strength = float( self.Config.get('Output', 'flt_out_strength')) self.background_source = self.Config.get('Output', 'background_source') self.trtrigger = self.Config.get('Output', 'trf_trig') else: print('File ' + str(filename) + ' does not exist.') def read_ui_parms(self, filename, widget): if os.path.isfile(filename): self.Config.read(filename) # Section 'Input' widget.playmode_wid.text = self.Config.get('Input', 'play_mode') widget.inp_wid.state = self.Config.get('Input', 'input') widget.flipx_wid.state = self.Config.get('Input', 'flip_x') widget.flipy_wid.state = self.Config.get('Input', 'flip_y') widget.iblur_wid.state = self.Config.get('Input', 'blr_inp') widget.iequ_wid.text = self.Config.get('Input', 'equ_inp') widget.idnz_wid.state = self.Config.get('Input', 'dnz_inp') widget.iflt_wid.text = self.Config.get('Input', 'flt_inp') widget.istab_wid.state = self.Config.get('Input', 'stb_inp') widget.igain_wid.value = float(self.Config.get( 'Input', 'gain_inp')) widget.ioffset_wid.value = float( self.Config.get('Input', 'offset_inp')) widget.ichan_wid.text = self.Config.get('Input', 'color_channel') # Section 'Processor' widget.mask_wid.text = self.Config.get('Processor', 'mask') widget.proc_wid.text = self.Config.get('Processor', 'mode_prc') widget.dark_wid.text = self.Config.get('Processor', 'dyn_dark') widget.vectype_wid.text = self.Config.get('Processor', 'vectype') widget.stack_wid.value = int( self.Config.get('Processor', 'stack_size')) widget.indzoom_wid.value = float( self.Config.get('Processor', 'ind_zoom')) widget.dout_wid.state = self.Config.get('Processor', 'dout') widget.actuator_wid.state = self.Config.get( 'Processor', 'actuator') widget.override_wid.state = self.Config.get( 'Processor', 'override') # Section 'Output' widget.out_wid.state = self.Config.get('Output', 'output') widget.recorder_wid.text = self.Config.get('Output', 'recorder') widget.oblur_wid.state = self.Config.get('Output', 'blr_out') widget.oequ_wid.text = self.Config.get('Output', 'equ_out') widget.odnz_wid.state = self.Config.get('Output', 'dnz_out') widget.oflt_wid.text = self.Config.get('Output', 'flt_out') widget.ostab_wid.state = self.Config.get('Output', 'stb_out') widget.ogain_wid.value = float( self.Config.get('Output', 'gain_out')) widget.ooffset_wid.value = float( self.Config.get('Output', 'offset_out')) widget.colors_wid.text = self.Config.get('Output', 'color_mode') widget.osd_wid.state = self.Config.get('Output', 'osd') widget.vec_wid.state = self.Config.get('Output', 'hud') widget.trf_wid.text = self.Config.get('Output', 'trf_mode') else: print('File ' + str(filename) + ' does not exist.')
def get(self, section, option): try: return KivyConfigParser.get(self, section, option) except NoOptionError: self.set(section, option, "off") return "off"