class PageUsers(BaseScreen): table_layout = ObjectProperty() menu_toolbar = ObjectProperty() dialog = None def __init__(self, **kwargs): super().__init__(**kwargs) self.userList = [] self.selectedUsers = [] def on_enter(self, *args): self.load_user_list() self.menu = self.init_dropdownmenu(self.menu_toolbar.ids.menu_button, self.menu_callback) def init_datatable(self, rowData): self.data_tables = MDDataTable( size_hint=(0.98, 0.98), use_pagination=True, check=True, column_data=[("No", dp(30), self.sort_on_rowno), ("Username", dp(40), self.sort_on_username), ("Full Name", dp(60), self.sort_on_fulname), ("User Role", dp(40), self.sort_on_userrole)], row_data=rowData, sorted_on="Username", sorted_order="ASC", elevation=2) self.data_tables.bind(on_row_press=self.on_row_press) self.data_tables.bind(on_check_press=self.on_check_press) self.ids.table_layout.add_widget(self.data_tables) # data_tables.open () def init_dropdownmenu(self, caller_instance, _callback): menu = MDDropdownMenu( caller=caller_instance, width_mult=4, callback=_callback, ) menu_items = [] data = [ { "icon": "plus-circle-outline", "text": "Add New", "code": "Add" }, { "icon": "square-edit-outline", "text": "Edit", "code": "Edit" }, { "icon": "trash-can-outline", "text": "Delete", "code": "Delete" }, ] for data_item in data: if data_item: menu_items.append({ "right_content_cls": None, "text": data_item.get('text', ''), "icon": data_item.get('icon', ''), "code": data_item.get('code', ''), }) else: menu_items.append({"viewclass": "MDSeparator", "height": 0.2}) menu.items = menu_items return menu def menu_callback(self, instance): print(instance.text) self.menu.dismiss() save_button = MDRaisedButton(text="Save", on_release=self.save_dialog) cancel_button = MDFlatButton(text="Cancel", on_release=self.cancel_dialog) if (instance.text == 'Add New'): user = User(None, '', '', '', UserRole.person.value) self.dialog = MDDialog( type="custom", title="User Information", size_hint=(.5, 1), content_cls=UserInfo({ "user": user, }), buttons=[cancel_button, save_button], ) self.dialog.open() elif (instance.text == 'Edit'): if (len(self.data_tables.get_row_checks()) == 0): self.dialogPopup = MDDialog( title="Warning", text='Select one row!', size_hint=(.5, 1), buttons=[ MDRaisedButton(text="OK", on_release=self.cancel_dialog_popup) ]) self.dialogPopup.open() elif (len(self.data_tables.get_row_checks()) > 1): self.dialogPopup = MDDialog( title="Warning", text='Select only one row!', size_hint=(.5, 1), buttons=[ MDRaisedButton(text="OK", on_release=self.cancel_dialog_popup) ]) self.dialogPopup.open() else: selectedUser = None selected_rows = self.data_tables.get_row_checks() for row in selected_rows: for user in self.userList: if (user['row_no'] == row[0]): selectedUser = user break if (selectedUser != None): break if (selectedUser != None): user = User(selectedUser['id'], selectedUser['username'], selectedUser['fullname'], None, selectedUser['userRole']) self.dialog = MDDialog( type="custom", title="User Information", size_hint=(.5, 1), content_cls=UserInfo({ "user": user, }), buttons=[cancel_button, save_button], ) self.dialog.open() elif (instance.text == 'Delete'): if (len(self.data_tables.get_row_checks()) == 0): pass else: self.selectedUsers = [] for row in self.data_tables.get_row_checks(): selectedUser = None for user in self.userList: if (user['row_no'] == row[0]): selectedUser = user break if (selectedUser != None): self.selectedUsers.append( User(selectedUser['id'], selectedUser['username'], selectedUser['fullname'], selectedUser['password'], selectedUser['userRole'])) if (len(self.selectedUsers) > 0): delete_button = MDRaisedButton(text="Delete", on_release=self.delete_user) cancel_button = MDFlatButton( text="Cancel", on_release=self.cancel_dialog_popup) self.dialogPopup = MDDialog( title="Confirmation", text= 'Are you sure you want to delete the selected rows?', size_hint=(.5, 1), buttons=[cancel_button, delete_button]) self.dialogPopup.open() def GetUserList(self): with Database() as db: userRepository = UserRepository(db) return userRepository.find_by_condition(None) def load_user_list(self): row_data = self.get_user_rows() self.init_datatable(row_data) def get_user_rows(self): row_list = [] self.userList = self.GetUserList() row_no = 0 for user in self.userList: row_no = row_no + 1 user['row_no'] = str(row_no) userRoleText = ("account", [255 / 256, 165 / 256, 0, 1], str(user['userRole'])) if (str(user['userRole']) == UserRole.admin.value): userRoleText = ("account-cog", [39 / 256, 174 / 256, 96 / 256, 1], str(user['userRole'])) row_list.insert(row_no - 1, (user['row_no'], user['username'], user['fullname'], userRoleText)) if (len(row_list) == 1): row_list.insert(1, ("", "", "", "")) return row_list def save_dialog(self, obj): username = self.dialog.content_cls.ids.username.text.strip() fullname = self.dialog.content_cls.ids.fullname.text.strip() password = self.dialog.content_cls.ids.password.text.strip() userRole = self.dialog.content_cls.ids.user_role.current_item.strip() self.dialog.content_cls.ids.username.focus = False self.dialog.content_cls.ids.fullname.focus = False self.dialog.content_cls.ids.password.focus = False self.dialog.content_cls.ids.user_role.focus = False if (username == None or len(username) == 0): self.dialog.content_cls.ids.username.error = True return if (fullname == None or len(fullname) == 0): self.dialog.content_cls.ids.fullname.error = True return if ((password == None or len(password) == 0) and self.dialog.content_cls.user.id == None): self.dialog.content_cls.ids.password.error = True self.dialog.content_cls.ids.password.focus = True return if (userRole == None or len(userRole) == 0): self.dialog.content_cls.ids.user_role.error = True return with Database() as db: try: userRepository = UserRepository(db) existedUser = userRepository.find_by_condition( "username='******'".format(username)) if (self.dialog.content_cls.user.id == None): user = User(None, username, fullname, password, userRole) else: user = User(self.dialog.content_cls.user.id, username, fullname, password, userRole) if (user.id == None): if (len(existedUser) == 0): user.password = userRepository.get_hash( None, user.password) userRepository.insert(user) else: self.dialogPopup = MDDialog( title="Warning", text='Username already exist!', size_hint=(.5, 1), buttons=[ MDRaisedButton( text="OK", on_release=self.cancel_dialog_popup) ]) self.dialogPopup.open() return else: if (len(existedUser) == 0 or (len(existedUser) > 0 and existedUser[0]['id'] == user.id)): # If the password not typed than use this method if (user.password == None or len(user.password) == 0): userRepository.updateWithoutPassword(user) else: user.password = userRepository.get_hash( None, user.password) userRepository.update(user) else: self.dialogPopup = MDDialog( title="Warning", text='Username already exist!', size_hint=(.5, 1), buttons=[ MDRaisedButton( text="OK", on_release=self.cancel_dialog_popup) ]) self.dialogPopup.open() return self.dialog.dismiss() self.load_user_list() except DbException as err: self.dialogPopup = MDDialog( title="Error", text="{0}".format(err), size_hint=(.5, 1), buttons=[ MDRaisedButton(text="OK", on_release=self.cancel_dialog_popup) ]) self.dialogPopup.open() def delete_user(self, obj): if (len(self.selectedUsers) > 0): with Database() as db: try: userRepository = UserRepository(db) for user in self.selectedUsers: userRepository.delete(user) self.dialogPopup.dismiss() self.load_user_list() except DbException as err: self.dialogPopup = MDDialog( title="Error", text="{0}".format(err), size_hint=(.5, 1), buttons=[ MDRaisedButton(text="OK", on_release=self.cancel_dialog_popup) ]) self.dialogPopup.open() def cancel_dialog(self, obj): self.dialog.dismiss() def cancel_dialog_popup(self, obj): self.dialogPopup.dismiss() def on_row_press(self, instance_table, instance_row): '''Called when a table row is clicked.''' print(instance_table, instance_row) def on_check_press(self, instance_table, current_row): '''Called when the check box in the table row is checked.''' print(instance_table, current_row) def sort_on_rowno(self, data): return sorted(data, key=lambda l: l[0]) def sort_on_username(self, data): return sorted(data, key=lambda l: l[1]) def sort_on_fulname(self, data): return sorted(data, key=lambda l: l[2]) def sort_on_userrole(self, data): return sorted(data, key=lambda l: l[3])
class FirstScreen(Screen): #Pantalla comparador de precios """Clase principal donde se ejecuta el modulo comparador de precios, en ella se inicializan las variables correspondientes que se utilizaran en el módulo""" def __init__(self, **kwargs): super().__init__(**kwargs) self.app = MDApp.get_running_app() self.valorbarra = 0 self.buttonactualizar = MDRectangleFlatIconButton( pos_hint={ "center_x": .5, "top": .95 }, #size_hint = (.3,.1), icon="cart-arrow-down", text=" Precios", ) self.msgactualiza = MDLabel(text='Actualizando, espera por favor', pos_hint={ "center_x": .5, "top": .87 }, size_hint=(.8, .1), theme_text_color="Primary", font_style="Subtitle1", halign="center") self.barra = MDProgressBar(id="barrasss", value=0, pos_hint={ "center_x": .5, "center_y": .80 }, size_hint=(.9, .1)) self.etiqueta1 = MDLabel(text='Consultar por Tienda', pos_hint={ "center_x": .5, "top": .80 }, size_hint=(.5, .1), theme_text_color="Primary", font_style="Subtitle1", halign="center") self.buttonche = MDFillRoundFlatButton( pos_hint={ "x": .05, "y": .6 }, size_hint=(.40, .1), text="Chedraui", on_release=lambda x: self.verboton('che')) self.buttonsor = MDFillRoundFlatButton( pos_hint={ "x": .55, "y": .6 }, size_hint=(.40, .1), text="Soriana", on_release=lambda x: self.verboton('sor')) self.buttonhbe = MDFillRoundFlatButton( pos_hint={ "x": .05, "y": .45 }, size_hint=(.40, .1), #theme_text_color = "Primary", text="HBE", on_release=lambda x: self.verboton('hbe')) self.buttoncomer = MDFillRoundFlatButton( pos_hint={ "x": .55, "y": .45 }, size_hint=(.40, .1), text="La Comer", on_release=lambda x: self.verboton('comer')) self.etiqueta2 = MDLabel(text='Consultar por Categoría', pos_hint={ "center_x": .5, "top": .40 }, size_hint=(.5, .1), theme_text_color="Primary", font_style="Subtitle1", halign="center") self.buttonfrutas = MDFillRoundFlatButton( pos_hint={ "x": .05, "y": .20 }, size_hint=(.25, .1), text="Frutas", on_release=lambda x: self.verboton('frutas')) self.buttonverduras = MDFillRoundFlatButton( pos_hint={ "x": .35, "y": .20 }, size_hint=(.25, .1), text="Verduras", on_release=lambda x: self.verboton('verduras')) self.buttoncarnes = MDFillRoundFlatButton( pos_hint={ "x": .65, "y": .20 }, size_hint=(.25, .1), text='Carnes', on_release=lambda x: self.verboton('carnes')) self.buttonlacteos = MDFillRoundFlatButton( pos_hint={ "x": .20, "y": .05 }, size_hint=(.25, .1), text='Lácteos', on_release=lambda x: self.verboton('lacteos')) self.buttonenlatados = MDFillRoundFlatButton( pos_hint={ "x": .50, "y": .05 }, size_hint=(.25, .1), text='Enlatados', on_release=lambda x: self.verboton('enlatados')) self.buttonactualizar.bind(on_press=lambda x: self.ActualizaPrecio()) self.add_widget(self.buttonactualizar) self.add_widget(self.buttonche) self.add_widget(self.buttonsor) self.add_widget(self.buttonhbe) self.add_widget(self.buttoncomer) self.add_widget(self.etiqueta1) self.add_widget(self.etiqueta2) self.add_widget(self.buttonfrutas) self.add_widget(self.buttonverduras) self.add_widget(self.buttoncarnes) self.add_widget(self.buttonlacteos) self.add_widget(self.buttonenlatados) #food-steak carne food-drumstick #food-apple fruta #cheese lacteos #carrot verduras #dome-light #return self.button #def tabla(self, widget): def MuestraNotificacionComparador(self): """Se muestra las notificaciones que se anexaron al modulo del comparador de precios""" self.a = randint(1, 6) print(self.a) if self.a == 1: notification.notify( title='Como Actualizar los precios', message= 'Puedes actualizar los precios de los productos pulsando el boton de Actualizar que se encuentra en' 'la parte superior', timeout=20) snackbar = Snackbar( text= "Puedes actualizar los precios de los productos pulsando el boton de Actualizar que se encuentra en la parte superior" ) snackbar.show() if self.a == 2: notification.notify( title='Visualización de los Precios', message= 'Los precios pueden ser consultados deslizando la tabla que se muestra al consultar alguna categoría', timeout=20) snackbar = Snackbar( text= "Los precios pueden ser consultados deslizando la tabla que se muestra al consultar alguna categoría" ) snackbar.show() pass def ActualizaPrecio(self): """Función desde la cual se obtienen los precios, se llama una funcion que esta en el fichero Actualiza Precios, se ejecutan hilos para obtener los precios simultaneamente, de esta manera se previene el congelamiento de la aplicación, en esta función tambien se llama a la funcion actualiza barra""" ap.main() self.add_widget(self.barra) self.add_widget(self.msgactualiza) self.buttonactualizar.disabled = True self.hiloactualiza = threading.Thread( target=self.actualizabarra ) # Inicializar un hilo llamando a una funcion self.hiloactualiza.start() #self.actualizabarra() self.dialog = MDDialog( title="Actualización de Precios", text= "Se actualizarán los precios que se muestran en cada una de las categorías del comparador de precios," " este proceso puede demorar algunos un par de minutos, por favor sea paciente", size_hint=[.9, .9], auto_dismiss=True, buttons=[ MDFlatButton(text="CERRAR", on_release=self.dialog_close), ]) self.dialog.open() def actualizabarra(self): """Funcion que actualiza la barra mostrada en el módulo comparador de precios""" #if ap.sor.correccion_datos_sor() == True: for a in range(100): self.valorbarra = self.valorbarra + 1 self.barra.value = self.valorbarra sleep(1.3) sleep(5) self.remove_widget(self.msgactualiza) sleep(1) self.remove_widget(self.barra) def dialog_close(self, *args): # Cierra el dialog del boton ayuda """Funcion que cierra el dialog que se despliega al oprimir el botón actualizar""" print("Cerrando Dialog") self.dialog.dismiss() def verboton(self, valor): self.MuestraNotificacionComparador() if valor == 'comer': datos = pd.read_csv("csv/info_lacomer.csv", encoding='utf8') elif valor == 'hbe': datos = pd.read_csv("csv/info_hbe.csv", encoding='utf8') elif valor == 'sor': datos = pd.read_csv("csv/info_sor.csv", encoding='utf8') elif valor == 'che': datos = pd.read_csv("csv/info_che.csv", encoding='utf8') elif valor == 'frutas': datos = pd.read_csv("csv/infofrutas.csv", encoding='utf8') elif valor == 'verduras': datos = pd.read_csv("csv/infoverduras.csv", encoding='utf8') elif valor == 'carnes': datos = pd.read_csv("csv/infocarnes.csv", encoding='utf8') elif valor == 'lacteos': datos = pd.read_csv("csv/infolacteos.csv", encoding='utf8') elif valor == 'enlatados': datos = pd.read_csv("csv/infoenlatados.csv", encoding='utf8') datos = datos.iloc[:, 1:] # primer arg selecciona todas las filas, segundo cols = datos.columns.values values = datos.values self.table = MDDataTable( pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, size_hint=(0.99, 0.99), #font_size = 10, #check= True, use_pagination=True, rows_num=10, column_data=[(col, dp(40)) for col in cols], row_data=values) self.table.bind(on_check_press=self.check_press) self.table.bind(on_check_press=self.row_press) self.table.open() print(valor) def my_callback( self, texto, popup_widget ): # funcion que ayuda a cerrar el dialog del boton actualizar print(texto) print(popup_widget) def open_table(self, instance): """Despliega el contenido de la tabla correpondiente al boton pulsado""" #screen.add_widget(table) self.table.open() def check_press(self, instance_table, current_row): print(instance_table, current_row) def row_press(self, instance_table, instance_row): print(instance_table, instance_row) #self.sub_title = "Comparador" def on_pre_enter(self, *args): self.app.title = "Comparador de precios" pass
class MainApp(MDApp): icons = "heart", data = { 'heart': 'I KNOW I AM A BIT BEKAAR', 'hand-heart': 'ON MESSAGING OFTEN BUT', 'heart-circle-outline': ' I WANT U TO KNOW THAT', 'emoticon-excited': 'I WILL ALWAYS BE THERE...', 'heart-circle': 'THANK U FOR EVERYTHING', 'emoticon-happy': 'U HAVE DONE', 'heart-pulse': 'FOR ME', } def build(self): return def callback(self, instance): toast("HAPPY BIRTHDAY TO YOU MISHTI") pass def dialog(self): butt = MDRaisedButton(text="AB YAHAN CLICK KAR", on_release=self.dialog2, pos_hint={'center_x': 0.5, 'center_y': 0.4}) self.dialog10 = MDDialog(title='Mana Kara Tha Na', text=" Sun Liya Kar Baat " "Ab Neeche Click Kar" , size_hint=(0.7, 1), auto_dismiss='FALSE', buttons=[butt]) self.dialog10.open() pass def dialog2(self, obj): self.dialog10.dismiss() pass def show_MDDialog(self): self.theme_cls.primary_palette = "Amber" button1 = MDRaisedButton(text=':)', font_size=(15), on_release=self.close_dialog, pos_hint={'center_x': 0.5, 'center_y': 0.4}) button2 = MDRaisedButton(text='THANK YOU', font_size=(15), on_release=self.change_color, pos_hint={'center_x': 0.5, 'center_y': 0.4}) button3 = MDIconButton(icon="close", user_font_size="23sp", on_release=self.close_dialog2, pos_hint={'center_x': 0.5, 'center_y': 0.4}) self.dialog = MDDialog(title='HAPPY BIRTHDAY BRUHHHHHHH', text="IT HAS BEEN AN AWESOME" " JOURNEY AND " "WILL ALWAYS BE ONE" " THANK YOU FOR " "ALWAYS BEING " "THERE FOR ME", size_hint=(0.9, 1), pos_hint={'center_x': 0.5, 'center_y': 0.5}, auto_dismiss='FALSE', buttons=[button3, button1, button2]) self.dialog.open() pass def call(self): toast('HAPPY BIRTHDAY BROOO') pass def close_dialog(self, obj): toast('HAPPY BIRTHDAY') pass def close_dialog2(self, obj): self.dialog.dismiss() self.theme_cls.primary_palette = "DeepOrange" self.theme_cls.primary_hue="A200" pass def change_color(self, obj): self.theme_cls.primary_palette = "Blue" toast('CHL NA BAE') pass
class main(MDApp): spin_active = BooleanProperty(False) storage_url = "https://farmzon-abdcb.appspot.com" database_url = "https://farmzon-abdcb.firebaseio.com/.json" data = {"uu": {"Joe Tilsed": "me"}} auth_key = "sBlt6fzvguYnrGl2FlXRK3k4vRxSfZJBV2P7yIRv" # Clock.max_iteration = 20 size_x = NumericProperty(0) size_y = NumericProperty(0) count = 11 count_screen = NumericProperty(0) dialog = None # XXX-------USER LOGIN VAR-------XXX user_name = StringProperty("") user_phone = StringProperty("") user_password = StringProperty("") user_city = StringProperty("") user_email = StringProperty("") user_address = StringProperty("") user_location = StringProperty("") user_image = StringProperty("") user_products = StringProperty("") user_followers = StringProperty("") user_purchased = StringProperty("") user_latitude = StringProperty("") user_longitude = StringProperty("") user_true = BooleanProperty(False) # XXX-------ADMIN LOGIN VAR-------XXX admin_name = StringProperty("") admin_phone = StringProperty("") admin_password = StringProperty("") admin_city = StringProperty("") admin_email = StringProperty("") admin_address = StringProperty("") admin_image = StringProperty("") admin_products = StringProperty("") admin_followers = StringProperty("") admin_purchased = StringProperty("") admin_true = BooleanProperty(False) # XXX-------USER REGISTER VAR-------XXX admin_r_name = StringProperty("") admin_r_phone = StringProperty("") admin_r_password = StringProperty("") admin_r_city = StringProperty("") admin_r_email = StringProperty("") admin_r_address = StringProperty("") type_business = StringProperty("company") # XXX-------USER REGISTER VAR-------XXX user_r_name = StringProperty("") user_r_phone = StringProperty("") user_r_password = StringProperty("") user_r_city = StringProperty("") user_r_email = StringProperty("") user_r_address = StringProperty("") # XXX-------CATEGORIES VAR----------XXX real_source = StringProperty("") label_name = StringProperty("") food_count = NumericProperty(0) fruit_count = NumericProperty(0) herbs_count = NumericProperty(0) # XXX------PRODUCT VAR-------XXX products_id = StringProperty("") product_image = StringProperty("") product_name = StringProperty("") product_max_price = StringProperty("") product_min_price = StringProperty("") product_full_sack = NumericProperty(0) product_half_sack = NumericProperty(0) product_date = StringProperty("") product_month = StringProperty("") product_year = StringProperty("") product_time = StringProperty("") product_state = StringProperty("") screen_name = [] # XXX------FRIENDLY FUNCTIONS------XXX def __init__(self, **kwargs): super().__init__() self.file_manager = MDFileManager() self.file_manager.exit_manager = self.exit_manager self.file_manager.select_path = self.select_path self.file_manager.preview = True self.file_manager.previous = True # self.file_manager.search = "files" def remember_me(self, user, password, name, image): with open("login.txt", "w") as fl: fl.write(user + "\n") fl.write(password) with open("user_info.txt", "w") as ui: ui.write(image + "\n") ui.write(name) fl.close() ui.close() def remember_me_admin(self, user, password, name, image): with open("admin.txt", "w") as fl: fl.write(user + "\n") fl.write(password) with open("admin_info.txt", "w") as ui: ui.write(image + "\n") ui.write(name) fl.close() ui.close() def Permission(self, android=None): if platform == 'android': from android.permissions import request_permissions, Permission # todo request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE]) # todo self.file_manager_open() # todo def check(self): te = self.root.ids.user_phone tex = te.text te.helper_text_mode = "on_focus" te.helper_text = "remain" + " " + str(self.count) self.count = tex.__len__() self.count = 10 - self.count if tex.__len__() < 10 or tex.__len__() > 10: te.icon_right = "alpha-x" te.icon_right_color = 1, 0, 0, 1 elif tex.__len__() == 10: te.icon_right = "check" te.icon_right_color = 0, 1, 0, 1 te.helper_text = "correct" def phone_number(self, phone): new_number = "" 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("wrong number") te = self.root.ids.user_phone te.text = "start with 07 or 06" return False else: return True def dark(self): self.theme_cls.theme_style = "Dark" def light(self): self.theme_cls.theme_style = "Light" def actively(self): if self.spin_active: self.spin_active = False def actively_reg(self): sm = self.root if self.spin_active: self.spin_active = False sm.current = "login screen" toast("Succefull Registerd!") def on_start(self): # screen manager sm = self.root sm.transition = SM.FadeTransition(duration=.2) EventLoop.window.bind(on_keyboard=self.hook_keyboard) self.user_memory() self.fps_monitor_start() def user_memory(self): file_size = os.path.getsize("login.txt") if file_size == 0: pass else: sm = self.root self.user_true = True file1 = open('login.txt', 'r') file2 = open("user_info.txt") Lines = file1.readlines() Lines2 = file2.readlines() count = 0 # Strips the newline character self.user_phone = Lines[0].strip() self.user_password = Lines[1].strip() self.user_name = Lines2[1] self.user_image = "alpha-" + self.user_name[0].lower() self.Signing_in(self.user_phone, self.user_password) sm.current = "main" def admin_memory(self): file_size = os.path.getsize("admin.txt") if file_size == 0: sm = self.root sm.current = "login_screen_admin" self.count_screen += 1 else: sm = self.root self.admin_true = True file1 = open('admin.txt', 'r') file2 = open("admin_info.txt") Lines = file1.readlines() Lines2 = file2.readlines() count = 0 # Strips the newline character self.admin_phone = Lines[0].strip() self.admin_password = Lines[1].strip() self.admin_name = Lines2[1] self.admin_image = Lines2[0] self.Signing_in_admin(self.admin_phone, self.admin_password) sm.current = "admin_main" self.count_screen += 1 def show_alert_dialog(self): if not self.dialog: self.dialog = MDDialog( text="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=quit ), ], ) self.dialog.open() def kill(self, *kwargs): self.dialog.dismiss() def hook_keyboard(self, window, key, *largs): count = self.screen_name.__len__() - 1 sm = self.root if key == 27 and self.count_screen == 0: self.show_alert_dialog() return True elif key == 27 and self.count_screen > 0: sm.current = "main" self.count_screen -= 1 return True def resize_bottom_tabs(self): # bottom_nav bv = self.root.ids.bottom_nav bv.on_resize() def screen_collector(self, name): self.screen_name.append(name) return self.screen_name.__len__() def Screen_changer(self, screen_name): sm = self.root sm.current = screen_name # XXX-------PROFILE VALIDATIONS FUNCTIONS------XXX def validate_user(self, phone, password): if phone == "": toast("please enter your phone number correctly") elif password == "": toast("please enter your password") else: self.spin_active = True self.Signing_in(phone, password) def Signing_in(self, phone, password): thread = threading.Thread(target=self.Signing_in_function, args=(phone, password,)) thread.start() def Signing_in_function(self, phone, password): if phone != "" and password != "": if UI.Signing_in(UI(), phone, password): sm = self.root # image = self.root.ids.user_image # taken from database self.user_name = UI.name self.user_image = "alpha-" + self.user_name[0].lower() self.remember_me(phone, password, self.user_name, UI.image) # image.source = UI.image # Clock.schedule_interval(lambda x: self.image_loader_user(UI.image), 1) self.user_purchased = UI.purchased self.user_products = UI.product self.user_followers = UI.follower if not self.user_true: sm.current = "main" self.screen_collector("main") self.spin_active = False else: toast("oop! phone number or password in correct or " "check your internet connection", 5) self.spin_active = False def image_loader_user(self, y): image = self.root.ids.drawer_logo Cache.remove(image.texture) image.source = y image.reload() def validate_registration1(self, name, phone, password, city, email, address): self.spin_active = True Clock.schedule_once(lambda x: self.validate_registration(name, phone, password, city, email, address), 2) def validate_registration(self, name, phone, password, city, email, address): if city != " " and address != " " and city.isalpha() and address.isalpha(): if self.phone_number(phone): self.user_location = address + "/" + city sm = self.root if LA.Generate_address(LA(), self.user_location): self.user_location = str(LA.location2) self.user_latitude = str(LA.latitude) self.user_longitude = str(LA.longitude) if name != "" and phone != "" and phone.__len__() == 10 and password != "" and city != "" and address != "" and email != "" and email.count( "@") == 1 and email.count(".") > 0: self.spin_active = True self.register(name, phone, password, city, address, email, self.user_location, self.user_latitude, self.user_longitude) else: toast("something is wrong") self.spin_active = False else: toast("your address is not available") self.spin_active = False city = self.root.ids.user_city district = self.root.ids.user_address city.text = " " district.text = " " else: toast("check your phone number") self.spin_active = False else: toast("your city, address and phone number invalid", 3) self.spin_active = False city = self.root.ids.user_city district = self.root.ids.user_address city.text = " " district.text = " " def register(self, name, phone, password, city, address, email, location, latitude, longitude): thread = threading.Thread(target=UI.upload_data_user, args=( UI(), name, phone, password, city, address, email, location, latitude, longitude)) thread.start() thread.join() self.actively_reg() def register_user(self): sm = self.root sm.current = "register screen" self.screen_collector("register screen") # XXX-------ADMIN FUNCTIONS------XXX def validate_admin(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() def Signing_in_admin_function(self, phone, password): if UI.Signing_in_admin(UI(), phone, password): sm = self.root image = self.root.ids.admin_image self.admin_name = UI.name_admin self.admin_image = UI.image_admin image.source = UI.image_admin Clock.schedule_interval(lambda x: self.image_loder_admin(UI.image_admin), 0.1) self.admin_purchased = UI.purchased_admin self.admin_products = UI.product_admin self.admin_followers = UI.follower_admin self.remember_me_admin(phone, password, self.admin_name, self.admin_image) if not self.admin_true: sm.current = "admin_main" else: self.spin_active = False toast("oops! phone number or password in correct") def image_loder_admin(self, x): image = self.root.ids.admin_image image.source = x def validate_registration_admin(self, name, phone, password, city, email, address): if name != "" and phone != "" and password != "" and city != "" and address != "" and email != "" and email.count( "@") == 1 and email.count(".") > 0: self.spin_active = True thread = threading.Thread(target=self.admin_register, args=(name, phone, password, city, address, email, self.type_business)) thread.start() else: toast("something is wrong!") def admin_register(self, name, phone, password, city, address, email, business): thread = threading.Thread(target=UI.upload_data_admin, args=(UI(), name, phone, password, city, address, email, self.type_business)) thread.start() thread.join() toast("registered") self.spin_active = False self.Screen_changer("login_screen_admin") def catergory_food_spinner1(self): self.spin_active = True Clock.schedule_once(lambda x: self.add_image_food("food", "categories_food"), 2) def add_image_food(self, cat, screen): from connection_status import connect if self.food_count == 0: self.food_count = self.food_count + 1 if connect(): food = self.root.ids.food_cat from firebase_admin import credentials, initialize_app, db cred = credentials.Certificate("farmzon-abdcb-c4c57249e43b.json") default_app = initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}, name="food") store = db.reference("Categories_url", default_app).child(cat) stores = store.get() for y, x in stores.items(): self.real_source = x["url"] food_categories = category() food_categories.add_widget(Labels(text=y)) food_categories.add_widget(MDSeparator(height="1dp")) food_categories.add_widget(cat_image(source=self.real_source)) food.add_widget(food_categories) sm = self.root sm.current = screen else: sm = self.root sm.current = screen def catergory_fruit_spinner2(self): self.spin_active = True Clock.schedule_once(lambda x: self.add_image_fruit("fruit", "categories_fruit"), 2) def add_image_fruit(self, cat, screen): from connection_status import connect if self.fruit_count == 0: self.fruit_count = self.fruit_count + 1 if connect(): food = self.root.ids.fruit_cat from firebase_admin import credentials, initialize_app, db cred = credentials.Certificate("farmzon-abdcb-c4c57249e43b.json") default_app = initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}, name="fruit") store = db.reference("Categories_url", default_app).child(cat) stores = store.get() for y, x in stores.items(): self.real_source = x["url"] food_categories = category() food_categories.add_widget(Labels(text=y)) food_categories.add_widget(MDSeparator(height="1dp")) food_categories.add_widget(cat_image(source=self.real_source)) food.add_widget(food_categories) sm = self.root sm.current = screen elif self.fruit_count != 0: sm = self.root sm.current = screen def catergory_herbs_spinner3(self): self.spin_active = True Clock.schedule_once(lambda x: self.add_image_herbs("herbs", "categories_herbs"), 2) def add_image_herbs(self, cat, screen): from connection_status import connect if self.herbs_count == 0: self.herbs_count = self.herbs_count + 1 if connect(): food = self.root.ids.herb_cat from firebase_admin import credentials, initialize_app, db cred = credentials.Certificate("farmzon-abdcb-c4c57249e43b.json") default_app = initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}, name="herbs") store = db.reference("Categories_url", default_app).child(cat) stores = store.get() for y, x in stores.items(): self.real_source = x["url"] food_categories = category() food_categories.add_widget(Labels(text=y)) food_categories.add_widget(MDSeparator(height="1dp")) food_categories.add_widget(cat_image(source=self.real_source)) food.add_widget(food_categories) sm = self.root sm.current = screen else: sm = self.root sm.current = screen def type_active(self, checkbox, value): if value: self.type_business = "company" toast(self.type_business) else: self.type_business = "individual" toast(self.type_business) # XXX------- PRODUCTS_FUNCTION---------XXX def Product_validation(self, name, max, min, date, month, year, description): if name != "" and max != "" and min != "" and date != "" and month != "" and year != "" and description != "": self.product_name = name self.product_date = date self.product_year = year self.product_month = month self.product_max_price = max self.product_min_price = min self.products_id = datetime.now() # XXX-------FILE_MANAGER------XXX def file_manager_open(self): from android.storage import primary_external_storage_path # todo primary_ext_storage = primary_external_storage_path() # todo self.file_manager.show("/") # todo self.file_manager.show(primary_ext_storage) # output manager to the screen self.manager_open = True 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) if path.lower().endswith(('.png', '.jpg', '.jpeg')): toast("correct format") image = self.root.ids.product_image image.source = path self.product_image = path else: toast("Wrong format") def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = False self.file_manager.close() 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 build(self): self.theme_cls.theme_style = "Light" self.theme_cls.primary_palette = "Brown" self.theme_cls.accent = "Brown" # Window.size = (360, 640) print(plyer.uniqueid.id) self.size_x, self.size_y = Window.size self.title = "farmzon"
class NoteItem(TwoLineListItem): dialog = None food_id = NumericProperty(None) food_name = StringProperty(None) def add_note_dialog(self): if not self.dialog: self.dialog = MDDialog( title=self.text, type='custom', content_cls=Content(), buttons=[ MDFlatButton( text='CANCEL', text_color=self.theme_cls.primary_color, on_release=self.my_callback ), MDFlatButton( text='ADD', text_color=self.theme_cls.primary_color, on_release=self.my_callback ) ], size_hint=[.8, 1], auto_dismiss=False ) self.dialog.set_normal_height() self.dialog.open() def view_note_dialog(self): if not self.dialog: self.dialog = MDDialog( title=self.text, text=self.secondary_text, buttons=[ MDFlatButton( text='CANCEL', text_color=self.theme_cls.primary_color, on_release=self.my_callback ), MDFlatButton( text='EDIT', text_color=self.theme_cls.primary_color, on_release=self.my_callback ) ], size_hint=[.8, .5], auto_dismiss=False ) self.dialog.open() def edit_note_dialog(self): if not self.dialog: self.dialog = MDDialog( title=self.text, type='custom', content_cls=Content(), buttons=[ MDFlatButton( text='CANCEL', text_color=self.theme_cls.primary_color, on_release=self.my_callback ), MDFlatButton( text='SAVE', text_color=self.theme_cls.primary_color, on_release=self.my_callback ) ], size_hint=[.8, 1], auto_dismiss=False ) self.dialog.content_cls.ids.note_text.text = self.secondary_text self.dialog.set_normal_height() self.dialog.open() def my_callback(self, popup_widget): app = MDApp.get_running_app() if popup_widget.text == 'EDIT': self.dialog.dismiss() self.dialog = None self.edit_note_dialog() elif popup_widget.text == 'ADD': query = 'UPDATE ingredients SET notes=? WHERE name1=? AND id=?;' vals = (self.dialog.content_cls.text, self.food_name, self.food_id) app.cursor.execute(query, vals) app.conn.commit() self.note_content = self.dialog.content_cls self.secondary_text = self.dialog.content_cls.text self.dialog.dismiss() self.dialog = None elif popup_widget.text == 'SAVE': query = 'UPDATE ingredients SET notes=? WHERE name1=? AND id=?;' vals = (self.dialog.content_cls.text, self.food_name, self.food_id) app.cursor.execute(query, vals) app.conn.commit() self.secondary_text = self.dialog.content_cls.text self.dialog.dismiss() self.dialog = None else: self.dialog.dismiss() self.dialog = None return popup_widget.text
class MainApp(MDApp): dialog = None info = None def build(self): pass def random_choise(self): global choise choise = random.random() def get_qrcode(self): #generate yours qrcode global store user_qrcode = self.root.ids.qrcode '''take ids ''' my_text = self.root.ids.inp img = qrcode.make(my_text.text) #take url or text self.random_choise() png = '.png' path_save_image = storagepath.get_pictures_dir() slash = "\\" #print(slash) path = path_save_image + slash forsave = path + str(choise) + png img.save(forsave) show_qr = forsave user_qrcode.source = show_qr #----------------------------------------------------------------------------DIALOGS def show_confirmation_dialog(self): if not self.dialog: self.dialog = MDDialog( title="Address:", type="custom", content_cls=Content(), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color), MDFlatButton(text="OK", text_color=self.theme_cls.primary_color), ], ) self.dialog.open() def info_about_developer(self): my_dialog = MDDialog(title="List of developers:", size_hint=[.8, .4], type="custom", content_cls=InfoAboutDevelopers(), buttons=[ MDRoundFlatIconButton(text="Facebook", icon="facebook-box", on_press=self.face) ]) my_dialog.open() def info_about_new_funck(self): my_dialog_2 = MDDialog( title="About Project:", text= "My project is built using a buildozer based on python and kivymd (kivy, plyer). In the future, features such as qrcode reader and barcode will be added to the project. The rest of the information and updates can be found on github.", size_hint=[.8, .3], buttons=[ MDRoundFlatIconButton(text="GITHUB", icon="github-circle", on_press=self.github, width=160) ]) my_dialog_2.open() def list_udpate(self): my_dialog_3 = MDDialog(title="List of Updates :", text="no updates now", size_hint=[.8, .2]) my_dialog_3.open() #send_________________________________________________EMAIL__________________________________________________________ def face(self, instance): webbrowser.open('https://www.facebook.com/jar.sin.54/') def paste(self): self.root.ids.inp.text = Clipboard.paste() def github(self, instance): webbrowser.open('https://github.com/Cifoxer/qrcodeapp') #_____________________________________SEND____BUG___________________________________________________________________________________________-- def send_email(self): text_email = self.root.ids.text_bug.text subject_email = self.root.ids.subject_bug.text email.send(recipient="*****@*****.**", subject=subject_email, text=text_email, create_chooser=False)
class MainScreen(Screen, FloatLayout): """ This class represant the Main Screen of the Application. """ def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.alarm_list = [] self.is_alarm_active = False def go_back_to_enter(self): self.manager.transition.direction = 'right' self.manager.current = 'enter' def set_logic_manager(self, logic_manager): self.logic_manager = logic_manager self.alarm_list = [self.get_alarm_dict(alarm) for alarm in logic_manager.alarm_list] self.set_alarm_widget_list() def find_alarm_by_id(self, alarm_list, alarm_id): """ Finds an alarm in list by a given alarm_id Args: alarm_list (list(dict)): List of alarms presented as a dictionary. alarm_id (String): The alarm_id of the alarm to be returned. Returns: The alarm with id of @alarm_id, None if it doesn't exists. """ for alarm in alarm_list: if alarm["alarm_id"] == alarm_id: return alarm return None def create_alarm(self): """ Creates alarm and adds it to the main screen """ # get the alarm_form screen alarm_form_screen = self.manager.screens[2] alarm_form_screen.form_toolbar.title = "Add Alarm" alarm_form_screen.check_true_curr_weekday() # transition to alarm_form screen self.manager.transition.direction = 'left' self.manager.current = 'alarm_form' def edit_alarm(self, alarm_id): """ Edits an alarm with a given alarm_id and present it in the main screen. """ alarm_to_edit = self.find_alarm_by_id(self.alarm_list, alarm_id) # get the alarm_form screen alarm_form_screen = self.manager.screens[2] alarm_form_screen.form_toolbar.title = "Edit Alarm" # set alarm_to_edit in the alarm_form alarm_form_screen.alarm_to_edit = alarm_to_edit # loading alarm to edit details in the alarm_form alarm_form_screen.load_alarm_to_edit_details() # transition to alarm_form screen self.manager.transition.direction = 'left' self.manager.current = 'alarm_form' def close_delete_dialog(self, alarm_id, *args, delete=False): def close(*args): if delete: self.delete_alarm(alarm_id) self.delete_dialog.dismiss(force=True) return close def show_delete_alarm_dialog(self, alarm_id): """ Shows a dialog that making sure that the user want to delete an alarm Args: alarm_id (String): the id of the alarm the user may or may not want to delete. """ self.delete_dialog = MDDialog( title="Delete Alarm?", text="This alarm will no longer be active", pos_hint={"center_x": .5, "center_y": .5}, size_hint_x=.8, buttons=[ MDFlatButton( text="CANCEL", on_press=self.close_delete_dialog(alarm_id, delete=False) ), MDRaisedButton( text="DELETE", on_press=self.close_delete_dialog(alarm_id, delete=True) ), ], ) self.delete_dialog.open() def delete_alarm(self, alarm_id): """ Deletes an alarm with a given alarm_id from the main screen """ # removes the alarm from the screen's alarm_list self.alarm_list = list( filter( lambda alarm: alarm["alarm_id"] != alarm_id, self.alarm_list ) ) # removes the alarm from the screen's view self.ids.list.remove_widget(self.ids[alarm_id]) self.logic_manager.delete_alarm(alarm_id) def load_alarm_active_details(self, alarm_dict): """ Loads the details of an alarm that needs to be ringed into the alarm active scree. Args: alarm_dict (dict): a dictionary containing the alarm's details. """ # getting the screen alarm_active_screen = self.manager.screens[3] # setting up details alarm_active_screen.alarm_active_time.text = alarm_dict["time"] alarm_active_screen.alarm_active_desc.text = alarm_dict["description"] alarm_active_screen.alarm_active_dismiss.on_press = self.stop_ringtone_dismiss_func( alarm_active_screen, alarm_dict["dismiss_func"]) alarm_active_screen.play_alarm_ringtone() # transitioning to the screen self.manager.transition.direction = 'left' self.manager.current = 'alarm_active' def stop_ringtone_dismiss_func(self, alarm_active_screen, dismiss_func): def dismiss(): alarm_active_screen.stop_alarm_ringtone() dismiss_func() return dismiss def set_alarm_item_details(self, alarm_item, alarm_dict, days_str): """ Sets the alarm details from the form in a Widget that later displayed on the main screen. Args: alarm_item (Widget): list item that displayed on the main screen """ alarm_item.name = alarm_dict["alarm_id"] alarm_item.text = alarm_dict["time"].strftime("%H:%M") alarm_item.secondary_text = alarm_dict["description"] alarm_item.tertiary_text = days_str def add_alarm_in_main(self, alarm_dict, add_to_list=False): """ Adds an alarm to the main screen Args: alarm_dict (dict): dictionary contaning the alarm's details. """ #main_screen = self.manager.screens[1] # getting a string represanting alarm days days_str = get_days_str(alarm_dict["days"]) alarm_id = alarm_dict["alarm_id"] # Loading an alarm_item Kivy Widget alarm_item = Builder.load_string(alarm_string) self.set_alarm_item_details(alarm_item, alarm_dict, days_str) # adds the alarm to list in the main screen if(add_to_list): self.alarm_list.append(alarm_dict) # adds the alarm to the list view in the main screen self.ids.list.add_widget(alarm_item) # holding up a reference for the alarm widget for deletion self.ids[alarm_id] = weakref.proxy(alarm_item) def set_alarm_widget_list(self): for alarm in self.alarm_list: self.add_alarm_in_main(alarm) def get_alarm_type(self, alarm): staring_time = alarm.get("staring_time", None) num_words = alarm.get("num_words", None) if num_words != None: return (0, num_words) elif staring_time != None: return (1, staring_time) else: return (2, None) def get_alarm_dict(self, alarm): alarm_dict = alarm.__dict__ alarm_dict["alarm_type"] = self.get_alarm_type(alarm_dict) return alarm_dict
class studyology(MDApp): Config.set('graphics', 'resizable', True) def build(self): self.icon = 'bg\\logo.png' return Builder.load_file('master.kv') def on_start(self): try: conn = sqlite3.connect("data4app.db") a = conn.cursor() b = conn.cursor() c = conn.cursor() a.execute('SELECT * FROM MyAcc') b.execute('SELECT * FROM MyAcc') c.execute('SELECT * FROM MyAcc') myname = a.fetchone()[0] mynum = b.fetchone()[1] mymail = c.fetchone()[2] self.root.ids.screen_manager.current = 'cl' except: pass def otp(self): if self.root.ids.otp.text != '': self.dialog = MDDialog( size=('150dp', '150dp'), size_hint=(None, None), text="INCORRECT OTP", ) self.dialog.open() def show_time_picker(self): time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time) time_dialog.open() def show_theme_picker(self): theme_dialog = MDThemePicker() theme_dialog.open() def get_time(self, instance, time): print(time) self.root.ids.time.text = str(time) def regis(self): soc = socket.socket() server_host = '192.168.137.1' port = 1024 soc.connect((server_host, port)) soc.send('regis'.encode()) time.sleep(.2) e = self.root.ids.e_m.text naam = self.root.ids.naam.text nuum = self.root.ids.nuum.text soc.send(nuum.encode()) time.sleep(.2) print("send number") soc.send(e.encode()) time.sleep(.2) print("send email") soc.send(naam.encode()) print("send name") num = (soc.recv(1024)) num = num.decode() e = (soc.recv(1024)) e = e.decode() nam = (soc.recv(1024)) nam = nam.decode() soc.close() def get_date(self, date): self.root.ids.date.text = str(date) def show_date_picker(self): date_dialog = MDDatePicker(callback=self.get_date) date_dialog.open() def login(self): soc = socket.socket() server_host = '192.168.137.1' number = self.root.ids.number.text port = 1024 soc.connect((server_host, port)) soc.send('login'.encode()) time.sleep(.2) soc.send(number.encode()) num = (soc.recv(1024)) num = num.decode() e = (soc.recv(1024)) e = e.decode() nam = (soc.recv(1024)) nam = nam.decode() self.root.ids.cont.nam = nam print(nam) self.root.ids.cont.em = e print(e) self.root.ids.cont.num = num print(num) soc.close() def som_warn(self): if self.root.ids.screen_manager.current == 'login': self.connect = MDDialog( size=('150dp', '150dp'), size_hint=(None, None), text="something is incorrect", ) self.connect.open() def delay(self): time.sleep(1) def logtodata(self): conn = sqlite3.connect("data4app.db") a = conn.cursor() a.execute(f'INSERT INTO MyAcc VALUES(?,?,?)', (self.root.ids.name.text, self.root.ids.number.text, self.root.ids.em.text)) conn.commit() conn.close() def test_info(self): z = socket.socket() server_host = '192.168.137.1' port = 1024 z.connect((server_host, port)) z.send('refresh'.encode()) math_t = (z.recv(1024)) math_d = (z.recv(1024)) math_des = (z.recv(1024)) bio_t = (z.recv(1024)) bio_d = (z.recv(1024)) bio_des = (z.recv(1024)) phy_t = (z.recv(1024)) phy_d = (z.recv(1024)) phy_des = (z.recv(1024)) chem_t = (z.recv(1024)) chem_d = (z.recv(1024)) chem_des = (z.recv(1024)) hist_t = (z.recv(1024)) hist_d = (z.recv(1024)) hist_des = (z.recv(1024)) civ_t = (z.recv(1024)) civ_d = (z.recv(1024)) civ_des = (z.recv(1024)) pbi_t = (z.recv(1024)) pbi_d = (z.recv(1024)) pbi_des = (z.recv(1024)) hin_t = (z.recv(1024)) hin_d = (z.recv(1024)) hin_des = (z.recv(1024)) geo_t = (z.recv(1024)) geo_d = (z.recv(1024)) geo_des = (z.recv(1024)) z.close() math = self.root.ids.math math.secondary_text = math_des math.tertiary_text = f'on {math_d},time: {math_t}' bio = self.root.ids.bio bio.secondary_text = bio_des bio.tertiary_text = f'on {bio_d},time: {bio_t}' chem = self.root.ids.chem chem.secondary_text = chem_des chem.tertiary_text = f'on {chem_d},time: {chem_t}' phy = self.root.ids.phy phy.secondary_text = phy_des phy.tertiary_text = f'on {phy_d},time: {phy_t}' hist = self.root.ids.hist hist.secondary_text = hist_des hist.tertiary_text = f'on {hist_d},time: {hist_t}' civ = self.root.ids.civ civ.secondary_text = civ_des civ.tertiary_text = f'on {civ_d},time: {civ_t}' pbi = self.root.ids.pbi pbi.secondary_text = pbi_des pbi.tertiary_text = f'on {pbi_d},time: {pbi_t}' hin = self.root.ids.hin hin.secondary_text = hin_des hin.tertiary_text = f'on {hin_d},time: {hin_t}' geo = self.root.ids.geo geo.secondary_text = geo_des geo.tertiary_text = f'on {geo_d},time: {geo_t}'
class JoinGroupWindow(Screen): def load_page(self, greg): ContentNavigationDrawer.populateNavDrawerValues(self) query = "SELECT ORG_ID,NAME,REGISTRATION,DESC FROM ORG WHERE REGISTRATION='" + greg + "'" # run direct SQL stmt = ibm_db.exec_immediate(connection.conn, query) userrow = ibm_db.fetch_tuple(stmt) org_id = "" org_name = "" org_reg = "" org_desc = "" if userrow != False: org_id = userrow[0] org_name = userrow[1] org_reg = userrow[2] org_desc = userrow[3] file_found = download_org_image(str(userrow[0])) if file_found == True: self.ids['grouplogo'].source = "resources/org/" + str( userrow[0]) + ".png" else: self.ids['grouplogo'].source = "resources/org/default.jpg" globalvariables.var_org_id = org_id globalvariables.var_org_name = org_name self.ids['gname'].text = org_name self.ids['greg'].text = org_reg self.ids['gdesc'].text = org_desc #USED TO POPULATE DROP DOWN OF ACTIVITY FOR PAYMENTS FOR NON JOINERS query = "SELECT ACTIVITY_ID,NAME FROM ACTIVITY WHERE ORG_ID=" + str( globalvariables.var_org_id) stmt = ibm_db.exec_immediate(connection.conn, query) act = ibm_db.fetch_both(stmt) actlist = [] while (act): actlist.append(str(act[1])) act = ibm_db.fetch_both(stmt) self.menu = MDDropdownMenu(caller=self.ids['activity_item'], position="center", width_mult=5, callback=self.set_item) for i in actlist: self.menu.items.append({"text": str(i)}) def set_item(self, instance): self.ids['activity_item'].set_item(instance.text) self.menu.dismiss() self.get_total_amount_collected(instance.text) def get_total_amount_collected(self, disaster): query = f'''SELECT TARGET_AMT FROM ACTIVITY WHERE NAME='{disaster}' AND ORG_ID={globalvariables.var_org_id} ''' # run direct SQL stmt = ibm_db.exec_immediate(connection.conn, query) userrow = ibm_db.fetch_tuple(stmt) if userrow != False: self.ids['planned_amount'].text = str(userrow[0]) query = f'''SELECT SUM(TXN.AMOUNT) AS AMOUNT FROM TRANSACTION TXN, ACTIVITY ACT WHERE TXN.ACTIVITY_ID = ACT.ACTIVITY_ID AND ACT.NAME = '{disaster}' AND ACT.ORG_ID = {globalvariables.var_org_id} ''' # run direct SQL stmt = ibm_db.exec_immediate(connection.conn, query) userrow = ibm_db.fetch_tuple(stmt) if userrow != False: self.ids['reached_amount'].text = str(userrow[0]) def donate_to_activity(self): query = f'''SELECT ACTIVITY_ID,NAME FROM ACTIVITY WHERE NAME='{self.ids['activity_item'].current_item}' AND ORG_ID={globalvariables.var_org_id}''' stmt = ibm_db.exec_immediate(connection.conn, query) print(query) act = ibm_db.fetch_tuple(stmt) if act != False: globalvariables.var_act_id = act[0] globalvariables.var_act_name = act[1] self.manager.current = 'payment_window' def join_group(self): query = f'''INSERT INTO CONTACT_ORG(ORG_ID, CONTACT_ID, STATUS, MEMBER_FLAG) VALUES ({globalvariables.var_org_id},{globalvariables.var_userid}, 'N', 'P')''' stmt = ibm_db.exec_immediate(connection.conn, query) if ibm_db.num_rows(stmt) > 0: ok_button = MDFlatButton(text='OK', on_release=self.dialog_close) self.dialog = MDDialog( title='Group Request Submitted', text= "Your group would be available in My Groups when a moderator approves", size_hint=(0.7, 1), buttons=[ok_button]) self.dialog.open() self.manager.transition.direction = 'left' self.manager.current = 'home_window' self.manager.get_screen('home_window').load_home_page() def cancel_join_group(self): self.manager.transition.direction = 'right' self.manager.current = 'group_window' def dialog_close(self, obj): self.dialog.dismiss()
class MainApp(MDApp): def build(self): screen = Screen() self.help_str = Builder.load_string(KV) self.url = "https://fir-practse.firebaseio.com/.json" screen.add_widget(self.help_str) return screen def singin(self): email = self.help_str.get_screen('singin').ids.user_email.text username = self.help_str.get_screen('singin').ids.user_name.text password = self.help_str.get_screen('singin').ids.user_password.text if email.split() == [] or username.split() == [] or password.split( ) == []: Cancel = MDFlatButton(text="Retry", on_press=self.cancel) self.dailog = MDDialog(title="Invalid Input", text="Please enter a valid Input", size_hint=(0.7, 0.1), buttons=[Cancel]) self.dailog.open() elif ("@" not in email): Cancel = MDFlatButton(text="Retry", on_press=self.cancel) self.dailog = MDDialog(title="Invalid Email", text="Please enter a valid Email", size_hint=(0.7, 0.1), buttons=[Cancel]) self.dailog.open() elif (len(password) < 5): Cancel = MDFlatButton(text="Retry", on_press=self.cancel) self.dailog = MDDialog(title="Invalid Password", text="Please enter a strong Password", size_hint=(0.7, 0.1), buttons=[Cancel]) self.dailog.open() else: singin_info = str({ f'\"{email}\":{{"Password":\"{password}\","Username":\"{username}\"}}' }) singin_info = singin_info.replace(".", "-") singin_info = singin_info.replace("\'", "") to_database = json.loads(singin_info) requests.patch(url=self.url, json=to_database) def login(self): check_input = True self.login_info = False user_email = self.help_str.get_screen('login').ids.user_email.text user_pass = self.help_str.get_screen('login').ids.user_password.text try: int(user_email) except: check_input = False if check_input or (user_email.split() == []) or (user_pass.split() == []): cancel_btn = MDFlatButton(text="Retry", on_press=self.cancel_button) self.dailog_box = MDDialog(title="Invalid Input", text="Please enter a valid Input", size_hint=(0.7, 0.1), buttons=[cancel_btn]) self.dailog_box.open() def cancel(self, object): self.dailog.dismiss() def cancel_button(self, object): self.dailog_box.dismiss()
class Recipes(Screen): # Recipe Window #class variable definitions #There's stuff in this class that need to be taken out cause they're not used data = { # 'database-plus': 'Add all checked to Pantry', 'delete': 'Delete all checked recipes', 'plus': 'Add recipe to Pantry', } bufferDate = None container = ObjectProperty() quantity = ObjectProperty() alreadyCheck = False alreadyCheckNav = False RecipeList = [ #to be filled by database "", #empty item because the positioning puts it under the nav bar ] def on_enter(self): icons_item = { #This needs extra items at the bottom to fill out the nav bar - mid priority bug to be fixed later "food-apple": "Food", "pasta": "Recipes", "database": "Pantry", "brush": "Theme", #completely unesccesary but would be cool to customize colors of the app #see MDThemePicker https://kivymd.readthedocs.io/en/latest/components/pickers/index.html "logout": "log out", "a":"", "b":"", "c":"", "d":"", } #pull items owned by a user from the database RecipeItems = App.db.exec(f"SELECT name FROM Recipe;") RecipeOtherThing = App.db.exec( f"SELECT * FROM Recipe;") #this will be used later #fill the list with them for item in RecipeItems: self.RecipeList.append(item[0]) print(RecipeOtherThing[3][3]) #debug if self.alreadyCheckNav == False: #If the navbar is already full, don't fill it again for icon_name in icons_item.keys(): self.ids.content_drawer.add_widget( ItemDrawer(icon=icon_name, text=icons_item[icon_name])) self.alreadyCheckNav = True if self.alreadyCheck == False: for i in self.RecipeList: #prints all the items in user local list self.ids.container.add_widget(SwipeItem_Recipe(text=i)) self.alreadyCheck = True def remove_item( self, instance ): #callback function to remove widgets, used for deleting items from the list self.ids.container.remove_widget(instance) def JSON_maker(self, food, date, quant): #debug print( food ) #returns the food name, will need to change the variable name of this #debug print("date in JSON maker: " + str(date)) if date != None: print(date) #debug if date != None: #if the date is not empty then set the expires boolean to true exp_bool = 1 else: exp_bool = 0 #otherwise set it to false if date != None: #2 different queries have to be called based on whether a date was given or not App.db.exec( f"INSERT INTO Food(owner,name,expired,exp_date) VALUES('{App.user.username}', '{food}', '{exp_bool}', '{date}')" ) else: App.db.exec( f"INSERT INTO Food(owner,name,expired) VALUES('{App.user.username}', '{food}', '{exp_bool}')" ) JSON = { #debug "Owner": App.user.username, "Name": food, "Expires": exp_bool, "Exp_date": date, "Quantity": quant, "Type": None } print(JSON) #debug def got_date(self, the_date): #gets date from the calender self.bufferDate = the_date return (self.bufferDate) def show_date_picker(self): #opens up the calender date_dialog = MDDatePicker(callback=self.got_date) date_dialog.open() def show_recipe( self, instance ): #Opens dialog box and prompts for additional information needed for the add to pantry functionality self.bufferDate = None #reset bufferdate back to null when dialog box opens self.food_name = instance.text #this gets the title of the item clicked self.pantry_item_instance = instance #So looks like variables need to use self. to be able to use elsewhere close_button = MDRectangleFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog( title="Recipe Info", size_hint=(0.8, 1), type="custom", content_cls=dialog_content_recipe(), buttons=[close_button], ) self.dialog.open() # open thingy that prompts for more info and then creates a food object which is then sent to the food handler def close_dialog(self, instance): #closes the dialog box self.dialog.dismiss() def submit_dialog(self, instance): #quant = self.dialog.content_cls.ids.quantity.text if App.sm.get_screen( "window2" ).bufferDate: #if a date was selected assign it to a nicer variable name date = App.sm.get_screen("window2").bufferDate else: #else let it be empty date = None if self.dialog.content_cls.ids.quantity.text: #If quantity was chosen assign it to a nicer variable name quant = self.dialog.content_cls.ids.quantity.text else: #else it defaults to 1 quant = 1 self.JSON_maker(self.food_name, date, quant) #send collected info to be sent to the database #after submitting, remove the item and close the box self.remove_item( self.pantry_item_instance ) #removes the item from the list when button is pressed self.dialog.dismiss() def call_back(self, instance): #debug if (instance.icon == 'delete'): self.deletion() else: self.show_data(self) def deletion(self): for delete in CheckedItemsList: self.alreadyCheck = False self.RecipeList.remove(delete) self.ids.container.clear_widgets() if self.alreadyCheck == False: for i in self.RecipeList: #prints all the items in user local list self.ids.container.add_widget(SwipeItem(text=i)) self.alreadyCheck = True CheckedItemsList.clear() print(*self.RecipeList, sep='\n') def show_data(self, obj): close_button = MDRectangleFlatButton(text="Add", pos_hint={ "center_x": 0.5, "center_y": 0.4 }, on_press=self.close_dialog, on_release=self.add_to_list) self.alreadyCheck = False x_button = MDFlatButton(text="X", pos_hint={ "center_x": 1.0, "center_y": 3.5 }, on_press=self.close_dialog) self.foodItem = MDTextField( hint_text="Enter an item", helper_text="e.g. apples, bananas, orange, etc.", helper_text_mode="on_focus", # icon_right_color = app.theme_cls.primary_color, pos_hint={ "center_x": 0.5, "center_y": 0.5 }, size_hint_x=None, width=250) self.dialog = MDDialog(title="Enter an item:", size_hint=(0.7, 1), buttons=[close_button, x_button]) self.dialog.add_widget(self.foodItem) self.dialog.open() self.alreadyCheck = True def add_to_list(self, obj): self.RecipeList.append(self.foodItem.text) self.ids.container.add_widget(SwipeItem(text=self.foodItem.text))
def masters_ok(self): """Checks if master passwords are OK.""" if not check_beta(): alert_dialog = MDDialog( title=self.tr( 'error_missing_master_title', txt_format=self.tr('beta') ), text=self.tr('error_missing_master_text'), auto_dismiss=False, buttons=[ MDFillRoundFlatIconButton( text=self.tr('set_password'), icon='account-key-outline', on_release=lambda x: self.dismiss_and_back( alert_dialog, 'settings' ) ), MDRoundFlatIconButton( text=self.tr('randomize'), icon='dice-multiple-outline', on_release=lambda x: [ self.reset_beta(), alert_dialog.dismiss() ] ) ] ) alert_dialog.open() return False elif not check_alpha(): alert_dialog = MDDialog( title=self.tr( 'error_missing_master_title', txt_format=self.tr('alpha') ), text=self.tr('error_missing_master_text'), auto_dismiss=False, buttons=[ MDFillRoundFlatIconButton( text=self.tr('set_password'), icon='account-key-outline', on_release=lambda x: self.dismiss_and_back( alert_dialog, 'settings' ) ), MDRoundFlatIconButton( text=self.tr('randomize'), icon='dice-multiple-outline', on_release=lambda x: [ self.reset_alpha(), alert_dialog.dismiss() ] ) ] ) alert_dialog.open() return False else: return True
class Thykel_WeatherApp(MDApp): city_name = StringProperty() country_name = StringProperty() temp_c = StringProperty() weather_text = StringProperty() is_day = StringProperty() img_url = StringProperty() humidity = StringProperty() wind = StringProperty() pressure = StringProperty() feels_like = StringProperty() uv = StringProperty() Today = StringProperty() today = date.today() current_city = StringProperty('Ho') current_country = StringProperty('Ghana') background_pic = StringProperty('images/bgpic.jpg' ) def __init__(self,*args, **kwargs): super().__init__() Window.size = (350,600) self.location = '' self.icon = '/home/fodela/Project/Python Projects/Kivy Projects/Thykel_Weather/images/weather_icon.png' self.ask_current_location_dialog = None self.err_dialog = None def on_start(self): location = f"{self.current_city}, {self.current_country} " self.get_data(location) self.background_pic = 'images/bgpic.jpg' def ask_current_location(self): if not self.ask_current_location_dialog: self.ask_current_location_dialog = MDDialog( title = 'Add Current Location:', type = 'custom', content_cls=LocationGetter(), size_hint = (.8,.3), buttons=[ MDFlatButton( text = 'Cancel', on_press = lambda x: self.cancel() ), MDRaisedButton( text = 'Add', on_press= lambda a:self.add_location() ) ] ) self.ask_current_location_dialog.open() def search(self,instance,keycode): location = self.root.ids.searched_city.text self.get_data(location) def get_data(self,location): self.Today = self.today.strftime("%a, %d %b") try: apikey = f"https://api.weatherapi.com/v1/current.json?key=a5b634c8339b46b5a60161317203110&q={location}" api_request = requests.get(apikey) api_response = json.loads(api_request.content) self.city_name = f"{api_response['location']['name']}" self.country_name = f"{api_response['location']['country']}" self.temp_c =f"{int(api_response['current']['temp_c'])}" self.img_url = f"http:{api_response['current']['condition']['icon']}" self.weather_text = f"{api_response['current']['condition']['text']}" self.is_day = f"{api_response['current']['is_day']}" self.humidity = f"{api_response['current']['humidity']}" self.wind = f"{api_response['current']['wind_mph']}" self.pressure = f"{api_response['current']['pressure_in']}" self.feels_like = f"{api_response['current']['feelslike_c']}" self.uv = f"{api_response['current']['uv']}" except Exception as e: self.error_dialog(str(e)) print(e) def close_dialog(self): try: self.ask_current_location_dialog.dismiss(force=True) except Exception as e: print(e) def add_location(self): location = f"{self.current_city}, {self.current_country} " self.get_data(location) self.close_dialog() def cancel(self): self.close_dialog() def error_dialog(self,err): self.err_dialog = MDDialog( title = 'Error!', type = 'custom', text = err, size_hint = (.8,.3) ) self.err_dialog.open()
class mainApp(MDApp): def build(self): self.theme_cls.theme_style = 'Light' self.data_tables = MDDataTable( size_hint=(0.8, 0.5), column_data=[ ("Work", dp(45)), ("Cost", dp(45)), ("Time", dp(45)), ], row_data=[ # The number of elements must match the length # of the `column_data` list. ("Assignment", "3Rs/Page(2 sides) + Material", "24 hours"), ("Project", "cost of Project + Our Charge", "Depends on Project"), ("Practical", "3Rs/Page(2 sides) + Material ", "24 hours"), ("Fast Service", "5Rs/Page(2 sides) + Material ", "less than 24 hours"), ]) return Builder.load_string(kv) def reward(self): self.data_tables.open() def show(self): self.dialog = MDDialog( title='How to Connect?', text= "Connect With Us Following These Steps \n1) Fill Notes form! \n2) Take ScreenShot \n3) Click On Top-left-corner Icon. \n4)Send ScreenShot On Any Given Platform. ", size_hint=(0.7, 0.5), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=self.dismiss), MDFlatButton(text="Done", text_color=self.theme_cls.primary_color, on_press=self.dismiss), ], ) self.dialog.open() def Contact(self): self.dialog = MDDialog( title='How to Connect?', text= "Connect With Us Following These Steps \n1) Fill Notes form! \n2) Take ScreenShot \n3) Click On Top-left-corner Icon. \n4)Send ScreenShot On Any Given Platform. ", size_hint=(0.8, 0.6), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=self.dismiss), MDFlatButton(text="Done", text_color=self.theme_cls.primary_color, on_press=self.dismiss), ], ) self.dialog.open() def dismiss(self, obj): self.dialog.dismiss() def facebook(self): self.web = webbrowser.open( "https://www.facebook.com/Home-Work-106918057844725/") def instagram(self): self.ins = webbrowser.open( "https://www.instagram.com/homework_assign/?igshid=levzzeoh0rrt&fbclid=IwAR3huKGtL99qynenJJiv9iF6CbKHfCDnSZdCarBJHlZykfNjESgVbUTkCgo" )
class MainScreen(Screen): dialog = None def __init__(self, *args, **kwargs): super(MainScreen, self).__init__(*args, **kwargs) self.ids.uroki.text = '[color=0000ff]Уроки[/color]' self.ids.trenajor.text = '[color=0000ff]Тренажеры[/color]' self.ids.btvvod.text = 'Вводный урок' self.ids.urok1.text = 'Урок №1' self.ids.urok2.text = 'Урок №2' self.ids.urok3.text = 'Урок №3' self.ids.urok4.text = 'Урок №4' self.ids.urok5.text = 'Урок №5' self.ids.urok6.text = 'Урок №6' self.ids.urok7.text = 'Урок №7' self.ids.urok8.text = 'Урок №8' self.ids.urok9.text = 'Урок №9' self.ids.soroban.text = 'Соробан' self.ids.bn.text = 'Выход' self.ids.bn_clear.text = 'Сбросить прогресс' self.ids.tren_stolb.text = 'Столбцы' self.ids.tren_flesh.text = 'Флеш-карты' self.ids.tren_audio.text = 'Аудио-диктанты' def exit_func(self): print(Login.urok) conn = sqlite3.connect("Pupil.db") cur = conn.cursor() cur.execute( " UPDATE users SET count_lesson = ?, progress = ? WHERE id_users = ?", (Login.urok, Login.progress, Login.id)) conn.commit() conn.close() print(Login.progress) def show_alert_dialog(self): if not self.dialog: self.dialog = MDDialog( title="Предупреждение!", type="custom", text="Вы уверены, что хотите сбросить прогресс?", buttons=[ MDFlatButton(text="Сбросить", on_release=self.clearprogress), MDFlatButton(text="Отмена", on_release=self.closeDialog), ], ) self.dialog.set_normal_height() self.dialog.open() def clearprogress(self, inst): print("Сброс") Login.urok = 0 Login.progress = 0 conn = sqlite3.connect("Pupil.db") cur = conn.cursor() cur.execute( " UPDATE users SET count_lesson = ?, progress = ? WHERE id_users = ?", (Login.urok, Login.progress, Login.id)) conn.commit() conn.close() self.manager.get_screen( 'mainscreen').ids.urok_bd.text = 'Начните с Вводного урока' self.manager.get_screen( 'mainscreen' ).ids.progress_bd.text = 'Вы правильно выполнили 0 заданий' self.dialog.dismiss() def closeDialog(self, inst): self.dialog.dismiss()
class NewGroupWindow(Screen): def cancel_org_creation(self): self.ids[ 'groupname'].text = "" #Setting the values to NULL after cancel registration self.ids['regnum'].text = "" self.ids['desc'].text = "" self.manager.transition.direction = 'right' self.manager.current = 'group_window' def load_nav_drawer(self): ContentNavigationDrawer.populateNavDrawerValues(self) def create_org(self, groupname, regnum, desc): ContentNavigationDrawer.populateNavDrawerValues(self) groupname = groupname.text regnum = regnum.text desc = desc.text valid_str = "" if groupname == "": valid_str = "Name is blank" elif regnum == "": valid_str = "Registration is blank" elif desc == "": valid_str = "Description is blank" if valid_str != "": ok_button = MDFlatButton(text='OK', on_release=self.dialog_close) self.dialog = MDDialog(title='Alert !', text=valid_str, size_hint=(0.7, 1), buttons=[ok_button]) self.dialog.open() else: status = "Y" query1 = f'''INSERT INTO ORG(NAME, REGISTRATION, DESC, OWNER_ID, STATUS) VALUES (UPPER('{groupname}'),UPPER('{regnum}'),'{desc}',{globalvariables.var_userid}, '{status}')''' # run direct SQL stmt = ibm_db.exec_immediate(connection.conn, query1) if ibm_db.num_rows(stmt) > 0: query2 = f'''SELECT ORG_ID FROM ORG WHERE REGISTRATION=UPPER('{regnum}') ''' stmt = ibm_db.exec_immediate(connection.conn, query2) orglist = ibm_db.fetch_both(stmt) orgid = "" while (orglist): orgid = orglist[0] query3 = f'''INSERT INTO CONTACT_ORG(ORG_ID, CONTACT_ID, MEMBER_FLAG, STATUS) VALUES ({orgid},{globalvariables.var_userid},'Y', '{status}')''' stmt1 = ibm_db.exec_immediate(connection.conn, query3) orglist = ibm_db.fetch_both(stmt) self.ids[ 'groupname'].text = "" #Setting the values to NULL after sucessfull registration self.ids['regnum'].text = "" self.ids['desc'].text = "" #To upload Org Logo if globalvariables.var_img_path != "": logo_path = globalvariables.var_img_path tgt_logo_path = "org_" + str(orgid) + ".png" upload_org_logo(logo_path, tgt_logo_path) globalvariables.var_img_path = "" ok_button = MDFlatButton(text='OK', on_release=self.dialog_close) self.dialog = MDDialog(title='Successfully Registered', text="Lets start helping!", size_hint=(0.7, 1), buttons=[ok_button]) self.dialog.open() self.manager.transition.direction = 'left' self.manager.current = 'home_window' self.manager.get_screen('home_window').load_home_page() def dialog_close(self, obj): self.dialog.dismiss()
class Adicionar_cliente_tela(Screen): dados_clientes = [] novo_cliente = {} popup_error = None popup_cnpj = None popup_infos = None def on_pre_enter(self): print('Entrando em Adicionar_cliente_tela') app = MDApp.get_running_app() app.registrar_tela() Window.bind(on_keyboard=app.voltar) self.dados_clientes = app.dados_clientes self.ids.codigo.text = str(len(self.dados_clientes) + 1) self.apagar_infos() self.ids.scroll.scroll_y = 1 def apagar_infos(self): print('Apagando infos da Adicionar_cliente_tela') self.ids.nome_fantasia.text = '' self.ids.endereco.text = '' self.ids.numero.text = '' self.ids.bairro.text = '' self.ids.cidade.text = '' self.ids.telefone_fixo.text = '' self.ids.perfil_cliente.text = '' self.ids.nome_1.text = '' self.ids.telefone_1.text = '' self.ids.tipo_1.text = '' self.ids.nome_2.text = '' self.ids.telefone_2.text = '' self.ids.tipo_2.text = '' self.ids.nome_3.text = '' self.ids.telefone_3.text = '' self.ids.tipo_3.text = '' self.ids.banho.active = False self.ids.tosa.active = False self.ids.pet_shop.active = False self.ids.clinica.active = False self.ids.razao_social.text = '' self.ids.cnpj.text = '' self.ids.cep.text = '' def adicionar(self): novo_cliente = {} nome = self.ids.nome_fantasia.text endereco = self.ids.endereco.text numero = self.ids.numero.text bairro = self.ids.bairro.text cidade = self.ids.cidade.text print('Nome:', nome) print('endereco:', endereco) print('numero:', numero) print('bairro:', bairro) print('cidade:', cidade) if nome == '' or endereco == '' or numero == '' or bairro == '' or cidade == '': self.abrir_popup_infos() print('Entrou no if') else: novo_cliente['codigo'] = self.ids.codigo.text novo_cliente['nome_fantasia'] = self.ids.nome_fantasia.text novo_cliente['endereco'] = self.ids.endereco.text novo_cliente['numero'] = self.ids.numero.text novo_cliente['bairro'] = self.ids.bairro.text novo_cliente['cidade'] = self.ids.cidade.text novo_cliente['telefone_fixo'] = self.ids.telefone_fixo.text novo_cliente['perfil_cliente'] = self.ids.perfil_cliente.text novo_cliente['nome_1'] = self.ids.nome_1.text novo_cliente['telefone_1'] = self.ids.telefone_1.text novo_cliente['tipo_1'] = self.ids.tipo_1.text novo_cliente['nome_2'] = self.ids.nome_2.text novo_cliente['telefone_2'] = self.ids.telefone_2.text novo_cliente['tipo_2'] = self.ids.tipo_2.text novo_cliente['nome_3'] = self.ids.nome_3.text novo_cliente['telefone_3'] = self.ids.telefone_3.text novo_cliente['tipo_3'] = self.ids.tipo_3.text novo_cliente['data'] = str(date.today()) novo_cliente['razao_social'] = self.ids.razao_social.text novo_cliente['cnpj'] = self.ids.cnpj.text novo_cliente['cep'] = self.ids.cep.text novo_cliente['banho'] = self.ids.banho.active novo_cliente['tosa'] = self.ids.tosa.active novo_cliente['pet_shop'] = self.ids.pet_shop.active novo_cliente['clinica'] = self.ids.clinica.active novo_cliente['cliente'] = '' novo_cliente['therapet'] = '' novo_cliente['tesoura'] = '' novo_cliente['tap_higienico'] = '' endereco_completo = novo_cliente['endereco'] + ', ' + novo_cliente[ 'numero'] + ' - ' + novo_cliente[ 'bairro'] + ' - ' + novo_cliente['cidade'] endereco = parse.quote(endereco_completo) api_key = '9V2b8ciJf0K3pqhOB2CahsBkpMYuPJKGHhRabS2-iwY' url = 'https://geocode.search.hereapi.com/v1/geocode?q=%s&apiKey=%s' % ( endereco, api_key) app = MDApp.get_running_app() app.popup_leituradados.open() self.novo_cliente = novo_cliente req = UrlRequest(url, on_success=self.success, on_error=self.error, on_failure=self.failure) def success(self, urlrequest, result): print('Success') print('tamanho de result:', len(result['items'])) pprint(result) if len(result['items']) == 0: app = MDApp.get_running_app() app.popup_leituradados.dismiss() self.abrir_popup_error() else: try: print(result['items'][0]['access'][0]['lat']) print(result['items'][0]['access'][0]['lng']) print('Postal Code:', result['items'][0]['address']['postalCode']) self.novo_cliente['lat'] = result['items'][0]['access'][0][ 'lat'] self.novo_cliente['lon'] = result['items'][0]['access'][0][ 'lng'] self.novo_cliente['cep'] = result['items'][0]['address'][ 'postalCode'] except KeyError: #Caso ele tente acessar algum valor do result e não consiga app = MDApp.get_running_app() app.popup_leituradados.dismiss() self.abrir_popup_error() self.dados_clientes.append(self.novo_cliente) app = MDApp.get_running_app() with open(app.path + 'clientes.json', 'w') as data: json.dump(self.dados_clientes, data) app = MDApp.get_running_app() app.popup_leituradados.dismiss() app.root.transition.direction = 'right' app.root.current = 'Menu_tela' def error(self, urlrequest, result): print('Error') app = MDApp.get_running_app() app.popup_leituradados.dismiss() self.abrir_popup_error() self.dados_clientes.append(self.novo_cliente) app = MDApp.get_running_app() with open(app.path + 'clientes.json', 'w') as data: json.dump(self.dados_clientes, data) app.root.transition.direction = 'right' app.root.current = 'Menu_tela' def failure(self, urlrequest, result): self.error(urlrequest, result) def abrir_popup_error(self): if not self.popup_error: self.popup_error = MDDialog( size_hint = [0.8,0.8], title= 'ERRO', text = ('As informações foram armazenadas mas houve um erro ao tentar conseguir as coordenadas geográficas e o CEP para o endereço digitado.' \ ' \n' 'Não será possivel colocar um marcador para esse cliente no mapa.'), buttons=[MDRaisedButton( text="OK", text_color=MDApp.get_running_app().theme_cls.primary_color, on_release = self.fechar ), MDLabel( text='') ], ) self.popup_error.open() def fechar(self, *args): self.popup_error.dismiss() def consulta_cnpj(self): url = 'https://www.receitaws.com.br/v1/cnpj/' cnpj = str(self.ids.cnpj.text) cnpj = cnpj.replace(".", '').replace(',', '').replace('/', '').replace( '-', '') # Para que fique somente os numeros print(cnpj) url_cnpj = url + cnpj UrlRequest(url_cnpj, on_success=self.success_cnpj) def success_cnpj(self, urlrequest, result): print('Tamanho do resultado:', len(result)) pprint(result) # Para auxiliar no debug if len(result) > 2: # Significa que deu certo self.ids.nome_fantasia.text = str(result['fantasia']) self.ids.endereco.text = str(result['logradouro']) self.ids.numero.text = str(result['numero']) self.ids.bairro.text = str(result['bairro']) self.ids.cidade.text = str(result['municipio']) self.ids.telefone_fixo.text = str(result['telefone']) self.ids.razao_social.text = str(result['nome']) self.ids.cep.text = str(result['cep']) else: if not self.popup_cnpj: self.popup_cnpj = MDDialog( size_hint=[0.8, 0.8], title=str(result['message']), text= ('Não foi possivel achar informações sobre esse CNPJ, confira se não há erro de digitação' ), buttons=[ MDRaisedButton(text="OK", text_color=MDApp.get_running_app(). theme_cls.primary_color, on_release=self.fechar_cnpj), MDLabel(text='') ], ) self.popup_cnpj.open() print('erro') def fechar_cnpj(self, *args): self.popup_cnpj.dismiss() def abrir_popup_infos(self): if not self.popup_infos: self.popup_infos = MDDialog( size_hint = [0.8,0.8], title= 'ERRO', text = ('Há informações que necessitam ser inseridas.' \ ' \n' 'Verifique se foram inseridos: \n' ' - Nome \n' ' - Endereço \n' ' - Numero \n' ' - Bairro \n' ' - Cidade'), buttons=[MDRaisedButton( text="OK", text_color=MDApp.get_running_app().theme_cls.primary_color, on_release = self.fechar_info ), MDLabel( text='') ], ) self.popup_infos.open() def fechar_info(self, *args): self.popup_infos.dismiss()
class NewMaterialScreen(Screen): # Property bound to IS_ERROR in viewmodel is_error = BooleanProperty() # Other properties for editting entries material_name = StringProperty('') formula = StringProperty('') molecular_weight = StringProperty('') density = StringProperty('') def __init__(self, *args, **kwargs): super(NewMaterialScreen, self).__init__(*args, **kwargs) Clock.schedule_once(lambda x: self.prepare(), 0) def prepare(self): """Bindings to corresponding viewmodel properties""" app = MDApp.get_running_app() app.update_view_model.bind(IS_ERROR=lambda x, y: self.change_error(y)) def change_error(self, is_error): """changes class 'is_error' to reflect viewmodel""" self.is_error = is_error def check_error(self): """ checks is_error to determine whether to switch screens """ if self.is_error == True: return else: self.back() def back(self): """navigates back to main update view screen""" app = MDApp.get_running_app() app.root.ids.screens.transition.direction = 'right' app.root.ids.screens.current = 'update' def on_leave(self): """clears all user input upon leaving screen""" self.ids.name.text = '' self.ids.formula.text = '' self.ids.molecular_weight.text = '' def submit(self): """sends inputs to viewmodel method to add material to database""" app = MDApp.get_running_app() app.update_view_model.add_material({ 'name': self.ids.name.text, 'formula': self.ids.formula.text, 'molecular_weight': self.ids.molecular_weight.text, 'density': self.ids.density.text }) self.check_error() def error_popup(self, error): """Displays error message (if any)""" self.dialog = MDDialog(title='Error', text=error, size_hint=(0.8, None), height=dp(200)) self.dialog.open()
def list_udpate(self): my_dialog_3 = MDDialog(title="List of Updates :", text="no updates now", size_hint=[.8, .2]) my_dialog_3.open()
class ButtonViewClass(OneLineAvatarIconListItem): # Class level constants CONFIRM = StringProperty('Yes') CANCEL = StringProperty('Maybe not...') # Nonetype if material, else Solvent polarity = None # Name of the solvent/material name = StringProperty('') def __init__(self, **kwargs): super().__init__(**kwargs) self.ids._right_container.width = self.ids.container.width def delete_solvent(self): """calls viewmodel method to delete entry from database""" app = MDApp.get_running_app() app.update_view_model.delete_solvent(self.name) app.update_view_model.get_solvents() self.dialog.dismiss() def delete_material(self): """calls viewmodel method to delete entry from database""" app = MDApp.get_running_app() app.update_view_model.delete_material(self.name) app.update_view_model.get_materials() self.dialog.dismiss() def confirm_popup(self): """popup to confirm deletion of solvent/material""" self.dialog = MDDialog( title= 'You are about to permanently delete this item.\nDo you wish to Continue?', type='confirmation', buttons=[ MDFlatButton(text=self.CANCEL, text_color=self.theme_cls.primary_color, on_release=lambda x: self.dialog.dismiss()), MDRectangleFlatButton( text=self.CONFIRM, text_color=self.theme_cls.primary_color, on_release=lambda x: self.delete_solvent() if self.polarity else self.delete_material()), ]) self.dialog.open() def info_popup(self): """popup to display more information about selection""" if self.polarity == None: record = Material.get_material(self.name) self.dialog = MDDialog( title=record['material_name'], type='custom', content_cls=MaterialInfo(), buttons=[ MDRectangleFlatButton( text="Okay", on_release=lambda x: self.dialog.dismiss()) ]) else: record = Solvent.get_solvent(self.name) self.dialog = MDDialog( title=record['solvent_name'], type='custom', content_cls=SolventInfo(), buttons=[ MDRectangleFlatButton( text="Okay", on_release=lambda x: self.dialog.dismiss()) ]) for key in record: setattr(self.dialog.content_cls, key, record[key]) self.dialog.open() def edit(self): """Takes solvent/material & opens information to be editted""" if self.polarity == None: record = Material.get_material(self.name) else: record = Solvent.get_solvent(self.name) app = MDApp.get_running_app() app.root.ids.screens.get_screen('update').edit(record) def handle_dialog(self, choice, inst): """helper method to handle dialog choice""" if choice == self.CONFIRM: self.delete_solvent() if self.polarity else self.delete_material() elif choice == self.CANCEL: return
class DemoApp(MDApp): user = None id = None identifier = None kind = None dialog = None Enter = False # Indicate whether Pressing Enter will save the added RFID roster, names = find_roster() # Look for Students Roster auto_complete = AutoComplete( names) # Object which generates name suggestions suggestions = [] # Suggested names in case of roster current_count = 0 # Number of characters currently in the text field input_mode = False index = 0 menu_items = [] original_input = "" received = False def build(self): self.theme_cls.primary_palette = "Gray" self.title = "Smart Cabinet Admin Application" Window.bind(on_key_down=self._on_keyboard_down) screen = Builder.load_string(KV) return screen def _on_keyboard_down(self, *args): if self.root.current != "admin_routine" or not self.received: # Ignore keys unless in admin_routine and there is no dialog and return if args[2] == 41: # Escape button if self.dialog: self.dismiss() self.shrink_suggestions() return elif args[3] and args[3] in ALLOWED_CHARS: # an allowed character self.root.ids.identifier.text += args[3] self.original_input += args[3] if self.root.ids.identifier.text[:-1] in self.suggestions: # If a name is highlighted and user inputs letter, add letter to the suggested name self.original_input = self.root.ids.identifier.text[:-1] + args[ 3] self.root.ids.identifier.text = self.original_input self.index = 0 elif args[2] == 42 and self.root.ids.identifier.text: # backspace and there is a letter to delete self.original_input = self.root.ids.identifier.text self.root.ids.identifier.text = self.root.ids.identifier.text[:-1] self.original_input = self.original_input[:-1] self.index = 0 if not self.root.ids.identifier.text: self.shrink_suggestions() return elif args[2] == 40: # If Enter key is pressed if self.dialog: # If dialog is open self.send_identifier() self.original_input = "" elif self.root.ids.identifier.text and self.received: # If dialog is closed, and Enter key is pressed: # If suggestions are shown, copy highlighted text and shrink suggestions # self.index = 0 self.validate_identifier() self.shrink_suggestions() return # elif not self.roster or self.kind != "student": # return elif args[ 2] == 81 and self.root.ids.identifier.text and not self.dialog: # down arrow self.index += 1 self.index = min(self.index, len(self.suggestions) - 1) elif args[ 2] == 82 and self.root.ids.identifier.text and not self.dialog: # up arrow self.index -= 1 self.index = max(self.index, 0) else: return # menu_items: [input text, 5 suggestions] if not self.roster or self.kind != "student": return if not self.menu_items: self.menu_items = [ self.root.ids.identifier, self.root.ids.name0, self.root.ids.name1, self.root.ids.name2, self.root.ids.name3, self.root.ids.name4 ] self.suggestions = [self.original_input] + self.auto_complete.auto( self.original_input, max_sugg=5) if len(self.suggestions) == 1: self.shrink_suggestions() return self.show_suggestions() self.highlight_suggestions() if self.index == 0: self.root.ids.identifier.text = self.original_input for idx in range(1, 6): # Populate the name suggestions as needed try: self.menu_items[idx].text = self.suggestions[idx] except IndexError: self.menu_items[idx].text = "" pass def show_suggestions(self): self.input_mode = True # Show suggestions self.root.ids.name_list.size_hint_y = (len(self.suggestions) - 1) * 0.06 self.root.ids.name_list.pos_hint = { "center_y": 0.47 - (len(self.suggestions) - 1) / 2 * .06, "center_x": .5 } def shrink_suggestions(self): self.input_mode = False self.root.ids.name_list.size_hint_y = 0 self.root.ids.name_list.pos_hint = {"center_y": .47, "center_x": .5} def highlight_suggestions(self): for idx in range(1, 6): if idx == self.index: if not self.menu_items[self.index].text: continue self.menu_items[self.index].bg_color = SUGG_COLOR else: self.menu_items[idx].bg_color = SUGG_MENU_COLOR self.root.ids.identifier.text = self.menu_items[self.index].text def on_start(self): return def on_stop(self): try: self.user.close() except AttributeError: pass def connect2(self): self.user = Admin(gui=True) self.root.transition = SlideTransition(direction='left') self.root.current = "access_screen" self.root.ids.spinner2.active = False def connect(self): self.root.ids.spinner2.active = True executor = concurrent.futures.ThreadPoolExecutor() f = executor.submit(self.connect2) def admin_routine(self, kind): # Go to admin_routine screen and save the kind of RFID to be added self.root.transition = SlideTransition(direction='left') self.root.current = "admin_routine" self.kind = kind def get_id(self): # Get the Scanned ID, and allow user to input name (identifier) self.root.ids.id_label.text = "" self.root.ids.spinner.active = True executor = concurrent.futures.ThreadPoolExecutor() f = executor.submit(self.receive) def receive(self): self.user.send_msg(self.kind.encode()) self.id = self.user.get_msg().decode() self.root.ids.id_label.text = self.id self.root.ids.identifier.hint_text = "Enter Name" self.received = True self.root.ids.spinner.active = False def back_btn(self): if self.received: return self.root.transition = SlideTransition(direction='right') self.root.current = "access_screen" self.root.ids.identifier.text = "" self.root.ids.id_label.text = "" def validate_identifier(self): self.identifier = self.root.ids.identifier if not self.identifier.text: return self.dialog = MDDialog( title='Name Check', text=f"Are you sure you want to save {self.identifier.text}?", size_hint=(0.8, 1), buttons=[ConfirmBtn(on_release=self.send_identifier)], ) self.dialog.open() def dismiss(self): if self.dialog: self.dialog.dismiss() self.dialog = None def send_identifier(self, *args): print(self.identifier.text, "Sent!") self.dismiss() name = self.identifier.text.strip() self.user.send_msg(name.encode()) self.root.ids.id_label.text = "SAVED" self.identifier.hint_text = "" self.identifier.disabled = True self.root.ids.get_id.disabled = False self.original_input = "" self.index = 0 self.suggestions = [] self.menu_items = [] self.received = False
class UpdateSolventScreen(Screen): # Property bound to IS_ERROR in viewmodel is_error = BooleanProperty() # Other properties for editting entries solvent_name = StringProperty('') formula = StringProperty('') polarity = StringProperty('') density = StringProperty('') def __init__(self, *args, **kwargs): super(UpdateSolventScreen, self).__init__(*args, **kwargs) Clock.schedule_once(lambda x: self.prepare(), 0) def prepare(self): """Bindings to corresponding viewmodel properties""" app = MDApp.get_running_app() app.update_view_model.bind(IS_ERROR=lambda x, y: self.change_error(y)) def change_error(self, is_error): """changes class 'is_error' to reflect viewmodel""" self.is_error = is_error def check_error(self): """ checks is_error to determine whether to switch screens """ app = MDApp.get_running_app() if self.is_error == True: app.update_view_model.IS_ERROR = False return else: self.back() def back(self): """navigates back to main update view screen""" app = MDApp.get_running_app() app.root.ids.screens.transition.direction = 'right' app.root.ids.screens.current = 'update' def submit(self): """sends inputs to viewmodel method to add solvent to database""" app = MDApp.get_running_app() app.update_view_model.update_solvent({ 'name': self.solvent_name, 'density': self.ids.density.text, 'formula': self.ids.formula.text, 'polarity': self.ids.polarity.text, }) self.check_error() def error_popup(self, error): """Displays error message (if any)""" if error == '': return else: self.dialog = MDDialog(text=f"Error: {error}", ) self.dialog.open() # Change error message back to "" app = MDApp.get_running_app() app.update_view_model.ERROR_MSG = ''
class KanjiKoohiiViewer(ScrollView): def __init__(self, master, **kwargs): super().__init__(**kwargs) self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text') if self._keyboard.widget: # If it exists, this widget is a VKeyboard object which you can use to change the keyboard layout. pass self._keyboard.bind(on_key_down=self._on_keyboard_down) self.master = master self.kanji = random.choice(self.master.kanji_koohi_stories_list) self.kanji_data = get_koohii_from_ib_kanji_json(self.kanji) self.dialog = None self.effect_cls = "ScrollEffect" self.scroll_type = ["bars"] self.bar_width = "10dp" self.kanji_layout = MDRelativeLayout(adaptive_height=True) #self.kanji_data = get_kanji_from_level(self.level) print(self.kanji_data) for k, v in self.kanji_data.items(): setattr(self, k, v) """ self.btn_texts = [" Show Meanings "," Show Radicals ", "Show Example Words"] self.kanji_layout.add_widget(Label(text=str(self.kanji), font_size=75,halign="center", pos_hint={"center_y":.8})) self.kanji_layout.add_widget(Label(text=str(self.stroke_count), font_size=20,halign="center", pos_hint={"center_y":.7})) self.carousel = KanjiStrokeImageCarousel(self.stroke_order_images) self.kanji_layout.add_widget(self.carousel) self.prev_btn = MDIconButton(icon="menu-left", user_font_size ="200sp", on_release = lambda x:self.carousel.load_previous(), pos_hint={"center_x":.1, "center_y":.5}) # pos_hint={"left":.2, "y":.5}, self.next_btn = MDIconButton(icon="menu-right", user_font_size ="200sp", on_release = lambda x:self.carousel.load_next(), pos_hint={"center_x":.9, "center_y":.5}) # pos_hint={"right":.8, "y":.5} self.kanji_layout.add_widget(self.prev_btn) self.kanji_layout.add_widget(self.next_btn) for i, reading in enumerate(self.readings): self.kanji_layout.add_widget(Label(text=reading,font_size=20, pos_hint={"center_x":.5,"center_y":.3-(i/20)})) #print(self.radicals_data, "\n") #print(" ".join([j for j in [" ".join(i) for i in self.radicals_data]])) formated_radicals = " \n".join([rad for rad in [":".join(tup) for tup in self.radicals_data]]) formated_word_examples = "\n".join(self.example_words) #print(self.radicals_data, self.example_words, sep="\n") #self.kanji_layout.add_widget(Label(text=formated_radicals,halign="center", font_size=15, pos_hint={"center_x":.5,"center_y":.1})) self.meanings_btn = MDRaisedButton(text=self.btn_texts[0], pos_hint={"center_x":.1,"center_y":.15}, on_release=lambda x:self.showDialog("Meanings",self.meanings)) self.kanji_layout.add_widget(self.meanings_btn) self.radicals_btn = MDRaisedButton(text=self.btn_texts[1], pos_hint={"center_x":.5,"center_y":.15}, on_release=lambda x:self.showDialog("Radicals",formated_radicals)) self.kanji_layout.add_widget(self.radicals_btn) self.examples_btn = MDRaisedButton(text=self.btn_texts[2], pos_hint={"center_x":.9,"center_y":.15}, on_release=lambda x:self.showDialog("Example Words",formated_word_examples)) self.kanji_layout.add_widget(self.examples_btn) self.add_widget(self.kanji_layout) """ def showDialog(self, title, text): self.dialog = None if not self.dialog: self.dialog = MDDialog( title=title, text=text, buttons=[ MDFlatButton( text="CLOSE", on_release=lambda *args: self.dialog.dismiss()) ]) self.dialog.open() # Keyboard methods def _keyboard_closed(self): print('My keyboard have been closed!') self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): print('The key', keycode, 'have been pressed', ' - text is %r' % text, ' - modifiers are %r' % modifiers, sep="\n") if keycode[1] == "left" or keycode[1] == "a": self.carousel.load_previous() if keycode[1] == "right" or keycode[1] == "d": self.carousel.load_next() if keycode[1] == "escape" or keycode[1] == 277: if isinstance(self.dialog, MDDialog): self.dialog.dismiss() if keycode[1] == "n": # Load new kanji by pressing 'r' current_screen = self.master.screen_manager.get_screen( self.master.screen_manager.current) current_screen.toolbar.load_new_kanji() if keycode[1] == "m": if isinstance(self.dialog, MDDialog): print("about to close dialog should exist") self.dialog.dismiss() self.meanings_btn.trigger_action(0) if keycode[1] == "r": if isinstance(self.dialog, MDDialog): self.dialog.dismiss() self.radicals_btn.trigger_action(0) if keycode[1] == "e": if isinstance(self.dialog, MDDialog): self.dialog.dismiss() self.examples_btn.trigger_action(0) # Return True to accept the key. Otherwise, it will be used by the system. return True
class SecureCheck(MDApp): def build(self): self.theme_cls.primary_pallet = "Green" self.theme_cls.theme_style = "Dark" screen = Screen() icon2 = MDIconButton(icon="file-upload-outline", pos_hint={'center_x': 0.8, 'center_y': 0.7}, on_release=self.example_fun) top = Builder.load_string(ttop) l2 = MDLabel(text="Scan File", pos=(40, 178), font_style="Body2", theme_text_color="Primary") self.f = Builder.load_string(us) l4 = MDRectangleFlatButton(text="Update", pos_hint={'center_x': 0.747, 'center_y': 0.2}, size_hint=(None, None), width=5, height=2, on_release=self.update) toptoolbar = Builder.load_string(tt) bt1 = MDRectangleFlatButton(text='Scan', pos_hint={'center_x': 0.4, 'center_y': 0.6}, size_hint=(None, None), width=5, height=2, on_release=self.start_scan) bt2 = MDRectangleFlatButton(text='Delete', pos_hint={'center_x': 0.74, 'center_y': 0.6}, size_hint=(None, None), width=5, height=2, on_release=self.delete_infected) screen.add_widget(toptoolbar) screen.add_widget(l2) screen.add_widget(self.f) screen.add_widget(l4) screen.add_widget(bt1) screen.add_widget(bt2) screen.add_widget(top) screen.add_widget(icon2) return screen # related to scan file def start_scan(self, obj): global path global md5sum if self.f.text == "": path = "Please Enter File Path" elif os.path.isfile(self.f.text) or zipfile.is_zipfile(self.f.text): path = self.f.text else: md5sum = self.f.text path = md5sum cb = MDFlatButton(text="EDIT", on_release=self.close_dialog) ed = MDFlatButton(text="NEXT", on_release=self.next) self.dialog = MDDialog(title="FIle Path", text=path, buttons=[cb, ed], size_hint=(0.7, 1)) self.dialog.open() # print(self.f.text) def next(self, obj): global x try: if zipfile.is_zipfile(str(self.f.text).strip()): with ZipFile(str(self.f.text).strip(), 'r')as zip: for i in zip.infolist(): sd = zip.read(i.filename) mdx2 = hashlib.md5(sd).hexdigest() with gzip.open("batadata.txt.gz", "rb")as writef: xy = writef.read() bindata = bytearray(xy) if bytes(mdx2, 'utf-8') in bindata: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="Infected\n md5 : " + mdx2, buttons=[ok], size_hint=(0.7, 1)) self.x.open() else: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="Not Infected\n md5 : " + mdx2, buttons=[ok], size_hint=(0.7, 1)) self.x.open() # self.dialog.dismiss() elif os.path.isfile(self.f.text): with open(str(path).strip(), "rb") as r: sum = r.read() mdx = hashlib.md5(sum).hexdigest() with gzip.open("batadata.txt.gz", "rb")as writef: xy = writef.read() bindata = bytearray(xy) if bytes(mdx, 'utf-8') in bindata: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="Infected\n md5 : " + mdx, buttons=[ok], size_hint=(0.7, 1)) self.x.open() else: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="Not Infected\n md5 : " + mdx, buttons=[ok], size_hint=(0.7, 1)) self.x.open() # self.dialog.dismiss() elif os.path.isdir(self.f.text): ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="It Is Directory Please Enter correct Path of the file", buttons=[ok], size_hint=(0.7, 1)) self.x.open() else: with gzip.open("batadata.txt.gz", "rb")as writef: xy = writef.read() bindata = bytearray(xy) if bytes(md5sum, 'utf-8') in bindata: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="Infected\n md5 : " + md5sum, buttons=[ok], size_hint=(0.7, 1)) self.x.open() else: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="Not Infected\n md5 : " + md5sum, buttons=[ok], size_hint=(0.7, 1)) self.x.open() except: ok = MDFlatButton(text="OK", on_release=self.go_back) self.x = MDDialog(text="No Such File Please Enter correct Path", buttons=[ok], size_hint=(0.7, 1)) self.x.open() def go_back(self, obj): self.x.dismiss() self.dialog.dismiss() def close_dialog(self, obj): self.dialog.dismiss() # help button content def help_fun(self): cdt1 = MDFlatButton(text="close", on_release=self.close_dt1) self.dt1 = MDDialog(title="About SecureCheck", text="1.Safeguards Your System\n2.Dectect Infected File\n3.Eleminate Infected File\n4.Can also Check md5 on\n virustotal to know if it is\n working write or not\n\n Made By: Abhay Mishra", pos_hint={'center_x': 0.5, 'center_y': 0.5}, size_hint=(0.7, 1), buttons=[cdt1]) self.dt1.open() # example button content def example_fun(self, ob): cdt1 = MDFlatButton(text="close", on_release=self.close_dt1) # ib = MDIconButton(icon="security", pos_hint={'center_x': 0.5, 'center_y': 0.5}) self.dt1 = MDDialog(title="Example Infected MD5_Checksums", text="1.1effb3351bd7222304e188421c52969a\n\n2.2ceee5b70dd6d020cffdcff586cafa0b\n\n" "3.69c0b64b41f318a4a959d70ea9486157\n\n4.537219e6e52cbbcdae6fdde1e47c9033\n\n5.772c7545a4eade7add5c89654648bbca", pos_hint={'center_x': 0.5, 'center_y': 0.5}, size_hint=(0.95, 1), buttons=[cdt1]) self.dt1.open() def close_dt1(self, ob): self.dt1.dismiss() # file Update button content def update(self, ob): ok12 = MDFlatButton(text="Update", on_release=self.goback22) cl = MDFlatButton(text="Close", on_release=self.goback2) self.z2 = MDDialog(title="Goto this Link ", text='https://virusshare.com/hashes.4n6 \n\nIf their is any file after 383\n' ' click on update else close', size_hint=(0.7, 1), buttons=[ok12, cl]) self.z2.open() def goback22(self, ob): try: res = urllib3.PoolManager() response = res.request('GET', 'https://virusshare.com/hashes/') with open('files1', 'ab+') as f: f.write(response.data) f.close() num_of_files = sum(1 for line in open('files1')) # print(num_of_files,",",num_of_files - 213,",", num_of_files - 13) os.remove("files1") for i in range(384, num_of_files - 12): fileNumber = '%05d' % i url = ('https://virusshare.com/hashes/VirusShare_%s.md5') % (fileNumber) # print(url) http1 = urllib3.PoolManager() HTML1 = http1.request('GET', url) # make requests to website with open('recent10.txt', 'ab')as fr: fr.write(HTML1.data) fr.close() try: file = open('recent10.txt', 'r') output_stream = [] input_stream_lines = (file.read()).split("\n") file.close() for line in input_stream_lines: if "#" in line: pass else: output_stream.append(line) # print(type(output_stream)) with open("betadata.txt", "a+") as wr: # wr.write("\n") wr.writelines("%s\n" % i for i in output_stream) wr.close() with open("betadata.txt", "rb")as rw: rwx = rw.read() bindata2 = bytearray(rwx) with gzip.open("batadata.txt.gz", "ab+")as wr1: wr1.write(bindata2) rw.close() except IOError: ok12 = MDFlatButton(text="OK", on_release=self.goback2) self.z2 = MDDialog(text='\033[91m' + "Error: can\'t find file or read data." + '\033[0m', buttons=[ok12], size_hint=(0.7, 1)) self.z2.open() exit(0) else: ok12 = MDFlatButton(text="OK", on_release=self.goback3) self.z3 = MDDialog( text='\x1b[6;30;42m' + "Unused charactors removed succesfully!!!\n" + '\x1b[0m' + fileNumber, buttons=[ok12], size_hint=(0.7, 1)) self.z3.open() ok122 = MDFlatButton(text="OK", on_release=self.goback4) self.z4 = MDDialog(text="Updated", buttons=[ok122], size_hint=(0.7, 1)) self.z4.open() except: print("Done") def goback2(self, obj): self.z2.dismiss() def goback3(self, obj): self.z3.dismiss() try: os.remove("recent10.txt") os.remove("beta_data.py") except: pass def goback4(self, obj): self.z4.dismiss() self.z2.dismiss() # related to deletefile def delete_infected(self, ob): dl = MDFlatButton(text="Delete", on_release=self.delete) self.del1_dialog = MDDialog(title="Infected File Name", text=self.f.text, pos_hint={'center_x': 0.5, 'center_y': 0.5}, size_hint=(0.7, 1), buttons=[dl]) self.del1_dialog.open() def delete(self, ob): try: os.remove(str(self.f.text).strip()) self.del1_dialog.dismiss() except: ok1 = MDFlatButton(text="OK", on_release=self.back) self.y = MDDialog(text="No Such File Please Enter correct Path", buttons=[ok1], size_hint=(0.7, 1)) self.y.open() def back(self, ob): self.del1_dialog.dismiss() self.y.dismiss()
class Lesson_two(Screen): k = 0 rez1 = 0 rez2 = 0 rez3 = 0 rez4 = 0 rez5 = 0 rez6 = 0 dialog = None def __init__(self, *args, **kwargs): super(Lesson_two, self).__init__(*args, **kwargs) self.ids[ 'toolbar'].title = "Урок №2 Сложение и вычитание на нижних косточках" self.ids.play_video.text = 'Начать урок' self.ids.exit.text = "Вернуться на главную страницу" self.ids.next_one.text = 'Задания' self.ids.prim.text = "Примеры" self.ids.prov.text = "Проверка" self.ids.next_up_2.text = 'Вернуться' self.ids.video.opacity = 0 self.primer() def stop_video(self): self.ids.video.state = 'stop' self.ids.play_video.text = 'Начать урок' def play_video(self): if self.ids.video.state == 'stop': self.ids.video.state = 'play' self.ids.video.opacity = 1 self.ids.play_video.text = 'Остановить урок' else: self.ids.video.state = 'stop' self.ids.video.opacity = 0 self.ids.play_video.text = 'Начать урок' def proverka(self): self.flag = True self.k = 0 id_i_list = ['i1', 'i2', 'i3', 'i4', 'i5', 'i6'] id_o_list = ['o1', 'o2', 'o3', 'o4', 'o5', 'o6'] for i in range(len(id_o_list)): if self.ids[id_o_list[i]].text == '': self.show_alert_dialog() self.flag = False if self.flag == True: for i in range(len(id_i_list)): self.ids[id_i_list[i]].opacity = 1 z = int(self.ids.o1.text) if self.rez1 == z: self.ids.i1.source = "Image/yes.png" self.k = self.k + 1 else: self.ids.i1.source = "Image/no.png" z = int(self.ids.o2.text) if self.rez2 == z: self.ids.i2.source = "Image/yes.png" self.k = self.k + 1 else: self.ids.i2.source = "Image/no.png" z = int(self.ids.o3.text) if self.rez3 == z: self.ids.i3.source = "Image/yes.png" self.k = self.k + 1 else: self.ids.i3.source = "Image/no.png" self.k = self.k + 1 z = int(self.ids.o4.text) if self.rez4 == z: self.ids.i4.source = "Image/yes.png" self.k = self.k + 1 else: self.ids.i4.source = "Image/no.png" z = int(self.ids.o5.text) if self.rez5 == z: self.ids.i5.source = "Image/yes.png" self.k = self.k + 1 else: self.ids.i5.source = "Image/no.png" z = int(self.ids.o6.text) if self.rez6 == z: self.ids.i6.source = "Image/yes.png" self.k = self.k + 1 else: self.ids.i6.source = "Image/no.png" print('k', self.k) if self.k == 6: if Login.urok < 2: Login.urok = 2 self.pars_urok(str(Login.urok)) Lesson_one.show_alert_dialog(Lesson_one) print(Login.urok) def pars_urok(self, text): self.manager.get_screen( 'mainscreen').ids.urok_bd.text = 'Вы закончили на Уроке №' + text def clean(self): id_o_list = ['o1', 'o2', 'o3', 'o4', 'o5', 'o6'] id_i_list = ['i1', 'i2', 'i3', 'i4', 'i5', 'i6'] for i in range(len(id_i_list)): self.ids[id_i_list[i]].opacity = 0 for i in range(len(id_o_list)): self.ids[id_o_list[i]].text = "" def primer(self): # Прямой счет на нижних косточках l1 = [[1, 2, 3, 4], [1, 2, 3, -1], [1, 2, -1, -2], [1, -1, -2, -3], [-1, -2, -3, -4]] id_o_list = ['o1', 'o2', 'o3', 'o4', 'o5', 'o6'] id_i_list = ['i1', 'i2', 'i3', 'i4', 'i5', 'i6'] for i in range(len(id_i_list)): self.ids[id_i_list[i]].opacity = 0 for i in range(len(id_o_list)): self.ids[id_o_list[i]].text = "" for j in range(6): s = random.randint(1, 4) rezstr = str(s) self.str = str(s) rez = s for i in range(4): s = random.choice(l1[rez]) self.str = str(s) rez = rez + s if s >= 0: rezstr = rezstr + ' + ' + str(s) else: s1 = (-1) * s rezstr = rezstr + ' - ' + str(s1) print(rez) rezstr = rezstr + ' = ' if j == 0: self.ids.p1.text = rezstr self.rez1 = rez if j == 1: self.ids.p2.text = rezstr self.rez2 = rez if j == 2: self.ids.p3.text = rezstr self.rez3 = rez if j == 3: self.ids.p4.text = rezstr self.rez4 = rez if j == 4: self.ids.p5.text = rezstr self.rez5 = rez if j == 5: self.ids.p6.text = rezstr self.rez6 = rez def show_alert_dialog(self): if not self.dialog: self.dialog = MDDialog( title='Ошибка', text='Некоторые поля остались пустыми', buttons=[MDFlatButton(text="CANCEL")], ) self.dialog.open()
def open_gps_access_popup(self): dialog=MDDialog(title="GPS Error",text="You need to enable to GPS access for the app to function properly") dialog.size_hint=[.8,.8] dialog.pos_hint={'center_x':.5,'center_y':.5} dialog.open()
class Locations(MDApp): def build(self): if platform == 'android': perms = ["android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.CAMERA", "android.permission.ACCESS_FINE_LOCATION"] haveperms = utils.acquire_permissions(perms) self.gps = plyer.gps self.gps.configure(self.gps_onlocation, self.gps_onstatus) import my_camera self.camera = my_camera.MyAndroidCamera() Window.bind(on_keyboard=self.popScreen) os.makedirs(utils.getDataDir() + "/images", exist_ok=True) self.markerMap = {} self.settings_cls = SettingsWithSidebar self.curMarker = None self.relocated = 0 self.dialog = None self.baseConfig = config.Config() self.error = self.baseConfig.getErrors() if self.error: Clock.schedule_once(self.show_error, 2) self.store = JsonStore("base.json") self.root = Page() try: base = self.store.get("base")["base"] self.baseConfig.getBase(self.base) except: base = self.baseConfig.getNames()[0] print("base", base) print("----------- /data/user/0/de.adfcmuenchen.abstellanlagen") utils.walk("/data/user/0/de.adfcmuenchen.abstellanlagen") # print("----------- cwd", os.getcwd()) # utils.walk(".") # print("------------getDataDir", utils.getDataDir()) # utils.walk(utils.getDataDir()) # print("------------getExternalFilesDir", utils.getExternalFilesDir()) # utils.walk(utils.getExternalFilesDir()) self.executor = ThreadPoolExecutor(max_workers=1) self.future = None laststored = self.getConfigValue("gespeichert") if not laststored: self.setConfigValue("gespeichert", time.strftime("%Y.%m.%d %H:%M:%S")) self.useGoogle = bool(self.getConfigValue("useGoogle")) self.setup(base) return self.root def setup(self, base): self.selected_base = base self.root.toolbar.title = self.selected_base self.root.datenbtn.text = self.selected_base self.store.put("base", base=self.selected_base) self.baseJS = self.baseConfig.getBase(self.selected_base) self.stellen = self.baseJS.get("gps").get("nachkommastellen") # self.root.sm.clear_widgets() does not work !? sm_screens = self.root.sm.screens[:] self.root.sm.clear_widgets(sm_screens) sm_screens = None self.karte = Karte(name="Karte") self.root.sm.add_widget(self.karte) self.mapview = self.karte.ids.mapview self.mapview.map_source = "osm-de" self.mapview.map_source.min_zoom = self.baseConfig.getMinZoom(self.selected_base) self.mapview.map_source.max_zoom = 19 self.mapview.map_source.bounds = self.baseConfig.getGPSArea(self.selected_base) # Hack, trying to fix random zoom bug # self.mapview._scatter.scale_min = 0.5 # MUH was 0.2 # self.mapview._scatter.scale_max: 2.0 # MUH was 3!? self.images = Images(self, name="Images") self.root.sm.add_widget(self.images) self.single = Single(self, name="Single") self.root.sm.add_widget(self.single) self.kamera = Kamera(self) self.account = Account(name="Account") self.root.sm.add_widget(self.account) self.daten = Daten(self, name="Daten") self.root.sm.add_widget(self.daten) self.zusatz = Zusatz(self, name="Zusatz") self.root.sm.add_widget(self.zusatz) self.pushScreen("Karte") if self.future is not None: self.future.result() self.future = self.executor.submit(self.setup2) def setup2(self): try: self.dbinst = db.DB.instance() self.dbinst.initDB(self) except Exception as e: self.message("Kann DB nicht öffnen:" + str(e)) raise (e) if self.useGoogle: try: self.message("Mit Google Sheets verbinden") self.gsheet = gsheets.GSheet(self) except Exception as e: self.message("Kann Google Sheets nicht erreichen:" + str(e)) raise (e) try: userInfo = self.gsheet.get_user_info(self.gsheet.getCreds()) self.message("Mit Google Photos verbinden als " + userInfo["name"]) self.gphoto = gphotos.GPhoto(self) except Exception as e: self.message("Kann Google Photos nicht erreichen:" + str(e)) raise (e) else: self.serverIntf = serverintf.ServerIntf(self) self.loadSheet(False) def show_markers(self, fromSheets, *args): with Spinner(): clat = self.mapview.centerlat clon = self.mapview.centerlon # roughly a square on the map delta = float(self.getConfigValue("delta", "5")) / 1000.0 minlat = clat - delta maxlat = clat + delta minlon = clon - 2 * delta maxlon = clon + 2 * delta for k in list(self.markerMap.keys()): # lat, lon = k.split(":") # lat = float(lat) # lon = float(lon) # if not (minlat < lat < maxlat and minlon < lon < maxlon): # markerOld = self.markerMap.get(k) # self.mapview.remove_marker(markerOld) # del self.markerMap[k] markerOld = self.markerMap.get(k) self.mapview.remove_marker(markerOld) del self.markerMap[k] if fromSheets: if self.useGoogle: self.message("Lade Daten von Google Sheets") try: sheetValues = self.gsheet.getValuesWithin(minlat, maxlat, minlon, maxlon) self.dbinst.fillWithSheetValues(sheetValues) except Exception as e: self.message("Konnte Daten nicht von Google Sheets laden: " + str(e)) raise (e) else: self.message("Lade Daten vom LocationsServer") try: dbValues = self.serverIntf.getValuesWithin(minlat, maxlat, minlon, maxlon) self.dbinst.fillWithDBValues(dbValues) except Exception as e: utils.printEx("Konnte Daten nicht vom LocationsServer laden", e) self.message("Konnte Daten nicht vom LocationsServer laden: " + str(e)) raise (e) self.message("Lade Map Marker") markers = self.dbinst.getMarkerLocs(minlat, maxlat, minlon, maxlon) self.show_markers2(markers) @mainthread def show_markers2(self, markers): for marker in markers: self.add_marker(marker[0], marker[1]) def show_account(self, *args): self.pushScreen("Account") def clear(self, *args): cur_screen = self.root.sm.current_screen if cur_screen.name == "Karte": return if cur_screen.name == "Daten": self.daten.clear() lat, lon = self.centerLatLon() self.add_marker(round(lat, self.stellen), round(lon, self.stellen)) return if cur_screen.name == "Zusatz": self.zusatz.clear() return if cur_screen.name == "Images": self.msgDialog("Auswahl", "Bitte ein Bild auswählen") return if cur_screen.name == "Single": src = cur_screen.im.source os.remove(src) src = os.path.basename(src) lat, lon = self.centerLatLon() self.dbinst.delete_images(lat, lon, src) self.add_marker(round(lat, self.stellen), round(lon, self.stellen)) self.show_daten(False) @mainthread def msgDialog(self, titel, text): if self.dialog is not None: self.dialog_dismiss() self.dialog = MDDialog(size_hint=(.8, .4), title=titel, text=text, buttons=[ MDFlatButton( text="Weiter", text_color=self.theme_cls.primary_color, on_press=self.dialog_dismiss )]) self.dialog.auto_dismiss = False self.dialog.open() def dialog_dismiss(self, *args): self.dialog.dismiss(animation=False, force=True) self.dialog = None def loadSheet(self, newCenter): if newCenter and self.future.running(): return if newCenter: lat = self.mapview.lat lon = self.mapview.lon self.store.put("latlon", lat=lat, lon=lon) else: try: lat = self.store.get("latlon")["lat"] lon = self.store.get("latlon")["lon"] except: lat = lon = 0 if lat == 0 or lon == 0: gps = self.baseJS.get("gps") lat = gps.get("center_lat") lon = gps.get("center_lon") self.center_on(lat, lon) if newCenter: # called from UI self.future = self.executor.submit(self.show_markers, True) else: self.show_markers(False) def storeImages(self, newImgs): # tuples to list, skip if image_url=row[7] is already set unsavedImgs = [list(row) for row in newImgs if not row[7].startswith("http")] # don't store already saved images again in gphoto: savedImgs = [list(row) for row in newImgs if row[7].startswith("http")] photo_objs = [{"filepath": utils.getDataDir() + "/images/" + row[6], "desc": row[6][0:row[6].index(".jpg")]} for row in unsavedImgs] # if len(photo_objs) > 0: # self.gphoto.upload_photos(photo_objs) pcnt = len(photo_objs) for i, photo_obj in enumerate(photo_objs): self.message(f"Speichere Bild {i + 1} von {pcnt}") if self.useGoogle: self.gphoto.upload_photos([photo_obj]) else: self.serverIntf.upload_photos([photo_obj]) for i, row in enumerate(unsavedImgs): old_image_path = row[6] new_image_path = photo_objs[i]["id"] new_image_url = photo_objs[i]["url"] self.dbinst.update_imagepath(old_image_path, new_image_path, new_image_url, row[4], row[5]) row[6] = new_image_path row[7] = new_image_url # store all of them in gsheets (duplicates removed by gsheet script) # or in Locationsserver DB unsavedImgs.extend(savedImgs) return unsavedImgs, photo_objs def storeSheet(self): if self.checkAlias(): if self.future.running(): self.msgDialog("Läuft noch", "Ein früherer Speichervorgang läuft noch!") return self.future = self.executor.submit(self.storeSheet2) def storeSheet2(self, *args): with Spinner(): try: laststored = self.getConfigValue("gespeichert") newvals = self.dbinst.getNewOrChanged(laststored) # special case images, store them first in gphotos newImgs = newvals[self.baseJS["db_tabellenname"] + "_images"] newImgs, photo_objs = self.storeImages(newImgs) imgCnt = len(newImgs) newvals[self.baseJS["db_tabellenname"] + "_images"] = newImgs recCnt = 0 self.message("Speichere Daten") for sheet_name in newvals.keys(): vals = newvals[sheet_name] if len(vals) > 0: recCnt += len(vals) if self.useGoogle: self.gsheet.appendValues(sheet_name, vals) else: self.serverIntf.appendValues(sheet_name, vals) self.setConfigValue("gespeichert", time.strftime("%Y.%m.%d %H:%M:%S")) for obj in photo_objs: os.remove(obj["filepath"]) self.msgDialog("Gespeichert", f"Es wurden {imgCnt} Fotos und {recCnt} neue oder geänderte Datensätze gespeichert") self.dbinst.deleteAll() except Exception as e: self.message("Konnte nicht in Google Drive oder Photos speichern:" + str(e)) raise (e) self.show_markers(True) def center_on(self, lat, lon): self.mapview.set_zoom_at(17, 0, 0, 2.0) self.mapview.center_on(lat, lon) self.mapview.centerlat = lat self.mapview.centerlon = lon self.relocated = 0 def map_relocated(self): self.relocated += 1 def centerLatLon(self): # if self.relocated == 1, the map has not moved since the last center_on if self.relocated == 1: return (self.mapview.centerlat, self.mapview.centerlon) return (self.mapview.lat, self.mapview.lon) def gps_onlocation(self, **kwargs): lat = kwargs["lat"] lon = kwargs["lon"] self.center_on(float(lat), float(lon)) self.gps.stop() def gps_onstatus(self, **kwargs): print("onsta", kwargs) def gps_fix(self, btn): # cannot get a continuous update to work, onlocation is called not more often than every 20 seconds # so update GPS loc once per button press if platform != 'android': return self.gps.start(minTime=10, minDistance=0) def show_images(self, *args): self.pushScreen("Images") self.images.show_images() def show_daten(self, delay): if self.checkAlias(): self.daten.setDaten() self.center_on(self.daten.lat, self.daten.lon) if delay and self.root.sm.current_screen.name == "Karte": Clock.schedule_once(self.show_daten2, 1) else: self.pushScreen("Daten") def show_daten2(self, *args): self.pushScreen("Daten") def on_pause(self): print("on_pause") # lat, lon = self.centerLatLon() # self.store.put("latlon", lat=lat, lon=lon) return True def on_stop(self): print("on_stop") return self.on_pause() def on_resume(self): print("on_resume") # base = self.store.get("base")["base"] # self.setup(base) return True def change_base(self, *args): self.dialog_dismiss() items = self.items for item in items: if item.ids.check.active: t = item.text if t != self.selected_base: self.setup(t) return def show_bases(self, *args): basen = list(self.baseConfig.getNames()) items = [ItemConfirm(text=base) for base in basen] x = basen.index(self.selected_base) for i, item in enumerate(items): items[i].ids.check.active = i == x self.items = items buttons = [MDFlatButton(text="OK", text_color=self.theme_cls.primary_color, on_press=self.change_base)] if self.dialog is not None: self.dialog_dismiss() self.dialog = MDDialog(size_hint=(.8, .4), type="confirmation", title="Auswahl der Datenbasis", text="Bitte Datenbasis auswählen", items=items, buttons=buttons) self.dialog.auto_dismiss = False # this line costed me two hours! Without, change_base is not called! self.dialog.open() def set_icon(self, instance_check, x): instance_check.active = True check_list = instance_check.get_widgets(instance_check.group) for check in check_list: if check != instance_check: check.active = False def createMarker(self, lat, lon): img = self.dbinst.existsImage(lat, lon) if self.baseJS.get("name") == "Abstellanlagen": col = self.dbinst.getRedYellowGreen(lat, lon) elif self.dbinst.existsDatenOrZusatz(lat, lon): col = "red" else: col = None if not img and col is None: return None if col is None: col = "red" if img: src = col + "_plus48.png" else: src = col + "48.png" mm = MyMapMarker(lat=lat, lon=lon, source=utils.getCurDir() + "/icons/" + src) return mm def add_marker(self, lat, lon): lat_round = round(lat, self.stellen) lon_round = round(lon, self.stellen) markerMapKey = str(lat_round) + ":" + str(lon_round) markerOld = self.markerMap.get(markerMapKey, None) markerNew = self.createMarker(lat_round, lon_round) if markerOld is not None: self.mapview.remove_marker(markerOld) if markerNew is None: del self.markerMap[markerMapKey] else: self.mapview.add_marker(markerNew) self.markerMap[markerMapKey] = markerNew def clickMarker(self, marker): self.curMarker = marker self.center_on(marker.lat, marker.lon) self.show_daten(True) def do_capture(self, *args): if self.checkAlias(): # and self.root.sm.current_screen.name == "Daten": self.daten.setDaten() self.kamera.do_capture(self.daten.lat, self.daten.lon) def checkAlias(self): if not self.account.ids.aliasname.text: self.msgDialog("Account", "Bitte den Aliasnamen ausfüllen") self.pushScreen("Account") return False self.dbinst.aliasname = self.account.ids.aliasname.text return True def show_error(self, *args): self.msgDialog("Konfigurationsfehler", self.error) def pushScreen(self, nextScreen): self.lastScreen = self.root.sm.current_screen.name self.root.sm.current = nextScreen def popScreen(self, window, key, *largs): if key != 27: return True if self.lastScreen is None: if self.dialog is not None: self.dialog_dismiss() self.dialog = MDDialog(size_hint=(.8, .4), title="Beenden?", text="Möchten Sie die App beenden?", buttons=[ MDFlatButton( text="Ja", text_color=self.theme_cls.primary_color, on_press=self.stopApp), MDFlatButton( text="Nein", text_color=self.theme_cls.primary_color, on_press=self.dialog_dismiss), ]) self.dialog.auto_dismiss = False # !!! self.dialog.open() else: self.root.sm.current = self.lastScreen self.lastScreen = None return True configDefaults = { # 'boolexample': True, # 'numericexample': 10, # 'stringexample': 'somestring', # 'optionsexample': 'options2', # 'pathexample': 'c:/temp', 'gespeichert': '', 'maxdim': 1024, 'thumbnaildim': 200, 'useGoogle': False, 'delta': 5, 'serverName': "raspberrylan.1qgrvqjevtodmryr.myfritz.net", 'serverPort': 80, 'restoreDefaults': False, } # see https://www.youtube.com/watch?v=oQdGWeN51EE def build_config(self, config): config.setdefaults('Locations', self.configDefaults) def build_settings(self, settings): settings_json = json.dumps([ {'type': 'title', 'title': 'Einstellungen'}, {'type': 'string', 'title': 'Gespeichert', 'desc': 'Datum des letzten Speicherns', 'section': 'Locations', 'key': 'gespeichert'}, {'type': 'numeric', 'title': 'Max Dim', 'desc': 'Max Größe der Photos vom LocationsServer oder Goggle Photos', 'section': 'Locations', 'key': 'maxdim'}, {'type': 'numeric', 'title': 'Vorschaubilder Dim', 'desc': 'Größe der Vorschaubilder', 'section': 'Locations', 'key': 'thumbnaildim'}, {'type': 'bool', 'title': 'Speichern mit Google', 'desc': 'On: Gsheets, GPhotos, Off: LocationsServer', 'section': 'Locations', 'key': 'useGoogle'}, {'type': 'numeric', 'title': 'Größe der MapMarker-Region', 'desc': 'Bestimmt die Größe der Kartenfläche, die mit MapMarkern gefüllt ist', 'section': 'Locations', 'key': 'delta'}, {'type': 'string', 'title': 'Server URL', 'desc': 'Name des LocationsServer', 'section': 'Locations', 'key': 'serverName'}, {'type': 'numeric', 'title': 'Server Portnummer', 'desc': 'Portnummer des LocationsServer', 'section': 'Locations', 'key': 'serverPort'}, {'type': 'bool', 'title': 'Default-Werte wiederherstellen', 'desc': 'Hier sichtbar leider nur nach Neustart, aber schon wirksam!', 'section': 'Locations', 'key': 'restoreDefaults'}, # {'type': 'bool', # 'title': 'A boolean setting', # 'desc': 'Boolean description text', # 'section': 'Locations', # 'key': 'boolexample'}, # {'type': 'numeric', # 'title': 'A numeric setting', # 'desc': 'Numeric description text', # 'section': 'Locations', # 'key': 'numericexample'}, # {'type': 'options', # 'title': 'An options setting', # 'desc': 'Options description text', # 'section': 'Locations', # 'key': 'optionsexample', # 'options': ['option1', 'option2', 'option3']}, # {'type': 'path', # 'title': 'A path setting', # 'desc': 'Path description text', # 'section': 'Locations', # 'key': 'pathexample'} ]) settings.add_json_panel('Locations', self.config, data=settings_json) def on_config_change(self, config, section, key, value): print(config, section, key, value) if section != "Locations": return if key == "useGoogle": self.useGoogle = bool(int(value)) # value is "0" or "1" !?! self.dbinst.deleteAll() self.gsheet = None self.gphoto = None self.serverIntf = None self.setup(self.selected_base) if key == "restoreDefaults": defaults = self.configDefaults.copy() del defaults["gespeichert"] self.config.setall(section, defaults) self.config.write() def getConfigValue(self, param, fallback=""): if param == "useGoogle": return self.config.getboolean("Locations", param) return self.config.get("Locations", param, fallback=fallback) def setConfigValue(self, param, value): self.config.set("Locations", param, value) self.config.write() def stopApp(self, *args): if self.future is not None and not self.future.done(): self.msgDialog("Bitte warten", "Das Speichern ist noch nicht beendet!") return self.stop() @mainthread def message(self, m): # toast(m, duration=5.0) t = Toast(duration=5) t.toast(m)
class ComicRackReader(MDApp): nav_drawer = ObjectProperty() lang = StringProperty("en") open_comics_list = ListProperty() sync_folder = StringProperty() full_screen = False LIST_SCREENS = ListProperty() store_dir = StringProperty() comic_db = ObjectProperty() username = StringProperty() password = StringProperty() api_key = StringProperty() max_books_page = NumericProperty() open_last_comic_startup = NumericProperty() how_to_open_comic = StringProperty() app_started = BooleanProperty(False) open_comic_screen = StringProperty() sync_is_running = BooleanProperty(False) def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events_program) Window.soft_input_mode = "below_target" self.LIST_SCREENS = [ "base", "license", "about", "server_lists_screen", "syncscreen", "server_readinglists_screen", "single_file_screen", "open_file_screen", ] self.list_previous_screens = ["base"] self.window = Window self.config = ConfigParser() self.manager = None self.window_language = None self.exit_interval = False self.comic_thumb_height = 240 self.comic_thumb_width = 156 self.dict_language = literal_eval( open(os.path.join(self.directory, "data", "locales", "locales.txt")).read()) # self.translation = Translation( # self.lang, 'Ttest', os.path.join(self.directory, # data', 'locales') # ) self.base_url = "" self.settings_cls = MySettings self.md_manager = None self.open_comic_screen = "" # def get_application_config(self): # return super(ComicRackReader, self).get_application_config( # '{}/%(appname)s.ini'.format(self.directory)) def build_config(self, config): """Creates an application settings file ComicRackReader.ini.""" config.adddefaultsection("Language") config.adddefaultsection("Saved") config.setdefault("Language", "language", "en") config.setdefault("Saved", "last_comic_id", "") config.setdefault("Saved", "last_comic_type", "") config.setdefault("Saved", "last_reading_list_id", "") config.setdefault("Saved", "last_reading_list_name", "") config.setdefault("Saved", "last_pag_pagnum", "") config.setdefaults( "General", { "base_url": "http://", "storagedir": self.user_data_dir, "use_api_key": 0, "api_key": "", "username": "", "password": "", "open_last_comic_startup": 0, "how_to_open_comic": "Open Local Copy", # 'use_pagination': '1', "max_books_page": 25, }, ) config.setdefaults("Sync", { "sync_folder": self.user_data_dir, "max_num_sync": 50 }) config.setdefaults( "Display", { "mag_glass_size": 200, "right2left": 0, "dblpagesplit": "0", "stretch_image": "0", "keep_ratio": "0", "reading_list_icon_size": "Small", "max_comic_pages_limit": 50, "max_height": 1500, }, ) config.setdefaults( "Screen Tap Control", { "bottom_right": "Next Page", "bottom_left": "Prev Page", "bottom_center": "Open Page Nav", "top_right": "Return to Home Screen", "top_left": "Precodv Page", "top_center": "Open Collection Browser", "middle_right": "None", "middle_left": "None", "middle_center": "Open NavBar", "dbl_tap_time": 250, }, ) config.setdefaults( "Hotkeys", { "hk_next_page": ".", "hk_prev_page": ",", "hk_open_page_nav": "p", "hk_open_collection": "j", "hk_return_comic_list": "c", "hk_return_base_screen": "r", "hk_toggle_navbar": "n", "hk_toggle_fullscreen": "f", }, ) def set_value_from_config(self, *args): """Sets the values of variables from the settings file ComicRackReader.ini.""" self.config.read(os.path.join(self.directory, "comicrackreader.ini")) self.lang = self.config.get("Language", "language") self.sync_folder = self.config.get("Sync", "sync_folder") self.store_dir = os.path.join(self.config.get("General", "storagedir"), "store_dir") if not Path(self.store_dir).is_dir(): os.makedirs(self.store_dir) self.base_url = self.config.get("General", "base_url").rstrip("\\") print(f"self.base_url:{self.base_url}") self.api_key = self.config.get("General", "api_key") self.username = self.config.get("General", "username") self.password = self.config.get("General", "password") self.api_url = self.base_url + "/API" self.my_data_dir = os.path.join(self.store_dir, "comics_db") if not os.path.isdir(self.my_data_dir): os.makedirs(self.my_data_dir) self.max_books_page = int(self.config.get("General", "max_books_page")) self.open_last_comic_startup = self.config.get( "General", "open_last_comic_startup") self.how_to_open_comic = self.config.get("General", "how_to_open_comic") def config_callback(self, section, key, value): if key == "storagedir": def __callback_for_please_wait_dialog(*args): if args[0] == "Delete Database": self.stop() elif args[0] == "Move Database": print("move") db_folder = self.my_data_dir old_dbfile = os.path.join(db_folder, "ComicRackReader.db") store_dir = os.path.join(value, "store_dir") new_data_dir = os.path.join(store_dir, "comics_db") new_dbfile = os.path.join(new_data_dir, "ComicRackReader.db") if not os.path.isdir(store_dir): os.makedirs(store_dir) if not os.path.isdir(new_data_dir): os.makedirs(new_data_dir) copyfile(old_dbfile, new_dbfile) self.stop() self.please_wait_dialog = MDDialog( title="Please Restart ComicRackReader", size_hint=(0.8, 0.4), text_button_ok="Delete Database", text_button_cancel="Move Database", text= f"Storage/Databse dir changed Delete Data or Move it to new dir \nApp will Close please restart it for new setting to take effect?", events_callback=__callback_for_please_wait_dialog, ) self.please_wait_dialog.open() else: config_items = { "base_url": "base_url", "api_key": "api_key", "sync_folder": "sync_folder", "password": "******", "username": "******", "max_books_page": "max_books_page", "sync_folder": "sync_folder", } item_list = list(config_items.keys()) if key in item_list: item = config_items[key] setattr(self, item, value) self.api_url = self.base_url + "/API" # self.my_data_dir = os.path.join(self.store_dir, 'comics_db') def build(self): r = Factory.register r("MDToolbarTooltips", module="libs.uix.widgets.mytoolbar") self.set_value_from_config() from libs.uix.baseclass.basescreen import BaseScreen from libs.uix.baseclass.about import About from libs.uix.baseclass.local_lists_screen import LocalListsScreen from libs.uix.baseclass.local_readinglists_screen import ( LocalReadingListsScreen, ) # from libs.uix.baseclass.navdrawer import NavDrawer from libs.uix.baseclass.server_comicbook_screen import ( ServerComicBookScreen, ) from libs.uix.baseclass.server_lists_screen import ServerListsScreen from libs.uix.baseclass.server_readinglists_screen import ( ServerReadingListsScreen, ) from libs.uix.baseclass.license import License from libs.uix.lists import SingleIconItem start_db() path = os.path.dirname(__file__) icon_path = os.path.join(path, f"data{os.sep}") self.icon = os.path.join(icon_path, f"icon.png") self.title = "ComicRackReader 1.2.4" self.theme_cls.primary_palette = "Amber" self.load_all_kv_files( os.path.join(self.directory, "libs", "uix", "kv")) self.screen = StartScreen() # program main screen self.manager = self.screen.ids.manager action_bar = self.screen.ids.action_bar # Left side Action bar Icons action_bar.left_action_items = [ ["home", "Home", lambda x: self.switch_base_screen()], ["settings", "Settings", lambda x: self.open_settings()], ["fullscreen", "Full Screen", lambda x: self.toggle_full_screen()], ] # right side Action bar Icons action_bar.right_action_items = [ ["file-cabinet", "Open File", lambda x: self.file_manager_open()], [ "server", "ComicRack Reading Lists", lambda x: self.switch_server_lists_screen(), ], [ "view-list", "Current Server Reading List", lambda x: self.switch_readinglists_screen(), ], [ "folder-sync", "Local Reading Lists", lambda x: self.switch_local_lists_screen(), ], [ "playlist-check", "Current Local Reading List", lambda x: self.switch_local_readinglists_screen(), ], [ "book-open-page-variant", "Open Comic Book", lambda x: self.switch_comic_reader(), ], ["close-box-outline", "Exit App", lambda x: self.stop()], ] self.config.add_callback(self.config_callback) return self.screen def load_all_kv_files(self, directory_kv_files): for kv_file in os.listdir(directory_kv_files): kv_file = os.path.join(directory_kv_files, kv_file) if os.path.isfile(kv_file): with open(kv_file, encoding="utf-8") as kv: Builder.load_string(kv.read()) def on_config_change(self, config, section, key, value): pass def events_program(self, instance, keyboard, keycode, text, modifiers): c = Keyboard() """Called when you press a Key""" app = App.get_running_app() current_screen = app.manager.current_screen hk_next_page = app.config.get("Hotkeys", "hk_next_page") hk_prev_page = app.config.get("Hotkeys", "hk_prev_page") hk_open_page_nav = app.config.get("Hotkeys", "hk_open_page_nav") hk_open_collection = app.config.get("Hotkeys", "hk_open_collection") hk_return_comic_list = app.config.get("Hotkeys", "hk_return_comic_list") hk_return_base_screen = app.config.get("Hotkeys", "hk_return_base_screen") hk_toggle_navbar = app.config.get("Hotkeys", "hk_toggle_navbar") hk_toggle_fullscreen = app.config.get("Hotkeys", "hk_toggle_fullscreen") Logger.debug(f"keyboard:{keyboard}") if current_screen.name not in self.LIST_SCREENS: if keyboard in (c.string_to_keycode(hk_next_page), 275): current_screen.load_next_slide() elif keyboard in (c.string_to_keycode(hk_prev_page), 276): current_screen.load_prev_slide() elif keyboard == c.string_to_keycode(hk_open_page_nav): current_screen.page_nav_popup_open() elif keyboard == c.string_to_keycode(hk_open_collection): current_screen.comicscreen_open_collection_popup() elif keyboard == c.string_to_keycode(hk_toggle_navbar): current_screen.toggle_option_bar() elif keyboard == c.string_to_keycode(hk_return_comic_list): app.switch_readinglists_screen() elif keyboard == c.string_to_keycode(hk_return_base_screen): app.show_action_bar() app.manager.current = "base" elif keyboard in (1001, 27): if self.nav_drawer.state == "open": self.nav_drawer.toggle_nav_drawer() self.back_screen(event=keyboard) elif keyboard == c.string_to_keycode(hk_toggle_fullscreen): self.toggle_full_screen() else: if keyboard in (282, 319): pass elif keyboard == c.string_to_keycode(hk_toggle_fullscreen): self.toggle_full_screen() elif keyboard == c.string_to_keycode(hk_return_comic_list): app.manager.current = "server_readinglists_screen" elif keyboard == c.string_to_keycode(hk_return_base_screen): app.show_action_bar() app.switch_base_screen() elif keyboard in (1001, 27): if self.nav_drawer.state == "open": self.nav_drawer.toggle_nav_drawer() self.back_screen(event=keyboard) return True def toggle_full_screen(self): if App.get_running_app().full_screen is False: Window.fullscreen = "auto" App.get_running_app().full_screen = True else: App.get_running_app().full_screen = False Window.fullscreen = False def back_screen(self, event=None): """Screen manager Called when the Back Key is pressed.""" # BackKey pressed. if event in (1001, 27): if self.manager.current == "base": self.dialog_exit() return try: self.manager.current = self.list_previous_screens.pop() except: # noqa self.manager.current = "base" # self.screen.ids.action_bar.title = self.title def show_license(self, *args): self.screen.ids.license.ids.text_license.text = ("%s") % open( os.path.join(self.directory, "LICENSE"), encoding="utf-8").read() self.nav_drawer._toggle() self.manager.current = "license" self.screen.ids.action_bar.left_action_items = [[ "chevron-left", lambda x: self.back_screen(27) ]] self.screen.ids.action_bar.title = "MIT LICENSE" def dialog_exit(self): def check_interval_press(interval): self.exit_interval += interval if self.exit_interval > 5: self.exit_interval = False Clock.unschedule(check_interval_press) if self.exit_interval: sys.exit(0) Clock.schedule_interval(check_interval_press, 1) toast("Press Back to Exit") def on_lang(self, instance, lang): self.translation.switch_lang(lang) def build_settings(self, settings): settings.add_json_panel("Sync Settings", self.config, data=settings_json_sync) settings.add_json_panel("General Settings", self.config, data=settings_json_server) settings.add_json_panel("Display Settings", self.config, data=settings_json_dispaly) settings.add_json_panel( "Screen Tap Control", self.config, data=settings_json_screen_tap_control, ) settings.add_json_panel("Hotkeys", self.config, data=settings_json_hotkeys) def switch_server_lists_screen(self): self.set_screen("List of Reading Lists Screen") self.manager.current = "server_lists_screen" def switch_readinglists_screen(self): screen = self.manager.get_screen("server_readinglists_screen") self.set_screen(screen.reading_list_title) self.manager.current = "server_readinglists_screen" def switch_local_readinglists_screen(self): screen = self.manager.get_screen("local_readinglists_screen") self.set_screen(screen.reading_list_title) self.manager.current = "local_readinglists_screen" def switch_comic_reader(self): if self.open_comic_screen: self.manager.current = "comic_book_screen" else: toast("No ComicBook Open") def switch_base_screen(self): self.set_screen("ComicRackReader Home Screen") self.manager.current = "base" def switch_local_lists_screen(self): self.set_screen("Local Sync Comics") self.manager.current = "local_lists_screen" def set_screen(self, title): self.screen.ids.action_bar.title = title def hide_action_bar(self): self.screen.ids.action_bar.opacity = 0 self.screen.ids.action_bar.disabled = True self.screen.ids.action_bar.size_hint_y = None self.screen.ids.action_bar.size = (0, 0) def show_action_bar(self): self.screen.ids.action_bar.opacity = 1 self.screen.ids.action_bar.disabled = False self.screen.ids.action_bar.size = ( Window.width, self.theme_cls.standard_increment, ) # FileManger def file_manager_open(self): previous = False if not self.md_manager: self.md_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.md_manager.add_widget(self.file_manager) self.file_manager.show(self.sync_folder) self.manager_open = True self.md_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; """ has_cb_files = False self.exit_manager() if os.path.isfile(path): ext = os.path.splitext(path)[-1].lower() if ext in (".cbz", ".cbr", ".cb7", ".cbp"): has_cb_files = True data = {"items": []} comic_data = convert_comicapi_to_json(path) data["items"].append(comic_data) new_rl = ComicReadingList( name="Single_FileLoad", data=data, slug="FileOpen", mode="FileOpen", ) new_comic = ComicBook(data["items"][0], mode="FileOpen") new_rl.add_comic(new_comic) else: pass elif os.path.isdir(path): if os.path.isdir(path): onlyfiles = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) ] data = {"items": []} for file in onlyfiles: ext = os.path.splitext(file)[-1].lower() if ext in (".cbz", ".cbr", ".cb7", ".cbp"): file_path = os.path.join(path, file) comic_data = convert_comicapi_to_json(file_path) data["items"].append(comic_data) has_cb_files = True else: pass if has_cb_files is True: new_rl = ComicReadingList(name=path, data=data, slug="path", mode="FileOpen") for item in new_rl.comic_json: comic_index = new_rl.comic_json new_comic = ComicBook( item, readinglist_ob=new_rl, comic_index=comic_index, mode="FileOpen", ) new_rl.add_comic(new_comic) if has_cb_files is True: max_books_page = int(self.config.get("General", "max_books_page")) paginator_obj = Paginator(new_rl.comics, max_books_page) screen = self.manager.get_screen("comic_book_screen") screen.setup_screen( readinglist_obj=new_rl, comic_obj=new_rl.comics[0], paginator_obj=paginator_obj, pag_pagenum=1, view_mode="FileOpen", ) self.manager.current = "comic_book_screen" toast(f"Opening {new_rl.comics[0].__str__}") else: toast("A vaild ComicBook File was not found") self.md_manager = None def exit_manager(self, *args): """Called when the user reaches the root of the directory tree.""" self.md_manager.dismiss() self.manager_open = False def delayed_work(self, func, items, delay=0): """Apply the func() on each item contained in items """ if not items: return def _sync_delayed_work(*l): item = items.pop(0) if func(item) is False or not len(items): return False Clock.schedule_once(_sync_delayed_work, delay) Clock.schedule_once(_sync_delayed_work, delay)
class LoginDemo(MDApp): current_provider = "" def build(self): initialize_google( self.after_login, self.error_listener, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, ) initialize_fb( self.after_login, self.error_listener, FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET, ) initialize_github( self.after_login, self.error_listener, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, ) if platform == "android": NewRelic.withApplicationToken( "eu01xx3a293465cda73cd2f5b1154ed969b9af4b27-NRMA" ).start(context.getApplication()) # set_statusbar_color() tmp = Builder.load_string(kv) if platform != "android": from kivymd.uix.dialog import MDDialog from kivymd.uix.button import MDFlatButton btn = MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color) btn.bind(on_release=lambda *args: (stop_login(), self.dialog.dismiss())) self.dialog = MDDialog( title="", size_hint_x=None, size_hint_y=None, width="250dp", type="custom", auto_dismiss=False, content_cls=Content(), buttons=[btn], ) return tmp def on_start(self): # if platform == "android": # if auto_login(login_providers.google): # self.current_provider = login_providers.google # elif auto_login(login_providers.facebook): # self.current_provider = login_providers.facebook # elif auto_login(login_providers.github): # self.current_provider = login_providers.github # elif auto_login(login_providers.twitter): # self.current_provider = login_providers.twitter # primary_clr= [ 108/255, 52/255, 131/255 ] # hex_color= '#%02x%02x%02x' % (int(primary_clr[0]*200), int(primary_clr[1]*200), int(primary_clr[2]*200)) # set_statusbar_color() pass def show_login_progress(self): if platform != "android": self.dialog.open() def hide_login_progress(self): if platform != "android": self.dialog.dismiss() def fb_login(self, *args): # if platform != "android": # self.dialog.open() login_facebook() self.current_provider = login_providers.facebook self.show_login_progress() def gl_login(self, *args): # if platform != "android": # self.dialog.open() login_google() self.current_provider = login_providers.google self.show_login_progress() def git_login(self, *args): # if platform != "android": # self.dialog.open() login_github() self.current_provider = login_providers.github self.show_login_progress() def twitter_login(self, *args): # if platform != "android": # self.dialog.open() login_twitter() self.current_provider = login_providers.twitter self.show_login_progress() def logout_(self): if self.current_provider == login_providers.google: logout_google(self.after_logout) if self.current_provider == login_providers.facebook: logout_facebook(self.after_logout) if self.current_provider == login_providers.github: logout_github(self.after_logout) if self.current_provider == login_providers.twitter: logout_twitter(self.after_logout) def after_login(self, name, email, photo_uri): self.hide_login_progress() if platform == "android": show_toast("Logged in using {}".format(self.current_provider)) else: Snackbar(text="Logged in using {}".format(self.current_provider)).show() self.root.current = "homescreen" self.update_ui(name, email, photo_uri) def after_logout(self): self.update_ui("", "", "") self.root.current = "loginscreen" if platform == "android": show_toast(text="Logged out from {} login".format(self.current_provider)) else: Snackbar( text="Logged out from {} login".format(self.current_provider) ).show() def update_ui(self, name, email, photo_uri): self.root.ids.home_screen.ids.user_photo.add_widget( AsyncImage( source=photo_uri, size_hint=(None, None), height=dp(60), width=dp(60) ) ) self.root.ids.home_screen.ids.user_name.title = "Welcome, {}".format(name) self.root.ids.home_screen.ids.user_email.text = ( "Your Email: {}".format(email) if email else "Your Email: Could not fetch email" ) def error_listener(self): if platform == "android": show_toast("Error logging in.") else: Snackbar(text="Error logging in. Check connection or try again.").show() Clock.schedule_once(lambda *args: self.hide_login_progress()) def send_to_github(self): if platform == "android": intent = Intent() intent.setAction(Intent.ACTION_VIEW) intent.setData(Uri.parse("https://github.com/shashi278/social-auth-kivy")) context.startActivity(intent) else: import webbrowser webbrowser.open("https://github.com/shashi278/social-auth-kivy")
class RightMenuIconButton(IRightBodyTouch, MDIconButton): task_instance = ObjectProperty() def __init__(self, **kwargs): super().__init__(**kwargs) # content for menu task_menu_items = [ {"text": 'edit', }, {'text': 'delete', } ] # created menu as dropdown menu self.task_menu = MDDropdownMenu( caller=self, items=task_menu_items, width_mult=2, selected_color=self.theme_cls.primary_dark_hue, ) # pressing triggeres task_menu_call self.task_menu.bind(on_release=self.task_menu_call) def task_menu_call(self, instance_menu, instance_menu_item, *args): # for easier referencing of Task (for delition, editing, ...) task_instance = self.parent.parent list_instance = self.parent.parent.parent # click delete if instance_menu_item.text == 'delete': self.task_menu_delete( instance_menu, task_instance, list_instance) # click edit elif instance_menu_item.text == 'edit': self.edit_task_menu(menu_instance=instance_menu, task_instance=task_instance) def task_menu_delete(self, menu_instance, task_instance, list_instance, *args): list_instance.remove_widget(task_instance) menu_instance.dismiss() def edit_task_menu(self, menu_instance, task_instance, *args): # task_instance needs to be parsed to self.change_task (parsed function) self.show_task_template(title='Change Task', task_instance=task_instance, function=lambda *args: self.change_task( task_instance, template, priority_dict=priority_translation) ) # reference to content of MDDialog template = self.dialog.content_cls.ids # dictionary for convertion of priority as int (in Task) and TaskTemplate.MDBoxLayout.priority_choice priority_translation = { '0': 'low', '1': 'normal', '2': 'high', '3': 'very high' } priority_key = str(len(task_instance.ids.priority_id.text)) # set task attributes in TaskTemplate Widgets template.task_description.text = task_instance.description # set priority chooser to value of priority in Task template.priority_choice.text = priority_translation[str( priority_key)] # set value for due date to value Task.due_date template.due_date_time_task.text = task_instance.due_date # close TaskTemplate menu_instance.dismiss() return None def show_task_template(self, title, task_instance=None, function=None): self.dialog = None if not self.dialog: self.dialog = MDDialog( title=str(title) + ':', type="custom", content_cls=TaskTemplate(task_instance=task_instance), buttons=[ MDFlatButton( text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.close_task_template ), MDFlatButton( text="SAVE", text_color=self.theme_cls.primary_color, on_release=(lambda *args: function()) ), ], ) self.dialog.open() def close_task_template(self, *args): self.dialog.dismiss() def change_task(self, task_instance, template, priority_dict, * args): # update task description task_instance.description = template.task_description.text # update task priority new_priority = [key for key, item in priority_dict.items( ) if item == template.priority_choice.text][0] task_instance.priority = new_priority # update due date task_instance.due_date = template.due_date_time_task.text # get index of old taks task_index = task_instance.find_task_index_in_TaskView() # replace old task with new one # OnelineTask or TwolineTask depending on due_date # automaticly removes old task task_list = task_instance.parent.parent.parent task_list.switch_task_type( description=task_instance.description, due_date=task_instance.due_date, priority=new_priority, index=task_index ) # closes TaskTemplate self.dialog.dismiss() return None