class HomeScreen(MDScreen): def __init__(self, **kwargs): super().__init__(**kwargs) items = [ "New group", "New broadcasts", "WhatsApp Web", "Starred messages", "Payments", "Settings", ] menu_items = [{ "text": item, "viewclass": "OneLineListItem", "height": dp(54), "divider": None, "on_release": self.menu_callback if item == "Settings" else lambda *args: None, } for item in items] self.menu = MDDropdownMenu( items=menu_items, width_mult=3, radius=[ dp(2), ], ) def open_menu(self, button): self.menu.caller = button self.menu.open() def menu_callback(self): self.manager.set_screen("settings") self.menu.dismiss() def on_tab_switch(self, *args): if args[3] == "[b]CHATS[/b]": self.ids.float_btn.icon = "android-messages" elif args[3] == "[b]STATUS[/b]": self.ids.float_btn.icon = "camera" elif args[3] == "[b]CALLS[/b]": self.ids.float_btn.icon = "phone-plus" self.toggle_pencil_btn(args[3]) def toggle_pencil_btn(self, current_tab): if current_tab == "[b]STATUS[/b]": anim = Animation(d=0.1, y=self.ids.float_btn.y + (self.ids.float_btn.height + dp(10))) self.ids.pencil_btn.disabled = False else: anim = Animation(d=0.1, y=self.ids.float_btn.y) self.ids.pencil_btn.disabled = True anim.start(self.ids.pencil_btn)
class Ingresos(Screen): def __init__(self, **kwargs): super(Ingresos, self).__init__() #variables globales input_patente = ObjectProperty() def Agrega_Movimientos(self): Fun_Ingresos.Agrega_Movimientos_patente(self) def menu_p(self): menu_items = [{ "text": "Ingreso Movimientos" }, { "text": "Consulta de Movimientos" }, { "text": "Salir" }] self.menu = MDDropdownMenu(caller=self.ids.button, items=menu_items, width_mult=5, callback=self.menu_callback) self.menu.open() def menu_callback(self, instance): opcion = instance if opcion.text == "Consulta de Movimientos": self.manager.current = 'Consulta' #self.menu.close() else: print("Opcion seleccionada es :", opcion.text)
class LongPressButton(MDRaisedButton, TouchBehavior): def __init__(self, **kwargs): super(LongPressButton, self).__init__(**kwargs) self.long_pressed = False def on_kv_post(self, base_widget): self.dropdown = MDDropdownMenu( caller=self, items=[{"text": "+24"}, {"text": "-24"}, {"text": "+1"}, {"text": "-1"}], width_mult=4, callback=self.update_amount ) def update_amount(self, instance): amount = int(instance.text) index = int(self.name[-1]) - 1 MDApp.get_running_app().root.ids.screen_manager.get_screen("turflist").update(index,amount) def on_long_touch(self, *args): self.long_pressed = True self.dropdown.open() def on_release(self): if self.long_pressed: self.long_pressed = False return index = int(self.name[-1]) - 1 MDApp.get_running_app().root.ids.screen_manager.get_screen("turflist").update(index, -1)
class Test(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.screen = MDScreen() # self.cust = MDRaisedButton(text="I AM A BUTTON") self.cust = MDRaisedButton(text="I AM A BUTTON", on_release=self.custom_func) self.menu_items = [ { "text": f"Item {i}", "viewclass": "OneLineListItem", "on_release": lambda x=f"Item {i}": self.menu_callback(x), } for i in range(5) ] self.menu = MDDropdownMenu( caller=self.cust, items=self.menu_items, width_mult=4, ) # self.cust.on_release=self.custom_func self.screen.add_widget(self.cust) def custom_func(self, *args, **kwargs): self.menu.open() def menu_callback(self, text_item): print(text_item) def build(self): return self.screen
class Test(MDApp): submenu = None def __init__(self, **kwargs): super().__init__(**kwargs) self.screen = Builder.load_string(KV) menu_items = [{ "icon": "git", "text": f"Item {i}" if i != 3 else "Open submenu", } for i in range(5)] self.menu = CustomDrop(caller=self.screen.ids.button, items=menu_items, width_mult=4, selected_color=self.theme_cls.bg_darkest) self.menu.bind(on_enter=self.check_item) def check_item(self, menu, item): if item.text == "Open submenu" and not self.submenu: menu_items = [{"text": f"Item {i}"} for i in range(5)] self.submenu = MDDropdownMenu( caller=item, items=menu_items, width_mult=4, selected_color=self.theme_cls.bg_darkest, ) self.submenu.bind(on_dismiss=self.set_state_submenu) self.submenu.open() def set_state_submenu(self, *args): self.submenu = None def build(self): return self.screen
class Consulta(Screen): data_tables: MDDataTable def __init__(self, **kwargs): super(Consulta, self).__init__() def menu_p(self): menu_items = [{ "text": "Ingreso Movimientos" }, { "text": "Consulta de Movimientos" }, { "text": "Salir" }] self.menu = MDDropdownMenu(caller=self.ids.button, items=menu_items, width_mult=5, callback=self.menu_callback) self.menu.bind(on_release=self.menu_callback) self.menu.open() def menu_callback(self, instance): opcion = instance if opcion.text == "Ingreso Movimientos": self.manager.current = 'Ingresos' else: print("Opcion seleccionada es :", opcion.text) def habre_md_table(self): Fun_Consultas.md_table(self)
class MDDropDownItem(ThemableBehavior, BoxLayout): items = ListProperty() """String list of items for a drop-down list.""" dropdown_bg = ListProperty() """Color of the background of the menu.""" dropdown_max_height = NumericProperty() """The menu will grow no bigger than this number.""" dropdown_width_mult = NumericProperty(2) """This number multiplied by the standard increment (56dp on mobile, 64dp on desktop, determines the width of the menu items. If the resulting number were to be too big for the application Window, the multiplier will be adjusted for the biggest possible one. """ current_item = StringProperty() """Current label of item MDDropDownItem class.""" _drop_list = None _list_menu = ListProperty() def __init__(self, **kwargs): super().__init__(**kwargs) if not self.dropdown_bg: self.dropdown_bg = self.theme_cls.primary_color def on_items(self, instance, value): for name_item in value: self._list_menu.append({ "viewclass": "OneLineListItem", "text": name_item, "on_release": lambda x=name_item: self.set_item(x), }) self.ids.label_item.text = self.current_item if self.current_item else value[ 0] def set_item(self, name_item): self.ids.label_item.text = name_item self.current_item = name_item self._drop_list.dismiss() def on_touch_down(self, touch): if self.collide_point(touch.x, touch.y) and self._list_menu: self._drop_list = MDDropdownMenu( _center=True, items=self._list_menu, background_color=self.dropdown_bg, max_height=self.dropdown_max_height, width_mult=self.dropdown_width_mult, width_rectangle=1, ) self._drop_list.open(self)
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 elif 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]}" ) elif icon == "language-python": self.root.ids.scr_mngr.current = "code viewer" try: self.data["Source code"][ "object" ].ids.code_input.text = open( f"{os.environ['KITCHEN_SINK_ASSETS']}md/{self.file_source_code}", "rt", encoding="utf-8", ).read() except FileNotFoundError: from kivymd.uix.snackbar import Snackbar Snackbar(text="Cannot load source code").show() menu_for_context_menu_source_code = [] data = { "Source code": "language-python", "Open in Wiki": "source-repository", } if self.root.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=4, width_rectangle=0.1, background_color=self.theme_cls.primary_dark, ) context_menu.open(instance.ids.right_actions.children[0])
def open_context_menu(self, entry_object, type_chooser): """Opens a context menu on right-clicking on a file or folder.""" menu = MDDropdownMenu( caller=entry_object, items=self.get_menu_right_click(entry_object, type_chooser), width_mult=4, background_color=self.theme_cls.bg_dark, max_height=dp(240), ) menu.bind(on_dismiss=self.context_menu_dismiss, ) menu.open() self.context_menu_open = True
def 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])
class Menu(MDFloatLayout): #menu = MDDropdownMenu() Num = 4 def __init__(self, **kwargs): #super().__init__(**kwargs) self.menu_items = [{ "text": f"Item {i}", "viewclass": "OneLineListItem", 'font_name': "./font/FangZhengHeiTiJianTi-1", "on_release": lambda x=f"Item {i}": self.menu_callback(x) } for i in range(self.Num)] self.menu = MDDropdownMenu( #caller=self.screen.ids.button, caller=None, items=self.menu_items, width_mult=4, ) self.menu.bind(on_release=self.menu_callback) print(123) #return self.menu # def menu_callback(self, instance_menu_item): print("instance_menu", instance_menu_item) #self.page_callback() self.test = "Change Page" print(self.test) self.menu.dismiss() def page_callback(self): self.test = "Change Page" print(self.test) # let's start def pop(self): self.menu.open()
class SelectBox(MDStackLayout): """An html style select box""" label = StringProperty('Select an option') value = StringProperty() options = ListProperty() dd_item = ObjectProperty() dropdown = None def on_dd_item(self, _instance, item): """Runs after setting the MDDropDownItem""" app = MDApp.get_running_app() print(f"Theme class {app.theme_cls.primary_color}") self.dropdown = MDDropdownMenu( caller=item, items=self.options, position="auto", width_mult=4, callback=self.select_option, ) item.bind(on_release=self.open_dropdown) def open_dropdown(self, *_args, **_kwargs): """Open the dropdown.""" self.dropdown.open() def on_options(self, _instance, options): """Change the selectbox items.""" if self.dropdown is not None: self.dropdown.items = options self.dropdown.create_menu_items() def on_label(self, _instance, value): """When the selectbox label changes, change the button text""" self.dd_item.text = value def select_option(self, option): """Selected the option of the SelectBox""" self.dropdown.dismiss() self.dd_item.set_item(option.text) self.value = option.text
class Main(Screen): menu = None def open_menu(self, instance_button): menu_items = [{"icon": "git", "text": f"Item {i}"} for i in range(5)] if self.menu == None: self.menu = MDDropdownMenu( caller=instance_button, items=menu_items, position="auto", width_mult=4, ) self.menu.bind(on_release=self.set_item) self.menu.open() def set_item(self, instance_menu, instance_menu_item): self.ids.label.text = instance_menu_item.text self.menu.dismiss() def slider_move(self, instance_slider, mouse_motion): self.ids.label.text = str(instance_slider.value/100) instance_slider.size_hint_y = instance_slider.value/100 self.ids.label.size_hint_y = 1-instance_slider.value/100
class MyDropdown(MDDropDownItem): def __init__(self, list_items, icon, first_item_chosen=None, **kwargs): super(MyDropdown, self).__init__(**kwargs) menu_items = [{"icon": icon, "text": str(item)} for item in list_items] self.menu = MDDropdownMenu(caller=self, items=menu_items, position="auto", width_mult=5) self.menu.bind(on_release=self.set_item_dropdown) self.bind(on_release=lambda _: self.menu.open()) if first_item_chosen is None: first_item_chosen = str(list_items[0]) self.set_item(first_item_chosen) def set_item_dropdown(self, _instance_menu, instance_menu_item): selected_item = instance_menu_item.text self.menu.dismiss() self.set_item(selected_item)
class BMICalc(App,MDApp): height = NumericProperty(175) weight = NumericProperty(75) age = NumericProperty(10) height_unit = StringProperty('cm') weight_unit = StringProperty('kg') def menu_callback(self, text_item): self.menu.dismiss() print(text_item) weight_items = [ { "text": "kg", "viewclass": "OneLineListItem", "on_release": lambda x="kg": menu_callback(x), }, { "text": "pounds", "viewclass": "OneLineListItem", "on_release": lambda x="pounds": menu_callback(x), }, ] height_items =[ { "text": "cm", "viewclass": "OneLineListItem", "on_release": lambda x="cm": self.menu_callback(x), }, { "text": "inches", "viewclass": "OneLineListItem", "on_release": lambda x="inches": self.menu_callback(x), } ] def drop(self,option,this): self.menu = MDDropdownMenu( caller=this, items=option, width_mult=2, ) self.menu.open() def weight_increase(self): self.weight += 1 def weight_decrease(self): self.weight -= 1 def age_increase(self): self.age += 1 def age_decrease(self): self.age -= 1 def height_increase(self): self.height += 1 def height_decrease(self): self.height -= 1 def calculate_bmi(self): bmi = round((self.weight)/((self.height*0.01)**2),1) result_popup = MDDialog(title='BMI',text=f"Your BMI is {bmi}",size_hint=[.8,.3]) result_popup.open() DEBUG=1 KV_FILES = { os.path.join(os.getcwd(),"bmi.kv") } CLASSES = { "ManagerScreens":"bmi", "MyHomeScreen":"bmi", "ResultScreen":"bmi", } AUTORELOADER_PATHS = [(".",{"recursive":True})] def build_app(self): Window.bind(on_keyboard=self._rebuild) self.sm = ManagerScreens() # self.home_page = MyHomeScreen() # screen = Screen(name='home') # screen.add_widget(self.home_page) # self.sm.add_widget(screen) # self.result_page =ResultScreen() # screen = Screen(name='result') # screen.add_widget(self.result_page) # self.sm.add_widget(screen) return self.sm def _rebuild(self,*args): if args[1] == 32: self.rebuild() def change_screen(self,screen_name): self.sm.current = screen_name def go_home(self): sm = ScreenManager() sm.add_widget(MyHomeScreen(name='home')) sm.add_widget(ResultScreen(name='result')) sm.current = 'home' def donothing(self): pass
class MainApp(MDApp): # APP storage_url = "https://farmzon-abdcb.appspot.com" database_url = "https://farmzon-abdcb.firebaseio.com/.json" data = {"uu": {"Joe Tilsed": "me"}} auth_key = "sBlt6fzvguYnrGl2FlXRK3k4vRxSfZJBV2P7yIRv" size_x = NumericProperty(0) size_y = NumericProperty(0) menu = ObjectProperty(None) count = NumericProperty(0) loggin_count = NumericProperty(0) count_update = NumericProperty(0) dialog = None dialog_phone = None dialog_last = None setter = None counter_image = NumericProperty(0) spin_active = BooleanProperty(False) menu_text = StringProperty("Your Location") loading = StringProperty("") # Business product_name = StringProperty("") phone_number = StringProperty("") location = StringProperty("") quantity = StringProperty("") total_amount = NumericProperty(0) order_number = StringProperty("0") category_tp = StringProperty("") # MATH calculator = StringProperty("0") calculator2 = StringProperty("0") # XXX-------ADMIN LOGIN VAR-------XXX admin_name = StringProperty("") admin_phone = StringProperty("") customer_phone = StringProperty("") admin_password = StringProperty("") admin_true = BooleanProperty(False) admin_product_description = StringProperty("") admin_product_image = StringProperty("images/picture.png") admin_product_name = StringProperty("") admin_product_price = StringProperty("") admin_product_id = StringProperty("") admin_product_url = StringProperty("") # ADS app_id = "ca-app-pub-9270156272717443~8633598837" interstitial = "ca-app-pub-9270156272717443/2248347409" # DATABASE def stream_handler(self, message): if True: print("hello") return notification.notify(title='New order', message='you have new order!') def notifi(self, phone): try: import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db id = datetime.datetime.now() cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) if phone != "0788204327": my_stream = db.reference("Yummy").child("Admin").child(phone).child("Orders").listen( self.stream_handler) else: my_stream = db.reference("Yummy").child("Orders").listen( self.stream_handler) except: print("poor me") def remember_me_admin(self, user, password, name): with open("credential/admin.txt", "w") as fl: fl.write(user + "\n") fl.write(password) with open("credential/admin_info.txt", "w") as ui: ui.write(name) fl.close() ui.close() def admin_memory(self): if self.loggin_count == 0: self.loggin_count = 1 + self.loggin_count self.admin_true = True file1 = open('credential/admin.txt', 'r') file2 = open("credential/admin_info.txt") Lines = file1.readlines() Lines2 = file2.readlines() # Strips the newline character self.admin_phone = Lines[0].strip() self.admin_password = Lines[1].strip() self.admin_name = Lines2[0] self.count += 1 thread = threading.Thread(self.notifi(self.admin_phone)) thread = threading.Thread(self.listen_db(self.admin_phone)) thread.start() else: sm = self.root sm.current = "admin_main" self.spin_active = False def actively_reg(self): if self.spin_active: self.spin_active = False toast("Successfully Registered!") def permision_req(self): if utils.platform == 'android': from android.permissions import request_permissions, Permission # todo request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE]) def notifier(self): notification.notify(title="Welcome", message="you can also sell and buy!") def on_start(self): m = self.root m.current = "one" identity = self.root.ids.drop_item_one self.menu_fun(identity) self.keyboard_hooker() def menu_fun(self, identity): vimbweta = [ "vimbweta vya uwanjani", "vimbweta vya stationary", "vimbweta vya girls hostel", "vimbweta vya boys hostel", "vimbweta nyuma ya ndege", "vimbweta vya block 16", "vimbweta vya adminstration", "class one", "class two", "class three", "Aviation classes" ] self.menu = MDDropdownMenu( caller=identity, width_mult=9, position="auto", callback=self.menu_callback ) for i in range(vimbweta.__len__()): self.menu.items.append( { "text": vimbweta[i] } ) for i in range(22): if i == 0: pass else: self.menu.items.append( { "text": "Block " + "" + str(i) } ) self.menu.bind( on_release=self.menu_callback ) self.setter = identity self.setter.set_item(self.menu_text) def show_alert_dialog(self): if not self.dialog: self.dialog = MDDialog( title="Do you real want to quit?", buttons=[ MDFlatButton( text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.kill ), MDRaisedButton( text="QUIT!", text_color=self.theme_cls.primary_color, on_release=lambda x: toast("Please press the home button!", 5) ), ], ) self.dialog.open() def phone_number_dialog(self): if not self.dialog_phone: self.dialog_phone = phone_dialog( title="Enter Your phone number", auto_dismiss=False, buttons=[ MDFlatButton( text="Cancel", text_color=self.theme_cls.primary_color, on_release=self.kill_phone ), MDRaisedButton( text="Submit", text_color=self.theme_cls.primary_color, on_release=lambda x: self.phone_number_check(self.phone_number) ), ], ) self.dialog_phone.open() def last_step_dialog(self): if not self.dialog_last: self.dialog_last = MDDialog( title="Confirm", type="custom", auto_dismiss=False, content_cls=last_dialog(), buttons=[ MDFlatButton( text="Cancel", text_color=self.theme_cls.primary_color, on_release=lambda x: self.adver() ), MDRaisedButton( text="Ok", on_release=lambda x: self.adver(), theme_text_color="Custom", md_bg_color=[243 / 255, 189 / 255, 106 / 255, 1] ), ], ) self.dialog_last.md_bg_color = 245 / 255, 0 / 255, 72 / 255, 1 self.dialog_last.open() def phone_number_check(self, phone): new_number = "" if phone != "": for i in range(phone.__len__()): if i == 0: pass else: new_number = new_number + phone[i] number = "+255" + new_number if not carrier._is_mobile(number_type(phonenumbers.parse(number))): toast("Please check your phone number!", 1) return False else: self.phone_number = phone thread = threading.Thread(target=self.Business(self.product_name, self.quantity, self.phone_number)) thread.start() self.kill_phone() return True else: toast("check your number") def phone_number_check_admin(self, phone): new_number = "" if phone != "": for i in range(phone.__len__()): if i == 0: pass else: new_number = new_number + phone[i] number = "+255" + new_number if not carrier._is_mobile(number_type(phonenumbers.parse(number))): toast("Please check your phone number!", 1) return False else: return True else: toast("enter phone number!") def kill(self, *kwargs): self.dialog.dismiss() def kill_phone(self, *kwargs): self.ads.request_interstitial() self.dialog_phone.dismiss() self.ads.show_interstitial() def kill_adver(self): self.dialog_last.dismiss() def Business(self, product, quantity, phone): self.last_step_dialog() print("location:", self.location, '\n' "Product name:", product, '\n' "quantity:", quantity, '\n' "Total amount:", self.total_amount, '\n' "Phone number:", phone) if self.category_tp != "admin": from helped import connection_status as CS if CS.Network.internet(CS.Network()): self.spin_active = True thread = threading.Thread(target=DB.upload_data, args=( DB(), self.customer_phone, phone, self.location, quantity, self.total_amount, product)) thread.start() thread.join() toast("Ordered successfully!", 10) self.spin_active = False else: self.spin_active = False toast("Sorry try again!", 5) else: from helped import connection_status as CS if CS.Network.internet(CS.Network()): self.spin_active = True thread = threading.Thread(target=DB.upload_data_admin, args=( DB(), self.customer_phone, phone, self.location, quantity, self.total_amount, product)) thread.start() thread.join() toast("Ordered successfully!", 10) self.spin_active = False else: self.spin_active = False toast("Sorry try again!", 5) def keyboard_hooker(self): EventLoop.window.bind(on_keyboard=self.hook_keyboard) def hook_keyboard(self, window, key, *largs): sm = self.root print(key, self.count) if key == 27 and self.count == 1 or self.count <= -1: sm.current = "one" print("change", self.count) self.count = self.count - 1 print("current>>", self.count) return True elif key == 27 and self.count == 0: # Window.on_close() self.show_alert_dialog() return True def menu_callback(self, menu): self.menu_text = menu.text self.setter.set_item(menu.text) self.menu.dismiss() print(menu.text) self.location = menu.text def callculator_rim(self, mingapi, price): identity = self.root.ids.quantity self.calculator = mingapi + "0" if mingapi == "": pass elif mingapi == '.': identity.text = "1" else: self.total_amount = self.calculator = str(float(mingapi) * int(price)) def callback(self, button): self.menu.caller = button self.menu.open() food_count = 0 def order_spinner2(self): if self.front_shop_count == 0: self.spin_active = True try: toast("loading please wait...", 10) self.loading = "Loading..." # Clock.schedule_once(lambda x: self.front_shop(), 4) thread = threading.Thread(target=self.front_shop()) thread.start() except: toast("no internet!") self.loading = "" self.spin_active = False def order_spinner3(self): if self.other_shops == 0: self.spin_active = True try: toast("loading please wait...", 10) Clock.schedule_once(lambda x: self.other_shop(), 4) # thread = threading.Thread(target=self.other_shop) # thread.start() except: toast("no internet!") self.spin_active = False def order_spinner1(self): sm = self.root file_size = os.path.getsize("credential/admin.txt") if file_size == 0: sm.current = "login" else: self.spin_active = True sm.current = "admin_main" thread = threading.Thread(target=self.admin_memory) thread.start() thread.join() self.spin_active = False def add_order(self): try: if self.food_count == 0: self.food_count = self.food_count + 1 food = self.root.ids.food_cat import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) store = db.reference("Yummy").child("Orders") stores = store.get() count = 0 for y, x in stores.items(): food_categories = category() del_btn = MDIconButton(icon="delete", on_release=self.remove_widgets, pos_hint={"center_x": .9, "center_y": .3}, theme_text_color="Custom", text_color={60 / 255, 66 / 255, 75 / 255}, user_font_size="26sp") count += 1 # food_categories.md_bg_color = 245 / 255, 0 / 255, 72 / 255, 1 food_categories.id = y del_btn.id = y food_categories.md_bg_color = 121 / 255, 174 / 255, 141 / 255, 1 food_categories.add_widget(Labels(text="Admin-phone:" + " " + str(x['Admin phone']))) food_categories.add_widget(Labels(text="Phone:" + " " + y)) food_categories.add_widget(MDSeparator(height="5dp")) food_categories.add_widget(Labels(text="Amount:" + " " + " " + str(x['amount']))) food_categories.add_widget(Labels(text="Location:" + " " + " " + str(x['location']))) food_categories.add_widget(Labels(text="Product-Name:" + " " + " " + str(x['product name']))) food_categories.add_widget(Labels(text="Quantity:" + " " + " " + str(x['quantity']))) food_categories.add_widget(Labels(text="Time-Ordered:" + " " + " " + str(x['time']))) food_categories.add_widget(del_btn) food.add_widget(food_categories) self.spin_active = False self.order_number = str(count) else: pass except: toast("no internet") self.spin_active = False def resize_bottom_tabs(self): # bottom_nav bv = self.root.ids.bottom_nav bv.on_resize() def add_order_admin(self): try: if self.food_count == 0: print("num>", self.admin_phone) self.food_count = self.food_count + 1 food = self.root.ids.food_cat import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) if self.admin_phone != "0788204327": store = db.reference("Yummy").child("Admin").child(self.admin_phone).child("Orders") stores = store.get() print(stores) count = 0 for y, x in stores.items(): print(x) food_categories = category() del_btn = MDIconButton(icon="delete", on_release=self.remove_widgets, pos_hint={"center_x": .9, "center_y": .3}, theme_text_color="Custom", text_color={60 / 255, 66 / 255, 75 / 255}, user_font_size="26sp") count += 1 # food_categories.md_bg_color = 245 / 255, 0 / 255, 72 / 255, 1 food_categories.id = y del_btn.id = y food_categories.md_bg_color = 121 / 255, 174 / 255, 141 / 255, 1 food_categories.add_widget(Labels(text="Admin-phone:" + " " + str(x['Phone number']))) food_categories.add_widget(Labels(text="Phone:" + " " + y)) food_categories.add_widget(MDSeparator(height="5dp")) food_categories.add_widget(Labels(text="Amount:" + " " + " " + str(x['amount']))) food_categories.add_widget(Labels(text="Location:" + " " + " " + str(x['location']))) food_categories.add_widget( Labels(text="Product-Name:" + " " + " " + str(x['product name']))) food_categories.add_widget(Labels(text="Quantity:" + " " + " " + str(x['quantity']))) food_categories.add_widget(Labels(text="Time-Ordered:" + " " + " " + str(x['time']))) food_categories.add_widget(del_btn) food.add_widget(food_categories) self.spin_active = False self.order_number = str(count) else: self.add_order() else: pass except: toast("no internet") self.spin_active = False all_products = {} front_products = {} front_shop_count = 0 other_shops = 0 def other_shop(self): if True: try: if self.other_shops == 0: self.other_shops = self.other_shops + 1 import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: shop = self.root.ids.other_shop cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) store = db.reference("Yummy").child("Products") stores = store.get() from retrive_data import Retrieve as RE RE.other_shop(RE(), stores) self.all_products = stores for y, x in stores.items(): self.admin_product_name = x["product_name"] self.customer_phone = x["admin_phone"] self.admin_product_url = x["image_url"] self.admin_product_price = x["product_price"] self.admin_product_description = x["product_description"] other_shops = Shops(on_release=self.selling_other) other_shops.add_widget(Labels(text=self.admin_product_name)) other_shops.add_widget(Shop_image(source=self.admin_product_url)) other_shops.add_widget(Labels(text=self.admin_product_price)) other_shops.id = y shop.add_widget(other_shops) self.spin_active = False except: self.spin_active = False toast("no internet!") def other_shop_offline(self): filename = "helped/other.json" try: file_size = os.path.getsize(filename) if file_size > 0: shop = self.root.ids.front_shop with open(filename) as file: line = json.load(file) print(line) for y, x in line.items(): self.admin_product_name = x["product_name"] self.customer_phone = x["admin_phone"] self.admin_product_url = x["image_url"] self.admin_product_price = x["product_price"] self.admin_product_description = x["product_description"] other_shops = Shops(on_release=self.selling_other) other_shops.add_widget(Labels(text=self.admin_product_name)) other_shops.add_widget(Shop_image(source=self.admin_product_url)) other_shops.add_widget(Labels(text=self.admin_product_price)) other_shops.id = y shop.add_widget(other_shops) self.spin_active = False except: self.spin_active = False self.order_spinner3() def other_shop_comparison(self): filename = "helped/other.json" try: file_size = os.path.getsize(filename) if file_size != 0: with open(filename) as file: line = json.load(file) local_len = len(line) import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) store = db.reference("Yummy").child("Products") stores = store.get() online_len = len(stores) print(local_len, online_len) if local_len == online_len: print(local_len, online_len) else: self.refresh_other() else: self.refresh_other() except: toast("something is wrong!") def other_shop_faster(self): filename = "helped/other.json" try: if self.other_shops == 0: self.other_shops = self.other_shops + 1 file_size = os.path.getsize(filename) thread = threading.Thread(target=self.other_shop_comparison) thread.start() if file_size != 0: shop = self.root.ids.other_shop with open(filename) as file: line = json.load(file) print(line) self.all_products = line for y, x in line.items(): self.admin_product_name = x["product_name"] self.customer_phone = x["admin_phone"] self.admin_product_url = x["image_url"] self.admin_product_price = x["product_price"] self.admin_product_description = x["product_description"] other_shops = Shops(on_release=self.selling_other) other_shops.add_widget(Labels(text=self.admin_product_name)) other_shops.add_widget(Shop_image(source=self.admin_product_url)) other_shops.add_widget(Labels(text=self.admin_product_price + "/Tsh")) other_shops.id = y shop.add_widget(other_shops) self.spin_active = False else: self.other_shops = 0 self.order_spinner3() except: self.other_shops = 0 self.order_spinner3() def selling_other(self, instance): print(instance.id) # self.count = self.count + 1 product = instance.id self.customer_phone = self.all_products[product]["admin_phone"] self.admin_product_url = self.all_products[product]["image_url"] self.admin_product_name = self.all_products[product]["product_name"] self.admin_product_price = self.all_products[product]["product_price"] self.admin_product_description = self.all_products[product]["product_description"] sm = self.root sm.current = "selling_other" def summon(self): sm = self.root sm.current = "other_shops" if self.other_shops == 0: self.spin_active = True def front_shop(self): if True: try: print("ok") if self.front_shop_count == 0: self.front_shop_count = self.front_shop_count + 1 print("yess..") import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: shop = self.root.ids.front_shop cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) store = db.reference("Yummy").child("Products_admin") print("nice") stores = store.get() from retrive_data import Retrieve as RE thread = threading.Thread(target=RE.front_shop, args=(RE(), stores)) thread.start() print("good") self.front_products = stores for y, x in stores.items(): self.admin_product_name = x["product_name"] self.customer_phone = x["admin_phone"] self.admin_product_url = x["image_url"] self.admin_product_price = x["product_price"] front_shops = Front_shop(on_release=self.selling_front) layout = FloatLayout() layout.add_widget(Labels(text=self.admin_product_name, pos_hint={"center_x": .5, "center_y": .2}, halign="center")) layout.add_widget(Cool(source=self.admin_product_url)) front_shops.add_widget(layout) front_shops.id = y shop.add_widget(front_shops) time.sleep(2) self.spin_active = False self.loading = "" else: print("f**k!") except: toast("no internet!") self.front_shop_offline() def front_shop_offline(self): filename = "helped/admin.json" try: file_size = os.path.getsize(filename) if file_size > 0: shop = self.root.ids.front_shop with open(filename) as file: line = json.load(file) print(line) for y, x in line.items(): self.admin_product_name = x["product_name"] self.customer_phone = x["admin_phone"] self.admin_product_url = x["image_url"] self.admin_product_price = x["product_price"] front_shops = Front_shop(on_release=self.selling_front) layout = FloatLayout() layout.add_widget(Labels(text=self.admin_product_name, pos_hint={"center_x": .5, "center_y": .2}, halign="center")) layout.add_widget(Cool(source=self.admin_product_url)) front_shops.add_widget(layout) front_shops.id = y shop.add_widget(front_shops) time.sleep(2) self.spin_active = False self.loading = "" except: button = MDTextButton(text="Retry", pos_hint={"center_x": .5, "center_y": .5}, on_release=lambda x: self.refresh_front()) button.id = "you" button.custom_color = 40 / 255, 123 / 255, 222 / 255, 1 shop = self.root.ids.front_shop shop.add_widget(button) self.loading = "" self.spin_active = False def front_shop_comparison(self): filename = "helped/admin.json" try: file_size = os.path.getsize(filename) if file_size != 0: with open(filename) as file: line = json.load(file) local_len = len(line) import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) store = db.reference("Yummy").child("Products_admin") stores = store.get() online_len = len(stores) if local_len == online_len: pass else: self.refresh_front() else: self.refresh_front() except: toast("something is wrong!") def front_shop_faster(self): filename = "helped/admin.json" try: if self.front_shop_count == 0: self.notifier() self.front_shop_count = self.front_shop_count + 1 file_size = os.path.getsize(filename) thread = threading.Thread(target=self.front_shop_comparison) thread.start() if file_size != 0: shop = self.root.ids.front_shop with open(filename) as file: line = json.load(file) print(line) self.front_products = line for y, x in line.items(): self.admin_product_name = x["product_name"] self.customer_phone = x["admin_phone"] self.admin_product_url = x["image_url"] self.admin_product_price = x["product_price"] front_shops = Front_shop(on_release=self.selling_front) layout = FloatLayout() layout.add_widget(Labels(text=self.admin_product_name, pos_hint={"center_x": .5, "center_y": .2}, halign="center")) layout.add_widget(Cool(source=self.admin_product_url)) front_shops.add_widget(layout) front_shops.id = y shop.add_widget(front_shops) self.spin_active = False self.loading = "" else: self.front_shop_count = 0 self.order_spinner2() except: self.front_shop_count = 0 self.order_spinner2() def selling_front(self, instance): print(instance.id) self.count = self.count + 1 self.category_tp = "admin" product = instance.id self.customer_phone = self.front_products[product]["admin_phone"] self.admin_product_url = self.front_products[product]["image_url"] self.admin_product_name = self.front_products[product]["product_name"] self.admin_product_price = self.front_products[product]["product_price"] sm = self.root sm.current = "selling" def success(self, *kwargs): self.refresh() def refresh(self): parent = self.root.ids.food_cat all_childs = parent.children identity = [] self.food_count = 0 for child in all_childs: identity.append(child.id) self.order_number = str(identity.__len__()) for i in identity: self.remove_wide(i) if self.admin_phone == "0788204327": self.add_order() else: self.add_order_admin() def refresh_front(self): parent = self.root.ids.front_shop all_childs = parent.children identity = [] self.front_shop_count = 0 for child in all_childs: identity.append(child.id) for i in identity: print(i) self.remove_wide_front(i) self.spin_active = True self.order_spinner2() def refresh_other(self): parent = self.root.ids.other_shop all_childs = parent.children identity = [] self.other_shops = 0 for child in all_childs: identity.append(child.id) for i in identity: print(i) self.remove_wide_other(i) self.spin_active = True self.order_spinner3() def remove_wide_front(self, name): parent = self.root.ids.front_shop for child in parent.children: if name == child.id: parent.remove_widget(child) def remove_wide_other(self, name): parent = self.root.ids.other_shop for child in parent.children: if name == child.id: parent.remove_widget(child) def remove_wide(self, name): parent = self.root.ids.food_cat for child in parent.children: if name == child.id: parent.remove_widget(child) def remove_widgets(self, instance): name = instance.id parent = self.root.ids.food_cat for child in parent.children: if name == child.id: parent.remove_widget(child) self.del_entity(child.id) def del_entity(self, name): import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db if not firebase_admin._apps: cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) if self.admin_phone == "0788204327": db.reference("Yummy").child("Orders").child(name).delete() else: db.reference("Yummy").child("Admin").child(self.admin_phone).child("Orders").child(name).delete() def validate_user(self, phone, password): if phone == "" and phone.Isdigit(): toast("please enter your phone number correctly") elif password == "": toast("please enter your password") else: self.spin_active = True thread = threading.Thread(target=self.Signing_in_admin_function, args=(phone, password)) thread.start() def Signing_in_admin(self, phone, password): # thread = threading.Thread(target=self.Signing_in_admin_function, args=(phone, password)) # thread.start() self.Signing_in_admin_function(phone, password) @mainthread def Signing_in_admin_function(self, phone, password): if DB.Signing_in_admin(DB(), phone, password): self.admin_name = DB.name_admin self.remember_me_admin(phone, password, self.admin_name) if not self.admin_true: self.listen_db(phone) sm = self.root sm.current = "admin_main" else: if self.admin_true: toast("no internet connection") self.spin_active = False else: self.spin_active = False toast("oops! phone number or password in correct or internet connection") # XXX---------CUSTOMER--------------XXX def id_generator(self): not_allowed = ".-:" date1 = datetime.datetime.now() date, time = id = str(date1).split(" ") self.admin_product_id = date + time product_id = "" for i in range(len(self.admin_product_id)): if self.admin_product_id[i] not in not_allowed: product_id = self.admin_product_id[i] + product_id id = self.admin_product_id = product_id print(id) return self.admin_product_id def get_info(self, phone, phone_other, name, price, product_name, image_path, password, category, description): if phone != "" and self.phone_number_check_admin(phone): if name != "" and name.isalpha() and price != "" and password != "": self.customer_phone = phone self.admin_password = password self.admin_name = name self.admin_product_image = image_path self.admin_product_price = price self.admin_product_name = product_name self.admin_product_id = self.id_generator() cate = category print(phone, name, price, product_name, image_path, password, self.admin_product_id) try: thread = threading.Thread(target=self.transporter, args=( phone, phone_other, name, price, product_name, image_path, password, self.admin_product_id, cate, description)) thread.start() except: toast("no internet") else: toast("check your info well") self.spin_active = False else: toast("check your mobile number") self.spin_active = False def transporter(self, phone, phone_other, name, price, product_name, image_path, password, id, cate, description): thread = threading.Thread(target=DB.upload_product_image, args=( DB(), cate, image_path, phone, phone_other, name, price, product_name, password, id, description)) thread.start() thread.join() self.actively_reg() def listen_db(self, phone): try: import firebase_admin firebase_admin._apps.clear() from firebase_admin import credentials, initialize_app, db id = datetime.datetime.now() cred = credentials.Certificate("credential/farmzon-abdcb-c4c57249e43b.json") initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}) self.admin_phone = phone if phone != "0788204327": print("i am listening......") my_stream = db.reference("Yummy").child("Admin").child(phone).child("Orders").listen(self.success) else: print("i am listening......") my_stream = db.reference("Yummy").child("Orders").listen(self.success) except: print("poor you") def Permission(self, android=None): if self.counter_image <= 0: if utils.platform == 'android': if self.count_update == 0: from gallary import Gambler as GA Clock.schedule_once(GA.user_select_image, 0) self.admin_product_image = GA.path_of_picture img = self.root.ids.product_image img.source = GA.path_of_picture self.count_update += self.count_update + 1 else: from gallary import Gambler as GA self.count_update = self.count_update - 1 self.admin_product_image = GA.path_of_picture img = self.root.ids.product_image img.source = GA.path_of_picture else: self.counter_image = self.counter_image + 1 for root, dirs, files in os.walk("/home/alpha9060/Downloads", topdown=False): for file_ in files: full_file_path = os.path.join(root, file_) if full_file_path.endswith(('.png', '.jpg', '.jpeg')): print(full_file_path) image = full_file_path cat_class = category_gal() cat_class.add_widget(category_ga(source=image)) img = self.root.ids.images_added img.add_widget(cat_class) else: pass ads = KivMob(TestIds.INTERSTITIAL) def adver(self): self.kill_adver() self.ads.show_interstitial() def build(self): self.ads.new_interstitial(TestIds.INTERSTITIAL) self.theme_cls.theme_style = "Light" self.theme_cls.primary_palette = "DeepOrange" self.theme_cls.accent = "Brown" # Window.size = (360, 640) self.size_x, self.size_y = Window.size self.title = "yummy"
class MDDropDownItem(ThemableBehavior, BoxLayout): """ :Events: `on_select` Called when an item is selected """ font_name = StringProperty(LabelBase._fonts[DEFAULT_FONT][0]) items = ListProperty() """String list of items for a drop-down list.""" dropdown_bg = ListProperty() """Color of the background of the menu.""" dropdown_max_height = NumericProperty() """The menu will grow no bigger than this number.""" dropdown_width_mult = NumericProperty(2) """This number multiplied by the standard increment (56dp on mobile, 64dp on desktop, determines the width of the menu items. If the resulting number were to be too big for the application Window, the multiplier will be adjusted for the biggest possible one. """ current_item = StringProperty() """Current label of item MDDropDownItem class.""" _center = BooleanProperty(True) _drop_list = None _list_menu = ListProperty() def __init__(self, **kwargs): super().__init__(**kwargs) self.register_event_type("on_select") if not self.dropdown_bg: self.dropdown_bg = self.theme_cls.primary_color def on_items(self, instance, value): _list_menu = [] for name_item in value: _list_menu.append( { "viewclass": "OneLineListItem", "text": name_item, "text_color": self.theme_cls.text_color, "font_name": self.font_name, "theme_text_color": "Custom", "on_release": lambda x=name_item: self.set_item(x), } ) self._list_menu = _list_menu self.ids.label_item.text = ( self.current_item if self.current_item else value[0] ) self.current_item = self.ids.label_item.text def set_item(self, name_item): self.ids.label_item.text = name_item self.current_item = name_item self._drop_list.dismiss() self.dispatch("on_select", name_item) def on_select(self, value): pass def on_touch_down(self, touch): if self.collide_point(touch.x, touch.y) and self._list_menu: self._drop_list = MDDropdownMenu( _center=self._center, items=self._list_menu, font_name=self.font_name, background_color=self.dropdown_bg, max_height=self.dropdown_max_height, width_mult=self.dropdown_width_mult, width_rectangle=1, ) self._drop_list.open(self)
class HistoryRoot(FloatLayout): """Root widget of the history screen.""" speed_dial_buttons = DictProperty() speed_dial = ObjectProperty() export_cookbook = export_cookbook def __init__(self, **kwargs): self.speed_dial_buttons = self.export_cookbook.to_button_dict() super().__init__(**kwargs) Clock.schedule_once(self.__post_init__) def __post_init__(self, *_): self.speed_dial.icon = "content-save" self.dropdown_menu = MDDropdownMenu( caller=self.ids.history_list, position="center", width_mult=4, items=[ { "text": "back to queue" }, { "text": "delete" }, { "text": "edit" }, ], ) self.dropdown_menu.on_release = self.on_dropdown_item self.text_input_dialog = TextInputDialog(title="Edit Word:") self.text_input_dialog.callback = self.text_input_dialog_callback # self.dropdown_menu.bind(on_release=self.on_dropdown_item) @staticmethod def filter(*_): """Placeholder-function.""" not_implemented_toast() @staticmethod def sort(*_): """Placeholder-function.""" not_implemented_toast() def click_on_item(self, item, *_): """Open dropdown menu with ``item`` as caller.""" self.dropdown_menu.caller = item self.dropdown_menu.open() def on_dropdown_item(self, item, *_): """Call option corresponding to clicked item.""" caller = self.dropdown_menu.caller if item.text == "delete": self.delete_item(caller.text) elif item.text == "edit": self.edit_item(caller.text) else: self.move_back_to_queue(caller.text) self.dropdown_menu.dismiss() @staticmethod def delete_item(item): """Delete ``text`` from the current template in the data-base and from ``app.word_state_dict``.""" app = MDApp.get_running_app() del app.word_state_dict[item] with db_session: app.get_current_template_db().get_card(item).delete() @app_busy def edit_item(self, item): """Open :attr:`text_input_dialog` to edit the word.""" self.text_input_dialog.default_text = item self.text_input_dialog.open() @staticmethod def move_back_to_queue(item): """Move item back to queue.""" old_state = MDApp.get_running_app().word_state_dict[item] new_state = "waiting" if old_state == "error" else "ready" set_word_state(item, new_state) def text_input_dialog_callback(self, button_txt, text): """If the ``OK``-button is pressed, delete old entry and add edited entry to queue.""" if button_txt == "OK": self.delete_item(self.text_input_dialog.default_text) set_word_state(text, "waiting")
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, 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(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
class ProxySpeedTestApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.icon = f"{environ['KITCHEN_SINK_ASSETS']}icon.png" self.version = __version__ self.theme_cls.primary_palette = "LightBlue" self.dialog_change_theme = None self.toolbar = None self.scaning = Queue() self.running = Queue() self.currentSpeed = Queue() self.pbar0 = Queue() self.pbar1 = Queue() self.pbar2 = Queue() self.totalpb = Queue() configs = dbRW.getAllConfigs() mirrors = dbRW.getAllMirrors() self.selLId = configs[0][2] if self.selLId: totalScan = dbRW.getProxysInxTS(self.selLId)[0] getips = dbRW.getAllCurrentProxys(self.selLId) protocol = getips[0][4] self.scan_list = [] if self.selLId: for l in getips: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6] }) self.theme_cls.theme_style = configs[0][0] miInx = configs[0][1] self.configs = { 'protocol': protocol if self.selLId else 'http', 'mirror': mirrors[miInx][0], 'timeout': int(configs[0][3]), 'fileSize': int(configs[0][4]), 'miInx': miInx, 'proxysInx': [], 'mirrors': mirrors, 'proxys': getips if self.selLId else [], 'totalScan': totalScan if self.selLId else 0 } # def on_resume(self): # self.ads.request_interstitial() def changeThemeMode(self, inst): self.theme_cls.theme_style = inst dbRW.updateThemeMode(inst) def checkUpdates(self, ava=False, d=False): # print(ava) upCURL = 'https://raw.githubusercontent.com/biplobsd/proxySpeedTestApp/master/updates.json' # from json import load # with open('updates.json', 'r') as read: # updateinfo = load(read) # toast("Checking for any updates ...") try: updateinfo = get(upCURL).json() except: updateinfo = { "version": float(self.version), "messages": "", "changelogs": "", "force": "false", "release": { "win": "", "linux": "", "android": "", "macosx": "", "unknown": "", "kivy_build": "" } } # toast("Faild app update check!") if updateinfo: try: appLink = updateinfo["release"][platform] except KeyError: return title = f"App update v{updateinfo['version']}" msg = "You are already in latest version!" b1 = "CENCEL" force = False if updateinfo['version'] > float(self.version) and appLink != "": if updateinfo['messages']: title = updateinfo['messages'] msg = "" b2 = "DOWNLOAD" force = bool(updateinfo['force']) if force: b1 = "EXIT" ava = True else: b2 = "CHECK" self.updateDialog = MDDialog( title=title, text=msg + updateinfo['changelogs'] + f"\n\n[size=15]Force update: {force}[/size]", auto_dismiss=False, buttons=[ MDFlatButton( text=b1, text_color=self.theme_cls.primary_color, on_release=lambda x: self.updateDialog.dismiss() if b1 == "CENCEL" else self.stop()), MDRaisedButton( text=b2, on_release=lambda x: open_link(appLink) if b2 == "DOWNLOAD" else self.FCU(self.updateDialog), text_color=self.theme_cls.primary_light, ), ], ) self.updateDialog.ids.title.theme_text_color = "Custom" self.updateDialog.ids.title.text_color = self.theme_cls.primary_light if ava: self.updateDialog.open() def FCU(self, inst): inst.dismiss() Clock.schedule_once(partial(self.checkUpdates, True)) def on_pause(self): return True def save_UpdateDB(self, l=[]): dbRW = MyDb() if l: dbRW.updateScanList(l) def build(self): if platform == "android": self._statusBarColor() Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/list_items.kv") Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/dialog_change_theme.kv") return Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/start_screen.kv") @run_on_ui_thread def _statusBarColor(self, color="#03A9F4"): window = activity.getWindow() window.clearFlags(WindowManager.FLAG_TRANSLUCENT_STATUS) window.addFlags(WindowManager.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.setStatusBarColor(Color.parseColor(color)) window.setNavigationBarColor(Color.parseColor(color)) def show_dialog_change_theme(self): if not self.dialog_change_theme: self.dialog_change_theme = KitchenSinkDialogChangeTheme() self.dialog_change_theme.set_list_colors_themes() self.dialog_change_theme.open() def on_start(self): """Creates a list of items with examples on start screen.""" unsort = self.scan_list # print(unsort) if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.root.ids.Tproxys.text = f"proxys: {len(sort)}" self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" else: self.root.ids.Tscan.text = "scan: 0" self.root.ids.Tproxys.text = "proxys: 0" self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Smirror.text = f"Mirror: {parse.urlparse(self.configs['mirror']).netloc}".upper( ) # self.root.ids.backdrop._front_layer_open=True Logger.info(f"Platform: {platform}") # if platform == 'android': # self.ads = KivMob(adMobIds.APP) # self.ads.new_banner(adMobIds.BANNER, top_pos=False) # self.ads.request_banner() # self.ads.show_banner() # self.root.ids.adsShow.size = (self.root.ids.backdrop_front_layer.width, 110) self.mirrorPic() self.protPic() self.listPic() self.tap_target_list_view = MDTapTargetView( widget=self.root.ids.Slist, title_text="Pic a lists", description_text="I will remember your list later!", widget_position="right_top", # outer_radius=dp(320), cancelable=True, outer_circle_color=self.theme_cls.primary_color[:-1], outer_circle_alpha=0.9, ) Thread(target=self.checkUpdates).start() def listPic(self): proxysInx = dbRW.getProxysInx() self.selLId = dbRW.getConfig('proxysInx')[0] Logger.debug(self.selLId) self.configs['proxysInx'] = proxysInx if proxysInx: selLIdindxDict = {} self.ListItems = [] i = 0 for Inx in proxysInx: self.ListItems.append({ "text": f'#{i} ' + agoConv(Inx[0]), "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" }) selLIdindxDict[Inx[0]] = i i += 1 else: self.ListItems = [{ "text": "None", "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" }] if proxysInx: self.selLIdindx = selLIdindxDict[self.selLId] self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper( ) if proxysInx else "list :" self.listSel = MDDropdownMenu( caller=self.root.ids.Slist, items=self.ListItems, width_mult=4, opening_time=0.2, position='auto', max_height=0, selected_color=self.theme_cls.primary_dark_hue) self.listSel.bind(on_release=self.set_list, on_dismiss=self.manuDismiss) def manuDismiss(self, ins): ins.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) def set_list(self, insMain, ins): import re self.selLIdindx = int(re.search(r'#(\d)\s', ins.text).group(1)) # withoutHash = re.search(r'#\d\s(.+)', ins.text).group(1) Logger.debug(self.selLIdindx) proxysInx = dbRW.getProxysInx() self.selLId = proxysInx[self.selLIdindx][0] proxys = dbRW.getAllCurrentProxys(self.selLId) protocol = proxys[0][4] dbRW.updateConfig("proxysInx", self.selLId) scan_list = proxys self.scan_list = [] if self.selLId: for l in scan_list: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6] }) unsort = self.scan_list if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.configs['proxys'] = proxys self.configs['protocol'] = protocol self.root.ids.Slist.text = f"list : {ins.text}".upper() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" # print(getips) toast(ins.text) # print(indx) self.listSel.dismiss() insMain.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) if self.tap_target_list_view.state == 'open': self.tap_target_list_view.stop() def protPic(self): items = [{ "text": protocol.upper(), "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" } for protocol in ['http', 'https', 'socks4', 'socks5']] self.protSel = MDDropdownMenu( caller=self.root.ids.Sprotocol, items=items, width_mult=3, opening_time=0.2, position='auto', selected_color=self.theme_cls.primary_dark_hue) self.protSel.bind(on_release=self.set_protocol, on_dismiss=self.manuDismiss) def set_protocol(self, insMain, ins): self.configs['protocol'] = ins.text.lower() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" toast(self.configs['protocol']) insMain.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) self.protSel.dismiss() def mirrorPic(self): mirrors = dbRW.getAllMirrors() self.configs['mirrors'] = mirrors items = [{ "text": parse.urlparse(mirror[0]).netloc, "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" } for mirror in mirrors] self.mirrSel = MDDropdownMenu( caller=self.root.ids.Smirror, items=items, opening_time=0.2, width_mult=5, position='auto', max_height=0, selected_color=self.theme_cls.primary_dark_hue) self.mirrSel.bind(on_release=self.set_mirror, on_dismiss=self.manuDismiss) def set_mirror(self, insMain, ins): miInx = 0 for l in self.configs['mirrors']: if ins.text in l[0]: break miInx += 1 self.configs['mirror'] = self.configs['mirrors'][miInx][0] self.root.ids.Smirror.text = f"Mirror: {ins.text}".upper() dbRW.updateConfig("proxysInx", self.selLId) dbRW.updateConfig("miInx", self.configs['miInx']) toast(self.configs['mirror']) insMain.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) self.mirrSel.dismiss() def update_screen(self, dt): try: while not self.pbar0.empty(): sp = self.pbar0.get_nowait() if sp != 0: self.root.ids.progressBar1.value += sp else: self.root.ids.progressBar1.value = 0 except Empty: pass try: while not self.pbar1.empty(): sp = self.pbar1.get_nowait() if sp != 0: self.root.ids.progressBar2.value += sp else: self.root.ids.progressBar2.value = 0 except Empty: pass try: while not self.pbar2.empty(): sp = self.pbar2.get_nowait() if sp != 0: self.root.ids.progressBar3.value += sp else: self.root.ids.progressBar3.value = 0 except Empty: pass try: proxysL = len(self.configs['proxys']) while not self.totalpb.empty(): sp = self.totalpb.get_nowait() if sp != 0: self.root.ids.totalpb.value += sp comP = (self.root.ids.totalpb.value / proxysL) * 100 self.root.ids.totalpbText.text = f"{round(comP)}%" else: self.root.ids.totalpb.max = proxysL self.root.ids.totalpb.value = 0 except Empty: pass self.speedcal() self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper( ) def start_scan(self, instance): # print("Clicked!!") if instance.text == "Start": self.mirrorPic() self.listPic() self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" if len(self.configs['proxys']) == 0: try: if self.configs['proxysInx']: self.tap_target_list_view.start() self.listSel.open() # toast("Pick that list!") return except: pass PSTDialogInput().open() toast("First input proxys ip:port list then start scan.") return instance.text = "Stop" color = "#f44336" instance.md_bg_color = get_color_from_hex(color) self.theme_cls.primary_palette = "Red" if platform == "android": self._statusBarColor(color) self.scaning.put_nowait(1) self.running.put_nowait(1) IndexTime = datetime.now() dbRW.updateConfig('proxysInx', IndexTime) dbRW.updateProxysInx(IndexTime, self.selLId) dbRW.updateProxys(IndexTime, self.selLId) configs = dbRW.getAllConfigs() self.configs['totalScan'] = dbRW.getProxysInxTS(IndexTime)[0] self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" # print(totalScan) self.configs['timeout'] = int(configs[0][3]) self.configs['fileSize'] = int(configs[0][4]) self.selLId = str(IndexTime) self.show_List() self.upScreen = Clock.schedule_interval(self.update_screen, 0.1) Thread(target=self.proxySpeedTest, args=( self.configs['proxys'], self.configs['protocol'], self.configs['mirror'], )).start() # self.proxySpeedTest('start') elif instance.text == "Stoping": toast(f"Waiting for finish {self.root.ids.currentIP.text[8:]}!") else: while not self.scaning.empty(): self.scaning.get_nowait() if not self.running.empty(): instance.text = "Stoping" # instance.text_color color = "#9E9E9E" self.theme_cls.primary_palette = "Gray" instance.md_bg_color = get_color_from_hex(color) if platform == "android": self._statusBarColor(color) def downloadChunk(self, idx, proxy_ip, filename, mirror, protocol): Logger.info(f'Scaning {idx} : Started') try: proxies = { 'http': f'{protocol}://{proxy_ip}', 'https': f'{protocol}://{proxy_ip}' } req = get(mirror, headers={ "Range": "bytes=%s-%s" % (0, self.configs['fileSize']), "user-agent": "Mozilla/5.0", }, stream=True, proxies=proxies, timeout=self.configs['timeout']) with (open(f'{filename}{idx}', 'ab')) as f: start = datetime.now() chunkSize = 0 # oldSpeed = 0 chunkSizeUp = 1024 for chunk in req.iter_content(chunk_size=chunkSizeUp): end = datetime.now() if 0.1 <= (end - start).seconds: delta = round( float((end - start).seconds) + float(str('0.' + str((end - start).microseconds))), 3) speed = round((chunkSize) / delta) # if oldSpeed < speed: # chunkSizeUp *= 3 # else: # chunkSizeUp = speed oldSpeed = speed start = datetime.now() self.currentSpeed.put_nowait(speed) chunkSize = 0 if chunk: chunkSize += sys.getsizeof(chunk) self.showupdate(idx) f.write(chunk) except ProxyError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except connError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except IndexError: self.showupdate(idx, 'd') Logger.info( f'Thread {idx} : You must provide a testing IP:PORT proxy') return False except ConnectTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ConnectTimeou for {proxy_ip}") return False except ReadTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ReadTimeout for {proxy_ip}") return False except RuntimeError: self.showupdate(idx, 'd') Logger.info( f"Thread {idx} : Set changed size during iteration. {proxy_ip}" ) return False except KeyboardInterrupt: self.showupdate(idx, 'd') Logger.info(f"Thread no {idx} : Exited by User.") self.showupdate(idx, 'd') def showupdate(self, idx, mode='u', error=True): if mode == 'u': if idx == 0: self.pbar0.put_nowait(1) elif idx == 1: self.pbar1.put_nowait(1) elif idx == 2: self.pbar2.put_nowait(1) elif mode == 'd': # color = "#f44336" if idx == 0: self.pbar0.put_nowait(0) elif idx == 1: self.pbar1.put_nowait(0) elif idx == 2: self.pbar2.put_nowait(0) self.root.ids.top_text.text = "0 KB/s" def proxySpeedTest(self, proxys, protocol, mirror): filename = 'chunk' unsort = list() sort = list() astTop3 = list() roundC = 0 self.totalpb.put(0) Logger.debug(proxys) for c, part in enumerate(proxys): if self.scaning.empty(): break proxy_ip = part[0].strip() self.root.ids.currentIP.text = f"CURRENT: {proxy_ip}" # Removing before test chunk file for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') # Starting chunk file downloading timeStart = datetime.now() downloaders = [ Thread( target=self.downloadChunk, args=(idx, proxy_ip, filename, mirror, protocol), ) for idx in range(3) ] for _ in downloaders: _.start() for _ in downloaders: _.join() timeEnd = datetime.now() filesize = 0 for i in range(3): try: filesize = filesize + getsize(f'{filename}{i}') except FileNotFoundError: continue filesizeM = round(filesize / pow(1024, 2), 2) delta = round( float((timeEnd - timeStart).seconds) + float(str('0.' + str((timeEnd - timeStart).microseconds))), 3) speed = round(filesize) / delta for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') unsort.append({ 'IP': proxy_ip, 'SIZE': filesizeM, 'TIME': delta, 'SPEED': int(speed), 'top3c': part[6] }) sort = self.sort_Type(unsort, showL=False) sortLL = len(sort) if sortLL >= 3: for t in range(sortLL): if t < 3: if sort[t]['SPEED'] != 0: if not sort[t]['IP'] in astTop3: sort[t]['top3c'] += 1 astTop3.append(sort[t]['IP']) else: for i in range(len(astTop3)): if sort[t]['IP'] == astTop3[i]: # print(i) astTop3.pop(i) sort[t]['top3c'] -= 1 break self.show_List(sort) self.save_UpdateDB(sort) self.totalpb.put(1) roundC = c # return True self.save_UpdateDB(sort) # print(roundC) # print(self.root.ids.totalpb.value) roundC += 1 while True: if self.root.ids.totalpb.value == roundC: self.upScreen.cancel() break self.root.ids.start_stop.text = "Start" self.theme_cls.primary_palette = "LightBlue" self.root.ids.start_stop.md_bg_color = self.theme_cls.primary_color if platform == "android": self._statusBarColor() while not self.running.empty(): self.running.get_nowait() Logger.info("Scan : Finished!") def sort_Change(self, inst, ckid): if ckid and inst.active: self.sort_Type(self.data_lists, mode=inst.text, reverse=False) inst.active = False elif ckid and inst.active == False: self.sort_Type(self.data_lists, mode=inst.text, reverse=True) inst.active = True def sort_Type(self, unsort, mode='SPEED', reverse=True, showL=True): if mode == 'SERVER': mode = 'IP' if mode == 'TOP3-%': mode = 'top3c' sort = sorted(unsort, key=lambda x: x[mode], reverse=reverse) if showL: self.show_List(sort) return sort def show_List(self, data=[]): # if not self.root.ids.backdrop_front_layer.data: # print(data) # print(len(self.root.ids.backdrop_front_layer.data)) totalP = len(self.configs['proxys']) ddict = { "viewclass": "ProxyShowList", "text": "", "text1": "", "text2": "", "text3": "", "text4": "", "on_release": lambda: toast("empty!") } if not data: self.root.ids.backdrop_front_layer.data = [] for i in range(totalP): self.root.ids.backdrop_front_layer.data.append(ddict) else: for i in range(totalP): try: _ = data[i] self.root.ids.backdrop_front_layer.data[i] = { "viewclass": "ProxyShowList", "text": data[i]['IP'], "text1": f"{round((data[i]['top3c']/self.configs['totalScan'])*100)} %", "text2": f"{data[i]['SIZE']} MB", "text3": sec_to_mins(float(data[i]['TIME'])), "text4": f"{size(data[i]['SPEED'], system=alternative)}/s", "on_release": lambda x=data[i]['IP']: self.copy_proxyip(x), } except IndexError: self.root.ids.backdrop_front_layer.data[i] = ddict self.data_lists = data def copy_proxyip(self, data): toast(f"Copied: {data}") Clipboard.copy(data) def speedcal(self): speed = 0 try: while not self.currentSpeed.empty(): speed += self.currentSpeed.get_nowait() except Empty: pass if speed != 0: self.root.ids.top_text.text = f"{size(speed, system=alternative)}/s"
class DoTaskApp(MDApp): title = 'DoTask' def __init__(self, **kwargs): super().__init__(**kwargs) self.menu_items = [] self.menu_item = '' self.todo_list = [] self.done_list = [] self.dialog = None self.menu = None self.sm = ScreenManager() self.sm.add_widget(ToDoScreen(name='todo')) self.sm.add_widget(DoneScreen(name='done')) self.sm.add_widget(NewTaskScreen(name='new_task')) def build(self): self.theme_cls.primary_palette = "DeepOrange" self.theme_cls.primary_hue = "700" self.theme_cls.theme_style = "Dark" def on_start(self): # Make self.todo_list and self.done_list draw in screens self.read_lists() # Set starting screen self.root.ids.screen_manager.current = 'new_task' # Draw about list self.menu_item = {'text': 'About'} self.menu_items.append(self.menu_item) self.menu = MDDropdownMenu(items=self.menu_items, width_mult=2) self.menu.bind(on_release=self.menu_callback) # Close menu dialog def dismiss_btn(self, obj): self.dialog.dismiss() # Open menu def dots_menu(self, button): self.menu.caller = button self.menu.open() # Menu link def menu_callback(self, instance_menu, instance_menu_item): if not self.dialog: self.dialog = MDDialog( text= 'Can add tasks and complete or delete those tasks by swiping.', buttons=[ MDFlatButton(text='Dismiss', on_release=self.dismiss_btn) ]) self.dialog.open() self.menu.dismiss() # Bottom bar action def bottom_nav(self, screen): self.root.ids.screen_manager.current = screen.name # To do list swipe def on_swipe_complete(self, instance): Snackbar(text="Task completed", snackbar_y=dp(50)).open() self.done_list.append(instance.text) self.root.ids.done_list.add_widget( SwipeToDeleteItem(text=instance.text)) done_index = self.todo_list.index(instance.text) self.todo_list.pop(done_index) self.save_list('todo') self.save_list('done') self.root.ids.todo_list.remove_widget(instance) # Done list swipe def on_swipe_delete(self, instance): Snackbar(text="Task deleted", snackbar_y=dp(50)).open() trash_index = self.done_list.index(instance.text) self.done_list.pop(trash_index) self.root.ids.done_list.remove_widget(instance) self.save_list('done') # New task input def todo_input(self): Snackbar(text="Task created", snackbar_y=dp(50)).open() text_input = self.root.ids.text_input.text self.root.ids.todo_list.add_widget( SwipeToCompleteItem(text=text_input)) self.todo_list.append(text_input.strip('\n')) self.save_list('todo') # Read lists from file def read_lists(self): with open("todo.txt") as data: for todo in data.readlines(): if todo != '\n': self.todo_list.append(todo) self.root.ids.todo_list.add_widget( SwipeToCompleteItem(text=todo)) with open("done.txt") as data: for done in data.readlines(): if done != '\n': self.done_list.append(done) self.root.ids.done_list.add_widget( SwipeToDeleteItem(text=done)) # Save list to file def save_list(self, list_type): if list_type == 'todo': with open(f"todo.txt", mode='w') as file: for todo in self.todo_list: file.write(f'{todo}\n') elif list_type == 'done': with open("done.txt", mode='w') as file: for done in self.done_list: file.write(f'{done}\n')
class KrowBarApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.active_color = [1, 1, 1, 1] def build(self): screen_manager = ScreenManager() self.loaded_values = [ 1, 0, 0, 0, 0, 0 ] # round num, cp, primary obj, 1st secondary, 2nd secondary, 3rd secondary self.update_values() self.theme_cls.primary_palette = "Gray" self.theme_cls.primary_hue = "800" # Game counters screen and backgrgound color self.counters = Screen(name="Counters") self.change_bg_color() screen_manager.add_widget(self.counters) # SCROLLVIEW self.scroll = ScrollView() self.counters.add_widget(self.scroll) # MENU self.menu_button = MDIconButton(icon='format-color-fill', on_release=self.menu_open) self.menu_button.pos_hint = {'center_x': .9, 'center_y': .1} self.menu_button.md_bg_color = (1, 1, 1, 1) items = [{ "text": "Ceramic White" }, { "text": "Loyal Angels Green" }, { "text": "Space Doggos Gray" }, { "text": "Codex Blue" }, { "text": "Vampire Angels Red" }, { "text": "Gray Nights" }, { "text": "Stubborn Fists Yellow" }] self.menu = MDDropdownMenu(caller=self.menu_button, items=items, callback=self.menu_callback, width_mult=5) self.counters.add_widget(self.menu_button) # MAIN GRID app_grid = GridLayout(cols=1, spacing=100, size_hint_y=None) app_grid.padding = [ Window.width / 40, Window.height / 20, Window.width / 40, Window.height / 4 ] # [left,top,right,bottom] app_grid.bind(minimum_height=app_grid.setter('height')) self.scroll.add_widget(app_grid) # ROUND COUNTER round_parent_grid = MDGridLayout() round_parent_grid.cols = 1 round_parent_grid.rows = 2 round_parent_grid.adaptive_height = True round_label = MDLabel(text='Round number:') round_label.halign = 'center' round_parent_grid.add_widget(round_label) app_grid.add_widget(round_parent_grid) grid_round = GridLayout() grid_round.cols = 3 increase_round = MDIconButton(icon="arrow-right-bold", on_press=self.increase_round) self.round_counter = MDLabel(text=str(self.loaded_values[0])) self.round_counter.halign = 'center' self.round_counter.valign = 'middle' decrease_round = MDIconButton(icon="arrow-left-bold", on_press=self.decrease_round) grid_round.add_widget(decrease_round) grid_round.add_widget(self.round_counter) grid_round.add_widget(increase_round) round_parent_grid.add_widget(grid_round) # COMMAND POINTS cp_parent_grid = MDGridLayout() cp_parent_grid.cols = 1 cp_parent_grid.rows = 2 cp_parent_grid.adaptive_height = True cp_label = MDLabel(text='Command Points Left:') cp_label.halign = 'center' cp_parent_grid.add_widget(cp_label) app_grid.add_widget(cp_parent_grid) grid_cp = MDGridLayout() grid_cp.cols = 3 increase_cp = MDIconButton(icon="arrow-right-bold", on_press=self.increase_cp) self.cp_counter = MDLabel(text=str(self.loaded_values[1])) self.cp_counter.halign = 'center' self.cp_counter.valign = 'middle' decrease_cp = MDIconButton(icon="arrow-left-bold", on_press=self.decrease_cp) grid_cp.add_widget(decrease_cp) grid_cp.add_widget(self.cp_counter) grid_cp.add_widget(increase_cp) cp_parent_grid.add_widget(grid_cp) # VP PRIMARY prim_parent_grid = MDGridLayout() prim_parent_grid.cols = 1 prim_parent_grid.rows = 2 prim_parent_grid.adaptive_height = True prim_label = MDLabel(text='Primary Objective Points:') prim_label.halign = 'center' prim_parent_grid.add_widget(prim_label) app_grid.add_widget(prim_parent_grid) grid_prim = MDGridLayout() grid_prim.cols = 3 increase_prim = MDIconButton(icon="arrow-right-bold", on_press=self.increase_prim) self.prim_counter = MDLabel(text=str(self.loaded_values[2])) self.prim_counter.halign = 'center' self.prim_counter.valign = 'middle' decrease_prim = MDIconButton(icon="arrow-left-bold", on_press=self.decrease_prim) grid_prim.add_widget(decrease_prim) grid_prim.add_widget(self.prim_counter) grid_prim.add_widget(increase_prim) prim_parent_grid.add_widget(grid_prim) # VP SECONDARY 1 sec1_parent_grid = MDGridLayout() sec1_parent_grid.cols = 1 sec1_parent_grid.rows = 2 sec1_parent_grid.adaptive_height = True sec1_label = MDTextField() sec1_label.hint_text = '1st Secondary Objective Points:' sec1_label.multiline = False #sec1_label = MDLabel(text='1st Secondary Objective Points:') sec1_label.halign = 'center' sec1_parent_grid.add_widget(sec1_label) app_grid.add_widget(sec1_parent_grid) grid_sec1 = MDGridLayout() grid_sec1.cols = 3 increase_sec1 = MDIconButton(icon="arrow-right-bold", on_press=self.increase_sec1) self.sec1_counter = MDLabel(text=str(self.loaded_values[3])) self.sec1_counter.halign = 'center' self.sec1_counter.valign = 'middle' decrease_sec1 = MDIconButton(icon="arrow-left-bold", on_press=self.decrease_sec1) grid_sec1.add_widget(decrease_sec1) grid_sec1.add_widget(self.sec1_counter) grid_sec1.add_widget(increase_sec1) sec1_parent_grid.add_widget(grid_sec1) # VP SECONDARY 2 sec2_parent_grid = MDGridLayout() sec2_parent_grid.cols = 1 sec2_parent_grid.rows = 2 sec2_parent_grid.adaptive_height = True sec2_label = MDTextField() sec2_label.hint_text = '2nd Secondary Objective Points:' sec2_label.multiline = False #sec2_label = MDLabel(text='2nd Secondary Objective Points:') sec2_label.halign = 'center' sec2_parent_grid.add_widget(sec2_label) app_grid.add_widget(sec2_parent_grid) grid_sec2 = MDGridLayout() grid_sec2.cols = 3 increase_sec2 = MDIconButton(icon="arrow-right-bold", on_press=self.increase_sec2) self.sec2_counter = MDLabel(text=str(self.loaded_values[4])) self.sec2_counter.halign = 'center' self.sec2_counter.valign = 'middle' decrease_sec2 = MDIconButton(icon="arrow-left-bold", on_press=self.decrease_sec2) grid_sec2.add_widget(decrease_sec2) grid_sec2.add_widget(self.sec2_counter) grid_sec2.add_widget(increase_sec2) sec2_parent_grid.add_widget(grid_sec2) # VP SECONDARY 3 sec3_parent_grid = MDGridLayout() sec3_parent_grid.cols = 1 sec3_parent_grid.rows = 2 sec3_parent_grid.adaptive_height = True sec3_label = MDTextField() sec3_label.hint_text = '3rd Secondary Objective Points:' sec3_label.multiline = False #sec3_label = MDLabel(text='3rd Secondary Objective Points:') sec3_label.halign = 'center' sec3_parent_grid.add_widget(sec3_label) app_grid.add_widget(sec3_parent_grid) grid_sec3 = MDGridLayout() grid_sec3.cols = 3 increase_sec3 = MDIconButton(icon="arrow-right-bold", on_press=self.increase_sec3) self.sec3_counter = MDLabel(text=str(self.loaded_values[5])) self.sec3_counter.halign = 'center' self.sec3_counter.valign = 'middle' decrease_sec3 = MDIconButton(icon="arrow-left-bold", on_press=self.decrease_sec3) grid_sec3.add_widget(decrease_sec3) grid_sec3.add_widget(self.sec3_counter) grid_sec3.add_widget(increase_sec3) sec3_parent_grid.add_widget(grid_sec3) # Empty grid to create space empty_grid = MDGridLayout() app_grid.add_widget(empty_grid) # Bottom grid for Score and Reset buttons bottom_grid = MDGridLayout() bottom_grid.cols = 2 app_grid.add_widget(bottom_grid) # SCORE TOAST score_button = MDFillRoundFlatIconButton(icon='flag-plus-outline', text="Show score", on_press=self.sum_up) button_anchor = AnchorLayout() button_anchor.anchor_y = 'bottom' button_anchor.add_widget(score_button) bottom_grid.add_widget(button_anchor) # RESET reset_button = MDFillRoundFlatIconButton(icon='backup-restore', text="Reset", on_press=self.reset_values) reset_button_anchor = AnchorLayout() reset_button_anchor.anchor_y = 'bottom' reset_button_anchor.add_widget(reset_button) bottom_grid.add_widget(reset_button_anchor) return screen_manager def menu_open(self, obj): self.menu.open() def increase_round(self, obj): if self.loaded_values[0] <= 4: self.loaded_values[0] += 1 self.loaded_values[1] += 1 self.round_counter.text = str(self.loaded_values[0]) self.cp_counter.text = str(self.loaded_values[1]) else: pass def decrease_round(self, obj): if self.loaded_values[0] >= 2: self.loaded_values[0] -= 1 if self.loaded_values[1] > 0: self.loaded_values[1] -= 1 self.round_counter.text = str(self.loaded_values[0]) self.cp_counter.text = str(self.loaded_values[1]) else: pass def increase_cp(self, obj): if self.loaded_values[1] <= 255: self.loaded_values[1] += 1 self.cp_counter.text = str(self.loaded_values[1]) else: pass def decrease_cp(self, obj): if self.loaded_values[1] >= 1: self.loaded_values[1] -= 1 self.cp_counter.text = str(self.loaded_values[1]) else: pass def increase_prim(self, obj): if self.loaded_values[2] <= 119: self.loaded_values[2] += 5 self.prim_counter.text = str(self.loaded_values[2]) else: pass def decrease_prim(self, obj): if self.loaded_values[2] >= 1: self.loaded_values[2] -= 5 self.prim_counter.text = str(self.loaded_values[2]) else: pass def increase_sec1(self, obj): if self.loaded_values[3] <= 14: self.loaded_values[3] += 1 self.sec1_counter.text = str(self.loaded_values[3]) else: pass def decrease_sec1(self, obj): if self.loaded_values[3] >= 1: self.loaded_values[3] -= 1 self.sec1_counter.text = str(self.loaded_values[3]) else: pass def increase_sec2(self, obj): if self.loaded_values[4] <= 14: self.loaded_values[4] += 1 self.sec2_counter.text = str(self.loaded_values[4]) else: pass def decrease_sec2(self, obj): if self.loaded_values[4] >= 1: self.loaded_values[4] -= 1 self.sec2_counter.text = str(self.loaded_values[4]) else: pass def increase_sec3(self, obj): if self.loaded_values[5] <= 14: self.loaded_values[5] += 1 self.sec3_counter.text = str(self.loaded_values[5]) else: pass def decrease_sec3(self, obj): if self.loaded_values[5] >= 1: self.loaded_values[5] -= 1 self.sec3_counter.text = str(self.loaded_values[5]) else: pass def sum_up(self, obj): final_score = 0 o = 2 while o <= 5: final_score += self.loaded_values[o] o += 1 toast("Final score is: " + str(final_score)) def update_values(self): try: file = open("Krowbar.txt", "r") z = 0 for x in file: self.loaded_values[z] = (int(x)) z += 1 file.close() except FileNotFoundError: file = open("Krowbar.txt", "x") file.close() def on_stop(self): self.save(obj=None) def save(self, obj): file = open("Krowbar.txt", "w") for i in self.loaded_values: file.write((str(i) + '\n')) file.close() def reset_values(self, obj): self.loaded_values = [1, 0, 0, 0, 0, 0] self.round_counter.text = str(self.loaded_values[0]) self.cp_counter.text = str(self.loaded_values[1]) self.prim_counter.text = str(self.loaded_values[2]) self.sec1_counter.text = str(self.loaded_values[3]) self.sec2_counter.text = str(self.loaded_values[4]) self.sec3_counter.text = str(self.loaded_values[5]) def menu_callback(self, menu_item): if menu_item.text == "Loyal Angels Green": self.loyal_angels_green() if menu_item.text == "Space Doggos Gray": self.cosmic_doggos_gray() if menu_item.text == "Vampire Angels Red": self.angel_red() if menu_item.text == "Gray Nights": self.gray_nights() if menu_item.text == "Stubborn Fists Yellow": self.fists_yellow() if menu_item.text == "Ceramic White": self.ceramic_white() if menu_item.text == "Codex Blue": self.codex_blue() def loyal_angels_green(self): self.active_color = [0, 25.1 / 100, 12.16 / 100, 1] self.menu_button.md_bg_color = (11.76 / 100, 45.1 / 100, 19.22 / 100, 1) self.theme_cls.primary_palette = "Green" self.theme_cls.primary_hue = "600" self.change_bg_color() self.reset_canvas_contents() def fists_yellow(self): self.active_color = [99.22 / 100, 72.16 / 100, 14.51 / 100, 1] self.menu_button.md_bg_color = (76.08 / 100, 9.8 / 100, 12.16 / 100, 1) self.theme_cls.primary_palette = "DeepOrange" self.theme_cls.primary_hue = "700" self.change_bg_color() self.reset_canvas_contents() def codex_blue(self): self.active_color = [5.1 / 100, 25.1 / 100, 49.8 / 100, 1] self.menu_button.md_bg_color = (25.88 / 100, 44.71 / 100, 72.16 / 100, 1) self.theme_cls.primary_palette = "Red" self.theme_cls.primary_hue = "700" self.change_bg_color() self.reset_canvas_contents() def gray_nights(self): self.active_color = [56.47 / 100, 65.88 / 100, 65.88 / 100, 1] self.menu_button.md_bg_color = (78.04 / 100, 87.84 / 100, 85.1 / 100, 1) self.theme_cls.primary_palette = "BlueGray" self.theme_cls.primary_hue = "900" self.change_bg_color() self.reset_canvas_contents() def angel_red(self): self.active_color = [60.39 / 100, 6.67 / 100, 8.24 / 100, 1] self.menu_button.md_bg_color = (76.08 / 100, 9.8 / 100, 12.16 / 100, 1) self.theme_cls.primary_palette = "Orange" self.theme_cls.primary_hue = "800" self.change_bg_color() self.reset_canvas_contents() def cosmic_doggos_gray(self): self.active_color = [32.94 / 100, 45.88 / 100, 53.33 / 100, 1] self.menu_button.md_bg_color = (44.31 / 100, 60.78 / 100, 71.76 / 100, 1) self.theme_cls.primary_palette = "BlueGray" self.theme_cls.primary_hue = "900" self.change_bg_color() self.reset_canvas_contents() def ceramic_white(self): self.active_color = [1, 1, 1, 1] self.menu_button.md_bg_color = (1, 1, 1, 1) self.theme_cls.primary_palette = "Gray" self.theme_cls.primary_hue = "800" self.change_bg_color() self.reset_canvas_contents() def change_bg_color(self): with self.counters.canvas: Color(rgba=self.active_color) self.r = Rectangle(pos=(0, 0), size=Window.size) def reset_canvas_contents(self): self.counters.remove_widget(self.scroll) self.counters.add_widget(self.scroll) self.counters.remove_widget(self.menu_button) self.counters.add_widget(self.menu_button) def wakawaka(self): print("waka waka")
class InfoPopup(FloatLayout): def __init__(self, address, **kwargs): self.ad = address self.font_size = kwargs.pop('font_size', 30) self.dic = kwargs.pop('dic', None) self.ffList = kwargs.pop('ffList', None) self.fmList = kwargs.pop('fmList', None) self.root = kwargs.pop('root', None) self.origine = kwargs.pop('origine', None) if self.ffList == None: self.ffList = updatelist()[0] self.fmList = updatelist()[1] if len(kwargs) > 0: raise Exception("[ERROR] argument enter not accpeted") def show(self, source): self.source = source #print("source ",source) self.f = FloatLayout() back = Button(disabled=True, pos_hint={ 'x': 0, 'y': 0 }, size_hint=(1, 1), text="", background_normal='', background_color=(0, 0, 0, 0.5)) back.background_disabled_normal = '' back.disabled_color = (0, 0, 0, 0.5) layer_w = Button(disabled=True, pos_hint={ 'x': 0.1, 'y': 0.1 }, size_hint=(0.8, 0.8), text="", background_normal='', background_color=(1, 1, 1, 1)) layer_w.background_disabled_normal = '' layer_w.disabled_color = (0, 0, 1, 1) Parents = Label(text='Parents', font_size=self.font_size + 1, pos_hint={ 'center_x': .2, 'center_y': .85 }, color=(0, 0, 0, 1)) PM = Button(pos_hint={ 'x': 0.2, 'y': 0.5 }, size_hint=(0.3, 0.3), text="", background_normal='', background_color=(0, 0, 1, 0.6)) PM.bind(on_release=self.show_caller_inner) PF = Button(pos_hint={ 'x': 0.5, 'y': 0.5 }, size_hint=(0.3, 0.3), text="", background_normal='', background_color=(1, 0, 0, 0.6)) PF.bind(on_release=self.show_caller_inner) fermer = Button(pos_hint={ 'x': 0.75, 'y': 0.8 }, size_hint=(0.1, 0.1), text="FERMER", background_normal='', color=(0, 0, 0, 1), background_color=(1, 1, 1, 0)) fermer.bind(on_release=self.fermer) Genre_data = 'Femmelle' for i in range(len(self.fmList)): #print(self.fmList[i]['name'] ,'vs', self.source['name'] ,'and', self.fmList[i]['num'] ,'vs', self.source['num']) if self.fmList[i]['name'] == self.source['name'] and self.fmList[ i]['num'] == self.source['num']: Genre_data = 'Mâle' break Nom = Label(text=source['name'], font_size=self.font_size, pos_hint={ 'center_x': .4, 'center_y': .45 }, color=(0, 0, 0, 1)) Num = Label(text=source['num'], font_size=self.font_size - 1, pos_hint={ 'center_x': .35, 'center_y': .4 }, color=(0, 0, 0, 1)) Genre = Label(text=Genre_data, font_size=self.font_size - 1, pos_hint={ 'center_x': .7, 'center_y': .4 }, color=(0, 0, 0, 1)) Nom_i = Label(text='Nom', font_size=self.font_size - 1, pos_hint={ 'center_x': .15, 'center_y': .45 }, color=(0, 0, 0, 0.8)) Num_i = Label(text='Num', font_size=self.font_size - 1, pos_hint={ 'center_x': .15, 'center_y': .4 }, color=(0, 0, 0, 0.8)) Genre_i = Label(text='Genre', font_size=self.font_size - 1, pos_hint={ 'center_x': .55, 'center_y': .4 }, color=(0, 0, 0, 0.8)) Nb_petits = Label(text='Total petits', font_size=self.font_size, pos_hint={ 'center_x': .25, 'center_y': .3 }, color=(0, 0, 0, 0.8)) Nb_petits_ans = Label(text='Petits par ans', font_size=self.font_size, pos_hint={ 'center_x': .5, 'center_y': .3 }, color=(0, 0, 0, 0.8)) modifier = Button(pos_hint={ 'x': 0.55, 'y': 0.8 }, font_size=self.font_size, size_hint=(0.1, 0.1), text="MODIFIER", background_normal='', color=(0, 0, 0, 1), background_color=(1, 1, 1, 0)) modifier.bind(on_release=self.edit) self.f.add_widget(back) self.f.add_widget(layer_w) self.Button_ID = {'M': PM, 'F': PF} self.f.add_widget(PM) self.f.add_widget(PF) if 'PM' in source and source['PM'] != 'Aucun': Nom_PM = Label(text=str(source['PM']['name']), font_size=self.font_size, pos_hint={ 'center_x': .3, 'center_y': .7 }, color=(0, 0, 0, 1)) Num_PM = Label(text=str(source['PM']['num']), font_size=self.font_size - 1, pos_hint={ 'center_x': .35, 'center_y': .6 }, color=(0, 0, 0, 1)) self.f.add_widget(Nom_PM) self.f.add_widget(Num_PM) else: Nom_PM = Label(text='Aucun', font_size=self.font_size, pos_hint={ 'center_x': .3, 'center_y': .7 }, color=(0, 0, 0, 1)) Num_PM = Label(text='', font_size=self.font_size - 1, pos_hint={ 'center_x': .3, 'center_y': .6 }, color=(0, 0, 0, 1)) self.f.add_widget(Nom_PM) self.f.add_widget(Num_PM) if 'PF' in source and source['PF'] != 'Aucun': Nom_PF = Label(text=str(source['PF']['name']), font_size=self.font_size, pos_hint={ 'center_x': .6, 'center_y': .7 }, color=(0, 0, 0, 1)) Num_PF = Label(text=str(source['PF']['num']), font_size=self.font_size - 1, pos_hint={ 'center_x': .65, 'center_y': .6 }, color=(0, 0, 0, 1)) self.f.add_widget(Nom_PF) self.f.add_widget(Num_PF) else: Nom_PF = Label(text='Aucun', font_size=self.font_size, pos_hint={ 'center_x': .6, 'center_y': .7 }, color=(0, 0, 0, 1)) Num_PF = Label(text='', font_size=self.font_size - 1, pos_hint={ 'center_x': .6, 'center_y': .55 }, color=(0, 0, 0, 1)) self.f.add_widget(Nom_PF) self.f.add_widget(Num_PF) if 'NBP' in source and source['NBP'] != []: #print("scollview", len(source['NBP']), 'size', len(source['NBP'])*0.35 ) s = ScrollView(size_hint=(0.5, 0.1), do_scroll_y=False, do_scroll_x=True, pos_hint={ 'center_x': .6, 'center_y': .2 }) sizex = 0.25 g = FloatLayout(size_hint=(len(source['NBP']) * 0.35, 1)) COUNT = 0 for i in range(len(source['NBP'])): COUNT += int(source['NBP'][i]['nombre']) print(sizex * i, sizex) g.add_widget( Button(background_normal='', background_color=(0, 0, 0, 0.4), text=str(source['NBP'][i]['anne']) + '\n' + str(source['NBP'][i]['nombre']), color=(0, 0, 0, 1), pos_hint={'x': 1 / len(self.source['NBP']) * i}, size_hint=(1 / len(source['NBP']), 1))) s.add_widget(g) self.f.add_widget(s) total = Label(text=str(COUNT), font_size=self.font_size - 5, pos_hint={ 'center_x': .2, 'center_y': .2 }, color=(0, 0, 0, 1)) self.f.add_widget(total) self.f.add_widget(Parents) self.f.add_widget(Nb_petits) self.f.add_widget(Nb_petits_ans) self.f.add_widget(fermer) self.f.add_widget(modifier) self.f.add_widget(Nom) self.f.add_widget(Num) self.f.add_widget(Genre) self.f.add_widget(Nom_i) self.f.add_widget(Num_i) self.f.add_widget(Genre_i) self.ad.add_widget(self.f) def edit(self, instance=None): self.fermer() source = self.source self.source_old = self.source #print("source ",source) self.f = FloatLayout() back = Button(disabled=True, pos_hint={ 'x': 0, 'y': 0 }, size_hint=(1, 1), text="", background_normal='', background_color=(0, 0, 0, 0.5)) back.background_disabled_normal = '' back.disabled_color = (0, 0, 0, 0.5) layer_w = Button(disabled=True, pos_hint={ 'x': 0.1, 'y': 0.1 }, size_hint=(0.8, 0.8), text="", background_normal='', background_color=(1, 1, 1, 1)) layer_w.background_disabled_normal = '' layer_w.disabled_color = (0, 0, 1, 1) Parents = Label(text='Parents', font_size=self.font_size + 1, pos_hint={ 'center_x': .2, 'center_y': .85 }, color=(0, 0, 0, 1)) PM = Button(pos_hint={ 'x': 0.2, 'y': 0.5 }, size_hint=(0.3, 0.3), text="", background_normal='', background_color=(0, 0, 1, 0.6)) PF = Button(pos_hint={ 'x': 0.5, 'y': 0.5 }, size_hint=(0.3, 0.3), text="", background_normal='', background_color=(1, 0, 0, 0.6)) fermer = Button(pos_hint={ 'x': 0.75, 'y': 0.8 }, size_hint=(0.1, 0.1), text="FERMER", background_normal='', color=(0, 0, 0, 1), background_color=(1, 1, 1, 0)) fermer.bind(on_release=self.fermer) Genre_data = 'Femmelle' for i in range(len(self.fmList)): #print(self.fmList[i]['name'] ,'vs', self.source['name'] ,'and', self.fmList[i]['num'] ,'vs', self.source['num']) if self.fmList[i]['name'] == self.source['name'] and self.fmList[ i]['num'] == self.source['num']: Genre_data = 'Mâle' break self.genre_old = Genre_data self.Nom = MDTextField(text=source['name'], font_size=self.font_size, size_hint=(0.4, 0.1), pos_hint={ 'center_x': .4, 'center_y': .45 }) self.Num = MDTextField(text=source['num'], font_size=self.font_size, size_hint=(0.32, 0.1), pos_hint={ 'center_x': .36, 'center_y': .4 }) Genre = MDDropDownItem(font_size=self.font_size - 3, pos_hint={ 'center_x': .76, 'center_y': .405 }) Genre.text = Genre_data self.Genre = Genre self.menuG = MDDropdownMenu( caller=Genre, items=[{ 'text': 'Femmelle' }, { 'text': 'Mâle' }], position="auto", width_mult=4, callback=self.GS, ) Genre.bind(on_release=self.menuG_open) Nom_i = Label(text='Nom', font_size=self.font_size - 1, pos_hint={ 'center_x': .15, 'center_y': .45 }, color=(0, 0, 0, 0.8)) Num_i = Label(text='Num', font_size=self.font_size - 1, pos_hint={ 'center_x': .15, 'center_y': .4 }, color=(0, 0, 0, 0.8)) Genre_i = Label(text='Genre', font_size=self.font_size - 1, pos_hint={ 'center_x': .59, 'center_y': .4 }, color=(0, 0, 0, 0.8)) Nb_petits = Label(text='Total petits', font_size=self.font_size, pos_hint={ 'center_x': .25, 'center_y': .35 }, color=(0, 0, 0, 0.8)) Nb_petits_ans = Label(text='Petits par ans', font_size=self.font_size, pos_hint={ 'center_x': .5, 'center_y': .35 }, color=(0, 0, 0, 0.8)) modifier = Button(pos_hint={ 'x': 0.55, 'y': 0.8 }, font_size=self.font_size, size_hint=(0.1, 0.1), text="VALIDER", background_normal='', color=(0, 0, 0, 1), background_color=(1, 1, 1, 0)) modifier.bind(on_release=self.edit_valider) self.f.add_widget(back) self.f.add_widget(layer_w) self.Button_ID = {'M': PM, 'F': PF} self.f.add_widget(PM) self.f.add_widget(PF) DM = MDDropDownItem(text='', pos_hint={ 'center_x': 0.3, 'center_y': 0.6 }) DM.text = 'Aucun' DM.bind(on_release=self.DM_OPEN) #print('drpo male',[{'text':str(self.fmList[i]['name'])+'\n'+str(self.fmList[i]['num'])} for i in range(len(self.fmList))]) item = [{ 'text': str(self.fmList[i]['name']) + '\n' + str(self.fmList[i]['num']) } for i in range(len(self.fmList))] item.append({'text': 'Aucun'}) self.menuM = MDDropdownMenu( caller=DM, items=item, position="auto", width_mult=4, callback=self.DM_SEL, ) self.DM = DM DF = MDDropDownItem(text='', pos_hint={ 'center_x': 0.6, 'center_y': 0.6 }) DF.text = 'Aucun' DF.bind(on_release=self.DF_OPEN) self.DF = DF #print([{'text':str(self.ffList[i]['name'])+'\n'+str(self.ffList[i]['num'])} for i in range(len(self.ffList))]) item = [{ 'text': str(self.ffList[i]['name']) + '\n' + str(self.ffList[i]['num']) } for i in range(len(self.ffList))] item.append({'text': 'Aucun'}) self.menuF = MDDropdownMenu( caller=DF, items=item, position="auto", width_mult=4, callback=self.DF_SEL, ) self.anne = MDTextField(size_hint=(0.2, 0.1), font_size=self.font_size - 2, pos_hint={ 'center_x': .65, 'center_y': .29 }) self.anne.hint_text = 'Année' self.nb = MDTextField(size_hint=(0.2, 0.1), font_size=self.font_size - 2, pos_hint={ 'center_x': .3, 'center_y': .29 }) self.nb.hint_text = 'Nombre' add = MDIconButton(icon="plus", pos_hint={ "center_x": .875, "center_y": .3 }) add.bind(on_release=self.add_NBP) self.f.add_widget(self.anne) self.f.add_widget(self.nb) self.f.add_widget(add) if 'PM' in source and source['PM'] != 'Aucun': DM.text = str(source['PM']['name']) + '\n' + str( source['PM']['num']) else: DM.text = str('Aucun') if 'PF' in source and source['PF'] != 'Aucun': DF.text = str(source['PF']['name']) + '\n' + str( source['PF']['num']) else: DF.text = str('Aucun') s = ScrollView(size_hint=(0.5, 0.1), do_scroll_y=False, do_scroll_x=True, pos_hint={ 'center_x': .6, 'center_y': .2 }) self.s = s self.total = Label(text=str(0), font_size=self.font_size - 5, pos_hint={ 'center_x': .2, 'center_y': .2 }, color=(0, 0, 0, 1)) self.f.add_widget(self.total) #if 'NBP' in source and source['NBP'] != []: self.s.clear_widgets() if 'NBP' in source: #print("scollview", len(source['NBP']), 'size', len(source['NBP'])*0.35 ) sizex = 0.25 g = FloatLayout(size_hint=(len(source['NBP']) * 0.35, 1)) COUNT = 0 self.cross = {} for i in range(len(source['NBP'])): COUNT += int(source['NBP'][i]['nombre']) #print(sizex*i,sizex) y = MDIconButton(icon='close-outline', pos_hint={ 'x': 1 / len(self.source['NBP']) * i + 0.15, 'y': -0.15 }, size_hint=(1 / len(source['NBP']), 1)) y.bind(on_release=self.delete_date) self.cross[y] = i g.add_widget( Button(background_normal='', background_color=(0, 0, 0, 0.4), text=str(source['NBP'][i]['anne']) + '\n' + str(source['NBP'][i]['nombre']), color=(0, 0, 0, 1), pos_hint={'x': 1 / len(self.source['NBP']) * i}, size_hint=(1 / len(source['NBP']), 1))) g.add_widget(y) s.add_widget(g) self.total.text = str(COUNT) #self.f.add_widget(self.total) self.f.add_widget(s) self.f.add_widget(Parents) self.f.add_widget(Nb_petits) self.f.add_widget(Nb_petits_ans) self.f.add_widget(fermer) self.f.add_widget(modifier) self.f.add_widget(self.Nom) self.f.add_widget(self.Num) self.f.add_widget(Genre) self.f.add_widget(Nom_i) self.f.add_widget(Num_i) self.f.add_widget(Genre_i) self.f.add_widget(DM) self.f.add_widget(DF) self.ad.add_widget(self.f) def addP(self, root=None): self.up = root source = { 'name': '', 'num': '', 'PF': 'Aucun', 'PM': 'Aucun', 'NBP': [] } self.source = source self.source_old = self.source #print("source ",source) self.f = FloatLayout() back = Button(disabled=True, pos_hint={ 'x': 0, 'y': 0 }, size_hint=(1, 1), text="", background_normal='', background_color=(0, 0, 0, 0.5)) back.background_disabled_normal = '' back.disabled_color = (0, 0, 0, 0.5) layer_w = Button(disabled=True, pos_hint={ 'x': 0.1, 'y': 0.1 }, size_hint=(0.8, 0.8), text="", background_normal='', background_color=(1, 1, 1, 1)) layer_w.background_disabled_normal = '' layer_w.disabled_color = (0, 0, 1, 1) Parents = Label(text='Parents', font_size=self.font_size + 1, pos_hint={ 'center_x': .2, 'center_y': .85 }, color=(0, 0, 0, 1)) PM = Button(pos_hint={ 'x': 0.2, 'y': 0.5 }, size_hint=(0.3, 0.3), text="", background_normal='', background_color=(0, 0, 1, 0.6)) PF = Button(pos_hint={ 'x': 0.5, 'y': 0.5 }, size_hint=(0.3, 0.3), text="", background_normal='', background_color=(1, 0, 0, 0.6)) fermer = Button(pos_hint={ 'x': 0.75, 'y': 0.8 }, size_hint=(0.1, 0.1), text="FERMER", background_normal='', color=(0, 0, 0, 1), background_color=(1, 1, 1, 0)) fermer.bind(on_release=self.fermer) Genre_data = 'Femmelle' for i in range(len(self.fmList)): #print(self.fmList[i]['name'] ,'vs', self.source['name'] ,'and', self.fmList[i]['num'] ,'vs', self.source['num']) if self.fmList[i]['name'] == self.source['name'] and self.fmList[ i]['num'] == self.source['num']: Genre_data = 'Mâle' break self.genre_old = Genre_data self.Nom = MDTextField(text=source['name'], font_size=self.font_size, size_hint=(0.4, 0.1), pos_hint={ 'center_x': .4, 'center_y': .45 }) self.Num = MDTextField(text=source['num'], font_size=self.font_size, size_hint=(0.32, 0.1), pos_hint={ 'center_x': .36, 'center_y': .4 }) Genre = MDDropDownItem(font_size=self.font_size - 3, pos_hint={ 'center_x': .76, 'center_y': .405 }) Genre.text = Genre_data self.Genre = Genre self.menuG = MDDropdownMenu( caller=Genre, items=[{ 'text': 'Femmelle' }, { 'text': 'Mâle' }], position="auto", width_mult=4, callback=self.GS, ) Genre.bind(on_release=self.menuG_open) Nom_i = Label(text='Nom', font_size=self.font_size - 1, pos_hint={ 'center_x': .15, 'center_y': .45 }, color=(0, 0, 0, 0.8)) Num_i = Label(text='Num', font_size=self.font_size - 1, pos_hint={ 'center_x': .15, 'center_y': .4 }, color=(0, 0, 0, 0.8)) Genre_i = Label(text='Genre', font_size=self.font_size - 1, pos_hint={ 'center_x': .59, 'center_y': .4 }, color=(0, 0, 0, 0.8)) Nb_petits = Label(text='Total petits', font_size=self.font_size, pos_hint={ 'center_x': .25, 'center_y': .35 }, color=(0, 0, 0, 0.8)) Nb_petits_ans = Label(text='Petits par ans', font_size=self.font_size, pos_hint={ 'center_x': .5, 'center_y': .35 }, color=(0, 0, 0, 0.8)) modifier = Button(pos_hint={ 'x': 0.55, 'y': 0.8 }, font_size=self.font_size, size_hint=(0.1, 0.1), text="VALIDER", background_normal='', color=(0, 0, 0, 1), background_color=(1, 1, 1, 0)) modifier.bind(on_release=self.new_valider) self.f.add_widget(back) self.f.add_widget(layer_w) self.Button_ID = {'M': PM, 'F': PF} self.f.add_widget(PM) self.f.add_widget(PF) DM = MDDropDownItem(text='', pos_hint={ 'center_x': 0.3, 'center_y': 0.6 }) DM.text = 'Aucun' DM.bind(on_release=self.DM_OPEN) #print('drpo male',[{'text':str(self.fmList[i]['name'])+'\n'+str(self.fmList[i]['num'])} for i in range(len(self.fmList))]) item = [{ 'text': str(self.fmList[i]['name']) + '\n' + str(self.fmList[i]['num']) } for i in range(len(self.fmList))] item.append({'text': 'Aucun'}) self.menuM = MDDropdownMenu( caller=DM, items=item, position="auto", width_mult=4, callback=self.DM_SEL, ) self.DM = DM DF = MDDropDownItem(text='', pos_hint={ 'center_x': 0.6, 'center_y': 0.6 }) DF.text = 'Aucun' DF.bind(on_release=self.DF_OPEN) self.DF = DF #print([{'text':str(self.ffList[i]['name'])+'\n'+str(self.ffList[i]['num'])} for i in range(len(self.ffList))]) item = [{ 'text': str(self.ffList[i]['name']) + '\n' + str(self.ffList[i]['num']) } for i in range(len(self.ffList))] item.append({'text': 'Aucun'}) self.menuF = MDDropdownMenu( caller=DF, items=item, position="auto", width_mult=4, callback=self.DF_SEL, ) self.anne = MDTextField(size_hint=(0.2, 0.1), font_size=self.font_size - 2, pos_hint={ 'center_x': .65, 'center_y': .29 }) self.anne.hint_text = 'Année' self.nb = MDTextField(size_hint=(0.2, 0.1), font_size=self.font_size - 2, pos_hint={ 'center_x': .3, 'center_y': .29 }) self.nb.hint_text = 'Nombre' add = MDIconButton(icon="plus", pos_hint={ "center_x": .875, "center_y": .3 }) add.bind(on_release=self.add_NBP) self.f.add_widget(self.anne) self.f.add_widget(self.nb) self.f.add_widget(add) if 'PM' in source and source['PM'] != 'Aucun': DM.text = str(source['PM']['name']) + '\n' + str( source['PM']['num']) else: DM.text = str('Aucun') if 'PF' in source and source['PF'] != 'Aucun': DF.text = str(source['PF']['name']) + '\n' + str( source['PF']['num']) else: DF.text = str('Aucun') s = ScrollView(size_hint=(0.5, 0.1), do_scroll_y=False, do_scroll_x=True, pos_hint={ 'center_x': .6, 'center_y': .2 }) self.s = s self.total = Label(text=str(0), font_size=self.font_size - 5, pos_hint={ 'center_x': .2, 'center_y': .2 }, color=(0, 0, 0, 1)) self.f.add_widget(self.total) #if 'NBP' in source and source['NBP'] != []: self.s.clear_widgets() if 'NBP' in source: #print("scollview", len(source['NBP']), 'size', len(source['NBP'])*0.35 ) sizex = 0.25 g = FloatLayout(size_hint=(len(source['NBP']) * 0.35, 1)) COUNT = 0 self.cross = {} for i in range(len(source['NBP'])): COUNT += int(source['NBP'][i]['nombre']) #print(sizex*i,sizex) y = MDIconButton(icon='close-outline', pos_hint={ 'x': 1 / len(self.source['NBP']) * i + 0.15, 'y': -0.15 }, size_hint=(1 / len(source['NBP']), 1)) y.bind(on_release=self.delete_date) self.cross[y] = i g.add_widget( Button(background_normal='', background_color=(0, 0, 0, 0.4), text=str(source['NBP'][i]['anne']) + '\n' + str(source['NBP'][i]['nombre']), color=(0, 0, 0, 1), pos_hint={'x': 1 / len(self.source['NBP']) * i}, size_hint=(1 / len(source['NBP']), 1))) g.add_widget(y) s.add_widget(g) self.total.text = str(COUNT) #self.f.add_widget(self.total) self.f.add_widget(s) self.f.add_widget(Parents) self.f.add_widget(Nb_petits) self.f.add_widget(Nb_petits_ans) self.f.add_widget(fermer) self.f.add_widget(modifier) self.f.add_widget(self.Nom) self.f.add_widget(self.Num) self.f.add_widget(Genre) self.f.add_widget(Nom_i) self.f.add_widget(Num_i) self.f.add_widget(Genre_i) self.f.add_widget(DM) self.f.add_widget(DF) self.ad.add_widget(self.f) def delete_date(self, instance): #print(self.cross[instance]) self.source['NBP'].pop(self.cross[instance]) s = self.s s.clear_widgets() sizex = 0.25 #print(len(self.source['NBP']),len(self.source['NBP'])*0.35, ) g = FloatLayout(size_hint=(len(self.source['NBP']) * 0.35, 1)) COUNT = 0 self.cross = {} for i in range(len(self.source['NBP'])): COUNT += int(self.source['NBP'][i]['nombre']) #print(sizex*i,sizex) y = MDIconButton(icon='close-outline', pos_hint={ 'x': 1 / len(self.source['NBP']) * i + 0.2 * (1 / len(self.source['NBP'])), 'y': -0.15 }, size_hint=(1 / len(self.source['NBP']), 1)) y.bind(on_release=self.delete_date) self.cross[y] = i g.add_widget( Button(background_normal='', background_color=(0, 0, 0, 0.4), text=str(self.source['NBP'][i]['anne']) + '\n' + str(self.source['NBP'][i]['nombre']), color=(0, 0, 0, 1), pos_hint={'x': 1 / len(self.source['NBP']) * i}, size_hint=(1 / len(self.source['NBP']), 1))) g.add_widget(y) s.add_widget(g) #self.s =s self.total.text = str(COUNT) def add_NBP(self, instance=None): print(self.anne.text) chiffre = True if self.anne.text != '' and self.nb.text != '': try: x = int(self.anne.text) x = int(self.nb.text) except Exception as e: print(e, 'pas chiffre') self.origine.Snac("Assurez-vous d'entrer des chiffres") chiffre = False if chiffre == True: found = False if 'NBP' not in self.source: self.source['NBP'] = [] for i in range(len(self.source['NBP'])): #print('NBP' in self.source, int(self.anne.text) == self.source['NBP'][i]['anne']) if 'NBP' in self.source and int( self.anne.text) == self.source['NBP'][i]['anne']: self.source['NBP'][i]['nombre'] += int(self.nb.text) found = True break if 'NBP' in self.source and found == False: self.source['NBP'].append({ 'anne': int(self.anne.text), 'nombre': int(self.nb.text) }) elif found == False: self.source['NBP'] = [{ 'anne': int(self.anne.text), 'nombre': int(self.nb.text) }] s = self.s s.clear_widgets() sizex = 0.25 #print(len(self.source['NBP']),len(self.source['NBP'])*0.35, ) g = FloatLayout(size_hint=(len(self.source['NBP']) * 0.35, 1)) COUNT = 0 self.cross = {} for i in range(len(self.source['NBP'])): COUNT += int(self.source['NBP'][i]['nombre']) #print(sizex*i,sizex) y = MDIconButton(icon='close-outline', pos_hint={ 'x': 1 / len(self.source['NBP']) * i + 0.2 * (1 / len(self.source['NBP'])), 'y': -0.15 }, size_hint=(1 / len(self.source['NBP']), 1)) y.bind(on_release=self.delete_date) self.cross[y] = i g.add_widget( Button(background_normal='', background_color=(0, 0, 0, 0.4), text=str(self.source['NBP'][i]['anne']) + '\n' + str(self.source['NBP'][i]['nombre']), color=(0, 0, 0, 1), pos_hint={'x': 1 / len(self.source['NBP']) * i}, size_hint=(1 / len(self.source['NBP']), 1))) g.add_widget(y) s.add_widget(g) #self.s =s self.total.text = str(COUNT) else: self.origine.Snac("Veuillez remplir les champs") def new_valider(self, instance=None): if self.Genre.text == 'Mâle': M_F = 'M' else: M_F = 'F' name = str(self.Nom.text) num = str(self.Num.text) PM = 'Aucun' PF = 'Aucun' for i in range(len(self.fmList)): if self.fmList[i]['name'] + '\n' + self.fmList[i][ 'num'] == self.DM.text: PM = { 'name': self.fmList[i]['name'], 'num': self.fmList[i]['num'] } break for i in range(len(self.ffList)): if self.ffList[i]['name'] + '\n' + self.ffList[i][ 'num'] == self.DF.text: PF = { 'name': self.ffList[i]['name'], 'num': self.ffList[i]['num'] } break if 'NBP' in self.source: NBP = self.source['NBP'] else: NBP = [] print('new', (M_F, name, num, PF, PM, NBP)) list_write(M_F, name, num, PF, PM, NBP) self.fermer() self.ffList = updatelist()[0] self.fmList = updatelist()[1] self.up.update_t() thr.Thread(target=self.origine.up_drop_down).start() def edit_valider(self, instance=None): #print('old', self.genre_old, self.source_old) #print('new', self.Nom.text , self.Num.text, self.DF.text, self.DM.text, self.Genre.text) if self.genre_old == 'Mâle': M_F = 'M' else: M_F = 'F' name = self.source_old['name'] num = self.source_old['num'] list_remove(M_F, name, num) if self.Genre.text == 'Mâle': M_F = 'M' else: M_F = 'F' name = str(self.Nom.text) num = str(self.Num.text) PM = 'Aucun' PF = 'Aucun' for i in range(len(self.fmList)): if self.fmList[i]['name'] + '\n' + self.fmList[i][ 'num'] == self.DM.text: PM = { 'name': self.fmList[i]['name'], 'num': self.fmList[i]['num'] } break for i in range(len(self.ffList)): if self.ffList[i]['name'] + '\n' + self.ffList[i][ 'num'] == self.DF.text: PF = { 'name': self.ffList[i]['name'], 'num': self.ffList[i]['num'] } break if 'NBP' in self.source: NBP = self.source['NBP'] else: NBP = [] print('new', (M_F, name, num, PF, PM, NBP)) list_write(M_F, name, num, PF, PM, NBP) self.fermer() self.ffList = updatelist()[0] self.fmList = updatelist()[1] self.root.update_t() #self.ad.ST.build() thr.Thread(target=self.origine.up_drop_down).start() def DM_OPEN(self, instance): self.menuM.open() def DF_OPEN(self, instance): self.menuF.open() def DF_SEL(self, instance): self.DF.text = instance.text self.menuF.dismiss() def DM_SEL(self, instance): self.DM.text = instance.text self.menuM.dismiss() def fermer(self, instance=None): self.f.clear_widgets() def show_caller(self, instance=None): self.show(instance) def menuG_open(self, instance=None): self.menuG.open() def GS(self, instance=None): self.Genre.text = instance.text def show_caller_inner(self, instance): if instance == self.Button_ID['M']: #print('m') #print(self.source['PM']) if 'PM' in self.source: for i in range(len(self.fmList)): #print(self.fmList[i]['name'] ,'vs', self.source['PM']['name'] ,'and', self.fmList[i]['num'] ,'vs', self.source['PM']['num']) if self.fmList[i]['name'] == self.source['PM'][ 'name'] and self.fmList[i]['num'] == self.source[ 'PM']['num']: #print("break") break self.fermer() self.show(self.fmList[i]) else: if 'PF' in self.source: for i in range(len(self.ffList)): #print(self.ffList[i]['name'] ,'vs', self.source['PF']['name'] ,'and', self.ffList[i]['num'] ,'vs', self.source['PF']['num']) if self.ffList[i]['name'] == self.source['PF'][ 'name'] and self.ffList[i]['num'] == self.source[ 'PF']['num']: #print("break") break self.fermer() self.show(self.ffList[i])
class AddServiceScreen(Screen): dialog = None # with self.root.canvas: # Color(rgba=(.5, .5, .5)) # return self.root def create_service(self): services = ["Laundry", "Dry Cleaning", "Ironing"] menu_items = [{"text": str(i)} for i in services] self.menu = MDDropdownMenu( caller=self.ids['client_services'], items=menu_items, width_mult=4, ) self.menu.open() self.menu.bind(on_release=self.set_item) def set_item(self, instance_menu, instance_menu_item): print('inside menu callback') # self.ids['client_services'].hint_text = '' self.ids['client_services'].text = instance_menu_item.text instance_menu.dismiss() def select_date(self): print('inside select date') # date_dialog = MDDatePicker( # callback=self.on_save, # min_date=datetime.date(2021, 2, 1), # max_date=datetime.date(2022, 12, 31), # ) # To make the MDDatePicker work and the MDDropDown work install the # pip3 install https://github.com/kivymd/KivyMD/archive/master.zip date_dialog = MDDatePicker() date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel) date_dialog.open() def on_save(self, instance, value, date_range): self.ids['client_date'].text = str(value) def on_cancel(self, instance, value): instance.dismiss() def set_slot_item(self, instance_menu, instance_menu_item): self.ids['client_slot'].text = instance_menu_item.text instance_menu.dismiss() def available_slots(self): print('available slots are') time_slots = [ "9 AM - 10 AM", "10:30 - 11:30", "12 PM - 2 PM", " 3 PM - 5 PM" ] menu_items = [{"text": str(i)} for i in time_slots] self.menu = MDDropdownMenu( caller=self.ids['client_slot'], items=menu_items, width_mult=4, ) self.menu.open() self.menu.bind(on_release=self.set_slot_item) def select_time(self): time_dialog = MDTimePicker() time_dialog.bind(time=self.set_time) time_dialog.open() def set_time(self, instance, time): self.ids['client_time'].text = str(time) return time def add_service(self): print('add service') client_name = self.ids['client_name'].text client_phone = self.ids['client_phone'].text service_type = self.ids['client_services'].text service_dt = self.ids['client_date'].text service_time = self.ids['client_slot'].text desc = self.ids['client_desc'].text print(client_name, client_phone, service_type, service_dt, service_time, desc) try: receiver_email_id = "*****@*****.**" s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login("*****@*****.**", "Arun@alf") # print(data) data = "Client Name : " + client_name + "\n" + "Client Phone: " + client_phone + "\n" data = data + "Service Type: " + service_type + "\n" + "Client Address: " + desc + "\n" data = data + "Service Date: " + service_dt + "\n" + "Service Time: " + service_time print(data) message = 'Subject: {}\n\n{}'.format("New Service Request", data) print('preparing to send email') s.sendmail("*****@*****.**", receiver_email_id, message) s.quit() print('Mail Sent.................') self.clear_data() self.show_dialog() except: print('error connecting email') def spin(self): btn = self.ids['submit'] btn.add_widget( MDSpinner( active=True, pos_hint="'center_x': .5, 'center_y': .5", )) def show_dialog(self): self.dialog = MDDialog( title="Success!", text="Service request placed Successfully!", buttons=[ MDFlatButton( text="OK", pos_hint={ "center_x": 0.5, "center_y": 0.5 }, on_release=self.close_dialog, ), ], ) self.dialog.open() # If registration successful return to login screen self.manager.current = 'login_screen' def close_dialog(self, inst): self.dialog.dismiss() def clear_data(self): self.ids['client_name'].text = "" self.ids['client_phone'].text = "" self.ids['client_services'].text = "Select Service Type *" self.ids['client_desc'].text = "" def show_datetime_picker(self): # min_date = datetime.strptime("2020:02:15", '%Y:%m:%d').date() # max_date = datetime.strptime("2020:05:30", '%Y:%m:%d').date() date_dialog = MDDatePicker( callback=self.got_date, min_date=datetime.date(2020, 2, 15), max_date=datetime.date(2022, 3, 27), ) # date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel) date_dialog.open() def show_time_picker(self): time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time) time_dialog.open() def get_time(self, instance, time): print(instance, time) self.ids['service_time'].text = str(time) return time def got_date(self, the_date): print(the_date) self.ids['service_dt'].text = str(the_date) def go_home(self): self.manager.current = 'home_screen'
class OneUIMockServerList(TwoLineAvatarIconListItem): id = None server = ObjectProperty() selected = ObjectProperty() edit = ObjectProperty(force_dispatch=True) delete = ObjectProperty(force_dispatch=True) default = ObjectProperty(force_dispatch=True) menu = None def __init__(self, mock: data.Mock = data.Mock()): super(OneUIMockServerList, self).__init__() self.server = mock self.menu = MDDropdownMenu(caller=self.ids.mock_server_option_button, items=self.options, width_mult=3) self.menu.bind(on_release=self.selected_option) def on_server(self, _, mock: data.Mock): self.id = mock.id self.text = f'{mock.name} :{mock.port}' self.secondary_text = f'Response delay: {mock.delay}' self.disabled = OneUIApplicationCache.mock.current_server == mock.id if self.id in OneUIApplicationCache.mock.running_server: self.toggle_server() def toggle_server(self): self.ids.mock_server_status_button.icon = "play" \ if self.ids.mock_server_status_button.icon == "stop-circle" \ else "stop-circle" def on_release(self): self.selected = self.server def update(self): self.edit = self.server def selected_option(self, instance_menu, instance_menu_item): if instance_menu_item.text.lower() == "edit": self.edit = self.server elif instance_menu_item.text.lower() == "delete": self.delete = self.server elif instance_menu_item.text.lower() == "default": self.default = self.server instance_menu.dismiss() def open_menu(self): if self.menu: self.menu.open() @property def options(self): return [ { "text": "Edit", "icon": "pencil" }, { "text": "Delete", "icon": "trash-can" }, { "text": "Default", "icon": "shield-check" }, ]
class PageBar(MDToolbar): title = StringProperty() def __init__(self, **kwargs): super().__init__(**kwargs) # 3dots menu self.menu = None self.submenu = None def update(self, title): self.title = title items = [{ "icon": "refresh", "text": "Refresh", }, { "icon": "sort", "text": "Sort by", "right_content_cls": RightPageMenuItemContent() }] if not self.title == "Notes": items.append({ "icon": "folder-plus-outline", "text": "Create new category" }) self.menu = MDDropdownMenu( items=items, width_mult=5, ) self.menu.bind(on_release=self.menu_release) self.submenu = None @staticmethod def side_menu_click(app): home_screen = app.root.home side_menu = home_screen.side_menu side_menu.open() @staticmethod def search(): app = App.get_running_app() sm = app.root.screen_manager sm.transition = FadeTransition(duration=.2, clearcolor=app.theme_cls.bg_dark) if sm.has_screen("Search"): sm.current = "Search" else: sm.switch_to(SearchScreen(name="Search")) def page_menu_open(self): if not self.children: return right_action_items = self.children[0] page_menu_button = right_action_items.children[0] self.menu.caller = page_menu_button self.menu.open() def menu_release(self, menu, item): if item.icon == "refresh": app = App.get_running_app() home_sm = app.root.home.screen_manager home_sm.current_screen.update() menu.dismiss() elif item.icon == "folder-plus-outline": TasksPageBox.create_new_category() menu.dismiss() elif item.icon == "sort": if self.submenu: self.submenu.open() return submenu_items = [{ "icon": "sort-alphabetical-ascending", "text": "Alphabetical order" }, { "icon": "sort-clock-ascending-outline", "text": "Date added" }] if not self.title == "Notes": submenu_items.extend([{ "icon": "sort-calendar-ascending", "text": "Deadline" }, { "icon": "sort-numeric-ascending", "text": "Priority" }]) self.submenu = MDDropdownMenu( caller=item, items=submenu_items, width_mult=4.2, ) self.submenu.bind(on_dismiss=self.submenu_dismiss) self.submenu.bind(on_release=self.submenu_release) self.submenu.open() def submenu_dismiss(self, submenu): self.menu.dismiss() def submenu_release(self, submenu, item): self.submenu.dismiss() self.menu.dismiss() app = App.get_running_app() page = app.root.home.screen_manager.current_screen ret = { "Alphabetical order": page.sort_alphabetical, "Date added": page.sort_date, } if not page.name == "Notes": ret["Priority"] = page.sort_priority ret["Deadline"] = page.sort_deadline ret[item.text]() Snackbar( text=f"The content is now sorted by {item.text.lower()}!").open()
class Container(BoxLayout): def __init__(self, change_theme, **kwargs): super().__init__(**kwargs) self.flag = True self.atb_model = None self.text_view = None self.audio_view = None self.change_theme = change_theme self.theme = 'Green' self.cur_ref = None self.vol_popup = self.VolumePopup() self.vol_popup.bind(volume=self.change_volume) self.vol_popup.separator_color = [0, 0, 0, 1] self.vol_popup.background = '../images/back.jpg' self.vol_popup.title_color = [0, 0, 0, 1] self.go_to_audio_popup = Popup(title="", content=self.GoToAudio(func=self.go_to_pos_audio, color=self.get_color), size_hint=(0.15, 0.15), separator_color=[0, 0, 0, 1], title_size='0') self.file_popup = None file_menu_items = [{"icon": "git", "text": f"Import book"}, {"icon": "git", "text": f"Open atb file"}] self.file_menu = MDDropdownMenu( caller=self.file_btn, items=file_menu_items, callback=self.set_item, width_mult=4, ) nav_menu_items = [{"icon": "git", "text": f"Go to begin"}, {"icon": "git", "text": f"Go to end"}, {"icon": "git", "text": f"Go to Page"}] self.nav_menu = MDDropdownMenu( caller=self.nav_btn, items=nav_menu_items, callback=self.nav_item, width_mult=4, ) font_menu_items = [{"icon": "git", "text": f"Font"}, {"icon": "git", "text": f"Font size"}] self.font_menu = MDDropdownMenu( caller=self.font_btn, items=font_menu_items, callback=self.font_item, width_mult=4, ) font_size_menu_items = [{"icon": "git", "text": f"Small"}, {"icon": "git", "text": f"Medium"}, {"icon": "git", "text": f"High"}] self.font_size_menu = MDDropdownMenu( caller=self.font_btn, items=font_size_menu_items, callback=self.font_size_item, width_mult=4, ) font_change_menu_items = [{"icon": "git", "text": f"Roboto"}, {"icon": "git", "text": f"DejaVuSans"}] self.font_change_menu = MDDropdownMenu( caller=self.font_btn, items=font_change_menu_items, callback=self.font_change_item, width_mult=4, ) view_menu_items = [{"icon": "git", "text": f"Theme color"}] self.view_menu = MDDropdownMenu( caller=self.view_btn, items=view_menu_items, callback=self.view_item, width_mult=4, ) theme_menu_items = [{"icon": "git", "text": f"Green"}, {"icon": "git", "text": f"Blue"}, {"icon": "git", "text": f"Dark"}] self.theme_menu = MDDropdownMenu( caller=self.view_btn, items=theme_menu_items, callback=self.theme_item, width_mult=4, ) lang_menu_items = [{"icon": "git", "text": f"English"}, {"icon": "git", "text": f"Русский"}] self.lang_menu = MDDropdownMenu( caller=self.view_btn, items=lang_menu_items, callback=self.lang_item, width_mult=4, ) self.go_to_page_dialog = MDDialog( title="Enter the number of page", type="custom", content_cls=self.GoToPage(), size_hint=[0.3, 0.5], buttons=[ MDFlatButton( text="CANCEL", on_release=self.dismiss_page_dialog ), MDRaisedButton( text="OK", on_release=self.go_to_page ), ], ) Clock.schedule_interval(self.file_menu.set_menu_properties, 0.1) Clock.schedule_interval(self.nav_menu.set_menu_properties, 0.1) Clock.schedule_interval(self.font_menu.set_menu_properties, 0.1) Clock.schedule_interval(self.font_size_menu.set_menu_properties, 0.1) Clock.schedule_interval(self.font_change_menu.set_menu_properties, 0.1) Clock.schedule_interval(self.view_menu.set_menu_properties, 0.1) Clock.schedule_interval(self.theme_menu.set_menu_properties, 0.1) Window.bind(on_resize=self.on_resize_window) self.msg_dialog = None self.cur_volume = 100 self.night_mode_on = False self.event = None self.mutex = threading.Lock() self.progress = 0 self.event2 = None self.cs = [0.117, 0.053, 0.09, 0.042, 0.077, 0.035] self.font_size = 0 class Music(Sound): def __init__(self, file, *args, **kwargs): super().__init__(*args, **kwargs) self.sound = SoundLoader.load(file) class VolumePopup(Popup): pass class ChooseFile(FloatLayout): select = ObjectProperty(None) cancel = ObjectProperty(None) fb2_is_load = ObjectProperty(False) mp3_is_load = ObjectProperty(False) fb2_path = ObjectProperty(None) theme = ObjectProperty(None) @staticmethod def get_path(): return os.path.abspath(os.curdir) def get_color(self, flag): if flag: hue = "600" else: hue = "800" if self.theme == 'Blue': return get_color_from_hex(colors["Blue"][hue]) if self.theme == 'Green': return get_color_from_hex(colors["Green"][hue]) if self.theme == 'Dark': return get_color_from_hex(colors["Gray"][hue]) class FileDialog(BoxLayout): import_book = ObjectProperty(None) open_atb = ObjectProperty(None) class MessagePopup(BoxLayout): close = ObjectProperty(None) class LoadingBar(BoxLayout): close = ObjectProperty(None) func = ObjectProperty(None) class GoToAudio(FloatLayout): func = ObjectProperty(None) color = ObjectProperty(None) class GoToPage(BoxLayout): pass def change_text_r(self): if self.text_view: self.text_view.change_text_r() def change_text_l(self): if self.text_view: self.text_view.change_text_l() def play_or_stop(self): if self.audio_view: self.audio_view.play_or_stop() def move_pos_audio(self, value): if self.audio_view: self.audio_view.move_pos_audio(value) def next_audio(self): if self.audio_view: self.audio_view.next_audio() def prev_audio(self): if self.audio_view: self.audio_view.prev_audio() def volume_slider_open(self): self.vol_popup.open() def change_volume(self, instance, value): self.cur_volume = value if value == 0: self.volume_btn.icon = 'volume-mute' if 0 < value < 33: self.volume_btn.icon = 'volume-low' if 33 <= value < 66: self.volume_btn.icon = 'volume-medium' if 66 <= value <= 100: self.volume_btn.icon = 'volume-high' if self.audio_view: self.audio_view.audio_file.sound.volume = value / 100 def ref_press(self, instance, ref): self.cur_ref = int(ref) print(ref, self.atb_model.word_list[self.cur_ref]) ind = self.text_view.find_page(self.cur_ref) if not self.text_view.clean_word(ind): self.go_to_audio_popup.open() def go_to_book(self): if self.atb_model: # self.audio_file.sound.stop() word_num = self.atb_model.get_word(self.audio_view.cur_audio, self.audio_view.audio_file.sound.get_pos()) if not word_num: return ind = self.text_view.find_page(word_num) self.text_view.clean_word(ind) self.text_view.mark_word(ind, word_num) if ind % 2 == 0: self.left_page.text = self.text_view.pages[ind] self.right_page.text = self.text_view.pages[ind + 1] self.text_view.cur_page = ind else: self.left_page.text = self.text_view.pages[ind - 1] self.right_page.text = self.text_view.pages[ind] self.text_view.cur_page = ind - 1 def test_go_to_book(self, dt): self.go_to_book() def go_to_pos_audio(self): self.go_to_audio_popup.dismiss() pos = self.atb_model.get_sec(self.cur_ref) if not pos: return if pos[0] != self.audio_view.cur_audio: self.audio_view.audio_file.sound.unload() self.audio_view.cur_audio = pos[0] self.audio_view.audio_file = self.Music(self.audio_view.play_list[pos[0]]) self.audio_view.audio_file.sound.seek(pos[1]) self.time_label.text = self.audio_view.get_audio_len() def import_book(self): self.file_popup = Popup(title="Select .fb2 file", content=self.ChooseFile(select=self.select_fb2_mp3, cancel=self.dismiss_popup, theme=self.theme), size_hint=(0.5, 0.6), background='../images/back.jpg', title_color=[0, 0, 0, 1], title_align='center', separator_color=[1, 1, 1, 1]) self.file_popup.content.select_button.text = 'Select .fb2 file' self.file_popup.open() self.file_menu.dismiss() def open_atb_file(self): self.file_popup = Popup(title="Select .atb file", content=self.ChooseFile(select=self.select_atb, cancel=self.dismiss_popup, theme=self.theme), size_hint=(0.5, 0.6), background='../images/back.jpg', title_color=[0, 0, 0, 1], title_align='center', separator_color=[1, 1, 1, 1]) self.file_popup.content.select_button.text = 'Select .atb file' self.file_popup.open() self.file_menu.dismiss() def select_atb(self, path, selection): if selection and selection[0].endswith('.atb'): self.dismiss_popup() self.loading_label.size_hint = [0.07, 1] self.spinner.color = [0, 0, 0, 1] self.spinner.active = True x = threading.Thread(target=self.import_atb, args=(selection[0], True)) x.start() else: self.show_msg('This is not .atb file') def select_fb2_mp3(self, path, selection): if not self.file_popup.content.fb2_is_load: if selection and selection[0].endswith('.fb2'): self.file_popup.content.fb2_path = selection[0] self.file_popup.title = 'Select folder with mp3 files' self.file_popup.content.select_button.text = 'Select folder' self.file_popup.content.fb2_is_load = True self.file_popup.content.filechooser.selection = [] else: self.show_msg('This is not .fb2 file') else: if not selection: mp3s = [] for fil in listdir(path): if fil.endswith('.mp3'): mp3s.append(fil) if not mp3s: self.show_msg('No mp3 files') else: mp3s.sort() for i in range(len(mp3s)): mp3s[i] = path + '/' + mp3s[i] self.dismiss_popup() book_path = self.file_popup.content.fb2_path obj = Model() obj.import_book(book_path, mp3s) book_name = book_path.split('/')[-1].replace('.fb2', '') x = threading.Thread(target=self.load_book, args=('books/' + book_name + '/' + book_name + '_data' + '.atb',)) x.start() else: self.show_msg('This is not a folder') def load_book(self, path): self.import_atb(path, False) #self.make_mapping() def update_bar(self, dt): self.mutex.acquire() self.loading_label.text = 'Sync: ' + str(self.atb_model.get_len_word_sec()) + '%' self.mutex.release() def make_mapping(self): self.event2 = Clock.schedule_interval(self.update_bar, 0.1) self.atb_model.make_mapping() self.event2.cancel() self.loading_label.size_hint = [0.1, 1] self.spinner.active = False self.loading_label.text = 'Done!' def on_resize_window(self, window, width, height): if self.text_view: if self.event: self.event.cancel() self.event = Clock.schedule_once(self.text_view.change_text, 0.3) def import_atb(self, path, flag): self.loading_label.text = "Loading..." self.loading_label.size_hint = [0.07, 1] self.spinner.color = [0, 0, 0, 1] self.spinner.active = True self.atb_model = Model() self.atb_model.load(path) if flag: self.atb_model.load_map() self.text_view = TextView(self.atb_model.get_text(), self.left_page, self.right_page) self.audio_view = AudioView(self.atb_model.get_audio_list(), self.music_button, self.time_label, self.cur_volume, self.slider) self.move_slider() self.cur_ref = 0 if flag: self.loading_label.size_hint = [0.1, 1] self.loading_label.text = "Done!" self.spinner.active = False def night_mode(self): if not self.night_mode_on: self.left_page.background_color = self.get_color('Gray', '800') self.left_page.color = [1, 1, 1, 1] self.right_page.background_color = self.get_color('Gray', '800') self.right_page.color = [1, 1, 1, 1] self.night_mode_on = True else: self.left_page.background_color = [1, 1, 1, 1] self.left_page.color = [0, 0, 0, 1] self.right_page.background_color = [1, 1, 1, 1] self.right_page.color = [0, 0, 0, 1] self.night_mode_on = False def move_slider(self): Clock.schedule_interval(self.audio_view.timer_callback, 1) return 0 def dismiss_popup(self): self.file_popup.dismiss() def show_msg(self, msg): self.msg_dialog = MDDialog( title=msg, size_hint=[0.3, 0.5], buttons=[ MDRaisedButton( text="OK", on_release=self.close_dialog ), ], ) self.msg_dialog.open() def close_dialog(self, instance): self.msg_dialog.dismiss() def close_loading_bar(self): self.loading_popup.dismiss() def run_test_go_to_book(self): Clock.schedule_interval(self.test_go_to_book, 0.5) @staticmethod def get_color(name, num): return get_color_from_hex(colors[name][num]) def set_item(self, instance): if instance.text == 'Open atb file': self.open_atb_file() else: self.import_book() def nav_item(self, instance): if self.text_view: if instance.text == 'Go to begin': self.text_view.cur_page = 0 if len(self.text_view.pages) > 0: self.left_page.text = self.text_view.pages[0] if len(self.text_view.pages) > 1: self.right_page.text = self.text_view.pages[1] if instance.text == 'Go to end': if len(self.text_view.pages) % 2 == 0: self.text_view.cur_page = len(self.text_view.pages) - 2 self.left_page.text = self.text_view.pages[len(self.text_view.pages) - 2] self.right_page.text = self.text_view.pages[len(self.text_view.pages) - 1] else: self.text_view.cur_page = len(self.text_view.pages) - 1 self.left_page.text = self.text_view.pages[len(self.text_view.pages) - 1] self.right_page.text = '' if instance.text == 'Go to Page': self.nav_menu.dismiss() self.go_to_page_dialog.content_cls.field.text = str(self.text_view.cur_page + 1) self.go_to_page_dialog.content_cls.label.text = 'of ' + str(len(self.text_view.pages)) self.go_to_page_dialog.open() def font_item(self, instance): if instance.text == 'Font': self.font_menu.dismiss() self.font_change_menu.open() else: self.font_menu.dismiss() self.font_size_menu.open() def font_size_item(self, instance): if instance.text == 'Small': self.left_page.font_size = '16sp' self.right_page.font_size = '16sp' self.change_text(self.cs[0], self.cs[1]) self.font_size = 0 if instance.text == 'Medium': self.left_page.font_size = '20sp' self.right_page.font_size = '20sp' self.change_text(self.cs[2], self.cs[3]) self.font_size = 1 if instance.text == 'High': self.left_page.font_size = '24sp' self.right_page.font_size = '24sp' self.change_text(self.cs[4], self.cs[5]) self.font_size = 2 def font_change_item(self, instance): if instance.text == 'Roboto': self.left_page.font_name = 'fonts/Roboto-Regular' self.right_page.font_name = 'fonts/Roboto-Regular' self.cs = [0.117, 0.053, 0.09, 0.042, 0.077, 0.035] self.change_text(self.cs[self.font_size * 2], self.cs[self.font_size * 2 + 1]) else: self.left_page.font_name = 'fonts/DejaVuSans' self.right_page.font_name = 'fonts/DejaVuSans' self.cs = [0.105, 0.053, 0.085, 0.041, 0.07, 0.035] self.change_text(self.cs[self.font_size * 2], self.cs[self.font_size * 2 + 1]) def change_text(self, c1, c2): if self.text_view: self.text_view.const1 = c1 self.text_view.const2 = c2 self.text_view.change_text(0) def view_item(self, instance): if instance.text == 'Theme color': self.view_menu.dismiss() self.theme_menu.open() else: self.view_menu.dismiss() self.lang_menu.open() def theme_item(self, instance): if instance.text == 'Green': self.change_theme('LightGreen', '300') self.theme = 'Green' self.up_bar.md_bg_color = self.get_color('LightGreen', '300') self.play_layout.md_bg_color = self.get_color('LightGreen', '300') self.slider.thumb_color_down = [0, 0, 0, 1] self.vol_popup.slider_id.thumb_color_down = [0, 0, 0, 1] if instance.text == 'Blue': self.change_theme('LightBlue', '300') self.theme = 'Blue' self.up_bar.md_bg_color = self.get_color('LightBlue', '300') self.play_layout.md_bg_color = self.get_color('LightBlue', '300') self.slider.thumb_color_down = [0, 0, 0, 1] self.vol_popup.slider_id.thumb_color_down = [0, 0, 0, 1] if instance.text == 'Dark': self.change_theme('Gray', '500') self.theme = 'Dark' self.up_bar.md_bg_color = self.get_color('Gray', '500') self.play_layout.md_bg_color = self.get_color('Gray', '500') self.slider.thumb_color_down = [0, 0, 0, 1] self.vol_popup.slider_id.thumb_color_down = [0, 0, 0, 1] def lang_item(self, instance): pass def go_to_page(self, instance): page = int(self.go_to_page_dialog.content_cls.field.text) - 1 if page >= len(self.text_view.pages): return self.text_view.cur_page = page - (page % 2) self.left_page.text = self.text_view.pages[self.text_view.cur_page] if self.text_view.cur_page + 1 < len(self.text_view.pages): self.right_page.text = self.text_view.pages[self.text_view.cur_page + 1] else: self.right_page.text = '' def dismiss_page_dialog(self, instance): self.go_to_page_dialog.dismiss() def close_go_to_page_popup(self): self.go_to_page_popup.dismiss()
class CreateProfileScreen(Screen): checkerCPS = StringProperty("") def openfile(self): path = '/' # path to the directory that will be opened in the file manager self.file_manager = MDFileManager( exit_manager=self. exit_manager_function, # function called when the user reaches directory tree root select_path=self. select_path_function, # function called when selecting a file/directory ) self.file_manager.show(path) def exit_manager_function(self, obj): self.file_manager.close() def select_path_function(self, path): storage.child(f"ProfilePhotos/{EmailID}/current").put( f"{path}", user['idToken']) self.exit_manager_function() label = MDLabel(text='Profile Photo Updated Successfully.', pos_hint={'center_y': 0.1}, halign='center', font_style='H6', theme_text_color='Custom', text_color=(0, 1, 0, 1)) self.add_widget(label) def menu(self): menu_items = [{ "icon": "face-agent", "text": "Male" }, { "icon": "face-woman", "text": "Female" }] self.menu_open = MDDropdownMenu( caller=self.ids.drop_item, items=menu_items, position="auto", callback=self.set_item, width_mult=4, ) self.menu_open.open() def set_item(self, instance): self.ids.drop_item.set_item(instance.text) self.menu_open.dismiss() def agree_and_continue(self): if self.ids.year_of_birth.text > "2010" or self.ids.year_of_birth.text < "1940": Snackbar( text= 'Looks Like You Are Not Eligible To Use This App Because Of Your Given DOB' ).show() if len(self.ids.mobile_number.text) != 10: Snackbar(text='Invalid Mobile Number. Please Check Again').show() try: self.checkerCPS = 'NoError' data = { 'first_name': f'{self.ids.first_name.text}', 'complete_name': f'{self.ids.first_name.text} {self.ids.middle_name.text} {self.ids.last_name.text}', 'address': f'{self.ids.address.text}', 'year_of_birth': f'{self.ids.year_of_birth.text}', 'mobile_number': f'{self.ids.mobile_number.text}' } db.child("Users").child(f"{EmailID}").set(data) except: self.checkerCPS = 'Error' Snackbar( text= 'We Are Having Trouble Connecting To The Internet..Please Try Again Later' ).show()
class MainScreen(Screen): # pass # isShownLabel = BooleanProperty(False) def add_plot(self): try: self.matrix(0,0) # self.fig1 = gcf() # return self.fig1 except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Talvez devesse importar os dados antes!", radius=[20, 7, 20, 7], ) self.dialog.open() def add_plot2(self): try: self.matrix(0,1) # self.fig2 = gcf() # return self.fig2 except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Talvez devesse importar os dados antes!", radius=[20, 7, 20, 7], ) self.dialog.open() def add_plot3(self): try: self.g_bar() except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Talvez devesse importar os dados antes!", radius=[20, 7, 20, 7], ) self.dialog.open() def Update3(self, dialog): self.dialog.dismiss() self.box1.clear_widgets() MainScreen.add_plot3(self) self.fig3 = Image(source = 'pizza.png') self.fig3.size_hint_y = 1.05 self.box1.add_widget(self.fig3) def Update(self, dialog): self.dialog.dismiss() # cla() self.box3.clear_widgets() # self.fig1 = MainScreen.add_plot(self) MainScreen.add_plot(self) self.fig1 = Image(source = 'teste1.png') # self.fig1.allow_stretch = True # self.fig1.keep_ratio = False # self.fig1.width = self.width self.fig1.size_hint_x = 1.62 self.box3.padding = 15 # self.fig1.pos = (100, 50) self.box3.add_widget(self.fig1) # self.box3.add_widget(FigureCanvasKivyAgg(self.fig1,size_hint=(1,1),pos_hint={"top":1.025})) # self.box3.add_widget(FigureCanvasAgg(self.fig1)) # canvas = self.fig1.canvas # canvas.draw() # self.box3.add_widget(canvas) # graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5, # x_ticks_major=25, y_ticks_major=1, # y_grid_label=True, x_grid_label=True, padding=5, # x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1) # plot = MeshLinePlot(color=[1, 0, 0, 1]) # plot.points = [(x, sin(x / 10.)) for x in range(0, 101)] # graph.add_plot(plot) # self.box3.add_widget(graph) def Update2(self,dialog): self.dialog.dismiss() # cla() self.box4.clear_widgets() # self.fig2 = MainScreen.add_plot2(self) # self.box4.add_widget(FigureCanvasAgg(self.fig2,size_hint=(1,1),pos_hint={"top":1})) # canvas = self.fig2.canvas MainScreen.add_plot2(self) self.fig2 = Image(source = 'barra1.png') self.fig2.size_hint_y = 1.25 self.box4.padding = 35 self.box4.add_widget(self.fig2) def Limpar(self): self.box1.clear_widgets() def Cancelar(self, arg): self.dialog.dismiss() def Cancelar_(self, arg): self.screen_manager.current = "Scr_2" Clock.schedule_interval(self.animate, 0.01) def animate(self, dt): circProgressBar = self.manager.get_screen('main_screen').ids.cp if circProgressBar.value<80: circProgressBar.set_value(circProgressBar.value+1) else: circProgressBar.set_value(0) def tread_nick(self,arg): # adquirir a variavel de texto for obj in self.dialog.content_cls.children: self.nick = (obj.text) # create the thread to invoke other_func with arguments (2, 5) t = Thread(target=self.chess_initt) # set daemon to true so the thread dies when app is closed t.daemon = True # start the thread t.start() if self.dialog: self.dialog.dismiss() self.screen_manager.current = "Scr_2" self.event = Clock.schedule_interval(self.animate, 0.01) # Clock.schedule_once(self.animate) Clock.schedule_interval(partial(self.disable, t),0.1) # self.g_bar() def disable(self, t, what): if not t.isAlive(): Clock.unschedule(self.event) self.screen_manager.current = "Scr_1" # self.add_plot3() return False def my_elo(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Atualizar dados?", text="Isso irá importar os dados e poderá levar alguns instantes.", size_hint=(0.8,1), buttons=[ MDFlatButton( text="CANCELAR", # text_color=self.box.theme_cls.primary_color, on_release=self.Cancelar ), MDFlatButton( text="ATUALIZAR?", # text_color=self.box.theme_cls.primary_color, on_release= self.Update ), ], ) self.dialog.open() def left_menu(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( # title="Atualizar dados?", type="simple", size_hint=(0.4,0.6), pos_hint= {'center_x': .75, 'center_y': .8}, items=[ Item(text="*****@*****.**", source="user-1.png"), Item(text="*****@*****.**", source="user-2.png"), Item(text="Add account", source="add-icon.png"), ], ) self.dialog.open() def nickname(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Chess.com", type="custom", content_cls=Content(), size_hint=(0.8,0.6), buttons=[ MDFlatButton( text="CANCEL", on_release=self.Cancelar ), MDFlatButton( text="OK", on_release= self.tread_nick ), ], ) self.dialog.open() def country(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Atualizar dados?", text="Isso irá importar os dados e poderá levar alguns instantes.", size_hint=(0.8,1), buttons=[ MDFlatButton( text="CANCELAR", # text_color=self.box.theme_cls.primary_color, on_release=self.Cancelar ), MDFlatButton( text="ATUALIZAR?", # text_color=self.box.theme_cls.primary_color, on_release= self.Update2 ), ], ) self.dialog.open() def barra_box1(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Atualizar dados?", text="Isso irá importar os dados e poderá levar alguns instantes.", size_hint=(0.8,1), buttons=[ MDFlatButton( text="CANCELAR", # text_color=self.box.theme_cls.primary_color, on_release=self.Cancelar ), MDFlatButton( text="ATUALIZAR?", # text_color=self.box.theme_cls.primary_color, on_release= self.Update3 ), ], ) self.dialog.open() # def table_(self): # self.data_tables = MDDataTable( # size_hint=(0.8, 0.6), # use_pagination=False, # check=True, # column_data=[ # ("No.", dp(30)), # ("Column 1", dp(30)), # ("Column 2", dp(30)), # ], # row_data=[ # (f"{i + 1}", "2.23", "3.65") # for i in range(50) # ], # ) # self.data_tables.open() # -------------------------------------------------------------------------------- ''' Ajeitar.. o comando está demorando.. Isso já é notificado pela documentação. porém não estou conseguindo fazer da maneira certa. A função init nao reconhece a screen e isso pode estar relacionado com ela não foi inicializada ainda e por isso não reconhece... ''' def tres_pontos(self): menu_labels = [ {"viewclass": "MDMenuItem", "text": "Label1"}, {"viewclass": "MDMenuItem", "text": "Label2"}, ] caller = self.manager.get_screen('main_screen').ids.botao self.dropdown = MDDropdownMenu(caller=caller, items=menu_labels, width_mult=4) # self.dropdown.open() def drop(self): self.tres_pontos() self.dropdown.open() # -------------------------------------------------------------------------------- def chess_initt(self): try: results = [] moves = [] dates = [] speed = [] games = [] my_elo = [] my_color = [] opponent_elo = [] opponent_country = [] opponent_name = [] # self.nick = nick # nick = """heru007""" chesscom = """https://www.chess.com/games/archive/""" + self.nick + """? gameOwner=other_game&gameTypes%5B0%5D=chess960 &gameTypes%5B1%5D=daily&gameType=live&page={}""" # print(chesscom) for i in range(1,5): # Get the page text = get(chesscom.format(i)).text # Soupifyd b = BeautifulSoup(text, 'html.parser') # Collect results results += pull_results(b) moves += pull_moves(b) dates += pull_dates(b) speed += pull_speed(b) games += pull_game_links(b) my_elo += pull_player_stats(b)[0] opponent_elo += pull_player_stats(b)[1] opponent_country += pull_player_stats(b)[2] opponent_name += pull_player_stats(b)[3] my_color += pull_player_stats(b)[4] # Check progress # print(i) # Make Df d = {'date': dates, 'result': results, 'moves': moves, 'speed': speed, 'link': games, 'my_elo': my_elo, 'opponent_elo': opponent_elo, 'opponent_country': opponent_country, 'opponent_name': opponent_name, 'color': my_color } games_df = DataFrame(d) # Escreve as partidas em arquivo .csv games_df.to_csv(path_or_buf='chess_games.csv') except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Algo pode ter dado errado", radius=[20, 7, 20, 7], ) self.dialog.open() def matrix(self,importar, plott): if importar == 1: self.chess_initt if plott == 0: self.games_df = read_csv('chess_games.csv', index_col=0) self.games_df.set_index(self.games_df.index[::-1], drop=True, inplace=True) self.games_df['date'] = to_datetime(self.games_df['date']) speed_games = self.games_df[self.games_df.speed=='10 min'] speed_games.reset_index(drop=True, inplace=True) speed_games.set_index(speed_games.index[::-1], drop=True, inplace=True) speed_games['my_elo_ma'] = speed_games['my_elo'][::-1].rolling(window=30).mean() speed_games['result'] = Series(where(speed_games.result.values == 'win', 1, 0), speed_games.index) # set_style("whitegrid") # figure(figsize=(13, 7)) # lineplot(y='my_elo', # x=speed_games.index, # data=speed_games, # color='darkslategray') # lineplot(y='my_elo_ma', # x=speed_games.index, # data=speed_games, # color='red') # xlabel('Number of Games', fontsize=11) # ylabel('My Elo', fontsize=13) # title('My Elo Over Time', fontsize=13) # xlim(-20) # legend(['elo', '30-day MA']) # style.context('dark_background') figure(figsize=(13, 7)) plot(speed_games.index,speed_games['my_elo'],'darkslategray',speed_games.index,speed_games['my_elo_ma'],'red') grid(True) xlabel('Number of Games', fontsize=20) ylabel('My Elo', fontsize=20) title('My Elo Over Time', fontsize=24) xlim(-20) legend(['elo', '30-day MA'],fontsize=20) subplots_adjust(bottom=0.14) xticks(fontsize=24) yticks(fontsize=24) savefig('teste1.png') elif plott == 1: self.games_df = read_csv('chess_games.csv', index_col=0) self.games_df.set_index(self.games_df.index[::-1], drop=True, inplace=True) self.games_df['date'] = to_datetime(self.games_df['date']) speed_games = self.games_df[self.games_df.speed=='10 min'] speed_games.reset_index(drop=True, inplace=True) speed_games.set_index(speed_games.index[::-1], drop=True, inplace=True) speed_games['my_elo_ma'] = speed_games['my_elo'][::-1].rolling(window=30).mean() speed_games['result'] = Series(where(speed_games.result.values == 'win', 1, 0), speed_games.index) figure(figsize=(13, 7)) quant = speed_games['opponent_country'].value_counts() quant.iloc[0:10].sort_values().plot(kind = 'barh') xlabel('Country', fontsize=24) ylabel('Number of Games', fontsize=24) title('Games against Different Countries', fontsize=26) subplots_adjust(left=0.3) xticks(fontsize=24) yticks(fontsize=24) savefig('barra1.png') def g_bar(self): # self.box1.clear_widgets() self.games_df = read_csv('chess_games.csv', index_col=0) w = Counter(self.games_df['color'])['white'] b = Counter(self.games_df['color'])['black'] # figure(figsize=(13, 17)) self.fig3, ax = subplots() size = 0.3 vals = array([[w], [b]]) cmap = get_cmap("tab20c") outer_colors = cmap(arange(3)*4) ax.pie(vals.sum(axis=1), radius=1.5, colors=outer_colors, shadow=True, wedgeprops=dict(width=size, edgecolor='w'),startangle=90) # ax.set(aspect="equal", title='Partidas Jogadas') sizes = vals/sum(vals)*100 labels = [r'Brancas', r'Pretas'] legend( loc = 'center', labels=['%s, %1.1f %%' % (l, s) for l, s in zip(labels, sizes)], title=('Partidas Jogadas'),fontsize=20, title_fontsize=20) title("Rondan1000", x=0.5,y=0.7,fontsize=28) # self.box1.add_widget(FigureCanvasKivyAgg(self.fig3,size_hint=(1.8,1),pos_hint={"top":0.98})) # self.box1.add_widget(FigureCanvasAgg(self.fig3)) # canvas = self.fig3.canvas # canvas.draw() savefig('pizza.png') # self.fig3 = Image(source = 'pizza.jpg') # self.fig3.size_hint_y = 1.06 # self.box1.add_widget(self.fig3) # aa = self.manager.get_screen('main_screen').ids.label1.opacity # print(aa) # aa = 0
class MainApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.title = "Tusk Inspection App" self.screen = Builder.load_file("main.kv") # Create this in Init because we can... componentgroupitems = [{"text": f"{i}"} for i in dt.componentgroups] self.componentgroupmenu = MDDropdownMenu( caller=self.screen.ids.componentgroup, items=componentgroupitems, position="bottom", callback=self.setcomponentgroup, width_mult=4) projectgroupitems = [{"text": "Project 1"}, {"text": "Project 2"}] self.projectgroupmenu = MDDropdownMenu(caller=self.screen.ids.project, items=projectgroupitems, position="bottom", callback=self.setproject, width_mult=4) roomitems = [{"text": "Room 1"}, {"text": "Room 2"}] self.roommenu = MDDropdownMenu(caller=self.screen.ids.room, items=roomitems, position="bottom", callback=self.setroom, width_mult=4) conditionitems = [{ "text": "Excellent" }, { "text": "Good" }, { "text": "Fair" }, { "text": "Poor" }, { "text": "Very Poor" }] self.conditionmenu = MDDropdownMenu(caller=self.screen.ids.condition, items=conditionitems, position="bottom", callback=self.setcondition, width_mult=4) def callprojectmenu(self): self.projectgroupmenu.open() def callroommenu(self): self.roommenu.open() def callcomponentgroupmenu(self): self.componentgroupmenu.open() def callcomponentmenu(self): if self.screen.ids.componentgroup.text in dt.components: self.componentmenu.open() def calldefectmenu(self): if self.screen.ids.component.text in dt.defecttypes: self.defectmenu.open() def callconditionmenu(self): self.conditionmenu.open() def setcomponentgroup(self, instance): # set the text to the selected itm self.screen.ids.componentgroup.text = instance.text print("set the component group to " + instance.text) # update the dropdown of the next menu as soon as we get the new value if self.screen.ids.componentgroup.text in dt.components: componentitems = dt.components[self.screen.ids.componentgroup.text] items = [{"text": f"{i}"} for i in componentitems] #print("Created the component items") self.componentmenu = MDDropdownMenu( caller=self.screen.ids.component, items=items, position="bottom", callback=self.setcomponent, width_mult=4, ) #print("Created the Content Menu Drop Down") else: print("Did not find the components for component group : " + instance.text) def setcomponent(self, instance): # update the dropdown of the next menu as soon as we get the new value self.screen.ids.component.text = instance.text if self.screen.ids.component.text in dt.defecttypes: defectitems = dt.defecttypes[self.screen.ids.component.text] items = [{"text": f"{i}"} for i in defectitems] self.defectmenu = MDDropdownMenu( caller=self.screen.ids.defect, items=items, position="bottom", callback=self.setdefect, width_mult=4, ) def setproject(self, instance): self.screen.ids.project.text = instance.text def setroom(self, instance): self.screen.ids.room.text = instance.text def setcondition(self, instance): self.screen.ids.condition.text = instance.text def setdefect(self, instance): self.screen.ids.defect.text = instance.text key = self.screen.ids.componentgroup.text + self.screen.ids.component.text + self.screen.ids.defect.text if key in dt.defectactions: self.screen.ids.action.text = dt.defectactions[key] def callcamera(self): print('calling camera') camera = self.screen.ids.cam timestr = time.strftime("%Y%m%d_%H%M%S") camera.export_to_png("img_{}.png".format(timestr)) def submitroom(self): print('submitting data to cloud/spreadsheet/database') def build(self): return self.screen