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 open_bottom_sheet(self, torrent): print(torrent) bs = MDListBottomSheet() bs.add_item(torrent["name"], lambda x: print('heyo')) bs.add_item("Download by magnet", lambda x: open_magnet(torrent["magnet"]), icon='download') bs.add_item("Download torrent file", lambda x: download_file(torrent["download_url"],torrent["name"]), icon='file') bs.open()
def editUser(self): # print("clicked!" + str(self)) # print(self.ids) bs = MDListBottomSheet() bs.add_item("Change user details of ", 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 nick_details(self, nick_list_item): self.app.connection.signedOn() nick_item_data = self.nick_data[nick_list_item.text] bs = MDListBottomSheet() bs.add_item("Whois ({})".format(nick_list_item.text), lambda x: x) bs.add_item( "{} ({}@{})".format(nick_item_data[7].split(' ')[1], nick_item_data[3], nick_item_data[2]), lambda x: x) bs.add_item( "{} is connected via {}".format(nick_list_item.text, nick_item_data[4]), lambda x: x) bs.open()
def show_example_bottom_sheet(self): global otrh_kost otrh_kost = self bs = MDListBottomSheet() i = 1 if RogueBotApp.RB_text == 'Вы не авторизированы.': bs.add_item('Авторизоваться', RogueBotApp.RB_Open_Settings) bs.open() return for all in RogueBotApp.RB_button: bs.add_item(all, eval('OTRH_RogueBot.otrh_' + str(i))) i += 1 bs.open()
def open_address_options(self): """ Loads the address options bottom sheet. """ bottom_sheet = MDListBottomSheet() bottom_sheet.add_item('Switch account', lambda x: self.load_switch_account(), icon='swap-horizontal') bottom_sheet.add_item('Show QR Code', lambda x: self.show_qr_code(), icon='information') bottom_sheet.add_item('Copy address', lambda x: self.copy_address_clipboard(), icon='content-copy') bottom_sheet.open()
def open_address_options(self): """ Loads the address options bottom sheet. """ bottom_sheet = MDListBottomSheet() bottom_sheet.add_item( 'Switch account', lambda x: self.load_switch_account(), icon='swap-horizontal') bottom_sheet.add_item( 'Change alias', lambda x: self.prompt_alias_dialog(), icon='information') bottom_sheet.add_item( 'Copy address', lambda x: self.copy_address_clipboard(), icon='content-copy') bottom_sheet.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_bottom(self): self.ids.spinner.active = True from iplugin import plugin print(self.title, 'getfoldr') print(CleanName(self.title), 'getfoldr') _plugin = plugin().getFolder(CleanName(self.title.replace( ' ', '+'))).replace('\\', '').replace('["', '').replace('"]', '') sv = ScrollView() bs = MDListBottomSheet() #sv.add_widget(bs) #json valider pas besoin de retest #main = re.findall('plugin": "(.+?)".+?{"title": "(.+?)", "url": "(.+?)", "qual": "(.+?)"}',str(_plugin)) #for sub in main: # text = ("%s - %s [%s]") % (sub[0], sub[1] ,sub[3]) # bs.add_item(text, lambda x, url=sub[2], title=sub[1]: self.plays(url=url, title=title)) #bs.open() for main in json.loads(_plugin): if main.get('source'): for sub in main.get('source'): text = ("%s - %s [%s]") % (main['plugin'], sub['title'], sub['qual']) bs.add_item(text, lambda x, url=sub['url'], title=sub['title']: self.plays(url=url, title=title)) else: text = ("%s - Aucune réponse") % (main['plugin']) bs.add_item(text, lambda x: x) bs.open() #loading stop en time mais a voir pour le mettre en vrais temp de chargement Clock.schedule_once(self.spinner_stop, 8)
class KitchenSink(App, Screens): theme_cls = ThemeManager() theme_cls.primary_palette = 'Blue' previous_date = ObjectProperty() title = "Kitchen Sink" theme_cls.primary_palette = 'Blue' # theme_cls.theme_style = 'Dark' def __init__(self, **kwargs): super(KitchenSink, self).__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 self.manager = 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.manager_open = False self.cards_created = False self.user_card = None self.bs_menu_1 = None self.bs_menu_2 = None self.tick = 0 self.create_stack_floating_buttons = False self.previous_text =\ "Welcome to the application [b][color={COLOR}]Kitchen Sink"\ "[/color][/b].\nTo see [b][color={COLOR}]KivyMD[/color][/b] "\ "examples, open the menu and select from the list the desired "\ "example\n\n"\ ""\ ""\ "Author - [b][color={COLOR}]Andrés Rodríguez[/color][/b]\n"\ "[u][b][color={COLOR}][email protected][/color]"\ "[/b][/u]\n\n"\ "Author this Fork - [b][color={COLOR}]Ivanov Yuri[/color][/b]\n"\ "[u][b][color={COLOR}][email protected][/color]"\ "[/b][u]".format(COLOR=get_hex_from_color( self.theme_cls.primary_color)) self.names_contacts = ('Alexandr Taylor', 'Yuri Ivanov', 'Robert Patric', 'Bob Marley', 'Magnus Carlsen', 'Jon Romero', 'Anna Bell', 'Maxim Kramerer', 'Sasha Gray', 'Vladimir Ivanenko') Window.bind(on_keyboard=self.events) crop_image( (Window.width, int(dp(Window.height * 35 // 100))), '{}/assets/guitar-1139397_1280.png'.format(self.directory), '{}/assets/guitar-1139397_1280_crop.png'.format(self.directory)) def crop_image_for_tile(self, instance, size, path_to_crop_image): 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.theme_picker import MDThemePicker self.md_theme_picker = MDThemePicker() self.md_theme_picker.open() def example_add_stack_floating_buttons(self): from kivymd.stackfloatingbuttons 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_accordion_list(self): from kivymd.accordionlistitem import MDAccordionListItem def callback(text): toast('{} to {}'.format(text, content.name_item)) content = ContentForAnimCard(callback=callback) for name_contact in self.names_contacts: self.accordion_list.ids.anim_list.add_widget( MDAccordionListItem(content=content, icon='assets/kivymd_logo.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.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.download_file.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.filemanager import MDFileManager from kivymd.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=(.8, .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): from kivymd.cards 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.')) instance_grid_card.add_widget( MDCardPost( source="./assets/kitten-1049129_1280.png", tile_text="Little Baby", tile_font_style="Headline", 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): def update_screen(interval): self.tick += 1 if self.tick > 2: instance.update = True self.tick = 0 self.update_spinner.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) # self.bottom_navigation_remove_mobile(self.main_widget) return self.main_widget def set_popup_screen(self, content_popup): popup_menu = ContentForAnimCard() popup_menu.add_widget(Widget(size_hint_y=None, height=dp(150))) popup_screen = self.popup_screen.ids.popup_screen popup_screen.screen = popup_menu popup_screen.background_color = [.3, .3, .3, 1] popup_screen.max_height = content_popup.ids.image.height + dp(5) 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_user_example_animation_card(self): from kivymd.useranimationcard import MDUserAnimationCard def main_back_callback(): toast('Close card') if not self.user_card: self.user_card = MDUserAnimationCard( user_name="Lion Lion", path_to_avatar="./assets/guitar-1139397_1280.png", callback=main_back_callback) self.user_card.box_content.add_widget(ContentForAnimCard()) self.user_card.open() def show_example_snackbar(self, snack_type): from kivymd.snackbars 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=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_input_dialog(self): def result(text_button, instance): toast(instance.text_field.text) if not self.input_dialog: from kivymd.dialog import MDInputDialog self.input_dialog = MDInputDialog(title='Title', hint_text='Hint text', size_hint=(.8, .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.dialog import MDDialog self.alert_dialog = MDDialog( title='Title', size_hint=(.8, .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.dialog import MDDialog self.ok_cancel_dialog = MDDialog( title='Title', size_hint=(.8, .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.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=(.8, .4), text_button_ok='Yes', events_callback=self.callback_for_menu_items) self.long_dialog.open() def get_time_picker_data(self, instance, time): self.pickers.ids.time_picker_label.text = str(time) self.previous_time = time def show_example_time_picker(self): from kivymd.time_picker import MDTimePicker time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time_picker_data) if self.pickers.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): self.previous_date = date_obj self.pickers.ids.date_picker_label.text = str(date_obj) def show_example_date_picker(self): from kivymd.date_picker import MDDatePicker if self.pickers.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): from kivymd.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): if not self.bs_menu_2: from kivymd.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_appbar(self): from kivymd.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): 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 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 add_icon_item(self, 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 }) def set_list_md_icons(self, text='', search=False): 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: self.add_icon_item(name_icon) else: self.add_icon_item(name_icon) def on_pause(self): return True def on_stop(self): pass def open_settings(self, *args): return False
def _open(self): bs = MDListBottomSheet() for val in self.values: bs.add_item(val, lambda x: self._update(x)) bs.open()
class Mergency(App, Designer): theme_cls = ThemeManager() theme_cls.accent_palette = 'Orange' previous_date = ObjectProperty() title = "Mergency" theme_cls.theme_style = 'Dark' 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 self.manager = None self.md_app_bar = None self.instance_menu_demo_apps = 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.manager_open = False self.cards_created = False self.user_card = None self.bs_menu_1 = None self.bs_menu_2 = None self.my_snackbar = None self._interval = 0 self.tick = 0 self.create_stack_floating_buttons = False Window.bind(on_keyboard=self.events) crop_image( (Window.width, int(dp(Window.height * 35 // 100))), '{}/assets/guitar-1139397_1280.png'.format(self.directory), '{}/assets/guitar-1139397_1280_crop.png'.format(self.directory)) # DB Data ======================================================= self.db = None self.host = StringProperty(None) self.user = StringProperty(None) self.password = StringProperty(None) self.service = StringProperty(None) self.port = StringProperty(None) # TABS Data ===================================================== self.accidents = None self.hospitals = None self.ambulances = None self.doctors = None self.patients = None 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.pickers import MDThemePicker self.md_theme_picker = MDThemePicker() self.md_theme_picker.open() def example_add_stack_floating_buttons(self): from kivymd.stackfloatingbuttons 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_accordion_list(self): from kivymd.accordionlistitem import MDAccordionListItem def callback(text): toast('{} to {}'.format(text, content.name_item)) content = ContentForAnimCard(callback=callback) for name_contact in self.names_contacts: self.accordion_list.ids.anim_list.add_widget( MDAccordionListItem(content=content, icon='assets/kivymd_logo.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.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.download_file.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.filemanager import MDFileManager from kivymd.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=(.8, .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.cards 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.')) instance_grid_card.add_widget( MDCardPost( source="./assets/kitten-1049129_1280.png", 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.update_spinner.ids.upd_lbl.text = "New string" Clock.unschedule(update_screen) Clock.schedule_interval(update_screen, 1) main_widget = None def set_popup_screen(self, content_popup): popup_menu = ContentForAnimCard() popup_menu.add_widget(Widget(size_hint_y=None, height=dp(150))) popup_screen = self.popup_screen.ids.popup_screen popup_screen.screen = popup_menu popup_screen.background_color = [.3, .3, .3, 1] popup_screen.max_height = content_popup.ids.image.height + dp(5) def show_user_example_animation_card(self): """Create and open instance MDUserAnimationCard for the screen UserCard.""" from kivymd.useranimationcard import MDUserAnimationCard def main_back_callback(): toast('Close card') if not self.user_card: self.user_card = MDUserAnimationCard( user_name="Lion Lion", path_to_avatar="./assets/guitar-1139397_1280.png", 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=.2) anim.start(self.snackbar.ids.button) Clock.unschedule(wait_interval) self._interval = 0 self.my_snackbar = None from kivymd.snackbars 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=.2) anim.bind(on_complete=lambda *args: Clock.schedule_interval( wait_interval, 0)) anim.start(self.snackbar.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.dialog import MDInputDialog self.input_dialog = MDInputDialog(title='Title', hint_text='Hint text', size_hint=(.8, .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.dialog import MDDialog self.alert_dialog = MDDialog( title='Title', size_hint=(.8, .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.dialog import MDDialog self.ok_cancel_dialog = MDDialog( title='Title', size_hint=(.8, .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.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=(.8, .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.pickers.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.pickers import MDTimePicker time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time_picker_date) if self.pickers.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.pickers.ids.date_picker_label.text = str(date_obj) def show_example_date_picker(self): """Show MDDatePicker from the screen Pickers.""" from kivymd.pickers import MDDatePicker if self.pickers.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.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.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.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 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_menu_for_demo_apps(self): if not len(self.menu_for_demo_apps): for name_item in self.demo_apps_list: self.menu_for_demo_apps.append({ 'viewclass': 'OneLineListItem', 'text': name_item, 'on_release': lambda x=name_item: self.show_demo_apps(x) }) def show_demo_apps(self, name_item): name_item = name_item.lower() { 'coffee menu': self.show_coffee_menu, 'shop window': self.show_shop_window, 'registration': self.show_registration_form_one, 'fitness club': self.show_fitness_club }[name_item]() self.main_widget.ids.scr_mngr.current = name_item self.instance_menu_demo_apps.dismiss() # CUSTOM ======================================================================== def button_connect(self, host, service, port, user, password): self.db = Database(host, service, port, user, password) self.db.connect() return def button_disconnect(self): if (self.db != None): self.db.disconnect() self.db = None else: pass return def dummy_push(self): if (self.db != None): self.db.init_tables(DB_SCHEMA) self.db.dummy_insert() self.db.dummy_select() else: pass return def dummy_pop(self): if (self.db != None): self.db.rollback_tables(DB_SCHEMA) else: pass return def remove_cards(self, tab): if (len(tab.children) != 0): tab.clear_widgets() else: pass return # IMPORTANT # Need to separate these methods into update and refresh for correct # content management, at this moment everytime a tab is accesed it # just adds again the content of the DB table over the old one! # FIX ASAP! def get_accidents(self, instance_grid_card): print( "ACCIDENTS --------------------------------------------------------------" ) """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.cards 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]) menu_items = [{ 'viewclass': 'MDMenuItem', 'text': 'Remove', 'callback': self.callback_for_menu_items } for _ in range(1)] # Implement a method to check empty tables and change above! if (self.db != None): try: self.accidents = self.db.get_info("Accident", "*") except Exception as ex: print(ex) return for _ in range(len(self.accidents)): instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, name_data= f"County: {self.accidents[_][1]}\nID: {self.accidents[_][0]}\nAdress: {self.accidents[_][2]}\nDetails: {self.accidents[_][3]}", tile_font_style='H4', path_to_avatar="assets/m_tab_accidents.png", card_size=(Window.width, Window.height - 480), text_post="", callback=callback)) else: pass # Implement to add here a Label to say that the DB table is empty return def get_hospitals(self, instance_grid_card): print( "HOSPITALS --------------------------------------------------------------" ) """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.cards 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]) menu_items = [{ 'viewclass': 'MDMenuItem', 'text': 'Remove', 'callback': self.callback_for_menu_items } for _ in range(1)] # Implement a method to check empty tables and change above! if (self.db != None): try: self.hospitals = self.db.get_info("Hospital", "*") except Exception as ex: print(ex) return for _ in range(len(self.hospitals)): instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, name_data= f"{self.hospitals[_][1]}\nID: {self.hospitals[_][0]}\nAdress: {self.hospitals[_][2]}\n", tile_font_style='H4', path_to_avatar="assets/m_tab_hospitals.png", card_size=(Window.width, Window.height - 480), text_post="", callback=callback)) else: pass # Implement to add here a Label to say that the DB table is empty return def get_ambulances(self, instance_grid_card): print( "AMBULANCES -------------------------------------------------------------" ) """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.cards 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]) menu_items = [{ 'viewclass': 'MDMenuItem', 'text': 'Remove', 'callback': self.callback_for_menu_items } for _ in range(1)] # Implement a method to check empty tables and change above! if (self.db != None): try: self.ambulances = self.db.get_info("Ambulance", "*") except Exception as ex: print(ex) return for _ in range(len(self.ambulances)): # 706F6F # FFAA00 if (self.ambulances[_][4] == 0): s = "assets/m_tab_ambulances_0.png" elif (self.ambulances[_][4] == 1): s = "assets/m_tab_ambulances_1.png" else: s = "assets/m_tab_ambulances_1.png" instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, name_data= f"{self.ambulances[_][2]}\nID: {self.ambulances[_][0]}", tile_font_style='H4', path_to_avatar=s, card_size=(Window.width, Window.height - 480), text_post= f"Producer: {self.ambulances[_][1]}\nCapacity: {self.ambulances[_][3]} persons", callback=callback)) else: pass # Implement to add here a Label to say that the DB table is empty return def get_doctors(self, instance_grid_card): print( "DOCTORS ----------------------------------------------------------------" ) """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.cards 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]) menu_items = [{ 'viewclass': 'MDMenuItem', 'text': 'Remove', 'callback': self.callback_for_menu_items } for _ in range(1)] # Implement a method to check empty tables and change above! if (self.db != None): try: self.doctors = self.db.get_info("Doctor", "*") except Exception as ex: print(ex) return for _ in range(len(self.doctors)): if (self.doctors[_][3] == "M"): s = "assets/m_tab_doctors_m.png" elif (self.doctors[_][3] == "F"): s = "assets/m_tab_doctors_f.png" else: s = "assets/m_tab_doctors_m.png" instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, name_data= f"{self.doctors[_][2]} {self.doctors[_][1]} ({self.doctors[_][3]})\nID: {self.doctors[_][0]}", tile_font_style='H4', path_to_avatar=s, card_size=(Window.width, Window.height - 480), text_post=f"Birthday: {self.doctors[_][4]}", callback=callback)) else: pass # Implement to add here a Label to say that the DB table is empty return def get_patients(self, instance_grid_card): print( "PATIENTS ---------------------------------------------------------------" ) """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.cards 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]) menu_items = [{ 'viewclass': 'MDMenuItem', 'text': 'Remove', 'callback': self.callback_for_menu_items } for _ in range(1)] # Implement a method to check empty tables and change above! if (self.db != None): try: self.patients = self.db.get_info("Patient", "*") except Exception as ex: print(ex) return for _ in range(len(self.patients)): if (self.patients[_][3] == "M"): s = "assets/m_tab_pacients_m.png" elif (self.patients[_][3] == "F"): s = "assets/m_tab_pacients_f.png" else: s = "assets/m_tab_pacients_m.png" instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, name_data= f"{self.patients[_][2]} {self.patients[_][1]} ({self.patients[_][3]})\nID: {self.patients[_][0]}", tile_font_style='H4', path_to_avatar=s, card_size=(Window.width, Window.height - 480), text_post= f"Birthday: {self.patients[_][4]}\nBlood Type: {self.patients[_][5]}\nRH: {self.patients[_][6]}", callback=callback)) else: pass # Implement to add here a Label to say that the DB table is empty return # CUSTOM ======================================================================== def build(self): self.main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), "./Mergency.kv")) return self.main_widget def on_pause(self): return True def on_stop(self): pass def open_settings(self, *args): return False
class KitchenSink(App, Screens): theme_cls = ThemeManager() theme_cls.primary_palette = "BlueGray" theme_cls.accent_palette = "Gray" previous_date = ObjectProperty() title = "Kitchen Sink" theme_cls.theme_style = "Dark" 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 self.manager = None self.md_app_bar = None self.instance_menu_demo_apps = 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.manager_open = False self.cards_created = False self.user_card = None self.bs_menu_1 = None self.bs_menu_2 = None self.my_snackbar = None self._interval = 0 self.tick = 0 self.x = 0 self.y = 25 self.create_stack_floating_buttons = False 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" f"Author this Fork - [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]") 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.menu_for_demo_apps = [] 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"{self.directory}/assets/guitar-1139397_1280.png", f"{self.directory}/assets/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.pickers import MDThemePicker self.md_theme_picker = MDThemePicker() self.md_theme_picker.open() def example_add_stack_floating_buttons(self): from kivymd.stackfloatingbuttons 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_accordion_list(self): from kivymd.accordionlistitem import MDAccordionListItem def callback(text): toast(f"{text} to {content.name_item}") content = ContentForAnimCard(callback=callback) for name_contact in self.names_contacts: self.data["Accordion List"]["object"].ids.anim_list.add_widget( MDAccordionListItem( 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.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.filemanager import MDFileManager from kivymd.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.cards 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.", )) instance_grid_card.add_widget( MDCardPost( source="./assets/kitten-1049129_1280.png", 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 set_popup_screen(self, content_popup): popup_menu = ContentForAnimCard() popup_menu.add_widget(Widget(size_hint_y=None, height=dp(150))) popup_screen = self.data["Popup Screen"]["object"].ids.popup_screen popup_screen.screen = popup_menu popup_screen.background_color = [0.3, 0.3, 0.3, 1] popup_screen.max_height = content_popup.ids.image.height + dp(5) def show_user_example_animation_card(self): """Create and open instance MDUserAnimationCard for the screen UserCard.""" from kivymd.useranimationcard import MDUserAnimationCard def main_back_callback(): toast("Close card") if not self.user_card: self.user_card = MDUserAnimationCard( user_name="Lion Lion", path_to_avatar="./assets/guitar-1139397_1280.png", 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.snackbars 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.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.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.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.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.pickers 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.pickers 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.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.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.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_menu_for_demo_apps(self): if not len(self.menu_for_demo_apps): for name_item in self.demo_apps_list: self.menu_for_demo_apps.append({ "viewclass": "OneLineListItem", "text": name_item, "on_release": lambda x=name_item: self.show_demo_apps(x), }) 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_stop(self): pass def open_settings(self, *args): return False
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="md-cast") bs.add_item("Here's another!", lambda x: x, icon="md-nfc") bs.open()
class KivyEmu(App): theme_cls = ThemeManager() theme_cls.primary_palette = 'Indigo' theme_cls.accent_palette = 'Indigo' theme_cls.theme_style = 'Dark' Window.size = (300, 650) filename = None class_name = None selection = ListProperty([]) bs_menu_1 = None # reloader = ReloaderApp() AUTORELOADER_PATHS = [ (".", { "recursive": True }), ] AUTORELOADER_IGNORE_PATTERNS = ["*.pyc", "*__pycache__*"] KV_FILES = [] CLASSES = {} def get_root(self): """ Return a root widget, that will contains your application. It should not be your application widget itself, as it may be destroyed and recreated from scratch when reloading. By default, it returns a RelativeLayout, but it could be a Viewport. """ return Factory.RelativeLayout() def build_app(self, first=False): """Must return your application widget. If `first` is set, it means that will be your first time ever that the application is built. Act according to it. """ raise NotImplemented() def unload_app_dependencies(self): """ Called when all the application dependencies must be unloaded. Usually happen before a reload """ for path in self.KV_FILES: path = realpath(path) Builder.unload_file(path) for name, module in self.CLASSES.items(): Factory.unregister(name) def load_app_dependencies(self): """ Load all the application dependencies. This is called before rebuild. """ for path in self.KV_FILES: path = realpath(path) Builder.load_file(path) for name, module in self.CLASSES.items(): Factory.register(name, module=module) def rebuild(self, *largs, **kwargs): print("rebuildig application") self.emulate_file(self.filename) print("done reloading") # Logger.debug("{}: Rebuild the application".format(self.appname)) # first = kwargs.get("first", False) # try: # if not first: # self.unload_app_dependencies() # self.load_app_dependencies() # self.set_widget(None) # # self.start_emulation() # except Exception as e: # pass # self.approot = self.build_app() # self.root.ids.emulator_screen = # self.set_widget(self.approot) # self.apply_state(self.state) # except Exception as e: # import traceback # Logger.exception("{}: Error when building app".format(self.appname)) # self.set_error(repr(e), traceback.format_exc()) # if not self.DEBUG and self.RAISE_ERROR: # raise @mainthread def set_error(self, exc, tb=None): print(tb) from kivy.core.window import Window lbl = Factory.Label(text_size=(Window.width - 100, None), text="{}\n\n{}".format(exc, tb or "")) self.set_widget(lbl) def bind_key(self, key, callback): """ Bind a key (keycode) to a callback (cannot be unbind) """ from kivy.core.window import Window def _on_keyboard(window, keycode, *largs): if key == keycode: return callback() Window.bind(on_keyboard=_on_keyboard) @property def appname(self): """ Return the name of the application class """ return self.__class__.__name__ def enable_autoreload(self): """ Enable autoreload manually. It is activated automatically if "DEBUG" exists in environ. It requires the `watchdog` module. """ try: from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler except ImportError: Logger.warn("{}: Autoreloader is missing watchdog".format( self.appname)) return # Logger.info(" Autoreloader activated") print("Autoreload activated") rootpath = self.get_root_path() # print("this is the root path",rootpath) self.w_handler = handler = FileSystemEventHandler() handler.dispatch = self._reload_from_watchdog self._observer = observer = Observer() for path in self.AUTORELOADER_PATHS: # print(path,"paths dey") options = {"recursive": True} if isinstance(path, (tuple, list)): # print("iii") path, options = path observer.schedule(handler, join(rootpath, path), **options) observer.start() @mainthread def _reload_from_watchdog(self, event): from watchdog.events import FileModifiedEvent if not isinstance(event, FileModifiedEvent): return for pat in self.AUTORELOADER_IGNORE_PATTERNS: if fnmatch(event.src_path, pat): return if event.src_path.endswith(".py"): # source changed, reload it try: Builder.unload_file(event.src_path) self._reload_py(event.src_path) except Exception as e: import traceback self.set_error(repr(e), traceback.format_exc()) return if event.src_path.endswith(".kv"): origin = str(event.src_path).split('.') main_path = str(event.src_path).split('\\')[:-1] main_path = "\\".join(main_path) print(main_path) if 'main.py' in os.listdir(main_path): new_path = os.path.join(main_path, 'main.py') try: Builder.unload_file(new_path) self._reload_py(new_path) except Exception as e: import traceback self.set_error(repr(e), traceback.format_exc()) return print("reload cause of", event) print(event.src_path, "this is the file that caused the reload") print(self.filename, "this is the original filename") Clock.unschedule(self.rebuild) Clock.schedule_once(self.rebuild, 0.1) def _reload_py(self, filename): # we don't have dependency graph yet, so if the module actually exists # reload it. filename = realpath(filename) print("filename from realpath") # check if it's our own application file try: mod = sys.modules[self.__class__.__module__] mod_filename = realpath(mod.__file__) except Exception as e: mod_filename = None # detect if it's the application class // main if mod_filename == filename: return self._restart_app(mod) module = self._filename_to_module(filename) if module in sys.modules: Logger.debug("{}: Module exist, reload it".format(self.appname)) Factory.unregister_from_filename(filename) self._unregister_factory_from_module(module) reload(sys.modules[module]) def _unregister_factory_from_module(self, module): # check module directly to_remove = [ x for x in Factory.classes if Factory.classes[x]["module"] == module ] # check class name for x in Factory.classes: cls = Factory.classes[x]["cls"] if not cls: continue if getattr(cls, "__module__", None) == module: to_remove.append(x) for name in set(to_remove): del Factory.classes[name] def _filename_to_module(self, filename): orig_filename = filename rootpath = self.get_root_path() if filename.startswith(rootpath): filename = filename[len(rootpath):] if filename.startswith("/"): filename = filename[1:] module = filename[:-3].replace("/", ".") print("translated to", orig_filename, module) # Logger.debug("{}: Translated {} to {}".format(self.appname, orig_filename, module)) return module def _restart_app(self, mod): _has_execv = sys.platform != 'win32' cmd = [sys.executable] + original_argv if not _has_execv: import subprocess subprocess.Popen(cmd) sys.exit(0) else: try: os.execv(sys.executable, cmd) except OSError: os.spawnv(os.P_NOWAIT, sys.executable, cmd) os._exit(0) def prepare_foreground_lock(self): """ Try forcing app to front permanently to avoid windows pop ups and notifications etc.app Requires fake fullscreen and borderless. .. note:: This function is called automatically if `FOREGROUND_LOCK` is set """ try: import ctypes LSFW_LOCK = 1 ctypes.windll.user32.LockSetForegroundWindow(LSFW_LOCK) Logger.info("App: Foreground lock activated") except Exception: Logger.warn("App: No foreground lock available") def set_widget(self, wid): """ Clear the root container, and set the new approot widget to `wid` """ self.root.clear_widgets() self.approot = wid if wid is None: return self.root.add_widget(self.approot) try: wid.do_layout() except Exception: pass def get_root_path(self): """ Return the root file path """ return realpath(os.getcwd()) # State management def apply_state(self, state): """Whatever the current state is, reapply the current state """ pass # Idle management leave def install_idle(self, timeout=60): """ Install the idle detector. Default timeout is 60s. Once installed, it will check every second if the idle timer expired. The timer can be rearm using :func:`rearm_idle`. """ if monotonic is None: Logger.exception( "{}: Cannot use idle detector, monotonic is missing".format( self.appname)) self.idle_timer = None self.idle_timeout = timeout Clock.schedule_interval(self._check_idle, 1) self.root.bind(on_touch_down=self.rearm_idle, on_touch_up=self.rearm_idle) def _check_idle(self, *largs): if not hasattr(self, "idle_timer"): return if self.idle_timer is None: return if monotonic() - self.idle_timer > self.idle_timeout: self.idle_timer = None self.dispatch("on_idle") def rearm_idle(self, *largs): """ Rearm the idle timer """ if not hasattr(self, "idle_timer"): return if self.idle_timer is None: self.dispatch("on_wakeup") self.idle_timer = monotonic() def on_idle(self, *largs): """ Event fired when the application enter the idle mode """ pass def on_wakeup(self, *largs): """ Event fired when the application leaves idle mode """ pass # internals def patch_builder(self): Builder.orig_load_string = Builder.load_string Builder.load_string = self._builder_load_string def _builder_load_string(self, string, **kwargs): if "filename" not in kwargs: from inspect import getframeinfo, stack caller = getframeinfo(stack()[1][0]) kwargs["filename"] = caller.filename return Builder.orig_load_string(string, **kwargs) # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def watchdog_reloader(self, args): print("reloading begins ") # self.AUTORELOADER_PATHS = self.AUTORELOADER_PATHS self.enable_autoreload() self.patch_builder() def choose(self): filechooser.open_file(on_selection=self.handle_selection) def handle_selection(self, selection): self.selection = selection def on_selection(self, *a, **k): self.clear() def clear(self): try: print("clearing screen") self.root.ids.emulator_screen.clear_widgets() Window.borderless = True Clock.schedule_once(self.watchdog_reloader, 2) self.filename = str(self.selection[0]) base = "\\".join(self.filename.split("\\")[:-1]) print(base) self.AUTORELOADER_PATHS.clear() self.AUTORELOADER_PATHS.append((base, {"recursive": True})) history = JsonStore(history_path) if history.exists(self.filename): print("file already exists") else: print('creating a new file with json store') history.put(self.filename, file_name=self.filename) self.emulate_file(self.selection[0]) print(self.AUTORELOADER_PATHS) except: pass def build(self): return EmuInterface() def emulate_file(self, filename, threaded=False): root = None if not os.path.exists(filename): return dirname = os.path.dirname(filename) sys.path.append(dirname) os.chdir(dirname) resource_add_path(dirname) # self.root.ids.emulator_screen.clear_widgets() if threaded: Thread(target=partial( self.start_emulation, filename, threaded=threaded)).start() else: self.start_emulation(filename, threaded=threaded) def start_emulation(self, filename, threaded=False): print("___________________________________") print("Starting thread") root = None # print(os.path.splitext(filename)) if os.path.splitext( filename)[1] == '.kv': # load the kivy file directly try: # cahching error with kivy files Builder.unload_file(filename) # print("unloaded the kv") root = Builder.load_file(filename) except: traceback.print_exc() print("You kivy file has a problem") elif os.path.splitext(filename)[1] == '.py': print("its a py") self.load_defualt_kv(filename) try: # cahching error with python files root = self.load_py_file(filename) except: traceback.print_exc() print("You python file has a problem") if root: print("this is the root", root) if threaded: self.emulation_done(root, filename) else: print("not threaded") self.root.ids.emulator_screen.clear_widgets() self.root.ids.emulator_screen.add_widget(root) dirname = os.path.dirname(filename) sys.path.pop() resource_remove_path(dirname) @mainthread def emulation_done(self, root, filename): if root: self.root.ids.emulator_screen.add_widget(root) def load_defualt_kv(self, filename): app_cls_name = self.get_app_cls_name(filename) self.class_name = app_cls_name if app_cls_name is None: return kv_name = app_cls_name.lower() if app_cls_name.endswith('App'): kv_name = app_cls_name[:len(app_cls_name) - 3].lower() if app_cls_name: file_dir = os.path.dirname(filename) kv_filename = os.path.join(file_dir, kv_name + '.kv') print(kv_filename) if os.path.exists(kv_filename): try: # cahching error with kivy files Builder.unload_file(kv_filename) print("unloaded the kv file ") # self.root.ids.emulator_screen.clear_widgets() print("clearing the emulator screen here") # self.root.ids.emulator_screen.clear_widgets() root = Builder.load_file(kv_filename) except: traceback.print_exc() print("You kivy file has a problem") def get_app_cls_name(self, filename): with open(filename) as fn: text = fn.read() lines = text.splitlines() app_cls = self.get_import_as('from kivy.app import App', lines) def check_app_cls(line): line = line.strip() return line.startswith('class') and line.endswith( '(%s):' % app_cls) found = list(filter(check_app_cls, lines)) if found: line = found[0] cls_name = line.split('(')[0].split(' ')[1] return cls_name def get_root_from_runTouch(self, filename): with open(filename) as fn: text = fn.read() lines = text.splitlines() run_touch = self.get_import_as('from kivy.base import runTouchApp', lines) def check_run_touch(line): line = line.strip() return line.startswith('%s(' % run_touch) found = list(filter(check_run_touch, lines)) if found: line = found[0] root_name = line.strip().split('(')[1].split(')')[0] root_file = self.import_from_dir(filename) root = getattr(reload(root_file), root_name) return root def load_py_file(self, filename): app_cls_name = self.get_app_cls_name(filename) if app_cls_name: root_file = self.import_from_dir(filename) app_cls = getattr(reload(root_file), app_cls_name) root = app_cls().build() return root run_root = self.get_root_from_runTouch(filename) if run_root: return run_root def import_from_dir(self, filename): ''' force python to import this file from the project_ dir''' dirname, file = os.path.split(filename) sys.path = [dirname] + sys.path import_word = os.path.splitext(file)[0] imported = __import__(import_word) return imported def get_import_as(self, start, lines): line = list(filter(lambda line: line.strip().startswith(start), lines)) if line: words = line[0].split(' ') import_word = words[len(words) - 1] return import_word else: return def callback_for_menu_items(self, *args): toast(args[0]) def show_example_bottom_sheet(self): from kivymd.bottomsheet import MDListBottomSheet if not self.bs_menu_1: self.bs_menu_1 = MDListBottomSheet() self.bs_menu_1.add_item("Open File", lambda x: self.choose(), icon='file') self.bs_menu_1.add_item("Open History Tab", lambda x: self.history_screen(), icon='history') self.bs_menu_1.add_item("Close Emulator", lambda x: self.stop(), icon='window-close') self.bs_menu_1.open() def history_screen(self): print(self.filename) self.root.ids.emulator_screen.clear_widgets() self.root.ids.history_screen.clear_widgets() self.root.ids.screen_manager.current = "history_screen"
class MainScreen(Screen): selected_week = NumericProperty(10) title = StringProperty() week = [ '所有课程', '第1周', '第2周', '第3周', '第4周', '第5周', '第6周', '第7周', '第8周', '第9周', '第10周', '第11周', '第12周', '第13周', '第14周', '第15周', '第16周', '第17周', '第18周', '第19周', '第20周', '第21周', '第22周' ] course_menu_items = [{ "viewclass": "DotsMenuButton", "name": "UpdateCourse", "text": "更新课表" }, { 'viewclass': 'DotsMenuButton', "name": "FontSize", 'text': '字体大小' }, { 'viewclass': 'DotsMenuButton', "name": "WeekendCourse", 'text': '周末课程' }, { 'viewclass': 'DotsMenuButton', "name": "DesktopWidget", 'text': '桌面组件' }, { 'viewclass': 'DotsMenuButton', "name": "BackgroundPicture", 'text': '背景图片' }, { 'viewclass': 'DotsMenuButton', "name": "BackgroundTransparent", 'text': '背景透明度' }] community_menu_items = [{ "viewclass": "DotsMenuButton", "name": "MyConfe", "text": "我的表白" }, { 'viewclass': 'DotsMenuButton', "name": "MyComment", 'text': '我的评论' }, { 'viewclass': 'DotsMenuButton', "name": "Refresh", 'text': '刷新' }] laf_menu_items = [{ "viewclass": "DotsMenuButton", "name": "MyAnnou", "text": "我发布的" }, { 'viewclass': 'DotsMenuButton', "name": "ConnectOwner", 'text': '联系失主' }] score_menu_items = [ { "viewclass": "DotsMenuButton", "name": "RefreshScore", "text": "更新成绩" } # {'viewclass': 'DotsMenuButton', # "name": "StatisticsInfo", # 'text': '统计信息'}, # {'viewclass': 'DotsMenuButton', # "name": "Calc", # 'text': '计算器'}, ] Builder.load_string(main_widget_kv) def on_enter(self): Clock.schedule_once(lambda x: self.load_course(), 2) def on_pause(self): return True def on_stop(self): pass 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 load_course(self): ''' scheduleList = {'scheduleList': []} courseList = {'courseList': {}} for schedule_item in a['result']["scheduleList"]: scheduleList["scheduleList"].append({'lessonId': schedule_item['lessonId'],'date': schedule_item['date'], 'room': schedule_item['room']['nameZh'], 'campus': schedule_item['room']['building']['campus']['nameZh'], 'weekday': schedule_item['weekday'], 'startTime': schedule_item['startTime'], 'endTime': schedule_item['endTime'], 'personName': schedule_item['personName'], 'weekIndex': schedule_item['weekIndex']}) for course_item in a['result']['lessonList']: courseList['courseList'][course_item['id']] = course_item['courseName'] scheduleList.update(courseList) with open('data.json', 'w',encoding='utf-8') as f: json.dump(scheduleList, f, ensure_ascii=False) ''' for weekday in range(1, 8): self.ids['weekday_' + str(weekday)].clear_widgets() course_data = get_json('course') current_week_course = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []} if self.selected_week == 0: print("allData") else: for item in course_data['scheduleList']: # courses of this week if item['weekIndex'] == self.selected_week: current_week_course[item['weekday']].append(item) for item in current_week_course: # for each day print(current_week_course[item]) weekday_status = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # the status of each time if current_week_course[item]: # if there is any course for course in current_week_course[item]: # for each course last_time = int( round((course['endTime'] - course['startTime'] - 40 * (int(course['endTime'] / 100) - int(course['startTime'] / 100))) / 60)) print(last_time) temp_flag = [ 810, 910, 1020, 1120, 1400, 1500, 1600, 1700, 1900, 2000, 2100 ].index(course['startTime']) print(temp_flag, last_time) weekday_status[temp_flag] = course['lessonId'] for i in range(1, last_time): print(i) weekday_status[temp_flag + i] = course['lessonId'] print(weekday_status) if not weekday_status[0]: # 8 o'clock - 9 o'clock self.ids['weekday_' + str(item)].add_widget( MDScreenWidthFlatButton( text="", height=self.ids.weekdays.height / 12)) else: self.ids['weekday_' + str(item)].add_widget( MDScreenWidthFlatButton( text=str(weekday_status[0]), height=self.ids.weekdays.height / 12 * weekday_status.count(weekday_status[0]))) for status in range(1, 11): if not weekday_status[status]: # 10 o'clock - 11 o'clock self.ids['weekday_' + str(item)].add_widget( MDScreenWidthFlatButton( text="", height=self.ids.weekdays.height / 12)) else: if weekday_status[status] == weekday_status[status - 1]: pass else: self.ids['weekday_' + str(item)].add_widget( MDScreenWidthFlatButton( text=str(weekday_status[status]), height=self.ids.weekdays.height / 12 * weekday_status.count( weekday_status[status]))) else: for i in range(0, 11): self.ids['weekday_' + str(item)].add_widget( MDScreenWidthFlatButton( text="", height=self.ids.weekdays.height / 12)) def select_menu_item(self, name): if name == "UpdateCourse": self.update_course() elif name == "FontSize": print("FontSize") self.show_sliderbar(text="字体大小") # elif name == "WeekendCourse": # print("WeekendCourse") # elif name == "DesktopWidget": # print("DesktopWidget") elif name == "BackgroundPicture": print("BackgroundPicture") elif name == "BackgroundTransparent": print("BackgroundTransparent") self.show_sliderbar(text="背景色透明度") elif name == "RefreshScore": print("RefreshScore") elif name == "Refresh": print("Refresh") elif name == "ConnectOwner": print("ConnectOwner") def select_week(self, week): self.selected_week = week self.bs.dismiss() self.load_course() def show_week_select(self): self.bs = MDListBottomSheet() self.bs.add_item("所有课程", lambda x: self.select_week(0)) self.bs.add_item("第1周", lambda x: self.select_week(1)) self.bs.add_item("第2周", lambda x: self.select_week(2)) self.bs.add_item("第3周", lambda x: self.select_week(3)) self.bs.add_item("第4周", lambda x: self.select_week(4)) self.bs.add_item("第5周", lambda x: self.select_week(5)) self.bs.add_item("第6周", lambda x: self.select_week(6)) self.bs.add_item("第7周", lambda x: self.select_week(7)) self.bs.add_item("第8周", lambda x: self.select_week(8)) self.bs.add_item("第9周", lambda x: self.select_week(9)) self.bs.add_item("第10周", lambda x: self.select_week(10)) self.bs.add_item("第11周", lambda x: self.select_week(11)) self.bs.add_item("第12周", lambda x: self.select_week(12)) self.bs.add_item("第13周", lambda x: self.select_week(13)) self.bs.add_item("第14周", lambda x: self.select_week(15)) self.bs.add_item("第15周", lambda x: self.select_week(14)) self.bs.add_item("第16周", lambda x: self.select_week(16)) self.bs.add_item("第17周", lambda x: self.select_week(17)) self.bs.add_item("第18周", lambda x: self.select_week(18)) self.bs.add_item("第19周", lambda x: self.select_week(19)) self.bs.add_item("第20周", lambda x: self.select_week(20)) self.bs.add_item("第21周", lambda x: self.select_week(21)) self.bs.add_item("第22周", lambda x: self.select_week(22)) self.bs.open() def update_course(self): content = MDLabel(font_style='Body1', theme_text_color='Hint', text="更新课表将导致自定义课程丢失,是否继续", size_hint_y=None, valign='top') content.bind(texture_size=content.setter('size')) self.dialog = MDDialog(title="更新课表", content=content, size_hint=(.8, None), height=dp(160), 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 show_sliderbar(self, text): slider = MDSlider(id="slider", min=0, max=100, value=1) bs = MDBottomSheet() txt = NavigationDrawerSubheader(text=text) l = TwoLineListItem() bs.add_widget(txt) bs.add_widget(slider) bs.add_widget(l) bs.open()