Esempio n. 1
0
def Config_GetDefault_Str(*, oConfig: ConfigParser, uSection: str,
                          uOption: str, vDefaultValue: Union[None, bool,
                                                             str]) -> str:
    """
    Replacement for the kivy function

    :param oConfig: The configparser object
    :param uSection: The name of the section
    :param uOption: The name of the option
    :param vDefaultValue: The default value
    :return: The value of an ini setting or the default value
    """
    uDefaultValue: str = u""

    if not oConfig.has_section(uSection):
        oConfig.add_section(uSection)
    if not oConfig.has_option(uSection, uOption):
        if vDefaultValue is not None:
            if type(vDefaultValue) == bool:
                if vDefaultValue:
                    uDefaultValue: str = u'1'
                else:
                    uDefaultValue: str = u'0'
            else:
                uDefaultValue = vDefaultValue
            oConfig.set(uSection, uOption, uDefaultValue)
        return uDefaultValue
    uRetVal: str = ToUnicode(oConfig.get(uSection, uOption))
    return uRetVal
Esempio n. 2
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. 3
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. 4
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. 5
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
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. 7
0
 class AddCardMenuScreen(Screen):
     question = ""
     answer = ""
     def __init__(self):
         Screen.__init__(self)
         self.name = "add"
         
         self.config = ConfigParser()
         self.config.add_section("add")
         self.config.set("add", "question", "Question")
         self.config.set("add", "answer", "Answer")
         self.config.set("add", "make", "action")
         self.config.add_callback(self.update_qa, section="add", key="question")
         self.config.add_callback(self.update_qa, section="add", key="answer")
         self.menu = SettingsWithNoMenu()
         
         
         self.menu.register_type("action", FlashcardAppManager.SettingDoAction)
         self.menu.add_json_panel("Add a card", self.config, os.path.join(os.path.dirname(__file__), 'add_menu.json'))
         
         self.add_widget(self.menu)
         
         
     def update_qa(self, *args):
         FlashcardAppManager.AddCardMenuScreen.question = self.config.get('add', 'question')
         FlashcardAppManager.AddCardMenuScreen.answer = self.config.get('add', 'answer')
Esempio n. 8
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. 9
0
    def update(self):
        """
        add data to Category settings

        retrieves data from database for a particular 'catid'
        """
        #/// add data ///

        self.clear_widgets()

        #define structure of fields (like an INI file)
        config = ConfigParser()
        config.add_section('category')
        config.add_section('icon_file')

        #--- set values (needs to come from database)
        #config.set('category','category_name','TestnameID: ' + str(self.catid))
        if self.data == None:
            config.set('category','category_name','Enter your category name here')
        else:
            config.set('category','category_name',self.data['name'])
        config.set('icon_file','icon_file','Testpath') #todo:how to deal with image data ???

        return config
Esempio n. 10
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. 11
0
class InterfaceManager(
        MDApp, BoxLayout,
        App):  #, FocusBehavior, LayoutSelectionBehavior,RecycleBoxLayout):
    def __init__(self, *args, **kwargs):

        self.clear_widgets()
        self.Start = False
        self.icon = 'logo_transparent.ico'
        try:
            self.capture.release()
        except:
            pass
        #self.main_layout.clear_widgets()
        super().__init__(**kwargs)
        self.config = ConfigParser()
        self.main_layout = BoxLayout(orientation="vertical")
        self.config.read('my.ini')
        lang = self.config.get('My Label', 'text')
        self.lang = lang
        size_label = self.config.get('My Label', 'font_size')
        if lang == 'ru':
            with open('yolov3-ru.txt', 'r') as f:
                self.classes = [line.strip() for line in f.readlines()]
            with open('yolov3.txt', 'r') as f:
                self.classes_en = [line.strip() for line in f.readlines()]
        else:
            with open('yolov3.txt', 'r') as f:
                self.classes = [line.strip() for line in f.readlines()]
            with open('yolov3.txt', 'r') as f:
                self.classes_en = [line.strip() for line in f.readlines()]
        if size_label == 'huge':
            self.font_size = 40
        elif size_label == 'medium':
            self.font_size = 30
        else:
            self.font_size = 20
        self.dict_classes = dict()
        for i in self.classes:
            self.dict_classes.update({i: True})
        self.translator = Translator(to_lang=self.lang)
        super(InterfaceManager, self).__init__(**kwargs)
        self.btn = Button(
            text=self.translator.translate("Tap the screen\n to start"),
            font_size=self.font_size)
        self.btn.bind(on_press=self.stop)

        self.btn8 = Button(text=self.translator.translate('Settings'),
                           background_color=(0, 1, 1, 1),
                           color=(1, 1, 1, 1),
                           size_hint_y=None,
                           height=60,
                           font_size=self.font_size)
        self.btn8.bind(on_press=self.settings)
        self.main_layout.add_widget(self.btn8)
        self.main_layout.add_widget(self.btn)
        self.add_widget(self.main_layout)
        self.theme_cls.primary_palette = "Gray"
        self.settings_cls = MySettingsWithTabbedPanel

    def settings(self, ev):
        self.clear_widgets()
        self.config = ConfigParser()
        self.config.read('my.ini')
        main_layout = BoxLayout(orientation="vertical")
        dropdown = DropDown()
        main_layout_1 = BoxLayout(orientation="horizontal")
        main_layout.add_widget(
            Label(text=self.translator.translate('Settings'),
                  color=(0, 0, 0, 1),
                  font_size=self.font_size * 2))
        for index in ['en', 'ru']:
            btn = Button(text='{}'.format(index),
                         size_hint_y=None,
                         height=60,
                         font_size=self.font_size)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)
        self.mainbutton = Button(text=self.config.get('My Label', 'text'),
                                 size_hint=(None, None),
                                 height=60,
                                 font_size=self.font_size,
                                 background_color=(0, 0, 1, 1))
        self.mainbutton.bind(on_release=dropdown.open)
        dropdown.bind(on_select=self.change_lg)
        main_layout_1.add_widget(
            Label(text=self.translator.translate('Language'),
                  color=(0, 0, 0, 1),
                  font_size=self.font_size))
        main_layout_1.add_widget(self.mainbutton)
        main_layout.add_widget(main_layout_1)
        dropdown1 = DropDown()
        main_layout_1 = BoxLayout(orientation="horizontal")
        for index in ['huge', 'medium', 'small']:
            btn = Button(text='{}'.format(index),
                         size_hint_y=None,
                         height=60,
                         font_size=self.font_size)
            btn.bind(on_release=lambda btn: dropdown1.select(btn.text))
            dropdown1.add_widget(btn)
        self.mainbutton1 = Button(text=self.config.get('My Label',
                                                       'font_size'),
                                  size_hint=(None, None),
                                  height=60,
                                  font_size=self.font_size,
                                  background_color=(0, 0, 1, 1))
        self.mainbutton1.bind(on_release=dropdown1.open)
        dropdown1.bind(on_select=self.change_sz)
        main_layout_1.add_widget(
            Label(text=self.translator.translate('Font Size'),
                  color=(0, 0, 0.0, 1),
                  font_size=self.font_size))
        main_layout_1.add_widget(self.mainbutton1)
        main_layout.add_widget(main_layout_1)
        self.btn5 = Button(text=self.translator.translate('Main'),
                           background_color=(0, 1, 1, 1),
                           color=(1, 1, 1, 1),
                           size_hint_y=None,
                           height=40,
                           font_size=self.font_size)
        self.btn5.bind(on_press=self.__init__)
        main_layout.add_widget(self.btn5)
        self.add_widget(main_layout)

    def change_lg(self, ev, instance, *args):
        self.config = ConfigParser()
        self.config.read('my.ini')
        button_text = instance
        setattr(self.mainbutton, 'text', button_text)
        self.config.set('My Label', 'text', button_text)
        self.config.write()

    def change_sz(self, ev, instance, *args):
        self.config = ConfigParser()
        self.config.read('my.ini')
        button_text = instance
        setattr(self.mainbutton1, 'text', button_text)
        self.config.set('My Label', 'font_size', button_text)
        self.config.write()

    def start(self, event):
        try:
            self.capture.release()
        except:
            pass
        self.main_layout = BoxLayout(orientation="vertical")
        self.counter = 0
        self.prev = ''
        self.net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
        self.clear_widgets()
        self.title = "KivyMD Examples - Progress Loader"

        self.Start = True
        try:
            if self.find != '':
                self.find = self.find
            else:
                self.find = ''
        except:
            self.find = ''
        self.text_input = TextInput(multiline=False,
                                    size_hint=(1, 0.1 * (self.font_size / 20)),
                                    font_size=self.font_size,
                                    pos_hint={
                                        'center_x': 0.5,
                                        'center_y': 0.95
                                    })
        self.text_input.bind(text=self.on_text)
        self.text_input_1 = TextInput(multiline=False,
                                      size_hint=(1,
                                                 0.1 * (self.font_size / 20)),
                                      font_size=self.font_size,
                                      pos_hint={
                                          'center_x': 0.5,
                                          'center_y': 0.95
                                      })
        self.text_input_1.bind(text=self.on_text)
        self.text_input_2 = TextInput(multiline=False,
                                      size_hint=(1,
                                                 0.1 * (self.font_size / 20)),
                                      font_size=self.font_size,
                                      pos_hint={
                                          'center_x': 0.5,
                                          'center_y': 0.95
                                      })
        self.text_input_2.bind(text=self.on_text)
        self.text_input_4 = TextInput(multiline=False,
                                      size_hint=(1,
                                                 0.1 * (self.font_size / 20)),
                                      font_size=self.font_size,
                                      pos_hint={
                                          'center_x': 0.5,
                                          'center_y': 0.95
                                      })
        self.text_input_4.bind(text=self.on_text)
        self.second = Button(text="Second")
        self.final = Label(text="Hello World")
        self.single = False
        self.lab = 'Показывать один объект'
        self.img1 = Image(size_hint=(2, 2),
                          pos_hint={
                              'center_x': 0.5,
                              'center_y': 0.8
                          })

        self.btn = Button(text=self.translator.translate("Aloud"),
                          font_size=self.font_size,
                          background_color=(1, 1, 1, 1),
                          color=(1, 1, 1, 1),
                          size=(32, 32),
                          size_hint=(.2, .5),
                          pos=(300, 300))

        self.btn.bind(on_press=self.callback_1)

        self.btn_2 = ToggleButton(text=self.translator.translate('One'),
                                  font_size=self.font_size,
                                  background_color=(1, 1, 1, 1),
                                  color=(1, 1, 1, 1),
                                  size=(32, 32),
                                  size_hint=(.2, .5),
                                  pos=(300, 250))
        self.btn_3 = ToggleButton(text=self.translator.translate('Fast'),
                                  font_size=self.font_size,
                                  background_color=(1, 1, 1, 1),
                                  color=(1, 1, 1, 1),
                                  size=(32, 32),
                                  size_hint=(.2, .5),
                                  pos=(300, 250))
        self.fast = False
        self.btn_2.bind(on_press=self.callback_2)

        self.btn_3.bind(on_press=self.callback_3)
        self.first = Button(text=self.translator.translate("Look for"),
                            font_size=self.font_size,
                            background_color=(1, 1, 1, 1),
                            color=(1, 1, 1, 1),
                            size=(32, 32),
                            size_hint=(.2, .5),
                            pos=(20, 25))

        if self.find:
            self.btn5 = Button(text=self.translator.translate(
                'Look for {}'.format(self.find)),
                               background_color=(0, 1, 1, 1),
                               font_size=self.font_size,
                               color=(1, 1, 1, 1),
                               size_hint_y=None,
                               height=40)
        else:
            self.btn5 = Button(text=self.translator.translate('Exit'),
                               background_color=(0, 1, 1, 1),
                               color=(1, 1, 1, 1),
                               font_size=self.font_size,
                               size_hint_y=None,
                               height=40)
        self.btn5.bind(on_press=self.start)
        if self.find:
            self.btn_5 = Button(text=self.translator.translate(
                'Look for {}'.format(self.find)),
                                background_color=(0, 1, 1, 1),
                                color=(1, 1, 1, 1),
                                font_size=self.font_size,
                                size_hint_y=None,
                                height=40)
        else:
            self.btn_5 = Button(text=self.translator.translate('Exit'),
                                background_color=(0, 1, 1, 1),
                                color=(1, 1, 1, 1),
                                font_size=self.font_size,
                                size_hint_y=None,
                                height=40)
        self.btn_5.bind(on_press=self.start)
        self.first.bind(on_press=self.show_second)
        self.capture = cv2.VideoCapture(0)

        self.bind(on_load=self.cb_loaded)
        self.matches = []
        self.main_layout = BoxLayout(orientation="vertical")
        self.main_layout_1 = BoxLayout(orientation="horizontal")
        if not self.find:
            self.clear_widgets()
            self.main_layout.clear_widgets()
            self.main_layout.add_widget(self.img1)
            self.main_layout_1.add_widget(self.btn)
            self.main_layout_1.add_widget(self.btn_2)
            self.main_layout_1.add_widget(self.first)
            self.main_layout_1.add_widget(self.btn_3)
            self.main_layout.add_widget(self.main_layout_1)
            self.add_widget(self.main_layout)
            self.btn8 = Button(text=self.translator.translate('Main'),
                               background_color=(0, 1, 1, 1),
                               color=(1, 1, 1, 1),
                               size_hint_y=None,
                               height=40,
                               font_size=self.font_size)
            self.btn8.bind(on_press=self.__init__)
            self.main_layout.add_widget(self.btn8)
            Clock.schedule_interval(self.update, 1.0 / 33.0)
        else:
            if self.Start:
                self.clear_widgets()
                self.main_layout.clear_widgets()
                self.Stop = False
                self.p = 0
                self.btn_6 = Button(text=self.translator.translate('Finish'),
                                    background_color=(1, 1, 1, 1),
                                    color=(1, 1, 1, 1),
                                    font_size=self.font_size,
                                    size_hint_y=None,
                                    height=40)
                self.btn_6.bind(on_press=self.stop)
                self.net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
                self.clear_widgets()
                self.main_layout.add_widget(self.img1)
                self.main_layout.add_widget(self.btn_6)
                self.add_widget(self.main_layout)
                Clock.schedule_interval(self.update, 1.0 / 33.0)

    def stop(self, event):
        self.find = ''
        self.start(0)

    def cb_loaded(self):
        self.clear_widgets()
        self.add_widget(self.btn_3)

    def update(self, df, pryams=[]):
        if self.Start:
            ret, frame = self.capture.read()
            frame = cv2.resize(frame, (800, 450))
            if not self.find:
                frame, self.indices, self.boxes, self.classes_ids, self.d = preprocess(
                    frame, self.single, self.net, self.classes,
                    self.classes_en, self.dict_classes)
            else:
                if self.Start:
                    frame, self.Stop, self.p = finder(frame, self.find,
                                                      self.lang, self.classes,
                                                      self.classes_en,
                                                      self.dict_classes)
            frame = cv2.flip(frame, 0)
            buf = frame.tostring()
            texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]),
                                      colorfmt='bgr')
            texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            self.img1.texture = texture1

    def callback_1(self, event):
        self.update(0, pryams=[[100, 100, 200, 200]])
        d = self.d
        for i in d:
            if d[i] == 1:
                translation = self.translator.translate(str(d[i]) + ' ' + i)
            else:
                if i[-1] in ['x', 's', 'o', 'ss', 'sh', 'ch']:
                    translation = self.translator.translate(
                        str(d[i]) + ' ' + i + 'es')
                else:
                    translation = self.translator.translate(
                        str(d[i]) + ' ' + i)
            say_bitch((translation), self.lang)

    def callback_2(self, event):
        if self.single:
            self.single = False
            self.lab = 'Показывать несколько объектов'
        else:
            self.single = True
            self.lab = 'Показывать один объект'

    def callback_3(self, event):
        if self.fast:
            self.net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
            self.fast = False
            self.clear_widgets()
            self.main_layout.clear_widgets()
            self.main_layout_1.clear_widgets()
            self.btn_3 = ToggleButton(text=self.translator.translate('Fast'),
                                      font_size=self.font_size,
                                      background_color=(1, 1, 1, 1),
                                      color=(1, 1, 1, 1),
                                      size=(32, 32),
                                      size_hint=(.2, .5),
                                      pos=(300, 250))
            self.btn_3.bind(on_press=self.callback_3)
            self.add_widget(self.btn_3)
            self.clear_widgets()
            self.main_layout.clear_widgets()
            self.main_layout.add_widget(self.img1)
            self.main_layout_1.add_widget(self.btn)
            self.main_layout_1.add_widget(self.btn_2)
            self.main_layout_1.add_widget(self.first)
            self.main_layout_1.add_widget(self.btn_3)
            self.main_layout.add_widget(self.main_layout_1)
            self.btn8 = Button(text=self.translator.translate('Main'),
                               background_color=(0, 1, 1, 1),
                               color=(1, 1, 1, 1),
                               size_hint_y=None,
                               height=40,
                               font_size=self.font_size)
            self.btn8.bind(on_press=self.__init__)
            self.main_layout.add_widget(self.btn8)
            self.add_widget(self.main_layout)
        else:
            self.fast = True
            self.net = cv2.dnn.readNet('yolov3-tiny.weights',
                                       'yolov3-tiny.cfg')
            self.clear_widgets()
            self.main_layout.clear_widgets()
            self.main_layout_1.clear_widgets()
            self.btn_3 = ToggleButton(
                text=self.translator.translate('Accurate'),
                font_size=self.font_size,
                background_color=(1, 1, 1, 1),
                color=(1, 1, 1, 1),
                size=(32, 32),
                size_hint=(.2, .5),
                pos=(300, 250))
            self.btn_3.bind(on_press=self.callback_3)
            self.clear_widgets()
            self.main_layout.clear_widgets()
            self.main_layout.add_widget(self.img1)
            self.main_layout_1.add_widget(self.btn)
            self.main_layout_1.add_widget(self.btn_2)
            self.main_layout_1.add_widget(self.first)
            self.main_layout_1.add_widget(self.btn_3)
            self.main_layout.add_widget(self.main_layout_1)
            self.btn8 = Button(text=self.translator.translate('Main'),
                               background_color=(0, 1, 1, 1),
                               color=(1, 1, 1, 1),
                               size_hint_y=None,
                               height=40,
                               font_size=self.font_size)
            self.btn8.bind(on_press=self.__init__)
            self.main_layout.add_widget(self.btn8)
            self.add_widget(self.main_layout)

    def show_second(self, button):
        try:
            self.capture.release()
        except:
            pass
        self.Start = False
        self.clear_widgets()
        self.main_layout.clear_widgets()
        self.word_list = self.classes
        main_layout = BoxLayout(orientation="vertical")
        self.main_layout.add_widget(self.text_input)
        self.btn5.bind(on_press=self.start)
        self.main_layout.add_widget(self.btn5)
        self.add_widget(self.main_layout)

    def on_text(self, instance, value):
        if value != self.prev and value != '':
            self.suggestion_text = ''
            val = value[value.rfind(' ') + 1:]
            self.prev = value
            if value != '':
                matches = [
                    self.word_list[i] for i in range(len(self.word_list))
                    if value in self.word_list[i][:len(value)]
                ]
            else:
                matches = []
            self.matches = matches
            #self.text_input = TextInput(multiline=False, size_hint=(1, 0.1), pos_hint={'center_x': 0.5, 'center_y': 0.95})
            #self.text_input.bind(text=self.on_text)
            #main_layout_1 = BoxLayout(orientation="vertical")
            if len(matches) != 0:
                self.clear_widgets()
                self.main_layout.clear_widgets()
                main_layout_1 = BoxLayout(orientation="vertical")
                self.text_input_1 = TextInput(
                    multiline=False,
                    size_hint=(1, 0.1 * (self.font_size / 20)),
                    font_size=self.font_size,
                    pos_hint={
                        'center_x': 0.5,
                        'center_y': 0.95
                    })
                self.text_input_1.bind(text=self.on_text)
                self.main_layout.add_widget(self.text_input)
                if self.find:
                    self.btn_5 = Button(text=self.translator.translate(
                        'Look for {}'.format(self.find)),
                                        background_color=(0, 1, 1, 1),
                                        font_size=self.font_size,
                                        color=(1, 1, 1, 1),
                                        size_hint_y=None,
                                        height=40)
                else:
                    self.btn_5 = Button(text=self.translator.translate('Exit'),
                                        background_color=(0, 1, 1, 1),
                                        color=(1, 1, 1, 1),
                                        font_size=self.font_size,
                                        size_hint_y=None,
                                        height=40)
                self.btn_5.bind(on_press=self.start)

                main_layout = BoxLayout(orientation="vertical")
                for i in matches:
                    self.btn = Button(text=i,
                                      background_color=(1, 1, 1, 1),
                                      color=(1, 1, 1, 1),
                                      font_size=self.font_size,
                                      size_hint_y=None,
                                      height=40)

                    # bind() use to bind the button to function callback
                    self.btn.bind(on_press=self.Pressbtn)
                    main_layout.add_widget(self.btn)
                self.main_layout.add_widget(main_layout)

                self.main_layout.add_widget(self.btn_5)
                self.add_widget(self.main_layout)
                #self.add_widget(main_layout_1)
                return
            else:
                return
            if not val:
                return
            try:
                word = [
                    word for word in self.word_list if word.startswith(val)
                ][0][len(val):]
                if not word:
                    return
                self.suggestion_text = word
            except IndexError:
                print('Index Error.')

    def Pressbtn(self, instance):
        button_text = instance.text
        self.main_layout.clear_widgets()
        self.find = button_text
        if self.find:
            self.btn5 = Button(text=self.translator.translate(
                'Look for {}'.format(self.find)),
                               background_color=(0, 1, 1, 1),
                               color=(1, 1, 1, 1),
                               size_hint_y=None,
                               font_size=self.font_size,
                               height=40)
        else:
            self.btn5 = Button(text=self.translator.translate('Exit'),
                               background_color=(0, 1, 1, 1),
                               color=(1, 1, 1, 1),
                               font_size=self.font_size,
                               size_hint_y=None,
                               height=40)
        self.clear_widgets()
        self.btn5.bind(on_press=self.start)
        # TODO: добавить действие для btn5
        main_layout_1 = BoxLayout(orientation="vertical")
        self.text_input.bind(text=self.on_text)
        self.main_layout.add_widget(self.text_input)
        main_layout = BoxLayout(orientation="vertical")
        for i in self.matches:
            self.btn = Button(text=i,
                              background_color=(1, 1, 1, 1),
                              color=(1, 1, 1, 1),
                              font_size=self.font_size,
                              size_hint_y=None,
                              height=40)

            # bind() use to bind the button to function callback
            self.btn.bind(on_press=self.Pressbtn)
            main_layout.add_widget(self.btn)
        self.main_layout.add_widget(main_layout)
        self.main_layout.add_widget(self.btn5)
        self.add_widget(self.main_layout)

    def on_stop(self):
        # without this, app will not exit even if the window is closed
        self.capture.release()
Esempio n. 12
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. 13
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)

    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. 14
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 = '.'

    def __init__(self, data_dir, save_timeout=2, **kwargs):
        self._schedule_save = Clock.create_trigger(self.save, save_timeout)
        self.prefs_file = data_dir + '/' + self.prefs_file_name
        self.data_dir = data_dir
        self.load()

    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 get_default_user_dir(self):
        if platform() == 'win':
            user_path = dirname(expanduser('~')) + sep + 'Documents'
        elif platform() == 'android':
            from jnius import autoclass
            env = autoclass('android.os.Environment')
            user_path = env.getExternalStorageDirectory().getPath()
        else:
            user_path = expanduser('~') + sep + 'Documents'
        return user_path

    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_dir = self.get_default_user_dir()
        self.config.setdefault('preferences', 'config_file_dir',
                               default_user_dir)
        self.config.setdefault('preferences', 'firmware_dir', default_user_dir)

    def load(self):
        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. 15
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. 16
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. 17
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. 18
0
    def update(self):
        """
        add data to Category settings

        retrieves data from database for a particular 'catid'
        """
        #/// add data ///

        self.clear_widgets()

        #define structure of fields (like an INI file)
        config = ConfigParser()
        config.add_section('market')
        config.add_section('location')

        #--- set values (needs to come from database)
        #config.set('category','category_name','TestnameID: ' + str(self.catid))
        if self.data == None:
            config.set('market','day','Enter the market DAY here')
            config.set('location','lon','enter longitude here')
            config.set('location','lat','enter latitude here')
            config.set('location','place_name','enter place name here')
            config.set('location','ranking','Ranking here')
            config.set('location','visited',False)
        else:
            config.set('market','day',self.data['day'])

        return config
Esempio n. 19
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. 20
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. 21
0
class MainApp(MDApp):
    # Language: get system locale.
    lang = StringProperty(locale.getdefaultlocale()[0][:2])
    # For showing/hiding search widget.
    is_search_focused = BooleanProperty(False)
    is_first_started = BooleanProperty(True)
    app_primary_palette = StringProperty("Teal")

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.selected_dampers = [
        ]  # Every damper selected by MyRightCheckbox add to this list.
        self.all_dampers_in_container = [
        ]  # Consists of all adding DamperListItem.
        self.damper = None
        self.dampers = [
        ]  # Has all getting dampers (class Damper) from the DB.
        self.found_dampers = []  # Has all found in searching dampers.
        self.menu_sort = None
        self.menu_dots = None
        # For exit on double tap on the buttnon back.
        self.is_back_clicked_once = False
        # My config.
        self.config = ConfigParser()
        # App theme.
        self.primary_palette = "Teal"
        self.accent_palette = "Amber"
        self.theme_style = "Light"
        # To avoid multi chosen right_checkbox_lang.
        self.lang_checkboxes_dict = dict()
        # Handling the back button.
        Window.bind(on_keyboard=self.key_input)
        # The current target TextInput widget requesting the keyboard
        # is presented just above the soft keyboard.
        Window.softinput_mode = "below_target"

    def build_config(self, config):
        """Default config."""
        self.config.setdefaults(
            "currenttheme", {
                "primary_palette": "Teal",
                "accent_palette": "Amber",
                "theme_style": "Light"
            })
        self.config.setdefaults("applanguage", {"language": self.lang})

    def save_config(self):
        """Save the App config."""
        self.config.set("currenttheme", "primary_palette",
                        self.primary_palette)
        self.config.set("currenttheme", "accent_palette", self.accent_palette)
        self.config.set("currenttheme", "theme_style", self.theme_style)
        self.config.set("applanguage", "language", self.lang)
        self.config.write()

    def my_load_config(self):
        """Load the App config."""
        self.primary_palette = self.config.get("currenttheme",
                                               "primary_palette")
        self.accent_palette = self.config.get("currenttheme", "accent_palette")
        self.theme_style = self.config.get("currenttheme", "theme_style")
        self.lang = self.config.get("applanguage", "language")

    def apply_mytoolbar_theme(self):
        """Apply loaded theme for MyToolbar."""
        self.theme_cls.primary_palette = self.primary_palette
        self.theme_cls.accent_palette = self.accent_palette
        self.theme_cls.theme_style = self.theme_style

    def build(self):
        # Loading and applying the App config.
        # Impossible to execute self.my_load_config() in __init__
        # because of configparser.NoSectionError: No section: 'currenttheme'.
        self.my_load_config()
        # Instantiate an instance of Lang.
        self.tr = Lang(self.lang)
        self.title = self.tr._("Dampers")

        self.menu_items_dots = [{
            "text": self.tr._("Select all"),
            "icon": "select-all"
        }, {
            "text": self.tr._("Cancel all selection"),
            "icon": "select-off"
        }, {
            "text": self.tr._("Add type"),
            "icon": "plus"
        }, {
            "text": self.tr._("Delete/Edit type"),
            "icon": "delete-outline"
        }, {
            "text": self.tr._("Add damper"),
            "icon": "plus"
        }, {
            "text": self.tr._("Edit selected damper"),
            "icon": "square-edit-outline"
        }, {
            "text": self.tr._("Delete selected dampers"),
            "icon": "delete-outline"
        }, {
            "text": self.tr._("Backup Database"),
            "icon": "content-save-outline"
        }, {
            "text": self.tr._("Restore Database"),
            "icon": "backup-restore"
        }, {
            "text": self.tr._("Clear DB"),
            "icon": "delete-forever-outline"
        }, {
            "text": self.tr._("Language"),
            "icon": "web"
        }, {
            "text": self.tr._("Change theme"),
            "icon": "theme-light-dark"
        }, {
            "text": self.tr._("Exit"),
            "icon": "exit-to-app"
        }]
        # Dict to process callback_menu_dots like switch in C++.
        self.dict_menu_dots_funcs = {
            self.tr._("Select all"):
            self.select_all,
            self.tr._("Cancel all selection"):
            self.cancel_all_selection,
            self.tr._("Add type"):
            partial(self.change_screen, "add_type_screen"),
            self.tr._("Delete/Edit type"):
            partial(self.change_screen, "delete_edit_type_screen"),
            self.tr._("Add damper"):
            partial(self.change_screen, "add_damper_screen"),
            self.tr._("Edit selected damper"):
            self.edit_selected_damper,
            self.tr._("Delete selected dampers"):
            self.show_delete_dampers_dialog,
            self.tr._("Backup Database"):
            self.choose,
            self.tr._("Restore Database"):
            partial(self.choose, False),
            self.tr._("Clear DB"):
            self.show_clear_db_dialog,
            self.tr._("Language"):
            partial(self.change_screen, "language_screen"),
            self.tr._("Change theme"):
            self.show_themepicker,
            self.tr._("Exit"):
            self.stop
        }

        self.menu_items_sort = [{
            "text": self.tr._("By 'number'"),
            "icon": "sort-numeric"
        }, {
            "text": self.tr._("By 'location'"),
            "icon": "format-columns"
        }, {
            "text": self.tr._("By 'check date'"),
            "icon": "calendar-month"
        }, {
            "text": self.tr._("By 'is released'"),
            "icon": "check-outline"
        }, {
            "text": self.tr._("By 'no order'"),
            "icon": "not-equal-variant"
        }
                                # "icon": "sort-variant-remove"}
                                ]
        # Dict to process callback_menu_sort like switch in C++..
        self.dict_menu_sort_funcs = {
            self.tr._("By 'number'"):
            partial(self.get_dampers, "by number"),
            self.tr._("By 'location'"):
            partial(self.get_dampers, "by location"),
            self.tr._("By 'check date'"):
            partial(self.get_dampers, "by check date"),
            self.tr._("By 'is released'"):
            partial(self.get_dampers, "by is released"),
            self.tr._("By 'no order'"):
            self.get_dampers
        }
        # Handling the back button.
        # Window.bind(on_keyboard=self.key_input)
        # The current target TextInput widget requesting the keyboard
        # is presented just above the soft keyboard.
        # Window.softinput_mode = "below_target"

        return Container()

    def on_start(self):
        if platform == "android":
            # Runtime permissions.
            from android.permissions import request_permissions, Permission
            request_permissions([
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE
            ])

        self.apply_mytoolbar_theme()

        self.screen_manager = self.root.ids["screen_manager"]
        self.home_screen = self.root.ids["home_screen"]
        self.dampers_container = self.home_screen.ids["dampers_container"]
        self.tf_search = self.home_screen.ids["tf_search"]
        self.container = self.home_screen.ids["container"]
        self.lang_screen = self.root.ids["language_screen"]
        # For passing old_damper info into the EditDamperScreen.
        self.edit_damper_screen = self.root.ids["edit_damper_screen"]
        # Creating MyToolbar dots and sort menus.
        self.menu_dots = MDDropdownMenu(
            caller=self.home_screen.ids["tb_home"].ids["ibtn_dots"],
            items=self.menu_items_dots,
            callback=self.callback_menu_dots,
            position="bottom",
            hor_growth="right",
            # ver_growth="down",
            width_mult=10)
        self.menu_sort = MDDropdownMenu(
            caller=self.home_screen.ids["tb_home"].ids["ibtn_sort"],
            items=self.menu_items_sort,
            callback=self.callback_menu_sort,
            position="bottom",
            hor_growth="right",
            # ver_growth="up",
            width_mult=7)
        self.change_toolbar_theme()

        self.add_lang_checkboxes_into_dict()
        self.lang_checkboxes_dict[self.lang].active = True

        self.get_dampers()
        self.is_first_started = False

    def add_lang_checkboxes_into_dict(self):
        """
        Store all right_checkbox_(lang) into the lang_checkboxes_dict
        to control which right_checkbox is chosen.
        """
        self.lang_checkboxes_dict["en"] = self.lang_screen.ids[
            "right_checkbox_en"]
        self.lang_checkboxes_dict["ru"] = self.lang_screen.ids[
            "right_checkbox_ru"]

    def on_stop(self):
        """Save config."""
        self.save_config()

    def on_pause(self):
        return True

    def on_resume(self):
        pass

    def on_lang(self, instance, lang):
        """User changed language."""
        # Skip the first tr.switch_lang
        # because self.tr is not defined yet.
        # The first switch will be in the build method: self.tr = Lang(self.lang)
        # after self.my_load_config().
        if not self.is_first_started:
            self.tr.switch_lang(lang)

            dialog = MDDialog(title=self.tr._("Change language"),
                              size_hint=(.7, .4),
                              text_button_ok=self.tr._("Ok"),
                              auto_dismiss=False,
                              events_callback=self.stop,
                              text=self.tr._(
                                  "You have to restart the app"
                                  "\nto change the language completely."))
            dialog.open()

    def key_input(self, window, key, scancode, codepoint, modifier):
        def reset_btn_back_clicked(*args):
            """
            Set is_back_clicked_once to False.
            There was no double click on the button back for exit.
            """
            self.is_back_clicked_once = False

        if key == 27:  # (the back button key is 27, codepoint is 270).
            if self.screen_manager.current != "home_screen":
                self.change_screen("home_screen")
            elif self.is_back_clicked_once:
                self.stop()
            else:
                self.is_back_clicked_once = True
                toast(self.tr._("Tap BACK again to exit"), duration=1)
                Clock.schedule_once(reset_btn_back_clicked, 3)

            return True
        return False

    def callback_menu_sort(self, instance):
        """
        Check what item in the menu_sort pressed and
        do the action according pressed menu item.
        Actions are in the self.dict_menu_sort.
        """
        self.dict_menu_sort_funcs.get(instance.text)()

    def callback_menu_dots(self, instance):
        """
        Check what item in the menu_dots pressed and
        do the action according pressed menu item.
        Actions are in the self.dict_menu_dots.
        """
        self.dict_menu_dots_funcs.get(instance.text)()

    def get_dampers(self, order="no order", *args):
        """
        Get all dampers from the DB and store them into self.dampers.
        :param order: str for sorting can be:
                                    "by number", "by location",
                                    "by check date", by is released",
                                    "no order"
        """
        self.damper = Damper()
        try:
            self.dampers = self.damper.get_dampers(order)
        except sqlite3.DatabaseError:
            toast(self.tr._("Can't get dampers from the DB"))
        else:
            # Not to show_dampers in the first start
            # because it'll be done in change_screen.
            if not self.is_first_started:
                self.show_dampers()

    def show_dampers(self, is_search=False, *args):
        """
        Get all dampers from the DB and show them.
        :param args: for Clock.schedule_once(self.set_field_focus, 1) in self.clear_db
        :param is_search: if True show only found dampers in self.found_dampers.
        """
        # Hide search if not search.
        if not is_search:
            self.hide_search()

        if self.all_dampers_in_container:
            for damper in self.all_dampers_in_container:
                self.dampers_container.remove_widget(damper)

        # Clear all selections.
        self.selected_dampers.clear()
        self.all_dampers_in_container.clear()

        # If search show only found dampers in self.found_dampers.
        dampers = self.found_dampers if is_search else self.dampers
        if self.dampers:
            for self.damper in dampers:
                # Format for output damper data.
                released = "Released" if self.damper.is_released else "Not released"
                text = "{}        {}".format(self.damper.number,
                                             self.damper.location)
                secondary_text = "{}       {}".format(self.damper.check_date,
                                                      released)
                tertiary_text = "{}          {}".format(
                    self.damper.d_type, self.damper.notes)

                a_damper_list_item = DamperListItem(
                    text=text,
                    secondary_text=secondary_text,
                    tertiary_text=tertiary_text)
                self.dampers_container.add_widget(a_damper_list_item)
                # Add all adding DamperListItem to the list for
                # getting access to right_checkbox_dampers in the future.
                self.all_dampers_in_container.append(a_damper_list_item)
        else:
            # Clock.schedule_once(lambda x: (toast("No dampers in the DB")), 4)
            toast(self.tr._("No dampers in the DB"))

    def show_search(self, *args):
        """Show search."""
        self.tf_search.focused = True
        self.is_search_focused = True
        # Slide tf_search top down from .96 to .9
        anim_search = Animation(top_hint_search=.9)
        anim_search.start(self.tf_search)

        # Slide container(GridLayout) top down from .9 to .84
        anim_container = Animation(top_hint_container=.84)
        anim_container.start(self.container)

    def hide_search(self, *args):
        """Hide search."""
        self.is_search_focused = False
        # Clear tf_search when hiding.
        self.tf_search.text = ""
        # Slide tf_search top up from .9 to .96
        anim_search = Animation(top_hint_search=.96)
        anim_search.start(self.tf_search)

        # Slide container(GridLayout) top up from .84 to .9
        anim_container = Animation(top_hint_container=.9)
        anim_container.start(self.container)

    def search_text_changed(self, finding_text):
        """
        Search dampers by finding_text,
        add filtered dampers to the self.found_dampers
        and output them in self.show_dampers.
        :param finding_text:
        """
        self.found_dampers = []
        for self.damper in self.dampers:
            if (finding_text in self.damper.number
                    or finding_text in self.damper.location
                    or finding_text in self.damper.check_date):
                self.found_dampers.append(self.damper)
        self.show_dampers(is_search=True)

    def choose(self, is_backup=True, *args):
        """
        Call plyer filechooser API to run a filechooser Activity.
        """
        if platform == "android":
            from android.permissions import request_permissions, Permission, check_permission
            # Check if the permissions still granted.
            if not check_permission(Permission.WRITE_EXTERNAL_STORAGE):
                request_permissions([Permission.WRITE_EXTERNAL_STORAGE])
            else:
                filechooser.open_file(on_selection=self.backup_db
                                      if is_backup else self.restore_db)
        else:
            filechooser.open_file(
                on_selection=self.backup_db if is_backup else self.restore_db)

    def backup_db(self, selection):
        """Backup Database."""
        # chosen_dir = filechooser.choose_dir(title="Choose directory")  # Doesn't work on Android (why?).
        chosen_dirname = os.path.dirname(selection[0])
        now = datetime.now()
        now_datetime = ("{}-{}-{}_{}-{}-{}".format(now.year,
                                                   str(now.month).zfill(2),
                                                   str(now.day).zfill(2),
                                                   str(now.hour).zfill(2),
                                                   str(now.minute).zfill(2),
                                                   str(now.second).zfill(2)))
        # dirname = os.path.dirname(__file__)  # doesn't work on Android.
        dirname = os.getcwd()
        src_db_path = "{}{}dampers.db".format(dirname, os.sep)
        dst_filename = "{}{}{}_{}".format(chosen_dirname, os.sep, now_datetime,
                                          "dampers.db")
        try:
            shutil.copyfile(src_db_path, dst_filename)
        except OSError as err:
            toast(str(err))
            # toast("SaveBackupError")
        else:
            toast(self.tr._("Backup file saved"))

    def restore_db(self, selection):
        """Restore Database."""
        # dst_db_path = os.path.dirname(__file__)   # doesn't work on Android.
        dst_db_path = os.getcwd()
        try:
            shutil.copyfile(selection[0],
                            "{}{}{}".format(dst_db_path, os.sep, "dampers.db"))
        except OSError as err:
            toast(str(err))
            # toast("RestoreBackupError")
        else:
            toast(self.tr._("Backup file restored"))
            # Get and show dampers after restoring.
            self.get_dampers()

    def show_themepicker(self, *args):
        picker = MDThemePicker()
        picker.open()
        picker.bind(on_dismiss=self.themepicker_dismiss)

    def themepicker_dismiss(self, instance):
        """
        Changing the App primary_palette, accent_palette and theme_style.
        :param instance: current MDThemePicker.
        """
        self.primary_palette = self.theme_cls.primary_palette
        self.accent_palette = self.theme_cls.accent_palette
        self.theme_style = self.theme_cls.theme_style

        self.change_toolbar_theme()
        self.save_config()

    def change_toolbar_theme(self):
        """Changing  tb_primary_palette for all MyToolbars."""
        self.home_screen.ids[
            "tb_home"].tb_primary_palette = self.primary_palette
        self.root.ids["add_type_screen"].ids[
            "tb_addedit"].tb_primary_palette = self.primary_palette
        self.root.ids["edit_type_screen"].ids[
            "tb_addedit"].tb_primary_palette = self.primary_palette
        self.root.ids["delete_edit_type_screen"].ids[
            "tb_deleteedittype"].tb_primary_palette = self.primary_palette
        self.root.ids["add_damper_screen"].ids[
            "tb_addedit"].tb_primary_palette = self.primary_palette
        self.root.ids["edit_damper_screen"].ids[
            "tb_addedit"].tb_primary_palette = self.primary_palette
        self.root.ids["language_screen"].ids[
            "tb_addedit"].tb_primary_palette = self.primary_palette

    def change_screen(self, screen_name, *args):
        if screen_name == "home_screen":
            self.tf_search.focused = False
            self.tf_search.text = ""
            self.get_dampers()

        self.screen_manager.current = screen_name

    def show_delete_dampers_dialog(self, *args):
        """Show delete damper dialog."""
        if self.selected_dampers:
            dialog = MDDialog(title=self.tr._("Delete damper"),
                              size_hint=(.7, .4),
                              text_button_ok=self.tr._("Delete"),
                              text_button_cancel=self.tr._("Cancel"),
                              auto_dismiss=False,
                              events_callback=self.delete_selected_dampers,
                              text=self.tr._(
                                  "This action will delete selected dampers"
                                  "\nfrom the Database."
                                  "\nDo you really want to do this?"))
            dialog.open()

    def delete_selected_dampers(self, text_of_selection, *args):
        """
        Delete selected items
        from DB and _item_container.
        """
        if text_of_selection == self.tr._("Delete"):
            # if self.selected_dampers:
            for selected_damper in self.selected_dampers:
                # Get the damper the_number.
                damper_number = selected_damper.text.split()[0]
                damper = Damper()
                try:
                    damper.delete_damper(damper_number)
                except sqlite3.DatabaseError:
                    toast("DeleteDamperError")
                else:
                    self.dampers_container.remove_widget(selected_damper)
            toast(self.tr._("Deleted"))
            self.get_dampers()

    def edit_selected_damper(self, *args):
        """Edit selected damper."""
        if self.selected_dampers:  # if self.selected_dampers is not empty.
            if len(self.selected_dampers) > 1:
                toast(self.tr._("Select one for editing"))
            else:
                number_location = self.selected_dampers[0].text.split()
                checkdate_isreleased = self.selected_dampers[
                    0].secondary_text.split()
                dtype_notes = self.selected_dampers[0].tertiary_text.split()

                self.edit_damper_screen.old_number = number_location[0]
                self.edit_damper_screen.old_location = number_location[1]
                self.edit_damper_screen.old_check_date = checkdate_isreleased[
                    0]
                self.edit_damper_screen.old_is_released = True if checkdate_isreleased[
                    1] == "Released" else False
                self.edit_damper_screen.old_d_type = dtype_notes[0]
                self.edit_damper_screen.old_notes = dtype_notes[1] if len(
                    dtype_notes) == 2 else ""

                self.change_screen("edit_damper_screen")

    def show_clear_db_dialog(self, *args):
        """Show clear DB dialog."""
        dialog = MDDialog(
            title=self.tr._("Clear Database"),
            size_hint=(.7, .4),
            text_button_ok=self.tr._("Clear"),
            text_button_cancel=self.tr._("Cancel"),
            auto_dismiss=False,
            events_callback=self.clear_db,
            text=self.tr._(
                "[color={}]This action will delete "
                "\n[b]ALL[/b] data from the Database."
                "\nDo you really want to do this?[/color]").format("#FF0000"))

        dialog.open()

    def clear_db(self, text_of_selection, *args):
        """Delete ALL date from the DB."""
        if text_of_selection == self.tr._("Clear"):
            damper = Damper()
            try:
                damper.clear_db()
            except sqlite3.DatabaseError:
                toast("ClearDBError")
            else:
                toast(self.tr._("Cleared"))
                # Delay for showing toast("Cleared")
                Clock.schedule_once(self.get_dampers, 1)

    def select_all(self, *args):
        """Select all elements."""
        for damper_list_item in self.all_dampers_in_container:
            damper_list_item.ids["right_checkbox_dampers"].active = True

    def cancel_all_selection(self, *args):
        """Cancel selection of all elements."""
        for damper_list_item in self.all_dampers_in_container:
            damper_list_item.ids["right_checkbox_dampers"].active = False

    def add_into_selected_dampers(self, instance):
        """Add selected item into the list: selected_dampers."""
        self.selected_dampers.append(instance)

    def del_from_selected_dampers(self, instance):
        """Delete selected item from the list: selected_dampers."""
        self.selected_dampers.remove(instance)
Esempio n. 22
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. 23
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)
Esempio n. 24
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. 25
0
class Settings:
    def __init__(self):
        self.Config = ConfigParser()
        self.Config.add_section('Input')
        self.Config.add_section('Processor')
        self.Config.add_section('Output')
        # default values
        self.cfgfilename = 'default.conf'
        self.helpfile = 'doc/PyFSPro_dataflow.jpg'
        self.numframes = 255  # No. of frames in stack
        self.color_mode = -1  # Greyscale output
        self.video_src = 0  # Default camera
        self.video_width = 1024
        self.video_height = 768
        self.show_inp = True
        self.show_out = True
        self.show_vec = False
        self.show_help = False

        # settings for video and image sequence recording
        self.recordi = False
        self.recordv = False
        self.novfile = True
        self.imgindx = 0
        self.output_path = './output/'
        self.image_dst = self.output_path
        self.video_dst = self.output_path

        # switches for image filters and tools
        self.blr_inp = False
        self.blr_out = False
        self.blr_strength = 7
        self.equ_inp = 0
        self.equ_out = 0
        self.dnz_inp = False
        self.dnz_out = False
        self.dnz_inp_str = 33
        self.dnz_out_str = 33
        self.flt_inp = 0
        self.flt_out = 0
        self.flt_inp_strength = 0
        self.flt_out_strength = 0
        self.flt_inp_kernel = None
        self.flt_out_kernel = None
        self.flip_x = False
        self.flip_y = False
        self.inp_kernel = None
        self.out_kernel = None
        #self.mode_in = 0
        self.mode_prc = 0
        #self.mode_out = 0
        self.pseudoc = False
        self.dyn_dark = True
        self.gain_inp = 1.0
        self.gain_out = 1.0
        self.offset_inp = 0
        self.offset_out = 0
        self.vec_zoom = 0.1
        self.loop = False
        self.stb_inp = False
        self.stb_out = False
        self.osd_txtline = 2
        self.green = (0, 255, 0)
        self.red = (0, 0, 255)
        self.blue = (255, 0, 0)
        self.black = (0, 0, 0)
        self.colormaps = [
            'AUTUMN', 'BONE', 'JET', 'WINTER', 'RAINBOW', 'OCEAN', 'SUMMER',
            'SPRING', 'COOL', 'HSV', 'PINK', 'HOT'
        ]
        self.set_defaults()

    def gettime(self):
        self.timestring = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
        return self.timestring

    def set_defaults(self):
        # Section 'Input'
        self.Config.setdefault('Input', 'video_src', self.video_src)
        self.Config.setdefault('Input', 'video_width', self.video_width)
        self.Config.setdefault('Input', 'video_height', self.video_height)
        self.Config.setdefault('Input', 'loop', self.loop)
        self.Config.setdefault('Input', 'flip_x', self.flip_x)
        self.Config.setdefault('Input', 'flip_y', self.flip_y)
        self.Config.setdefault('Input', 'blr_inp', self.blr_inp)
        self.Config.setdefault('Input', 'equ_inp', self.equ_inp)
        self.Config.setdefault('Input', 'dnz_inp', self.dnz_inp)
        self.Config.setdefault('Input', 'dnz_inp_str', self.dnz_inp_str)
        self.Config.setdefault('Input', 'flt_inp', self.flt_inp)
        self.Config.setdefault('Input', 'flt_inp_strength',
                               self.flt_inp_strength)
        #self.Config.setdefault('Input','mode_in', self.mode_in)
        self.Config.setdefault('Input', 'gain_inp', self.gain_inp)
        self.Config.setdefault('Input', 'offset_inp', self.offset_inp)
        self.Config.setdefault('Input', 'stb_inp', self.stb_inp)

        # Section 'Processor'
        self.Config.setdefault('Processor', 'mode_prc', self.mode_prc)
        self.Config.setdefault('Processor', 'dyn_dark', self.dyn_dark)
        self.Config.setdefault('Processor', 'blr_strength', self.blr_strength)
        self.Config.setdefault('Processor', 'numframes', self.numframes)

        # Section 'Output'
        self.Config.setdefault('Output', 'video_dst', self.video_dst)
        self.Config.setdefault('Output', 'image_dst', self.image_dst)
        self.Config.setdefault('Output', 'recordv', self.recordv)
        self.Config.setdefault('Output', 'recordi', self.recordi)
        self.Config.setdefault('Output', 'blr_out', self.blr_out)
        self.Config.setdefault('Output', 'equ_out', self.equ_out)
        self.Config.setdefault('Output', 'dnz_out', self.dnz_out)
        self.Config.setdefault('Output', 'dnz_out_str', self.dnz_out_str)
        self.Config.setdefault('Output', 'flt_out', self.flt_out)
        self.Config.setdefault('Output', 'flt_out_strength',
                               self.flt_out_strength)
        #self.Config.setdefault('Output','mode_out', self.mode_out)
        self.Config.setdefault('Output', 'gain_out', self.gain_out)
        self.Config.setdefault('Output', 'offset_out', self.offset_out)
        self.Config.setdefault('Output', 'color_mode', self.color_mode)
        self.Config.setdefault('Output', 'pseudoc', self.pseudoc)
        self.Config.setdefault('Output', 'vec_zoom', self.vec_zoom)
        self.Config.setdefault('Output', 'stb_out', self.stb_out)

    def write_config(self, filename):
        if filename is None:
            filename = self.cfgfilename
        self.cfgfile = open(filename, 'w')

        # Section 'Input'
        self.Config.set('Input', 'video_src', self.video_src)
        self.Config.set('Input', 'video_width', self.video_width)
        self.Config.set('Input', 'video_height', self.video_height)
        self.Config.set('Input', 'loop', self.loop)
        self.Config.set('Input', 'flip_x', self.flip_x)
        self.Config.set('Input', 'flip_y', self.flip_y)
        self.Config.set('Input', 'blr_inp', self.blr_inp)
        self.Config.set('Input', 'equ_inp', self.equ_inp)
        self.Config.set('Input', 'dnz_inp', self.dnz_inp)
        self.Config.set('Input', 'dnz_inp_str', self.dnz_inp_str)
        self.Config.set('Input', 'flt_inp', self.flt_inp)
        self.Config.set('Input', 'flt_inp_strength', self.flt_inp_strength)
        #self.Config.set('Input','mode_in', self.mode_in)
        self.Config.set('Input', 'gain_inp', self.gain_inp)
        self.Config.set('Input', 'offset_inp', self.offset_inp)
        self.Config.set('Input', 'stb_inp', self.stb_inp)

        # Section 'Processor'
        self.Config.set('Processor', 'mode_prc', self.mode_prc)
        self.Config.set('Processor', 'dyn_dark', self.dyn_dark)
        self.Config.set('Processor', 'blr_strength', self.blr_strength)
        self.Config.set('Processor', 'numframes', self.numframes)

        # Section 'Output'
        self.Config.set('Output', 'video_dst', self.video_dst)
        self.Config.set('Output', 'image_dst', self.image_dst)
        self.Config.set('Output', 'recordv', self.recordv)
        self.Config.set('Output', 'recordi', self.recordi)
        self.Config.set('Output', 'blr_out', self.blr_out)
        self.Config.set('Output', 'equ_out', self.equ_out)
        self.Config.set('Output', 'dnz_out', self.dnz_out)
        self.Config.set('Output', 'dnz_out_str', self.dnz_out_str)
        self.Config.set('Output', 'flt_out', self.flt_out)
        self.Config.set('Output', 'flt_out_strength', self.flt_out_strength)
        #self.Config.set('Output','mode_out', self.mode_out)
        self.Config.set('Output', 'gain_out', self.gain_out)
        self.Config.set('Output', 'offset_out', self.offset_out)
        self.Config.set('Output', 'color_mode', self.color_mode)
        self.Config.set('Output', 'pseudoc', self.pseudoc)
        self.Config.set('Output', 'vec_zoom', self.vec_zoom)
        self.Config.set('Output', 'stb_out', self.stb_out)

        self.Config.write(self.cfgfile)
        self.cfgfile.close()

    def read_config(self, filename):
        if os.path.isfile(filename):
            self.Config.read(filename)
            self.video_src = self.Config.get('Input', 'video_src')
            self.video_width = int(self.Config.get('Input', 'video_width'))
            self.video_height = int(self.Config.get('Input', 'video_height'))
            self.loop = self.Config.getboolean('Input', 'loop')
            self.flip_x = self.Config.getboolean('Input', 'flip_x')
            self.flip_y = self.Config.getboolean('Input', 'flip_y')
            self.blr_inp = self.Config.getboolean('Input', 'blr_inp')
            self.equ_inp = int(self.Config.get('Input', 'equ_inp'))
            self.dnz_inp = self.Config.getboolean('Input', 'dnz_inp')
            self.dnz_inp_str = float(self.Config.get('Input', 'dnz_inp_str'))
            self.flt_inp = int(self.Config.get('Input', 'flt_inp'))
            self.flt_inp_strength = float(
                self.Config.get('Input', 'flt_inp_strength'))
            self.gain_inp = float(self.Config.get('Input', 'gain_inp'))
            self.offset_inp = float(self.Config.get('Input', 'offset_inp'))
            self.stb_inp = self.Config.getboolean('Input', 'stb_inp')
            self.mode_prc = int(self.Config.get('Processor', 'mode_prc'))
            self.dyn_dark = self.Config.getboolean('Processor', 'dyn_dark')
            self.blr_strength = int(
                self.Config.get('Processor', 'blr_strength'))
            self.numframes = int(self.Config.get('Processor', 'numframes'))
            self.video_dst = self.Config.get('Output', 'video_dst')
            self.image_dst = self.Config.get('Output', 'image_dst')
            self.recordv = self.Config.getboolean('Output', 'recordv')
            self.recordi = self.Config.getboolean('Output', 'recordi')
            self.blr_out = self.Config.getboolean('Output', 'blr_out')
            self.equ_out = int(self.Config.get('Output', 'equ_out'))
            self.dnz_out = self.Config.getboolean('Output', 'dnz_out')
            self.dnz_out_str = float(self.Config.get('Output', 'dnz_out_str'))
            self.flt_out = int(self.Config.get('Output', 'flt_out'))
            self.flt_out_strength = float(
                self.Config.get('Output', 'flt_out_strength'))
            self.gain_out = float(self.Config.get('Output', 'gain_out'))
            self.offset_out = float(self.Config.get('Output', 'offset_out'))
            self.color_mode = int(self.Config.get('Output', 'color_mode'))
            self.pseudoc = self.Config.getboolean('Output', 'pseudoc')
            self.vec_zoom = float(self.Config.get('Output', 'vec_zoom'))
            self.stb_out = self.Config.getboolean('Output', 'stb_out')
        else:
            print('File ' + str(filename) + ' does not exist.')
Esempio n. 26
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. 27
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. 28
0
    def update(self):

        self.clear_widgets()

        #define structure of fields (like an INI file)
        config = ConfigParser()
        config.add_section('general')
        config.add_section('location')
        config.add_section('icon_file')

        #--- set values (needs to come from database) todo
        #config.set('general','place_name','Name of the place: ' + str(self.placeid))
        if self.data == None:
            config.set('location','lat','Enter lat here')
            config.set('location','lon','This is a dummy lon.')

            config.set('general','place_name','This is a dummy which should never be seen')
            config.set('general','category_name','This is a dummy which should never be seen')
            config.set('general','ranking','This is a dummy which should never be seen')
            config.set('general','visited','This is a dummy which should never be seen')
            config.set('icon_file','icon_file','This is a dummy which should never be seen')
        else:
            place = self.data
            config.set('location','lat',place.lat)
            config.set('location','lon',place.lon)

            config.set('general','place_name',place.name)

            config.set('general','category_name',place.cat_name )
            config.set('general','ranking', self._ranking2str(place.stars))
            config.set('general','visited',place.status)
            config.set('icon_file','icon_file','Testpath') #todo:how to deal with image data ???

        return config
Esempio n. 29
0
 class MenuScreen(Screen):
     def __init__(self):
         Screen.__init__(self)
         self.name = 'menu'
         self.config = ConfigParser()
         self.config.add_section("deck")
         self.config.add_section("card")
         self.config.adddefaultsection("menu")
         self.config.set("deck", "start_studying", 1)
         self.config.set("deck", "change_deck_mode", "Normal")
         self.config.set("deck", "show_list", True)
         self.config.set("deck", "undo", True)
         self.config.set("deck", "redo", True)
         self.config.set("card", "add", "")
         self.config.set("card", "edit", True)
         self.config.set("card", "remove", True)
         
         self.config.add_callback(self.check_deck_locks, "deck", "redo")
         self.config.add_callback(self.check_deck_locks, "deck", "undo")
         
         self.config.add_callback(self.check_card_locks, "card", "edit")
         self.config.add_callback(self.check_card_locks, "card", "add")
         
         
         self.menu = SettingsWithNoMenu()
         self.menu.register_type("screen", FlashcardAppManager.SettingNewScreen)
         self.menu.register_type("action", FlashcardAppManager.SettingDoAction)
         self.menu.add_json_panel("Flashcards", self.config, os.path.join(os.path.dirname(__file__), 'menu.json'))
         
         self.add_widget(self.menu)
         
 
     def check_deck_locks(self, section, key, value):
         print(self.config.get(section, key))
     
     def check_card_locks(self, section, key, value):
         print()
Esempio n. 30
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. 31
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. 32
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)
class Settings:

    __defaults = {
        'kivy': {
            'log_level': 'debug',  # TODO: Change default to info
            'log_enable': 1,
            'log_dir': 'logs',
            'log_name': 'ps_%y-%m-%d_%_.txt',
            'log_maxfiles': 100
        },
        'data': {
            'dir': 'C:/pressure-data/',
            'ppr': 20
        },
        'com': {
            'port': 'COM1',
            'baudrate': 9600,
            'bytesize': '8',
            'parity': 'None',
            'stopbits': '1'
        },
        'calibration': {
            'user_point1': 0,
            'sensor_point1': 0,
            'user_point2': 2,
            'sensor_point2': 1024
        }
    }

    def __init__(self):
        self.config = ConfigParser()
        self.widget = SettingsWithNoMenu()

    def load(self, filename):
        for k, v in self.__defaults.items():
            self.config.setdefaults(k, v)
        self.config.read(filename)
        self.config.write()

        Config.read(filename)

        Logger.info('Settings: Loaded setting file: %s', filename)

        Logger.debug('Settings: Setting up panel')
        self.panel = self.widget.create_json_panel('Settings',
                                                   self.config,
                                                   data=self.windgetconfigdata)
        self.widget.children[0].add_widget(self.panel)

        Logger.debug('Settings: Setting options')
        self.setPanelOptions('port', SerialAdapter.getPortNames())
        self.setPanelOptions('bytesize', SerialAdapter.BYTESIZE.keys())
        self.setPanelOptions('parity', SerialAdapter.PARITY.keys())
        self.setPanelOptions('stopbits', SerialAdapter.STOPBITS.keys())

    def updateAvailablePorts(self):
        Logger.debug('Settings: Setting port options')
        self.setPanelOptions('port', SerialAdapter.getPortNames())

    def getPanelSetting(self, key):
        return next(
            (x for x in self.panel.children if not isinstance(x, SettingTitle)
             and not isinstance(x, Label) and x.key == key), None)

    def setPanelOptions(self, key, options):
        s = self.getPanelSetting(key)
        if s != None:
            s.options = options

    def getWidget(self):
        return self.widget

    def addCallback(self, callback, section=None, key=None):
        Logger.debug('Settings: Adding callback: %s, %s', section, key)
        self.config.add_callback(callback, section, key)
        if key != None:
            callback(section, key, self.get(section, key))

    def get(self, section, key):
        return self.config.get(section, key)

    def set(self, section, key, value):
        return self.config.set(section, key, value)

    def getDefault(self, section, key):
        return self.__defaults[section][key]

    def saveConfig(self):
        self.config.write()

    windgetconfigdata = """[
Esempio n. 34
0
 class EditCardMenuScreen(Screen):
     question = ""
     answer = ""
     nquestion = ""
     nanswer = ""
     EditCardMenuConfig = None
     
     def update_qa(self, *args):
             FlashcardAppManager.EditCardMenuScreen.nquestion = self.config.get('edit', 'nquestion')
             FlashcardAppManager.EditCardMenuScreen.nanswer = self.config.get("edit", "nanswer")
             
     def __init__(self):
         Screen.__init__(self)
         
         self.name = "edit"
         
         self.config = ConfigParser()
         self.config.add_section("edit")
         self.config.set("edit", "question", "Question")
         self.config.set("edit", "answer", "Answer")
         self.config.set("edit", "nquestion", "Question")
         self.config.set("edit", "nanswer", "Answer")
         self.config.set("edit", "edit", "action")
         
         FlashcardAppManager.EditCardMenuScreen.question = self.config.get('edit', 'question')
         FlashcardAppManager.EditCardMenuScreen.answer = self.config.get('edit', 'answer')
         FlashcardAppManager.EditCardMenuScreen.nquestion = self.config.get('edit', 'nquestion')
         FlashcardAppManager.EditCardMenuScreen.nanswer = self.config.get('edit', 'nanswer')
         
         
             
         self.config.add_callback(self.update_qa, section="edit", key="nquestion")
         self.config.add_callback(self.update_qa, section="edit", key="nanswer")
         
         self.menu = SettingsWithNoMenu()
         
         
         self.menu.register_type("action", FlashcardAppManager.SettingDoAction)
         self.menu.add_json_panel("Add a card", self.config, os.path.join(os.path.dirname(__file__), 'edit_menu.json'))
         
         FlashcardAppManager.EditCardMenuScreen.EditCardMenuConfig = self.config
         
         self.add_widget(self.menu)
         
         def on_pre_enter(self, *args):
             FlashcardAppManager.EditCardMenuScreen.question = FlashcardAppManager.deck_widget.deck.get_selected().get_question()
             FlashcardAppManager.EditCardMenuScreen.answer = FlashcardAppManager.deck_widget.deck.get_selected().get_answer()
             self.config.set("edit", "question", FlashcardAppManager.EditCardMenuScreen.question)
             self.config.set("edit", "answer", FlashcardAppManager.EditCardMenuScreen.answer)
Esempio n. 35
0
class MainApp(MDApp):
    title = __projectname__
    version = __version__
    icon = 'icon.png'
    nav_drawer = ObjectProperty()

    def __init__(self, **kvargs):
        super(MainApp, self).__init__(**kvargs)
        Window.bind(on_keyboard=self.events_program)
        Window.softinput_mode = 'below_target'
        LabelBase.register(name="Roboto", fn_regular="./data/droid.ttf")

        self.list_previous_screens = ['base']
        self.window = Window
        self.config = ConfigParser()
        self.manager = None
        self.exit_interval = False

    def set_value_from_config(self):
        self.config.read(os.path.join(self.directory, 'main.ini'))
        self.style = self.config.get('General', 'theme_style')
        self.theme_cls.theme_style = self.style

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

    def show_about(self, *args):
        self.nav_drawer.toggle_nav_drawer()
        self.screen.ids.about.ids.label.text = \
            (
                u'[size=20][b]{name}[/b][/size]\n\n'
                u'[b]Version:[/b] {version}\n'
                u'[b]License:[/b] {license}\n\n'
                u'[size=20][b]Developer[/b][/size]\n\n'
                u'[ref={site}]'
                u'[color={link_color}]{author}[/color][/ref]\n'
                u'{mail}\n\n'
                u'[b]Source code:[/b] '
                u'[ref={repo}]'
                u'[color={link_color}]GitHub[/color][/ref]').format(
                name=__projectname__,
                version=__version__,
                license=__copyright__,
                author=__author__,
                site=__site__,
                mail=__mail__,
                repo=__repo__,
                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.toggle_nav_drawer()
        self.screen.ids.license.ids.text_license.text = \
            open(os.path.join(self.directory, 'LICENSE'), 'r', encoding='utf-8').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 = 'MIT LICENSE'

    def select_style(self, *args):
        if self.style == 'Light':
            self.theme_cls.theme_style = 'Dark'
            self.style = 'Dark'
            self.config.set('General', 'theme_style', self.style)
            self.config.write()
        else:
            self.theme_cls.theme_style = 'Light'
            self.style = 'Light'
            self.config.set('General', 'theme_style', self.style)
            self.config.write()

    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)
        Snackbar(text='Press Back to Exit').show()
Esempio n. 36
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)
Esempio n. 37
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. 38
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. 39
0
class DictionaryApp(App):
    
    def __init__(self, **kwargs):
        super(DictionaryApp, self).__init__(**kwargs)
        global i, unerwuenscht, invalsettings, status, durchlauf, bu_pfad
        
        invalsettings = True
        
        self.config = ConfigParser()
        
        # Zaehler um anzuzueigen, wie viele Vokabeln in Dict
        i = 0
        
        status = "main"
        
        # Abfragedurchlauf Initialisieren
        anzahl = "0"
        durchlauf = 0
                
        # unerwuenschte Zeichen
        unerwuenscht = "[(?!:;.1234567890)+-]"
        
        # switch off Kivy_settings
        self.use_kivy_settings = False
        
        # Directory for Backups
        
        if platform == "android":
            bu_pfad = "/sdcard/backups/voctrainer/"
            try:
                if not os.path.exists(bu_pfad):
                    os.makedirs(bu_pfad)
            except:
                bu_pfad = "../backups/voctrainer/"
                os.makedirs(bu_pfad)
        else:
            bu_pfad = "../backups/voctrainer/"
            if not os.path.exists(bu_pfad):
                    os.makedirs(bu_pfad)
        
        
    def build(self):
        self.root = DictionaryRoot()
        
        # init the variables for search-query
        self.take_from_build_away()
        
        self.title = "Voc-Trainer"
        return self.root
    
    # this needs to be separated from def build(); otherwise you get problems when running
    # from def on_config_change()
    def take_from_build_away(self):
        global learn_lang, mother_lang, return_lang, lang_learn, lang_mother, lang_return, invalsettings, dictlist, dateiname, ersatz_pfad
        
        # capture error on android
        self.build_config(self.config)
        
        # get values from settingsmenu
        learn_lang = self.config.get("languages", "learnlanguage")
        mother_lang = self.config.get("languages", "motherlanguage")
        return_lang = self.config.get("languages", "returnlanguage")
       
        ## load backupfile
        try:
            # dateiname bei erstem durchlauf noch nicht konfiguriert --> Error
            # check language of backupfile
            if not ersatz_pfad[ersatz_pfad.find("VOC_TR_"):] == dateiname:
                raise
            # get data in backupfile
            open_dict = DateiHandling()
            # overwrite global variable dictlist
            dictlist = open_dict.oeffnen(ersatz_pfad)
            open_dict.schreiben_datei(dateiname, dictlist)
            ersatz_pfad = ""
            # reset backuppath
        except:
            pass
        
        # reset backuppath
        try:
            self.config.read("dictionary.ini")
            # reset path
            self.config.set("languages", "backuppath", bu_pfad)
        except:
            pass
        
        # exception handler neccessary because of opening app after having made
        # backup causes issues
        try:
            if self.config.get("languages", "makebackup") == "yes" and len(dictlist) != 0:
                Backup()       
        except:
            pass
        
        # reset settings
        self.config.set("languages", "makebackup", "no")
        
        # get varibles for search-query
        lang_learn, lang_mother, lang_return = self.init_variables(learn_lang, mother_lang, return_lang)

        # check invalide settings
        self.check_inval_settings()
        if not invalsettings:
            # open the requested file, if exists; otherwise create it
            self.load_dictionary()
    
    def load_dictionary(self):
        global dictlist, lang_learn, lang_mother, lang_return, dateiname
        # Dictionary importieren und in der Variablen "dictlist" ablegen
        open_dict = DateiHandling()
        dateiname = str("VOC_TR_" + lang_learn + "-" + lang_mother + "-" + lang_return + ".txt")
        #print "Open file:", dateiname
        dictlist = open_dict.oeffnen(dateiname)
        
    
    # config-preset for our own settings:
    def build_config(self, config):
        try:
            config.read("dictionary.ini")
            config.set("languages", "backuppath", bu_pfad)
        except:
            config.setdefaults(
                           "languages", {
                                         "learnlanguage": "Italian",
                                         "motherlanguage": "German",
                                         "returnlanguage": "English",
                                         "backuppath": "../backups/voctrainer/",
                                         "makebackup": 0}
                               )
    
    # add our own settings:
    def build_settings(self, settings):
        settings.register_type("scrolloptions", SettingScrollOptions)
        settings.add_json_panel("VOC-Trainer Settings", self.config, data = settings_json)
        
    # change variables on settings-change
    def on_config_change(self, config, section, key, value):
        global invalsettings, ersatz_pfad
        # ersatzpfad notwendig, da neuer build_config durchlauf in take_from_build_away
        ersatz_pfad = self.config.get("languages", "backuppath")
        self.back_refactor()
        self.check_inval_settings()
        self.root.add_widget(DictionaryRoot())
        if not invalsettings:
            self.take_from_build_away()
        else:
            return
    
    def check_inval_settings(self):
        global invalsettings
        # get all three languages:
        langlist = [self.config.get("languages", "learnlanguage"), self.config.get("languages", "motherlanguage"), self.config.get("languages", "returnlanguage")]
        
        # if any language appears more than 1 time --> invalsettings = True
        for i in langlist:
            if langlist.count(i) != 1:
                invalsettings = True
                return
        invalsettings = False        
        
    def init_variables(self, learn_lang, mother_lang, return_lang):
        # initialize lang_learn depending on settings
        lang_learn = self.select_lang(learn_lang)
        lang_mother = self.select_lang(mother_lang)
        lang_return = self.select_lang(return_lang)
        return lang_learn, lang_mother, lang_return
    
    def select_lang(self, language):
        # ita - Italian
        # en - English
        # de - German
        # fra - French
        # es - Spanish
        # ru - Russian
        # ro - Romanian
        # tr - Turkish
        # ar - Arabic
        # la - Latin
        # sv - Swedish
        # ku - Kurdish
        if language == "Arabic":
            lang = "ar"
        elif language == "English":
            lang = "en"
        elif language == "French":
            lang = "fra"
        elif language == "German":
            lang = "deu"
        elif language == "Italian":
            lang = "ita"
        elif language == "Kurdish":
            lang = "ku"
        elif language == "Latin":
            lang = "la"
        elif language == "Romanian":
            lang = "ro"
        elif language == "Russian":
            lang = "ru"
        elif language == "Spanish":
            lang = "es"
        elif language == "Swedish":
            lang = "sv"
        elif language == "Turkish":
            lang = "tr"        
        return lang
    
    
    def back(self):
        # setzt i fuer Anzeige der Anzahl der Vokabeln zurueck
        
        global i, dateiname, status
        #### hier muss das Dictionary gespeichert werden ####
        write_dict = DateiHandling()
        # das funktioniert, weil diclist.append nur aufgerufen wird, wenn auch muttersprache und englische Vokabel eingegeben wurde!!!
        # ansonsten ist dictlist unveraendert
        write_dict.schreiben_datei(dateiname, dictlist)
        # damit man wieder zum Input zurueck kommt, wenn show von dort aufgerufen wird
        if status == "from_input":
            self.back_refactor()
            self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02)
            self.root.add_widget(Input_Learn())
        elif status == "from_list":
            self.back_refactor()
            self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02)
            self.root.add_widget(List())
        elif status == "abfrage":
            self.back_refactor()
            self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02)
            self.root.add_widget(Abfrage())
            return
        else:
            # Zuruecksetzen des Zaehlers, damit beim erneuten Aufruf wieder die Anzahl der Vokabeln im Dictionary angezeigt wird
            i = 0
            status = "main"
            self.back_refactor()
            self.root.add_widget(DictionaryRoot())
            
    def back_refactor(self):
            self.root.clear_widgets()
            self.root.canvas.clear() # sonst Fehler mit Hintergrundfarbe
            self.root.padding = 0 # sonst Fehler        
        
    def show(self):
        global voc_learn, edit_learn, edit_mother, edit_en, search, status
       
        if status == "input":
            status = "from_input"
        elif status == "list":
            status = "from_list"
            
        search = unicode(voc_learn, "utf-8")
        edit_learn = search
        edit_mother = ",".join(dictlist[search][0])
        edit_en = ",".join(dictlist[search][1])
        self.back_refactor()
        self.root.padding = (self.root.width * 0.02, self.root.width * 0.02) if self.root.width < self.root.height else (self.root.height * 0.02, self.root.height * 0.02)
        self.root.add_widget(Edit())
    
    def on_pause(self):
        return True
    
    def on_resume(self):
        pass
    
    # changes the function of the "back" button aka. "esc" to not throw you out of application 
    # when not in main-menu
    def on_start(self):
        EventLoop.window.bind(on_keyboard=self.checkback)
        
    # checks every key-event if esc-button
    def checkback(self, window, key, *args):
        if key == 27:
            if status != "main":
                self.back()
                return True
            else:
                return False
        return
class 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. 41
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. 42
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. 43
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. 44
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. 45
0
 def set(self, *args, **kwargs):
     KivyConfigParser.set(self, *args, **kwargs)
     self.write()