Exemple #1
0
class GMDP_Control(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "GMDP Team2 Smart Room"

    Room_1_Temp = ObjectProperty()
    Room_1_Current_Setting = ObjectProperty()
    Room_1_Light = ObjectProperty()
    Room_1_AC_Status = ObjectProperty()
    Room_1_Running_Time = ObjectProperty()
    Room_1_Energy_Saving = ObjectProperty()

    Room_1_PIR_Triggering_Times = ObjectProperty()
    Room_1_Occupancy_Status = ObjectProperty()
    Room_1_Occupancy_Color = ObjectProperty()

    Room_2_Temp = ObjectProperty()
    Room_2_Current_Setting = ObjectProperty()
    Room_2_Light = ObjectProperty()
    Room_2_AC_Status = ObjectProperty()
    Room_2_Running_Time = ObjectProperty()
    Room_2_Energy_Saving = ObjectProperty()

    User_1_Configuration = ObjectProperty()

    def build(self):
        self.var_init()
        main_widget = Builder.load_file('main.kv')
        # self.theme_cls.theme_style = 'Dark'
        return main_widget

    def var_init(self):
        self.get_temperature()
        self.get_occupancy_info()
        self.get_energy_info()
        # self.get_temperature_setting_room1()
        self.Room_1_Light = 0
        self.Room_2_Light = 0
        self.Room_1_AC_Status = 0
        self.Room_2_AC_Status = 0
        self.Room_1_Current_Setting = "Off"
        # self.read_user1_configuration()

    def read_user1_configuration(self):
        with open('data/user_1.json', 'r') as read_file:
            self.User_1_Configuration = json.load(read_file)
            self.Room_1_Current_Setting = self.User_1_Configuration['room1'][
                'current_temperature_setting']

    def write_user1_configuration(self):
        with open('data/user_1.json', 'w') as write_file:
            json.dump(self.User_1_Configuration, write_file)

    def get_temperature(self):
        r = requests.get(baseURL_Room1_Condition)
        data = json.loads(r.text)
        self.Room_1_Temp = round(self.read_valid_data(data, 'field1'))

    def get_occupancy_info(self):
        r = requests.get(baseURL_Room1_Condition)
        data = json.loads(r.text)
        self.Room_1_PIR_Triggering_Times = (self.read_valid_data(
            data, 'field4'))
        if self.Room_1_PIR_Triggering_Times <= 10:
            self.Room_1_Occupancy_Status = 'Empty Room'
            self.Room_1_Occupancy_Color = GREEN
        elif 10 <= self.Room_1_PIR_Triggering_Times < 100:
            self.Room_1_Occupancy_Status = 'One or two people are here'
            self.Room_1_Occupancy_Color = LIME
        elif 100 <= self.Room_1_PIR_Triggering_Times < 200:
            self.Room_1_Occupancy_Status = 'Several people are here'
            self.Room_1_Occupancy_Color = YELLOW
        elif 200 <= self.Room_1_PIR_Triggering_Times < 300:
            self.Room_1_Occupancy_Status = 'Many people are here'
            self.Room_1_Occupancy_Color = ORANGE
        elif 300 <= self.Room_1_PIR_Triggering_Times < 400:
            self.Room_1_Occupancy_Status = 'The Room is Full !'
            self.Room_1_Occupancy_Color = RED
        elif 400 <= self.Room_1_PIR_Triggering_Times < 500:
            self.Room_1_Occupancy_Status = 'The Room is Full !!'
            self.Room_1_Occupancy_Color = BROWN
        elif self.Room_1_PIR_Triggering_Times >= 500:
            self.Room_1_Occupancy_Status = 'The Room is Full !!!'
            self.Room_1_Occupancy_Color = BROWN
        else:
            self.Room_1_Occupancy_Status = -1

    def get_energy_info(self):
        r = requests.get(baseURL_energy)
        data = json.loads(r.text)
        self.Room_1_Running_Time = round(
            self.read_valid_data(data, 'field3') / 60, 1)
        self.Room_1_Energy_Saving = round(
            self.read_valid_data(data, 'field4') * 50 / 3600, 3)

    def get_temperature_setting_room1(self):
        r = requests.get(baseURL_temperature_setting_room1_get)
        data = json.loads(r.text)
        self.Room_1_Current_Setting = int(data['feeds'][1]['field1'][1:])

    def switch_light(self):
        self.Room_1_Light = 1 - self.Room_1_Light
        post_command("00" + str(self.Room_1_Light), 1)
        if self.Room_1_Light == 0:
            self.do_notify('Turn off light #1 successfully!')
        elif self.Room_1_Light == 1:
            self.do_notify('Turn on light #1 successfully!')

    def switch_light_2(self):
        self.Room_2_Light = 1 - self.Room_2_Light
        post_command("01" + str(self.Room_2_Light), 1)
        if self.Room_2_Light == 0:
            self.do_notify('Turn off light #2 successfully!')
        elif self.Room_2_Light == 1:
            self.do_notify('Turn on light #2 successfully!')

    def on_off_room1_ac(self):
        self.Room_1_AC_Status = 1 - self.Room_1_AC_Status
        if self.Room_1_AC_Status == 0:
            self.Room_1_Current_Setting = 'Off'
            post_command('1000', 1)
            self.write_user1_configuration()
        elif self.Room_1_AC_Status == 1:
            self.read_user1_configuration()
            post_command('1010', 1)
            post_command(
                '11' + str(self.User_1_Configuration['room1']
                           ['current_temperature_setting']), 1)
            self.read_user1_configuration()

    def increase_temperature(self):
        if self.Room_1_Current_Setting != "Off":
            self.Room_1_Current_Setting += 1
            self.User_1_Configuration['room1'][
                'current_temperature_setting'] += 1
            self.write_user1_configuration()
            post_command(
                '11' + str(self.User_1_Configuration['room1']
                           ['current_temperature_setting']), 1)

    def decrease_temperature(self):
        if self.Room_1_Current_Setting != "Off":
            self.Room_1_Current_Setting -= 1
            self.User_1_Configuration['room1'][
                'current_temperature_setting'] -= 1
            self.write_user1_configuration()
            post_command(
                '11' + str(self.User_1_Configuration['room1']
                           ['current_temperature_setting']), 1)

    @staticmethod
    def get_temperature_plot():
        webbrowser.open('https://thingspeak.com/channels' +
                        '/723513/charts/1?bgcolor=%23ffffff&color=%23d62020' +
                        '&dynamic=true&results=200&type=line&update=15')

    @staticmethod
    def get_occupancy_plot():
        webbrowser.open(
            'https://thingspeak.com/channels/723513/charts/4?' +
            'bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=200&type=line&update=15'
        )

    @staticmethod
    def read_valid_data(data, field):
        i = 49
        latest_valid_data = data['feeds'][i][field]
        while i >= 0:
            while data['feeds'][i][field] is None:
                i -= 1
            latest_valid_data = data['feeds'][i][field]
            print('latest valid data is: ' + str(latest_valid_data))
            break
        return float(latest_valid_data)

    @staticmethod
    def do_notify(message):
        notification.notify(message=message, toast=True)

    # @staticmethod
    # def do_vibrate(self, time): # not work on Android Q
    #     print(vibrator.exists())
    #     vibrator.vibrate(time=2)

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass
Exemple #2
0
class PasswordApp(App):
    theme_cls = ThemeManager()
    hash_one_items = [{
        'viewclass':
        'MDMenuItem',
        'text':
        'MD5',
        "on_press":
        "app.updateHashButton('hashselector1', 'MD5')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA1',
        "on_press":
        "app.updateHashButton('hashselector1', 'SHA1')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA224',
        "on_press":
        "app.updateHashButton('hashselector1', 'SHA224')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA256',
        "on_press":
        "app.updateHashButton('hashselector1', 'SHA256')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA384',
        "on_press":
        "app.updateHashButton('hashselector1', 'SHA384')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA512',
        "on_press":
        "app.updateHashButton('hashselector1', 'SHA512')"
    }]

    hash_two_items = [{
        'viewclass':
        'MDMenuItem',
        'text':
        'MD5',
        "on_press":
        "app.updateHashButton('hashselector2', 'MD5')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA1',
        "on_press":
        "app.updateHashButton('hashselector2', 'SHA1')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA224',
        "on_press":
        "app.updateHashButton('hashselector2', 'SHA224')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA256',
        "on_press":
        "app.updateHashButton('hashselector2', 'SHA256')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA384',
        "on_press":
        "app.updateHashButton('hashselector2', 'SHA384')"
    }, {
        'viewclass':
        'MDMenuItem',
        'text':
        'SHA512',
        "on_press":
        "app.updateHashButton('hashselector2', 'SHA512')"
    }]

    pass
 def __init__(self, **kwargs):
     self.theme_cls = ThemeManager()
     self.theme_cls.theme_style = 'Dark'
     self.theme_cls.primary_palette = "Orange"
     Window.size = (400, 600)
     super().__init__(**kwargs)
Exemple #4
0
class KitchenSink(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "NBA Prediction App"

    menu_items = [
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        # main_widget.ids.text_field_error.bind(
        #     on_text_validate=self.set_error_message,
        #     on_focus=self.set_error_message)
        self.bottom_navigation_remove_mobile(main_widget)
        return main_widget

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_example_snackbar(self, snack_type):
        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(
                text=
                "This is a very very very very very very very long snackbar!"
            ).show()

    def show_example_dialog(self):
        content1 = MDTextField(hint_text="Имя",
                               required=True,
                               helper_text="Обязательное поле",
                               helper_text_mode="on_error")
        content2 = MDTextField(hint_text="Парол",
                               required=True,
                               helper_text="Обязательное поле",
                               helper_text_mode="on_error")
        content1.hint_text = "Имя пользователя"
        content1.helper_text = "Некорректный ввод"
        content1.min_text_length = 2
        content1.color_mode = 'accent'
        content2.hint_text = "Пароль"
        content2.helper_text = "Некорректный ввод"
        content2.min_text_length = 8
        content2.color_mode = 'accent'
        layout1 = BoxLayout(orientation='vertical',
                            size_hint_y=None,
                            height=dp(180),
                            padding=dp(48),
                            spacing=10)
        layout1.add_widget(content1)
        layout1.add_widget(content2)

        # content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Вход",
                               content=layout1,
                               size_hint=(.8, None),
                               height=dp(300),
                               auto_dismiss=False)
        self.dialog.add_action_button("ОК",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.add_action_button("Отмена",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj

        connect = sqlite3.connect("nbadb.db")
        cursor = connect.cursor()

        r = str(date_obj) + 'T00:00:00'
        cursor.execute(
            """SELECT GAME_ID, HOME_TEAM_ID, VISITOR_TEAM_ID FROM calendar
                          WHERE GAME_DATE_EST = (?)
                      """, (r, ))

        l = cursor.fetchall()
        self.output_string = []
        bs = MDListBottomSheet()
        bs.add_item("Список игр: " + str(date_obj), lambda x: x)

        for i in range(len(l)):
            self.output_string.append('')
            cursor.execute(
                """SELECT TEAM_CITY, TEAM_NAME FROM team
                                      WHERE TEAM_ID = (?)
                                  """, (l[i][2], ))
            fetchall = cursor.fetchall()[0]
            self.output_string[i] += str(fetchall[0]) + " " + str(
                fetchall[1]) + ' vs '
            cursor.execute(
                """SELECT TEAM_CITY, TEAM_NAME FROM team
                                                  WHERE TEAM_ID = (?)
                                              """, (l[i][1], ))
            fetchall = cursor.fetchall()[0]
            self.output_string[i] += str(fetchall[0]) + " " + str(fetchall[1])
            bs.add_item(self.output_string[i],
                        self.show_game_info,
                        icon='bomb')

        bs.open()

        connect.commit()

    def show_game_info(self, date):

        self.root.ids.scr_mngr.current = 'game-toolbar'
        self.root.ids.game_header.title = date.text
        result = re.split(' ', str(date.text))
        connect = sqlite3.connect("nbadb.db")
        cursor = connect.cursor()

        if (result[0] == 'New') or (result[0] == 'San') or (
                result[0] == 'Los') or (result[0] == 'Golden') or (
                    result[0] == 'Oklahoma') or (result[0] == 'Portland'):
            self.root.ids.image1.source = 'nba_logos/' + result[2] + '.png'
            self.root.ids.image2.source = 'nba_logos/' + result[len(result) -
                                                                1] + '.png'
            team_name_away = str(result[0] + ' ' + result[1] + ' ' + result[2])

        else:
            self.root.ids.image1.source = 'nba_logos/' + result[1] + '.png'
            self.root.ids.image2.source = 'nba_logos/' + result[len(result) -
                                                                1] + '.png'
            team_name_away = str(result[0] + ' ' + result[1])

        if (result[len(result) - 3]
                == 'New') or (result[len(result) - 3] == 'San') or (
                    result[len(result) - 3]
                    == 'Los') or (result[len(result) - 3] == 'Golden') or (
                        result[len(result) - 3]
                        == 'Oklahoma') or (result[len(result) - 3]
                                           == 'Portland'):
            team_name_home = str(result[len(result) - 3] + ' ' +
                                 result[len(result) - 2] + ' ' +
                                 result[len(result) - 1])
        else:
            team_name_home = str(result[len(result) - 2] + ' ' +
                                 result[len(result) - 1])
        cursor.execute(
            """SELECT W, L, TEAM_ID FROM team_adv_stats
                                                          WHERE TEAM_NAME = (?)
                                                      """, (team_name_away, ))

        wins_visitor, losses_visitor, self.team_id_visitor = cursor.fetchall(
        )[0]
        self.root.ids.wins_visitor.text = str(wins_visitor)
        self.root.ids.losses_visitor.text = str(losses_visitor)

        cursor.execute(
            """SELECT W, L,TEAM_ID FROM team_adv_stats
                                                          WHERE TEAM_NAME = (?)
                                                      """, (team_name_home, ))

        wins_home, losses_home, self.team_id_home = cursor.fetchall()[0]

        self.root.ids.wins_home.text = str(wins_home)
        self.root.ids.losses_home.text = str(losses_home)

        cursor.execute(
            """SELECT TEAM_CONFERENCE, TEAM_DIVISION,CONF_RANK FROM team
                                                                          WHERE TEAM_ID = (?)
                                                                      """,
            (self.team_id_visitor, ))
        away_team_conf, away_team_div, away_team_conf_rank = cursor.fetchall(
        )[0]
        self.root.ids.conf_visitor.text = str(away_team_conf)
        self.root.ids.div_visitor.text = str(away_team_div)
        self.root.ids.pos_visitor.text = str(away_team_conf_rank)

        cursor.execute(
            """SELECT TEAM_CONFERENCE, TEAM_DIVISION,CONF_RANK, TEAM_CITY FROM team
                                                                  WHERE TEAM_ID = (?)
                                                              """,
            (self.team_id_home, ))
        home_team_conf, home_team_div, home_team_conf_rank, city = cursor.fetchall(
        )[0]
        self.root.ids.conf_home.text = str(home_team_conf)
        self.root.ids.div_home.text = str(home_team_div)
        self.root.ids.pos_home.text = str(home_team_conf_rank)
        self.root.ids.game_head_label.text = "Дата:\n" + str(
            self.previous_date) + "\nГород:\n" + str(city)
        self.root.ids.pred_home.text = '-'
        self.root.ids.pred_visitor.text = '-'

    def show_result(self):
        score_home, score_away, home, guest = get_tempo(
            self.team_id_home, self.team_id_visitor)
        score_home, score_away, home, guest = get_refs(score_home, score_away,
                                                       home, guest)
        score_home, score_away, home, guest = get_reb(score_home, score_away,
                                                      home, guest)
        score_home, score_away = get_clutch(score_home, score_away, home,
                                            guest)
        self.root.ids.pred_home.text = str(round(score_home))
        self.root.ids.pred_visitor.text = str(round(score_away))

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon",
                    lambda x: x,
                    icon='clipboard-account')
        bs.add_item("Here's another!", lambda x: x, icon='nfc')
        bs.open()

    def show_example_grid_bottom_sheet(self):
        bs = MDGridBottomSheet()
        bs.add_item("Facebook",
                    lambda x: x,
                    icon_src='./assets/facebook-box.png')
        bs.add_item("YouTube",
                    lambda x: x,
                    icon_src='./assets/youtube-play.png')
        bs.add_item("Twitter", lambda x: x, icon_src='./assets/twitter.png')
        bs.add_item("Da Cloud",
                    lambda x: x,
                    icon_src='./assets/cloud-upload.png')
        bs.add_item("Camera", lambda x: x, icon_src='./assets/camera.png')
        bs.open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass
Exemple #5
0
class sponsers(Screen):
    theme_cls = ThemeManager()

    def cng_scr(self, k):
        self.manager.current = k
Exemple #6
0
class total(App):
    theme_cls = ThemeManager()
    map_state = 0
    info_state = 0
    event_scr_effects = [0, 0, 0, 0, 0, 0]
    path_back = []
    prof_con = [False, False, False, False, False]

    def cng_scr(self, scr):
        if (db.get_status() == 0):
            self.golag = pop.conf_pop('Please Login to submit Feedback',
                                      'Login', lambda x: self.GoLog())
            self.golag.open()
            return
        self.main_widget.ids.scr_mngr.current = scr

    def logout(self):
        db.change_status('0')
        try:
            self.dialog0.dismiss()
        except Exception:
            pass
        self.main_widget.ids.scr_mngr.current = 'all'

    def build(self):
        self.main_widget = Builder.load_string(main_widget_kv)
        self.main_widget.ids.scr_mngr.transition = SwapTransition()
        self.main_widget.ids.scr_mngr.add_widget(home_screen())
        self.main_widget.ids.scr_mngr.add_widget(first_intro.kar())
        self.main_widget.ids.scr_mngr.add_widget(events.event())
        self.main_widget.ids.scr_mngr.add_widget(prof.profser())
        self.main_widget.ids.scr_mngr.add_widget(events.sponsers())
        self.main_widget.ids.scr_mngr.add_widget(feed.fed())
        self.main_widget.ids.scr_mngr.add_widget(Example())
        self.main_widget.ids.scr_mngr.add_widget(exmple())
        return self.main_widget

    def on_start(self):
        if (db.get_status() == 0):
            self.main_widget.ids.logStatus.text = 'login'
        from kivy.base import EventLoop
        EventLoop.window.bind(on_keyboard=self.hook_keyboard)

    def hook_keyboard(self, window, key, *largs):
        if key == 27:
            if (self.main_widget.ids.scr_mngr.current_screen.name == 'vute'):
                return True
            level = {
                'logi': 'all',
                'rege': 'all',
                'info': 'vute',
                'show6': 'event',
                'show5': 'event',
                'show3': 'event',
                'show4': 'event',
                'show1': 'event',
                'prof1': 'pro',
                'prof2': 'pro',
                'prof3': 'pro',
                'event': 'vute',
                'shed': 'vute',
                'pro': 'vute',
                'spons': 'vute',
                'feed': 'vute',
                'cont': 'vute',
                'dir': 'vute'
            }
            self.main_widget.ids.scr_mngr.current = level[
                self.main_widget.ids.scr_mngr.current_screen.name]
        return True

    def on_pause(self):
        return True

    def back(self, sc):
        self.main_widget.ids.scr_mngr.current = sc

    def show_logout(self):
        print(db.get_status())
        if (db.get_status() == 0):
            self.logout()
            return
        self.dialog0 = pop.conf_pop('are you sure to logout', 'logout',
                                    lambda x: self.logout())
        self.dialog0.open()

    def enroll(self, status, event, no):
        if (db.get_status() == 0):
            self.golag = pop.conf_pop('Please Login to get Enroll', 'Login',
                                      lambda x: self.GoLog())
            self.golag.open()
            return
        if status == 'registered':
            return
        self.dialog0 = pop.conf_pop('are you sure to enroll ' + event,
                                    'enroll',
                                    lambda x: self.enroll2(event, no))
        self.dialog0.open()

    def enroll2(self, event, no):
        self.dialog0.dismiss()
        self.dialoga = pop.load_pop()
        k = threading.Thread(target=self.enroll1, args=(event, no))
        k.start()
        self.dialoga.open()

    def enroll1(self, event, no):
        dblist = db.get_db('all')
        namedb = dblist[0]
        numberdb = dblist[1]
        maildb = dblist[2]
        data = {numberdb: {'name': namedb}}
        k1 = set_firebase(event, data)
        data1 = {'t' + str(no): '1'}
        k2 = set_firebase(maildb, data1)
        if (k1 == 0) | (k2 == 0):
            pop.error_pop('please turn on internet')
            self.dialoga.dismiss()
            return
        else:
            db.change_db(no, '1')
        self.dialoga.dismiss()
        self.event_scr_effects[no - 1] = 1
        if self.info_state != 0:
            self.info_state = 1
        Snackbar(text="successfully enrolled").show()
        self.main_widget.ids.scr_mngr.current = 'event'

    def load_map(self):
        if self.map_state == 0:
            self.main_widget.ids.scr_mngr.add_widget(direction.Venue())
            self.map_state = 1
        self.path_back.append('vute')
        self.main_widget.ids.scr_mngr.current = 'dir'

    def load_info(self):
        if (db.get_status() == 0):
            self.golag = pop.conf_pop('Please Login to get info', 'Login',
                                      lambda x: self.GoLog())
            self.golag.open()
            return
        if self.info_state == 0:
            self.main_widget.ids.scr_mngr.add_widget(person.lis())
            self.info_state = 2
        elif self.info_state == 1:
            self.main_widget.ids.scr_mngr.get_screen('info').clear_widgets()
            self.main_widget.ids.scr_mngr.get_screen('info').__init__()
        self.path_back.append('vute')
        self.main_widget.ids.scr_mngr.current = 'info'

    def cng_screen(self, non, pro=0):
        if (self.main_widget.ids.scr_mngr.has_screen(non)):
            self.cng_screen1(non, pro)
            return
        elif (self.main_widget.ids.scr_mngr.has_screen('show' + str(non))):
            self.cng_screen1(non, pro)
            return
        else:
            self.dialoga = pop.load_pop()
            #k=threading.Thread(target=self.cng_screen1,args=(non,pro))
            #k.start()
            Clock.schedule_once(lambda dt: self.cng_screen1(non, pro), 0)
            self.dialoga.open()

    def GoLog(self):
        self.main_widget.ids.scr_mngr.current = 'all'
        try:
            self.golag.dismiss()
        except Exception:
            pass

    def cng_screen1(self, non, pro=0):
        if (pro == 1):
            if ((non == "prof1") & (not self.prof_con[0])):
                print('loading')
                self.prof_con[0] = True
                self.main_widget.ids.scr_mngr.add_widget(prof.prof1())
            if ((non == "prof2") & (not self.prof_con[1])):
                self.prof_con[1] = True
                self.main_widget.ids.scr_mngr.add_widget(prof.prof2())
            if ((non == "prof3") & (not self.prof_con[2])):
                self.prof_con[2] = True
                self.main_widget.ids.scr_mngr.add_widget(prof.prof3())
            if ((non == "cont") & (not self.prof_con[3])):
                self.prof_con[3] = True
                self.main_widget.ids.scr_mngr.add_widget(events.contact())
            if ((non == "shed") & (not self.prof_con[4])):
                try:
                    self.main_widget.ids.scr_mngr.add_widget(listest.lis())
                except Exception:
                    self.dialog0 = pop.conf_pop(
                        'no Internet Connection', 'Dismiss',
                        lambda x: self.dialog0.dismiss())
                    self.dialog0.open()
                    self.dialoga.dismiss()
                    return
                self.prof_con[4] = True
            try:
                self.dialoga.dismiss()
            except Exception:
                pass
            self.main_widget.ids.scr_mngr.current = non
            return

        if not self.main_widget.ids.scr_mngr.has_screen('show' + str(non)):
            if (non == 1):
                self.main_widget.ids.scr_mngr.add_widget(events.show1())
                self.event_scr_effects[non - 1] = 0
            if (non == 2):
                self.main_widget.ids.scr_mngr.add_widget(events.show2())
                self.event_scr_effects[non - 1] = 0
            if (non == 3):
                self.main_widget.ids.scr_mngr.add_widget(events.show3())
                self.event_scr_effects[non - 1] = 0
            if (non == 4):
                self.main_widget.ids.scr_mngr.add_widget(events.show4())
                self.event_scr_effects[non - 1] = 0
            if (non == 5):
                self.main_widget.ids.scr_mngr.add_widget(events.show5())
                self.event_scr_effects[non - 1] = 0
            if (non == 6):
                self.main_widget.ids.scr_mngr.add_widget(events.show6())
                self.event_scr_effects[non - 1] = 0
            self.path_back.append('event')
            try:
                self.dialoga.dismiss()
            except Exception:
                pass
            self.main_widget.ids.scr_mngr.current = 'show' + str(non)
            return
        if self.event_scr_effects[non - 1] == 0:
            self.path_back.append('event')
            try:
                self.dialoga.dismiss()
            except Exception:
                pass
            self.main_widget.ids.scr_mngr.current = 'show' + str(non)
            return
        posta = int(db.get_db(non))
        if (posta == 1):
            nor = 'registered'
            nocolor = self.theme_cls.green_color
        else:
            nor = 'enroll'
            nocolor = self.theme_cls.primary_color
        self.main_widget.ids.scr_mngr.get_screen('show' +
                                                 str(non)).ids.but.text = nor
        self.main_widget.ids.scr_mngr.get_screen(
            'show' + str(non)).ids.but.md_bg_color = nocolor
        self.event_scr_effects[non - 1] = 0
        self.path_back.append('event')
        try:
            self.dialoga.dismiss()
        except Exception:
            pass
        self.main_widget.ids.scr_mngr.current = 'show' + str(non)

    def pop1(self):
        p = Popup(title='IT 2017-2021',
                  title_color=[1, 0, 0, 1],
                  background='',
                  size_hint=[0.75, 0.6])
        b = BoxLayout(orientation='vertical')
        #b.add_widget(Image(source='a1.jpg'))
        b1 = BoxLayout(orientation='vertical')
        b1.add_widget(MDSeparator(height=dp(1)))
        b1.add_widget(
            MDLabel(
                text=
                'Developed by IT 2017 Batch\n Special Thanks to All who helped this',
                halign='left'))
        b1.add_widget(MDSeparator(height=dp(1)))
        b.add_widget(b1)
        p.add_widget(b)
        p.open()

    def gallery(self):
        webbrowser.open(
            'https://drive.google.com/folderview?id=112Jf12hrm2V5sjiXXXrRIAY2YMIuwYPa'
        )
Exemple #7
0
class DatelbotApp(App):
    theme_cls = ThemeManager()
    help_text = """
How to use [color=442B69]Datelbot[/color]:
1) Open new tab in any browser and navigate to nedatluj.cz
2) Select your exercise
3) Press Emulate button in [color=442B69]Datelbot[/color]

[i][color=444]Note: Datelbot works only with Chrome web browser at the moment[/color][/i]

\u00a9[color=442B69]Xtremeware[/color] 2018 All rights reserved
Created by: [color=442B69]Jakub Bláha[/color]
"""
    small_height = 110
    large_height = 300

    def __init__(self):
        super(DatelbotApp, self).__init__()

        self.theme_cls.primary_palette = 'Purple'

    def build(self):
        Window.on_cursor_enter = self.on_enter
        Window.on_cursor_leave = self.on_leave

        foo = lambda *args: self.info("Hey, use the help button!")
        Clock.schedule_once(foo, 4)

        return CustStackLayout()

    def on_leave(self, *args):
        anim = Animation(color=[.8, .8, .8, 1], d=.1)
        anim.start(self.root.ids.header)

    def on_enter(self, *args):
        anim = Animation(color=self.theme_cls.primary_color, d=.1)
        anim.start(self.root.ids.header)

    def info(self, text):
        self.root.ids.info.update(text)

    def help(self):
        self.root.ids.help_button.disabled = True

        self.help_popup = HelpPopup()

        anim = Animation(
            size=(Window.width, self.large_height + 6), t='out_expo', d=1)

        anim.start(Window)

        Clock.schedule_once(self.help_popup.open, .2)

    def dismiss_help(self):
        self.help_popup.dismiss()

        anim = Animation(
            size=(Window.width, self.small_height - 4), t='out_expo', d=1)

        anim.start(Window)

        def fix_fuzz(*args):
            Window.size = (Window.width, self.small_height)

        def enable_help(*args):
            self.root.ids.help_button.disabled = False

        Clock.schedule_once(fix_fuzz, .6)
        Clock.schedule_once(enable_help, 1)

    def run_emul(self):
        if Switcher.switch_to_target():
            Emulator.emulate()
            self.info("Completed")

        else:
            self.info("Failed to load browser tab!")

    def on_start(self, *args):
        register_topmost(Window, TITLE)
Exemple #8
0
class HackFCApp(App):
    theme_cls = ThemeManager()

    def get_StatusMercado(self, *args):
        url = 'https://api.cartolafc.globo.com/mercado/status'
        r = requests.get(url)
        status = r.json()

        status_mer = ''
        if True:  # status['status_mercado'] == 1:
            status_mer = "Mercado Aberto: Fecha em %s" % datetime.fromtimestamp(
                int(status['fechamento']['timestamp'])).strftime(
                    "%d/%m/%Y %H:%M")
        else:
            status_mer = 'Mercado Fechado'

        return status_mer

    def build(self):
        self.rv = self.root.ids.rv
        self.popula_listview()
        self.menu_items = [
            {
                'viewclass': 'MDMenuItem',
                'text': 'Classificar por:'
            },
            {
                'viewclass': 'MDMenuItem',
                'text': 'Example item'
            },
            {
                'viewclass': 'MDMenuItem',
                'text': 'Example item'
            },
            {
                'viewclass': 'MDMenuItem',
                'text': 'Example item'
            },
            {
                'viewclass': 'MDMenuItem',
                'text': 'Example item'
            },
            {
                'viewclass': 'MDMenuItem',
                'text': 'Example item'
            },
            {
                'viewclass': 'MDMenuItem',
                'text': 'Example item'
            },
        ]

    def proccess_atleta(self, atleta):
        foto = ''
        try:
            if atleta['foto'][-4:] == '.png':
                foto = atleta['foto'][:-11] + '140x140.png'
            elif atleta['foto'][-5:] == '.jpeg':
                foto = atleta['foto'][:-12] + '140x140.jpeg'
            else:
                foto = ''
        except:
            pass

        a = {
            'viewclass':
            'Atletas',
            'nome':
            '[b]%s[/b]\n[color=22FF59]C$ %s[/color]' %
            (atleta['apelido'], atleta['preco_num']),
            'link_on_avatar':
            foto,
            'height':
            dp(80)
        }
        return a

    def popula_listview(self, *args):
        url = 'https://api.cartolafc.globo.com/atletas/mercado'
        r = requests.get(url)
        dados = r.json()
        atletas = dados['atletas']

        self.rv.data = [self.proccess_atleta(a) for a in atletas]
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     Window.bind(on_keyboard=self.android_back_click)
     theme_cls = ThemeManager()
from kivy.app import App
from kivy.properties import ObjectProperty

from kivymd.theming import ThemeManager

from .screens import SCREENS, SCREEN_TYPE


class {{cookiecutter.repo_name | capitalize}}App(App):
    """Basic kivy app

    Edit {{cookiecutter.repo_name}}.kv to get started.
    """
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'DeepPurple'
    title = "{{ cookiecutter.project_name }}"

    manager = ObjectProperty(None)

    def build(self):
        self.manager = self.root.ids.manager
        return self.root
    
    def on_start(self, ):
        self.goto(SCREEN_TYPE.HOME)

    def goto(self, screenType, **kwargs):
        if isinstance(screenType, SCREEN_TYPE):
            screen = SCREENS[screenType](self, **kwargs)
            self.manager.switch_to(screen)
        else:
Exemple #11
0
class KitchenSink(App, Screens):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = "BlueGray"
    theme_cls.accent_palette = "Gray"
    previous_date = ObjectProperty()
    title = "Kitchen Sink"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.menu_items = [{
            "viewclass": "MDMenuItem",
            "text": "Example item %d" % i,
            "callback": self.callback_for_menu_items,
        } for i in range(15)]
        self.Window = Window

        # Default class instances.
        self.manager = None
        self.md_app_bar = None
        self.instance_menu_demo_apps = None
        self.instance_menu_source_code = None
        self.md_theme_picker = None
        self.long_dialog = None
        self.input_dialog = None
        self.alert_dialog = None
        self.ok_cancel_dialog = None
        self.long_dialog = None
        self.dialog = None
        self.user_card = None
        self.bs_menu_1 = None
        self.bs_menu_2 = None
        self.popup_screen = None
        self.my_snackbar = None
        self.dialog_load_kv_files = None

        self.create_stack_floating_buttons = False
        self.manager_open = False
        self.cards_created = False

        self._interval = 0
        self.tick = 0
        self.x = 0
        self.y = 25
        self.file_source_code = ""

        self.hex_primary_color = get_hex_from_color(
            self.theme_cls.primary_color)
        self.previous_text = (
            f"Welcome to the application [b][color={self.hex_primary_color}]"
            f"Kitchen Sink[/color][/b].\nTo see [b]"
            f"[color={self.hex_primary_color}]KivyMD[/color][/b] "
            f"examples, open the menu and select from the list the desired "
            f"example or")
        self.previous_text_end = (
            f"for show example apps\n\n"
            f"Author - [b][color={self.hex_primary_color}]"
            f"Andrés Rodríguez[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n\n"
            f"Authors this Fork:\n\n"
            f"[b][color={self.hex_primary_color}]"
            f"Ivanov Yuri[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"[b][color={self.hex_primary_color}]Artem S. Bulgakov[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"and contributors...")
        self.names_contacts = (
            "Alexandr Taylor",
            "Yuri Ivanov",
            "Robert Patric",
            "Bob Marley",
            "Magnus Carlsen",
            "Jon Romero",
            "Anna Bell",
            "Maxim Kramerer",
            "Sasha Gray",
            "Vladimir Ivanenko",
        )
        self.demo_apps_list = [
            "Shop Window",
            "Coffee Menu",
            "Fitness Club",
            "Registration",
            "Account Page",
        ]
        self.list_name_icons = list(md_icons.keys())[0:15]
        Window.bind(on_keyboard=self.events)
        crop_image(
            (Window.width, int(dp(Window.height * 35 // 100))),
            f"{demos_assets_path}guitar-1139397_1280.png",
            f"{demos_assets_path}guitar-1139397_1280_crop.png",
        )

    def set_list_for_refresh_layout(self):
        async def set_list_for_refresh_layout():
            names_icons_list = list(md_icons.keys())[self.x:self.y]
            for name_icon in names_icons_list:
                await asynckivy.sleep(0)
                self.data["Refresh Layout"]["object"].ids.box.add_widget(
                    ItemForListRefreshLayout(icon=name_icon, text=name_icon))
            self.data["Refresh Layout"][
                "object"].ids.refresh_layout.refresh_done()

        asynckivy.start(set_list_for_refresh_layout())

    def refresh_callback(self, *args):
        """A method that updates the state of your application
        while the spinner remains on the screen."""
        def refresh_callback(interval):
            self.data["Refresh Layout"]["object"].ids.box.clear_widgets()
            if self.x == 0:
                self.x, self.y = 25, 50
            else:
                self.x, self.y = 0, 25
            self.set_list_for_refresh_layout()
            self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def build_tabs(self):
        for name_tab in self.list_name_icons:
            tab = Factory.MyTab(text=name_tab)
            self.data["Tabs"]["object"].ids.android_tabs.add_widget(tab)

    def switch_tabs_to_icon(self, istance_android_tabs):
        for i, instance_tab in enumerate(
                istance_android_tabs.ids.scrollview.children[0].children):
            istance_android_tabs.ids.scrollview.children[0].remove_widget(
                instance_tab)
            istance_android_tabs.add_widget(
                Factory.MyTab(text=self.list_name_icons[i]))

    def switch_tabs_to_text(self, istance_android_tabs):
        for instance_tab in istance_android_tabs.ids.scrollview.children[
                0].children:
            for k, v in md_icons.items():
                if v == instance_tab.text:
                    istance_android_tabs.ids.scrollview.children[
                        0].remove_widget(instance_tab)
                    istance_android_tabs.add_widget(
                        Factory.MyTab(
                            text=" ".join(k.split("-")).capitalize()))
                    break

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        """Crop images for Grid screen."""

        if not os.path.exists(os.path.join(self.directory,
                                           path_to_crop_image)):
            size = (int(size[0]), int(size[1]))
            path_to_origin_image = path_to_crop_image.replace("_tile_crop", "")
            crop_image(size, path_to_origin_image, path_to_crop_image)
        instance.source = path_to_crop_image

    def theme_picker_open(self):
        if not self.md_theme_picker:
            from kivymd.uix.picker import MDThemePicker

            self.md_theme_picker = MDThemePicker()
        self.md_theme_picker.open()

    def example_add_stack_floating_buttons(self):
        from kivymd.uix.stackfloatingbutton import MDStackFloatingButtons

        def set_my_language(instance_button):
            toast(instance_button.icon)

        if not self.create_stack_floating_buttons:
            screen = self.main_widget.ids.scr_mngr.get_screen("stack buttons")
            screen.add_widget(
                MDStackFloatingButtons(
                    icon="lead-pencil",
                    floating_data={
                        "Python": "language-python",
                        "Php": "language-php",
                        "C++": "language-cpp",
                    },
                    callback=set_my_language,
                ))
            self.create_stack_floating_buttons = True

    def set_expansion_panel(self):
        from kivymd.uix.expansionpanel import MDExpansionPanel

        def callback(text):
            toast(f"{text} to {content.name_item}")

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.data["Expansion Panel"]["object"].ids.anim_list.add_widget(
                MDExpansionPanel(
                    content=content,
                    icon="assets/kivy-logo-white-512.png",
                    title=name_contact,
                ))

    def set_chevron_back_screen(self):
        """Sets the return chevron to the previous screen in ToolBar."""

        self.main_widget.ids.toolbar.right_action_items = [[
            "dots-vertical", lambda x: self.root.toggle_nav_drawer()
        ]]

    def download_progress_hide(self, instance_progress, value):
        """Hides progress progress."""

        self.main_widget.ids.toolbar.right_action_items = [[
            "download",
            lambda x: self.download_progress_show(instance_progress),
        ]]

    def download_progress_show(self, instance_progress):
        self.set_chevron_back_screen()
        instance_progress.open()
        instance_progress.animation_progress_from_fade()

    def show_example_download_file(self, interval):
        from kivymd.uix.progressloader import MDProgressLoader

        def get_connect(host="8.8.8.8", port=53, timeout=3):
            import socket

            try:
                socket.setdefaulttimeout(timeout)
                socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
                    (host, port))
                return True
            except (TimeoutError, ConnectionError, OSError):
                return False

        if get_connect():
            link = ("https://www.python.org/ftp/python/3.5.1/"
                    "python-3.5.1-embed-win32.zip")
            progress = MDProgressLoader(
                url_on_image=link,
                path_to_file=os.path.join(self.directory, "python-3.5.1.zip"),
                download_complete=self.download_complete,
                download_hide=self.download_progress_hide,
            )
            progress.start(self.data["Download File"]["object"].ids.box_flt)
        else:
            toast("Connect error!")

    def download_complete(self):
        self.set_chevron_back_screen()
        toast("Done")

    def file_manager_open(self):
        from kivymd.uix.filemanager import MDFileManager
        from kivymd.uix.dialog import MDDialog

        def open_file_manager(text_item, dialog):
            previous = False if text_item == "List" else True
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(
                exit_manager=self.exit_manager,
                select_path=self.select_path,
                previous=previous,
            )
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(self.user_data_dir)
            self.manager_open = True
            self.manager.open()

        MDDialog(
            title="Title",
            size_hint=(0.8, 0.4),
            text_button_ok="List",
            text="Open manager with 'list' or 'previous' mode?",
            text_button_cancel="Previous",
            events_callback=open_file_manager,
        ).open()

    def select_path(self, path):
        """It will be called when you click on the file name
        or the catalog selection button.
        :type path: str;
        :param path: path to the selected directory or file;
        """

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        """Called when the user reaches the root of the directory tree."""

        self.manager.dismiss()
        self.manager_open = False
        self.set_chevron_menu()

    def set_chevron_menu(self):
        self.main_widget.ids.toolbar.left_action_items = [[
            "menu", lambda x: self.root.toggle_nav_drawer()
        ]]

    def events(self, instance, keyboard, keycode, text, modifiers):
        """Called when buttons are pressed on the mobile device."""

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True

    def callback_for_menu_items(self, *args):
        toast(args[0])

    def add_cards(self, instance_grid_card):
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        from kivymd.uix.card import MDCardPost

        def callback(instance, value):
            if value is None:
                toast("Delete post %s" % str(instance))
            elif isinstance(value, int):
                toast("Set like in %d stars" % value)
            elif isinstance(value, str):
                toast("Repost with %s " % value)
            elif isinstance(value, list):
                toast(value[1])

        if not self.cards_created:
            self.cards_created = True
            menu_items = [{
                "viewclass": "MDMenuItem",
                "text": "Example item %d" % i,
                "callback": self.callback_for_menu_items,
            } for i in range(2)]
            buttons = ["facebook", "vk", "twitter"]

            instance_grid_card.add_widget(
                MDCardPost(text_post="Card with text",
                           swipe=True,
                           callback=callback))
            instance_grid_card.add_widget(
                MDCardPost(
                    right_menu=menu_items,
                    swipe=True,
                    text_post="Card with a button to open the menu MDDropDown",
                    callback=callback,
                ))
            instance_grid_card.add_widget(
                MDCardPost(
                    likes_stars=True,
                    callback=callback,
                    swipe=True,
                    text_post="Card with asterisks for voting.",
                ))

            image_for_card = (
                f"{demos_assets_path}kitten-for_card-1049129_1280-crop.png")
            if not os.path.exists(image_for_card):
                crop_image(
                    (int(Window.width), int(dp(200))),
                    f"{demos_assets_path}kitten-1049129_1280.png",
                    image_for_card,
                )
            instance_grid_card.add_widget(
                MDCardPost(
                    source=image_for_card,
                    tile_text="Little Baby",
                    tile_font_style="H5",
                    text_post="This is my favorite cat. He's only six months "
                    "old. He loves milk and steals sausages :) "
                    "And he likes to play in the garden.",
                    with_image=True,
                    swipe=True,
                    callback=callback,
                    buttons=buttons,
                ))

    def update_screen(self, instance):
        """Set new label on the screen UpdateSpinner."""
        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.data["Update Screen Widget"][
                    "object"].ids.upd_lbl.text = "New string"
                Clock.unschedule(update_screen)

        Clock.schedule_interval(update_screen, 1)

    main_widget = None

    def build(self):
        self.main_widget = Builder.load_string(main_widget_kv)
        return self.main_widget

    def show_popup_screen(self):
        if not self.popup_screen:
            self.popup_screen = self.data["Popup Screen"]["object"].ids.popup
            content_screen = ContentForPopupScreen()
            self.popup_screen.screen = content_screen
            self.popup_screen.padding = dp(10)
            self.popup_screen.background_color = self.theme_cls.primary_color
        self.popup_screen.show()

    def show_user_example_animation_card(self):
        """Create and open instance MDUserAnimationCard
        for the screen UserCard."""

        from kivymd.uix.useranimationcard import MDUserAnimationCard

        def main_back_callback():
            toast("Close card")

        if not self.user_card:
            image_for_user_card = (
                f"{demos_assets_path}guitar-for-user-card1139397_1280-crop.png"
            )
            if not os.path.exists(image_for_user_card):
                crop_image(
                    (int(Window.width), int(dp(Window.height * 40 // 100))),
                    f"{demos_assets_path}guitar-1139397_1280.png",
                    image_for_user_card,
                )

            self.user_card = MDUserAnimationCard(
                user_name="Lion Lion",
                path_to_avatar=image_for_user_card,
                callback=main_back_callback,
            )
            self.user_card.box_content.add_widget(ContentForAnimCard())
        self.user_card.open()

    def show_example_snackbar(self, snack_type):
        """Create and show instance Snackbar for the screen MySnackBar."""
        def callback(instance):
            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.my_snackbar.duration:
                anim = Animation(y=dp(10), d=0.2)
                anim.start(self.data["Snackbars"]["object"].ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.my_snackbar = None

        from kivymd.uix.snackbar import Snackbar

        if snack_type == "simple":
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == "button":
            Snackbar(
                text="This is a snackbar",
                button_text="WITH A BUTTON",
                button_callback=callback,
            ).show()
        elif snack_type == "verylong":
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()
        elif snack_type == "float":
            if not self.my_snackbar:
                self.my_snackbar = Snackbar(
                    text="This is a snackbar!",
                    button_text="Button",
                    duration=3,
                    button_callback=callback,
                )
                self.my_snackbar.show()
                anim = Animation(y=dp(72), d=0.2)
                anim.bind(on_complete=lambda *args: Clock.schedule_interval(
                    wait_interval, 0))
                anim.start(self.data["Snackbars"]["object"].ids.button)

    def show_example_input_dialog(self):
        """Creates an instance of the dialog box and displays it
        on the screen for the screen Dialogs."""
        def result(text_button, instance):
            toast(instance.text_field.text)

        if not self.input_dialog:
            from kivymd.uix.dialog import MDInputDialog

            self.input_dialog = MDInputDialog(
                title="Title",
                hint_text="Hint text",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                events_callback=result,
            )
        self.input_dialog.open()

    def show_example_alert_dialog(self):
        if not self.alert_dialog:
            from kivymd.uix.dialog import MDDialog

            self.alert_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="This is Alert dialog",
                events_callback=self.callback_for_menu_items,
            )
        self.alert_dialog.open()

    def show_example_ok_cancel_dialog(self):
        if not self.ok_cancel_dialog:
            from kivymd.uix.dialog import MDDialog

            self.ok_cancel_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="This is Ok Cancel dialog",
                text_button_cancel="Cancel",
                events_callback=self.callback_for_menu_items,
            )
        self.ok_cancel_dialog.open()

    def show_example_long_dialog(self):
        if not self.long_dialog:
            from kivymd.uix.dialog import MDDialog

            self.long_dialog = MDDialog(
                text="Lorem ipsum dolor sit amet, consectetur adipiscing "
                "elit, sed do eiusmod tempor incididunt ut labore et "
                "dolore magna aliqua. Ut enim ad minim veniam, quis "
                "nostrud exercitation ullamco laboris nisi ut aliquip "
                "ex ea commodo consequat. Duis aute irure dolor in "
                "reprehenderit in voluptate velit esse cillum dolore eu "
                "fugiat nulla pariatur. Excepteur sint occaecat "
                "cupidatat non proident, sunt in culpa qui officia "
                "deserunt mollit anim id est laborum.",
                title="Title",
                size_hint=(0.8, 0.4),
                text_button_ok="Yes",
                events_callback=self.callback_for_menu_items,
            )
        self.long_dialog.open()

    def get_time_picker_date(self, instance, time):
        """Get date for MDTimePicker from the screen Pickers."""

        self.data["Pickers"]["object"].ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        """Show MDTimePicker from the screen Pickers."""

        from kivymd.uix.picker import MDTimePicker

        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.get_time_picker_date)

        if self.data["Pickers"][
                "object"].ids.time_picker_use_previous_time.active:
            try:
                time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        time_dialog.open()

    def set_previous_date(self, date_obj):
        """Set previous date for MDDatePicker from the screen Pickers."""

        self.previous_date = date_obj
        self.data["Pickers"]["object"].ids.date_picker_label.text = str(
            date_obj)

    def show_example_date_picker(self):
        """Show MDDatePicker from the screen Pickers."""

        from kivymd.uix.picker import MDDatePicker

        if self.data["Pickers"][
                "object"].ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        """Show menu from the screen BottomSheet."""

        from kivymd.uix.bottomsheet import MDListBottomSheet

        if not self.bs_menu_1:
            self.bs_menu_1 = MDListBottomSheet()
            self.bs_menu_1.add_item(
                "Here's an item with text only",
                lambda x: self.callback_for_menu_items(
                    "Here's an item with text only"),
            )
            self.bs_menu_1.add_item(
                "Here's an item with an icon",
                lambda x: self.callback_for_menu_items(
                    "Here's an item with an icon"),
                icon="clipboard-account",
            )
            self.bs_menu_1.add_item(
                "Here's another!",
                lambda x: self.callback_for_menu_items("Here's another!"),
                icon="nfc",
            )
        self.bs_menu_1.open()

    def show_example_grid_bottom_sheet(self):
        """Show menu from the screen BottomSheet."""

        if not self.bs_menu_2:
            from kivymd.uix.bottomsheet import MDGridBottomSheet

            self.bs_menu_2 = MDGridBottomSheet()
            self.bs_menu_2.add_item(
                "Facebook",
                lambda x: self.callback_for_menu_items("Facebook"),
                icon_src="./assets/facebook-box.png",
            )
            self.bs_menu_2.add_item(
                "YouTube",
                lambda x: self.callback_for_menu_items("YouTube"),
                icon_src="./assets/youtube-play.png",
            )
            self.bs_menu_2.add_item(
                "Twitter",
                lambda x: self.callback_for_menu_items("Twitter"),
                icon_src="./assets/twitter.png",
            )
            self.bs_menu_2.add_item(
                "Da Cloud",
                lambda x: self.callback_for_menu_items("Da Cloud"),
                icon_src="./assets/cloud-upload.png",
            )
            self.bs_menu_2.add_item(
                "Camera",
                lambda x: self.callback_for_menu_items("Camera"),
                icon_src="./assets/camera.png",
            )
        self.bs_menu_2.open()

    def set_title_toolbar(self, title):
        """Set string title in MDToolbar for the whole application."""

        self.main_widget.ids.toolbar.title = title

    def set_appbar(self):
        """Create MDBottomAppBar for the screen BottomAppBar."""

        from kivymd.uix.toolbar import MDBottomAppBar

        def press_button(inctance):
            toast("Press Button")

        self.md_app_bar = MDBottomAppBar(
            md_bg_color=self.theme_cls.primary_color,
            left_action_items=[
                ["menu", lambda x: x],
                ["clock", lambda x: x],
                ["dots-vertical", lambda x: x],
            ],
            anchor="right",
            callback=press_button,
        )

    def move_item_menu(self, anchor):
        """Sets icons in MDBottomAppBar for the screen BottomAppBar."""

        md_app_bar = self.md_app_bar
        if md_app_bar.anchor != anchor:
            if len(md_app_bar.right_action_items):
                md_app_bar.left_action_items.append(
                    md_app_bar.right_action_items[0])
                md_app_bar.right_action_items = []
            else:
                left_action_items = md_app_bar.left_action_items
                action_items = left_action_items[0:2]
                md_app_bar.right_action_items = [left_action_items[-1]]
                md_app_bar.left_action_items = action_items

    def show_password(self, field, button):
        """
        Called when you press the right button in the password field
        for the screen TextFields.

        instance_field: kivy.uix.textinput.TextInput;
        instance_button: kivymd.button.MDIconButton;

        """

        # Show or hide text of password, set focus field
        # and set icon of right button.
        field.password = not field.password
        field.focus = True
        button.icon = "eye" if button.icon == "eye-off" else "eye-off"

    def set_error_message(self, *args):
        """Checks text of TextField with type "on_error"
        for the screen TextFields."""

        text_field_error = args[0]
        if len(text_field_error.text) == 2:
            text_field_error.error = True
        else:
            text_field_error.error = False

    def set_list_md_icons(self, text="", search=False):
        """Builds a list of icons for the screen MDIcons."""
        def add_icon_item(name_icon):
            self.main_widget.ids.scr_mngr.get_screen(
                "md icons").ids.rv.data.append({
                    "viewclass":
                    "MDIconItemForMdIconsList",
                    "icon":
                    name_icon,
                    "text":
                    name_icon,
                    "callback":
                    self.callback_for_menu_items,
                })

        self.main_widget.ids.scr_mngr.get_screen("md icons").ids.rv.data = []
        for name_icon in md_icons.keys():
            if search:
                if text in name_icon:
                    add_icon_item(name_icon)
            else:
                add_icon_item(name_icon)

    def set_source_code_file(self):
        """Assigns the file_source_code attribute the file name
        with example code for the current screen."""

        if self.main_widget.ids.scr_mngr.current == "code viewer":
            return

        has_screen = False
        for name_item_drawer in self.data.keys():
            if (self.data[name_item_drawer]["name_screen"] ==
                    self.main_widget.ids.scr_mngr.current):
                self.file_source_code = self.data[name_item_drawer].get(
                    "source_code", None)
                has_screen = True
                break
        if not has_screen:
            self.file_source_code = None

    def open_context_menu_source_code(self, instance):
        def callback_context_menu(icon):
            context_menu.dismiss()

            if not self.file_source_code:
                from kivymd.uix.snackbar import Snackbar

                Snackbar(text="No source code for this example").show()
                return
            if icon == "source-repository":
                if platform in ("win", "linux", "macosx"):
                    webbrowser.open(
                        f"https://github.com/HeaTTheatR/KivyMD/wiki/"
                        f"{os.path.splitext(self.file_source_code)[0]}")
                return
            elif icon == "language-python":
                self.main_widget.ids.scr_mngr.current = "code viewer"
                if self.file_source_code:
                    with open(
                            f"{self.directory}/KivyMD.wiki/{self.file_source_code}"
                    ) as source_code:
                        self.data["Source code"][
                            "object"].ids.code_input.text = source_code.read()

        menu_for_context_menu_source_code = []
        data = {
            "Source code": "language-python",
            "Open in Wiki": "source-repository",
        }
        if self.main_widget.ids.scr_mngr.current == "code viewer":
            data = {"Open in Wiki": "source-repository"}
        for name_item in data.keys():
            menu_for_context_menu_source_code.append({
                "viewclass":
                "MDIconItemForMdIconsList",
                "text":
                name_item,
                "icon":
                data[name_item],
                "text_color": [1, 1, 1, 1],
                "callback":
                lambda x=name_item: callback_context_menu(x),
            })
        context_menu = MDDropdownMenu(
            items=menu_for_context_menu_source_code,
            max_height=dp(260),
            width_mult=3,
        )
        context_menu.open(instance.ids.right_actions.children[0])

    def open_menu_for_demo_apps(self, instance):
        """
        Called when you click the "Click me" button on the start screen.
        Creates and opens a list of demo applications.

        :type instance: <kivymd.uix.button.MDRaisedButton object>

        """

        if not self.instance_menu_demo_apps:
            menu_for_demo_apps = []
            for name_item in self.demo_apps_list:
                menu_for_demo_apps.append({
                    "viewclass":
                    "OneLineListItem",
                    "text":
                    name_item,
                    "on_release":
                    lambda x=name_item: self.show_demo_apps(x),
                })
            self.instance_menu_demo_apps = MDDropdownMenu(
                items=menu_for_demo_apps,
                max_height=dp(260),
                width_mult=4,
                _center=True,
            )
        self.instance_menu_demo_apps.open(instance)

    def show_demo_apps(self, name_item):
        self.show_screens_demo(name_item)
        self.main_widget.ids.scr_mngr.current = name_item.lower()
        self.instance_menu_demo_apps.dismiss()

    def on_pause(self):
        return True

    def on_start(self):
        def _load_kv_for_demo(name_screen):
            from demo_apps.formone import FormOne
            from demo_apps.shopwindow import ShopWindow
            from demo_apps.coffeemenu import CoffeeMenu
            from demo_apps.fitnessclub import FitnessClub
            from demo_apps.accountpage import AccountPage

            Builder.load_string(self.data_for_demo[name_screen]["kv_string"])
            self.data_for_demo[name_screen]["object"] = eval(
                self.data_for_demo[name_screen]["class"])
            self.main_widget.ids.scr_mngr.add_widget(
                self.data_for_demo[name_screen]["object"])

        async def load_all_kv_files():
            for name_screen in self.data.keys():
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                Builder.load_string(self.data[name_screen]["kv_string"])
                self.data[name_screen]["object"] = eval(
                    self.data[name_screen]["Factory"])
                if name_screen == "Bottom App Bar":
                    self.set_appbar()
                    self.data[name_screen]["object"].add_widget(
                        self.md_app_bar)
                self.main_widget.ids.scr_mngr.add_widget(
                    self.data[name_screen]["object"])
                if name_screen == "Text fields":
                    self.data[name_screen]["object"].ids.text_field_error.bind(
                        on_text_validate=self.set_error_message,
                        on_focus=self.set_error_message,
                    )
                elif name_screen == "MD Icons":
                    self.set_list_md_icons()
                elif name_screen == "Tabs":
                    self.build_tabs()
                elif name_screen == "Refresh Layout":
                    self.set_list_for_refresh_layout()

            from demo_apps.formone import registration_form_one
            from demo_apps.shopwindow import screen_shop_window
            from demo_apps.coffeemenu import screen_coffee_menu
            from demo_apps.fitnessclub import screen_fitness_club
            from demo_apps.accountpage import screen_account_page

            data = {
                "Registration": registration_form_one,
                "Shop Window": screen_shop_window,
                "Coffee Menu": screen_coffee_menu,
                "Fitness Club": screen_fitness_club,
                "Account Page": screen_account_page,
            }

            for name_screen in data.keys():
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                self.data_for_demo[name_screen]["kv_string"] = data[
                    name_screen]
                _load_kv_for_demo(name_screen)

            self.dialog_load_kv_files.dismiss()

        self.dialog_load_kv_files = DialogLoadKvFiles()
        self.dialog_load_kv_files.open()
        asynckivy.start(load_all_kv_files())

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
Exemple #12
0
class MDApp(App, FpsMonitoring):
    theme_cls = ObjectProperty(ThemeManager())
Exemple #13
0
 def build(self):
     self.theme_cls = ThemeManager()
     pass
Exemple #14
0
class MobileInsightApp(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "MobileInsight"

    index = NumericProperty(0)
    current_title = StringProperty()
    screen_names = ListProperty([])

    use_kivy_settings = False

    def __init__(self, **kwargs):
        super(MobileInsightApp, self).__init__(**kwargs)
        self.title = 'MobileInsight'
        self.screens = {}
        self.available_screens = screens.__all__
        self.home_screen = None
        self.log_viewer_screen = None

        if not create_folder():
            # MobileInsight folders unavailable. Add warnings
            Logger.error("main: SDcard is unavailable. Please check.")
        main_utils.init_libs()
        main_utils.check_security_policy()
        COORDINATOR.start()  # FIXME: DEADLOCK HERE!!!

    def __del__(self):
        Logger.error("__del__")

    def __popup_dismiss(self, instance, answer):
        self.popup.dismiss()
        self.stop()
        return True

    def build_settings(self, settings):

        with open("settings.json", "r") as settings_json:
            settings.add_json_panel('General',
                                    self.config,
                                    data=settings_json.read())

        self.create_app_settings(self.config, settings)

    def create_app_settings(self, config, settings):
        app_list = get_plugins_list()
        for app in app_list:
            APP_NAME = app
            APP_DIR = app_list[app][0]
            setting_path = os.path.join(APP_DIR, "settings.json")
            if os.path.exists(setting_path):
                with open(setting_path, "r") as settings_json:
                    raw_data = settings_json.read()

                    # Regulate the config into the format that kivy can accept
                    tmp = eval(raw_data)

                    result = "["
                    default_val = {}

                    for index in range(len(tmp)):
                        if tmp[index]['type'] == 'title':
                            result = result + '{"type": "title","title": ""},'
                        elif tmp[index]['type'] == 'options':
                            default_val[tmp[index]
                                        ['key']] = tmp[index]['default']
                            result = result + '{"type": "' + tmp[index]['type'] \
                                + '","title":"' + tmp[index]['title'] \
                                + '","desc":"' + tmp[index]['desc'] \
                                + '","section":"' + APP_NAME \
                                + '","key":"' + tmp[index]['key'] \
                                + '","options":' + json.dumps(tmp[index]['options']) \
                                + '},'
                        else:
                            default_val[tmp[index]
                                        ['key']] = tmp[index]['default']
                            result = result + '{"type": "' + tmp[index]['type'] \
                                + '","title":"' + tmp[index]['title'] \
                                + '","desc":"' + tmp[index]['desc'] \
                                + '","section":"' + APP_NAME \
                                + '","key":"' + tmp[index]['key'] \
                                + '"},'
                    result = result[0:-1] + "]"

                    # Update the default value and setting menu
                    settings.add_json_panel(APP_NAME, config, data=result)

    def build_config(self, config):
        # Yuanjie: the ordering of the following options MUST be the same as
        # those in settings.json!!!
        config.setdefaults(
            'mi_general', {
                'bcheck_update': 0,
                'log_level': 'info',
                'bstartup': 0,
                'bstartup_service': 0,
                'bgps': 1,
                'start_service': 'NetLogger',
                'privacy': 0,
            })
        self.create_app_default_config(config)

    def create_app_default_config(self, config):
        app_list = get_plugins_list()
        for app in app_list:
            APP_NAME = app
            APP_DIR = app_list[app][0]
            setting_path = os.path.join(APP_DIR, "settings.json")
            if os.path.exists(setting_path):
                with open(setting_path, "r") as settings_json:
                    raw_data = settings_json.read()

                    # Regulate the config into the format that kivy can accept
                    tmp = eval(raw_data)

                    default_val = {}

                    for index in range(len(tmp)):
                        if tmp[index]['type'] == 'title':
                            pass
                        elif 'default' in tmp[index]:
                            default_val[tmp[index]
                                        ['key']] = tmp[index]['default']

                    # Update the default value and setting menu
                    config.setdefaults(APP_NAME, default_val)

    def build(self):
        # Force to initialize all configs in .mobileinsight.ini
        # This prevents missing config due to existence of older-version .mobileinsight.ini
        # Work-around: force on_config_change, which would update config.ini
        config = self.load_config()
        val = int(config.get('mi_general', 'bcheck_update'))
        config.set('mi_general', 'bcheck_update', int(not val))
        config.write()
        config.set('mi_general', 'bcheck_update', val)
        config.write()

        Window.borderless = False

        self.screens = {}
        self.available_screens = screens.__all__
        self.screen_names = self.available_screens
        for i in range(len(self.available_screens)):
            self.screens[i] = getattr(screens, self.available_screens[i])()
        self.home_screen = self.screens[0]
        COORDINATOR.setup_analyzers()
        COORDINATOR.send_control('START')
        self.root.ids.scr_mngr.switch_to(self.screens[0])

    def go_screen(self, idx):
        if self.index == idx:
            return
        self.index = idx
        self.root.ids.scr_mngr.switch_to(self.load_screen(idx),
                                         direction='left')

    def load_screen(self, index):
        return self.screens[index]

    def get_time_picker_data(self, instance, time):
        self.root.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        self.time_dialog = MDTimePicker()
        self.time_dialog.bind(time=self.get_time_picker_data)
        if self.root.ids.time_picker_use_previous_time.active:
            try:
                self.time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        self.time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.root.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_pause(self):
        # Yuanjie: The following code prevents screen freeze when screen off ->
        # screen on
        Logger.error("on_pause")
        try:
            pm = current_activity.getSystemService(
                autoclass('android.content.Context').POWER_SERVICE)
            if not pm.isInteractive():
                current_activity.moveTaskToBack(True)
        except Exception as e:
            try:
                # API 20: pm.isScreenOn is depreciated
                pm = current_activity.getSystemService(
                    autoclass('android.content.Context').POWER_SERVICE)
                if not pm.isScreenOn():
                    current_activity.moveTaskToBack(True)
            except Exception as e:
                Logger.exception(traceback.format_exc())

        # print "on_pause"
        return True  # go into Pause mode

    def on_resume(self):
        # print "on_resume"
        Logger.error("on_resume")
        pass

    def check_update(self):
        """
        Check if new update is available
        """
        try:
            config = ConfigParser()
            config.read('/sdcard/.mobileinsight.ini')
            bcheck_update = config.get("mi_general", "bcheck_update")
            if bcheck_update == "1":
                import check_update
                check_update.check_update()
        except Exception as e:
            Logger.exception(traceback.format_exc())

    def privacy_check(self):
        """
        Check if new update is available
        """
        try:
            config = ConfigParser()
            config.read('/sdcard/.mobileinsight.ini')
            privacy_agreed = int(config.get("mi_general", "privacy"))
            if privacy_agreed == 0:
                import privacy_app
                privacy_app.PrivacyApp().run()
                # if privacy_app.disagree_privacy:
                #     self.stop()
        except Exception as e:
            Logger.exception(traceback.format_exc())

    def on_start(self):
        # android.stop_service() # Kill zombine service from previous app instances

        Config.set('kivy', 'exit_on_escape', 0)

        if not main_utils.is_rooted():
            err_str = "MobileInsight requires root privilege. Please root your device for correct functioning."
            Logger.error(err_str)
            self.home_screen.log_error(err_str)
        elif not main_utils.check_diag_mode():
            err_str = "The diagnostic mode is disabled. Please check your phone settings."
            Logger.error(err_str)
            self.home_screen.log_error(err_str)
            # content = ConfirmPopup(text=err_str)
            # content.bind(on_answer=self.__popup_dismiss)
            # self.popup = Popup(title='Diagnostic mode is not available',
            #             content=content,
            #             size_hint=(None, None),
            #             size=(1200, 400),
            #             auto_dismiss=False)
            # self.popup.open()
        else:
            self.privacy_check()
            self.check_update()

    def on_stop(self):
        Logger.error("on_stop")
        COORDINATOR.stop()
Exemple #15
0
class Set(Screen):
    theme_cls = ThemeManager()

    def printStorage_for_storage_mining(self, text):
        mining_storage = text
        print(mining_storage)
class YoutubeCounter(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Orange'

    def build(self):
        return Builder.load_file("gui.kv")
Exemple #17
0
class AppApp(App):
    """Point d'entrée de l'application.
    """
    title = "ReDoxLab"
    use_kivy_settings = False

    theme = 'default'

    theme_cls = ThemeManager()
    theme_cls.primary_palette = "BlueGray"
    theme_cls.accent_palette = "Gray"
    theme_cls.theme_style = "Dark"

    def build(self):
        Window.bind(on_keyboard=self.key_input)
        self.register_event_type('on_theme_colors')

        #Chargement des configuration
        config = self.config
        self.theme = config.get('Apparence', 'theme')
        self.theme_cls.theme_style, self.theme_cls.primary_palette,\
            self.theme_cls.accent_palette = config.get('Apparence', 'theme-colors') .split(', ')

        self.load_theme_kv("app-{}.kv")

        self.load_theme_kv("components/cox_popup-{}.kv")
        self.load_theme_kv("components/entrypopup-{}.kv")
        self.load_theme_kv("components/errorpopup-{}.kv")
        self.load_theme_kv("components/file_chooser-{}.kv")
        self.load_theme_kv("components/intervalbox-{}.kv")
        self.load_theme_kv("components/interval_popup-{}.kv")
        self.load_theme_kv("components/spinbox-{}.kv")

        self.settings_cls = Settings

        #print(self.theme_cls.primary_color)

        self.root = MainWindow()
        self.bind(on_theme_colors=self.root.on_theme_colors)

        if self.theme == 'material-design':
            self.dispatch('on_theme_colors',
                          config.get('Apparence', 'theme-colors'))

        return self.root

    def load_theme_kv(self, path):
        """
        path must be similar to "/optional/mywidget{}.kv" to be parsed by format.
        """
        try:
            Builder.load_file(path.format(self.theme))
        except FileNotFoundError as err:
            print("""Erreur lors de l'ouverture du fichier {} : {}
Chargement du fichier kv par défaut.""".format(path.format(self.theme), err))
            Builder.load_file(path.format("default"))

    def build_config(self, config):
        """
        Définie les valeurs par défaut pour les sections de configuration.
        """
        config.setdefaults('Apparence', {
            'theme': 'material-design',
        })
        config.setdefaults(
            'Apparence', {
                'theme-colors':
                '{}, {}, {}'.format(self.theme_cls.theme_style,
                                    self.theme_cls.primary_palette,
                                    self.theme_cls.accent_palette),
            })

    def build_settings(self, settings):
        """
        Ajoute notre propre section à l'objet de configuration par défaut.
        """
        settings.register_type('theme-picker', SettingThemePicker)
        settings.add_json_panel('Apparence', self.config, 'settings.json')

    def on_config_change(self, config, section, key, value):
        """
        Répond aux changements dans la configuration.
        """

        if section == "Apparence":
            if key == "theme":
                pass
            if key == "theme-colors":
                if self.theme == 'material-design':
                    self.dispatch('on_theme_colors', value)

    def on_theme_colors(self, *args):
        pass

    def close_settings(self, settings=None):
        """
        Appelé quand le panneau des paramètres est clos.
        """
        super(AppApp, self).close_settings(settings)

    def on_pause(self):
        return True

    def on_resume(self):
        return True

    def key_input(self, window, key, scancode, codepoint, modifier):
        #Gestion de la touche Esc/Echap et du bouton Back sur Android.
        if key == 27:

            if self.theme == "default":
                content = BoxLayout(orientation='vertical')
                content.add_widget(
                    Label(text="Voulez vous vraiment fermer l'application ?"))

                buttons = BoxLayout(orientation='horizontal')
                button_close = Button(text='Fermer')
                button_cancel = Button(text='Annuler')
                buttons.add_widget(button_close)
                buttons.add_widget(button_cancel)

                content.add_widget(buttons)
                popup = Popup(title="Fermer ?",
                              content=content,
                              auto_dismiss=True,
                              size_hint=(0.3, 0.2))

                #lie l'evènement "on_press" du buton à la fonction dismiss()
                button_cancel.bind(on_press=popup.dismiss)
                button_close.bind(on_press=popup.dismiss)
                button_close.bind(on_press=self.close)

                #ouvre le popup
                popup.open()
            elif self.theme == "material-design":
                from kivymd.dialog import MDDialog

                def callback(self, result):
                    if result == "Fermer":
                        self.close()
                    popup.dismiss()

                popup = MDDialog(
                    title="Fermer ?",
                    size_hint=(0.3, 0.2),
                    text_button_ok="Fermer",
                    text="Voulez vous vraiment fermer l'application ?",
                    text_button_cancel="Annuler",
                    events_callback=lambda *args: callback(self, args[0]))
                popup.open()
            return True
        else:  #la touche ne fait maintenant plus rien
            return False

    def close(self, *args, **kwargs):
        Window.close()
        App.get_running_app().stop()
Exemple #18
0
    class TabsApp(App):
        theme_cls = ThemeManager()

        def build(self):
            from kivy.core.window import Window
            Window.size = (540, 720)

            return Builder.load_string("""
#:import Toolbar kivymd.toolbar.Toolbar
#:import MDRaisedButton kivymd.button.MDRaisedButton


BoxLayout:
    orientation:'vertical'

    Toolbar:
        id: toolbar
        title: 'Page title'
        md_bg_color: app.theme_cls.primary_color
        left_action_items: [['menu', lambda x: '']]

    MDTabbedPanel:
        id: tab_mgr
        tab_display_mode:'icons'

        MDTab:
            name: 'music'
            text: "Music"
            icon: "playlist-play"
            MDLabel:
                font_style: 'Body1'
                theme_text_color: 'Primary'
                text: "Here is my music list :)"
                halign: 'center'

        MDTab:
            name: 'movies'
            text: 'Movies'
            icon: "movie"
            MDLabel:
                font_style: 'Body1'
                theme_text_color: 'Primary'
                text: "Show movies here :)"
                halign: 'center'

    MDBottomNavigation:

        MDBottomNavigationItem:
            name: 'movies'
            text: 'Movies'
            icon: "movie"
            MDLabel:
                font_style: 'Body1'
                theme_text_color: 'Primary'
                text: "Show movies here :)"
                halign: 'center'

        MDBottomNavigationItem:
            name: 'files1'
            text: "Files"
            icon: "file"
            MDLabel:
                font_style: 'Body1'
                theme_text_color: 'Primary'
                text: "all of the files"
                halign: 'center'

        MDBottomNavigationItem:
            name: 'files2'
            text: "Files"
            icon: "file"
            MDLabel:
                font_style: 'Body1'
                theme_text_color: 'Primary'
                text: "all of the files"
                halign: 'center'

        MDBottomNavigationItem:
            name: 'files3'
            text: "Files"
            MDLabel:
                font_style: 'Body1'
                theme_text_color: 'Primary'
                text: "all of the files"
                halign: 'center'
""")
Exemple #19
0
class Example(App):
    theme_cls = ThemeManager()
Exemple #20
0
class MainApp(App):
    theme_cls = ThemeManager()
    #Container()
    #create_table()
    #data_entry()
    find_data()
Exemple #21
0
    class AccordionApp(App):
        theme_cls = ThemeManager()

        def build(self):
            self.theme_cls.primary_palette = 'Indigo'
            return Builder.load_string('''
#:import MDLabel kivymd.label.MDLabel


BoxLayout:
    spacing: '64dp'

    MDAccordion:
        orientation: 'vertical'

        MDAccordionItem:
            title: 'Item 1'
            icon: 'home'
            MDAccordionSubItem:
                text: "Subitem 1"
            MDAccordionSubItem:
                text: "Subitem 2"
            MDAccordionSubItem:
                text: "Subitem 3"
        MDAccordionItem:
            title: 'Item 2'
            icon: 'earth'
            MDAccordionSubItem:
                text: "Subitem 4"
            MDAccordionSubItem:
                text: "Subitem 5"
            MDAccordionSubItem:
                text: "Subitem 6"
        MDAccordionItem:
            title: 'Item 3'
            MDAccordionSubItem:
                text: "Subitem 7"
            MDAccordionSubItem:
                text: "Subitem 8"
            MDAccordionSubItem:
                text: "Subitem 9"

    MDAccordion:
        orientation: 'horizontal'

        MDAccordionItem:
            title:'Item 1'
            icon: 'home'
            MDLabel:
                text:'Content 1'
                theme_text_color:'Primary'
        MDAccordionItem:
            title:'Item 2'
            MDLabel:
                text:'Content 2'
                theme_text_color:'Primary'
        MDAccordionItem:
            title:'Item 3'
            MDLabel:
                text:'Content 3'
                theme_text_color:'Primary'
''')
Exemple #22
0
class Chat(Widget):
    theme_cls = ThemeManager()
Exemple #23
0
class DatosApp(App):
    theme_cls = ThemeManager()
    #theme_cls.theme_style = 'Dark'
    theme_cls.primary_palette = "Green"
    theme_cls.secondary_palette = "Blue"
    nav_drawer = ObjectProperty()

    def build(self):
        self.main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        #~ main_widget.ids.text_field_error.bind(
        #~ on_text_validate=self.set_error_message,
        #~ on_focus=self.set_error_message)

        self.nav_drawer = PisoNavDrawer()
        #~ self.nav_drawer.add_widget(NavigationDrawerIconButton(text="seee"))
        self.iniciar("bottomsheet", "piso_1")
        return self.main_widget

    ########################################################################
    def iniciar(self, actual_screen, next_screen):
        #if next_screen == "info":
        #Clock.schedule_interval(self.update, 0.5)
        print "inicia!"
        try:
            self.client = InfluxDBClient('influxdb.linti.unlp.edu.ar', 8086,
                                         "lihuen", '***REMOVED***',
                                         'uso_racional')
            self.client.query(
                'SELECT mota_id FROM medicion LIMIT 1'
            )  #por ahora la unica forma de testear la conexion.

        except Exception as e:
            print str(e)
            print("Error al efectuar la conexion")
            #popup = Popup(title='Error al conectarse', content=Label(text="Error de conexión.\nVerifique su conexión a internet y sus credenciales de acceso.\n\n\nPara cerrar el cuadro de diálogo presione fuera de este."), size_hint=(.8, .6))
            #popup.open()
        else:
            #instancio piso y paso el client - falta ahcer una consulta para saber cuantos pisos hay
            pisos = self.client.query('SELECT * FROM piso')
            print pisos.get_points().next()
            print "----------------------aaaaaaaaaaaaaaaaaaaa-------------------------------------"
            #p_imgs = ["imagenes/plano-2piso.jpg","imagenes/primer_piso.jpg"]
            self.pisos = []
            #~ self.spinner = Spinner(text="1", size_hint= (.09,.05), pos_hint={'top':1,'left':.9})
            for pp in pisos:
                for p in pp:
                    print "*************************************"
                    print p
                    print "**********************pppppp*********"
                    #~ self.spinner.values.append(str(p))
                    sensores = self.client.query(
                        "SELECT * FROM mota WHERE piso_id ='" +
                        str(p["piso_id"]) + "'")
                    print sensores
                    print "+++++++++++++++++++++++++****++++++++++++++++++++++++++++++"
                    img = 'piso_' + str(p["piso_id"]) + '.png'
                    print img
                    if ((not os.path.exists(img))
                            and (not os.path.exists("imagenes/" + img))):
                        try:
                            urllib.urlretrieve(str(p['mapa']), img)
                        except Exception as e:
                            print "Error al descargar la imagen del piso " + img + "\n"
                            print e
                    #~ else:
                    print pisos
                    self.pisos.append(
                        Piso(p['piso_id'], sensores, img, self.client))
                    self.pisos[-1].agregar_motas()
                    p_nav = NavigationDrawerIconButton(
                        text=self.pisos[-1].getName())
                    p_nav.icon = "checkbox-blank-circle"
                    p_nav.bind(on_release=partial(self.cambiar_piso,
                                                  self.pisos[-1].getName()))
                    self.nav_drawer.add_widget(p_nav)
                    self.main_widget.ids["scr_mngr"].add_widget(self.pisos[-1])
            else:
                self.main_widget.ids["scr_mngr"].current = next_screen

    def cambiar_piso(self, name, evnt):
        self.main_widget.ids["scr_mngr"].current = name

    def on_pause(self):
        if platform == 'android':
            from android import AndroidService
            service = AndroidService('Datos Sensores', 'running')
            service.start('service started')
            self.service = service
        return True
        #~ #~
    def on_resume(self):
        self.service.stop()
        self.service = None
Exemple #24
0
class DWApp(App):
    theme_cls = ThemeManager(theme_style='Light')

    def build(self):
        return SM()
Exemple #25
0
class Program(App, _class.ShowPlugin, _class.ShowAbout, _class.ShowLicense):
    '''Функционал программы.'''

    settings_cls = customsettings.CustomSettings
    customsettings.TEXT_INPUT = data.string_lang_enter_value
    # nav_drawer = ObjectProperty()
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Green'

    def __init__(self, **kvargs):
        super(Program, self).__init__(**kvargs)
        Window.bind(on_keyboard=self.events_program)

        self.data = data
        self.window = Window
        self.open_exit_dialog = None
        self.load_all_kv_files('{}/libs/uix/kv'.format(self.directory))
        self.load_all_kv_files('{}/libs/uix/kv/activity'.format(
            self.directory))
        self.bottom_sheet_content = {
            'Add account':
            ['Settings', lambda x: None, 'data/images/settings.png']
        }

    def build_config(self, config):
        config.adddefaultsection('General')
        config.setdefault('General', 'language', 'Русский')
        config.setdefault('General', 'theme', 'default')

    def build_settings(self, settings):
        with open('{}/data/settings/general.json'.format(data.prog_path),
                  'r') as settings_json:
            settings.add_json_panel(
                data.string_lang_settings,
                self.config,
                data=settings_json.read().format(
                    language=data.string_lang_setting_language,
                    title=data.string_lang_setting_language_title,
                    desc=data.string_lang_setting_language_desc,
                    russian=data.string_lang_setting_language_russian,
                    english=data.string_lang_setting_language_english))

    def build(self):
        self.use_kivy_settings = False
        self.title = data.string_lang_title  # заголовок окна программы
        self.icon = 'data/images/logo.png'  # иконка окна программы

        self.config = ConfigParser()
        self.config.read('{}/program.ini'.format(data.prog_path))

        # Главный экран программы.
        # self.screen = StartScreen(events_callback=self.events_program)
        self.screen = StartScreen()
        self.screen_root_manager = self.screen.ids.root_manager
        # self.nav_drawer = NavDrawer(title=data.string_lang_menu)

        return self.screen

    def events_program(self, *args):
        '''Вызывается при выборе одного из пунктов меню программы.'''

        if len(args) == 2:  # нажата ссылка
            event = args[1]
        else:  # нажата кнопка программы
            try:
                _args = args[0]
                event = _args if isinstance(_args, str) else _args.id
            except AttributeError:  # нажата кнопка девайса
                event = args[1]

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

        if event == data.string_lang_settings:
            self.open_settings()
        elif event == data.string_lang_exit_key:
            self.exit_program()
        elif event == data.string_lang_license:
            self.show_license()
        elif event == data.string_lang_plugin:
            self.show_plugins()
        elif event in (1001, 27):
            self.back_screen(event)
        elif event in (282, 319):
            self.show_bottom_sheet()
        elif event == 'About':
            self.show_about()

        return True

    def back_screen(self, name_screen):
        '''Менеджер экранов.'''

        name_current_screen = self.screen_root_manager.current

        # Нажата BackKey.
        if name_screen in (1001, 27):
            if name_current_screen == 'Start screen':
                self.exit_program()
                return
            else:
                self.screen_root_manager.current = 'Start screen' \
                    if name_current_screen == 'Add account own provider' \
                    else self.screen_root_manager.previous()
                return

        self.screen_root_manager.current = 'Start screen' \
            if name_current_screen == 'Add account own provider' \
            else name_screen

    def exit_program(self, *args):
        def close_dialog():
            self.open_exit_dialog.dismiss()
            self.open_exit_dialog = None

        if self.open_exit_dialog:
            return

        self.open_exit_dialog = dialog(
            text=data.string_lang_exit,
            title=self.title,
            dismiss=False,
            buttons=[[data.string_lang_yes, lambda *x: sys.exit(0)],
                     [data.string_lang_no, lambda *x: close_dialog()]])

    def load_all_kv_files(self, directory_kv_files):
        for kv_file in os.listdir(directory_kv_files):
            if kv_file == 'bugreporter.kv' or os.path.isdir('{}/{}'.format(
                    directory_kv_files, kv_file)):
                continue
            Builder.load_file('{}/{}'.format(directory_kv_files, kv_file))

    def show_bottom_sheet(self):
        current_name_screen = self.screen_root_manager.current
        bottom_sheet = MDGridBottomSheet()

        if current_name_screen in self.bottom_sheet_content:
            name_item, callback, icon = \
                self.bottom_sheet_content[current_name_screen]
            bottom_sheet.add_item(name_item, callback, icon_src=icon)
            bottom_sheet.open()

    def delete_textfield_and_set_check_in_addaccountroot(self):
        add_account_own_provider = self.screen.ids.add_account_own_provider
        add_account_root = add_account_own_provider.ids.add_account_root
        add_account_root.ids.check.active = False
        add_account_root.ids.box.remove_widget(
            add_account_root.ids.confirm_password)

    def set_focus_on_textfield(self,
                               interval=0,
                               instance_textfield=None,
                               focus=True):
        if instance_textfield:
            instance_textfield.focus = focus

    def check_len_login_in_textfield(self, instance_textfield):
        if len(instance_textfield.text) > 20:
            instance_textfield.text = instance_textfield.text[:20]
        instance_textfield.message = '*****@*****.**' \
            if instance_textfield.text == '' \
            else '{}@conversations.im'.format(instance_textfield.text)

    def set_text_on_textfields(self, interval):
        add_account_root = self.screen.ids.add_account.ids.add_account_root
        field_username = add_account_root.ids.username
        field_password = add_account_root.ids.password
        field_confirm_password = add_account_root.ids.confirm_password

        field_username.text = self.screen.ids.create_account.ids.username.text.lower(
        )
        field_password.focus = True
        password = self.generate_password()
        field_password.text = password
        field_confirm_password.text = password

        Clock.schedule_once(
            lambda x: self.set_focus_on_textfield(
                instance_textfield=field_password, focus=False), .5)
        Clock.schedule_once(
            lambda x: self.set_focus_on_textfield(instance_textfield=
                                                  field_username), .5)

    def generate_password(self):
        for x in range(1):
            return ''.join([
                choice(string.ascii_lowercase + string.digits)
                for i in range(8)
            ])

    def on_config_change(self, config, section, key, value):
        '''Вызывается при выборе одного из пункта настроек программы.'''

        if key == 'language':
            if not os.path.exists('{}/data/language/{}.txt'.format(
                    self.directory, data.select_locale[value])):
                dialog(text=data.string_lang_not_locale.format(
                    data.select_locale[value]),
                       title=self.title)
                config.set(section, key, data.old_language)
                config.write()
                self.close_settings()

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

        return True

    def on_stop(self):
        '''Вызывается при выходе из прилодения.'''

        pass
Exemple #26
0
class BookStoreApp(App, MainScreenManagement, BookList, BookScreenManagement):
    theme_cls = ThemeManager()
    nav_drawer = ObjectProperty()

    def build(self):
        self.load_all_view_files(KV_DIR)

        self.main_screen = StartScreen()
        self.nav_drawer = Navigator()

        self.main_screen_manager = self.main_screen.ids.main_manager

        # setting up menu links

        self.screens = [
            SearchBookScreen(name="search_book"),
            AddBookScreen(name="add_book"),
            SearchAuthorScreen(name="search_author"),
            SearchTopicScreen(name="search_topic"),
            AboutScreen(name="about")
        ]

        btn = Button(text="suka")
        # self.screens[0].add_widget(btn)
        self.main_screen_manager.add_widget(self.screens[0])
        self.main_screen_manager.add_widget(self.screens[1])
        self.main_screen_manager.add_widget(self.screens[2])
        self.main_screen_manager.add_widget(self.screens[3])
        self.main_screen_manager.add_widget(self.screens[4])
        # self.book_screen_manager = self.root.ids.book_manager
        # self.book_screen_manager = self.main_screen.ids.book_manager

        return self.main_screen

    def load_all_view_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) as kv:
                    Builder.load_string(kv.read())

    def add_screens(self, name_screen, screen_manager, new_screen):
        screen = Screen(name=name_screen)
        screen.add_widget(new_screen)
        screen_manager.add_widget(screen)
        screen_manager.current = name_screen

    # Navigation menu links
    def show_about(self, *args):
        self.root.ids.main_manager.current = "about"
        return True

    def show_search_book(self, *args):
        self.root.ids.main_manager.current = "search_book"
        return True

    def show_add_book(self, *args):
        self.root.ids.main_manager.current = "add_book"
        return True

    def show_search_author(self, *args):
        self.root.ids.main_manager.current = "search_author"
        return True

    def show_search_topic(self, *args):
        self.root.ids.main_manager.current = "search_topic"
        return True
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)
Exemple #28
0
class ImageApp(App):
    theme_cls = ThemeManager()

    def build(self):
        img = ImageWidget()
        return img
Exemple #29
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.theme_cls = ThemeManager()
Exemple #30
0
class MainApp(App):

    theme_cls = ThemeManager()

    def build(self):
        self.icon = "docs/images/icon.png"