class ProjectSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of project.
    '''

    project = ObjectProperty(None)
    '''Reference to :class:`desginer.project_manager.Project`
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def load_proj_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser()
        file_path = os.path.join(self.project.path, PROJ_CONFIG)
        if not os.path.exists(file_path):
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))

            CONFIG_TEMPLATE = '''[proj_name]
name = Project

[arguments]
arg =

[env variables]
env =
'''
            f = open(file_path, 'w')
            f.write(CONFIG_TEMPLATE)
            f.close()

        self.config_parser.read(file_path)
        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]
        settings_dir = os.path.join(_dir, 'designer', 'settings')
        self.add_json_panel('Shell Environment',
                            self.config_parser,
                            os.path.join(settings_dir,
                                         'proj_settings_shell_env.json'))
        self.add_json_panel('Project Properties',
                            self.config_parser,
                            os.path.join(settings_dir,
                                         'proj_settings_proj_prop.json'))

    @ignore_proj_watcher
    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(ProjectSettings, self).on_config_change(*args)
Esempio n. 2
0
class ProjectSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of project.
    '''

    proj_loader = ObjectProperty(None)
    '''Reference to :class:`desginer.project_loader.ProjectLoader`
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def load_proj_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser()
        file_path = os.path.join(self.proj_loader.proj_dir, PROJ_CONFIG)
        if not os.path.exists(file_path):
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))

            CONFIG_TEMPLATE = '''[proj_name]
name = Project

[arguments]
arg =

[env variables]
env =
'''
            f = open(file_path, 'w')
            f.write(CONFIG_TEMPLATE)
            f.close()

        self.config_parser.read(file_path)
        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]
        settings_dir = os.path.join(_dir, 'designer', 'settings')
        self.add_json_panel('Shell Environment',
                            self.config_parser,
                            os.path.join(settings_dir,
                                         'proj_settings_shell_env.json'))
        self.add_json_panel('Project Properties',
                            self.config_parser,
                            os.path.join(settings_dir,
                                         'proj_settings_proj_prop.json'))

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(ProjectSettings, self).on_config_change(*args)
Esempio n. 3
0
    def load_config(self):
        '''(internal) This function is used for returning a ConfigParser with
        the application configuration. It's doing 3 things:

            #. Creating an instance of a ConfigParser
            #. Loading the default configuration by calling
               :meth:`build_config`, then
            #. If it exists, it loads the application configuration file,
               otherwise it creates one.

        :return:
            :class:`~kivy.config.ConfigParser` instance
        '''
        try:
            config = ConfigParser.get_configparser('app')
        except KeyError:
            config = None
        if config is None:
            config = ConfigParser(name='app')
        self.config = config
        self.build_config(config)
        # if no sections are created, that's mean the user don't have
        # configuration.
        if len(config.sections()) == 0:
            return
        # ok, the user have some sections, read the default file if exist
        # or write it !
        filename = self.get_application_config()
        if filename is None:
            return config
        Logger.debug('App: Loading configuration <{0}>'.format(filename))
        if exists(filename):
            try:
                config.read(filename)
            except:
                Logger.error('App: Corrupted config file, ignored.')
                config.name = ''
                try:
                    config = ConfigParser.get_configparser('app')
                except KeyError:
                    config = None
                if config is None:
                    config = ConfigParser(name='app')
                self.config = config
                self.build_config(config)
                pass
        else:
            Logger.debug('App: First configuration, create <{0}>'.format(
                filename))
            config.filename = filename
            config.write()
        return config
Esempio n. 4
0
class ProjectSettings(Settings):
    """Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of project.
    """

    project = ObjectProperty(None)
    """Reference to :class:`desginer.project_manager.Project`
    """

    config_parser = ObjectProperty(None)
    """Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    """

    def load_proj_settings(self):
        """This function loads project settings
        """
        self.config_parser = ConfigParser()
        file_path = os.path.join(self.project.path, PROJ_CONFIG)
        if not os.path.exists(file_path):
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))

            CONFIG_TEMPLATE = """[proj_name]
name = Project

[arguments]
arg =

[env variables]
env =
"""
            f = open(file_path, "w")
            f.write(CONFIG_TEMPLATE)
            f.close()

        self.config_parser.read(file_path)

        settings_dir = os.path.join(get_kd_data_dir(), "settings")
        self.add_json_panel(
            "Shell Environment", self.config_parser, os.path.join(settings_dir, "proj_settings_shell_env.json")
        )
        self.add_json_panel(
            "Project Properties", self.config_parser, os.path.join(settings_dir, "proj_settings_proj_prop.json")
        )

    @ignore_proj_watcher
    def on_config_change(self, *args):
        """This function is default handler of on_config_change event.
        """
        self.config_parser.write()
        super(ProjectSettings, self).on_config_change(*args)
Esempio n. 5
0
    def load_config(self):
        '''(internal) This function is used for returning a ConfigParser with
        the application configuration. It's doing 3 things:

            #. Creating an instance of a ConfigParser
            #. Loading the default configuration by calling
               :meth:`build_config`, then
            #. If it exists, it loads the application configuration file,
               otherwise it creates one.

        :return:
            :class:`~kivy.config.ConfigParser` instance
        '''
        try:
            config = ConfigParser.get_configparser('app')
        except KeyError:
            config = None
        if config is None:
            config = ConfigParser(name='app')
        self.config = config
        self.build_config(config)
        # if no sections are created, that's mean the user don't have
        # configuration.
        if len(config.sections()) == 0:
            return
        # ok, the user have some sections, read the default file if exist
        # or write it !
        filename = self.get_application_config()
        if filename is None:
            return config
        Logger.debug('App: Loading configuration <{0}>'.format(filename))
        if exists(filename):
            try:
                config.read(filename)
            except:
                Logger.error('App: Corrupted config file, ignored.')
                config.name = ''
                try:
                    config = ConfigParser.get_configparser('app')
                except KeyError:
                    config = None
                if config is None:
                    config = ConfigParser(name='app')
                self.config = config
                self.build_config(config)
                pass
        else:
            Logger.debug('App: First configuration, create <{0}>'.format(
                filename))
            config.filename = filename
            config.write()
        return config
Esempio n. 6
0
 def _on_answer(self, instance, answer):
     if answer == "yes":
         config = ConfigParser()
         config.read('/sdcard/.mobileinsight.ini')
         config.set("mi_general", "privacy", 1)
         config.set("NetLogger", "privacy", 1)
         config.write()
         self.popup.dismiss()
     elif answer == "no":
         # global disagree_privacy
         # disagree_privacy = 1
         config = ConfigParser()
         config.read('/sdcard/.mobileinsight.ini')
         config.set("mi_general", "privacy", 1)
         config.set("NetLogger", "privacy", 0)
         config.write()
         self.popup.dismiss()
Esempio n. 7
0
class AppSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''
    def __init__(self, **kwargs):
        super(AppSettings, self).__init__(*kwargs)
        self.app = App.get_running_app()

    def pre_load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser(name='App Settings')
        APP_CONFIG = os.path.join(self.app.dir, APP_CONFIG_FILE_NAME)

        _dir = self.app.dir

        DEFAULT_CONFIG = os.path.join(_dir, APP_CONFIG_FILE_NAME)
        if not os.path.exists(APP_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG, APP_CONFIG)

        self.config_parser.read(APP_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)

    def load_settings(self):

        _dir_json = os.path.join(self.app.dir, 'settings')
        # creates a panel before insert it to update code input theme list
        panel = self.create_json_panel(
            'App Settings', self.config_parser,
            os.path.join(_dir_json, 'app_settings.json'))
        uid = panel.uid
        if self.interface is not None:
            self.interface.add_panel(panel, 'Kivy Designer Settings', uid)

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(AppSettings, self).on_config_change(*args)
Esempio n. 8
0
class DesignerSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser()
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(),
                                       DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG,
                            DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)
        self.add_json_panel('Kivy Designer Settings', self.config_parser,
                            os.path.join(_dir, 'designer',
                                         'settings', 'designer_settings.json'))

        path = self.config_parser.getdefault(
            'global', 'python_shell_path', '')

        if path == "":
            self.config_parser.set('global', 'python_shell_path',
                                   sys.executable)
            self.config_parser.write()

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
Esempio n. 9
0
class DesignerSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''
    def load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser()
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(),
                                       DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)
        self.add_json_panel(
            'Kivy Designer Settings', self.config_parser,
            os.path.join(_dir, 'designer', 'settings',
                         'designer_settings.json'))

        path = self.config_parser.getdefault('global', 'python_shell_path', '')

        if path == "":
            self.config_parser.set('global', 'python_shell_path',
                                   sys.executable)
            self.config_parser.write()

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
Esempio n. 10
0
    def on_new(self, *args):
        '''Handler for "New Profile" button
        '''
        new_name = 'new_profile'
        i = 1
        while os.path.exists(
                os.path.join(self.PROFILES_PATH, new_name + str(i) + '.ini')):
            i += 1
        new_name += str(i)
        new_prof_path = os.path.join(self.PROFILES_PATH, new_name + '.ini')

        shutil.copy2(os.path.join(self.DEFAULT_PROFILES, 'desktop.ini'),
                     new_prof_path)
        config_parser = ConfigParser()
        config_parser.read(new_prof_path)
        config_parser.set('profile', 'name', new_name.upper())
        config_parser.write()

        self.update_panel()
        self.settings_changed = True
Esempio n. 11
0
    def on_new(self, *args):
        '''Handler for "New Profile" button
        '''
        new_name = 'new_profile'
        i = 1
        while os.path.exists(os.path.join(
                self.PROFILES_PATH, new_name + str(i) + '.ini')):
            i += 1
        new_name += str(i)
        new_prof_path = os.path.join(
            self.PROFILES_PATH, new_name + '.ini')

        shutil.copy2(os.path.join(self.DEFAULT_PROFILES, 'desktop.ini'),
                     new_prof_path)
        config_parser = ConfigParser()
        config_parser.read(new_prof_path)
        config_parser.set('profile', 'name', new_name.upper())
        config_parser.write()

        self.update_panel()
        self.settings_changed = True
Esempio n. 12
0
 def load_config(self):
     try:
         config = ConfigParser.get_configparser('app')
     except KeyError:
         config = None
     if config is None:
         config = ConfigParser(name='app')
     self.config = config
     self.build_config(config)
     # if no sections are created, that's mean the user don't have
     # configuration.
     if len(config.sections()) == 0:
         return
     # ok, the user have some sections, read the default file if exist
     # or write it !
     filename = self.get_application_config()
     if filename is None:
         return config
     Logger.debug('FlexApp: Loading configuration <{0}>'.format(filename))
     if exists(filename):
         try:
             config.read(filename)
         except:
             Logger.error('FlexApp: Corrupted config file, ignored.')
             config.name = ''
             try:
                 config = ConfigParser.get_configparser('app')
             except KeyError:
                 config = None
             if config is None:
                 config = ConfigParser(name='app')
             self.config = config
             self.build_config(config)
             pass
     else:
         Logger.debug('FlexApp: First configuration, create <{0}>'.format(
             filename))
         config.filename = filename
         config.write()
     return config
Esempio n. 13
0
class DesignerSettings(Settings):
    """Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    """

    config_parser = ObjectProperty(None)
    """Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    """

    def load_settings(self):
        """This function loads project settings
        """
        self.config_parser = ConfigParser()
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME), DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.add_json_panel(
            "Kivy Designer Settings",
            self.config_parser,
            os.path.join(_dir, "designer", "settings", "designer_settings.json"),
        )

        path = self.config_parser.getdefault("global", "python_shell_path", "")

        if path == "":
            self.config_parser.set("global", "python_shell_path", sys.executable)
            self.config_parser.write()

    def on_config_change(self, *args):
        """This function is default handler of on_config_change event.
        """
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
Esempio n. 14
0
 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()
         except configparser.NoSectionError:
             App.get_running_app().build_config(config)
             config.write()
     App.get_running_app().set_user(user)
     App.get_running_app().set_user_handler(user_handler)
Esempio n. 15
0
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)
Esempio n. 16
0
class App(KivyApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # UI
        self.title: str = 'Aiventure'
        self.sm: Optional[ScreenManager] = None
        self.screens: Dict[str, ClassVar] = {}
        # AI
        self.ai: Optional[AI] = None
        self.adventure: Optional[Adventure] = None
        # Threading
        self.threads: Dict[str, Thread] = {}
        # Modules
        self.loaded_modules: Dict[str, str] = {}
        self.input_filters: List[Callable[[str], str]] = []
        self.output_filters: List[Callable[[str], str]] = []
        self.display_filter: Optional[Callable[[List[str]], str]] = None

    def build(self) -> ScreenManager:
        """
        """
        self.init_mods()
        self.init_ui()
        return self.sm

    def build_config(self, _) -> None:
        """
        """
        self.config = ConfigParser()
        self.config.read('config.ini')
        self.config.setdefaults('general', {
            'userdir': 'user',
            'autosave': True
        })
        self.config.setdefaults(
            'ai', {
                'timeout': 20.0,
                'memory': 20,
                'max_length': 60,
                'beam_searches': 1,
                'temperature': 0.8,
                'top_k': 40,
                'top_p': 0.9,
                'repetition_penalty': 1.1
            })
        self.config.setdefaults(
            'modules', {
                'input_filters': 'aiventure:filters',
                'output_filters': 'aiventure:filters',
                'display_filter': 'aiventure:filters'
            })
        self.config.write()

    def init_mods(self) -> None:
        """
        Initializes the game's module system and loads mods based on the current configuration.
        """
        sys.path.append(self.config.get('general', 'userdir'))

        for f in self.config.get('modules', 'input_filters').split(','):
            domain, module = f.split(':')
            Logger.info(f'Modules: Loading {f}.filter_input')
            self.input_filters += [
                self.load_submodule(domain, module, 'filter_input')
            ]

        for f in self.config.get('modules', 'output_filters').split(','):
            domain, module = f.split(':')
            Logger.info(f'Modules: Loading {f}.filter_output')
            self.output_filters += [
                self.load_submodule(domain, module, 'filter_output')
            ]

        domain, module = self.config.get('modules',
                                         'display_filter').split(':')
        Logger.info(f'Modules: Loading {f}.filter_display')
        self.display_filter = self.load_submodule(domain, module,
                                                  'filter_display')

    def init_ui(self) -> None:
        """
        Initializes the screen manager, loads all screen kivy files and their associated python modules.
        """
        self.sm = ScreenManager()
        self.screens = {'menu': MenuScreen, 'play': PlayScreen}
        for n, s in self.screens.items():
            Builder.load_file(f'aiventure/client/uix/{n}.kv')
            self.sm.add_widget(s(name=n))
        self.sm.current = 'menu'

    def get_user_path(self, *args: str) -> str:
        """
        Retrieves a path relative to the current user directory.

        :param args: The subdirectories / filenames in the user directory.
        :return: A path in the current user directory.
        """
        return os.path.join(self.config.get('general', 'userdir'), *args)

    def get_model_path(self, model: str) -> str:
        """
        Gets the path to the currently selected (but not necessarily loaded) AI model.

        :param model: The model within the models subdirectory.
        :return: The current selected model path.
        """
        return self.get_user_path('models', model)

    def get_valid_models(self) -> List[str]:
        """
        :return: A list of valid model names, inside {userdir}/models
        """
        return [
            m.name for m in os.scandir(self.get_user_path('models'))
            if is_model_valid(m.path)
        ]

    def get_module_path(self, domain: str, module: str) -> str:
        return self.get_user_path('modules', domain, f'{module}.py')

    def load_module(self, domain: str, module: str) -> Any:
        """
        Loads a module and returns it (if it hasn't been loaded already).

        :param domain: The module domain.
        :param module: The module to load from the given domain.
        :return: The loaded module.
        """
        k = f'{domain}:{module}'
        v = self.loaded_modules.get(k)
        if v is None:
            v = importlib.import_module(f'.{module}', f'modules.{domain}')
            self.loaded_modules[k] = v
        return v

    def load_submodule(self, domain: str, module: str, submodule: str) -> str:
        """
        Loads a submodule (a method, class, or variable from a given module).

        :param domain: The module domain.
        :param module: The module to load from the given domain.
        :param submodule: The submodule to load from the given module.
        :return: The loaded submodule.
        """
        m = self.load_module(domain, module)
        return getattr(m, submodule)

    # SAVING AND LOADING

    def save_adventure(self) -> None:
        """
        Saves the current adventure.
        """
        savefile = get_save_name(self.adventure.name)
        with open(self.get_user_path('adventures', f'{savefile}.json'),
                  'w') as json_file:
            json.dump(self.adventure.to_dict(), json_file, indent=4)

    def load_adventure(self) -> None:
        """
        Loads the current adventure.
        """
        savefile = get_save_name(self.adventure.name)
        with open(self.get_user_path('adventures', f'{savefile}.json'),
                  'r') as json_file:
            self.adventure.from_dict(json.load(json_file))
Esempio n. 17
0
class DesignerSettings(Settings):
    """Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    """

    config_parser = ObjectProperty(None)
    """Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    """

    def __init__(self, **kwargs):
        super(DesignerSettings, self).__init__(*kwargs)
        self.register_type("list", SettingList)
        self.register_type("shortcut", SettingShortcut)

    def load_settings(self):
        """This function loads project settings
        """
        self.config_parser = ConfigParser(name="DesignerSettings")
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)

        # creates a panel before insert it to update code input theme list
        panel = self.create_json_panel(
            "Kivy Designer Settings",
            self.config_parser,
            os.path.join(_dir, "designer", "settings", "designer_settings.json"),
        )
        uid = panel.uid
        if self.interface is not None:
            self.interface.add_panel(panel, "Kivy Designer Settings", uid)

        # loads available themes
        for child in panel.children:
            if child.id == "code_input_theme_options":
                child.items = styles.get_all_styles()

        # tries to find python and buildozer path if it's not defined
        path = self.config_parser.getdefault("global", "python_shell_path", "")

        if path.strip() == "":
            self.config_parser.set("global", "python_shell_path", sys.executable)
            self.config_parser.write()

        buildozer_path = self.config_parser.getdefault("buildozer", "buildozer_path", "")

        if buildozer_path.strip() == "":
            buildozer_path = find_executable("buildozer")
            if buildozer_path:
                self.config_parser.set("buildozer", "buildozer_path", buildozer_path)
                self.config_parser.write()

        self.add_json_panel(
            "Buildozer", self.config_parser, os.path.join(_dir, "designer", "settings", "buildozer_settings.json")
        )
        self.add_json_panel(
            "Hanga", self.config_parser, os.path.join(_dir, "designer", "settings", "hanga_settings.json")
        )
        self.add_json_panel(
            "Keyboard Shortcuts", self.config_parser, os.path.join(_dir, "designer", "settings", "shortcuts.json")
        )

    def on_config_change(self, *args):
        """This function is default handler of on_config_change event.
        """
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
Esempio n. 18
0
class cScriptConfig(object):
    """ Class to manage the initialisation/configuration and access the the settings of an Script settings objects

    """
    def __init__(self, oScript):
        self.oScript = oScript
        self.oConfigParser = KivyConfigParser()
        self.oFnConfig = None
        self.uCurrentSection = None
        self.uDefaultConfigName = u'SCRIPTDEFAULT'
        self.aDiscoverScriptList = None
        self.oInputKeyboard = None
        self.dDefaultSettings = {
            "SettingTitle": {
                "active": "enabled",
                "order": 0,
                "type": "title",
                "title": "$lvar(560)"
            },
            "TimeOut": {
                "active": "disabled",
                "order": 1,
                "type": "numericfloat",
                "title": "$lvar(6019)",
                "desc": "$lvar(6020)",
                "section": "$var(ScriptConfigSection)",
                "key": "TimeOut",
                "default": "1.0"
            },
            "Host": {
                "active": "disabled",
                "order": 5,
                "type": "string",
                "title": "$lvar(6004)",
                "desc": "$lvar(6005)",
                "section": "$var(ScriptConfigSection)",
                "key": "Host",
                "default": "192.168.1.2"
            },
            "Port": {
                "active": "disabled",
                "order": 6,
                "type": "string",
                "title": "$lvar(6002)",
                "desc": "$lvar(6003)",
                "section": "$var(ScriptConfigSection)",
                "key": "Port",
                "default": "80"
            },
            "User": {
                "active": "disabled",
                "order": 7,
                "type": "string",
                "title": "$lvar(6006)",
                "desc": "$lvar(6007)",
                "section": "$var(ScriptConfigSection)",
                "key": "User",
                "default": ""
            },
            "Password": {
                "active": "disabled",
                "order": 8,
                "type": "string",
                "title": "$lvar(6008)",
                "desc": "$lvar(6009)",
                "section": "$var(ScriptConfigSection)",
                "key": "Password",
                "default": ""
            },
            "ConfigChangeButtons": {
                "active":
                "disabled",
                "order":
                999,
                "type":
                "buttons",
                "title":
                "$lvar(565)",
                "desc":
                "$lvar(566)",
                "section":
                "$var(ScriptConfigSection)",
                "key":
                "configchangebuttons",
                "buttons": [{
                    "title": "$lvar(569)",
                    "id": "button_add"
                }, {
                    "title": "$lvar(570)",
                    "id": "button_delete"
                }, {
                    "title": "$lvar(571)",
                    "id": "button_rename"
                }]
            },
        }

        self.dSettingsCombined = {}

    def Init(self):
        """ Init function, sets the configuration file name and add the default sections """

        self.oFnConfig = cFileName(self.oScript.oPathMy) + u'config.ini'
        if not self.oFnConfig.Exists():
            self.oConfigParser.filename = self.oFnConfig.string
            self.CreateSection(uSectionName=self.uDefaultConfigName)

    def LoadConfig(self):
        """ Loads the config file (only once) """

        try:
            self.oConfigParser.filename = self.oFnConfig.string
            if len(self.oConfigParser._sections) == 0:
                if self.oFnConfig.Exists():
                    self.oScript.ShowDebug(u'Reading Config File')
                    self.oConfigParser.read(self.oFnConfig.string)
        except Exception as e:
            self.oScript.ShowError(
                u"can\'t load config file: %s" % self.oFnConfig.string, None,
                e)

    def CreateSection(self, uSectionName):
        """
        Adds a new section to the config parser

        :param string uSectionName: The name of the section to create
        """
        self.oScript.ShowDebug('Adding new section [%s]' % (uSectionName))
        self.oConfigParser.add_section(uSectionName)
        self.oConfigParser.write()

    def GetSettingParFromIni(self, uSectionName, uVarName):
        """
        Returns a setting for the configuration ini file
        If the entry does not exist, it tries to puls the value from the  aInterFaceIniSettings dict of already predifined settings
        If not exist there as well, an error will be logged

        :rtype: string|None
        :param string uSectionName: The name of the section
        :param uVarName: The name of the parameter/setting in the section
        :return: The value of the setting, empty string if not found
         """

        oSetting = self.oScript.GetSettingObjectForConfigName(uSectionName)
        uResult = Config_GetDefault_Str(self.oConfigParser, uSectionName,
                                        uVarName, None)
        if uResult is None:
            uResult = str(oSetting.aScriptIniSettings.queryget(uVarName))
        if uResult is None:
            uResult = ''
            self.oScript.ShowError(u'can\'t find script setting: %s:%s' %
                                   (uSectionName, uVarName))
        else:
            self.oScript.ShowDebug(u'Returning script setting: %s from %s:%s' %
                                   (uResult, uSectionName, uVarName))
        return uResult

    def WriteDefinitionConfigPar(self,
                                 uSectionName,
                                 uVarName,
                                 uVarValue,
                                 bNowrite=False,
                                 bForce=False):
        """ Writes a variable to the config file
        :param string uSectionName: The name of the section
        :param string uVarName: The name of the parameter/setting in the section
        :param string uVarValue: The value for the setting
        :param bool bNowrite: Flag, if we should not immidiatly write the the setting
        :param bool bForce: Flag to force write, even if parameter exists in config
        """
        self.LoadConfig()
        if not self.oConfigParser.has_section(uSectionName):
            self.CreateSection(uSectionName=uSectionName)

        if self.oConfigParser.has_option(uSectionName, uVarName):
            if not bForce:
                return

        self.oConfigParser.set(uSectionName, uVarName, uVarValue)
        if not bNowrite:
            self.oConfigParser.write()

        for uSettingName in self.oScript.aSettings:
            oSetting = self.oScript.aSettings[uSettingName]
            if oSetting.uConfigName == uSectionName:
                oSetting.aScriptIniSettings[uVarName] = uVarValue
                break

    def WriteDefinitionConfig(self, uSectionName, dSettings):
        """
        writes all vars given in a dictionary to the config file

        :param string uSectionName: The name of the section
        :param dict dSettings: A dict of all settings to write
        """

        for uKey in dSettings:
            self.WriteDefinitionConfigPar(uSectionName=uSectionName,
                                          uVarName=uKey,
                                          uVarValue=dSettings[uKey],
                                          bNowrite=True)
        self.oConfigParser.write()

    def ConfigureKivySettings(self, oKivySetting):
        """
        Create the JSON string for all sections and applies it to a kivy settings object
        Discover settings are excluded

        :param setting oKivySetting:
        :return: The KivySetting object
        """
        RegisterSettingTypes(oKivySetting)
        aSections = self.oConfigParser.sections()
        if len(aSections) == 0:
            self.CreateSection(uSectionName=self.uDefaultConfigName)

        for uSection in aSections:
            # the Section list should be applied as a orca var
            SetVar(uVarName=u'ScriptConfigSection', oVarValue=uSection)
            # Let create a new temporary cSetting object to not harm the existing ones
            oSetting = self.oScript.cScriptSettings(self.oScript)
            # Read the ini file for this section
            oSetting.ReadConfigFromIniFile(uSection)
            # Create the setting string
            dSettingsJSON = self.CreateSettingJsonCombined(oSetting=oSetting)
            uSettingsJSON = SettingDictToString(dSettingsJSON)
            uSettingsJSON = ReplaceVars(uSettingsJSON)
            oSetting = None

            # if there is nothing to configure, then return
            if uSettingsJSON == u'{}':
                Globals.oNotifications.SendNotification('closesetting_script')
                return False

            # add the jSon to the Kivy Setting
            oKivySetting.add_json_panel(uSection,
                                        self.oConfigParser,
                                        data=uSettingsJSON)

        # Adds the action handler
        oKivySetting.bind(on_config_change=self.On_ConfigChange)
        return oKivySetting

    def On_ConfigChange(self, oSettings, oConfig, uSection, uKey, uValue):
        """ reacts, if user changes a setting """
        if uKey == u'configchangebuttons':
            self.uCurrentSection = uSection
            if uValue == u'button_add':
                SetVar(uVarName=u'SCRIPTINPUT', oVarValue=u'DEVICE_dummy')
                self.oInputKeyboard = ShowKeyBoard(u'SCRIPTINPUT',
                                                   self.On_InputAdd)
            if uValue == u'button_delete':
                ShowQuestionPopUp(
                    uTitle=u'$lvar(5003)',
                    uMessage=u'Do you really want to delete this setting?',
                    fktYes=self.On_InputDel,
                    uStringYes=u'$lvar(5001)',
                    uStringNo=u'$lvar(5002)')
            if uValue == u'button_rename':
                SetVar(uVarName=u'SCRIPTINPUT', oVarValue=uSection)
                self.oInputKeyboard = ShowKeyBoard(u'SCRIPTINPUT',
                                                   self.On_InputRen)
        else:
            oSetting = self.oScript.GetSettingObjectForConfigName(
                uConfigName=uSection)
            oSetting.aScriptIniSettings[uKey] = uValue

    def On_InputAdd(self, uInput):
        """ User pressed the add configuration button """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser.add_section(uInput)
        # self.InitializeSection(uInput)
        self.oConfigParser.write()
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Scriptsettings'
        }])
        self.ShowSettings()

    def On_InputDel(self):
        """ User pressed the del configuration button """
        self.oConfigParser.remove_section(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def On_InputRen(self, uInput):
        """ User pressed the rename configuration button """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser._sections[uInput] = self.oConfigParser._sections[
            self.uCurrentSection]
        self.oConfigParser._sections.pop(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def ShowSettings(self):
        """ Shows the settings page """
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Scriptsettings'
        }])

    def GetSettingParFromVar2(self, uScriptName, uConfigName, uSettingParName):
        """
        Gets a Value for a setting parameter from the orca vars
        The Orca vars fpr the parameter are automatically set in the cInterfaceMonitoredSettings class

        :rtype: string
        :param uScriptName: The name of script to use
        :param uConfigName: The nemae of the Config
        :param uSettingParName: The name of the parameter
        :return: The value of the parameter
        """

        return GetVar(uVarName="CONFIG_" + uSettingParName.upper(),
                      uContext=uScriptName + u'/' + uConfigName)

    def CreateSettingJsonCombined(self, oSetting):
        """
        Creates a json dict which holds all the setting defintions of
        the core interface plus the settinmgs from the discover script (if requested)

        :rtype: dict
        :param cBaseInterFaceSettings oSetting: an IterFaceSettins Object
        :return: a dict of combined settings
        """

        if len(self.dSettingsCombined) != 0:
            return self.dSettingsCombined
        dRet = {}

        for uKey in self.dDefaultSettings:
            if self.dDefaultSettings[uKey]["active"] != "disabled":
                dRet[uKey] = self.dDefaultSettings[uKey]

        dScriptJSON = self.oScript.GetConfigJSON()
        for uKey in dScriptJSON:
            dLine = dScriptJSON[uKey]
            iOrder = dLine['order']
            for uKey2 in dRet:
                if dRet[uKey2]['order'] >= iOrder:
                    dRet[uKey2]['order'] += 1
            dRet[uKey] = dLine

        self.dSettingsCombined = dRet
        return dRet
Esempio n. 19
0
class MangoPaint(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Blue'
    title = 'Mango Paint'
    icon = 'Screens/resources/imgs/mango.jpg'
    screen = ObjectProperty(None)
    lang = StringProperty('en')

    # 해당 클래스가 객체화될때 구동되는 섹션으로 관련된 컴포넌트들을 활성화시켜서 실제 running 되기 직전까지 만들어놓음.
    def __init__(self, **kwargs):
        super(MangoPaint, self).__init__(**kwargs)
        Window.bind(on_keybord=self.events_program)
        Window.soft_input_mode = 'below_target'

        self.list_previous_screens = ['gallery']
        self.window = Window
        self.config = ConfigParser()
        self.manager = None
        self.window_language = None
        self.exit_interval = False
        self.name_program = sets.string_lang_title
        self.sets = sets

        self.dict_language = literal_eval(
            open(os.path.join(self.directory, 'Libs', 'locales',
                              'locales.txt')).read())

        self.translation = Translation(
            self.lang, 'Ttest', os.path.join(self.directory, 'Libs',
                                             'locales'))

    # application 레벨 설정값 정보 관리
    def get_application_config(self):
        return super(MangoPaint, self).get_application_config(
            '{}/Libs/mangopaint.ini'.format(self.directory))

    def set_value_from_config(self):
        ''' mangopaint.ini 로 셋팅값 넣기 '''
        self.config.read(os.path.join(self.directory, 'Libs/mangopaint.ini'))
        self.lang = self.config.get('General', 'language')

    def build_config(self, config):
        ''' mangopaint.ini 기본 설정값 만들기 '''
        config.adddefaultsection('General')
        config.setdefault('General', 'language', 'English')

    # build 는 App 클래스에서는 App.run()으로 invoke 되며, 메인프로그램을 스타트 시킴.
    # 단, 일반 프로그램은 build 함수를 만들지 않는다.
    def build(self):
        # mangopaint.ini 의 저장된 설정값들을 셋팅하기
        self.set_value_from_config()
        self.title = sets.string_lang_title[:-1]
        self.icon = "Screens/resources/icons/logo.png"
        self.load_all_kv_files(os.path.join(self.directory, 'Screens'))
        # 메인 베이스가 되는 화면, 각 서브화면들은 screenmanager 로 switch 하면서 사용함
        self.start_screen = StartScreen(title_previous=self.name_program,
                                        events_callback=self.events_program,
                                        sets=sets)
        self.screen = self.start_screen
        self.manager = self.screen.ids.root_manager
        self.nav_drawer = self.screen.ids.nav_drawer
        return self.screen

    def load_all_kv_files(self, directory_kv_files):
        # i = 0
        print('kv-files: ', os.listdir(directory_kv_files))
        for kv_file in os.listdir(directory_kv_files):
            kv_file = os.path.join(directory_kv_files, kv_file)
            # i = i+1
            # print('==========================================================')
            # print('kv-file: ', str(i), ': ', kv_file)
            if os.path.isfile(kv_file):
                with open(kv_file, encoding='utf-8') as kv:
                    _kv = kv.read()
                    Builder.load_string(_kv)
                    # print(_kv)  # kivy 파일들 syntax 오류 점검시 필요

    # 분기 프로그램 with events_callback로 함수를 파라미터로 전달하여 구동
    # 연계할 프로그램명을 호출하고 연이어 프로그램명.kv 까지 동작시킬 터널을 뚫은 후,
    # kv파일의 on-이벤트의 events_callback에 파리미터로 전달할 프로그램명을 기술하여
    # 최종 원하는 프로그램을 기동할수 있도록 하는 패턴함수임.
    def events_program(self, *args):
        '''프로그램 이벤트 처리'''
        print(args)
        if len(args) == 2:  # url 사용시
            event = args[1]
        else:  # 프로그램 버튼 클릭시
            try:
                _args = args[0]
                event = _args if isinstance(_args, str) else str(_args) if \
                    isinstance(_args, dict) else _args.id
            except AttributeError:
                event = args[1]

        # if PY2:
        #     if isinstance(event, unicode):
        #         event = event.encode('utf-8')

        if event == sets.string_lang_exit_key:
            self.exit_program()
        elif event == sets.string_lang_exit_key:
            self.exit_program()
        elif event == sets.string_lang_license:
            self.show_license()
        elif event == 'search_shop':
            self.search_shop()
        elif event == 'navigation_drawer':
            self.navigation_drawer.toggle_state()
        elif event in (1001, 27):
            self.back_screen(event=keyboard)
        return True

    def show_gallery(self, *args):
        print('show_gallery2')
        self.nav_drawer._toggle()
        self.manager.current = 'gallery'
        return self.screen

    def show_effect(self, *args):
        print('show_effect2')
        self.nav_drawer._toggle()
        self.manager.current = 'effects'
        return self.screen

    def show_mystudio(self, *args):
        print('show_mystudio2')
        pass

    def show_community(self, *args):
        print('show_community2')
        pass

    def show_purchase(self, *args):
        print('show_purchase2')
        pass

    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.title = \
        #     self.translation._('MIT LICENSE')

    def show_about(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.screen.ids.about.ids.label.text = \
            self.translation._(
                u'[size=20][b]MangoPaint[/b][/size]\n\n'
                u'[b]Version:[/b] {version}\n'
                u'[b]License:[/b] MIT License\n\n'
                u'[size=20][b]mangoPaint develop Team.[/b][/size]\n\n'
                u'[ref=www.miraelabs.com]'
                u'[color={link_color}]mango-saam, susan han, JM, \n Yoo Jung, Taeyoon Lee, 손정현 [/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'

    def select_locale(self, *args):
        '''사용 가능한 언어 locale 이  있는 창을 표시합니다.
        응용 프로그램 언어 설정.'''
        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 back_screen(self, event=None):
        if event in (1001, 27):
            if self.manager.current == 'gallery':
                self.dialog_exit()
                return
            try:
                self.manager.current = self.list_previous_screens.pop()
            except:
                self.manager.current = 'gallery'
            self.screen.ids.action_bar.title = self.title
            self.screen.ids.action_bar.left_action_items = \
                [['menu', lambda x: self.nav_drawer._toggle()]]

    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 on_pause(self):
        ''' 이렇게 하면 응용 프로그램이 '일시 중지'로 표시됩니다.
        그렇지 않으면 프로그램 시작 다시 '''
        return True

    def on_resume(self):
        print('on_resume')

    def on_stop(self):
        print('on_stop')

    def exit_program(self, *args):
        def dismiss(*args):
            self.open_dialog = False

        def answer_callback(answer):
            if answer == sets.string_lang_yes:
                sys.exit(0)
            dismiss()

        if not self.open_dialog:
            KDialog(answer_callback=answer_callback,
                    on_dismiss=dismiss,
                    separator_color=sets.separator_color,
                    title_color=get_color_from_hex(
                        sets.theme_text_black_color),
                    title=self.name_program).show(
                        text=sets.string_lang_exit.format(
                            sets.theme_text_black_color),
                        text_button_ok=sets.string_lang_yes,
                        text_button_no=sets.string_lang_no,
                        param='query',
                        auto_dismiss=True)
            self.open_dialog = True
Esempio n. 20
0
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)
Esempio n. 21
0
class DesignerSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''
    def __init__(self, **kwargs):
        super(DesignerSettings, self).__init__(*kwargs)
        self.register_type('list', SettingList)

    def load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser(name='DesignerSettings')
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(),
                                       DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)

        # creates a panel before insert it to update code input theme list
        panel = self.create_json_panel(
            'Kivy Designer Settings', self.config_parser,
            os.path.join(_dir, 'designer', 'settings',
                         'designer_settings.json'))
        uid = panel.uid
        if self.interface is not None:
            self.interface.add_panel(panel, 'Kivy Designer Settings', uid)

        # loads available themes
        for child in panel.children:
            if child.id == 'code_input_theme_options':
                child.items = styles.get_all_styles()

        # tries to find python and buildozer path if it's not defined
        path = self.config_parser.getdefault('global', 'python_shell_path', '')

        if path.strip() == '':
            self.config_parser.set('global', 'python_shell_path',
                                   sys.executable)
            self.config_parser.write()

        buildozer_path = self.config_parser.getdefault('buildozer',
                                                       'buildozer_path', '')

        if buildozer_path.strip() == '':
            buildozer_path = find_executable('buildozer')
            if buildozer_path:
                self.config_parser.set('buildozer', 'buildozer_path',
                                       buildozer_path)
                self.config_parser.write()

        self.add_json_panel(
            'Buildozer', self.config_parser,
            os.path.join(_dir, 'designer', 'settings',
                         'buildozer_settings.json'))
        self.add_json_panel(
            'Hanga', self.config_parser,
            os.path.join(_dir, 'designer', 'settings', 'hanga_settings.json'))

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
class DesignerSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def __init__(self, **kwargs):
        super(DesignerSettings, self).__init__(*kwargs)
        self.register_type('list', SettingList)
        self.register_type('shortcut', SettingShortcut)

    def load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser(name='DesignerSettings')
        DESIGNER_CONFIG = os.path.join(get_config_dir(),
                                       DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG,
                            DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)

        # creates a panel before insert it to update code input theme list
        panel = self.create_json_panel('Kivy Designer Settings',
                                        self.config_parser,
                            os.path.join(_dir, 'designer',
                                         'settings', 'designer_settings.json'))
        uid = panel.uid
        if self.interface is not None:
            self.interface.add_panel(panel, 'Kivy Designer Settings', uid)

        # loads available themes
        for child in panel.children:
            if child.id == 'code_input_theme_options':
                child.items = styles.get_all_styles()

        # tries to find python and buildozer path if it's not defined
        path = self.config_parser.getdefault(
            'global', 'python_shell_path', '')

        if path.strip() == '':
            self.config_parser.set('global', 'python_shell_path',
                                   sys.executable)
            self.config_parser.write()

        buildozer_path = self.config_parser.getdefault('buildozer',
                                                       'buildozer_path', '')

        if buildozer_path.strip() == '':
            buildozer_path = find_executable('buildozer')
            if buildozer_path:
                self.config_parser.set('buildozer',
                                       'buildozer_path',
                                        buildozer_path)
                self.config_parser.write()

        self.add_json_panel('Buildozer', self.config_parser,
                            os.path.join(_dir, 'designer', 'settings',
                                         'buildozer_settings.json'))
        self.add_json_panel('Hanga', self.config_parser,
                            os.path.join(_dir, 'designer', 'settings',
                                         'hanga_settings.json'))
        self.add_json_panel('Keyboard Shortcuts', self.config_parser,
                            os.path.join(_dir, 'designer', 'settings',
                                         'shortcuts.json'))

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
Esempio n. 23
0
class name_project(App):
    '''Функционал программы.'''

    title = 'name_project'
    icon = 'icon.png'
    nav_drawer = ObjectProperty()
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Blue'
    lang = StringProperty('en')

    def __init__(self, **kvargs):
        super(name_project, 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(name_project, self).get_application_config(
                        '{}/%(appname)s.ini'.format(self.directory))

    def build_config(self, config):
        '''Создаёт файл настроек приложения name_project.ini.'''

        config.adddefaultsection('General')
        config.setdefault('General', 'language', 'en')

    def set_value_from_config(self):
        '''Устанавливает значения переменных из файла настроек name_project.ini.'''

        self.config.read(os.path.join(self.directory, 'name_project.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]name_project[/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_on_github]'
                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)
Esempio n. 24
0
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=(',', ': '))
Esempio n. 25
0
class name_project(App):
    title = 'TalantA'
    icon = 'icon.png'
    nav_drawer = ObjectProperty()
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Brown'
    lang = StringProperty('en')

    def __init__(self, **kvargs):
        super(name_project, 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(name_project, 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, 'name_project.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.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.nav_drawer.toggle_nav_drawer()
                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_about(self, *args):
        self.nav_drawer.toggle_nav_drawer()

        self.manager.current = 'about'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_help(self, *args):
        self.nav_drawer.toggle_nav_drawer()

        self.manager.current = 'helper'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_browse_art(self, *args):
        self.nav_drawer.toggle_nav_drawer()

        self.manager.current = 'browse'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def toggle_nav(self, *args):
        self.nav_drawer.toggle_nav_drawer()

    def show_account(self, *args):
        self.nav_drawer.toggle_nav_drawer()

        self.manager.current = 'account'
        self.screen.ids.action_bar.left_action_items = \
        [['chevron-left', lambda x: self.back_screen(27)]]

    def show_sign_up(self, *args):
        #self.nav_drawer.toggle_nav_drawer()

        self.manager.current = 'signup'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.show_login()]]

    def show_login(self, *args):
        # self.nav_drawer.toggle_nav_drawer()

        self.manager.current = 'login'
        self.screen.ids.action_bar.left_action_items = []

    def show_events(self, *args):
        self.manager.current = 'browse_gallery'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    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)
Esempio n. 26
0
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)
Esempio n. 27
0
class cInterFaceConfig(object):
    """ Class to manage the initialisation/configuration and access toe the settings of an Interface settings objects

    """
    def __init__(self, oInterFace):
        self.oInterFace = oInterFace
        self.oConfigParser = KivyConfigParser()
        self.oFnConfig = None
        self.uCurrentSection = None
        self.uDefaultConfigName = u'DEVICE_DEFAULT'
        self.aDiscoverScriptList = None
        self.oInputKeyboard = None
        self.dDefaultSettings = {
            "SettingTitle": {
                "active": "enabled",
                "order": 0,
                "type": "title",
                "title": "$lvar(560)"
            },
            "Host": {
                "active": "disabled",
                "order": 1,
                "type": "string",
                "title": "$lvar(6004)",
                "desc": "$lvar(6005)",
                "section": "$var(InterfaceConfigSection)",
                "key": "Host",
                "default": "192.168.1.2"
            },
            "Port": {
                "active": "disabled",
                "order": 2,
                "type": "string",
                "title": "$lvar(6002)",
                "desc": "$lvar(6003)",
                "section": "$var(InterfaceConfigSection)",
                "key": "Port",
                "default": "80"
            },
            "User": {
                "active": "disabled",
                "order": 3,
                "type": "string",
                "title": "$lvar(6006)",
                "desc": "$lvar(6007)",
                "section": "$var(InterfaceConfigSection)",
                "key": "User",
                "default": "root"
            },
            "Password": {
                "active": "disabled",
                "order": 4,
                "type": "string",
                "title": "$lvar(6008)",
                "desc": "$lvar(6009)",
                "section": "$var(InterfaceConfigSection)",
                "key": "Password",
                "default": ""
            },
            "FNCodeset": {
                "active": "disabled",
                "order": 5,
                "type": "scrolloptions",
                "title": "$lvar(6000)",
                "desc": "$lvar(6001)",
                "section": "$var(InterfaceConfigSection)",
                "key": "FNCodeset",
                "default": "Select",
                "options": ["$var(InterfaceCodesetList)"]
            },
            "ParseResult": {
                "active": "disabled",
                "order": 6,
                "type": "scrolloptions",
                "title": "$lvar(6027)",
                "desc": "$lvar(6028)",
                "section": "$var(InterfaceConfigSection)",
                "key": "ParseResult",
                "default": "store",
                "options": ["no", "tokenize", "store", "json", "dict", "xml"]
            },
            "TokenizeString": {
                "active": "disabled",
                "order": 7,
                "type": "string",
                "title": "$lvar(6029)",
                "desc": "$lvar(6030)",
                "section": "$var(InterfaceConfigSection)",
                "key": "TokenizeString",
                "default": ":"
            },
            "TimeOut": {
                "active": "disabled",
                "order": 8,
                "type": "numericfloat",
                "title": "$lvar(6019)",
                "desc": "$lvar(6020)",
                "section": "$var(InterfaceConfigSection)",
                "key": "TimeOut",
                "default": "1.0"
            },
            "TimeToClose": {
                "active": "disabled",
                "order": 9,
                "type": "numeric",
                "title": "$lvar(6010)",
                "desc": "$lvar(6011)",
                "section": "$var(InterfaceConfigSection)",
                "key": "TimeToClose",
                "default": "10"
            },
            "DisableInterFaceOnError": {
                "active": "disabled",
                "order": 10,
                "type": "bool",
                "title": "$lvar(529)",
                "desc": "$lvar(530)",
                "section": "$var(InterfaceConfigSection)",
                "key": "DisableInterFaceOnError",
                "default": "0"
            },
            "DisconnectInterFaceOnSleep": {
                "active": "disabled",
                "order": 11,
                "type": "bool",
                "title": "$lvar(533)",
                "desc": "$lvar(534)",
                "section": "$var(InterfaceConfigSection)",
                "key": "DisconnectInterFaceOnSleep",
                "default": "1"
            },
            "DiscoverSettingButton": {
                "active":
                "disabled",
                "order":
                12,
                "type":
                "buttons",
                "title":
                "$lvar(6033)",
                "desc":
                "$lvar(6034)",
                "section":
                "$var(InterfaceConfigSection)",
                "key":
                "DiscoverSettings",
                "buttons": [{
                    "title": "Discover Settings",
                    "id": "button_discover"
                }]
            },
            "ConfigChangeButtons": {
                "active":
                "enabled",
                "order":
                999,
                "type":
                "buttons",
                "title":
                "$lvar(565)",
                "desc":
                "$lvar(566)",
                "section":
                "$var(InterfaceConfigSection)",
                "key":
                "configchangebuttons",
                "buttons": [{
                    "title": "$lvar(569)",
                    "id": "button_add"
                }, {
                    "title": "$lvar(570)",
                    "id": "button_delete"
                }, {
                    "title": "$lvar(571)",
                    "id": "button_rename"
                }]
            }
        }

        self.dGenericDiscoverSettings = {
            "DiscoverScriptName": {
                "active": "hidden",
                "order": 100,
                "scriptsection": "$lvar(539)",
                "type": "scrolloptions",
                "title": "$lvar(6035)",
                "desc": "$lvar(6036)",
                "section": "$var(InterfaceConfigSection)",
                "key": "DiscoverScriptName",
                "default": "",
                "options": ["$var(DISCOVERSCRIPTLIST)"]
            },
            "SaveDiscoveredIP": {
                "active": "hidden",
                "order": 101,
                "scriptsection": "$lvar(539)",
                "type": "bool",
                "title": "$lvar(6031)",
                "desc": "$lvar(6032)",
                "section": "$var(InterfaceConfigSection)",
                "key": "SaveDiscoveredIP",
                "default": "1"
            },
            "OldDiscoveredIP": {
                "active": "hidden",
                "order": 102,
                "scriptsection": "$lvar(539)",
                "type": "string",
                "title": "$lvar(6021)",
                "desc": "$lvar(6022)",
                "section": "$var(InterfaceConfigSection)",
                "key": "OldDiscoveredIP",
                "default": ""
            },
            "CheckDiscoverButton": {
                "active":
                "disabled",
                "order":
                103,
                "scriptsection":
                "$lvar(539)",
                "type":
                "buttons",
                "title":
                "Check Discover",
                "desc":
                "$lvar(6034)",
                "section":
                "$var(InterfaceConfigSection)",
                "key":
                "CheckDiscover",
                "buttons": [{
                    "title": "Check Discover",
                    "id": "button_checkdiscover"
                }]
            },
        }
        self.dSettingsCombined = {}

    def Init(self):
        """ Init function, sets the configuration file name and add the default sections """

        self.oFnConfig = cFileName(self.oInterFace.oPathMy) + u'config.ini'
        if not self.oFnConfig.Exists():
            self.CreateSection(uSectionName=self.uDefaultConfigName)

    def LoadConfig(self):
        """ Loads the config file (only once) """

        try:
            self.oConfigParser.filename = self.oFnConfig.string
            if len(self.oConfigParser._sections) == 0:
                if self.oFnConfig.Exists():
                    self.oInterFace.ShowDebug(u'Reading Config File')
                    self.oConfigParser.read(self.oFnConfig.string)
            else:
                if not self.oFnConfig.Exists():
                    self.oConfigParser.write()
        except Exception as e:
            self.oInterFace.ShowError(
                u"can\'t load config file: %s" % self.oFnConfig.string, None,
                e)

    def CreateSection(self, uSectionName):
        """
        Adds a new section to the config parser

        :param string uSectionName: The name of the section to create
        """

        self.oInterFace.ShowDebug('Adding new section [%s]' % (uSectionName))
        self.oConfigParser.add_section(uSectionName)
        self.oConfigParser.write()

    def GetSettingParFromIni(self, uSectionName, uVarName):
        """
        Returns a setting for the configuration ini file
        If the entry does not exist, it tries to puls the value from the  aInterFaceIniSettings dict of already predifined settings
        If not exist there as well, an error will be logged

        :rtype: string|None
        :param string uSectionName: The name of the section
        :param uVarName: The name of the parameter/setting in the section
        :return: The value of the setting, empty string if not found
         """

        oSetting = self.oInterFace.GetSettingObjectForConfigName(uSectionName)
        uResult = Config_GetDefault_Str(self.oConfigParser, uSectionName,
                                        uVarName, None)
        if uResult is None:
            uResult = str(oSetting.aInterFaceIniSettings.queryget(uVarName))
        if uResult is None:
            uResult = ''
            self.oInterFace.ShowError(u'can\'t find interface setting: %s:%s' %
                                      (uSectionName, uVarName))
        else:
            self.oInterFace.ShowDebug(
                u'Returning interface setting: %s from %s:%s' %
                (uResult, uSectionName, uVarName))
        return uResult

    def WriteDefinitionConfigPar(self,
                                 uSectionName,
                                 uVarName,
                                 uVarValue,
                                 bNowrite=False,
                                 bForce=False):
        """ Writes a variable to the config file
        :param string uSectionName: The name of the section
        :param string uVarName: The name of the parameter/setting in the section
        :param string uVarValue: The value for the setting
        :param bool bNowrite: Flag, if we should not immidiatly write the the setting
        :param bool bForce: Flag to force write, even if parameter exists in config
        """
        self.LoadConfig()
        if not self.oConfigParser.has_section(uSectionName):
            self.CreateSection(uSectionName=uSectionName)

        if self.oConfigParser.has_option(uSectionName, uVarName):
            if not bForce:
                return

        self.oConfigParser.set(uSectionName, uVarName, uVarValue)
        if not bNowrite:
            self.oConfigParser.write()

        for uSettingName in self.oInterFace.aSettings:
            oSetting = self.oInterFace.aSettings[uSettingName]
            if oSetting.uConfigName == uSectionName:
                oSetting.aInterFaceIniSettings[uVarName] = uVarValue
                break

    def WriteDefinitionConfig(self, uSectionName, dSettings):
        """
        writes all vars given in a dictionary to the config file

        :param string uSectionName: The name of the section
        :param dict dSettings: A dict of all settings to write
        """

        for uKey in dSettings:
            self.WriteDefinitionConfigPar(uSectionName=uSectionName,
                                          uVarName=uKey,
                                          uVarValue=dSettings[uKey],
                                          bNowrite=True)
        self.oConfigParser.write()

    def ConfigureKivySettings(self, oKivySetting):
        """
        Create the JSON string for all sections and applies it to a kivy settings object
        Discover settings are excluded

        :param setting oKivySetting:
        :return: The KivySetting object
        """
        RegisterSettingTypes(oKivySetting)
        aSections = self.oConfigParser.sections()
        if len(aSections) == 0:
            self.CreateSection(uSectionName=self.uDefaultConfigName)

        # The Codeset List could be applied as a orca var, so set it to the list
        SetVar(uVarName=u'InterfaceCodesetList',
               oVarValue=self.oInterFace.CreateCodsetListJSONString())

        for uSection in aSections:
            # the Section list should be applied as a orca var
            SetVar(uVarName=u'InterfaceConfigSection', oVarValue=uSection)
            # Let create a new temporary cSetting object to not harm the existing ones
            oSetting = self.oInterFace.cInterFaceSettings(self.oInterFace)
            # Read the ini file for this section
            oSetting.ReadConfigFromIniFile(uSection)
            # Create the setting string
            dSettingsJSON = self.CreateSettingJsonCombined(
                oSetting=oSetting, bIncludeDiscoverSettings=False)
            uSettingsJSON = SettingDictToString(dSettingsJSON)
            uSettingsJSON = ReplaceVars(uSettingsJSON)
            oSetting = None

            # if there is nothing to configure, then return
            if uSettingsJSON == u'{}':
                Globals.oNotifications.SendNotification(
                    'closesetting_interface')
                return False

            # add the jSon to the Kivy Setting
            oKivySetting.add_json_panel(uSection,
                                        self.oConfigParser,
                                        data=uSettingsJSON)

        # Adds the action handler
        oKivySetting.bind(on_config_change=self.On_ConfigChange)
        return oKivySetting

    def On_ConfigChange(self, oSettings, oConfig, uSection, uKey, uValue):
        """
        reacts, if user changes a setting

        :param setting oSettings: The kivy settings object
        :param ConfigParser oConfig: The Kivy config parser
        :param string uSection: The section of the change
        :param string uKey: The key name
        :param string uValue: The value
        """
        if uKey == u'configchangebuttons':
            self.uCurrentSection = uSection
            if uValue == u'button_add':
                SetVar(uVarName=u'INTERFACEINPUT', oVarValue=u'DEVICE_dummy')
                self.oInputKeyboard = ShowKeyBoard(u'INTERFACEINPUT',
                                                   self.On_InputAdd)
            if uValue == u'button_delete':
                ShowQuestionPopUp(
                    uTitle=u'$lvar(5003)',
                    uMessage=u'Do you really want to delete this setting?',
                    fktYes=self.On_InputDel,
                    uStringYes=u'$lvar(5001)',
                    uStringNo=u'$lvar(5002)')
            if uValue == u'button_rename':
                SetVar(uVarName=u'INTERFACEINPUT', oVarValue=uSection)
                self.oInputKeyboard = ShowKeyBoard(u'INTERFACEINPUT',
                                                   self.On_InputRen)
        elif uKey == u'DiscoverSettings':
            Globals.oTheScreen.uConfigToConfig = uSection
            Globals.oTheScreen.AddActionShowPageToQueue(
                uPageName=u'Page_InterfaceSettingsDiscover')
        elif uKey == u'FNCodeset':
            oSetting = self.oInterFace.GetSettingObjectForConfigName(
                uConfigName=uSection)
            oSetting.aInterFaceIniSettings[uKey] = uValue
            oSetting.ReadCodeset()
        else:
            oSetting = self.oInterFace.GetSettingObjectForConfigName(
                uConfigName=uSection)
            oSetting.aInterFaceIniSettings[uKey] = uValue
            # ShowMessagePopUp(uMessage=u'$lvar(5011)')
            if uKey == u'FNCodeset':
                oSetting.ReadCodeset()

    def On_InputAdd(self, uInput):
        """
        User pressed the add configuration button

        :param string uInput: The Name of the section
        :return:
        """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser.add_section(uInput)
        self.oConfigParser.write()
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Interfacesettings'
        }])
        self.ShowSettings()

    def On_InputDel(self):
        """ User pressed the del configuration button """
        self.oConfigParser.remove_section(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def On_InputRen(self, uInput):
        """ User pressed the rename configuration button """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser._sections[uInput] = self.oConfigParser._sections[
            self.uCurrentSection]
        self.oConfigParser._sections.pop(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def ShowSettings(self):
        """ Shows the settings page """
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Interfacesettings'
        }])

    def GetSettingParFromVar2(self, uInterFaceName, uConfigName,
                              uSettingParName):
        """
        Gets a Value for a setting parameter from the orca vars
        The Orca vars fpr the parameter are automatically set in the cInterfaceMonitoredSettings class

        :rtype: string
        :param uInterFaceName: The name of interface to use
        :param uConfigName: The nemae of the Config
        :param uSettingParName: The name of the parameter
        :return: The value of the parameter
        """

        return GetVar(uVarName="CONFIG_" + uSettingParName.upper(),
                      uContext=uInterFaceName + u'/' + uConfigName)

    def GetSettingParFromVar(self, uLink):
        """
        Returns a setting var of a an other interface or config
        The Interfca emust already be initalized
        syntax should be: linked:interfacename:configname:varname

        :rtype: string
        :param string uLink: The link: syntax should be: linked:interfacename:configname:varname
        :return: The Value of the linked setting, empty string, if not found
        """

        aLinks = uLink.split(':')
        if len(aLinks) == 4:
            uInterFaceName = aLinks[1]
            uConfigName = aLinks[2]
            uSettingParName = aLinks[3]
            Globals.oInterFaces.LoadInterface(uInterFaceName)
            oInterface = Globals.oInterFaces.GetInterface(uInterFaceName)
            oSetting = oInterface.GetSettingObjectForConfigName(
                uConfigName=uConfigName)
            oSetting.Discover()
            return self.GetSettingParFromVar2(uInterFaceName=uInterFaceName,
                                              uConfigName=uConfigName,
                                              uSettingParName=uSettingParName)
        return ""

    def CreateSettingJsonCombined(self,
                                  oSetting,
                                  bIncludeDiscoverSettings=True):
        """
        Creates a json dict which holds all the setting defintions of
        the core interface plus the settings from the discover script (if requested)

        :rtype: dict
        :param cBaseInterFaceSettings oSetting: an IterFaceSettins Object
        :param bool bIncludeDiscoverSettings: If we want to include the discover settings
        :return: a dict of combined settings
        """

        if len(self.dSettingsCombined) != 0:
            return self.dSettingsCombined
        dRet = {}

        for uKey in self.dDefaultSettings:
            if self.dDefaultSettings[uKey]["active"] != "disabled":
                dRet[uKey] = self.dDefaultSettings[uKey]

        dInterFaceJSON = self.oInterFace.GetConfigJSON()
        for uKey in dInterFaceJSON:
            dLine = dInterFaceJSON[uKey]
            iOrder = dLine['order']
            for uKey2 in dRet:
                if dRet[uKey2]['order'] >= iOrder:
                    dRet[uKey2]['order'] += 1
            dRet[uKey] = dLine

        if 'DiscoverSettingButton' in dRet and bIncludeDiscoverSettings:
            dRet.update(self.dGenericDiscoverSettings)
            if self.aDiscoverScriptList is None:
                self.aDiscoverScriptList = Globals.oScripts.GetScriptListForScriptType(
                    "DEVICE_DISCOVER")
            iLastOrder = 200
            for uDiscoverScriptName in self.aDiscoverScriptList:
                oScript = Globals.oScripts.LoadScript(uDiscoverScriptName)
                dScriptJSONSettings = oScript.cScript.GetConfigJSONforParameters(
                    oSetting.aInterFaceIniSettings)
                iMax = 0
                for uKey in dScriptJSONSettings:
                    uTempKey = uDiscoverScriptName + "_" + uKey
                    dRet[uTempKey] = dScriptJSONSettings[uKey]
                    dRet[uTempKey]['key'] = uDiscoverScriptName.upper(
                    ) + "_" + dScriptJSONSettings[uKey]['key']
                    dRet[uTempKey]['scriptsection'] = uDiscoverScriptName
                    dRet[uTempKey]['active'] = 'hidden'
                    iOrder = dRet[uTempKey]['order']
                    iMax = max(iMax, iOrder)
                    dRet[uTempKey]['order'] = iOrder + iLastOrder

                iLastOrder += iMax
        self.dSettingsCombined = dRet
        return dRet
Esempio n. 28
0
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)
Esempio n. 29
0
class MainApp(App):
    def __init__(self, *args, **kwargs):
        super(MainApp, self).__init__(*args, **kwargs)
        self.logger = logging.getLogger('kivy.operator.app')
        if not os.path.isdir("/sdcard/operator"):
            os.makedirs("/sdcard/operator")
        self.map = None
        self.messaging = None
        self.xmpp_client = None
        self.user_location_markers = {}
        self._last_location_update = 0
        Window.bind(on_keyboard=self.on_back_btn)
        self.android_setflag()
        self.xmpp_config_ok = False
        self.start = True
        self.confirmation_popup = Popup()
        self.lock_btn_presses = []
        self.configuration = ConfigParser()
        self.configuration.read(CONFIG_PATH)
        self.check_config()

    def check_config(self):
        """
		Checks to see if the config has the required XMPP fields filled out accordingly.
		Then, it evaluates the config file to make sure that all fields exist, at least corresponding to the
		example config file.
		"""
        conf = self.configuration

        if conf.has_section('xmpp'):
            if all(
                    conf.has_option('xmpp', k) and conf.get('xmpp', k)
                    for k in MANDATORY_XMPP_OPTIONS):
                self.xmpp_config_ok = True

        def_conf = ConfigParser()
        def_conf.read(DEFAULT_CONFIG_PATH)

        for section in def_conf.sections():
            if conf.has_section(section):
                for option in def_conf.options(section):
                    if not conf.has_option(section, option) or conf.get(
                            section, option) is None:
                        conf.set(section, option,
                                 def_conf.get(section, option))
            else:
                conf.add_section(section)
                for option in def_conf.options(section):
                    conf.set(section, option, def_conf.get(section, option))

        self.configuration = conf
        self.configuration.write()

    def build(self):
        self.root = RootWidget()
        if self.xmpp_config_ok:
            self.xmpp_client = OperatorXMPPClient(
                sz_utils.parse_server(self.configuration.get('xmpp', 'server'),
                                      5222),
                self.configuration.get('xmpp', 'username'),
                self.configuration.get('xmpp', 'password'),
                self.configuration.get('xmpp', 'room'),
                self.configuration.getboolean('xmpp', 'filter'))
            self.xmpp_client.bind(
                on_user_location_update=self.on_user_location_update)
            self.xmpp_client.bind(on_message_receive=self.on_message_receive)
            self.xmpp_client.bind(on_muc_receive=self.on_muc_receive)
        else:
            self.logger.warning(
                "XMMP config invalid, disabling XMPP operations")

        self.map = self.root.ids.map_panel_widget.ids.map_widget
        self.messaging = self.root.ids.message_menu
        gps.configure(on_location=self.on_gps_location)
        gps.start()
        return self.root

    def on_back_btn(self, window, key, *args):
        """ To be called whenever user presses Back/Esc Key """
        # If user presses Back/Esc Key
        if key == 27:
            return self.root.on_back_btn()
        return False

    def build_config(self, config):
        # add default sections here
        default_sections = ('miscellaneous', 'xmpp')
        for section in default_sections:
            if not config.has_section:
                config.add_section(section)

        # load the custom configuration ini file
        custom_config = 'data/settings/config.ini'
        if os.path.isfile(custom_config):
            self.logger.info(
                'loading custom config: {0}'.format(custom_config))
            config.update_config(custom_config, overwrite=False)

    def build_settings(self, settings):
        settings.add_json_panel('XMPP', self.configuration,
                                'data/settings/xmpp.json')
        settings.add_json_panel('Map', self.configuration,
                                'data/settings/map.json')

    def on_message_receive(self, event, msg):
        self.messaging.on_message_receive(msg)

    def on_muc_receive(self, event, msg):
        self.messaging.on_muc_receive(msg)

    def on_gps_location(self, **kwargs):
        # kwargs on Galaxy S5 contain:
        #   altitude, bearing, lat, lon, speed
        if self.start:
            if self.xmpp_client:
                self.messaging.get_users()
            self.start = False
        if not ('lat' in kwargs and 'lon' in kwargs):
            return
        current_time = time.time()
        if current_time - self._last_location_update < self.configuration.getint(
                'miscellaneous', 'gps_update_freq'):
            return
        latitude = kwargs.pop('lat')
        longitude = kwargs.pop('lon')
        altitude = kwargs.pop('altitude', None)
        bearing = kwargs.pop('bearing', None)
        speed = kwargs.pop('speed', None)

        self.map.update_location((latitude, longitude), altitude, bearing,
                                 speed)
        if self.xmpp_client:
            self.xmpp_client.update_location((latitude, longitude), altitude,
                                             bearing, speed)
        self._last_location_update = current_time

    def get_users(self):
        return self.xmpp_client.get_users()

    def send_message(self, msg, user):
        self.xmpp_client.on_message_send(msg, user)

    def send_muc(self, msg, group):
        self.xmpp_client.on_muc_send(msg, group)

    def on_pause(self):
        return False

    def on_resume(self):
        pass

    def on_stop(self):
        self.map.save_marker_file()
        if self.xmpp_client:
            self.xmpp_client.shutdown()

    def on_user_location_update(self, _, info):
        if not self.map.is_ready:
            self.logger.warning('map is not ready for user marker')
            return
        user = info['user']
        if user in self.user_location_markers:
            self.user_location_markers[user].remove()
        if self.xmpp_client:
            user_mood = self.xmpp_client.user_moods.get(user, 'calm')
        icon_color = {
            'angry': 'red',
            'calm': 'yellow',
            'happy': 'green'
        }.get(user_mood, 'yellow')
        marker = self.map.create_marker(draggable=False,
                                        title=info['user'],
                                        position=info['location'],
                                        marker_color=icon_color)
        self.user_location_markers[user] = marker

    def toast_status(self):
        return self.configuration.getboolean('xmpp', 'toast_all')

    def xmpp_log(self, log_type, log):
        if log_type == 'info':
            self.xmpp_client.logger.info(log)

    def prompt_lock_screen(self):
        """
		Popup confirming with the user whether they want to lock the screen.
		"""
        confirmation_box = BoxLayout(orientation='vertical')
        confirmation_box.add_widget(
            Label(text='Do you want to lock the screen?'))
        box_int = BoxLayout(orientation='horizontal', spacing=50)
        affirm_button = Button(text='Yes')
        affirm_button.bind(on_release=lambda x: self.lock_screen())
        dismiss_button = Button(text='Cancel')
        dismiss_button.bind(
            on_release=lambda x: self.confirmation_popup.dismiss())
        box_int.add_widget(affirm_button)
        box_int.add_widget(dismiss_button)
        confirmation_box.add_widget(box_int)
        self.confirmation_popup = Popup(title='Confirmation',
                                        content=confirmation_box,
                                        size_hint=(.7, None),
                                        size=(500, 500),
                                        auto_dismiss=False)
        self.confirmation_popup.open()

    @run_on_ui_thread
    def lock_screen(self):
        """
		Lock the screen by going to a black layout and not allowing input. Will disable after 10 taps.
		"""
        self.confirmation_popup.dismiss()
        flag = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        PythonActivity.mActivity.getWindow().getDecorView(
        ).setSystemUiVisibility(flag)
        mb = True
        for child in self.root.walk():
            if hasattr(child, 'name'):
                if child.name == 'root' and mb:
                    self.removed = child
                    child.parent.remove_widget(child)
                    mb = False
        self.bl = BoxLayout(orientation='vertical')
        self.bl.add_widget(
            Button(size_hint=(1, 1),
                   background_color=[0, 0, 0, 1],
                   on_release=lambda x: self.lock_button()))
        self.root.add_widget(self.bl)

    def lock_button(self):
        """
		Registers clicks on the locked screen. Only counts clicks within 10 second gap.
		"""
        current_time = time.time()
        self.lock_btn_presses.append(current_time)
        while current_time - self.lock_btn_presses[
                0] > self.configuration.getint('miscellaneous',
                                               'lockout_timeout'):
            del self.lock_btn_presses[0]

        if len(self.lock_btn_presses) == self.configuration.getint(
                'miscellaneous', 'lockout_clicks'):
            self.root.remove_widget(self.bl)
            self.root.add_widget(self.removed)
            self.lock_btn_presses = []

    @run_on_ui_thread
    def android_setflag(self):
        PythonActivity.mActivity.getWindow().addFlags(
            Params.FLAG_KEEP_SCREEN_ON)

    def update_mood(self, mood):
        if self.xmpp_client:
            self.xmpp_client.update_mood(mood)
Esempio n. 30
0
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()
Esempio n. 31
0
class VKGroups(App, AuthorizationOnVK, GetAndSaveLoginPassword):
    '''Функционал программы.'''

    title = 'VKGroups'
    icon = 'icon.png'
    use_kivy_settings = False
    nav_drawer = ObjectProperty()
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'BlueGrey'
    lang = StringProperty('ru')

    def __init__(self, **kvargs):
        super(VKGroups, self).__init__(**kvargs)

        Window.bind(on_keyboard=self.events_program)

        self.POSSIBLE_FILES = \
            ['.png', '.jpg', '.jpeg', '.gif', '.zip', '.txt']
        self.DEVISE_ONLINE = {
            'mobile': 'desktop-mac',
            'computer': 'laptop',
            0: 'power'
        }

        self.PATTERN_WHOM_COMMENT = pattern_whom_comment
        self.PATTERN_REPLACE_LINK = pattern_replace_link

        self.window = Window
        self.config = ConfigParser()
        # Окно прогресса.
        self.load_dialog = ModalView(size_hint=(None, None),
                                     pos_hint={
                                         'x': 5.0 / Window.width,
                                         'y': 5.0 / Window.height
                                     },
                                     background_color=[0, 0, 0, .2],
                                     size=(dp(120), dp(50)),
                                     background=os.path.join(
                                         'data', 'images', 'decorator.png'),
                                     auto_dismiss=False)
        # Экземпляр для вывода списка плагинов пользователя.
        self.instance_list_user_plugins = ShowPlugins(self)
        # Файловый менеджер.
        self.window_file_manager = ModalView(
            size_hint=(1, 1),
            auto_dismiss=False,
            on_open=lambda x: self.load_dialog.dismiss())
        self.window_file_manager_open = False
        self.file_manager = FileManager(
            exit_manager=self.exit_manager,
            floating_button_color=self.theme_cls.primary_color)
        self.window_file_manager.add_widget(self.file_manager)

        self.current_screen_tab = None
        self.current_tab_manager = None
        self.name_press_tab = 'Home_page'
        self.file_manager_not_opening = True
        self.password_form = None
        self.box_posts = None
        self.attach_file = []
        self.attach_image = []
        self.box_for_attach_file = None
        self.box_for_attach_image = None
        self.group_info = None
        self.result_sending_post = None
        self.exit_interval = False
        self.flag_attach = ''
        self.window_user_groups = None
        self.window_language = None
        self.path_to_avatar = os.path.join(self.directory, 'data', 'images',
                                           'avatar.png')
        self.dict_language = ast.literal_eval(
            open(os.path.join(self.directory, 'data', 'locales',
                              'locales')).read())

    def get_application_config(self):
        return super(VKGroups, self).get_application_config(
            '{}/%(appname)s.ini'.format(self.directory))

    def build_config(self, config):
        '''Создаёт файл настроек приложения vkgroups.ini.'''

        config.adddefaultsection('General')
        config.setdefault('General', 'language', 'ru')
        config.setdefault('General', 'theme', 'default')
        config.setdefault('General', 'authorization', 0)
        config.setdefault('General', 'issues_in_group', 0)
        config.setdefault('General', 'count_issues', 20)
        config.setdefault('General', 'user_name', 'User')
        config.setdefault('General', 'last_group', '99411738')
        config.setdefault('General', 'regdata',
                          "{'login': None, 'password': None}")
        config.setdefault('General', 'last_screen', 'load screen')
        config.setdefault('General', 'last_path', '/')
        config.setdefault('General', 'show_dialog_on_download', 0)

    def set_value_from_config(self):
        '''Устанавливает значения переменных из файла настроек
        vkgroups.ini.'''

        self.config.read(os.path.join(self.directory, 'vkgroups.ini'))
        self.theme = self.config.get('General', 'theme')
        self.language = self.config.get('General', 'language')
        self.authorization = self.config.getint('General', 'authorization')
        self.last_path = self.config.get('General', 'last_path')
        self.last_screen = self.config.get('General', 'last_screen')
        self.regdata = \
            ast.literal_eval(self.config.get('General', 'regdata'))
        self.login = self.regdata['login']
        self.password = self.regdata['password']
        try:
            self.user_name = ast.literal_eval(
                self.config.get('General', 'user_name')).decode('utf-8')
        except ValueError:
            self.user_name = self.config.get('General', 'user_name')
        self.group_id = self.config.get('General', 'last_group')
        self.count_issues = self.config.getint('General', 'count_issues')
        self.issues_in_group = \
            self.config.getint('General', 'issues_in_group')
        self.show_dialog_on_download = \
            self.config.getint('General', 'show_dialog_on_download')

    def build(self):
        self.set_value_from_config()
        self.translation = Translation(self.language, 'kivyissues',
                                       '%s/data/locales' % self.directory)
        self.RELATION = {
            1: self.translation._('не женат/не замужем'),
            2: self.translation._('есть друг/подруга'),
            3: self.translation._('помолвлен'),
            4: self.translation._('женат/замужем'),
            5: self.translation._('всё сложно'),
            6: self.translation._('в активном поиске'),
            7: self.translation._('влюблён/влюблена'),
            8: self.translation._('в гражданском браке'),
            0: self.translation._('не указано')
        }
        self.message_about_files_mismatch = {
            'FILE': self.translation._('This file unsupported!'),
            'FOTO': self.translation._('This is not image!')
        }
        self.load_dialog.add_widget(
            MDLabel(text=self.translation._(' Загрузка...')))
        self.load_all_kv_files(self.directory + '/libs/uix/kv')
        self.screen = StartScreen()  # главный экран программы
        self.navigation_button = self.screen.ids.navigation_button
        self.previous = self.navigation_button.ids.previous
        self.manager = self.screen.ids.manager
        self.nav_drawer = self.screen.ids.nav_drawer
        self.current_screen_tab = self.navigation_button.ids.home_page

        if not self.login or not self.password:
            self.show_screen_registration()
        else:  # авторизация на сервере
            self._authorization_on_vk(self.login, self.password, self.group_id)

        Clock.schedule_interval(self.wait_info_for_home_page_group, 1)
        return self.screen

    def wait_info_for_home_page_group(self, interval):
        '''Ожидает получения данных от сервера после чего устанавливает
        значения переменных для экрана Previous.'''

        if self.group_info:
            self.previous.ids.group_title.source = \
                self.group_info['photo_200']
            self.previous.ids.group_name.text = \
                '[size=17][b]%s[/b][/size]\n[size=14]%s[/size]' % (
                    self.group_info['name'], self.group_info['status']
                )
            self.previous.ids.group_link.text = \
                '[ref={link}]{link}[/ref]'.format(
                    link='https://vk.com/%s' % self.group_info['screen_name']
                )
            self.previous.ids.group_people.text = \
                '%s %s' % (
                    self.translation._('Участники'),
                    self.group_info['members_count']
                )
            self.previous.ids.description.text = \
                self.group_info['description']
            self.nav_drawer.ids.user_name.text = \
                '[b]%s[/b]\n[size=12]online[/size]\n' % get_user_name()[0]

            Clock.unschedule(self.wait_info_for_home_page_group)
            Clock.schedule_once(
                lambda kwargs: self.show_form_for_messages(whom_name=''), 1)
            self.check_groups_user(name_group=self.group_info['name'],
                                   info_group=self.group_info['status'],
                                   logo_group=self.group_info['photo_200'])

        if os.path.exists('%s/data/state.txt' % self.directory):
            os.remove('%s/data/state.txt' % self.directory)

    def check_state_fields(self, id_instance, text_field):
        '''Сохраняет содержимое формы регистрации.'''

        if text_field == '':
            return

        if os.path.exists('%s/data/state.txt' % self.directory):
            data_state = ast.literal_eval(
                open('%s/data/state.txt' % self.directory).read())
        else:
            data_state = {}

        data_state[id_instance] = text_field

        # TODO: добавить шифрование данных.
        with open('%s/data/state.txt' % self.directory, 'w') as state_form:
            state_form.write(str(data_state))

    def check_groups_user(self, **kwargs):
        '''Проверяет и добавляет в список новые группы пользователя, которые он посещал.
        Данные имеют вид:
        {'Имя группы': ['Описание группы', 'ссылка на логотип группы', 'id группы,]}.'''

        file_groups_path = '%s/data/groups_user.ini' % self.directory
        if not os.path.exists(file_groups_path):
            with open(file_groups_path, 'w') as file_groups_user:
                file_groups_user.write('{}')

        groups_user = ast.literal_eval(
            open('%s/data/groups_user.ini' % self.directory,
                 encoding='utf-8').read())
        if not kwargs['name_group'] in groups_user:
            groups_user[kwargs['name_group']] = \
                [kwargs['info_group'], kwargs['logo_group'], self.group_id]
            with open(file_groups_path, 'w',
                      encoding='utf-8') as file_groups_user:
                file_groups_user.write(str(groups_user))

    def show_login_and_password(self, selection):
        '''
        Устанавливает свойства текстовых полей для ввода логина и пароля.

        :type selection: <class 'int'>

        '''

        if selection:
            self.password_form.ids.login.password = False
            self.password_form.ids.password.password = False
        else:
            self.password_form.ids.login.password = True
            self.password_form.ids.password.password = True

    def show_groups_user(self, *args):
        '''Выводит окно со списком групп пользователя.'''
        def callback_on_button_click(**kwargs):
            def on_press(text_button):
                # TODO: добавить группу в словарь groups.ini.
                field.dismiss()
                toast(str(text_button))

            field = input_dialog(
                title=kwargs['title'],
                hint_text='',
                text_button_ok=self.translation._('Добавить'),
                text_button_cancel=self.translation._('Отмена'),
                events_callback=on_press)

        def callback_on_item_click(name_item, mode):
            description_group, logo_group, id_group = groups_user[name_item]
            dialog(title=name_item,
                   text='%s\nID - %s' % (description_group, str(id_group)))

        if not self.window_user_groups:
            dict_groups_user = {}
            groups_user = ast.literal_eval(
                open('%s/data/groups_user.ini' % self.directory,
                     encoding='utf-8').read())

            for name_group in groups_user.keys():
                description_group, logo_group, id_group = groups_user[
                    name_group]
                dict_groups_user[name_group] = [description_group, logo_group]

            list_user_groups = ListUserGroups()
            _list = list_user_groups.ids.groups_list
            _list.events_callback = callback_on_item_click
            list_user_groups.ids.add_group.on_press = \
                lambda **kwargs: callback_on_button_click(
                    title=self.translation._('Введите ID группы:')
                )
            _list.two_list_custom_icon(dict_groups_user, IconItemAsync)

            self.window_user_groups = card(list_user_groups, size=(.85, .55))
        self.window_user_groups.open()

    def show_screen_registration(self, fail_registration=False):
        '''Окно с формой регистрации.'''

        if not self.password_form:
            self.password_form = \
                PasswordForm(callback=self.check_fields_login_password)
            self.password_form.ids.group_id.text = self.group_id

        self.screen.ids.load_screen.add_widget(self.password_form)

        # Если произошла ошибка регистрации, деактивируем спиннер и чистим
        # лейблы статуса авторизации.
        if fail_registration:
            self.screen.ids.load_screen.ids.spinner.active = False
            self.screen.ids.load_screen.ids.status.text = ''

    def show_screen_connection_failed(self, text_error):
        '''Выводит подпись о не активном соединении и кнопку для повторного
        подключения.'''

        self.screen.ids.load_screen.ids.spinner.active = False
        self.screen.ids.load_screen.ids.status.text = ''

        box = BoxLayout(orientation='vertical',
                        spacing=dp(10),
                        size_hint_y=None,
                        height=dp(100),
                        pos_hint={'center_y': .5})
        texts_errors = {
            'OAuth2 authorization error':
            self.translation._('Повторите попытку позже…'),
            'Failed to establish a new connection':
            self.translation._('Соединение Интернет отсутствует')
        }

        _text_error = self.translation._('Неизвестная ошибка…')
        for name_error in texts_errors.keys():
            if name_error in text_error:
                _text_error = texts_errors[name_error]

        box.add_widget(
            MDLabel(text=_text_error, halign='center', font_style='Subhead'))
        box.add_widget(
            MDFlatButton(text=self.translation._('Повторить попытку'),
                         theme_text_color='Custom',
                         pos_hint={'center_x': .5},
                         text_color=self.theme_cls.primary_color,
                         on_release=lambda x: self._authorization_on_vk(
                             self.login,
                             self.password,
                             self.group_id,
                             from_fail_screen=True)))
        self.screen.ids.load_screen.add_widget(box)

    @thread
    def send_post(self, text):
        self.result_sending_post, text_error = \
             create_issue(text, self.attach_file, self.attach_image)

    @thread
    def send_messages(self, text, user_id):
        self.result_sending_post, text_error = \
            send_message(
                user_id=user_id,
                files=self.attach_file,
                images=self.attach_image,
                text=text
            )

    @thread
    def send_comment(self, text, post_id, comment_id):
        self.result_sending_post, text_error = \
            create_comment(text, self.attach_file, self.attach_image, post_id, comment_id)

    def show_result_sending_posts(self, interval):
        def unschedule():
            Clock.unschedule(self.show_result_sending_posts)
            self.result_sending_post = None
            toast(message)
            self.clear_box_for_attach(remove_all=True)

        message = self.translation._('Sent!')
        if self.result_sending_post:
            # Обновляем списки постов/комментариев.
            if self.name_press_tab != 'Home_page':
                self.box_posts.update_posts()
            unschedule()
        elif self.result_sending_post is False:
            message = self.translation._('Error while sending!')
            unschedule()

    def callback_for_input_text(self, **kwargs):
        '''Вызывается при событиях из формы ввода текста.'''

        self.flag_attach = kwargs.get('flag')
        data = kwargs.get('kwargs')
        comment_id = int(data.get('comment_id', 0))
        post_id = int(data.get('post_id', 0))
        user_id = int(
            data.get('kwargs').get('user_id')) if 'kwargs' in data else 0
        whom_name = data.get('whom_name', '')
        text = whom_name + ', ' + self.form_for_messages.ids.text_form.text if whom_name != '' else self.form_for_messages.ids.text_form.text

        if self.flag_attach in ('FILE', 'FOTO'):
            self.show_manager(self.last_path, self.tap_on_file_in_filemanager)
        elif self.flag_attach == 'SEND':
            if self.manager.current == 'navigation button' and self.name_press_tab != 'Home_page' or self.manager.current == 'user info':
                self.form_for_messages.hide()

            if text.isspace() or text != '':
                if self.manager.current == 'navigation button' and self.name_press_tab == 'Wall_posts':
                    self.send_comment(text, post_id, comment_id)
                elif self.manager.current == 'user info':
                    self.send_messages(text, user_id)
                else:
                    self.send_post(text)

                self.form_for_messages.clear()
                Clock.schedule_interval(self.show_result_sending_posts, 0)

    def clear_box_for_attach(self, remove_all=False):
        self.attach_file = []
        self.attach_image = []

        if remove_all:
            if self.box_for_attach_image:
                self.form_for_messages.remove_widget(self.box_for_attach_image)
            if self.box_for_attach_file:
                self.form_for_messages.remove_widget(self.box_for_attach_file)

        self.box_for_attach_image = None
        self.box_for_attach_file = None

    def remove_attach(self, select_instance_attach):
        '''Удаляет превью файлов и изображений из формы для отправки сообщений.'''
        def _remove_attach(interval):
            parent_widget.remove_widget(instance_attach)

        if self.box_for_attach_file and select_instance_attach in self.box_for_attach_file.children:
            parent_widget = self.box_for_attach_file
        else:
            parent_widget = self.box_for_attach_image

        for instance_attach in parent_widget.children:
            if instance_attach == select_instance_attach:
                Clock.schedule_once(_remove_attach, .25)
                break

    def add_preview_attached_image(self, path_to_attach):
        '''Добавляет превью файлов в форму для отправки сообщений.'''

        if os.path.splitext(path_to_attach)[1] not in self.POSSIBLE_FILES[-2:]:
            if not self.box_for_attach_image:
                self.box_for_attach_image = BoxAttach(spacing=dp(5))
                self.form_for_messages.add_widget(self.box_for_attach_image)
            self.box_for_attach_image.add_widget(
                Icon(source=path_to_attach,
                     size_hint=(None, None),
                     size=(dp(60), dp(120)),
                     on_release=self.remove_attach))

    def add_preview_attached_file(self, path_to_attach):
        if not self.box_for_attach_file:
            self.box_for_attach_file = BoxAttachFile(spacing=dp(5))
            self.form_for_messages.add_widget(self.box_for_attach_file)
        attach = SingleIconItem(icon='file',
                                text=os.path.split(path_to_attach)[1],
                                events_callback=self.remove_attach)
        attach.ids._lbl_primary.font_style = 'Caption'
        self.box_for_attach_file.add_widget(attach)

    def write_last_path_manager(self, path_to_file_folder, path_to_file):
        self.config.set('General', 'last_path', path_to_file_folder)
        self.config.write()
        self.last_path = path_to_file_folder

    def tap_on_file_in_filemanager(self, path_to_file):
        self.window_file_manager.dismiss()
        self.window_file_manager_open = False
        path_to_file_folder, name_file = os.path.split(path_to_file)
        self.write_last_path_manager(path_to_file_folder, path_to_file)
        if os.path.splitext(name_file)[1] not in self.POSSIBLE_FILES:
            toast(self.message_about_files_mismatch[self.flag_attach])
        else:
            if self.flag_attach == 'FILE':
                self.attach_file.append(path_to_file)
                self.add_preview_attached_file(path_to_file)
            else:
                self.attach_image.append(path_to_file)
            self.add_preview_attached_image(path_to_file)

    def set_avatar(self, path_to_avatar):
        self.nav_drawer.ids.avatar.source = path_to_avatar
        self.nav_drawer.ids.avatar.reload()

    def choice_avatar_user(self):
        '''Выводит файловый менеджер для выбора аватара
        и устанавливает его в качестве аватара пользователя.'''
        def on_select(path_to_avatar):
            self.window_file_manager.dismiss()

            if os.path.splitext(path_to_avatar)[1] \
                    not in self.POSSIBLE_FILES[:3]:
                toast(self.translation._('This is not image!'))
            else:
                new_path_to_avatar = \
                    self.directory + '/data/images/avatar.png'
                create_previous_portrait(path_to_avatar, new_path_to_avatar)
                self.set_avatar(new_path_to_avatar)
                toast(self.translation._('Аватар изменён'))
                self.nav_drawer.state = 'open'

        self.show_manager(self.last_path, on_select)

    def show_plugins(self, *args):
        self.instance_list_user_plugins.show_plugins()

    def show_manager(self, directory, callback=None):
        ''''Выводит на экран файловый менеджер.'''

        if self.file_manager_not_opening:
            self.load_dialog.open()
            self.file_manager_not_opening = False

        self.window_file_manager_open = True
        Clock.schedule_once(self.window_file_manager.open, .2)
        if callback:
            self.file_manager.select_path = callback
        self.file_manager.show(directory)

    def show_posts(self, instance_tab=None):

        self.current_screen_tab.clear_widgets()
        if not self.box_posts:
            self.box_posts = BoxPosts(_app=self)
        self.box_posts.clear()
        self.box_posts.show_posts(increment=False)

    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(keyboard)
        elif keyboard in (282, 319):
            pass

        return True

    def back_screen(self, event=None):
        '''Менеджер экранов. Вызывается при нажатии Back Key
        и шеврона "Назад" в ToolBar.'''

        current_screen = self.manager.current
        if not self.window_file_manager_open:
            self.clear_box_for_attach()
        # Нажата BackKey.
        if event in (1001, 27):
            # Если информация с сервера о группе ещё не получена -
            # идёт авторизация либо данные в процессе загрузки.
            if not self.group_info:
                return
            if self.name_press_tab == 'Wall_posts' and self.form_for_messages.visible and \
                    not self.window_file_manager_open:
                self.form_for_messages.hide()
                return
            if self.window_file_manager_open:
                self.file_manager.back()
                return
            if current_screen == 'navigation button':
                if hasattr(self, 'previous_image'):
                    if self.previous_image.previous_open:
                        self.previous_image.dismiss()
                        return
                if self.box_posts and self.box_posts.show_comments:
                    self.box_posts.show_comments = False
                    self.show_posts()
                    return
                self.dialog_exit()
                return
        if current_screen == 'show license':
            self.manager.current = self.manager.screens[-1].name
        elif current_screen == 'user info':
            self.manager.current = 'navigation button'
        else:
            if not self.login or not self.password:
                self.dialog_exit()
                return
            self.manager.current = self.manager.previous()

    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._('Нажмите еще раз для выхода'))

    def show_form_for_messages(self, **kwargs):
        '''Выводит форму для ввода комментариев.'''

        self.form_for_messages = FormForMessages(
            callback=self.callback_for_input_text, kwargs=kwargs)

        self.form_for_messages.show(
            parent_instance=self.current_screen_tab if self.manager.current == 'navigation button' \
            else self.screen.ids.user_info.ids.float_layout
        )
        if kwargs.get('whom_name') == '':
            self.form_for_messages.visible = False

    def form_for_messages_hide(self):
        if self.form_for_messages.visible and not self.form_for_messages.ids.text_form.focus:
            self.form_for_messages.hide()

    def show_about(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.screen.ids.load_screen.ids.status.text = \
            self.translation._(
                '[size=20][b]VKGroups[/b][/size]\n\n'
                '[b]Версия:[/b] {version}\n'
                '[b]Лицензия:[/b] MIT\n\n'
                '[size=20][b]Разработчики[/b][/size]\n\n'
                '[b]Backend:[/b] [ref=https://m.vk.com/fogapod]'
                '[color={link_color}]Евгений Ершов[/color][/ref]\n'
                '[b]Frontend:[/b] [ref=https://m.vk.com/heattheatr]'
                '[color={link_color}]Иванов Юрий[/color][/ref]\n\n'
                '[b]Исходный код:[/b] '
                '[ref=https://github.com/HeaTTheatR/VKGroups]'
                '[color={link_color}]GitHub[/color][/ref]').format(
                version=__version__,
                link_color=get_hex_from_color(self.theme_cls.primary_color)
            )
        self.screen.ids.load_screen.ids.spinner.active = False
        self.manager.current = 'load screen'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen()]]

    def show_license(self, *args):
        self.screen.ids.show_license.ids.text_license.text = \
            self.translation._('%s') % open(
                '%s/license/license_en.txt' %
                    self.directory, encoding='utf-8').read()
        self.nav_drawer._toggle()
        self.manager.current = 'show 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 exit_manager(self, *args):
        '''Закрывает окно файлового менеджера.'''

        self.window_file_manager.dismiss()
        self.window_file_manager_open = False

    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 set_chevron_back_screen(self):
        '''Устанавливает шеврон возврата к предыдущему экрану в ToolBar.'''

        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(self.manager.current)]]

    def download_progress_hide(self, instance_progress, value):
        '''Скрывает виджет прогресса загрузки файлов.'''

        instance_progress.dismiss()
        self.screen.ids.action_bar.right_action_items = \
            [['download', lambda x: self.download_progress_show(instance_progress)]]

    def download_progress_show(self, instance_progress):
        self.screen.ids.action_bar.right_action_items = []
        instance_progress.open()
        instance_progress.animation_progress_from_fade()

    def download_complete(self, result):
        self.screen.ids.action_bar.right_action_items = []
        if result == 'Done':
            toast(self.translation._('Загружено'))
        else:
            toast(self.translation._('Ошибка загрузки'))

    def tap_on_icon_user(self, user_id):
        '''Вызывается при тапе по иконке пользователя в списках постов/комментариев.
        Получает, устанавливает и выводит на экран информацию о выбранном пользователе.
        '''
        def unschedule(error=False):
            if error:
                toast(self.translation._('Данные не получены'))
            Clock.unschedule(wait_result)
            self.load_dialog.dismiss()

        def set_value_for_screen(instance_screen_user_info):
            '''Устанавливает значения подписей в экране информации о пользователе.'''

            instance_screen_user_info.ids.avatar.source = result['photo_200']
            instance_screen_user_info.ids.user_name.text = instance_screen_user_info.ids.user_name.text % (
                result['first_name'] + ' ' + result['last_name'],
                self.translation._('Последний раз был в сети в ') +
                time.strftime("%H:%M",
                              time.localtime(result['last_seen']['time'])))
            instance_screen_user_info.ids.label_user_status.text = \
                instance_screen_user_info.ids.label_user_status.text % result['status']
            instance_screen_user_info.ids.message_button.bind(
                on_release=lambda kwargs: self.show_form_for_messages(
                    kwargs={'user_id': user_id}))

            data = {
                'bdate': {
                    'result': result['bdate'] if 'bdate' in result else None,
                    'bad_result': self.translation._('скрыта'),
                    'label_instance':
                    instance_screen_user_info.ids.label_bdate,
                    'label_text': self.translation._('Дата рождения')
                },
                'city': {
                    'result':
                    result['city']['title'] if 'city' in result else None,
                    'bad_result': self.translation._('не указан'),
                    'label_instance': instance_screen_user_info.ids.label_city,
                    'label_text': self.translation._('Город')
                },
                'relation': {
                    'result':
                    self.RELATION[result['relation']]
                    if 'relation' in result else None,
                    'bad_result':
                    self.translation._('не указано'),
                    'label_instance':
                    instance_screen_user_info.ids.label_marital_status,
                    'label_text':
                    self.translation._('Семейное положение')
                }
            }

            for key in data:
                text_for_label = data[key]['result'] if data[key][
                    'result'] else data[key]['bad_result']
                data[key]['label_instance'].text = data[key][
                    'label_instance'].text % (data[key]['label_text'],
                                              text_for_label)
            unschedule()

        def wait_result(interval):
            '''Ожидает информации от сервера.'''

            if result:
                self.manager.current = 'user info'
                set_value_for_screen(self.screen.ids.user_info)

        if user_id == int(self.group_id):
            return
        result = None
        self.load_dialog.open()
        Clock.schedule_once(wait_result, 0)
        result, text_error = get_user_info(user_id=user_id)
        if text_error:
            unschedule(error=True)

    def load_all_kv_files(self, directory_kv_files):
        for kv_file in os.listdir(directory_kv_files):
            with open(os.path.join(directory_kv_files, kv_file),
                      encoding='utf-8') as kv:
                Builder.load_string(kv.read())

    def on_tab_press(self, instance_tab):
        '''Вызывается при выборе одного из пунктов BottomNavigation.'''

        self.clear_box_for_attach()
        self.name_press_tab = instance_tab.name
        self.current_screen_tab = instance_tab
        self.current_tab_manager = instance_tab.parent_widget.ids.tab_manager

        if self.current_tab_manager.current == self.name_press_tab:
            return

        # Вкладка 'Записи группы'.
        if self.name_press_tab == 'Wall_posts':
            self.show_posts(instance_tab)
            self.form_for_messages.hide()
        elif self.name_press_tab == 'Home_page':
            self.box_posts = None
            self.show_form_for_messages(whom_name='')

    def on_lang(self, instance, lang):
        self.translation.switch_lang(lang)

    def on_pause(self):
        '''Ставит приложение на 'паузу' при сворачивании его в трей.'''

        self.config.set('General', 'last_screen', self.manager.current)
        self.config.write()

        return True

    def on_start(self):
        '''Вызывается при открытии стартового экрана приложения.'''

        # Восстанавливаем форму ввода логина и пароля.
        if self.last_screen == 'load screen' and \
                not self.login and not self.password:
            if os.path.exists('%s/data/state.txt' % self.directory):
                data_state = \
                    ast.literal_eval(open('%s/data/state.txt' % self.directory).read())
                self.password_form.ids.login.text = \
                    data_state['login'] if 'login' in data_state else ''
                self.password_form.ids.password.text = \
                    data_state['password'] if 'password' in data_state else ''
                self.password_form.ids.group_id.text = data_state['group']
Esempio n. 32
0
class StoryBook(Widget):
    # This story's title
    title = StringProperty(None)

    # The story's library
    library_parent = StringProperty(None)

    # The story's library number
    story_number = NumericProperty(None)

    # The current set page by name
    current_page = StringProperty("title")

    # The current set page by number
    current_page_no = NumericProperty(0)

    # List of all pages by name
    pages = ListProperty()

    # The parsed story config
    story_config = ObjectProperty(None)

    # The defaults file
    story_config_file = StringProperty(None)

    # Where is the title media?
    title_media_location = StringProperty(None)

    def __init__(self, **kwargs):
        """
        Initialize starting values. Set kwargs values.
        Set current page to title and page number to 0.
        :param kwargs:
        title: The title of this story
        library: The name of this story's library
        story_number: This story's library number
        """
        super(StoryBook, self).__init__(**kwargs)
        self.title = kwargs['title']
        self.library_parent = kwargs['library']
        self.story_number = kwargs['number']

        self.current_page = "title"
        self.current_page_no = 0
        self.pages = []
        self.story_config_file = ""

    def load_story_config(self, library_dir):
        self.story_config = ConfigParser()
        story_file_loc = library_dir.joinpath(self.title + '.ini')
        if not story_file_loc.is_file():
            self.story_config.setdefaults('metadata',
                                          get_metadata_defaults(self.title, self.library_parent))
            self.story_config.setdefaults('title',
                                          get_page_defaults(self.title))

        self.story_config_file = str(story_file_loc)

        # Set config from story's config file.
        self.story_config.read(str(self.story_config_file))
        if self.story_config.get('metadata', 'story') != self.title:
            self.story_config.set('metadata', 'story', self.title)

        if self.story_config.get('metadata', 'library') != self.library_parent:
            self.story_config.set('metadata', 'library', self.library_parent)

        # Find the media location for this story's title page
        self.title_media_location = self.story_config.get('title', 'media_location')

        # Find all the pages
        self.pages = ['title'] + [x.strip() for x in self.story_config.get('metadata', 'pages').split(',')]
        self.story_config.write()

    def start_page(self):
        """
        Updates the current page to be the first page
        :return:
        """
        self.current_page_no = 0
        self.current_page = self.pages[0]

    def next_page(self):
        """
        Updates the current page to be the next page
        """
        self.current_page_no = min(self.current_page_no + 1, len(self.pages) - 1)
        self.current_page = self.pages[self.current_page_no]

    def previous_page(self):
        """
        Updates the current page to be the previous page
        """
        self.current_page_no = min(self.current_page_no - 1, len(self.pages) - 1)
        self.current_page = self.pages[self.current_page_no]

    def get_story_value(self, page, value):
        return self.story_config.get(page, value)

    def get_title_image(self):
        media_location = self.get_story_value(self.pages[0], 'media_location')
        if len(media_location) == 0:
            media_location = 'images/background.png'

        return media_location

    def get_story_media(self):
        media_location = self.get_story_value(self.current_page, 'media_location')
        if len(media_location) == 0:
            media_location = 'images/background.png'

        return media_location

    def get_story_text(self):
        return self.get_story_value(self.current_page, 'text')
Esempio n. 33
0
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.')
Esempio n. 34
0
class wfpiconsole(App):

    # Define App class observation dictionary properties
    Obs = DictProperty      ([('rapidSpd','--'),       ('rapidDir','----'),    ('rapidShift','-'),
                              ('WindSpd','-----'),     ('WindGust','--'),      ('WindDir','---'),
                              ('AvgWind','--'),        ('MaxGust','--'),       ('RainRate','---'),
                              ('TodayRain','--'),      ('YesterdayRain','--'), ('MonthRain','--'),
                              ('YearRain','--'),       ('Radiation','----'),   ('UVIndex','----'),
                              ('peakSun','-----'),     ('outTemp','--'),       ('outTempMin','---'),
                              ('outTempMax','---'),    ('inTemp','--'),        ('inTempMin','---'),
                              ('inTempMax','---'),     ('Humidity','--'),      ('DewPoint','--'),
                              ('Pres','---'),          ('MaxPres','---'),      ('MinPres','---'),
                              ('PresTrend','----'),    ('FeelsLike','----'),   ('StrikeDeltaT','-----'),
                              ('StrikeDist','--'),     ('StrikeFreq','----'),  ('Strikes3hr','-'),
                              ('StrikesToday','-'),    ('StrikesMonth','-'),   ('StrikesYear','-')
                             ])
    Astro = DictProperty    ([('Sunrise',['-','-',0]), ('Sunset',['-','-',0]), ('Dawn',['-','-',0]),
                              ('Dusk',['-','-',0]),    ('sunEvent','----'),    ('sunIcon',['-',0,0]),
                              ('Moonrise',['-','-']), ('Moonset',['-','-']),   ('NewMoon','--'),
                              ('FullMoon','--'),      ('Phase','---'),         ('Reformat','-'),
                             ])
    MetData = DictProperty  ([('Weather','Building'),  ('Temp','--'),          ('Precip','--'),
                              ('WindSpd','--'),        ('WindDir','--'),       ('Valid','--')
                             ])
    Sager = DictProperty    ([('Forecast','--'),       ('Issued','--')])
    System = DictProperty   ([('Time','-'),            ('Date','-')])
    Version = DictProperty  ([('Latest','-')])

    # Define App class configParser properties
    BarometerMax = ConfigParserProperty('-','System', 'BarometerMax','wfpiconsole')
    BarometerMin = ConfigParserProperty('-','System', 'BarometerMin','wfpiconsole')
    IndoorTemp   = ConfigParserProperty('-','Display','IndoorTemp',  'wfpiconsole')

    # BUILD 'WeatherFlowPiConsole' APP CLASS
    # --------------------------------------------------------------------------
    def build(self):

        # Load user configuration from wfpiconsole.ini and define Settings panel
        # type
        self.config = ConfigParser(allow_no_value=True,name='wfpiconsole')
        self.config.optionxform = str
        self.config.read('wfpiconsole.ini')
        self.settings_cls = SettingsWithSidebar

        # Force window size if required based on hardware type
        if self.config['System']['Hardware'] == 'Pi4':
            Window.size = (800,480)
            Window.borderless = 1
            Window.top = 0
        elif self.config['System']['Hardware'] == 'Other':
            Window.size = (800,480)

        # Initialise real time clock
        Clock.schedule_interval(partial(system.realtimeClock,self.System,self.config),1.0)

        # Initialise Sunrise and Sunset time, Moonrise and Moonset time, and
        # MetOffice or DarkSky weather forecast
        astro.SunriseSunset(self.Astro,self.config)
        astro.MoonriseMoonset(self.Astro,self.config)
        forecast.Download(self.MetData,self.config)

        # Generate Sager Weathercaster forecast
        Thread(target=sagerForecast.Generate, args=(self.Sager,self.config), name="Sager", daemon=True).start()

        # Initialise websocket connection
        self.WebsocketConnect()

        # Check for latest version
        Clock.schedule_once(partial(system.checkVersion,self.Version,self.config,updateNotif))

        # Initialise Station class, and set device status to be checked every
        # second
        self.Station = Station()
        Clock.schedule_interval(self.Station.getDeviceStatus,1.0)

        # Schedule function calls
        Clock.schedule_interval(self.UpdateMethods,1.0)
        Clock.schedule_interval(partial(astro.sunTransit,self.Astro,self.config),1.0)
        Clock.schedule_interval(partial(astro.moonPhase ,self.Astro,self.config),1.0)

    # BUILD 'WeatherFlowPiConsole' APP CLASS SETTINGS
    # --------------------------------------------------------------------------
    def build_settings(self,settingsScreen):

        # Register setting types
        settingsScreen.register_type('ScrollOptions',     SettingScrollOptions)
        settingsScreen.register_type('FixedOptions',      SettingFixedOptions)
        settingsScreen.register_type('ToggleTemperature', SettingToggleTemperature)

        # Add required panels to setting screen. Remove Kivy settings panel
        settingsScreen.add_json_panel('Display',          self.config, data = settings.JSON('Display'))
        settingsScreen.add_json_panel('Primary Panels',   self.config, data = settings.JSON('Primary'))
        settingsScreen.add_json_panel('Secondary Panels', self.config, data = settings.JSON('Secondary'))
        settingsScreen.add_json_panel('Units',            self.config, data = settings.JSON('Units'))
        settingsScreen.add_json_panel('Feels Like',       self.config, data = settings.JSON('FeelsLike'))
        self.use_kivy_settings = False

    # OVERLOAD 'on_config_change' TO MAKE NECESSARY CHANGES TO CONFIG VALUES
    # WHEN REQUIRED
    # --------------------------------------------------------------------------
    def on_config_change(self,config,section,key,value):

        # Update current weather forecast and Sager Weathercaster forecast when
        # temperature or wind speed units are changed
        if section == 'Units' and key in ['Temp','Wind']:
            if self.config['Station']['Country'] == 'GB':
                forecast.ExtractMetOffice(self.MetData,self.config)
            else:
                forecast.ExtractDarkSky(self.MetData,self.config)
            if key == 'Wind' and 'Dial' in self.Sager:
                self.Sager['Dial']['Units'] = value
                self.Sager['Forecast'] = sagerForecast.getForecast(self.Sager['Dial'])

        # Update "Feels Like" temperature cutoffs in wfpiconsole.ini and the
        # settings screen when temperature units are changed
        if section == 'Units' and key == 'Temp':
            for Field in self.config['FeelsLike']:
                if 'c' in value:
                    Temp = str(round((float(self.config['FeelsLike'][Field])-32) * 5/9))
                    self.config.set('FeelsLike',Field,Temp)
                elif 'f' in value:
                    Temp = str(round(float(self.config['FeelsLike'][Field])*9/5 + 32))
                    self.config.set('FeelsLike',Field,Temp)
            self.config.write()
            panels = self._app_settings.children[0].content.panels
            for Field in self.config['FeelsLike']:
                for panel in panels.values():
                    if panel.title == 'Feels Like':
                        for item in panel.children:
                            if isinstance(item,Factory.SettingToggleTemperature):
                                if item.title.replace(' ','') == Field:
                                    item.value = self.config['FeelsLike'][Field]

        # Update barometer limits when pressure units are changed
        if section == 'Units' and key == 'Pressure':
            Units = ['mb','hpa','inhg','mmhg']
            Max = ['1050','1050','31.0','788']
            Min = ['950','950','28.0','713']
            self.config.set('System','BarometerMax',Max[Units.index(value)])
            self.config.set('System','BarometerMin',Min[Units.index(value)])

        # Update primary and secondary panels displayed on CurrentConditions
        # screen
        if section in ['PrimaryPanels','SecondaryPanels']:
            for Panel,Type in App.get_running_app().config['PrimaryPanels'].items():
                if Panel == key:
                    self.CurrentConditions.ids[Panel].clear_widgets()
                    self.CurrentConditions.ids[Panel].add_widget(eval(Type + 'Panel')())
                    break

        # Update button layout displayed on CurrentConditions screen
        if section == 'SecondaryPanels':
            ii = 0
            self.CurrentConditions.buttonList = []
            Button = ['Button' + Num for Num in ['One','Two','Three','Four','Five','Six']]
            for Panel, Type in App.get_running_app().config['SecondaryPanels'].items():
                self.CurrentConditions.ids[Button[ii]].clear_widgets()
                if Type and Type != 'None':
                    self.CurrentConditions.ids[Button[ii]].add_widget(eval(Type + 'Button')())
                    self.CurrentConditions.buttonList.append([Button[ii],Panel,Type,'Primary'])
                    ii += 1

            # Change 'None' for secondary panel selection to blank in config
            # file
            if value == 'None':
                self.config.set(section,key,'')
                self.config.write()
                panels = self._app_settings.children[0].content.panels
                for panel in panels.values():
                    if panel.title == 'Secondary Panels':
                        for item in panel.children:
                            if isinstance(item,Factory.SettingOptions):
                                if item.title.replace(' ','') == key:
                                    item.value = ''
                                    break

    # CONNECT TO THE SECURE WEATHERFLOW WEBSOCKET SERVER
    # --------------------------------------------------------------------------
    def WebsocketConnect(self):
        Server = 'wss://ws.weatherflow.com/swd/data?api_key=' + self.config['Keys']['WeatherFlow']
        self._factory = WeatherFlowClientFactory(Server,self)
        reactor.connectTCP('ws.weatherflow.com',80,self._factory,)

    # SEND MESSAGE TO THE WEATHERFLOW WEBSOCKET SERVER
    # --------------------------------------------------------------------------
    def WebsocketSendMessage(self,Message):
        Message = Message.encode('utf8')
        proto = self._factory._proto
        if Message and proto:
            proto.sendMessage(Message)

    # DECODE THE WEATHERFLOW WEBSOCKET MESSAGE
    # --------------------------------------------------------------------------
    def WebsocketDecodeMessage(self,Msg):

        # Extract type of received message
        Type = Msg['type']

        # Start listening for device observations and events upon connection of
        # websocket based on device IDs specified in user configuration file
        if Type == 'connection_opened':
            if self.config['Station']['TempestID']:
                self.WebsocketSendMessage('{"type":"listen_start",' +
                                          ' "device_id":' + self.config['Station']['TempestID'] + ',' +
                                          ' "id":"Sky"}')
                self.WebsocketSendMessage('{"type":"listen_rapid_start",' +
                                          ' "device_id":' + self.config['Station']['TempestID'] + ',' +
                                          ' "id":"rapidWind"}')
            elif self.config['Station']['SkyID']:
                self.WebsocketSendMessage('{"type":"listen_start",' +
                                          ' "device_id":' + self.config['Station']['SkyID'] + ',' +
                                          ' "id":"Sky"}')
                self.WebsocketSendMessage('{"type":"listen_rapid_start",' +
                                          ' "device_id":' + self.config['Station']['SkyID'] + ',' +
                                          ' "id":"rapidWind"}')
            if self.config['Station']['OutAirID']:
                self.WebsocketSendMessage('{"type":"listen_start",' +
                                          ' "device_id":' + self.config['Station']['OutAirID'] + ',' +
                                          ' "id":"OutdoorAir"}')
            if self.config['Station']['InAirID']:
                self.WebsocketSendMessage('{"type":"listen_start",' +
                                          ' "device_id":' + self.config['Station']['InAirID'] + ',' +
                                          ' "id":"IndoorAir"}')

        # Extract observations from obs_st websocket message
        elif Type == 'obs_st':
            Thread(target=websocket.Tempest, args=(Msg,self), name="Tempest", daemon=True).start()

        # Extract observations from obs_sky websocket message
        elif Type == 'obs_sky':
            Thread(target=websocket.Sky, args=(Msg,self), name="Sky", daemon=True).start()

        # Extract observations from obs_air websocket message based on device
        # ID
        elif Type == 'obs_air':
            if self.config['Station']['InAirID'] and Msg['device_id'] == int(self.config['Station']['InAirID']):
                Thread(target=websocket.indoorAir, args=(Msg,self),  name="indoorAir",  daemon=True).start()
            if self.config['Station']['OutAirID'] and Msg['device_id'] == int(self.config['Station']['OutAirID']):
                Thread(target=websocket.outdoorAir, args=(Msg,self), name="outdoorAir", daemon=True).start()

        # Extract observations from rapid_wind websocket message
        elif Type == 'rapid_wind':
            websocket.rapidWind(Msg,self)

        # Extract observations from evt_strike websocket message
        elif Type == 'evt_strike':
            websocket.evtStrike(Msg,self)

    # UPDATE 'WeatherFlowPiConsole' APP CLASS METHODS AT REQUIRED INTERVALS
    # --------------------------------------------------------------------------
    def UpdateMethods(self,dt):

        # Get current time in station timezone
        Tz = pytz.timezone(self.config['Station']['Timezone'])
        Now = datetime.now(pytz.utc).astimezone(Tz)
        Now = Now.replace(microsecond=0)

        # At 5 minutes past each hour, download a new forecast for the Station
        # location
        if (Now.minute,Now.second) == (5,0):
            forecast.Download(self.MetData,self.config)

        # At the top of each hour update the on-screen forecast for the Station
        # location
        if self.config['Station']['Country'] == 'GB':
            if Now.hour > self.MetData['Time'].hour or Now.date() > self.MetData['Time'].date():
                forecast.ExtractMetOffice(self.MetData,self.config)
                self.MetData['Time'] = Now
        elif self.config['Keys']['DarkSky']:
            if Now.hour > self.MetData['Time'].hour or Now.date() > self.MetData['Time'].date():
                forecast.ExtractDarkSky(self.MetData,self.config)
                self.MetData['Time'] = Now

        # Once dusk has passed, calculate new sunrise/sunset times
        if Now >= self.Astro['Dusk'][0]:
            self.Astro = astro.SunriseSunset(self.Astro,self.config)

        # Once moonset has passed, calculate new moonrise/moonset times
        if Now > self.Astro['Moonset'][0]:
            self.Astro = astro.MoonriseMoonset(self.Astro,self.config)

        # At midnight, update Sunset, Sunrise, Moonrise and Moonset Kivy Labels
        if self.Astro['Reformat'] and Now.replace(second=0).time() == time(0,0,0):
            self.Astro = astro.Format(self.Astro,self.config,"Sun")
            self.Astro = astro.Format(self.Astro,self.config,"Moon")
Esempio n. 35
0
class hodl_mobile(App):
    def show_popup(self):
        p = Theme_Popup()
        p.open()

    '''Функционал программы.'''

    title = 'hodl_mobile'
    icon = 'icon.png'
    nav_drawer = ObjectProperty()
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Blue'
    lang = StringProperty('en')
    cont = StringProperty()

    def __init__(self, **kvargs):
        super(hodl_mobile, 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.window_contacts = None
        self.exit_interval = False
        self.dict_language = literal_eval(
            open(os.path.join(self.directory, 'data', 'locales',
                              'locales.txt')).read())
        self.dict_contacts = literal_eval(
            open(os.path.join(self.directory, 'data', 'contacts.txt')).read())
        self.translation = Translation(
            self.lang, 'Ttest', os.path.join(self.directory, 'data',
                                             'locales'))

    def get_application_config(self):
        return super(hodl_mobile, self).get_application_config(
            '{}/%(appname)s.ini'.format(self.directory))

    def build_config(self, config):
        '''Создаёт файл настроек приложения hodl_mobile.ini.'''

        config.adddefaultsection('General')
        config.setdefault('General', 'language', 'en')

    def set_value_from_config(self):
        '''Устанавливает значения переменных из файла настроек hodl_mobile.ini.'''

        self.config.read(os.path.join(self.directory, 'hodl_mobile.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()  # main screen
        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):
                with open(kv_file, encoding='utf-8') as kv:
                    Builder.load_string(kv.read())

    def events_program(self, instance, keyboard, keycode, text, modifiers):
        '''On menu button press.'''

        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):
        '''Менеджер экранов. Вызывается при нажатии Back Key
        и шеврона "Назад" в ToolBar.'''

        # Нажата BackKey.
        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 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 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]hodl_mobile[/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'HODL is a cryptocurrency with smart contracts.\n\n'
                u'[ref=SITE_PROJECT]'
                u'[color={link_color}]NAME_AUTHOR[/color][/ref]\n\n'
                u'[b]Source code:[/b] '
                u'[ref=https://github.com/hodleum/hodl_mobile.git]'
                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.title = \
            self.translation._('About')

    def show_buy_new_tokens(self, *args):
        self.manager.current = 'buy_new_tokens'
        self.screen.ids.action_bar.title = \
            self.translation._('Buy tokens')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_trade()]]

    def show_scan(self, *args):
        self.manager.current = 'scan'
        self.screen.ids.action_bar.title = \
            self.translation._('Scan')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_main()]]

    def show_find_new_contact(self, *args):
        self.manager.current = 'find_new_contact'
        self.screen.ids.action_bar.title = \
            self.translation._('Find new contact')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_contacts()]]

    def show_new_transaction(self, *args):
        self.manager.current = 'new_transaction'
        self.screen.ids.action_bar.title = \
            self.translation._('New transaction')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_main()]]

    def show_tokens_info(self, *args):
        self.manager.current = 'tokens_info'
        self.screen.ids.action_bar.title = \
            self.translation._('DVT')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_trade()]]

    def show_back_tokens_info(self, *args):
        self.manager.current = 'tokens_info'
        self.screen.ids.action_bar.title = \
            self.translation._('DVT')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_trade()]]

    def show_choose_from_contacts(self, *args):
        def select_contact(name_contact):
            for contact in self.dict_contacts.keys():
                if name_contact == self.dict_contacts[contact]:
                    self.window_contacts.dismiss()
                    self.cont = name_contact
                    text_cont = name_contact
                    print(text_cont)
                    self.window_contacts.dismiss()

        dict_info_contacts = {}
        for contact in self.dict_contacts.keys():
            dict_info_contacts[self.dict_contacts[contact]] = \
                ['contact', contact == self.cont]

        if not self.window_contacts:
            self.window_contacts = card(Lists(dict_items=dict_info_contacts,
                                              events_callback=select_contact,
                                              flag='one_select_check'),
                                        size=(.85, .55))
        self.window_contacts.open()

    def show_invoicecreation(self, *args):
        self.manager.current = 'invoicecreation'
        self.screen.ids.action_bar.title = \
            self.translation._('Invoice creation')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_main()]]

    def show_set(self, *args):
        self.manager.current = 'set'
        self.nav_drawer._toggle()
        self.screen.ids.action_bar.title = \
            self.translation._('Settings')

    def show_trade(self, *args):
        self.manager.current = 'trade'
        self.nav_drawer._toggle()
        self.screen.ids.action_bar.title = \
            self.translation._('Trade')

    def show_new_wallet(self, *args):
        self.manager.current = 'new_wallet'
        self.nav_drawer._toggle()
        self.screen.ids.action_bar.title = \
            self.translation._('New wallet')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_main()]]

    def show_back_trade(self, *args):
        self.manager.current = 'trade'
        self.screen.ids.action_bar.title = \
            self.translation._('Trade')
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer._toggle()]]

    def show_buy_more1(self, *args):
        self.manager.current = 'buy_more1'
        self.screen.ids.action_bar.title = \
            self.translation._('Buy')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_trade()]]

    def show_sell1(self, *args):
        self.manager.current = 'sell1'
        self.screen.ids.action_bar.title = \
            self.translation._('Sell')
        self.screen.ids.action_bar.left_action_items = \
            [['arrow-left', lambda x: self.show_back_trade()]]

    def show_contacts(self, *args):
        self.manager.current = 'contacts'
        self.nav_drawer._toggle()
        self.screen.ids.action_bar.title = \
            self.translation._('Contacts')

    def show_back_contacts(self, *args):
        self.manager.current = 'contacts'
        self.screen.ids.action_bar.title = \
            self.translation._('Contacts')
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer._toggle()]]

    def show_main(self, *args):
        self.manager.current = 'base'
        self.nav_drawer._toggle()
        self.screen.ids.action_bar.title = \
            self.translation._('Home screen')

    def show_back_main(self, *args):
        self.manager.current = 'base'
        self.screen.ids.action_bar.title = \
            self.translation._('Home screen')
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer._toggle()]]

    def show_network(self, *args):
        self.manager.current = 'network'
        self.nav_drawer._toggle()
        self.screen.ids.action_bar.title = \
            self.translation._('Network')

    def show_license(self, *args):
        self.screen.ids.license.ids.text_license.text = \
            self.translation._('%s') % open(
                os.path.join(self.directory, 'LICENSE'), encoding='utf-8').read()
        self.nav_drawer._toggle()
        self.manager.current = 'license'
        self.screen.ids.action_bar.title = \
            self.translation._('MIT LICENSE')

    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 change_theme(self, value):
        self.theme_cls.primary_palette = value
        return value

    def on_lang(self, instance, lang):
        self.translation.switch_lang(lang)

    def to_start(self):

        self.screen = StartScreen()
        return self.screen
Esempio n. 36
0
class cBaseScript(object):
    ''' basic script class to inherit all scrpts from '''
    def __init__(self):
        self.bIsInit                = False
        self.uMyPath                = u''
        self.uScriptName            = u''
        self.uScriptFile            = u''
        self.iMyVersion             = ToIntVersion('1.0.0')
        self.fOrcaVersion           = ToIntVersion('1.0.0')
        self.uType                  = u'Generic'
        self.uSubType               = u'Generic'
        self.aScriptIniSettings     = QueryDict()
        self.oConfigParser          = KivyConfigParser()
        self.uDefaultConfigName     = ""
        self.uConfigFileName        = ""
        self.uSection               = ""

    def RunScript(self, args):
        ''' Dummy '''
        pass

    def Init(self,oParORCA,uScriptName,uScriptFile):
        ''' Initializes the script '''
        self.bIsInit            = True
        self.uScriptName        = uScriptName
        self.uScriptFile        = uScriptFile
        self.uDefaultConfigName = uScriptName

        self.uMyPath            = AdjustPathToOs(oORCA.uScriptsPath+'/'+self.uScriptName)
        if not os.path.exists(self.uMyPath):
            CreateDir(self.uMyPath)
        oORCA.oTheScreen.oLanguage.LoadXmlFile("SCRIPT", uScriptName)

        self.uConfigFileName    = AdjustPathToOs(self.uMyPath+u'/config.ini')
        oRepManagerEntry=cRepManagerEntry()
        oRepManagerEntry.uFileName=uScriptFile
        if oRepManagerEntry.ParseFromSourceFile():
            self.iMyVersion     = oRepManagerEntry.oRepEntry.iVersion
            self.fOrcaVersion   = oRepManagerEntry.oRepEntry.iMinOrcaVersion
            #OrcaVersion defines for what Orca Version the Interface has been developed

        self.ShowDebug(u'Init')
        if not FileExists(self.uConfigFileName):
            self.CreateAndInitializeIniFile()

        oRepManagerEntry=cRepManagerEntry()
        oRepManagerEntry.uFileName=uScriptFile
        if oRepManagerEntry.ParseFromSourceFile():
            self.iMyVersion     = oRepManagerEntry.oRepEntry.iVersion
            self.fOrcaVersion   = oRepManagerEntry.oRepEntry.iMinOrcaVersion
            #OrcaVersion defines for what Orca Version the Script has been developed
        self.ReadConfigFromIniFile(self.uDefaultConfigName)

    def InitializeSection(self,uSection):
        ''' Initializes a section in the config.ini file for the script '''
        self.ReadConfigFromIniFile(uSection)
    def CreateAndInitializeIniFile(self):
        ''' Creates the ini file '''
        self.oConfigParser.add_section(self.uDefaultConfigName)
        self.InitializeSection(self.uDefaultConfigName)
        self.oConfigParser.write()
    def LoadConfig(self):
        ''' loads a config from the ini file '''
        self.oConfigParser.filename=self.uConfigFileName
        if len(self.oConfigParser._sections)==0:
            if FileExists(self.uConfigFileName):
                self.ShowDebug(u'Reading Config File')
                self.oConfigParser.read(self.uConfigFileName)
    def GetConfigJSONStringforSection(self,uSection):
        ''' dummy '''
        return u'{}'

    def ReadConfigFromIniFile(self,uConfigName):
        ''' reads a config from the ini file '''
        self.uSection = uConfigName

        try:
            SetVar('ScriptConfigSection',uConfigName)
            self.LoadConfig()
            oIniDef = json.loads(self.GetConfigJSONStringforSection(uConfigName))

            for oLine in oIniDef:
                uType       = oLine.get("type")
                uKey        = oLine.get("key")
                uDefault    = oLine.get("default")

                if uType == "scrolloptions" or uType == "string":
                    uPre = "u" + uKey
                    self.aScriptIniSettings[uPre]=Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault)
                elif uType == "numeric" or uType == "numericslider":
                    uPre= "i" + uKey
                    self.aScriptIniSettings[uPre]=ToInt(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "numericfloat" :
                    uPre= "f" + uKey
                    self.aScriptIniSettings[uPre]=ToFloat(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "bool":
                    uPre = "b" + uKey
                    self.aScriptIniSettings[uPre]=ToBool(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "title":
                    pass
                else:
                    self.ShowError(u'Cannot read config name (base), wrong attribute:'+self.uConfigFileName + u' Section:'+self.uSection+" " +oLine["type"])

        except Exception as e:
            self.ShowError(u'Cannot read config name (base):'+self.uConfigFileName + u' Section:'+self.uSection,e)
            return

    def DeInit(self):
        ''' deinitializes the ini file '''
        self.ShowDebug(u'DeInit')
    def OnPause(self):
        ''' called by system, if the device goes on pause '''
        self.ShowInfo(u'OnPause')
    def OnResume(self):
        ''' called by system, if the device resumes '''
        self.ShowInfo(u'OnResume')

    def ShowWarning(self,uMsg):
        ''' creates a warning debug line '''
        uRet=u'Script '+self.uScriptName+u': '+ uMsg
        Logger.warning (uRet)
        return uRet

    def ShowDebug(self,uMsg):
        ''' creates a debug line '''
        uRet=u'Script '+self.uScriptName+u': '+ uMsg
        Logger.debug (uRet)
        return uRet

    def ShowInfo(self,uMsg):
        ''' creates a info debug line '''
        uRet=u'Script '+self.uScriptName+u': '+ uMsg
        Logger.info (uRet)
        return uRet

    def ShowError(self,uMsg,oException=None):
        ''' creates a error debug line '''
        iErrNo = 0
        if oException!=None:
            if hasattr(oException,'errno'):
                iErrNo=oException.errno
        if iErrNo is None:
            iErrNo=12345

        uRet=LogErrorSmall (u'Script '+self.uScriptName+u': '+ uMsg + " (%d) " % (iErrNo),oException)
        return uRet

    def _ReadConfig(self):
        ''' reads the config for the settings dialog '''
        oConfig = KivyConfigParser()
        oConfig.read(self.uConfigFileName)
        return oConfig

    def ConfigScriptSettings(self,oScriptSetting):
        ''' for here we need a separate config object '''
        self.oConfigParser=self._ReadConfig()
        oScriptSetting.register_type('buttons'               , SettingButtons)
        oScriptSetting.register_type('numericslider'         , SettingNumericSlider)
        oScriptSetting.register_type('numericfloat'          , SettingNumeric)
        oScriptSetting.register_type('scrolloptions'         , SettingScrollOptions)

        SetVar('ScriptConfigSection',self.uDefaultConfigName)
        uSettingsJSON=self.GetConfigJSONStringforSection(self.uDefaultConfigName)
        self.ReadConfigFromIniFile(self.uDefaultConfigName)
        if uSettingsJSON==u'{}':
            return self.On_SettingsClose(None)
        uSettingsJSON=ReplaceVars(uSettingsJSON)
        oScriptSetting.add_json_panel(self.uDefaultConfigName,self.oConfigParser, data=uSettingsJSON)
        oScriptSetting.bind(on_close=self.On_SettingsClose)

        return oScriptSetting

    def On_SettingsClose(self,instance):
        ''' Dispatched when the user closes the settings dialog '''
        oORCA.DispatchSystemKey('buttonclosesetting_script')
        return True

    def ShowSettings(self):
        '''  shows the settings dialog '''
        oORCA.oTheScreen.AddActionToQueue([{'string':'updatewidget','widgetname':'Scriptsettings'}])
Esempio n. 37
0
class Gllearn(MDApp):
    title = 'Gllearn'
    icon = '.data/images/icon.png'
    nav_drawer = ObjectProperty()
    lang = StringProperty('ru')
    lang_games = StringProperty('en')
    __version__ = '0.6'

    def __init__(self, **kvargs):
        super(Gllearn, 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.window_game_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, 'Gllearn',
            os.path.join(self.directory, 'data', 'locales'))
        self.translation_game = Translation(
            self.lang_games, 'Games',
            os.path.join(self.directory, 'data', 'locales'))

        self.snake_words_with_color = [{
            word: get_random_color(alpha=1.0)
            for word in words
        } for words in [
            s.split(' ')
            for s in self.translation_game._('snake_rounds').split(' | ')
        ]]
        self.current_round_snake = 0

    def set_value_from_config(self):
        self.config.read(os.path.join(self.directory, 'gllearn.ini'))
        self.lang = self.config.get('General', 'language')
        self.lang_games = self.config.get('Games', 'language')

    def build(self):
        self.theme_cls.primary_palette = "Indigo"
        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):
                with open(kv_file, encoding='utf-8') as kv:
                    Builder.load_string(kv.read())

    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()
            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()
                self.manager.transition.direction = 'right'
            except Exception:
                self.manager.current = 'base'
                self.manager.transition.direction = 'right'
            self.screen.ids.action_bar.title = self.title
            self.screen.ids.action_bar.left_action_items = \
                [['menu', lambda x: self.nav_drawer.set_state()]]

    def back_screen_on_game(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()
                self.manager.transition.direction = 'down'
            except Exception:
                self.manager.current = 'base'
                self.manager.transition.direction = 'down'
            self.screen.ids.action_bar.title = self.title
            Clock.unschedule(self.show_snake)
            self.screen.ids.action_bar.left_action_items = \
                [['menu', lambda x: self.nav_drawer.set_state()]]

    def show_about(self, *args):
        self.nav_drawer.set_state()
        self.screen.ids.about.ids.label.text = \
            self.translation._(
                u'[size=20][b]Gllearn[/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}]Minnakhmetov Musa Albertovich[/color][/ref]\n\n'
                u'[b]Source code:[/b] '
                u'[ref=https://github.com/katustrica/Gllearn]'
                u'[color={link_color}]GitHub[/color][/ref]').format(
                version=self.__version__,
                link_color=get_hex_from_color(self.theme_cls.primary_color)
            )
        self.manager.current = 'about'
        self.manager.transition.direction = 'left'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_words(self, *args):
        self.screen.ids.action_bar.title = f'Змейка полиглот {self.current_round_snake+1} lvl'
        self.manager.current = 'words'
        self.manager.transition.direction = 'up'
        self.screen.ids.action_bar.left_action_items = [[
            'chevron-left', lambda x: self.back_screen_on_game(27)
        ]]
        Clock.schedule_once(self.show_snake, 8)

    def next_snake_words(self, *args):
        Clock.unschedule(self.show_snake)
        self.screen.ids.action_bar.title = f'Змейка полиглот {self.current_round_snake+1} lvl'
        self.manager.current = 'words'
        self.manager.transition.direction = 'down'
        self.screen.ids.action_bar.left_action_items = [[
            'chevron-left', lambda x: self.back_screen_on_game(27)
        ]]
        Clock.schedule_once(self.show_snake, 8)

    def show_snake(self, *args):
        self.manager.current = 'snake'
        self.manager.transition.direction = 'up'
        self.screen.ids.action_bar.left_action_items = [[
            'chevron-left', lambda x: self.back_screen_on_game(27)
        ]]

    def show_translator(self, *args):
        self.manager.current = 'translator'
        self.screen.ids.action_bar.title = f'Переводчик'
        self.manager.transition.direction = 'up'
        self.screen.ids.action_bar.left_action_items = [[
            'chevron-left', lambda x: self.back_screen_on_game(27)
        ]]

    def show_license(self, *args):
        self.nav_drawer.set_state()
        self.screen.ids.license.ids.text_license.text = \
            self.translation._('%s') % open(
                os.path.join(self.directory, 'LICENSE'), encoding='utf-8').read()
        self.manager.current = 'license'
        self.manager.transition.direction = 'left'
        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 select_game_locale(self, *args):
        def select_game_locale(name_locale):
            for locale in self.dict_language.keys():
                if name_locale == self.dict_language[locale]:
                    self.lang_games = locale
                    self.config.set('Games', 'language', self.lang_games)
                    self.config.write()
                    self.translation_game.switch_lang(name_locale)
                    self.snake_words_with_color = [{
                        word: get_random_color(alpha=1.0)
                        for word in words
                    } for words in [
                        s.split(' ') for s in self.translation_game._(
                            'snake_rounds').split(' | ')
                    ]]

        dict_info_locales = {}
        for locale in self.dict_language.keys():
            dict_info_locales[self.dict_language[locale]] = \
                ['locale', locale == self.lang_games]
        if not self.window_game_language:
            self.window_game_language = card(Lists(
                dict_items=dict_info_locales,
                events_callback=select_game_locale,
                flag='one_select_check'),
                                             size=(.85, .55))
        self.window_game_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)
        self.translation_game.switch_lang(lang)
Esempio n. 38
0
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)
Esempio n. 39
0
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)
Esempio n. 40
0
class keepupthepaceMD(MDApp):
    title = 'keepupthepaceMD'
    icon = 'icon.png'
    nav_drawer = properties.ObjectProperty()
    lang = properties.StringProperty('en')
    #load saved profiles and instantiate the default one
    listofprofiles, myProfile = persistence.getDefaultProfileFromShelf()

    # define the properties that will be updated in the user interface
    knbmi = properties.StringProperty('0')
    kbbmi = properties.StringProperty('0')
    krmr1918 = properties.StringProperty('0')
    krmr1984 = properties.StringProperty('0')
    krmr1990 = properties.StringProperty('0')
    krmrml1918 = properties.StringProperty('0')
    krmrml1984 = properties.StringProperty('0')
    krmrml1990 = properties.StringProperty('0')
    khbe1918 = properties.StringProperty('0')
    khbe1984 = properties.StringProperty('0')
    khbe1990 = properties.StringProperty('0')
    kqfp = properties.StringProperty('0')
    kefp = properties.StringProperty('0')

    # initialize a profile to test the app, if none loaded
    if not (isinstance(myProfile, profile.Profile)):
        myProfile = profile.Profile('not coming from shelf')
        myProfile.isdefault = True
        myProfile.age = 35
        myProfile.gender = enumandconst.Gender.FEMALE
        myProfile.weightIntegerPart = 60
        myProfile.weightDecimalPart = 0
        myProfile.heightIntegerPart = 1
        myProfile.heightDecimalPart = 68
        myProfile.metricChoice = enumandconst.MetricChoice.ISO
        myProfile.computeAll()
    else:
        myProfile.computeAll()

    # initialize all the MET tables
    bicycling = c01.Bicycling
    conditionningExercises = c02.ConditionningExercises
    dancing = c03.Dancing
    fishingHunting = c04.FishingHunting
    homeActivity = c05.HomeActivity
    homeRepair = c06.HomeRepair
    inactivity = c07.Inactivity
    lawnGarden = c08.LawnGarden
    miscellaneous = c09.Miscellaneous
    musicPlaying = c10.MusicPlaying
    occupation = c11.Occupation
    running = c12.Running
    selfcare = c13.SelfCare
    sexualActivity = c14.SexualActivity
    sports = c15.Sports
    transportation = c16.Transportation
    walking = c17.Walking
    waterActivities = c18.WaterActivities
    winterActivites = c19.WinterActivities
    religiousActivities = c20.ReligiousActivities
    volunteeractivities = c21.VolunteerActivities

    def __init__(self, **kvargs):
        super(keepupthepaceMD, 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.gender_menu = None
        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.listOfMetTables = [
            self.translation._('01-Bicycling'),
            self.translation._('02-Conditionning Exercises'),
            self.translation._('03-Dancing'),
            self.translation._('04-Fishing & Hunting'),
            self.translation._('05-Home Activity'),
            self.translation._('06-Home Repair'),
            self.translation._('07-Inactivity'),
            self.translation._('08-Lawn Garden'),
            self.translation._('09-Miscellaneous'),
            self.translation._('10-Music Playing'),
            self.translation._('11-Occupation'),
            self.translation._('12-Runing'),
            self.translation._('13-Self Care'),
            self.translation._('14-Sexual Activity'),
            self.translation._('15-Sports'),
            self.translation._('16-Transportation'),
            self.translation._('17-Walking'),
            self.translation._('18-Water Activities'),
            self.translation._('19-Winter Activities'),
            self.translation._('20-Religious Activities'),
            self.translation._('21-Volunteer Activities')
        ]

    def get_application_config(self):
        return super(keepupthepaceMD, 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, 'keepupthepacemd.ini'))
        self.lang = self.config.get('General', 'language')

    def build(self):
        LabelBase.register(name="Arial", fn_regular="Arial.ttf")

        theme_font_styles.append('Arial')
        self.theme_cls.font_styles["Arial"] = [
            "Arial",
            16,
            False,
            0.15,
        ]
        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 refreshValuesToDisplayOnScreen(self):
        '''
            Refresh the values to display whenever it's needed
        '''
        self.kbbmi = self.myProfile.displaybBMI()
        self.knbmi = self.myProfile.displaynBMI()
        self.krmr1918, self.krmr1984, self.krmr1990 = self.myProfile.displayRMR(
        )
        self.krmrml1918, self.krmrml1984, self.krmrml1990 = self.myProfile.displayRMRml(
        )
        self.khbe1918, self.khbe1984, self.khbe1990 = self.myProfile.displayHBE(
        )
        self.kqfp, self.kefp = self.myProfile.displayFAT()

    def doThingsBetweenScreen(self):
        '''
            save profiles when leaving some selectted tabs
        '''
        self.myProfile.computeAll()
        persistence.saveprofiles()
        self.refreshValuesToDisplayOnScreen()

    def on_stop(self):
        persistence.saveprofiles()

    def on_pause(self):
        persistence.saveprofiles()

    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):
                with open(kv_file, encoding='utf-8') as kv:
                    Builder.load_string(kv.read())

    def events_program(self, instance, keyboard, keycode, text, modifiers):
        if keyboard == 27:
            if self.nav_drawer.state == 'open':
                self.nav_drawer.toggle_nav_drawer()
            self.back_screen(event=keyboard)
        return True

    def back_screen(self, event=None):
        if event == 27:
            if self.manager.current == 'base':
                self.dialog_exit()
                return
            try:
                self.doThingsBetweenScreen()
                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_metrics(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.manager.current = 'metrics'
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]]
        self.screen.ids.action_bar.right_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_onelist(self, *args):
        self.list_previous_screens.append('compendiumlist')
        self.manager.current = 'onelist'
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]]
        self.screen.ids.action_bar.right_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_compendium(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.manager.current = 'compendiumlist'
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]]
        self.screen.ids.action_bar.right_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_about(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.screen.ids.about.ids.label.text = \
            self.translation._(
                u'[size=20][b]keepupthepaceMD[/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 = \
            [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]]
        self.screen.ids.action_bar.right_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def show_license(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.screen.ids.license.ids.text_license.text = \
            self.translation._('%s') % open(
                os.path.join(self.directory, 'LICENSE'), encoding='utf-8').read()
        self.manager.current = 'license'
        self.screen.ids.action_bar.left_action_items = \
            [['menu', lambda x: self.nav_drawer.toggle_nav_drawer()]]
        self.screen.ids.action_bar.right_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)
Esempio n. 41
0
class Migren(App):
    title = 'Дневник головной боли'
    icon = 'icon.png'
    nav_drawer = ObjectProperty()
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Grey'
    lang = StringProperty('en')


    def __init__(self, **kvargs):
        super(Migren, 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(Migren, 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, 'migren.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):
                with open(kv_file, encoding='utf-8') as kv:
                    Builder.load_string(kv.read())

    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()]]


    def add_note(self, *args):
        #self.screen.ids.base.add_name_previous_screen()
        #self.nav_drawer.toggle_nav_drawer()
        self.manager.current = 'note'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def add_note2(self, *args):
        #self.screen.ids.base.add_name_previous_screen()
        #self.nav_drawer.toggle_nav_drawer()
        self.manager.current = 'note2'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def add_note3(self, *args):
        #self.screen.ids.base.add_name_previous_screen()
        #self.nav_drawer.toggle_nav_drawer()
        self.manager.current = 'note3'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]



    def show_diary(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.manager.current = 'diary'
        self.screen.ids.action_bar.left_action_items = \
            [['chevron-left', lambda x: self.back_screen(27)]]

    def send_email(self, *args):
        addr_from = "*****@*****.**"  # Отправитель
        password = "******"  # Пароль

        msg = MIMEMultipart()  # Создаем сообщение
        msg['From'] = addr_from  # Адресат
        msg['To'] = self.screen.ids.diary.ids.mail_to.text  # Получатель
        msg['Subject'] = self.screen.ids.diary.ids.theme.text  # Тема сообщения
        users_name = self.screen.ids.diary.ids.user_name.text.replace(' ', '_')
        name = 'diary.xls'
        filepath = os.path.join(os.getcwd(), name)
        filename = os.path.basename(filepath)
        if os.path.isfile(filepath):
            rb = xlrd.open_workbook(filepath, formatting_info=True)
            wb = copy(rb)
            wb.save(users_name+'_diary.xls')
            os.remove(filepath)
        name = users_name+'_diary.xls'
        filepath = os.path.join(os.getcwd(), name)
        filename = os.path.basename(filepath)

        body = 'Дневник головной боли:\n\nПациент: '+ self.screen.ids.diary.ids.user_name.text + '\n'+\
                'Комментарий пациента: ' + self.screen.ids.diary.ids.comment.text + '\n\n' +\
            'Адресс для обратной связи: ' + self.screen.ids.diary.ids.add_mail.text  # Текст сообщения
        msg.attach(MIMEText(body, 'plain'))  # Добавляем в сообщение текст

        if os.path.isfile(filepath):  # Если файл существует
            ctype, encoding = mimetypes.guess_type(filepath)  # Определяем тип файла на основе его расширения
            if ctype is None or encoding is not None:  # Если тип файла не определяется
                ctype = 'application/octet-stream'  # Будем использовать общий тип
            maintype, subtype = ctype.split('/', 1)  # Получаем тип и подтип
            with open(filepath, 'rb') as fp:
                file = MIMEBase(maintype, subtype)  # Используем общий MIME-тип
                file.set_payload(fp.read())  # Добавляем содержимое общего типа (полезную нагрузку)
                fp.close()
            encoders.encode_base64(file)  # Содержимое должно кодироваться как Base64
            file.add_header('Content-Disposition', 'attachment', filename=filename)  # Добавляем заголовки
            msg.attach(file)  # Присоединяем файл к сообщению

        server = smtplib.SMTP_SSL('smtp.yandex.ru', 465)  # Создаем объект SMTP
        server.login(addr_from, password)  # Получаем доступ
        server.send_message(msg)  # Отправляем сообщение
        server.quit()  # Выходим

        rb = xlrd.open_workbook(filepath, formatting_info=True)
        wb = copy(rb)
        wb.save(users_name+'_old_diary.xls')

        self.create_new_table(name)

        toast(self.translation._('Дневник отправлен'))
        self.screen.ids.diary.ids.mail_to.text = ''
        self.screen.ids.diary.ids.theme.text = ''
        self.screen.ids.diary.ids.comment.text = ''

    def create_new_table(self, name, *args):
        font0 = xlwt.Font()
        font0.name = 'Times New Roman'
        font0.bold = True
        style0 = xlwt.XFStyle()
        style0.font = font0
        style1 = xlwt.XFStyle()
        style1.num_format_str = 'D-MMM-YY'
        sheet = str(datetime.now())
        sheet = sheet[0:10]
        wb = xlwt.Workbook()
        ws = wb.add_sheet(sheet)
        Col = ws.col(0)
        Col.width = 256 * 21
        ws.write(0, 0, 'Дата и время', style0)
        Col = ws.col(1)
        Col.width = 256 * 41
        ws.write(0, 1, 'Тип боли', style0)
        Col = ws.col(2)
        Col.width = 256 * 41
        ws.write(0, 2, 'Локализация боли', style0)
        Col = ws.col(3)
        Col.width = 256 * 23
        ws.write(0, 3, 'Продолжительность боли', style0)
        Col = ws.col(4)
        Col.width = 256 * 65
        ws.write(0, 4, 'Комментарий пациента', style0)
        wb.save(name)



    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]PyConversations[/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}]Pechka and Bomj[/color][/ref]\n\n'
                u'[b]Source code:[/b] '
                u'[ref=https://github.com/NikolaevVR/Migrebot]'
                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.screen.ids.license.ids.text_license.text = \
   #         self.translation._('%s') % open(
   #             os.path.join(self.directory, 'LICENSE'), encoding='utf-8').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')
    #    self.screen.ids.action_bar.left_action_items = \
    #        [['chevron-left', lambda x: self.back_screen(27)]]


    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)