class TopBar(Widget): __grid = None # type: GridLayout def __init__(self, height: int, **kwargs): super(TopBar, self).__init__(**kwargs) topBack = Image() topBack.color = [0, 0, 0, 1] topBack.width = Window.size[0] topBack.height = height self.add_widget(topBack) self.__grid = GridLayout() self.__grid.cols = 10 self.__grid.rows = 1 self.__grid.width = Window.size[0] self.__grid.height = height self.add_widget(self.__grid) def clear_buttons(self): for child in self.__grid.children: self.__grid.remove_widget(child) def add_buttons(self, buttons): for index in range(0, len(buttons)): btn = buttons[index] # type: Button self.__grid.add_widget(btn, self.__grid.cols - 1 - index)
class Day_Select(GridLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.output_path = 'Output/' self.cols = 2 self.flag = 0 self.padding = [100, 100, 100, 100] self.spacing = [20, 20] self.name = TextInput(multiline=False, size_hint=(.2, None), height=40) add = Button(text='ADD', font_size=30, italic=True, background_color=[255, 1, 1, 1]) #Next = Button(text='NEXT', font_size = 30, italic = True, background_color = [1, 1, 255, 1]) self.label = Label(text='Add Day!!!', font_size=38, color=[255, 255, 255, 1]) add.bind(on_press=self.add) #Next.bind(on_press = self.gonext) self.button_layout = GridLayout(rows=4, spacing=[20, 20]) self.button_layout.add_widget(self.name) self.button_layout.add_widget(add) #self.button_layout.add_widget(Next) self.button_layout.add_widget(self.label) self.add_widget(self.button_layout) def add(self, instance): if len(self.name.text) != 0: global day day = self.name.text UI_interface.screen_manager.current = "Home" if day == 'day_1': print("First day") embeddings, usernames = readAllBlobData() for username in usernames: if username not in attendance.keys(): attendance[username] = 'Absent' insert_data(username, 0, day) else: print("Not 1st day") bar_graph(day) pie_chart(day) embeddings, usernames = readAllBlobData() for username in usernames: if username not in attendance.keys(): attendance[username] = 'Absent' insert_data(username, 0, day) else: self.button_layout.remove_widget(self.label) self.label = Label(text='Enter Day', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label)
class CurrentBlockScreen(Screen): def __init__(self): self.root = Screen(name="CurrentBlockScreen") self.grid = GridLayout( cols=1) #block content, then comment scrollview, then text input #for i in data: #data is map of comments i think mine = Button(text="mine") mine.bind(on_press=self.mine) switch_page = Button(text="Switch Page") switch_page.bind(on_press=self.switch_page) refresh_page = Button(text="Refresh Page", background_color="blue") refresh_page.bind(on_press=self.reload_current_block) toolbar = GridLayout(cols=3, size_hint_y=.3) toolbar.add_widget(refresh_page) toolbar.add_widget(switch_page) toolbar.add_widget(mine) self.root.add_widget(self.grid) self.block_display = CurrentBlockDisplay(-1).root self.block_display_container = GridLayout( cols=1) #just to make refresh stay in one spot self.block_display_container.add_widget(self.block_display) self.grid.add_widget(self.block_display_container) self.grid.add_widget(toolbar) def switch_page(self, instance): app = App.get_running_app() app.sm.current = "ChainScreen" def mine(self, instance): app = App.get_running_app() app.blockchain.mine(app.uname) def reload_current_block(self, instance): #app = App.get_running_app() #data = app.blockchain.chain[-1] self.block_display_container.remove_widget(self.block_display) self.block_display = CurrentBlockDisplay(-1).root self.block_display_container.add_widget(self.block_display)
class MainScreen(Screen): def __init__(self, **kw): super(MainScreen, self).__init__(**kw) super(MainScreen, self).__init__(**kw) box = BoxLayout(orientation='vertical') self.items_grid = GridLayout(cols=1, spacing=10, size_hint_y=None, padding=10) # Make sure the height is such that there is something to scroll. self.items_grid.bind(minimum_height=self.items_grid.setter('height')) scroll_view = ScrollView(size_hint=(1, 1), size=(Window.width, Window.height)) scroll_view.add_widget(self.items_grid) box.add_widget(scroll_view) box.add_widget(Button(text='Добавить элемент;)', on_press=lambda x: set_screen('add_item'), size_hint_y=None, height=dp(80))) self.add_widget(box) def on_enter(self): # Будет вызвана в момент открытия экрана all_items = gv.db.get_all_items() for (item_id, item_title, item_time_create) in all_items: wrapper = BoxLayout(size_hint_y=None, height=dp(40),) btn = Button( text=item_title, on_press=lambda x, item_id=item_id: self._view_item(item_id) ) btn_del = Button( text='DEL', size_hint_x=None, width=dp(70), on_press=lambda x, item_id=item_id, wrapper=wrapper: self._del_item(item_id, wrapper) ) wrapper.add_widget(btn_del) wrapper.add_widget(btn) self.items_grid.add_widget(wrapper) def on_leave(self): # Будет вызвана в момент закрытия экрана self.items_grid.clear_widgets() def _view_item(self, id_item): gv.cur_id_item = id_item set_screen('view_item') def _del_item(self, id_item, wrapper): gv.db.delete_item(id_item) self.items_grid.remove_widget(wrapper)
class TabletteApp(App): server = None IpTable = IPTable PortTable = "8080" tablette = ObjectProperty(None) nbClient = NumericProperty(0) def build(self): self.tablette = GridLayout(cols=3, rows=2) return self.tablette def appairage(self, ip, port, status): if status != "Connected": if self.nbClient < 6: self.nbClient += 1 joueur = Joueur() joueur.TrueColor = randomColor() joueur.Adresse = ip joueur.Port = port joueur.ID = self.nbClient joueur.createHttpClient() self.tablette.add_widget(joueur) # print self.nbClient return ( '{"status":"Connected","color":{"r":"' + str(joueur.TrueColor[0]) + '","g":"' + str(joueur.TrueColor[1]) + '","b":"' + str(joueur.TrueColor[2]) + '"}' + "}" ) else: return '{"status":"Refused","message":"too many clients"}' else: return '{"status":"Connected","message":"alredy connected"}' def on_stop(self): self.server.shutdown() def removeJoueur(self, clientAddress): for child in self.tablette.children: if child.Adresse == clientAddress: self.tablette.remove_widget(child) self.nbClient -= 1
class MyApp(App): def get_score(self): return "[size=200]Hits: {}, misses: {}[/size]".format( self.hits, self.misses) def refresh(self): self.hits = 0 self.misses = 0 cols = 10 rows = 10 with urllib.request.urlopen(GAME_ENDPOINT) as url: data = json.loads(url.read().decode()) board = data["board"] for i in range(rows): for j in range(cols): state = board[i][j] if state == HIT: self.hits += 1 elif state == MISS: self.misses += 1 self.layout.add_widget(genButton(state=state, x=i, y=j)) def build(self): cols = 10 rows = 10 box = BoxLayout(padding=10, orientation='vertical') self.score = Label(text='Score: 0', markup=True) self.layout = GridLayout(cols=cols, row_force_default=True, row_default_height=50) self.refresh() Clock.schedule_interval(self.update, 1) box.add_widget(self.layout) box.add_widget(self.score) return box def update(self, *args): widgets = [] for child in self.layout.children: widgets.append(child) for child in widgets: self.layout.remove_widget(child) self.score.text = self.get_score() self.refresh()
class MyGrid(GridLayout): def __init__(self, **kwargs): super(MyGrid, self).__init__(**kwargs) self.cols = 1 self.inside = GridLayout() self.inside.cols = 2 self.inside.add_widget(Label(text="First Name: ")) self.name = TextInput(multiline=False) self.inside.add_widget(self.name) self.inside.add_widget(Label(text="Last Name: ")) self.lastname = TextInput(multiline=False) self.inside.add_widget(self.lastname) self.inside.add_widget(Label(text="Email: ")) self.email = TextInput(multiline=False) self.inside.add_widget(self.email) self.question = Label(text=MyApp.random_question(MyApp)) self.inside.add_widget(self.question) self.add_widget(self.inside) self.submit = Button(text="submit", font_size=40) self.submit.bind(on_press=self.pressed) self.add_widget(self.submit) self.new_question = Button(text="mudar pergunta", font_size=40) self.add_widget(self.new_question) def pressed(self, instance): name = self.name.text last = self.lastname.text email = self.email.text print("name :", name, " last: ", last, " email: ", email) self.name.text = "" self.lastname.text = "" self.email.text = "" self.inside.remove_widget(self.question) self.nova_questao = Label(text=MyApp.random_question(MyApp)) self.inside.add_widget(self.nova_questao)
class TabletteApp(App): server = None IpTable = IPTable PortTable = "8080" tablette = ObjectProperty(None) nbClient = NumericProperty(0) def build(self): self.tablette = GridLayout(cols=3, rows=2) return self.tablette def appairage(self, ip, port, status): if status != "Connected": if self.nbClient < 6: self.nbClient += 1 joueur = Joueur() joueur.TrueColor = randomColor() joueur.Adresse = ip joueur.Port = port joueur.ID = self.nbClient joueur.createHttpClient() self.tablette.add_widget(joueur) #print self.nbClient return '{"status":"Connected","color":{"r":"' + str( joueur.TrueColor[0]) + '","g":"' + str( joueur.TrueColor[1]) + '","b":"' + str( joueur.TrueColor[2]) + '"}' + '}' else: return '{"status":"Refused","message":"too many clients"}' else: return '{"status":"Connected","message":"alredy connected"}' def on_stop(self): self.server.shutdown() def removeJoueur(self, clientAddress): for child in self.tablette.children: if child.Adresse == clientAddress: self.tablette.remove_widget(child) self.nbClient -= 1
class MultilingualApp(App): def build(self): self.set_language('en_US') self.root = GridLayout(cols = 1) self.root.add_widget(Multilingual()) return self.root #self.root.myfunction('blah') def set_language(self,selectedLanguage): self.t = gettext.translation('multilingual', languagePath, languages=[selectedLanguage], fallback=True) _ = self.t.ugettext #The 'u' in 'ugettext' is for Unicode - use this to keep Unicode from breaking the app #self.root.greeting = _('Hello!') def get_text(self, *args): return self.t.ugettext(*args) def build_config(self, config): config.add_section('localization') config.set('localization', 'language', 'en_US') def build_settings(self, settings): settings.add_json_panel('Multilingual', self.config, data='''[ { "type": "title", "title": "Language Settings" }, { "type": "options", "title": "Language", "desc": "Choose which language to translate the text of this app into", "section": "localization", "key": "language", "options": ["en_US", "de", "fr", "es"]} ]''') def on_config_change(self, config, section, key, value): if config is not self.config: return token = (section, key) if token == ('localization', 'language'): self.set_language(value) self.root.clear_widgets() self.root.remove_widget(Multilingual()) self.root.add_widget(Multilingual()) print "Language is now", value
class MainTApp(App): im = Image(source='images/graph.png') def build(self): try: os.remove("images/graph.png") except Exception: pass self.root = GridLayout() self.root.cols = 4 c = Imglayout() global x self.x = TextInput() submit = Button(text="Submit.") submit.bind(on_press=self.callback) # submit.bind(on_press=self.myfunc) self.root.add_widget(c) self.im.keep_ratio = True self.im.allow_stretch = True c.add_widget(self.im) self.root.add_widget(self.x) self.root.add_widget(submit) return self.root def callback(self, instance): try: os.remove("images/graph.png") shutil.move("graph.png", "images") except Exception: pass x = np.linspace(-10, 10) y = eval(self.x.text) plt.plot(x, y) plt.savefig("graph.png") self.im.source = 'images/graph.png' self.root.remove_widget(self.im) self.im.reload()
class MaterialEditor(ScrollView, IObserver, AEditor): ''' the material-edit is the component, where the user can see the materials and create new material with the material-creater ''' # cross-section-shape csShape = ObjectProperty() # switch to proof whether the editor-gui was created boolEditor = BooleanProperty(True) ''' constructor ''' def __init__(self, **kwargs): super(MaterialEditor, self).__init__(**kwargs) self.allMaterials = self.csShape.allMaterials self.allMaterials.add_listener(self) self.create_gui() ''' the method create gui create the gui of the materialEditor and create the popups ''' def create_gui(self): # self.create_material_information() self.materialLayout = GridLayout(cols=1, spacing=2, size_hint_y=None) # Make sure the height is such that there is something to scroll. self.materialLayout.bind(minimum_height=self.materialLayout.setter('height')) for i in self.allMaterials.allMaterials: btn = OwnButton(text=i.name) btn.bind(on_press=self.show_material_information) self.materialLayout.add_widget(btn) self.btnMaterialEditor = OwnButton(text=self.createStr) self.btnMaterialEditor.bind(on_press=self.show_creater) self.materialLayout.add_widget(self.btnMaterialEditor) self.add_widget(self.materialLayout) ''' create the popups: popupInfo to show the material information popupCreate to create new material ''' def create_popups(self): self.create_base_popups() self.popupInfo = OwnPopup(title=self.materialStr, content=self.content) creater = MaterialCreater(_parent=self) self.popupCreate = OwnPopup(title=self.createStr, content=creater) ''' create the gui which is necessary for the show of the material-information ''' def create_material_information(self): self.create_btns() self.content = GridLayout(cols=2, spacing=Design.spacing) self.create_information() self.information.add_widget(self.btnEdit) self.information.add_widget(self.btnBack) self.graph = OwnGraph(xlabel=self.strainStr, ylabel=self.stressStr, y_grid_label=True, x_grid_label=True) self.p = LinePlot(color=[0, 0, 0]) self.graph.add_plot(self.p) self.content.add_widget(self.graph) self.content.add_widget(self.information) self.create_popups() ''' create all btns of the component ''' def create_btns(self): self.create_base_btns() self.btnBack, self.btnEdit = OwnButton(text=self.cancelStr), OwnButton(text=self.okStr) self.btnBack.bind(on_press=self.cancel_show) self.btnEdit.bind(on_press=self.edit_material) ''' the method update_materials update the view of the materials. its make sure that the create material button is the last component of the gridlayout ''' def update(self): self.materialLayout.remove_widget(self.btnMaterialEditor) btnMaterialA = OwnButton(text=self.allMaterials.allMaterials[-1].name) btnMaterialA.bind(on_press=self.show_material_information) self.materialLayout.add_widget(btnMaterialA) self.materialLayout.add_widget(self.btnMaterialEditor) ''' edit the selected material. all components which use this material will have the new properties ''' def edit_material(self, btn): self.focusBtnMaterial.text = self.nameBtn.text self.focusMaterial.name = self.nameBtn.text self.focusMaterial.density = float(self.densityBtn.text) self.focusMaterial.price = float(self.priceBtn.text) self.focusMaterial.materialLaw = self.materialLawEditor.f self.cancel_show(None) ''' set the labeltext with the materialproperties and open the popup to edit the material ''' def show_material_information(self, btn): if self.boolEditor: self.create_material_information() self.boolEditor = False for material in self.allMaterials.allMaterials: if material.name == btn.text: self.focusBtnMaterial = btn self.focusMaterial = material self.materialLawEditor.f = material.materialLaw self.nameBtn.text = material.name self.priceBtn.text = str(material.price) self.densityBtn.text = str(material.density) self.materialLaw.text = material.materialLaw.f_toString() self.update_graph(material.materialLaw.minStrain, material.materialLaw.maxStrain, material.materialLaw.points) self.popupInfo.open() return ''' show the material-law ''' def show_material_law_editor(self, btn): f = self.focusMaterial.materialLaw self.materialLawEditor.f = f if isinstance(f, Linear): self.materialLawEditor.focusBtn = self.materialLawEditor.btnLinear self.materialLawEditor.linearEditor.update_function(f.points, f.minStrain, f.maxStrain, f.a) self.materialLawEditor.confirm(None) elif isinstance(f, Multilinear): self.materialLawEditor.focusBtn = self.materialLawEditor.btnMultiLinear self.materialLawEditor.confirm(None) elif isinstance(f, Quadratic): self.materialLawEditor.focusBtn = self.materialLawEditor.btnQuadratic self.materialLawEditor.quadraticEditor.update_function(f.points, f.minStrain, f.maxStrain, f.a, f.b) self.materialLawEditor.confirm(None) elif isinstance(f, Exponential): self.materialLawEditor.focusBtn = self.materialLawEditor.btnExponential self.materialLawEditor.exponentialEditor.update_function(f.points, f.minStrain, f.maxStrain, f.a, f.b) self.materialLawEditor.confirm(None) elif isinstance(f, Logarithm): self.materialLawEditor.focusBtn = self.materialLawEditor.btnLogarithm self.materialLawEditor.logarithmEditor.update_function(f.points, f.minStrain, f.maxStrain, f.a, f.b) self.materialLawEditor.confirm(None) self.popupLawEditor.open() ''' open the material-creater ''' def show_creater(self, btn): if self.boolEditor: self.create_material_information() self.boolEditor = False self.popupCreate.open() ''' cancel the create-process. this method is necessary, because editor creator-instance call the method cancel_edit_materialfrom the parent ''' def cancel_edit_material(self): self.popupCreate.dismiss() ''' close the popup, which shows the information from the chosen material ''' def cancel_show(self, button): self.popupInfo.dismiss()
class ShapeSelection(GridLayout): ''' the shape-selection-component make it possible to change the cross-section-shape ''' #reinforcement-editor information = ObjectProperty() okStr = StringProperty('ok') cancelStr = StringProperty('cancel') rectStr = StringProperty('rectangle') # constructor def __init__(self, **kwargs): super(ShapeSelection, self).__init__(**kwargs) self.padding = Design.padding self.cols, self.spacing = 2, Design.spacing self.create_gui() ''' create the gui ''' def create_gui(self): self.create_graphs() self.create_selection() ''' create all graphs ''' def create_graphs(self): self.create_graph_rectangle() # default-shape Rectangle self.add_widget(self.graphRectangle) self.focusGraph = self.graphRectangle ################################################################### # here you can add more shapes. # # implement a graph which represent the shape # ################################################################### ''' create the plot graph ''' def create_graph_rectangle(self): self.graphRectangle = OwnGraph( x_ticks_major=0.1, y_ticks_major=0.05, y_grid_label=True, x_grid_label=True, xmin=0, xmax=0.5, ymin=0, ymax=0.25) self.p = LinePlot(color=[1, 1, 1, 1], points=self.draw_rectangle()) self.graphRectangle.add_plot(self.p) ''' draw the plot ''' def draw_rectangle(self): c, h, w = 1e-2, 0.23, 0.45 return [(c, c), (c, h), (w, h), (w, c), (c, c)] ''' create the right area where you can select the shape ''' def create_selection(self): self.create_btns() self.contentRight = GridLayout(cols=1) # self.contentRight.add_widget(self.focusShape) self.btns = GridLayout(cols=1, spacing=Design.spacing, size_hint_y=None) # self.contentRight.add_widget(self.btns) # Make sure the height is such that there is something to scroll. self.btns.bind(minimum_height=self.btns.setter('height')) self.btns.add_widget(self.plot) ################################################################### # here you can add more shapes. # # implement the button in the create_btns method # ################################################################### layout = GridLayout(cols=2, spacing=Design.spacing) layout.add_widget(self.btnOK) layout.add_widget(self.btnCancel) self.btns.add_widget(layout) self.shapes = ScrollView() self.shapes.add_widget(self.btns) self.contentRight.add_widget(self.shapes) self.add_widget(self.contentRight) ''' create and bind all btns from the gui ''' def create_btns(self): self.btnOK = OwnButton(text=self.okStr) self.btnOK.bind(on_press=self.finished) self.btnCancel = OwnButton(text=self.cancelStr) self.btnCancel.bind(on_press=self.cancel) # default-shape=rectangle self.focusShape = OwnButton(text=self.rectStr) self.focusShape.bind(on_press=self.show_shapes_btn) # btns self.plot = OwnButton(text=self.rectStr) self.plot.bind(on_press=self.show_rectangle) ####################################################################### # here you can add more shapes # # Attention: make sure that the buttons habe the properties # # size_hint_y=None, height=self.btnSize and a bind-method # # like the show_rectangle-method # ####################################################################### ''' show Rectangle-Graph ''' def show_rectangle(self, btn): self.remove_widget(self.focusGraph) self.add_widget(self.graphRectangle, 1) self.focusGraph = self.graphRectangle self.focusShape.text = btn.text ####################################################### # if you want add new shapes make sure, that the shape# # has a show-method like the show_rectangle # ####################################################### ''' show the btns where you can select the shape ''' def show_shapes_btn(self, btn): self.contentRight.remove_widget(self.focusShape) self.contentRight.add_widget(self.shapes) ''' finished the totally selection and call the finished_shape_selection of the information ''' def finished(self, btn): self.information.finished_shape_selection(self.focusShape) ''' cancel the shape selection ''' def cancel(self, btn): self.information.cancel_shape_selection()
class ChatScreen(Screen): def __init__(self, screen_manager, **kwargs): super(ChatScreen, self).__init__(**kwargs) self.screen_manager = screen_manager self.database = None self.client_transport = None self.contact = None self.client_login = None self.main_layout = GridLayout(cols=1) self.header_layout = GridLayout(cols=3, size_hint=(1, 0.1)) self.scroll_view = ScrollView(size_hint=(1, 0.8), size=(100, 100), scroll_y=0) self.footer_layout = GridLayout(cols=2, size_hint=(1, 0.1)) self.contact_list_button = Button(text='<=', size_hint=(0.1, 1)) self.contact_list_button.on_press = self.go_to_contact_list self.label = CLabel(text="Chat with bla bla", size_hint=(0.9, 1)) self.contact_menu = DropDown() for name in ['Info', 'Delete']: btn = Button(text=f'{name}', size_hint_y=None, height=30) btn.bind(on_release=lambda btn: self.contact_menu.select(btn.text)) self.contact_menu.add_widget(btn) self.main_button = Button(text=':', size_hint=(.1, .3)) self.main_button.bind(on_release=self.contact_menu.open) self.contact_menu.bind( on_select=lambda instance, x: self.menu_contact(x)) self.messages = [] self.messages_layout = GridLayout(cols=1, padding=(30, 0, 30, 0), size_hint_y=None, row_force_default=True, row_default_height=40) self.messages_layout.bind( minimum_height=self.messages_layout.setter('height')) self.scroll_view.add_widget(self.messages_layout) self.text_input = TextInput(size_hint=(0.9, 1)) self.send_button = Button(text='>>', size_hint=(0.1, 1)) self.send_button.on_press = self.send_message self.header_layout.add_widget(self.contact_list_button) self.header_layout.add_widget(self.label) self.header_layout.add_widget(self.main_button) self.footer_layout.add_widget(self.text_input) self.footer_layout.add_widget(self.send_button) self.main_layout.add_widget(self.header_layout) self.main_layout.add_widget(self.scroll_view) self.main_layout.add_widget(self.footer_layout) self.add_widget(self.main_layout) def send_message(self): message_text = self.text_input.text if message_text: is_success = self.client_transport.send_user_message( self.contact, message_text) self.text_input.text = '' if not is_success: self.show_info_screen('Lost server connection!', 'login') elif is_success is True: self.add_message_history(message_text) else: self.show_info_screen(is_success, 'contacts') def show_info_screen(self, *args): self.screen_manager.current = 'info' self.screen_manager.get_screen('info').set_message(*args) def go_to_contact_list(self): self.screen_manager.current = 'contacts' def load_chat(self, contact_name): self.contact = contact_name if self.client_transport.is_received_pubkey(contact_name): self.show_history() else: self.clear_messages() def set_objects(self, database, client_transport): self.database = database self.client_transport = client_transport self.client_login = self.client_transport.client_login def clear_messages(self): for msg in self.messages: self.messages_layout.remove_widget(msg) self.messages.clear() self.label.text = f'Chat with {self.contact}' def show_history(self): self.clear_messages() list_message = sorted(self.database.get_history(self.contact), key=lambda item: item[3]) # sort by date length = len(list_message) start_index = 0 if length > 20: start_index = length - 20 for i in range(start_index, length): item = list_message[i] message = re.findall(r'>([^<>]+)</p|>([^<>]+)</span', item[2]) if message: message = message[0][0] else: message = item[2] if item[1] == 'in': time = f'{self.contact}' \ f' {item[3].replace(microsecond=0)}:' label = Label(text=f"{time}\n{message}", color=[0.7, 0.3, 1, 0.8], halign='right', valign='middle') label.bind(size=label.setter('text_size')) self.messages.append(label) self.messages_layout.add_widget(self.messages[-1]) elif item[1] == 'out': time = f'{self.client_login}' \ f' {item[3].replace(microsecond=0)}:' label = Label(text=f"{time}\n{message}", color=[0.8, 1, .3, 0.7], halign='left', valign='middle') label.bind(size=label.setter('text_size')) self.messages.append(label) self.messages_layout.add_widget(self.messages[-1]) def add_message_history(self, message): time = f'{self.client_login}' \ f' {datetime.datetime.now().replace(microsecond=0)}:' label = Label(text=f"{time}\n{message}", color=[0.8, 1, .3, 0.7], halign='left', valign='middle') label.bind(size=label.setter('text_size')) self.messages.append(label) self.messages_layout.add_widget(self.messages[-1]) def get_message(self, *args): if self.screen_manager.current == 'chat': sender = args[0] if sender == self.contact: self.show_history() else: if self.database.is_contact(sender): text_title = f'New message from {sender}' text_label = f'Received a new message from {sender}, open chat with him?' create_message_window(text_title, text_label, self.open_new_chat, sender) else: text_title = f'New message from {sender}' text_label = f'Received a new message from {sender}.\n ' \ f'This user is not in your contact list.\n ' \ f'Add to contacts and open a chat with him?' create_message_window(text_title, text_label, self.add_contact, sender) def add_contact(self, sender): if self.client_transport.add_contact(sender): text_title = 'Info message' text_label = f'Contact {sender} successfully added.' create_message_window(text_title, text_label, self.open_new_chat, sender) else: text_title = 'Info message' text_label = f'Lost server connection!.' create_message_window(text_title, text_label, self.show_login_screen) def open_new_chat(self, sender): self.load_chat(sender) def connect_chat_signal(self, client_obj): client_obj.new_message_signal_chat.connect(self.get_message) def show_login_screen(self): self.screen_manager.current = 'login' def menu_contact(self, button): if button == 'Delete': if self.client_transport.del_contact(self.contact): text_title = 'Success!' text_label = 'Contact successfully removed.' create_message_window(text_title, text_label) self.update_contact_list() else: text_title = 'Error!' text_label = 'Lost server connection.' create_message_window(text_title, text_label, self.go_to_login) elif button == 'Info': self.screen_manager.current = 'contact_info' self.screen_manager.get_screen('contact_info').get_contact_name( self.contact)
class menuApp(App): def build(self): self.title = "Menu" self.al = AnchorLayout(anchor_x='right', anchor_y='bottom', padding=[160, 85, 0, 0]) self.gl = GridLayout(cols=2) self.b1 = Button(text='Редактор \n файлов', size_hint=(None, None), size=(180, 90), on_press=self.update) self.b2 = Button(text='Калькулятор', size_hint=(None, None), size=(180, 90), on_press=self.calculator) self.b3 = Button(text='X и O', size_hint=(None, None), size=(180, 90), on_press=self.XandO) self.b4 = Button(text='Книги', size_hint=(None, None), size=(180, 90), on_press=self.books) self.b5 = Button(text='Картинки', size_hint=(None, None), size=(180, 90), on_press=self.pictures) self.b6 = Button(text='Кодировки', size_hint=(None, None), size=(180, 90), on_press=self.code) self.gl.add_widget(self.b1) self.gl.add_widget(self.b2) self.gl.add_widget(self.b3) self.gl.add_widget(self.b4) self.gl.add_widget(self.b5) self.gl.add_widget(self.b6) self.al.add_widget(self.gl) return self.al def remove(self): self.gl.remove_widget(self.b1) self.gl.remove_widget(self.b2) self.gl.remove_widget(self.b3) self.gl.remove_widget(self.b4) self.gl.remove_widget(self.b5) self.gl.remove_widget(self.b6) def update(self, instance): self.remove() menuApp().stop() updateFilesApp().run() def calculator(self, instance): self.remove() menuApp().stop() colculatorApp().run() def XandO(self, instance): self.remove() menuApp().stop() XandOApp().run() def books(self, instance): self.remove() menuApp().stop() booksApp().run() def pictures(self, instance): self.remove() menuApp().stop() picturesApp().run() def code(self, instance): self.remove() menuApp().stop() codeApp().run()
class ScoreBoard(GridLayout): """ScoreBoard """ __MENU_BUTTON_WIDTH = "30sp" def __init__(self, clock_countdown_start, login_button_handler, join_game_handler, **kwargs): kwargs["cols"] = 2 super(ScoreBoard, self).__init__(**kwargs) self.col1 = GridLayout(cols=2, padding=[5, 0, 0, 0]) self.menu = MenuButton(login_button_handler, join_game_handler, source=\ "images/font-awesome_4-7-0_" + "bars" + "_48_0_333300_none.png",\ size_hint_x=None, width=self.__MENU_BUTTON_WIDTH) self.col1.add_widget(self.menu) self.clock_countdown_start = clock_countdown_start self.ui_clock = Clock(self.clock_countdown_start, bold=True, font_size="20sp",\ color=get_color_from_hex("#333300")) self.col1.add_widget(self.ui_clock) self.add_widget(self.col1) self.col2 = GridLayout(cols=2, padding=[5, 0, 0, 0]) self.kv_score = Label(font_size="20sp", bold=True, text="0",\ color=get_color_from_hex("#333300")) self.col2.add_widget(self.kv_score) self.add_widget(self.col2) self.players = [] self.scores = [] def on_size(self, *args): """on_size """ try: with self.canvas.before: Color(rgb=get_color_from_hex("#ffffb0")) Rectangle(pos=self.pos, size=self.size) except AttributeError: pass def set_score(self, scores, in_device): """set_score param scores [<int>, <int>, ... numPlayers ] param in_device <boolean> """ if in_device: self.kv_score.text = str(scores[0]) else: for i, score in enumerate(scores): self.scores[i].text = str(score) def get_score(self): """ get_score """ return int(self.kv_score.text) def render_game_state(self, game_state): """ render_game_state """ self.set_score(game_state["scores"], game_state["in-device"]) # self.render_turn(game_state["turn"]) def init_clock(self, level_time): """init_clock """ self.col1.remove_widget(self.ui_clock) self.ui_clock.stopped = True self.ui_clock = Clock(level_time, bold=True, font_size="20sp",\ color=get_color_from_hex("#333300")) # Clock(level_time) self.col1.add_widget(self.ui_clock) #, index=1) def start_clock(self): """start_clock """ self.ui_clock.init_time_counter() self.ui_clock.tick() def stop_clock(self): """ stop_clock """ self.ui_clock.stop() def get_clock_val(self): """get_clock_val\n return <int>\n """ return self.ui_clock.get_current_value() def set_clock_timeout_trigger(self, callback): """set_clock_timeout_trigger param callback Called when the countdown clock has reached its minimum val. """ self.ui_clock.set_timeout_trigger(callback) def render_my_name_ack(self, result_code, username): """render_my_name_ack param result_code <int> 0: OK 1: USER_DOES_NOT_EXIST param username <str> """ if result_code == 0: self.menu.init_gaming(username) def render_online_list(self, online_list): """render_online_list param online_list <list> """ self.menu.handle_online_list(online_list) def render_games_list(self, games_list): """render_games_list """ self.menu.handle_games_list(games_list) def render_join_game_ack(self, result_code, game): """render_join_game_ack param result_code <int> 0 = OK, otherwise error param game See MenuButton.wait_for_gaming, [gameId, numPlayers, numPairs] """ if result_code == 0: self.menu.wait_for_gaming(game) def render_start_game(self, game_state, clock_timeout_callback): """render_start_game """ self.menu.close_modal() if game_state["in-device"]: self.init_clock(game_state["game-max-len"]) self.set_clock_timeout_trigger(clock_timeout_callback) self.start_clock() else: self.col1.clear_widgets() self.col2.clear_widgets() self.col1.cols = 3 self.col2.cols = 3 if len(game_state["players"]) == 2: player1 = PlayerLabel(game_state["turn"] == 1, text=game_state["players"][0]) score1 = Label(text=str(game_state["scores"][0]),\ color=get_color_from_hex("#333300")) self.col1.add_widget(self.menu) self.col1.add_widget(player1) self.col1.add_widget(score1) player2 = PlayerLabel(game_state["turn"] == 2, text=game_state["players"][1]) score2 = Label(text=str(game_state["scores"][1]),\ color=get_color_from_hex("#333300")) self.col2.add_widget(score2) self.col2.add_widget(player2) self.col2.add_widget(Image(source="images/transparent_48.png", size_hint_x=None,\ width=self.__MENU_BUTTON_WIDTH)) # this makes evenly sized cols self.players.append(player1) self.players.append(player2) self.scores.append(score1) self.scores.append(score2) def render_turn(self, turn): """render_turn """ if len(self.players) > 1: if turn == 1: print("turn == 1", "activate", self.players[0].text, "inactivate", self.players[1].text) self.players[0].activate() self.players[1].inactivate() else: print("turn != 1", "activate", self.players[1].text, "inactivate", self.players[0].text) self.players[0].inactivate() self.players[1].activate() def render_gameover(self, game_state): """render_gameover """ self.menu.render_gameover(game_state) self.menu.open_modal()
class TertiaryWindow(Screen): order_list = [] order_list_past = [] def __init__(self, **kwargs): # GUI from top to bottom, left to right super(TertiaryWindow, self).__init__(**kwargs) with self.canvas: Color(0.2, 0.2, 0.28) Rectangle(size=(Window.width**2, Window.height**2)) self.scroll = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) self.scroll_btn = None self.scroll_grid = GridLayout(cols=1, spacing=1, size_hint_y=None) self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height')) self.btn_menu = Button(size_hint_y=None, height=40, text="Order Database >", background_color=[0.45, 0.45, 0.45, 3], on_release=self.changeWindow) self.scroll_grid.add_widget(self.btn_menu) self.btn_menu.set_disabled(1) self.btn_connecting = Button( size_hint_y=None, height=80, text="Connecting to server . . .", background_color=[1.3, 0.2, 0.2, 3], background_down='atlas://data/images/defaulttheme/button') self.scroll_grid.add_widget(self.btn_connecting) self.button_id = None self.div = Button( text=f"[b]----------[/b]", markup=True, size_hint_y=None, height=20, background_color=[0.4, 0.4, 0.4, 3], background_down='atlas://data/images/defaulttheme/button') self.popup = Popup( title='Notice', title_align='center', content=Label( text= 'This order has not been submitted by the cashier yet. Please wait until' ' the order has been submitted to finish it.', size=(400, 400), text_size=[380, 380], halign='center', valign='center'), size_hint=(None, None), size=(400, 400)) threading.Thread(target=self.connectSocket).start() if len(self.scroll.children) == 0: self.scroll.add_widget(self.scroll_grid) self.add_widget(self.scroll) def connectSocket(self): host = '10.0.0.69' port = 8912 address = (host, port) header_len = 19 while True: time.sleep(0.5) try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(address) self.scroll_grid.remove_widget(self.btn_connecting) self.btn_connecting.text = 'Lost connection with server. Trying to reconnect. . .' self.btn_menu.set_disabled(0) while True: time.sleep(0.5) header = '0'.encode() try: header = client.recv(10) if header.decode() == 'B=G#J3>m$p': print('<Connection alive>') except UnicodeDecodeError: msg = pickle.loads(header + client.recv(4096)) self.order_list_past.append(msg) self.generatePastOrders() except ConnectionResetError: print('<Connection to server lost>') self.scroll_grid.add_widget(self.btn_connecting) break except ConnectionRefusedError: continue def changeWindow(self, instance): if 'Order Database' in instance.text: sm.current = 'secondary' sm.transition.direction = 'left' screen_second.generateOrders() def reset(self): self.scroll_grid.clear_widgets() self.scroll_grid.add_widget(self.btn_menu) def cancelOrder(self): temp_list = [] temp_num = 0 temp_total = 0 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for child in rev: if 'Order' not in child.text and '^ ^ ^' not in child.text and '- - -' not in child.text and '----------' not in child.text: temp_list.append(child) temp_total += 1 continue elif '----------' in child.text: for items in temp_list: temp_num += 1 if temp_total == temp_num and temp_num > 0: for item in temp_list: self.scroll_grid.remove_widget(item) self.scroll_grid.remove_widget(self.div) temp_list.clear() temp_num = 0 temp_total = 0 break else: temp_list.clear() temp_num = 0 temp_total = 0 else: temp_list.clear() temp_num = 0 temp_total = 0 def itemFinished(self, instance=None): self.button_id = instance if "[s]" not in instance.text: instance.text = f"[s]{instance.text}[/s]" instance.background_color = [0.6, 0.6, 0.6, 3] else: instance.text = f"{instance.text[3:-4]}" instance.background_color = [1.8, 0.8, 0, 3] temp_list = [] temp_num = 0 temp_total = 0 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for child in rev: if 'Order' not in child.text and '^ ^ ^' not in child.text and '- - -' not in child.text and '----------' not in child.text: temp_list.append(child) temp_total += 1 continue else: div = child for items in temp_list: if '[/s]' in items.text: temp_num += 1 if temp_total == temp_num and temp_num > 0: if "----------" in div.text: self.popup.open() instance.text = f"{instance.text[3:-4]}" instance.background_color = [1.8, 0.8, 0, 3] break for item in temp_list: self.scroll_grid.remove_widget(item) self.scroll_grid.remove_widget(div) temp_list.clear() temp_num = 0 temp_total = 0 break else: temp_list.clear() temp_num = 0 temp_total = 0 # def generateCurOrders(self, instance=None, text=None): # self.cancelOrder() # # for i in range(len(screen_main.order_list)): # t = screen_main.order_list[i].time # if int(t.split(':')[0]) > 12 and 'PM' not in t: # hour = int(t.split(':')[0]) - 12 # screen_main.order_list[i].time = f"{hour}{t[-3:]} PM" # else: # if 'AM' not in t and 'PM' not in t: # screen_main.order_list[i].time = f"{t} AM" # # self.scroll_grid.add_widget( # Button( # text=f"{screen_main.order_list[i].details}{screen_main.order_list[i].food}" # f"{screen_main.order_list[i].to_go} | [b]{screen_main.order_list[i].time}[/b]", # size_hint_y=None, height=40, background_color=[1.8, 0.8, 0, 3], # markup=True, on_release=self.itemFinished)) # # if len(screen_main.order_list) > 0: # self.scroll_grid.add_widget(self.div) # def generatePastOrders(self, instance=None, text=None): self.cancelOrder() for i in range(len(self.order_list_past[-1])): t = self.order_list_past[-1][i].time if int(t.split(':')[0]) > 12 and 'PM' not in t: hour = int(t.split(':')[0]) - 12 self.order_list_past[-1][i].time = f"{hour}{t[-3:]} PM" else: if 'AM' not in t and 'PM' not in t: self.order_list_past[-1][i].time = f"{t} AM" self.scroll_grid.add_widget( Button( text= f"{self.order_list_past[-1][i].details}{self.order_list_past[-1][i].food}" f"{self.order_list_past[-1][i].to_go} | [b]{self.order_list_past[-1][i].time}[/b]", markup=True, size_hint_y=None, height=40, background_color=[1.8, 0.8, 0, 3], on_release=self.itemFinished)) # if len(screen_main.txt_name.text) == 0: self.scroll_grid.add_widget( Button(text=f"[b]- - -[/b]", markup=True, size_hint_y=None, height=20, background_color=[0.4, 0.4, 0.4, 3], background_down='atlas://data/images/defaulttheme/button'))
class ReinforcementEditorGui: ''' class to create the gui of the reinforcement editor ''' # strings densityStr, stiffnessStr = StringProperty('density[kg/m^3]:'), StringProperty('stiffness[MPa]:') priceStr, strengthStr = StringProperty('price[euro/m]:'), StringProperty('cracking stress [MPa]:') weightStr, areaStr = StringProperty('weight [kg/m]:'), StringProperty('area [m^2]: ') nameStr, steelStr = StringProperty('name:'), StringProperty('steel') rectangleStr, shapeStr = StringProperty('rectangle'), StringProperty('shape') materialStr, resetStr = StringProperty('material:'), StringProperty('-') ratioStr = StringProperty('reinforcement ratio [%]:') addStr, deleteStr = StringProperty('add layer'), StringProperty('delete layer') ''' create the gui ''' def create_gui(self): # if you add more shapes, uncomment the follow row # self.create_selection_menu() self.create_cross_section_area() self.create_add_delete_area() self.create_material_information() self.create_add_layer_information_area() self.numpad = Numpad(p=self) self.popupNumpad = OwnPopup(title=self.areaStr, content=self.numpad) ''' the method create_add_delete_area create the area where you can add new materials and delete materials from the cs_view ''' def create_add_delete_area(self): self.addDeleteLayout = GridLayout(cols=2, row_force_default=True, row_default_height=Design.btnHeight, size_hint_y=None, height=Design.btnHeight, spacing=Design.spacing) btnAdd = OwnButton(text=self.addStr) btnDelete = OwnButton(text=self.deleteStr) btnAdd.bind(on_press=self.show_add_layer_area) btnDelete.bind(on_press=self.delete_layer) self.addDeleteLayout.add_widget(btnAdd) self.addDeleteLayout.add_widget(btnDelete) self.add_widget(self.addDeleteLayout) ''' the method create_material_information create the area where you can see the information about the selected materials ''' def create_material_information(self): self.materialLayout = GridLayout(cols=1) self.lblName, self.lblRatio = OwnLabel(text=self.resetStr), OwnLabel(text=self.resetStr) self.lblDensity, self.lblStiffness = OwnLabel(text=self.resetStr), OwnLabel(text=self.resetStr) self.lblStrength, self.areaInput = OwnLabel(text=self.resetStr), OwnButton(text=self.resetStr) self.areaInput.bind(on_press=self.show_numpad) materialLayout = GridLayout(cols=4, row_force_default=True, row_default_height=3 * Design.lblHeight, height=Design.btnHeight) materialLayout.add_widget(OwnLabel(text=self.nameStr)) materialLayout.add_widget(self.lblName) materialLayout.add_widget(OwnLabel(text=self.ratioStr)) materialLayout.add_widget(self.lblRatio) materialLayout.add_widget(OwnLabel(text=self.densityStr)) materialLayout.add_widget(self.lblDensity) materialLayout.add_widget(OwnLabel(text=self.stiffnessStr)) materialLayout.add_widget(self.lblStiffness) materialLayout.add_widget(OwnLabel(text='strength[MPa]')) materialLayout.add_widget(self.lblStrength) materialLayout.add_widget(OwnLabel(text=self.areaStr)) materialLayout.add_widget(self.areaInput) self.materialLayout.add_widget(materialLayout) self.add_widget(self.materialLayout) ''' the method create_cross_section_area create the area where you can see the information of the cs_view ''' def create_cross_section_area(self): self.lblcsPrice = OwnLabel(text=self.resetStr) self.lblcsWeight = OwnLabel(text=self.resetStr) self.lblcsStrength = OwnLabel(text=self.resetStr) self.csLayout = GridLayout(cols=2, row_force_default=True, row_default_height=3 * Design.lblHeight, height=2 * Design.lblHeight) self.csLayout.add_widget(OwnLabel(text=self.priceStr)) self.csLayout.add_widget(self.lblcsPrice) self.csLayout.add_widget(OwnLabel(text=self.weightStr)) self.csLayout.add_widget(self.lblcsWeight) self.csLayout.add_widget(OwnLabel(text=self.strengthStr)) self.csLayout.add_widget(self.lblcsStrength) self.add_widget(self.csLayout) ''' the method create_add_layer_information_area create the area where you can add new materials ''' def create_add_layer_information_area(self): self.create_material_options() btnConfirm = OwnButton(text='confirm') btnCancel = OwnButton(text='cancel') btnConfirm.bind(on_press=self.add_layer) btnCancel.bind(on_press=self.cancel_adding) self.addLayout = GridLayout(cols=2, row_force_default=True, row_default_height=Design.btnHeight, size_hint_y=None, height=4.5 * Design.btnHeight, spacing=Design.spacing) self.addLayout.add_widget(OwnLabel(text=self.materialStr)) self.btnMaterialOption = OwnButton(text=self.steelStr) self.btnMaterialOption.bind(on_release=self.popup.open) self.addLayout.add_widget(self.btnMaterialOption) self.lblMaterialPercent = OwnLabel(text=self.areaStr) self.addLayout.add_widget(self.lblMaterialPercent) self.areaBtn = OwnButton(text='0.0') self.areaBtn.bind(on_press=self.show_numpad) self.addLayout.add_widget(self.areaBtn) self.addLayout.add_widget(btnConfirm) self.addLayout.add_widget(btnCancel) ''' the method create_material_options create the popup where you can select the materials for the new layer ''' def create_material_options(self): self.materialSelectionLayout = GridLayout(cols=1, spacing=Design.spacing, size_hint_y=None) # Make sure the height is such that there is something to scroll. self.materialSelectionLayout .bind(minimum_height=self.materialSelectionLayout.setter('height')) self.materialEditor = MaterialCreater(p=self) self.popupMaterialEditor = OwnPopup(title='editor', content=self.materialEditor) for i in range(0, len(self.allMaterials.allMaterials) - 1): btnMaterialA = OwnButton(text=self.allMaterials.allMaterials[i].name) btnMaterialA.bind(on_press=self.select_material) self.materialSelectionLayout.add_widget(btnMaterialA) self.btnMaterialEditor = OwnButton(text='create material') self.btnMaterialEditor.bind(on_press=self.popupMaterialEditor.open) self.materialSelectionLayout.add_widget(self.btnMaterialEditor) self.root = ScrollView() self.root.add_widget(self.materialSelectionLayout) popupContent = GridLayout(cols=1) popupContent.add_widget(self.root) self.popup = OwnPopup(title=self.materialStr, content=popupContent) ''' create the layout where you can select the cross-section-shape ''' def create_selection_menu(self): self.create_popup_shape() selectionContent = GridLayout(cols=2, height=Design.btnHeight, size_hint_y=None, row_force_default=True, row_default_height=Design.btnHeight) self.btnSelection = OwnButton(text=self.rectangleStr) self.btnSelection.bind(on_press=self.show_shape_selection) selectionContent.add_widget(OwnLabel(text=self.shapeStr)) selectionContent.add_widget(self.btnSelection) self.add_widget(selectionContent) ''' create popup where you can select the shape of the cross section ''' def create_popup_shape(self): shapeContent = ShapeSelection(information=self) self.shapeSelection = OwnPopup(title=self.shapeStr, content=shapeContent) ''' the method update_materials update the view of the materials. its make sure that the create material button is the last component of the gridlayout ''' def update(self): self.materialSelectionLayout.remove_widget(self.btnMaterialEditor) btnMaterial = OwnButton(text=self.allMaterials.allMaterials[-1].name) btnMaterial.bind(on_press=self.select_material) self.materialSelectionLayout.add_widget(btnMaterial) self.materialSelectionLayout.add_widget(self.btnMaterialEditor) ''' the method will be called when the user selected a material the popup will be closed and the button text change to the material lblName ''' def select_material(self, btn): self.popup.dismiss() self.btnMaterialOption.text = btn.text ''' the method update_layinfo was developed to update the information, when the user selected a other rectangle in the view ''' def update_layinfo(self, name, price, density, stiffness, strength, percent): self.lblName.text, self.lblRatio.text = str(name), str(percent * 100) self.lblDensity.text = str(density) self.lblStiffness.text = str(stiffness) self.lblStrength.text = str(strength) self.areaInput.text = '%.2E' % Decimal(str(self.cs.h * self.cs.w * percent)) ''' reset the layer_information when no layer is focused ''' def reset_layer_information(self): self.lblName.text = self.resetStr self.lblRatio.text = self.resetStr self.lblDensity.text = self.resetStr self.lblStiffness.text = self.resetStr self.lblStrength.text = self.resetStr self.areaInput.text = self.resetStr ''' the method update_cs_information update the cross section information. ''' def update_cs_information(self, price, weight, strength): self.lblcsPrice.text = '%.2E' % Decimal(str(price)) self.lblcsWeight.text = '%.2E' % Decimal(str(weight)) self.lblcsStrength.text = '%.2E' % Decimal(str(strength)) ''' open the numpad for the input ''' def show_numpad(self, btn): self.focusBtn = btn self.popupNumpad.open() ''' method when the user confirm the input ''' def finished_numpad(self): v = float(self.numpad.lblTextinput.text) self.focusBtn.text = str(v) # if the percentage of the layer must change if self.focusBtn == self.areaInput: self.cs.view.update_percent(v / self.cs.size) self.popupNumpad.dismiss() ''' close the numpad ''' def close_numpad(self): self.popupNumpad.dismiss() ''' the method show_add_layer_area was developed to show the the addLayout and hide the material_information ''' def show_add_layer_area(self, button): self.remove_widget(self.materialLayout) self.remove_widget(self.csLayout) self.remove_widget(self.information) self.remove_widget(self.addDeleteLayout) self.add_widget(self.addLayout, 0) ''' the method finished_adding was developed to hide the the addLayout and show the materialLayout ''' def finished_adding(self): self.remove_widget(self.addLayout) self.add_widget(self.materialLayout, 0) self.add_widget(self.addDeleteLayout, 1) self.add_widget(self.csLayout, 2) self.add_widget(self.information, 3) ''' the method cancel_adding would be must call when the user wouldn't add a new materials ''' def cancel_adding(self, button): self.finished_adding() ''' the method cancel_edit_material cancel the editing of the material and reset the values of the materialEditor ''' def cancel_edit_material(self): self.popupMaterialEditor.dismiss() self.materialEditor.reset_editor()
class LoginScreen(FloatLayout): #x = ListProperty([]) #print x def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) #gc.disable() self.DropdownObjects = [] self.add_widget(Label(text= "Wilkommen [color=ff3333] [sub] bei der [/sub][/color][color=3333ff][b] Bonierungs[sup][color=#098125ff]App[/sup][/b][/color]", markup = True, pos_hint={'top': 1.2}, font_size='20sp')) self.GridlayoutS1 = GridLayout(cols = 2, size_hint_y = 1/5, pos_hint={'top': 0.6}) self.add_widget(self.GridlayoutS1) self.GridlayoutS1.add_widget(Label(text='User Name')) #, size_hint_x = 0.2, size_hint_y = 0.2)) self.username = TextInput(multiline=False) #, size_hint_x = 0.2, size_hint_y = 0.2) self.username.bind(on_text_validate=self.on_enter) self.GridlayoutS1.add_widget(self.username) self.GridlayoutS1.add_widget(Label(text='password')) #,size_hint_x = 0.2, size_hint_y = 0.2)) self.password = TextInput(password=True, multiline=False) #, size_hint_x = 0.2, size_hint_y = 0.2) self.GridlayoutS1.add_widget(self.password) self.BenutzerListe = {"": ""}; self.add_widget(Button(text='Einloggen', size_hint_y= 1/5, pos_hint={'top': 0.4}, on_release = self.AbfrageLogin)) self.LabelLoginanzeiger = Label(size_hint_y= 1/5) self.add_widget(self.LabelLoginanzeiger) def on_enter(self, instance): print('User pressed enter in', instance) self.password.focus = True def AbfrageLogin(self, widget): Username = self.username.text Passwort = self.password.text if Username in self.BenutzerListe and Passwort == self.BenutzerListe[Username]: self.LabelLoginanzeiger.text = 'Login korrekt' self.clear_widgets() self.HauptProgramm() else: self.LabelLoginanzeiger.text = 'Login inkorrekt' def HauptProgramm(self, *args): self.SpinnerButtonZustand = 'Alle' App.AuswahlHauptlisteAlt = [] print 'das ist das Hauptprogramm' self.BilderListeVorlaeufer = [] self.BilderListeVorlaeufer = os.listdir(os.getcwd() + '/pictures') self.Pfade = [] for i in self.BilderListeVorlaeufer: Pfad = os.path.join('pictures', i) if os.path.isfile(Pfad) == True: self.Pfade.append(Pfad) self.HauptCarousel = Carousel(scroll_timeout = 100) App.Pfade = self.Pfade self.add_widget(self.HauptCarousel) #################################################################################################### ### Erste Seite im HauptCarousel momentan mit den produktbildern self.HauptCarousel.FloatLayout = FloatLayout() self.HauptCarousel.add_widget(self.HauptCarousel.FloatLayout) self.HauptCarousel.FloatLayout.GridLayout = GridLayout(cols=3, pos_hint={'x': 0,'y': 0}, size_hint=[1,0.9]) self.HauptCarousel.FloatLayout.add_widget(self.HauptCarousel.FloatLayout.GridLayout) for i in range(2): button = Button(background_normal = self.Pfade[i], background_down= 'bilder_oberflaeche/1361740537_Ball Green_mitHaken.png', mipmap= True) self.HauptCarousel.FloatLayout.GridLayout.add_widget(button) ## self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test')) ## self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test2')) ##################################################################################################### ### 2 Seite im Hauptcarousel mit testbutton zur datei Erstellung ### 2 Page in MainCarousel with testbutton for creating /exporting to a file self.HauptCarousel2 = BoxLayout(orientation='vertical') ###self.HauptCarousel.add_widget(self.HauptCarousel2) self.HauptCarousel2.Texteingabe = TextInput(multiline=True) self.HauptCarousel2.add_widget(self.HauptCarousel2.Texteingabe) self.HauptCarousel2.ButtonSchreiben = Button(text="datei schreiben", on_release = self.datenpickeln) self.HauptCarousel2.add_widget(self.HauptCarousel2.ButtonSchreiben) ####################################################################### ### 3 Seite im Hauptcarousel momentan mit Datei Auslesefunktion ### 3 Page in MainCarousel atm with functionality to read from file self.HauptCarousel3 = BoxLayout(orientation='vertical') ###self.HauptCarousel.add_widget(self.HauptCarousel3) self.HauptCarousel3.Textausgabe = TextInput(multiline=True, readonly = True) self.HauptCarousel3.add_widget(self.HauptCarousel3.Textausgabe) self.HauptCarousel3.ButtonLesen = Button(text="datei auslesen", on_release = self.datenentpickeln) self.HauptCarousel3.add_widget(self.HauptCarousel3.ButtonLesen) ####################################################################### ### 4 Seite im Hauptcarousel momentan mit Tischmanager ### 4 Page in Maincarousel atm with some kind of Table Manager BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] self.CustomLayout = CustomLayout() self.HauptCarousel.add_widget(self.CustomLayout) #self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=#098125ff]Organizer[/sup][/b][/color]', markup = True, #halign= 'left', valign= 'top', text_size= self.size, pos_hint={'x':0, 'y': 0}, font_size= '30sp') self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=18ea1d]Organizer[/sup][/b][/color]', markup = True, # alte farbe: #098125ff halign= 'left', font_size= '30sp') #self.CustomLayout.add_widget(self.CustomLayout.TopLabel) self.CustomLayout.BoxLayout = BoxLayout (orientation = 'horizontal', size_hint = [1,0.05], pos_hint={'x':0, 'y': 0.95}) self.CustomLayout.add_widget(self.CustomLayout.BoxLayout) self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.TopLabel) ButtonMenu1 = self.DropdownbuttonCreator() self.CustomLayout.BoxLayout.Button1 = ButtonMenu1 ## self.CustomLayout.BoxLayout.Button2 = Button(text = 'Tisch+' , on_release = self.tischhinzufuegen) ## self.CustomLayout.BoxLayout.Button3 = Button(text = 'Spalte+', on_release = self.spaltehinzufuegen) ## self.CustomLayout.BoxLayout.Button4 = Button(text = 'Zeile+', on_release = self.zeilehinzufuegen) self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button1) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button2) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button3) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button4) self.CustomLayoutGridLayout = GridLayout(cols = 3, rows = 4, padding = [20,20], spacing = [30,30], size_hint = [1,0.95], pos_hint={'x':0, 'y': 0}) #cGridLayout = StackLayout(orientation = "tb-lr", padding = [20,20], spacing = [30,30], size_hint = [1,0.9], pos_hint={'x':0, 'y': 0}) self.CustomLayout.add_widget(self.CustomLayoutGridLayout) self.Tischliste = [] Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] AnzahlTische = 12 Zielwidget = self.CustomLayoutGridLayout self.tischerstellung(Zielwidget,AnzahlTische, Auswahlliste, BackgroundcolorListe) self.Box=BoxLayout(oreintation='vertical') self.CustomScrollviewProduktOrganizerInstanz = CustomScrollviewProduktOrganizer() ######### ######### self.ProduktOrganizerInstanz = ProduktOrganizer() self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer.bind(text=self.produktorganizerfilter) self.Box.add_widget(self.ProduktOrganizerInstanz) self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.HauptListeDictonaries self.HauptCarousel.add_widget(self.Box) #self.HauptCarousel.add_widget(self.ProduktOrganizerInstanz) self.ButtonHinzufuegen = self.ProduktOrganizerInstanz.ids.ProduktlisteButtonHinzufuegen self.ButtonHinzufuegen.on_release = self.produkthinzufuegen self.PopupDateiAuswaehlenInst= PopupDateiAuswaehlenProduktorganizer() PopupDateiauswahl = self.PopupDateiAuswaehlenInst.ids.b.ids.a self.LadeButton = self.ProduktOrganizerInstanz.ids.LadeButton self.LadeButton.on_release = PopupDateiauswahl.open self.PopupDateiAuswaehlenInst.ids.b.ids.OkButtonFilechooser.on_release = self.datenentpickeln self.PopupDateiAuswaehlenInst.ids.b.ids.LayoutPopup.add_widget(Label (text='[b][color=ff3333]Achtung, nicht gespeicherte Eingaben gehen verloren![/b][/color]', size_hint= (1,0.1), markup = True, font_size = 14)) self.PopupDateiAuswaehlenSpeichernInst = PopupDateiAuswaehlenProduktorganizer() PopupDateiauswahlSpeichern = self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.a self.SpeicherButton = self.ProduktOrganizerInstanz.ids.SpeicherButton self.SpeicherButton.on_release = PopupDateiauswahlSpeichern.open self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.OkButtonFilechooser.on_release = self.datenpickeln #print 'tempChildernListe',TempChildrenList #self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.add_widget(TextInput(multiline=False, size_hint= (1,0.15))) self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.add_widget(Label (text='[b][color=ff3333]Achtung, der Inhalt der Datei wird ueberschrieben![/b][/color]', size_hint= (1,0.1), markup = True, font_size = 14)) TempChildrenList = [] for q in self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.children: TempChildrenList.append(q) self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.clear_widgets() FileSaveLabelTextInput = Label(text='Zur Erstellung einer neuen Datei,einen Namen angeben',size_hint= (1,0.15), font_size=16) self.FileSaveTextInput = TextInput(multiline=False,size_hint= (1,0.15)) TempChildrenList.sort(reverse=True) print "vor dem Einfuegen" for index, item in enumerate(TempChildrenList): print index, item TempChildrenList.insert(2, FileSaveLabelTextInput) TempChildrenList.insert(3, self.FileSaveTextInput) for i in TempChildrenList: #i.parent = None self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.add_widget(i) print "nach dem Einfuegen und sortieren" for index, item in enumerate(TempChildrenList): print index, item #self.LadeButton.bind(on_release = self.datenentpickeln) Spinner =self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer SpinnerText = Spinner.text self.LadeButton.bind(on_release = self.produktorganizerfilter) #self.ButtonHinzufuegen.on_release = self.inputdata #self.Box.add_widget(Button(size_hint= (1,0.1),text='inputdata', on_release=self.inputdata)) self.PopupInst = PopupBildAuswaehlenProduktorganizer() popup = self.PopupInst.ids.a self.ProduktOrganizerInstanz.ids.ProduktBildAuswaehlen.on_release = popup.open self.PersonalOrganizerInstanz = PersonalOrganizer() self.HauptCarousel.add_widget(self.PersonalOrganizerInstanz) self.ZeitOrganizerInstanz = ZeitOrganizer() self.HauptCarousel.add_widget(self.ZeitOrganizerInstanz) ## def inputdata(self): ## print 'inputdadat runs' ## #self.CustomScrollviewProduktOrganizerInstanz.data = [str(i) for i in range(5)] ## self.ProduktOrganizerInstanz.ids.custScrlInst.data = [str(i) for i in range(5)] def produkthinzufuegen(self): #App.AuswahlHauptlisteAlt = App.AuswahlHauptliste NeuesDict ={} WertEingabeFeldBezeichnung = self.ProduktOrganizerInstanz.ids.EingabeFeldBezeichnung.text WertEingabeFeldPreis = self.ProduktOrganizerInstanz.ids.EingabeFeldPreis.text ## StatusCheckBoxVerkauf = self.ProduktOrganizerInstanz.ids.CheckBoxVerkauf.active WertSpinnerKategorie = str(self.ProduktOrganizerInstanz.ids.SpinnerKategorie.text) filechooser = self.PopupInst.ids.filechooser DateiAuswahl = (str(filechooser.selection))[((str(filechooser.selection)).find('pictures')):-2] #print 'hallo', WertEingabeFeldBezeichnung, WertEingabeFeldPreis,DateiAuswahl,WertSpinnerKategorie ID = len(App.HauptListeDictonaries) NeuesDict = {'ID': ID, 'Bezeichnung':WertEingabeFeldBezeichnung, 'Preis':WertEingabeFeldPreis, 'Bild':DateiAuswahl, 'Kategorie':WertSpinnerKategorie} #print 'len(App.HauptListeDictonaries)', (len(App.HauptListeDictonaries)) ## if len(App.HauptListeDictonaries)<1: ## App.HauptListeDictonaries.append(NeuesDict) ## print 'Fall 1' ## else: Treffer = False for i in range(len(App.HauptListeDictonaries[:])): print 'App.HauptListeDictonaries[i][Bezeichnung] ist', App.HauptListeDictonaries[i]['Bezeichnung'] Bezeichnungdict = str(App.HauptListeDictonaries[i]['Bezeichnung']) Bezeichnungneuesdict = str(NeuesDict['Bezeichnung']) if Bezeichnungdict == Bezeichnungneuesdict: Treffer = True break else: Treffer = False if Treffer == True: #print 'Dieses Produkt existiert schon' ButtonVerstanden = Button(text='Verstanden') popup = Popup(title='Dieses Produkt existiert bereits ', size_hint = (0.5, 0.25), content= ButtonVerstanden) popup.open() ButtonVerstanden.on_release = popup.dismiss else: App.HauptListeDictonaries.append(NeuesDict) #self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.clear_widgets() ## print len(App.HauptListeDictonaries) ## for index, item in enumerate(App.HauptListeDictonaries): ## print index, item #self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.HauptListeDictonaries #self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.AuswahlHauptliste #AktuelleWidgetsInDerListe = self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.children #print 'App.AuswahlHauptlisteAlt', App.AuswahlHauptlisteAlt #AktuelleWidgetsInDerListe = self.CustomScrollviewProduktOrganizerInstanz.ids.content2.children #print AktuelleWidgetsInDerListe #self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.add_widget(Button(text='testmanuellereinfuegung')) AktuellerSpinnerWert = self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer.text self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.clear_widgets() App.AuswahlHauptliste = [] if AktuellerSpinnerWert == 'Alle': #self.CustomScrollviewProduktOrganizerInstanz.ids.content2.clear_widgets() print 'haha' App.AuswahlHauptliste = [] for i in App.HauptListeDictonaries: if i not in App.AuswahlHauptlisteAlt: pass App.AuswahlHauptliste = App.HauptListeDictonaries App.AuswahlHauptlisteAlt = [] else: if self.SpinnerButtonZustand == 'Alle': App.AuswahlHauptlisteAlt = [] else: pass for i in App.HauptListeDictonaries: if i not in App.AuswahlHauptlisteAlt: if i['Kategorie'] == AktuellerSpinnerWert: App.AuswahlHauptliste.append(i) else: continue else: continue self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.AuswahlHauptliste def produktorganizerfilter(self, spinner, text='Alle'): spinner =self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer text = spinner.text self.ProduktOrganizerInstanz.ids.custScrlInst.data = [] #print 'produktorganizerfilter, App.AuswahlHauptlisteAlt', App.AuswahlHauptlisteAlt if self.SpinnerButtonZustand == 'Alle': App.AuswahlHauptlisteAlt = [] else: App.AuswahlHauptlisteAlt = App.AuswahlHauptliste #custScrlInst self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.clear_widgets() #self.CustomScrollviewProduktOrganizerInstanz.ids.content2.clear_widgets() App.AuswahlHauptliste=[] if text == 'Alle': App.AuswahlHauptliste = App.HauptListeDictonaries self.SpinnerButtonZustand = 'Alle' if self.ProduktOrganizerInstanz.ids.custScrlInst.data == App.AuswahlHauptliste: self.ProduktOrganizerInstanz.ids.custScrlInst.data = [] else: self.SpinnerButtonZustand = 'Anders' for i in App.HauptListeDictonaries: if i not in App.AuswahlHauptlisteAlt: #print i['Kategorie'] if i['Kategorie'] == text: App.AuswahlHauptliste.append(i) else: continue else: continue #print 'Auswahl Hauptliste ist nun', App.AuswahlHauptliste self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.AuswahlHauptliste def DropdownbuttonCreator(self): Auswahlliste = ["Tisch +", "Tisch -", "Spalte + ", "Spalte -", "Reihe + ", "Reihe -"] BackgroundcolorListe = [(0,1,0,1),(1,0,0,1),(0,1,0,1),(1,0,0,1),(0,1,0,1),(1,0,0,1)] Aktionsliste = [self.tischhinzufuegen, self.tischentfernen, self.spaltehinzufuegen, self.spalteentfernen, self.zeilehinzufuegen, self.zeileentfernen] DropdownObjekt = CustomDropDown() DropdownObjektButton = CustomButton(text = "Menue", #DropdownObjektButton = ToggleButton(text="Menue", size_hint=[1,1], background_color = (0.8, 0.8, 0.00, 1), background_normal='bilder_oberflaeche/white2.png', background_down='bilder_oberflaeche/white3.png') #self.CustomLayout.add_widget(DropdownObjektButton) DropdownObjektButton.bind(on_release=DropdownObjekt.open) self.DropdownObjects.append(DropdownObjekt) for x in range(len(Auswahlliste)): DropdownUnterbutton = Button(text=Auswahlliste[x], font_size = 15, size_hint_y=None, height=60, background_color = BackgroundcolorListe[x], background_normal='bilder_oberflaeche/white2.png', background_down='bilder_oberflaeche/white3.png', opacity = 0.8, on_release = Aktionsliste[x]) DropdownObjekt.add_widget(DropdownUnterbutton) ButtonMenu1 = DropdownObjektButton return ButtonMenu1 def tischerstellung (self, Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe): Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] Aktionsliste = [self.bestellung, self.abrechnung, self.bestellungaendern, self.tischbenennen] #self.DropdownObjects = [] for i in range(AnzahlTische): if self.Tischliste != []: LetzterTisch = self.Tischliste[-1]['Nummer'] ## print LetzterTisch + 1 else: LetzterTisch = 0 TischNr = str(LetzterTisch+1) TischButtonText = "T " + TischNr DropdownObjekt = CustomDropDown() #von kovak hinzugefuegt #DropdownObjektButton = CustomButton(text = TischButtonText, DropdownObjektButton = ToggleButton(text = TischButtonText, group='Tische', #background_normal='bilder_oberflaeche/white2.png', background_normal='bilder_oberflaeche/buttonbackground_normal_gruenrandaussenbraun.png', background_down='bilder_oberflaeche/buttonbackground_normal_weissrandaussenbraun.png', #background_down='bilder_oberflaeche/white4.png', #background_color = (0.79, 0.39, 0.09, 1))#0.6)) background_color = (1, 1, 1, 1))#0.6)) Zielwidget.add_widget(DropdownObjektButton) DropdownObjektButton.bind(on_release=DropdownObjekt.open) self.DropdownObjects.append(DropdownObjekt) #von kovak hinzugefuegt for x in range(len(Auswahlliste)): DropdownUnterbutton = Button(text=Auswahlliste[x], id = TischNr, #auto_width='False', #width = '200sp', font_size = 15, size_hint_y=None, height=60, background_normal='bilder_oberflaeche/white2.png', background_down='bilder_oberflaeche/white3.png', background_color = BackgroundcolorListe[x], on_release = Aktionsliste[x]) DropdownObjekt.add_widget(DropdownUnterbutton) #print' button', i, 'unterbutton', x DropdownObjektButton.text= TischButtonText self.TischButtondict = {'Nummer':(LetzterTisch + 1),'Objekt':DropdownObjektButton} self.Tischliste.append(self.TischButtondict) def garbagecollectortracking(self, widget): for i in self.Tischliste: a = i print gc.is_tracked(a) ### function for Editing a Table####################################### #def tischmanipulieren(self, widget): # widget.text = 'mein text' #### function for adding an extra table to layout ########################## def tischhinzufuegen(self, widget): if len(self.Tischliste) >= 1: if hasattr(self, 'CustomLayoutBottomLabel'): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) AnzahlTische = 1 Zielwidget = self.CustomLayoutGridLayout Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] LetzterTisch = self.Tischliste[-1]['Nummer'] if (self.CustomLayoutGridLayout.cols * self.CustomLayoutGridLayout.rows) <= (LetzterTisch +1): self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1 self.tischerstellung(Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe) def tischentfernen(self, widget): self.Warnlabel = 0 if len(self.Tischliste) <= 1: if hasattr(self, 'CustomLayoutBottomLabel'): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel=1 print 'das ist der Letzte Tisch, der kann nicht entfernt werden' if self.Warnlabel == 0: self.CustomLayoutBottomLabel= Label(text='Das ist der Letzte Tisch,\n der kann nicht \n entfernt werden', text_size = self.size) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: Zielwidget = self.CustomLayoutGridLayout Zielwidget.remove_widget(self.Tischliste[-1]['Objekt']) del self.Tischliste[-1] LetzterTisch = self.Tischliste[-1]['Nummer'] print 'die anzahl der Tische ist nun:', LetzterTisch pass #### function for adding a column to layout #################################### def spaltehinzufuegen(self, widget): if self.CustomLayoutGridLayout.cols >= 1: if hasattr(self, 'CustomLayoutBottomLabel'): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) self.WarnLabel = 0 self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols + 1 print 'Zeile hinzufuegen' def spalteentfernen(self, widget): self.Warnlabel = 0 if self.CustomLayoutGridLayout.cols <= 1: if hasattr(self, 'CustomLayoutBottomLabel'): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel=1 print 'das ist die letzte Tischreihe, sie kann nicht entfernt werden' if self.Warnlabel == 0: self.CustomLayoutBottomLabel= Label(text='Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden', text_size = self.size) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: TischanzahlVerbleibend = (self.CustomLayoutGridLayout.cols -1) * self.CustomLayoutGridLayout.rows for i in range(len(self.Tischliste[TischanzahlVerbleibend:])): self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend+ i]['Objekt']) del self.Tischliste[TischanzahlVerbleibend:] self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols - 1 #### function for adding a row to layout #################################### def zeilehinzufuegen(self, widget): if self.CustomLayoutGridLayout.rows >= 1: if hasattr(self, 'CustomLayoutBottomLabel'): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) self.WarnLabel = 0 self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1 print 'Zeile hinzufuegen' def zeileentfernen(self, widget=None): self.Warnlabel = 0 if self.CustomLayoutGridLayout.rows <= 1: if hasattr(self, 'CustomLayoutBottomLabel'): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel=1 print 'das ist die letzte Tischreihe, sie kann nicht entfernt werden' if self.Warnlabel == 0: self.CustomLayoutBottomLabel= Label(text='Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden', text_size = self.size) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: TischanzahlVerbleibend = (self.CustomLayoutGridLayout.rows -1) * self.CustomLayoutGridLayout.cols for i in range(len(self.Tischliste[TischanzahlVerbleibend:])): self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend+ i]['Objekt']) del self.Tischliste[TischanzahlVerbleibend:] self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows - 1 def bestellung(self, widget): App.my_index = -1 TischNr = widget.id PopupFloatLayout = FloatLayout(size_hint=(1, 1)) self.PopupScrollview = CustomScrollviewPopupContent() self.PopupScrollviewItem = CustomButton2() App.AuswahlHauptliste = App.HauptListeDictonaries self.PopupScrollview.data = App.AuswahlHauptliste #content = self.PopupScrollview.ids.content #item = self.PopupScrollviewItem popup = Popup(title='Bestellung für Tisch ' + str(TischNr), content= PopupFloatLayout) BoxTop = BoxLayout(size_hint= [0.52,0.065],pos_hint={'x': 0.5, 'y': 1.005}, spacing = 5) ButtonExit = Button(text="Exit", #pos_hint={'x': 0.825, 'y': 1.005}, #size_hint = [0.2,0.065], size_hint = [0.3,1], #on_release = self.zeromyindex, on_release = popup.dismiss) #myindexzero = 0 #ButtonExit.bind(on_release=ButtonExit.setter('myindexzero')) #print App.my_index self.ButtonSpinner =Spinner(text= "Alle", values= ("Mittag-Essen", "Getraenke", "AlcGetraenke", "Essen Alltime", "Alle"), size_hint= [0.7,1], #pos_hint={'x': 0.625, 'y': 1.005} ) self.ButtonSpinner.bind(text=self.show_selected_value) #halign: 'right' #valign: 'top' #PopupFloatLayout.add_widget(ButtonExit) #PopupFloatLayout.add_widget(ButtonSpinner) BoxTop.add_widget(self.ButtonSpinner) BoxTop.add_widget(ButtonExit) PopupFloatLayout.add_widget(BoxTop) self.PopupScrollview.size_hint = [1.05,1.017] self.PopupScrollview.center = popup.center PopupFloatLayout.add_widget(self.PopupScrollview) for i in App.ScrollviewButtons: i.ids.customID.on_release = self.Optionsfenster popup.open() print App.ScrollviewButtons ## ## def on_data(self, instance, value): ## content_add = self.PopupScrollview.ids.content.add_widget ## for item in value: ## print item ## content_add(CustomButton2(text=item)) #return CustomScrollviewPopupContent() def show_selected_value(self, spinner, text): print 'The spinner', spinner, 'have text', text App.AuswahlHauptliste=[] if text == 'Alle': App.AuswahlHauptliste = App.HauptListeDictonaries self.PopupScrollview.data = App.AuswahlHauptliste else: for i in App.HauptListeDictonaries: if i['Kategorie'] == text: App.AuswahlHauptliste.append(i) else: continue self.PopupScrollview.data = App.AuswahlHauptliste def zeromyindex(self, widget): App.my_index = (-1) def Optionsfenster(self): self.OptionenPopupBestellungen = OptionenPopupBestellungen() print 'App.AktuelleBestellungProduktAnzahlzaehler', App.AktuelleBestellungProduktAnzahlzaehler for i in range(App.AktuelleBestellungProduktAnzahlzaehler): self.OptionenPopupBestellungen.ids.OptionsPopupContent.add_widget(ToggleButton(text=i)) self.OptionenPopupBestellungen.open() def groesse(self,widget): print 'die buttongroesse ist:', widget.size def abrechnung(self, widget): TischNr = widget.id PopupFloatLayout = FloatLayout() self.ScreenmanagerPopup = CustomScreenManager() self.ScreenPopup = CustomScreen for x in xrange(4): self.ScreenmanagerPopup.add_widget(self.ScreenPopup(name='Screen %d' % x)) #popup = Popup(title='Abrechnung für ' + str(TischNr), # content=self.ScreenmanagerPopup,size_hint=(1, 1) ) popup = Popup(title='Abrechnung für Tisch' + str(TischNr), content=PopupFloatLayout)#, #size_hint=(1, 1), #pos_hint={'x': 0.5, 'y': 0.5} ) self.ScreenmanagerPopup.pos_hint = {'x': 0, 'y': 0} PopupFloatLayout.add_widget(self.ScreenmanagerPopup) ButtonExit = Button(text="Exit", pos_hint={'x': 0.8, 'y': 1.005}, size_hint = [0.2,0.065], on_release = popup.dismiss) PopupFloatLayout.add_widget(ButtonExit) popup.open() def bestellungaendern(self, widget): pass def tischbenennen(self, widget): TischNr = widget.id PopupBox1LayoutTischBennenen = BoxLayout(orientation = 'vertical') popup = Popup(title='Tisch Nr. ' + str(TischNr) + 'benennen', content=PopupBox1LayoutTischBennenen, size_hint=(0.75, 0.5)) EingabeTextfeld = TextInput(text='hier Tischbezeichnung eintragen - Funktion muss noch eingebaut werden') PopupBox1LayoutTischBennenen.add_widget(EingabeTextfeld) PopupBoxLayoutTischBenennen = BoxLayout(orientation = 'horizontal', size_hint=(1,1)) ButtonAbbrechenTischBenennen = Button(text="Abbrechen", size_hint=(0.5, 0.5)) ButtonAbbrechenTischBenennen.bind(on_press=popup.dismiss) ButtonOkTischBenennen = Button(text="OK", size_hint=(0.5, 0.5)) ButtonOkTischBenennen.bind(on_press=popup.dismiss) PopupBox1LayoutTischBennenen.add_widget(PopupBoxLayoutTischBenennen) PopupBoxLayoutTischBenennen.add_widget(ButtonAbbrechenTischBenennen) PopupBoxLayoutTischBenennen.add_widget(ButtonOkTischBenennen) #popup.add_widget popup.open() pass #### function for exporting Data to file #################################### def datenpickeln(self): filechooser = self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.filechooser AusgewaehlteDatei = str(filechooser.selection) AusgewaehlteDatei = (AusgewaehlteDatei)[AusgewaehlteDatei.find('Produktlisten'):-2] if self.FileSaveTextInput.text != '': print 'Du hast einen Dateinamen eingegeben' AusgewaehlteDatei = 'Produktlisten/'+(str(self.FileSaveTextInput.text)) print 'Daten Speichern ausgefuehrt' print AusgewaehlteDatei SicherungsItem1 = self.HauptCarousel2.Texteingabe.text SicherungsItem2 = App.HauptListeDictonaries Sicherungsliste = [SicherungsItem1, SicherungsItem2] '''function to pickle data to make it ready for sending''' try: with open(AusgewaehlteDatei, 'w+b') as SicherungslisteDaten_File: pickle.dump(Sicherungsliste, SicherungslisteDaten_File) except IOError as err: print('Dateifehler: ' + str(err)) except pickle.PickleError as perr: print('Pickling Fehler: ' + str(perr)) #### function for importing Data to file #################################### def datenentpickeln(self): filechooser = self.PopupDateiAuswaehlenInst.ids.b.ids.filechooser AusgewaehlteDatei = str(filechooser.selection) print 'Daten Laden ausgefuehrt' print AusgewaehlteDatei AusgewaehlteDatei = (AusgewaehlteDatei)[AusgewaehlteDatei.find('Produktlisten'):-2] #App.datenentpickeln = self(datenentpickeln(widget = None)) with open(AusgewaehlteDatei, 'rb') as SicherungslisteDaten_File_entpickelt: SicherungslisteWiederhergestellt = pickle.load(SicherungslisteDaten_File_entpickelt) #self.HauptCarousel3.Textausgabe.text = SicherungslisteWiederhergestellt[0] App.HauptListeDictonaries = SicherungslisteWiederhergestellt[1] ## App.AuswahlHauptListe = App.HauptListeDictonaries ## self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.AuswahlHauptListe self.produktorganizerfilter(self) print 'die daten wurden wieder hergestellt'
class EditSlide(BoxLayout): btn_close = ObjectProperty() btn_save = ObjectProperty() layout_kl = ObjectProperty() layout_chunk = ObjectProperty() layout_meaning = ObjectProperty() selected = ObjectProperty() approved = ObjectProperty() unapproved = ObjectProperty() undefined = ObjectProperty() chunk = ObjectProperty() #chunk meaning = ListProperty([]) #found meaning category = ObjectProperty() score = ObjectProperty() def __init__(self, verbose=False, **kwargs): super(EditSlide, self).__init__(**kwargs) self.id = 'editslide' self.verbose = verbose self.db = Manager() self.app = App.get_running_app() self.popupedit = self self.rows_ud = None self.rows_kl = None self.meaning = [] self.found_numb = 0 self.counter = 0 self.btn_split = None self.wiki = Wikiapi() self.conceptnet = ConceptNet5() def fill_data(self): self.layout_meaning.clear_widgets() if self.btn_split != None: self.layout_chunk.remove_widget(self.btn_split) self.grid_row = GridLayout(cols=1, spacing=5) self.layout_meaning.add_widget(self.grid_row) #CHUNK print 'current chunk: ', self.app.root.current_chunk self.chunk.text = self.app.root.current_chunk ##retrieve data from userdata e knowledge table self.rows_ud = self.db.getchunk_ud(self.app.root.current_chunk, self.app.root.userID, self.app.root.senderID) self.rows_kl = self.db.getchunk_kl(self.app.root.current_chunk) #check if it is a ngram and if so add split button if int(self.rows_kl[0].ngram) > 1: self.btn_split = ColorDownButtonH50(id='split', text="[b]SPLIT[/b]", markup=True, size_hint_x=0.25, on_press=self.split) self.layout_chunk.add_widget(self.btn_split) #insert list of possible meaning/url for idx, row in enumerate(self.rows_kl): self.add_meaning_full(row) #set by default the first meaning True self.grid_row.children[0].children[0].active = True self.addmore = IconButtonPlus(id='addmore', spacing=20, size_hint_y=None, height=self.app.row_height) self.addmore.bind(on_press=self.add_meaning_empty) self.grid_row.add_widget(self.addmore) #set categories self.category.text = self.rows_kl[0].category #set score self.score.text = str(self.rows_ud[0].score) #set table radio button if self.rows_ud[0].status == 0: self.undefined.state = 'down' elif self.rows_ud[0].status == 1: self.approved.state = 'down' else: self.unapproved.state = 'down' def add_meaning_empty(self, instance): """ Add a meaning row on the GUI to let the user add his own meaning :param instance: :return: """ self.grid_row.remove_widget(self.addmore) self.found_numb += 1 self.counter += 1 bl = BoxLayoutH50(id='bl'+str(self.found_numb)) al = AnchorLayout(anchor_x='center', anchor_y='center', size_hint_x=0.05, size_hint_y=None, height=self.app.row_height) al.add_widget(IconButtonDel(id='btn'+str(self.found_numb), on_press=self.remove_line)) bl.add_widget(al) al2 = AnchorLayout(anchor_x='center', anchor_y='center', size_hint_x=0.05, size_hint_y=None, height=self.app.row_height) btn_ref = IconButtonRefresh(id='btn_ref'+str(self.found_numb)) btn_ref.bind(on_press=self.update_wiki) al2.add_widget(btn_ref) bl.add_widget(al2) bl.add_widget(TextInputH50(id='found'+str(self.found_numb), text='', size_hint_x=0.25)) bl.add_widget(TextInputH50(id='url'+str(self.found_numb), text='', size_hint_x=0.3)) bl.add_widget(CheckBoxH50(id='dis'+str(self.found_numb), size_hint_x=0.15)) bl.add_widget(CheckBoxH50(id='approved'+str(self.found_numb), size_hint_x=0.1)) bl.add_widget(CheckBoxH50(id='chosen'+str(self.found_numb), group='chosen', size_hint_x=0.1)) self.grid_row.add_widget(bl) self.grid_row.add_widget(self.addmore) def add_meaning_full(self, row): """ Add a meaning row on the GUI to let the user add his own meaning :param instance: :return: """ self.found_numb += 1 self.counter += 1 bl = BoxLayoutH50(id='bl'+str(self.found_numb)) al = AnchorLayout(anchor_x='center', anchor_y='center', size_hint_x=0.05, size_hint_y=None, height=self.app.row_height) al.add_widget(IconButtonDel(id='btn'+str(self.found_numb), on_press=self.remove_line)) bl.add_widget(al) al2 = AnchorLayout(anchor_x='center', anchor_y='center', size_hint_x=0.05, size_hint_y=None, height=self.app.row_height) btn_ref = IconButtonRefresh(id='btn_ref'+str(self.found_numb)) btn_ref.bind(on_press=self.update_wiki) al2.add_widget(btn_ref) bl.add_widget(al2) bl.add_widget(TextInputH50(id='found', text=row.found, size_hint_x=0.25)) bl.add_widget(TextInputH50(id='url'+str(self.found_numb), text=row.url, size_hint_x=0.3)) if row.disambiguation_url == 1: bl.add_widget(CheckBoxH50(id='dis'+str(self.found_numb), size_hint_x=0.15, active=True)) else: bl.add_widget(CheckBoxH50(id='dis'+str(self.found_numb), size_hint_x=0.15)) bl.add_widget(CheckBoxH50(id='approved'+str(self.found_numb), size_hint_x=0.1, active=True)) bl.add_widget(CheckBoxH50(id='chosen'+str(self.found_numb), group='chosen', size_hint_x=0.1)) self.grid_row.add_widget(bl) def remove_line(self, instance): """ callback event on del button, must remove corresponding line :param instance: :return: """ self.counter -= 1 self.grid_row.remove_widget(instance.parent.parent) def update_wiki(self, instance): """ function to automatically update the wikipedia url from the corresponding founded meaning :param instance: :return: """ print 'update wiki' chunk = instance.parent.parent.children[4].text if chunk == '': return url, dis = self.wiki.geturl(chunk.lower()) instance.parent.parent.children[3].text = url if dis == 1: instance.parent.parent.children[2].active = True else: instance.parent.parent.children[2].active = False def update_cat(self): """ function to automatically update the category from the original chunk :return: """ print 'update category' print 'chunk: ', self.chunk.text self.conceptnet.search_edit(self.chunk.text) def split(self, instance): """ callback function after "split" button pressed, opens a popup to allow user split the phrase :return: """ print 'split button pressed' sp = SplitPopup(self.chunk.text, len(self.chunk.text.split(" ")), self.rows_ud, self.rows_kl) sp.bind(on_dismiss=self.split_end) sp.open() def split_end(self, instance): """ callback function when split popup close :param instance: :return: """ self.app.root.carousel.load_slide(self.app.root.approved) def update(self): """ callback function after save changes button pressed. Store the new data in the DB :return: void """ ########################################################## ## INPUT CHECK ########################################################## if self.chunk.text == '' or self.score.text == '' or not self.is_number(self.score.text): popup = Popup(title='Alert!!', content=Label(text="Incomplete data, please re-check!"), size_hint=(None, None), size=(400, 200)) popup.open() return if self.counter == 0: # no meaning for that chunk popup = Popup(title='Alert!!', content=Label(text="No meaning for this chunk\nInsert at least one!"), size_hint=(None, None), size=(400, 200)) popup.open() return self.meaning = [] chosen_mean = '' for bl in self.layout_meaning.children: for idx, elem in enumerate(bl.children): if idx == 0: continue #the first children is the ADD new button #parse all rows mean = elem.children[4].text url = elem.children[3].text dis = elem.children[2].active approved = elem.children[1].active chosen = elem.children[0].active if mean == '': popup = Popup(title='Alert!!', content=Label(text="Empty meaning not allowed!"), size_hint=(None, None), size=(400, 200)) popup.open() return self.meaning.append(dict(found=mean, url=url, dis=dis, approved=approved, chosen=chosen)) ## check at least 1 approved count_approved = 0 for x in self.meaning: print x if x['approved'] is True: count_approved += 1 if count_approved == 0: popup = Popup(title='Alert!!', content=Label(text="At least insert one approved meaning!"), size_hint=(None, None), size=(400, 200)) popup.open() return chosen_table = 0 l = ToggleButtonBehavior.get_widgets('table') for toggle in l: if toggle.state == 'down': if toggle.text == '[b]Approved[/b]': chosen_table = 1 elif toggle.text == '[b]Unapproved[/b]': chosen_table = 2 del l print 'chunk: ', self.chunk.text print 'rows: ', self.meaning print 'category: ', self.category.text print 'chosen table: ', chosen_table print 'score: ', self.score.text print 'old_chunk: ', self.app.root.current_chunk print 'old_found: ', self.rows_kl ########################################################## ## DATA DUMP ########################################################## ##delete section (no update because I can have multiple meanings) for row in self.rows_kl: print 'dentro elimina kl' self.db.del_row_kl(chunk=str(self.app.root.current_chunk), found=row.found) self.db.del_chunk_ud(userid=self.app.root.userID, senderid=self.app.root.senderID, chunk=self.rows_ud[0].chunk) ##insert section for row in self.meaning: print row if row['approved']: print 'pre inserimento DB KL' self.db.insert_single_kl(chunk=self.chunk.text, found=row['found'], category=self.category.text, url=row['url'], dis=row['dis'], ngram=len(self.chunk.text.split(" "))) if row['chosen']: print 'pre inserimento DB UD' self.db.insert_single_ud( userid=self.app.root.userID, senderid=self.app.root.senderID, chunk=self.chunk.text, found=row['found'], score=int(self.score.text), status=chosen_table) ########################################################## ## END ########################################################## self.app.root.carousel.load_slide(self.app.root.approved) def is_number(self, number): """ function to check if a string represent a integer :param number: :return: """ try: int(number) return True except ValueError: return False
class TabBox(BoxLayout): def __init__(self, *args, **kwargs): super(TabBox, self).__init__(*args, **kwargs) self.tab_holder = GridLayout(rows=1, spacing=5, size_hint=(None, 1)) self.tab_holder.bind(minimum_width=self.tab_holder.setter('width')) self.ids.tab_scroller.add_widget(self.tab_holder) self.tabs = {} self.scroll_left = None self.scroll_right = None self.bind(width=self.check_width) def add_tab(self, name, text, position=0, has_close=True): name = name.encode('ascii', 'ignore') tab = Tab(self, name, has_close) tab.ids.tab_label.text = text screen = Screen(name=name) self.tabs[name] = { 'tab':tab, 'screen':screen, } self.ids.tab_content.add_widget(screen) self.tab_holder.add_widget(tab, position) self.check_width() if len(self.tabs) == 1: self.switch_tab(name) return tab def check_width(self, *args): if len(self.tabs) * TAB_WIDTH > self.width: # we're too wide, we should have scroll buttons if not self.scroll_left: # more tabs than box width, put in the scroller buttons self.scroll_left = Button(text='<', width=40, height=40, size_hint=(None, None), disabled=True) self.scroll_left.bind(on_release=self.pushed_scroll_left) self.ids.tab_header.add_widget(self.scroll_left, 2) self.scroll_right = Button(text='>', width=40, height=40, size_hint=(None, None)) self.scroll_right.bind(on_release=self.pushed_scroll_right) self.ids.tab_header.add_widget(self.scroll_right, 0) else: # we're not wide, remove any scroll buttons if self.scroll_left: self.ids.tab_header.remove_widget(self.scroll_left) self.ids.tab_header.remove_widget(self.scroll_right) self.scroll_left = None self.scroll_right = None def remove_tab(self, name): name = name.encode('ascii', 'ignore') if self.ids.tab_content.current == name: # removing the current tab if len(self.tabs) == 1: show_tab = '__empty__' else: show_tab = self.ids.tab_content.previous() if not show_tab or show_tab == '__empty__': show_tab = self.ids.tab_content.next() self.switch_tab(show_tab) self.ids.tab_content.remove_widget(self.tabs[name]['screen']) self.tab_holder.remove_widget(self.tabs[name]['tab']) del self.tabs[name] self.check_width() def get_content_widget(self, name): return self.tabs[name]['screen'] def pushed_scroll_left(self, *args): scroll_amount = 1.0 / float(len(self.tabs)) value = self.ids.tab_scroller.scroll_x - scroll_amount if value <= 0.0: value = 0.0 self.scroll_left.disabled = True self.ids.tab_scroller.scroll_x = value self.scroll_right.disabled = False def pushed_scroll_right(self, *args): scroll_amount = 1.0 / float(len(self.tabs)) value = self.ids.tab_scroller.scroll_x + scroll_amount if value >= 1.0: value = 1.0 self.scroll_right.disabled = True self.ids.tab_scroller.scroll_x = value self.scroll_left.disabled = False def switch_tab(self, name): name = name.encode('ascii', 'ignore') old = self.ids.tab_content.current if old in self.tabs: self.tabs[old]['tab'].ids.tab_label.bold = False if name != '__empty__': self.tabs[name]['tab'].ids.tab_label.bold = True self.ids.tab_content.current = name
class crit_Controls(GridLayout): """Area for sliders""" def __init__(self, **kwargs): super(crit_Controls, self).__init__(**kwargs) self.cols = 2 # Left Half is a 6 row slider grid self.sliders = GridLayout( rows = 6, size_hint_x = 75, spacing = 20, padding = 20 ) # Previous Injuries self.prevInjuriesLabel = Label( text = "Previous Critical Injuries" ) self.prevInjuriesSlider = Slider( range = (0,15), step = 1, value = 0, size_hint_x = 90 ) self.prevInjuriesReadout = Label( text = "[b]" + str(int(self.prevInjuriesSlider.value)) + "[/b]", markup = True ) self.prevInjuriesSliderGrid = GridLayout( cols = 3, spacing = 12 ) self.prevInjuriesSliderGrid.add_widget(Label( text = '0', size_hint_x = 5 )) self.prevInjuriesSliderGrid.add_widget(self.prevInjuriesSlider) self.prevInjuriesSliderGrid.add_widget(Label( text = '15', size_hint_x = 5 )) # Roll Modifier self.modLabel = Label( text = "Roll Modifier" ) self.modSlider = Slider( range = (-150,150), step = 5, value = 0, size_hint_x = 90 ) self.modReadout = Label( text = "[b]" + str(int(self.modSlider.value)) + "[/b]", markup = True ) self.modSliderGrid = GridLayout( cols = 3, spacing = 12 ) self.modSliderGrid.add_widget(Label( text = '-150', size_hint_x = 5 )) self.modSliderGrid.add_widget(self.modSlider) self.modSliderGrid.add_widget(Label( text = '150', size_hint_x = 5 )) # Right Half is Reset and Roll Buttons self.buttonContainer = GridLayout( cols = 1, padding = 20, spacing = 20, size_hint_x = 25 ) self.resetButton = Button( text = "Reset", on_press = self.reset, size_hint_y = 30 ) self.rollButton = Button( text = "Roll", on_press = self.roll, size_hint_y = 70 ) # Add all widgets for widget in ( self.prevInjuriesLabel, self.prevInjuriesSliderGrid, self.prevInjuriesReadout, self.modLabel, self.modSliderGrid, self.modReadout ): self.sliders.add_widget(widget) self.add_widget(self.sliders) self.add_widget(self.buttonContainer) self.buttonContainer.add_widget(self.resetButton) self.buttonContainer.add_widget(self.rollButton) # Binds for Bg Color self.bind( size = self._update_bg, pos = self._update_bg ) # Binds for Slide values self.prevInjuriesSlider.bind( value = self._update_slider_readouts ) self.modSlider.bind( value = self._update_slider_readouts ) # BG Color with self.canvas.before: Color(.033, .149, .202) self.bg = Rectangle( size = self.size, pos = self.pos ) def roll(self, ignore=''): self.parent.resultBox.roll() def reset(self, ignore=''): self.prevInjuriesSlider.value = 0 self.modSlider.value = 0 self._update_slider_readouts() def _update_bg(self, instance, value): self.bg.size = instance.size self.bg.pos = instance.pos def _update_slider_readouts(self, instance='', value=''): self.sliders.remove_widget(self.prevInjuriesReadout) self.prevInjuriesReadout = Label( text = "[b]" + str(int(self.prevInjuriesSlider.value)) + "[/b]", markup = True ) self.sliders.add_widget(self.prevInjuriesReadout, index = 3) self.sliders.remove_widget(self.modReadout) self.modReadout = Label( text = "[b]" + str(int(self.modSlider.value)) + "[/b]", markup = True ) self.sliders.add_widget(self.modReadout, index = 0)
class LoginScreen(FloatLayout): # x = ListProperty([]) # print x def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # gc.disable() self.DropdownObjects = [] self.add_widget( Label( text="Wilkommen [color=ff3333] [sub] bei der [/sub][/color][color=3333ff][b] Bonierungs[sup][color=#098125ff]App[/sup][/b][/color]", markup=True, pos_hint={"top": 1.2}, font_size="20sp", ) ) self.GridlayoutS1 = GridLayout(cols=2, size_hint_y=1 / 5, pos_hint={"top": 0.6}) self.add_widget(self.GridlayoutS1) self.GridlayoutS1.add_widget(Label(text="User Name")) # , size_hint_x = 0.2, size_hint_y = 0.2)) self.username = TextInput(multiline=False) # , size_hint_x = 0.2, size_hint_y = 0.2) self.username.bind(on_text_validate=self.on_enter) self.GridlayoutS1.add_widget(self.username) self.GridlayoutS1.add_widget(Label(text="password")) # ,size_hint_x = 0.2, size_hint_y = 0.2)) self.password = TextInput(password=True, multiline=False) # , size_hint_x = 0.2, size_hint_y = 0.2) self.GridlayoutS1.add_widget(self.password) self.BenutzerListe = {"": ""} self.add_widget( Button(text="Einloggen", size_hint_y=1 / 5, pos_hint={"top": 0.4}, on_release=self.AbfrageLogin) ) self.LabelLoginanzeiger = Label(size_hint_y=1 / 5) self.add_widget(self.LabelLoginanzeiger) def on_enter(self, instance): print ("User pressed enter in", instance) self.password.focus = True def AbfrageLogin(self, widget): Username = self.username.text Passwort = self.password.text if Username in self.BenutzerListe and Passwort == self.BenutzerListe[Username]: self.LabelLoginanzeiger.text = "Login korrekt" self.clear_widgets() self.HauptProgramm() else: self.LabelLoginanzeiger.text = "Login inkorrekt" def HauptProgramm(self, *args): print "das ist das Hauptprogramm" self.BilderListeVorlaeufer = [] self.BilderListeVorlaeufer = os.listdir(os.getcwd() + "/pictures") self.Pfade = [] for i in self.BilderListeVorlaeufer: Pfad = os.path.join("pictures", i) if os.path.isfile(Pfad) == True: self.Pfade.append(Pfad) self.HauptCarousel = Carousel(scroll_timeout=100) App.Pfade = self.Pfade self.add_widget(self.HauptCarousel) #################################################################################################### ### Erste Seite im HauptCarousel momentan mit den produktbildern self.HauptCarousel.FloatLayout = FloatLayout() self.HauptCarousel.add_widget(self.HauptCarousel.FloatLayout) self.HauptCarousel.FloatLayout.GridLayout = GridLayout(cols=3, pos_hint={"x": 0, "y": 0}, size_hint=[1, 0.9]) self.HauptCarousel.FloatLayout.add_widget(self.HauptCarousel.FloatLayout.GridLayout) for i in range(9): button = Button( background_normal=self.Pfade[i], background_down="bilder_oberflaeche/1361740537_Ball Green_mitHaken.png", mipmap=True, ) self.HauptCarousel.FloatLayout.GridLayout.add_widget(button) ## self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test')) ## self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test2')) ##################################################################################################### ### 2 Seite im Hauptcarousel mit testbutton zur datei Erstellung ### 2 Page in MainCarousel with testbutton for creating /exporting to a file self.HauptCarousel2 = BoxLayout(orientation="vertical") ###############self.HauptCarousel.add_widget(self.HauptCarousel2) self.HauptCarousel2.Texteingabe = TextInput(multiline=True) self.HauptCarousel2.add_widget(self.HauptCarousel2.Texteingabe) self.HauptCarousel2.ButtonSchreiben = Button(text="datei schreiben", on_release=self.datenpickeln) self.HauptCarousel2.add_widget(self.HauptCarousel2.ButtonSchreiben) ####################################################################### ### 3 Seite im Hauptcarousel momentan mit Datei Auslesefunktion ### 3 Page in MainCarousel atm with functionality to read from file self.HauptCarousel3 = BoxLayout(orientation="vertical") ######################self.HauptCarousel.add_widget(self.HauptCarousel3) self.HauptCarousel3.Textausgabe = TextInput(multiline=True, readonly=True) self.HauptCarousel3.add_widget(self.HauptCarousel3.Textausgabe) self.HauptCarousel3.ButtonLesen = Button(text="datei auslesen", on_release=self.datenentpickeln) self.HauptCarousel3.add_widget(self.HauptCarousel3.ButtonLesen) ####################################################################### ### 4 Seite im Hauptcarousel momentan mit Tischmanager ### 4 Page in Maincarousel atm with some kind of Table Manager BackgroundcolorListe = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)] self.CustomLayout = CustomLayout() self.HauptCarousel.add_widget(self.CustomLayout) # self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=#098125ff]Organizer[/sup][/b][/color]', markup = True, # halign= 'left', valign= 'top', text_size= self.size, pos_hint={'x':0, 'y': 0}, font_size= '30sp') self.CustomLayout.TopLabel = Label( text="Tisch[sup][color=#098125ff]Organizer[/sup][/b][/color]", markup=True, halign="left", font_size="30sp" ) # self.CustomLayout.add_widget(self.CustomLayout.TopLabel) self.CustomLayout.BoxLayout = BoxLayout( orientation="horizontal", size_hint=[1, 0.05], pos_hint={"x": 0, "y": 0.95} ) self.CustomLayout.add_widget(self.CustomLayout.BoxLayout) self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.TopLabel) ButtonMenu1 = self.DropdownbuttonCreator() self.CustomLayout.BoxLayout.Button1 = ButtonMenu1 ## self.CustomLayout.BoxLayout.Button2 = Button(text = 'Tisch+' , on_release = self.tischhinzufuegen) ## self.CustomLayout.BoxLayout.Button3 = Button(text = 'Spalte+', on_release = self.spaltehinzufuegen) ## self.CustomLayout.BoxLayout.Button4 = Button(text = 'Zeile+', on_release = self.zeilehinzufuegen) self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button1) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button2) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button3) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button4) self.CustomLayoutGridLayout = GridLayout( cols=3, rows=4, padding=[20, 20], spacing=[30, 30], size_hint=[1, 0.95], pos_hint={"x": 0, "y": 0} ) # cGridLayout = StackLayout(orientation = "tb-lr", padding = [20,20], spacing = [30,30], size_hint = [1,0.9], pos_hint={'x':0, 'y': 0}) self.CustomLayout.add_widget(self.CustomLayoutGridLayout) self.Tischliste = [] Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] AnzahlTische = 12 Zielwidget = self.CustomLayoutGridLayout self.tischerstellung(Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe) self.ProduktOrganizerInstanz = ProduktOrganizer() self.HauptCarousel.add_widget(self.ProduktOrganizerInstanz) ButtonHinzufuegen = self.ProduktOrganizerInstanz.ids.ProduktlisteButtonHinzufuegen ButtonHinzufuegen.on_release = self.produkthinzufuegen self.PopupInst = PopupBildAuswaehlenProduktorganizer() popup = self.PopupInst.ids.a self.ProduktOrganizerInstanz.ids.ProduktBildAuswaehlen.on_release = popup.open self.CustomScrollviewProduktOrganizer = CustomScrollviewProduktOrganizer self.CustomScrollviewProduktOrganizerInstanz = CustomScrollviewProduktOrganizer() self.ProduktOrganizerItemInstanz = CustomScrollviewItem() self.ProduktOrganizerInstanz.add_widget(Button(text="test", on_release=self.listeaktualisieren)) # self.ProduktOrganizerInstanz.ids.ProduktlisteButtonHinzufuegen.on_release = self.listeaktualisieren self.ProduktOrganizerInstanz.add_widget(Button(text="manuell", on_release=self.itemmanuellhinzufuegen)) self.ProduktOrganizerInstanz.add_widget(Button(text="listeaktualisiern+pos", on_release=self.positionenzeigen)) def itemmanuellhinzufuegen(self, widget): self.CustomScrollviewProduktOrganizerInstanz = CustomScrollviewProduktOrganizer() # print dir(self.CustomScrollviewProduktOrganizerInstanz.ids.content2.children) self.CustomScrollviewProduktOrganizerInstanz.ids.content2.clear_widgets() self.testButtonx = Button(text="testbutton", size_hint=(1, 1)) # self.CustomScrollviewProduktOrganizerInstanz.ids.content2.add_widget(self.testButtonx) # print dir(self.CustomScrollviewProduktOrganizerInstanz.ids) def positionenzeigen(self, widget): # print self.testButtonx.pos # print self.testButtonx.size self.listeaktualisieren(self) def listeaktualisieren(self, widget): # print 'listeacktualisieren wurde ausgefuert' # self.CustomScrollviewProduktOrganizer = CustomScrollviewProduktOrganizer() # print [str(i) for i in range(30)] # self.CustomScrollviewProduktOrganizerInstanz.data = ['0','1','2','3','4'] self.CustomScrollviewProduktOrganizerInstanz.data = [str(i) for i in App.HauptListeDictonaries] # print dir(self.CustomScrollviewProduktOrganizer.children)#content2.clear_widgets() def produkthinzufuegen(self): NeuesDict = {} WertEingabeFeldBezeichnung = self.ProduktOrganizerInstanz.ids.EingabeFeldBezeichnung.text WertEingabeFeldPreis = self.ProduktOrganizerInstanz.ids.EingabeFeldPreis.text ## StatusCheckBoxVerkauf = self.ProduktOrganizerInstanz.ids.CheckBoxVerkauf.active WertSpinnerKategorie = self.ProduktOrganizerInstanz.ids.SpinnerKategorie.text filechooser = self.PopupInst.ids.filechooser DateiAuswahl = (str(filechooser.selection))[((str(filechooser.selection)).find("/pictures")) : -2] # print 'hallo', WertEingabeFeldBezeichnung, WertEingabeFeldPreis,DateiAuswahl,WertSpinnerKategorie NeuesDict = { "Bezeichnung": WertEingabeFeldBezeichnung, "Preis": WertEingabeFeldPreis, "Bild": DateiAuswahl, "Kategorie": WertSpinnerKategorie, } # print 'len(App.HauptListeDictonaries)', (len(App.HauptListeDictonaries)) if len(App.HauptListeDictonaries) < 1: App.HauptListeDictonaries.append(NeuesDict) print "Fall 1" else: for i in range(len(App.HauptListeDictonaries[:])): print "App.HauptListeDictonaries[i][Bezeichnung] ist", App.HauptListeDictonaries[i]["Bezeichnung"] Bezeichnungdict = str(App.HauptListeDictonaries[i]["Bezeichnung"]) Bezeichnungneuesdict = str(NeuesDict["Bezeichnung"]) if Bezeichnungdict == Bezeichnungneuesdict: Treffer = True break else: Treffer = False if Treffer == True: # print 'Dieses Produkt existiert schon' ButtonVerstanden = Button(text="Verstanden") popup = Popup( title="Dieses Produkt existiert bereits ", size_hint=(0.5, 0.25), content=ButtonVerstanden ) popup.open() ButtonVerstanden.on_release = popup.dismiss else: App.HauptListeDictonaries.append(NeuesDict) print len(App.HauptListeDictonaries) for index, item in enumerate(App.HauptListeDictonaries): print index, item def DropdownbuttonCreator(self): Auswahlliste = ["Tisch +", "Tisch -", "Spalte + ", "Spalte -", "Reihe + ", "Reihe -"] BackgroundcolorListe = [(0, 1, 0, 1), (1, 0, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1)] Aktionsliste = [ self.tischhinzufuegen, self.tischentfernen, self.spaltehinzufuegen, self.spalteentfernen, self.zeilehinzufuegen, self.zeileentfernen, ] DropdownObjekt = CustomDropDown() DropdownObjektButton = CustomButton( text="Menue", # DropdownObjektButton = ToggleButton(text="Menue", size_hint=[1, 1], background_color=(0.8, 0.8, 0.00, 1), background_normal="bilder_oberflaeche/white2.png", background_down="bilder_oberflaeche/white3.png", ) # self.CustomLayout.add_widget(DropdownObjektButton) DropdownObjektButton.bind(on_release=DropdownObjekt.open) self.DropdownObjects.append(DropdownObjekt) for x in range(len(Auswahlliste)): DropdownUnterbutton = Button( text=Auswahlliste[x], font_size=15, size_hint_y=None, height=60, background_color=BackgroundcolorListe[x], background_normal="bilder_oberflaeche/white2.png", background_down="bilder_oberflaeche/white3.png", opacity=0.8, on_release=Aktionsliste[x], ) DropdownObjekt.add_widget(DropdownUnterbutton) ButtonMenu1 = DropdownObjektButton return ButtonMenu1 def tischerstellung(self, Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe): Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] BackgroundcolorListe = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)] Aktionsliste = [self.bestellung, self.abrechnung, self.bestellungaendern, self.tischbenennen] # self.DropdownObjects = [] for i in range(AnzahlTische): if self.Tischliste != []: LetzterTisch = self.Tischliste[-1]["Nummer"] ## print LetzterTisch + 1 else: LetzterTisch = 0 TischNr = str(LetzterTisch + 1) TischButtonText = "T " + TischNr DropdownObjekt = CustomDropDown() # von kovak hinzugefuegt # DropdownObjektButton = CustomButton(text = TischButtonText, DropdownObjektButton = ToggleButton( text=TischButtonText, group="Tische", background_normal="bilder_oberflaeche/white2.png", background_down="bilder_oberflaeche/white4.png", background_color=(0.79, 0.39, 0.09, 0.6), ) Zielwidget.add_widget(DropdownObjektButton) DropdownObjektButton.bind(on_release=DropdownObjekt.open) self.DropdownObjects.append(DropdownObjekt) # von kovak hinzugefuegt for x in range(len(Auswahlliste)): DropdownUnterbutton = Button( text=Auswahlliste[x], id=TischNr, # auto_width='False', # width = '200sp', font_size=15, size_hint_y=None, height=60, background_normal="bilder_oberflaeche/white2.png", background_down="bilder_oberflaeche/white3.png", background_color=BackgroundcolorListe[x], on_release=Aktionsliste[x], ) DropdownObjekt.add_widget(DropdownUnterbutton) # print' button', i, 'unterbutton', x DropdownObjektButton.text = TischButtonText self.TischButtondict = {"Nummer": (LetzterTisch + 1), "Objekt": DropdownObjektButton} self.Tischliste.append(self.TischButtondict) def garbagecollectortracking(self, widget): for i in self.Tischliste: a = i print gc.is_tracked(a) ### function for Editing a Table####################################### # def tischmanipulieren(self, widget): # widget.text = 'mein text' #### function for adding an extra table to layout ########################## def tischhinzufuegen(self, widget): if len(self.Tischliste) >= 1: if hasattr(self, "CustomLayoutBottomLabel"): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) AnzahlTische = 1 Zielwidget = self.CustomLayoutGridLayout Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] BackgroundcolorListe = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)] LetzterTisch = self.Tischliste[-1]["Nummer"] if (self.CustomLayoutGridLayout.cols * self.CustomLayoutGridLayout.rows) <= (LetzterTisch + 1): self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1 self.tischerstellung(Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe) def tischentfernen(self, widget): self.Warnlabel = 0 if len(self.Tischliste) <= 1: if hasattr(self, "CustomLayoutBottomLabel"): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel = 1 print "das ist der Letzte Tisch, der kann nicht entfernt werden" if self.Warnlabel == 0: self.CustomLayoutBottomLabel = Label( text="Das ist der Letzte Tisch,\n der kann nicht \n entfernt werden", text_size=self.size ) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: Zielwidget = self.CustomLayoutGridLayout Zielwidget.remove_widget(self.Tischliste[-1]["Objekt"]) del self.Tischliste[-1] LetzterTisch = self.Tischliste[-1]["Nummer"] print "die anzahl der Tische ist nun:", LetzterTisch pass #### function for adding a column to layout #################################### def spaltehinzufuegen(self, widget): if self.CustomLayoutGridLayout.cols >= 1: if hasattr(self, "CustomLayoutBottomLabel"): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) self.WarnLabel = 0 self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols + 1 print "Zeile hinzufuegen" def spalteentfernen(self, widget): self.Warnlabel = 0 if self.CustomLayoutGridLayout.cols <= 1: if hasattr(self, "CustomLayoutBottomLabel"): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel = 1 print "das ist die letzte Tischreihe, sie kann nicht entfernt werden" if self.Warnlabel == 0: self.CustomLayoutBottomLabel = Label( text="Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden", text_size=self.size ) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: TischanzahlVerbleibend = (self.CustomLayoutGridLayout.cols - 1) * self.CustomLayoutGridLayout.rows for i in range(len(self.Tischliste[TischanzahlVerbleibend:])): self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend + i]["Objekt"]) del self.Tischliste[TischanzahlVerbleibend:] self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols - 1 #### function for adding a row to layout #################################### def zeilehinzufuegen(self, widget): if self.CustomLayoutGridLayout.rows >= 1: if hasattr(self, "CustomLayoutBottomLabel"): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) self.WarnLabel = 0 self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1 print "Zeile hinzufuegen" def zeileentfernen(self, widget): self.Warnlabel = 0 if self.CustomLayoutGridLayout.rows <= 1: if hasattr(self, "CustomLayoutBottomLabel"): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel = 1 print "das ist die letzte Tischreihe, sie kann nicht entfernt werden" if self.Warnlabel == 0: self.CustomLayoutBottomLabel = Label( text="Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden", text_size=self.size ) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: TischanzahlVerbleibend = (self.CustomLayoutGridLayout.rows - 1) * self.CustomLayoutGridLayout.cols for i in range(len(self.Tischliste[TischanzahlVerbleibend:])): self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend + i]["Objekt"]) del self.Tischliste[TischanzahlVerbleibend:] self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows - 1 def bestellung(self, widget): TischNr = widget.id PopupFloatLayout = FloatLayout(size_hint=(1, 1)) self.PopupScrollview = CustomScrollviewPopupContent() self.PopupScrollviewItem = CustomButton2() self.PopupScrollview.data = [str(i) for i in range(10)] # content = self.PopupScrollview.ids.content # item = self.PopupScrollviewItem popup = Popup(title="Bestellung für Tisch " + str(TischNr), content=PopupFloatLayout) ## for i in range(9): ## content.add_widget(CustomButton(text = str(i))) # self.PopupScrollview.ids.CSPopup.open() # print dir(CustomScrollviewPopupContent.data) ButtonExit = Button( text="Exit", pos_hint={"x": 0.825, "y": 1.005}, size_hint=[0.2, 0.065], on_release=popup.dismiss ) PopupFloatLayout.add_widget(ButtonExit) self.PopupScrollview.size_hint = [1.05, 1.017] self.PopupScrollview.center = popup.center PopupFloatLayout.add_widget(self.PopupScrollview) self.PopupScrollview.ids.populate.on_release = self.kasse popup.open() ## ## def on_data(self, instance, value): ## content_add = self.PopupScrollview.ids.content.add_widget ## for item in value: ## print item ## content_add(CustomButton2(text=item)) # return CustomScrollviewPopupContent() def kasse(self): self.PopupScrollview.data = [str(i) for i in range(30)] # print dir(CustomScrollviewPopupContent().ids.viewitems) # y.ids.content.clear_widgets() ## x.data = ListProperty([str(i) for i in range(10)]) ## print 'x.data', x.data ## ## print CustomScrollviewPopupContent.data ## CustomScrollviewPopupContent.data = x.data ## print '2ens', CustomScrollviewPopupContent.data def groesse(self, widget): print "die buttongroesse ist:", widget.size def abrechnung(self, widget): TischNr = widget.id PopupFloatLayout = FloatLayout() self.ScreenmanagerPopup = CustomScreenManager() self.ScreenPopup = CustomScreen for x in xrange(4): self.ScreenmanagerPopup.add_widget(self.ScreenPopup(name="Screen %d" % x)) # popup = Popup(title='Abrechnung für ' + str(TischNr), # content=self.ScreenmanagerPopup,size_hint=(1, 1) ) popup = Popup(title="Abrechnung für Tisch" + str(TischNr), content=PopupFloatLayout) # , # size_hint=(1, 1), # pos_hint={'x': 0.5, 'y': 0.5} ) self.ScreenmanagerPopup.pos_hint = {"x": 0, "y": 0} PopupFloatLayout.add_widget(self.ScreenmanagerPopup) ButtonExit = Button( text="Exit", pos_hint={"x": 0.8, "y": 1.005}, size_hint=[0.2, 0.065], on_release=popup.dismiss ) PopupFloatLayout.add_widget(ButtonExit) popup.open() def bestellungaendern(self, widget): pass def tischbenennen(self, widget): TischNr = widget.id PopupBox1LayoutTischBennenen = BoxLayout(orientation="vertical") popup = Popup( title="Tisch Nr. " + str(TischNr) + "benennen", content=PopupBox1LayoutTischBennenen, size_hint=(0.75, 0.5) ) EingabeTextfeld = TextInput(text="hier Tischbezeichnung eintragen - Funktion muss noch eingebaut werden") PopupBox1LayoutTischBennenen.add_widget(EingabeTextfeld) PopupBoxLayoutTischBenennen = BoxLayout(orientation="horizontal", size_hint=(1, 1)) ButtonAbbrechenTischBenennen = Button(text="Abbrechen", size_hint=(0.5, 0.5)) ButtonAbbrechenTischBenennen.bind(on_press=popup.dismiss) ButtonOkTischBenennen = Button(text="OK", size_hint=(0.5, 0.5)) ButtonOkTischBenennen.bind(on_press=popup.dismiss) PopupBox1LayoutTischBennenen.add_widget(PopupBoxLayoutTischBenennen) PopupBoxLayoutTischBenennen.add_widget(ButtonAbbrechenTischBenennen) PopupBoxLayoutTischBenennen.add_widget(ButtonOkTischBenennen) # popup.add_widget popup.open() pass #### function for exporting Data to file #################################### def datenpickeln(self, widget): BonListe = self.HauptCarousel2.Texteingabe.text """function to pickle data to make it ready for sending""" try: with open("bonliste.txt", "w+b") as BonListeDaten_File: pickle.dump(BonListe, BonListeDaten_File) except IOError as err: print ("Dateifehler: " + str(err)) except pickle.PickleError as perr: print ("Pickling Fehler: " + str(perr)) #### function for importing Data to file #################################### def datenentpickeln(self, widget): with open("bonliste.txt", "rb") as BonListeDaten_File_entpickelt: BonListeWiederhergestellt = pickle.load(BonListeDaten_File_entpickelt) print "die entpickelte BinListe ist: " print BonListeWiederhergestellt BonListe = BonListeWiederhergestellt self.HauptCarousel3.Textausgabe.text = BonListe
class SuperControllerGUI(BoxLayout): def __init__(self, root_class): super(SuperControllerGUI, self).__init__(orientation='vertical') self.add_button = Button(text='Add New Rutine', size_hint=(1,None), size=(1,40)) self.add_button.bind(on_press=self.add_routine) self.ok_button = Button(text='OK', size_hint=(1, None), size=(1, 40)) self.ok_button.bind(on_press=self.ok_opoup) self.cancel_button = Button(text='Cancel', size_hint=(1, None), size=(1, 40)) self.cancel_button.bind(on_press=self.close_opoup) self.path_container = GridLayout(cols=1, spacing=0, size_hint_y=None) # row_default_height=30) self.path_container.bind(minimum_height=self.path_container.setter('height')) scroll_root = ScrollView(size_hint=(1, 1)) scroll_root.add_widget(self.path_container) self.buttons_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,40)) self.buttons_layout.add_widget(self.ok_button) self.buttons_layout.add_widget(self.cancel_button) self.add_widget(self.add_button) self.add_widget(scroll_root) self.add_widget(self.buttons_layout) self.config_path = {} self.config_cont = 0 self.control_gui = root_class def add_popup(self, opopup): self.popup = opopup def close_opoup(self, instance): self.popup.dismiss() def add_routine(self, instance): file_dir = os.path.dirname(os.path.realpath(__file__)) file_dir = file_dir.replace('super_controller','extract_data_panel/alternatives/roach_configurations') fc_conf = BofFileChooserIconView(self.load_data, path=file_dir, filter=['*.pkl']) self.file_roch_popup = Popup(title='Choose Configuration', auto_dismiss=False, content=fc_conf, \ size_hint=(None, None), size=(400, 400)) fc_conf.set_popup(self.file_roch_popup) self.file_roch_popup.open() def load_data(self, path): self.config_path[str(self.config_cont)] = path name= path.split('/')[-2] path_button = Button(text=name, size_hint=(1, None), size=(1, 40)) key = self.config_cont path_button.bind(on_press=lambda instance: self.del_path(str(key), path_button)) self.config_cont += 1 self.path_container.add_widget(path_button) def del_path(self, key, button): del self.config_path[key] self.path_container.remove_widget(button) def ok_opoup(self, instance): self.control_gui.configure_super_controller(self.config_path) self.popup.dismiss()
class Material_Editor(GridLayout, IObserver): ''' the material-edit is the component, where the user can see the materials and create new material with the material-creater ''' # important components cs = ObjectProperty() creater=ObjectProperty() concrete = StringProperty('concrete') densityStr = StringProperty('density[kg/m^3]:') stiffnessStr = StringProperty('stiffness[MPa]:') priceStr = StringProperty('price[euro/kg]:') strengthStr = StringProperty('strength[MPa]:') nameStr = StringProperty('name') defaultValueStr = StringProperty('1.0') createStr = StringProperty('create material') materialStr = StringProperty('material') backStr = StringProperty('cancel') confirmStr = StringProperty('confirm') # constructor def __init__(self, **kwargs): super(Material_Editor, self).__init__(**kwargs) self.cols = 1 self.h = dp(40) # height of the btns self.creater=MaterialCreater(p=self) ''' the method create gui create the gui of the material_editor and create the popups ''' def create_gui(self): self.create_material_information() self.materialLayout = GridLayout(cols=1, spacing=Design.spacing, size_hint_y=None) self.materialLayout.padding = Design.padding # Make sure the height is such that there is something to scroll. self.materialLayout.bind(minimum_height=self.materialLayout.setter('height')) for i in self.allMaterials.allMaterials: btn = OwnButton(text=i.name) btn.height = self.h btn.bind(on_press=self.show_material_information) self.materialLayout.add_widget(btn) self.btnMaterialEditor = OwnButton(text=self.createStr) self.btnMaterialEditor.height = self.h self.btnMaterialEditor.bind(on_press=self.create_material) self.materialLayout.add_widget(self.btnMaterialEditor) scrollView = ScrollView() scrollView.add_widget(self.materialLayout) self.add_widget(scrollView) ''' popupInfo to show the material information popupCreate to create new material ''' def create_popups(self): self.numpad, self.keyboard = Numpad(), Keyboard() self.numpad.p, self.keyboard.p = self, self self.editNumpad = OwnPopup(content=self.numpad) self.editKeyboard = OwnPopup(title=self.nameStr, content=self.keyboard) self.popupInfo = OwnPopup(title=self.materialStr, content=self.contentLayout) self.popupCreate = OwnPopup(title=self.createStr, content=self.creater) ''' create the gui which is necessary for the show of the material-information ''' def create_material_information(self): # create the btns to edit the values or the name self.btnName, self.btnPrice = OwnButton(), OwnButton() self.btnDensity, self.btnStiffness = OwnButton(), OwnButton() self.btnStrenght = OwnButton() # bind the values to the methods show_numpad and show_keyboard self.btnName.bind(on_press=self.show_keyboard) self.btnPrice.bind(on_press=self.show_numpad) self.btnDensity.bind(on_press=self.show_numpad) self.btnStiffness.bind(on_press=self.show_numpad) self.btnStrenght.bind(on_press=self.show_numpad) # fill the contentLayout with the components self.contentLayout = GridLayout(cols=2, row_force_default=True, row_default_height=Design.btnHeight, height=Design.btnHeight, spacing=Design.spacing) self.contentLayout.add_widget(OwnLabel(text=self.nameStr)) self.contentLayout.add_widget(self.btnName) self.contentLayout.add_widget(OwnLabel(text=self.priceStr)) self.contentLayout.add_widget(self.btnPrice) self.contentLayout.add_widget(OwnLabel(text=self.densityStr)) self.contentLayout.add_widget(self.btnDensity) self.contentLayout.add_widget(OwnLabel(text=self.stiffnessStr)) self.contentLayout.add_widget(self.btnStiffness) self.contentLayout.add_widget(OwnLabel(text=self.strengthStr)) self.contentLayout.add_widget(self.btnStrenght) # btn_back=go back to the materials-view btn_back = OwnButton(text=self.backStr) btn_back.bind(on_press=self.cancel_show) # edit the new values btn_confirm = OwnButton(text=self.confirmStr) btn_confirm.bind(on_press=self.edit_material) self.contentLayout.add_widget(btn_confirm) self.contentLayout.add_widget(btn_back) self.create_popups() ''' set the labeltext with the materialproperties ''' def show_material_information(self, button): for i in range(0, len(self.cs.allMaterials.allMaterials)): material = self.allMaterials.allMaterials[i] if material.name == button.text: self.focusMaterial = material self.btnName.text = material.name self.btnPrice.text = str(material.price) self.btnDensity.text = str(material.density) self.btnStiffness.text = str(material.stiffness) self.btnStrenght.text = str(material.strength) self.popupInfo.title = material.name self.popupInfo.open() ''' close the popup, which shows the information from the choosen material ''' def cancel_show(self, button): self.popupInfo.dismiss() ''' open the popup, which has the creator as contentLayout ''' def create_material(self, button): self.popupCreate.open() ''' the method update_materials update the view of the materials. its make sure that the create material button is the last component of the gridlayout ''' def update(self): self.materialLayout.remove_widget(self.btnMaterialEditor) btn_material_A = OwnButton(text=self.allMaterials.allMaterials[-1].name) btn_material_A.height = self.h btn_material_A.bind(on_press=self.show_material_information) self.materialLayout.add_widget(btn_material_A) self.materialLayout.add_widget(self.btnMaterialEditor) ''' cancel the create-process. this method is necessary, because editor is the parent of the creator and creator call the method cancel_edit_material from the parent ''' def cancel_edit_material(self): self.popupCreate.dismiss() ''' the method set_cross_section was developed to say the view, which cross section should it use ''' def set_cross_section(self, cs): self.cs = cs self.allMaterials = self.cs.allMaterials self.allMaterials.add_listener(self) self.create_gui() ''' edit the selected material by the new values ''' def edit_material(self, btn): self.popupInfo.dismiss() self.focusMaterial.name = self.btnName.text self.focusMaterial.density = float(self.btnDensity.text) self.focusMaterial.price = float(self.btnPrice.text) self.focusMaterial.stiffness = float(self.btnStiffness.text) self.focusMaterial.strength = float(self.btnStrenght.text) if self.focusMaterial.name == self.concrete: self.cs.update_concrete_information(self.focusMaterial.density, self.focusMaterial.price, self.focusMaterial.stiffness, self.focusMaterial.strength) self.cs.update_informations() ''' open the popup to edit the value of the material ''' def show_numpad(self, btn): self.focusBtn = btn self.numpad.lblTextinput.text = btn.text if self.focusBtn == self.btnDensity: self.editNumpad.title = self.densityStr elif self.focusBtn == self.btnPrice: self.editNumpad.title = self.priceStr elif self.focusBtn == self.btnStrenght: self.editNumpad.title = self.strengthStr elif self.focusBtn == self.btnStiffness: self.editNumpad.title = self.stiffnessStr self.editNumpad.open() ''' open the popup to edit the name of the material ''' def show_keyboard(self, btn): self.focusBtn = btn self.keyboard.lblTextinput.text = btn.text self.editKeyboard.open() ''' finished the name-input and the set the text of the btnName ''' def finished_keyboard(self): self.focusBtn.text = self.keyboard.lblTextinput.text self.editKeyboard.dismiss() ''' finished the value-input and set the text of the focusbtn to the value ''' def finished_numpad(self): self.focusBtn.text = self.numpad.lblTextinput.text self.editNumpad.dismiss() ''' close the numpad and change nothing ''' def close_numpad(self): self.editNumpad.dismiss()
class ChristofidesApp(App): def nextFrame(self, *args): #print("call") if (self.flag == True and self.once == False): print(len(self.Grapha.curPos)) self.once = True self.next() global graphicsLineInd, graphicsLine, graphicsTriangleInd, graphicsTriangle if (graphicsLineInd > len(graphicsLine) - 1): if (graphicsTriangleInd > len(graphicsTriangle) - 1): return else: with self.layout.canvas: Color(rgb=(0, 0, 1)) Ellipse(segments=3, pos=graphicsTriangle[graphicsTriangleInd][1], size=(d * 1.5, d * 1.5)) graphicsTriangleInd += 1 return if (graphicsLine[graphicsLineInd][0] == (.20, .72, .11)): self.speed = 0.7 with self.layout.canvas: Color(rgb=graphicsLine[graphicsLineInd][0]) Line(points=graphicsLine[graphicsLineInd][1], width=graphicsLine[graphicsLineInd][2]) graphicsLineInd += 1 def build(self): self.once = False self.flag = False self.layout = GridLayout(cols=2) Window.clearcolor = (1, 1, 1, 1) self.speed = 0.03 self.partition() self.painter = getGraph() self.doneButton = Button(text="DONE") self.doneButton.bind(on_release=self.done) self.text = customLabel("Select Points on Left Block") self.layout.add_widget(self.painter) self.layout.add_widget(self.text) self.layout.add_widget(self.doneButton) Clock.schedule_interval(self.nextFrame, self.speed) return self.layout def partition(self): with self.layout.canvas: Color(rgba=(0, 0, 0, 1)) Line(points=[ 0, Window.size[1] / 2, Window.size[0], Window.size[1] / 2 ], width=2) Line(points=[ Window.size[0] / 2, 0, Window.size[0] / 2, Window.size[1] ], width=2) def done(self, obj): self.flag = True self.painter.canvas.clear() self.layout.remove_widget(self.doneButton) self.layout.remove_widget(self.painter) self.layout.remove_widget(self.text) self.Grapha = makeGraph() self.Graphb = makeGraph() self.Graphc = makeGraph() self.Graphd = makeGraph() self.layout.add_widget( Button(text="Minimum Spanning Tree", size_hint=(1, 0.04))) self.layout.add_widget( Button(text="Induced Subgraph", size_hint=(1, 0.04))) self.layout.add_widget(self.Grapha) self.layout.add_widget(self.Graphb) self.layout.add_widget( Button(text="Perfect Matching", size_hint=(1, 0.04))) self.layout.add_widget( Button(text="Hamiltonian Circuit", size_hint=(1, 0.04))) self.layout.add_widget(self.Graphc) self.layout.add_widget(self.Graphd) self.t1 = Clock.schedule_once(self.Grapha.getPos) self.t2 = Clock.schedule_once(self.Graphb.getPos) self.t3 = Clock.schedule_once(self.Graphc.getPos) self.t4 = Clock.schedule_once(self.Graphd.getPos) Clock.tick() def next(self): self.Grapha.draw() self.Graphb.draw() self.Graphc.draw() self.Graphd.draw() self.Grapha.makeEdges() Adjacent = graph(Subst) Adjacent.initEdges() Spanning = spantheTree(Adjacent) Matching = Spanning.solve() self.Grapha.draw() MST = subgraphInduced(Matching) MST.toDraw() MST.Matching() Union = MST.union() Cycle = EulerianCycle(Union).getCycles() DrawEvery = Draw() DrawEvery.drawEdges(Union) DrawEvery.DrawEuler(Cycle)
class LoadDynamic(Empty): def __init__(self, **kwargs): super(LoadDynamic, self).__init__(kwargs=kwargs) self.path_modules_and_xml = os.path.dirname(__file__) .replace\ ('/gui/data_processing_panel/alternatives','/controller/procesing/dynamic_modules') self.function_dictionary = self.load_xml() self.add_function = Button(text="add new") self.add_function.bind(on_press=self.create_function) self.import_function = Button(text='import function') self.import_function.bind(on_press=self.copy_function) top_layot = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30)) top_layot.add_widget(self.import_function) top_layot.add_widget(self.add_function) #### self.func_container = GridLayout(cols=1, spacing=0, size_hint_y=None)#row_default_height=30) self.func_container.bind(minimum_height=self.func_container.setter('height')) scroll_root = ScrollView(size_hint=(1,1), size=(1, 125)) scroll_root.add_widget(self.func_container) ### padding_layout = BoxLayout(size_hint=(1,1)) big_one = BoxLayout(orientation='vertical') big_one.add_widget(top_layot) big_one.add_widget(scroll_root) #big_one.add_widget(padding_layout) self.add_widget(big_one) self.modules_function_loaded = {} self.free_run_variable_dictionary = {} def load_xml(self): FILE = open(self.path_modules_and_xml + "/setup.xml", 'r') modules = xmlfromstring(FILE.read()) dic_return = {} for module in modules._children: module_name = module.attrib['name'] module_dict = {} for functions in module._children: function_name = functions.attrib['name'] args_name = [] for args in functions._children: args_name.append(args.attrib['name']) module_dict[function_name] = args_name dic_return[module_name] = module_dict return dic_return def create_function(self, instance): function_list = self.get_function_list() threading.Thread(target=self.create_function_thread, args=(function_list,)).start() def create_function_thread(self, function_list): content = FunctionSelector( function_list) a_popup = Popup(title='Choose Bof', auto_dismiss=False, content=content, size_hint=(None, None), size=(400,400)) content.set_popup(a_popup) a_popup.open() while content.continues: pass keys = content.choosen_name.split('.') if content.is_default(): return new_widget = FunctionGui( keys[0],keys[1],self.function_dictionary[keys[0]][keys[1]], self.delete_one_function) new_widget.update_free_run_dictionary(self.free_run_variable_dictionary) self.func_container.add_widget(new_widget) if not new_widget.module_name in self.modules_function_loaded: self.modules_function_loaded[new_widget.module_name] = {} self.modules_function_loaded[new_widget.module_name][new_widget.function_name + new_widget.special_name] = new_widget #self.func_container.add_widget(Button(text=content.choosen_name + ' ' + str(self.function_dictionary[keys[0]][keys[1]]),size_hint=(1,None), size=(1,30))) def delete_one_function(self, module_name, function_name): print self.modules_function_loaded module_dic = self.modules_function_loaded[module_name] del_function = module_dic[function_name] del module_dic[function_name] self.func_container.remove_widget(del_function) print self.modules_function_loaded def get_function_list(self): function_list_return = [] for module in self.function_dictionary: module_dic = self.function_dictionary[module] for function in module_dic: function_list_return.append(module + '.' + function) return function_list_return def copy_function(self, instance): content = BofFileChooserIconView(return_selection_path=self.copy_function_copy_file ) a_popup = Popup(title='Choose Bof', auto_dismiss=False, content=content, size_hint=(None, None), size=(400,400)) content.set_popup(a_popup) a_popup.open() def copy_function_copy_file(self, path): module_name = path.split("/")[-1] module_name = str(module_name.replace('.py','')) print 'name',module_name, type(module_name) command = "cp %s %s" %(path, self.path_modules_and_xml) print command os.system(command) try: dynamic_module = __import__('omt.controller.procesing.dynamic_modules' , globals(), locals(), [module_name,],-1) dynamic_module = getattr(dynamic_module, module_name) posible_fucntion_list = dir(dynamic_module) except Exception as e: Popup(title='Import Error',content=Label(text=e.msg + '\nline ' + str(e.lineno)), size_hint=(None,None), size=(500,300)).open() return actual_functions = [] #extract the created function for a_funtion in posible_fucntion_list: function_aux = getattr(dynamic_module,a_funtion) if types.FunctionType == type(function_aux) and a_funtion.replace('__','',1) == a_funtion: actual_functions.append(a_funtion) print actual_functions module_function_list = {} for a_function in actual_functions: funct_reference = getattr(dynamic_module, a_function) #function_dic['args_name'] = funct_reference.__code__.co_varnames module_function_list[a_function] = funct_reference.__code__.co_varnames[:funct_reference.__code__.co_argcount] #module_function_list[a_function + "_instance"] = funct_reference if not module_name in self.function_dictionary: print 'add info to dic' self.function_dictionary[module_name] = module_function_list else: Popup(title='Module Error', content=Label(text="Repeated module name,\nplease change yours")\ , size_hint=(None, None), size=(200,200)).open() return print self.function_dictionary self.save_xml() def save_xml(self, ): module_dict_xml = Element('dynamic_modules') comment = Comment('Modules info') module_dict_xml.append(comment) for aKey in self.function_dictionary: module_dic = self.function_dictionary[aKey] module_xml = SubElement(module_dict_xml,'module',attrib={'name':aKey}) for aFunctionKey in module_dic: aFunction = module_dic[aFunctionKey] function_xml = SubElement(module_xml,'function', name=aFunctionKey) for args in aFunction: arg_xml = SubElement(function_xml,'arg', name=args) rough_string = xmltostring(module_dict_xml, 'utf-8') reparsed = minidom.parseString(rough_string) string_xml = reparsed.toprettyxml(indent=" ") FILE = open(self.path_modules_and_xml + "/setup.xml", "w") FILE.write(string_xml) FILE.close() def update_free_run_dictionary(self, data_dic): self.free_run_variable_dictionary = data_dic for m_key in self.modules_function_loaded: module_dic = self.modules_function_loaded[m_key] for f_key in module_dic: function = module_dic[f_key] function.update_free_run_dictionary(data_dic) def get_source_config(self): return_dic = {} for element in self.modules_function_loaded: module = self.modules_function_loaded[element] for key in module: widget = module[key] return_dic[widget.special_name] = widget.get_source_config() return return_dic def sava_config_dictionary(self): return_dic = {} for element in self.modules_function_loaded: module = self.modules_function_loaded[element] for key in module: widget = module[key] dic = widget.get_source_config() return_dic[dic['function_name_special']] = dic return return_dic def set_configuration(self, dic): self.modules_function_loaded = {} self.func_container.clear_widgets() for func in dic: func_dic = dic[func] func_module = func_dic['module_name'] func_name = func_dic['function_name'] new_widget = FunctionGui( func_module,func_name,self.function_dictionary[func_module][func_name], self.delete_one_function) new_widget.update_free_run_dictionary(self.free_run_variable_dictionary) self.func_container.add_widget(new_widget) if not new_widget.module_name in self.modules_function_loaded: self.modules_function_loaded[new_widget.module_name] = {} self.modules_function_loaded[new_widget.module_name][new_widget.function_name + new_widget.special_name] = new_widget new_widget.set_configuration(func_dic)
class MyApp(App): def build(self): ############## ############### thread.start() ############## ############## ## # Initialise the characters to be selected ## self.current_string = 'SELECT_CHARS' self.string_array = [] self.initialise_string_array(self.current_string) ############## # Add text input widget ############## self.text_input = TextInput( hint_text="Enter character string for selection.") self.text_submit_button = Button(text='Submit new code', on_press=self.process_text_input) self.text_layout = GridLayout(rows=1, size_hint_y=0.1) self.text_layout.add_widget(self.text_input) self.text_layout.add_widget(self.text_submit_button) ##### # Create initial character selection ##### self.char_buttons = self.generate_char_buttons(self.current_string) ###### # Stick it all together ###### self.layout = GridLayout(cols=1) self.layout.add_widget(self.text_layout) # self.layout.add_widget(self.character_select_layout) self.layout.add_widget(self.char_buttons) # return self.character_select_layout return self.layout def initialise_string_array(self, string): self.string_array = [] for letter in string: self.string_array.append(0) print(self.string_array) def generate_char_buttons(self, string): self.character_select_layout2 = GridLayout(rows=1) self.widgets2 = {} i = 0 for letter in string: self.widgets2[i] = (ToggleButton(text=letter.upper())) self.widgets2[i].bind( on_press=partial(self.letter_select, position=i)) # self.character_select_layout.add_widget(ToggleButton(text=letter)) self.character_select_layout2.add_widget(self.widgets2[i]) i += 1 self.character_select_layout2.add_widget( Button(text='Process', on_press=self.process)) return self.character_select_layout2 def letter_select(self, instance, position=None): print('button was pressed!') if not position == None: print('it was button ', position) if self.string_array[position] == 0: self.string_array[position] = 1 else: self.string_array[position] = 0 print(self.string_array) def enter_input_text_via_serial(self, received_string): self.text_input.text = received_string print('setting text!') def process_text_input(self, instance): print('text input button pressed!') print(self.text_input.text) text_input_text = self.text_input.text if len(text_input_text) > 3: self.current_string = text_input_text self.initialise_string_array(text_input_text) self.update_char_select(text_input_text) else: print('ERROR! ENTER MORE THAN 3 CHARACTERS') def update_char_select(self, new_char_string): self.layout.remove_widget(self.char_buttons) self.char_buttons = self.generate_char_buttons(new_char_string) self.layout.add_widget(self.char_buttons) def process(self, instance): print('process button was pressed!') end = False new_preset = '' i = 0 if 1 in self.string_array: for position in self.string_array: if not end: if position == 0: new_preset += '?' else: end = True new_preset += self.current_string[i] print(position) else: if not position == 0: new_preset += self.current_string[i] else: new_preset += '!' break i += 1 print(new_preset) print('WP,402,' + bytes.hex(new_preset.encode())) preset_command = 'WP,402,' + bytes.hex(new_preset.encode()) + '\r' sock.sendall(preset_command.encode('utf-8')) print('Preset sent!') else: print('not ready to process')
class ResultsScreen(Screen): def __init__(self, **kwargs): super(ResultsScreen, self).__init__(**kwargs) self.layout = GridLayout() self.layout.rows = 5 self.cols = 1 self.layout.padding = (200, 0, 200, 100) self.layout.spacing = [20, 10] # Initiliaze scores self.score = 0 # Initilaise the current player self.playing_username = None self.rank = None self.total_players = None self.layout.add_widget( Label(text='Quiz complete', font_size=50, size_hint=(1, 1))) self.score_label = Label(text="", font_size=40) self.layout.add_widget(self.score_label) # self.layout.add_widget( # Label(text='Personal Best 345 points! Congrats !!', font_size=35)) # self.layout.add_widget( # Label(text='Correct on first attempt is 9/10', font_size=25)) self.user_name_input = TextInput( text="Enter your username (enter when done)!", multiline=False) self.layout.add_widget(self.user_name_input) self.leader_board_label = Label(font_size=25) # Add the leader_board label once the user hits enter on the user_name field self.user_name_input.bind(on_text_validate=self.user_name_entered) self.restart = Button(text='Restart') self.restart.bind(on_press=self.handle_restart) self.layout.add_widget(self.restart) # Add the above layout to this screen self.add_widget(self.layout) def handle_restart(self, press): # print(f"Press {press}") # Go back to the initial screen self.manager.current = 'home_screen' def on_enter(self, ): # print(f"The current score :> {self.score}") self.score_label.text = f"Score is {self.score}/ {self.quiz_length}" # Update the leaderboard stats self.total_players = self.get_total_players(self.category) self.rank = self.get_rank(self.playing_username, self.category) if self.rank == 0: self.rank = self.total_players self.leader_board_label.text = f""" Hey {self.playing_username} ! Your rank on the leaderboard is {self.rank} out of {self.total_players}""" def get_rank(self, user_name, category): rank = 0 cursor = connection.cursor() sql = """SELECT *, RANK() OVER (ORDER BY score DESC) output_rank FROM leaderboard WHERE Category = ? ;""" params = (category, ) cursor.execute(sql, params) results = [dict(row) for row in cursor.fetchall()] for raw_rank in results: if raw_rank.get('username') == user_name: rank = raw_rank.get('output_rank') return rank def get_total_players(self, category): cursor = connection.cursor() sql = 'SELECT COUNT(*) AS total FROM leaderboard WHERE Category = ?;' params = (category, ) cursor.execute(sql, params) results = [dict(row) for row in cursor.fetchall()] return results[0].get('total') def update_user_leaderboard_score(self, user_name, category, new_score): cursor = connection.cursor() sql = 'SELECT * FROM leaderboard WHERE username = ? AND Category = ?;' params = (user_name, category) cursor.execute(sql, params) results = [dict(row) for row in cursor.fetchall()] current_score = results[0].get('score') if new_score > current_score: sql = 'UPDATE leaderboard SET score = ? WHERE username = ? AND Category = ?;' params = (new_score, user_name, self.category) cursor.execute(sql, params) def user_name_entered(self, user_name_input_event): try: # print( f"{user_name_input_event}, Current player is {self.playing_username}") user_name = user_name_input_event.text rank = self.get_rank(user_name, self.category) self.total_players = self.get_total_players(self.category) if self.total_players == 0: self.total_players = 1 # First player on this category # print( f"Current rank is {rank}, and total players are {self.total_players}") if not rank: # First time for this user cursor = connection.cursor() sql = "INSERT INTO leaderboard (username, score, category) VALUES (?, ?, ?);" params = (user_name, self.score, self.category) cursor.execute(sql, params) self.rank = self.total_players else: # This is a returning player update the score # print(f"New score is {self.score}") self.update_user_leaderboard_score(user_name, self.category, self.score) # refresh rank self.rank = self.get_rank(user_name, self.category) # Delete the current user_name input self.layout.remove_widget(self.user_name_input) # If the app is not stopped, continue using the current username self.playing_username = user_name # Add the leaderboard label self.leader_board_label.text = f""" Hey {self.playing_username} ! Your rank on the leaderboard is {self.rank} out of {self.total_players}""" self.layout.add_widget(self.leader_board_label) # Commit current transactions connection.commit() except Exception as e: print(f"Error {e}")
class Authentication_Page(GridLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.output_path = 'Output/' self.flag = 0 self.cols = 2 self.padding = [100, 100, 100, 100] self.spacing = [20, 20] self.begin = Button(text='BEGIN', font_size=30, italic=True, background_color=[1, 255, 1, 1]) self.begin.bind(on_press=self.start) self.add_widget(self.begin) self.back = Button(text='GO BACK', font_size=30, italic=True, background_color=[255, 1, 1, 1]) self.back.bind(on_press=self.goback) self.add_widget(self.back) def start(self, instance): global camera_index self.flag = 1 self.img = Image() self.layout = BoxLayout() self.layout.add_widget(self.img) self.remove_widget(self.begin) self.remove_widget(self.back) self.add_widget(self.layout) mark = Button(text='VERIFY ME', font_size=30, italic=True, background_color=[255, 1, 1, 1]) back = Button(text='GO BACK', font_size=30, italic=True, background_color=[1, 1, 255, 1]) self.label = Label(text='Authenticate Yourself!!', font_size=38, color=[255, 255, 255, 1]) mark.bind(on_press=self.recognize) back.bind(on_press=self.goback) self.button_layout = GridLayout(rows=3, spacing=[20, 20]) self.button_layout.add_widget(mark) self.button_layout.add_widget(back) self.button_layout.add_widget(self.label) self.add_widget(self.button_layout) self.capture = cv2.VideoCapture(camera_index) self.event = Clock.schedule_interval(self.update, 1.0 / 33.0) def update(self, instance): _, self.frame = self.capture.read() self.frame = extract_all_faces(self.frame) buf1 = cv2.flip(self.frame, 0) buf = buf1.tostring() texture = Texture.create(size=(self.frame.shape[1], self.frame.shape[0]), colorfmt='bgr') texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.img.texture = texture def recognize(self, instance): ts = datetime.datetime.now() img_name = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) img_path = self.output_path + img_name cv2.imwrite(img_path, self.frame) print("[INFO] saved {}".format(img_name)) if image_enhance == 'on': if image_enhance_use_gpu == 'on': os.system('sh image_enhance_gpu.sh') elif image_enhance_use_gpu == 'off': os.system('sh image_enhance_cpu.sh') embedding, flag = generate_embedding(img_path) os.system('rm ./Output/*') if embeddings is not None: if flag == 1: ones_matrix = np.ones((len(usernames), 1)) embedding_matrix = np.matmul(ones_matrix, embedding.detach().numpy()) distances = calc_distance(embedding_matrix, embeddings) if (distances[np.argmin(distances)] < 1.0000): print(usernames[np.argmin(distances)] + ' Marked') self.button_layout.remove_widget(self.label) self.label = Label(text=usernames[np.argmin(distances)] + ' Marked', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) attendance[usernames[np.argmin(distances)]] = "Present" else: self.button_layout.remove_widget(self.label) self.label = Label(text='User Not Registered', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) else: self.button_layout.remove_widget(self.label) self.label = Label(text='Zero/Muliple Faces Detected', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) else: self.button_layout.remove_widget(self.label) self.label = Label(text='No Registered Users', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) def goback(self, instance): if self.flag == 1: self.event.cancel() self.capture.release() self.remove_widget(self.layout) self.remove_widget(self.button_layout) self.__init__() UI_interface.screen_manager.current = "Home"
class MainWindow(Screen): total = 0 tax_rate = 1.093 current_item = None current_time = None order_list = [] order_count = 1 order_list_details = {} order_list_times = [] order_list_times_past = [] live_orders_timed = [] time = [] order_database = {} order_database_dates = {} vendor = False menu_dict = {'All-Veg Sampler': 9.25, 'Alumutter': 8} menu_dict_vendor = {'All-Veg Sampler': 7, 'Alumutter': 6} def __init__(self, **kwargs): super(MainWindow, self).__init__(**kwargs) self.background = FloatLayout() self.callDatabase() with self.canvas: Color(0.2, 0.2, 0.28) Rectangle(size=(Window.width**2, Window.height**2)) # Color(1, 0, 0, .5, mode='rgba') # Rectangle(pos=self.pos, size=(210,210)) # Color(0.2, 0.2, 0.28) # Rectangle(pos=self.pos, size=(200,200)) # Food labels self.lbl_curry = Label(pos_hint={ "x": 0.11, "y": 0.92 }, size_hint=[0.1, 0.08], font_size=20, color=[1, 0.5, 0, 1], text="[b]Curry[/b]", markup=True) # Menu food item buttons self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="Chicken", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_alumutter = Button(pos_hint={ "x": 0.16, "y": 0.85 }, size_hint=[0.15, 0.08], text="Alumutter", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) # Other non-food panels of GUI self.lbl_subtotal = Label(pos_hint={ "x": 0.48, "y": 0.3 }, size_hint=[0.8, 0.2], font_size=15, color=[0.4, 0.4, 0.6], text=f"Subtotal: ${self.total}", markup=True) self.lbl_tax = Label(pos_hint={ "x": 0.48, "y": 0.27 }, size_hint=[0.8, 0.2], font_size=15, color=[0.4, 0.4, 0.6], text=f"Tax: ${self.total}", markup=True) self.lbl_total = Label(pos_hint={ "x": 0.48, "y": 0.23 }, size_hint=[0.8, 0.2], font_size=25, color=[0.6, 0.6, 0.8], text=f"Total: ${self.total}", markup=True) self.btn_complete = Button(pos_hint={ "x": 0.78, "y": 0.2 }, size_hint=[0.2, 0.1], text="Complete Order", background_color=[0.6, 0.5, 0.9, 3], on_release=self.submitOrder) self.btn_cancel = Button(pos_hint={ "x": 0.914, "y": 0.118 }, size_hint=[0.0666, 0.08], text="Cancel\n Order", background_color=[1.3, 0.3, 0.3, 3], font_size=14, on_release=self.cancelOrderPopup) self.btn_vendor = Button(pos_hint={ "x": 0.847, "y": 0.118 }, size_hint=[0.0666, 0.08], text="Vendor", background_color=[0.2, 0.5, 0.9, 3], font_size=14, on_release=self.vendorCheck) self.btn_to_go = Button(pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.toGo) self.txt_name = TextInput(pos_hint={ "x": 0.7805, "y": 0.062 }, size_hint=[0.2, 0.055], text='', background_color=[0.1, 0.45, 0.45, 3], multiline=False, halign='center', hint_text='Customer Name', hint_text_color=[0.8, 0.8, 0.8, 1]) self.btn_orders = Button(pos_hint={ "right": 1, "top": 1 }, size_hint=[0.03, 1], text="", background_color=[0.8, 0.8, 1, 0.02], on_release=self.changeWindow, markup=True) # Instantiate the GUI self.addWidgets(self.btn_orders, self.lbl_curry, self.btn_allveg, self.btn_alumutter, self.lbl_subtotal, self.lbl_tax, self.btn_to_go, self.txt_name, self.lbl_total, self.btn_cancel, self.btn_complete, self.btn_vendor) self.add_widget(self.background) # Popup for order cancellation confirmation self.popup_cancel_grid = GridLayout(cols=1, spacing=20, size_hint=(1, 0.95), size=(Window.width, Window.height)) self.popup_cancel = Popup(title='Confirmation', title_align='center', content=self.popup_cancel_grid, pos_hint={ 'x': 0.75, 'y': 0.03 }, size_hint=(0.23, 0.33), size=(Window.width, Window.height)) self.popup_cancel_grid.add_widget( Label(text='Are you sure you want \nto cancel this order?')) self.popup_cancel_grid.add_widget( Button(text='No', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.popup_cancel.dismiss, background_color=[0, 1.4, 1.45, 3])) self.popup_cancel_grid.add_widget( Button(text='Yes', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.popup_cancel.dismiss, on_press=self.resetOrder, background_color=[1.3, 0.2, 0.2, 3])) # Scroll window to list the current items self.scroll_grid = GridLayout(cols=1, spacing=0, size_hint_y=None, size_hint_x=self.background.height / self.background.width) self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height')) self.scroll = ScrollView(size_hint=[0.159, 0.525], pos_hint={ 'x': 0.82, 'y': 0.45 }) self.scroll_btn = None # Popup window shown when an item in the scroll view is indicated self.popup_grid = GridLayout(cols=1, spacing=20, size_hint=(1, 0.95), pos_hint={'bottom': 0.2}, size=(Window.width, Window.height)) self.popup_grid_top = GridLayout(cols=2, spacing=20, size_hint=(1, 1), pos_hint={'top': 0.95}, size=(Window.width, Window.height)) self.popup_btn_delete = Button(text='Text', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.removeItem, background_color=[0.9, 0.2, 0.2, 3]) self.popup_btn_to_go = Button(text='Text', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.toGo, background_color=[0.4, 0.8, 0.4, 3]) self.popup_btn_no_cilantro = Button( text='No Cilantro', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.cilantroMod, background_color=[0.3, 1.4, 1.4, 3]) self.popup_btn_extra_cilantro = Button( text='Extra Cilantro', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.cilantroMod, background_color=[0.3, 1.4, 1.4, 3]) self.popup_txt = TextInput(size_hint=[1, 0.4], text='', background_color=[0.4, 0.3, 0.6, 3], multiline=False, halign='center', font_size=18, padding_y=33, hint_text='Enter Order Details', hint_text_color=[0.8, 0.8, 0.8, 1]) self.popup_grid_top.add_widget(self.popup_btn_delete) self.popup_grid_top.add_widget(self.popup_btn_to_go) self.popup_grid_top.add_widget(self.popup_btn_no_cilantro) self.popup_grid_top.add_widget(self.popup_btn_extra_cilantro) self.popup_grid.add_widget(self.popup_grid_top) self.popup_grid.add_widget(self.popup_txt) self.popup = Popup(title='Title', title_align='center', content=self.popup_grid, on_dismiss=self.addDetails, size_hint=(0.45, 0.7), size=(Window.width, Window.height)) self.button_id = None self.data = None self.data_backups = [] self.client_socket = None try: threading.Thread(target=self.connectSocket).start() except Exception as e: print(f'Error: {e}') def connectSocket(self, instance=None): host = '0.0.0.0' port = 8912 address = (host, port) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(address) server.listen(5) print( f'Listening on {socket.gethostbyname(socket.gethostname())}:{port}' ) while True: conn, addr = server.accept() print(f"Connection from {address} has been established.") self.client_socket = conn while True: time.sleep(0.5) try: conn.send('B=G#J4>m$p'.encode()) except ConnectionResetError: print('Connection with client lost.') break def generateCurOrder(self): self.scroll_btn = Button(text=f"{self.order_list[-1].food}", font_size=11, size_hint_y=None, height=33, background_color=[0.7, 0.7, 1, 1], on_release=self.popupItem) self.scroll_grid.add_widget(self.scroll_btn) if len(self.scroll.children) == 0: self.scroll.add_widget(self.scroll_grid) self.background.add_widget(self.scroll) # def duplicateItem(self, instance): //-- Decided not to use this stuff but I'll keep it here # //-- in case I change my mind later. # for i in range(self.popup_slider.value): # self.scroll_btn = Button(text=f"{self.order_list[self.order_list.index(self.button_id.text)]}", # font_size=12, size_hint_y=None, height=33, # background_color=[0.7, 0.7, 1, 1], on_release=self.popupItem) # self.scroll_grid.add_widget(self.scroll_btn) # self.order_list.append(self.button_id.text) # self.addTotal(self.menu_dict[self.button_id.text]) # # def updateSlider(self, instance, touch): # if self.popup_slider.value == 1: # self.popup_slider_btn.text = f"Duplicate this item {int(self.popup_slider.value)} time" # else: # self.popup_slider_btn.text = f"Duplicate this item {int(self.popup_slider.value)} times" # # self.popup_slider = Slider(min=1, max=10, value=1, step=1, value_track=True, # value_track_color=[0.4, 0.4, 0.6, 1], # on_touch_move=self.updateSlider) # # self.popup_slider_btn = Button(font_size=20, background_color=[0.7, 0.7, 1, 1], on_release=self.duplicateItem, # text=f"Duplicate this item {int(self.popup_slider.value)} time", markup=True) # # self.popup_grid.add_widget(self.popup_slider) # self.popup_grid.add_widget(self.popup_slider_btn) def addTotal(self, x): self.total += x subtotal = format(self.total, '.2f') tax = format((self.total * self.tax_rate) - self.total, '.2f') total = format(float(subtotal) + float(tax), '.2f') self.lbl_subtotal.text = f"Subtotal: ${subtotal}" self.lbl_tax.text = f"Tax: ${tax}" self.lbl_total.text = f"Total: ${total}" def addList(self): self.current_item.time = str(datetime.datetime.now())[:19][11:-3] self.order_list.append(self.current_item) screen_third.generateCurOrders() def addDetails(self, instance=None): if self.popup_txt.text != '': num = 1 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for i in range(len(rev)): if rev[i] == self.button_id: break else: num += 1 for i in range(len(self.order_list)): if self.order_list[i].food == self.button_id.text: if self.order_list[i].order_id == num: self.order_list[ i].details = f"({self.popup_txt.text}) " break screen_third.generateCurOrders() def submitOrder(self, instance=None): if len(self.order_list) > 0: self.live_orders_timed = [self.order_list.copy()] self.order_database[len(self.order_database)] = f"{str(datetime.datetime.now())[:19]} - " \ f"{[x.food for x in self.live_orders_timed[-1]]}" with open('database.txt', 'a') as db: db.write( f"{str(datetime.datetime.now())[:19]} - {[x.food for x in self.live_orders_timed[-1]]} - " f"${format((self.total * self.tax_rate), '.2f')}\n") self.data = [x for x in self.order_list] msg = pickle.dumps(self.data) try: if len(self.data_backups) > 0: self.client_socket.send(pickle.dumps(self.data_backups)) self.data_backups.clear() print('<INFO> Backups sent to client.') self.client_socket.send(msg) except Exception as e: if ['BACKUP'] not in self.data_backups: self.data_backups.append(['BACKUP']) self.data_backups.append([x.food for x in self.order_list]) print( f'<ERROR> No connection with client. Backup data created.\n{e}' ) screen_third.generatePastOrders() self.resetOrder() screen_third.scroll_grid.remove_widget(screen_third.div) def cancelOrderPopup(self, instance=None): if len(self.order_list) > 0: self.popup_cancel.open() def resetOrder(self, instance=None): self.total = 0 self.current_item = OrderItem(order_id=0) self.order_list.clear() self.lbl_subtotal.text = f"Subtotal: ${self.total}" self.lbl_tax.text = f"Tax: ${self.total}" self.lbl_total.text = f"Total: ${self.total}" self.scroll_grid.clear_widgets() self.txt_name.text = '' self.order_count = 1 self.background.remove_widget(self.btn_to_go) self.btn_to_go = Button(pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.toGo) self.addWidgets(self.btn_to_go) screen_third.cancelOrder() @staticmethod def changeWindow(instance): sm.current = 'tertiary' sm.transition.direction = 'left' def callDatabase(self): # This is always called with __init__ count = 0 with open('database.txt', 'r') as db: for line in db: self.time.append(f"{line[:19]}") self.order_database[count] = line[:-1] self.order_database_dates[line[:10]] = None count += 1 self.order_database_dates = [key for key in self.order_database_dates] def popupItem(self, instance): self.button_id = instance num = 1 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for i in range(len(rev)): if rev[i] == self.button_id: break else: num += 1 for i in range(len(self.order_list)): if self.order_list[i].food == self.button_id.text: if self.order_list[i].order_id == num: self.popup_txt.text = self.order_list[i].details[1:-2] break self.popup.title = f'Options for selected item - {instance.text}' self.popup_btn_delete.text = f"Remove this '{instance.text}' from the order." if "TO-GO" not in instance.text: self.popup_btn_to_go.text = f"Make this order to-go." else: self.popup_btn_to_go.text = f"Make this '{instance.text[:-6]}' for here." self.popup.open() def vendorCheck(self, instance=None): if self.vendor: self.vendor = False instance.background_normal = 'atlas://data/images/defaulttheme/button' self.vendorGen() else: self.vendor = True instance.background_normal = 'atlas://data/images/defaulttheme/button_pressed' self.vendorGen() def vendorGen(self, instance=None): self.total = 0 if self.vendor: for item in self.order_list: self.addTotal(self.menu_dict_vendor[item.food]) else: for item in self.order_list: self.addTotal(self.menu_dict[item.food]) def cilantroMod(self, instance=None): if instance.text == 'No Cilantro': if self.popup_txt.text != '' and 'Cilantro' not in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text}, No Cilantro" elif 'No Cilantro' in self.popup_txt.text: pass elif ', Extra Cilantro' in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text.split(',')[0]}, No Cilantro" else: self.popup_txt.text = 'No Cilantro' else: if self.popup_txt.text != '' and 'Cilantro' not in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text}, Extra Cilantro" elif 'Extra Cilantro' in self.popup_txt.text: pass elif ', No Cilantro' in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text.split(',')[0]}, Extra Cilantro" else: self.popup_txt.text = 'Extra Cilantro' # def toGo(self, instance=None): # # if "TO-GO" not in self.button_id.text: # i = self.order_list.index(self.button_id.text) # self.button_id.text = f"{self.order_list[i]} TO-GO" # self.order_list[i] = f"{self.order_list[i]} [b]|| [u]TO-GO[/u] ||[/b]" # screen_third.generateCurOrders() # else: # self.button_id.text = self.button_id.text[:-6] # screen_third.generateCurOrders() # for i in range(len(self.order_list)): # if "TO-GO[/u] ||[/b]" in self.order_list[i] and self.button_id.text in self.order_list[i]: # self.order_list[i] = self.order_list[i][:-26] # break # # screen_third.generateCurOrders() # # self.popup.dismiss() def toGo(self, instance=None): if len(self.order_list) > 0: for i in range(len(self.order_list)): self.order_list[i].to_go = ' [b][u]TO-GO[/u][/b]' self.background.remove_widget(self.btn_to_go) self.btn_to_go = Button( pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.forHere, background_normal= 'atlas://data/images/defaulttheme/button_pressed') self.addWidgets(self.btn_to_go) screen_third.generateCurOrders() def forHere(self, instance=None): if len(self.order_list) > 0: for i in range(len(self.order_list)): self.order_list[i].to_go = '' self.background.remove_widget(self.btn_to_go) self.btn_to_go = Button( pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.toGo, background_normal='atlas://data/images/defaulttheme/button') self.addWidgets(self.btn_to_go) screen_third.generateCurOrders() def removeItem(self, instance): count = 0 for i in range(len(self.scroll_grid.children)): if self.scroll_grid.children[i] != self.button_id: count += 1 else: break self.order_list.remove(self.order_list[count]) if self.vendor: self.addTotal(-self.menu_dict_vendor[self.button_id.text]) else: self.addTotal(-self.menu_dict[self.button_id.text]) self.scroll_grid.remove_widget(self.button_id) self.popup.dismiss() self.order_count -= 1 screen_third.generateCurOrders() if len(self.order_list) == 0: self.resetOrder() screen_third.scroll_grid.remove_widget(screen_third.div) def addWidgets(self, *args): for i in args: self.background.add_widget(i) def pressed(self, instance): self.current_item = OrderItem(order_id=self.order_count, food=instance.text) self.order_count += 1 self.addList() self.vendorGen() self.generateCurOrder()
class ContextMenu(TabbedPanel): '''ContextMenu class. See module documentation for more information. :Events: `on_select`: data Fired when a selection is done, with the data of the selection as first argument. Data is what you pass in the :meth:`select` method as first argument. `on_dismiss`: .. versionadded:: 1.8.0 Fired when the ContextMenu is dismissed either on selection or on touching outside the widget. ''' container = ObjectProperty(None) '''(internal) The container which will be used to contain Widgets of main menu. :data:`container` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`~kivy.uix.boxlayout.BoxLayout`. ''' main_tab = ObjectProperty(None) '''Main Menu Tab of ContextMenu. :data:`main_tab` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' bubble_cls = ObjectProperty(MenuBubble) '''Bubble Class, whose instance will be used to create container of ContextMenu. :data:`bubble_cls` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`MenuBubble`. ''' header_cls = ObjectProperty(MenuHeader) '''Header Class used to create Tab Header. :data:`header_cls` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`MenuHeader`. ''' attach_to = ObjectProperty(allownone=True) '''(internal) Property that will be set to the widget on which the drop down list is attached to. The method :meth:`open` will automatically set that property, while :meth:`dismiss` will set back to None. ''' auto_width = BooleanProperty(True) '''By default, the width of the ContextMenu will be the same as the width of the attached widget. Set to False if you want to provide your own width. ''' dismiss_on_select = BooleanProperty(True) '''By default, the ContextMenu will be automatically dismissed when a selection have been done. Set to False to prevent the dismiss. :data:`dismiss_on_select` is a :class:`~kivy.properties.BooleanProperty`, default to True. ''' max_height = NumericProperty(None, allownone=True) '''Indicate the maximum height that the dropdown can take. If None, it will take the maximum height available, until the top or bottom of the screen will be reached. :data:`max_height` is a :class:`~kivy.properties.NumericProperty`, default to None. ''' __events__ = ('on_select', 'on_dismiss') def __init__(self, **kwargs): self._win = None self.add_tab = super(ContextMenu, self).add_widget self.bubble = self.bubble_cls(size_hint=(None, None)) self.container = None self.main_tab = self.header_cls(text='Main') self.main_tab.content = ScrollView(size_hint=(1, 1)) self.main_tab.content.bind(height=self.on_scroll_height) super(ContextMenu, self).__init__(**kwargs) self.bubble.add_widget(self) self.bind(size=self._reposition) self.bubble.bind(on_height=self._bubble_height) def _bubble_height(self, *args): '''Handler for bubble's 'on_height' event. ''' self.height = self.bubble.height def open(self, widget): '''Open the dropdown list, and attach to a specific widget. Depending the position of the widget on the window and the height of the dropdown, the placement might be lower or higher off that widget. ''' # if trying to open a non-visible widget if widget.parent is None: return # ensure we are not already attached if self.attach_to is not None: self.dismiss() # we will attach ourself to the main window, so ensure the widget we are # looking for have a window self._win = widget.get_parent_window() if self._win is None: raise ContextMenuException( 'Cannot open a dropdown list on a hidden widget') self.attach_to = widget widget.bind(pos=self._reposition, size=self._reposition) self.add_tab(self.main_tab) self.switch_to(self.main_tab) self.main_tab.show_arrow = False self._reposition() # attach ourself to the main window self._win.add_widget(self.bubble) self.main_tab.color = (0, 0, 0, 0) def on_select(self, data): '''Default handler for 'on_select' event. ''' pass def dismiss(self, *largs): '''Remove the dropdown widget from the window, and detach itself from the attached widget. ''' if self.bubble.parent: self.bubble.parent.remove_widget(self.bubble) if self.attach_to: self.attach_to.unbind(pos=self._reposition, size=self._reposition) self.attach_to = None self.switch_to(self.main_tab) for child in self.tab_list[:]: self.remove_widget(child) self.dispatch('on_dismiss') def select(self, data): '''Call this method to trigger the `on_select` event, with the `data` selection. The `data` can be anything you want. ''' self.dispatch('on_select', data) if self.dismiss_on_select: self.dismiss() def on_dismiss(self): '''Default event handler for 'on_dismiss' event. ''' pass def _set_width_to_bubble(self, *args): '''To set self.width and bubble's width equal. ''' self.width = self.bubble.width def _reposition(self, *largs): # calculate the coordinate of the attached widget in the window # coordinate sysem win = self._win widget = self.attach_to if not widget or not win: return wx, wy = widget.to_window(*widget.pos) wright, wtop = widget.to_window(widget.right, widget.top) # set width and x if self.auto_width: # Calculate minimum required width if len(self.container.children) == 1: self.bubble.width = max(self.main_tab.parent.parent.width, self.container.children[0].width) else: self.bubble.width = max( self.main_tab.parent.parent.width, self.bubble.width, *([i.width for i in self.container.children])) Clock.schedule_once(self._set_width_to_bubble, 0.01) # ensure the dropdown list doesn't get out on the X axis, with a # preference to 0 in case the list is too wide. # try to center bubble with parent position x = wx - self.bubble.width / 4 if x + self.bubble.width > win.width: x = win.width - self.bubble.width if x < 0: x = 0 self.bubble.x = x # bubble position relative with the parent center x_relative = x - (wx - self.bubble.width / 4) x_range = self.bubble.width / 4 # consider 25% as the range # determine if we display the dropdown upper or lower to the widget h_bottom = wy - self.bubble.height h_top = win.height - (wtop + self.bubble.height) def _get_hpos(): '''Compare the position of the widget with the parent to display the arrow in the correct position ''' _pos = 'mid' if x_relative == 0: _pos = 'mid' elif x_relative < -x_range: _pos = 'right' elif x_relative > x_range: _pos = 'left' return _pos if h_bottom > 0: self.bubble.top = wy self.bubble.arrow_pos = 'top_' + _get_hpos() elif h_top > 0: self.bubble.y = wtop self.bubble.arrow_pos = 'bottom_' + _get_hpos() else: # none of both top/bottom have enough place to display the widget at # the current size. Take the best side, and fit to it. height = max(h_bottom, h_top) if height == h_bottom: self.bubble.top = wy self.bubble.height = wy self.bubble.arrow_pos = 'top_' + _get_hpos() else: self.bubble.y = wtop self.bubble.height = win.height - wtop self.bubble.arrow_pos = 'bottom_' + _get_hpos() def on_touch_down(self, touch): '''Default Handler for 'on_touch_down' ''' if super(ContextMenu, self).on_touch_down(touch): return True if self.collide_point(*touch.pos): return True self.dismiss() def on_touch_up(self, touch): '''Default Handler for 'on_touch_up' ''' if super(ContextMenu, self).on_touch_up(touch): return True self.dismiss() def add_widget(self, widget, index=0): '''Add a widget. ''' if self.content is None: return if widget.parent is not None: widget.parent.remove_widget(widget) if self.tab_list and widget == self.tab_list[0].content or\ widget == self._current_tab.content or \ self.content == widget or\ self._tab_layout == widget or\ isinstance(widget, TabbedPanelContent) or\ isinstance(widget, TabbedPanelHeader): super(ContextMenu, self).add_widget(widget, index) return if not self.container: self.container = GridLayout(orientation='vertical', size_hint_y=None, cols=1) self.main_tab.content.add_widget(self.container) self.container.bind(height=self.on_main_box_height) self.container.add_widget(widget, index) if hasattr(widget, 'cont_menu'): widget.cont_menu = self widget.bind(height=self.on_child_height) widget.size_hint_y = None def remove_widget(self, widget): '''Remove a widget ''' if self.container and widget in self.container.children: self.container.remove_widget(widget) else: super(ContextMenu, self).remove_widget(widget) def on_scroll_height(self, *args): '''Event Handler for scollview's height. ''' if not self.container: return self.container.height = max(self.container.height, self.main_tab.content.height) def on_main_box_height(self, *args): '''Event Handler for main_box's height. ''' if not self.container: return self.container.height = max(self.container.height, self.main_tab.content.height) if self.max_height: self.bubble.height = min( self.container.height + self.tab_height + dp(16), self.max_height) else: self.bubble.height = self.container.height + \ self.tab_height + dp(16) def on_child_height(self, *args): '''Event Handler for children's height. ''' height = 0 for i in self.container.children: height += i.height self.main_tab.content.height = height self.container.height = height def add_tab(self, widget, index=0): '''To add a Widget as a new Tab. ''' super(ContextMenu, self).add_widget(widget, index)
class TertiaryWindow(Screen): def __init__(self, **kwargs): # GUI from top to bottom, left to right super(TertiaryWindow, self).__init__(**kwargs) with self.canvas: Color(0.2, 0.2, 0.28) Rectangle(size=(Window.width**2, Window.height**2)) self.scroll = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) self.scroll_btn = None self.scroll_grid = GridLayout(cols=1, spacing=1, size_hint_y=None) self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height')) self.btn_menu = Button(size_hint_y=None, height=40, text="Order Database >", background_color=[0.45, 0.45, 0.45, 3], on_release=self.changeWindow) self.scroll_grid.add_widget(self.btn_menu) self.button_id = None self.div = Button( text=f"[b]----------[/b]", markup=True, size_hint_y=None, height=20, background_color=[0.4, 0.4, 0.4, 3], background_down='atlas://data/images/defaulttheme/button') self.popup = Popup( title='Notice', title_align='center', content=Label( text= 'This order has not been submitted by the cashier yet. Please wait until' ' the order has been submitted to finish it.', size=(400, 400), text_size=[380, 380], halign='center', valign='center'), size_hint=(None, None), size=(400, 400)) if len(self.scroll.children) == 0: self.scroll.add_widget(self.scroll_grid) self.add_widget(self.scroll) def changeWindow(self, instance): if 'Order Database' in instance.text: sm.current = 'secondary' sm.transition.direction = 'left' screen_second.generateOrders() def reset(self): self.scroll_grid.clear_widgets() self.scroll_grid.add_widget(self.btn_menu) def cancelOrder(self): temp_list = [] temp_num = 0 temp_total = 0 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for child in rev: if 'Order' not in child.text and '^ ^ ^' not in child.text and '- - -' not in child.text and '----------' not in child.text: temp_list.append(child) temp_total += 1 continue elif '----------' in child.text: for items in temp_list: temp_num += 1 if temp_total == temp_num and temp_num > 0: for item in temp_list: self.scroll_grid.remove_widget(item) self.scroll_grid.remove_widget(self.div) temp_list.clear() temp_num = 0 temp_total = 0 break else: temp_list.clear() temp_num = 0 temp_total = 0 else: temp_list.clear() temp_num = 0 temp_total = 0 def itemFinished(self, instance=None): self.button_id = instance if "[s]" not in instance.text: instance.text = f"[s]{instance.text}[/s]" instance.background_color = [0.6, 0.6, 0.6, 3] else: instance.text = f"{instance.text[3:-4]}" instance.background_color = [1.8, 0.8, 0, 3] temp_list = [] temp_num = 0 temp_total = 0 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for child in rev: if 'Order' not in child.text and '^ ^ ^' not in child.text and '- - -' not in child.text and '----------' not in child.text: temp_list.append(child) temp_total += 1 continue else: div = child for items in temp_list: if '[/s]' in items.text: temp_num += 1 if temp_total == temp_num and temp_num > 0: if "----------" in div.text: self.popup.open() instance.text = f"{instance.text[3:-4]}" instance.background_color = [1.8, 0.8, 0, 3] break for item in temp_list: self.scroll_grid.remove_widget(item) self.scroll_grid.remove_widget(div) temp_list.clear() temp_num = 0 temp_total = 0 break else: temp_list.clear() temp_num = 0 temp_total = 0 def generateCurOrders(self, instance=None, text=None): self.cancelOrder() for i in range(len(screen_main.order_list)): t = screen_main.order_list[i].time if int(t.split(':')[0]) > 12 and 'PM' not in t: hour = int(t.split(':')[0]) - 12 screen_main.order_list[i].time = f"{hour}{t[-3:]} PM" else: if 'AM' not in t and 'PM' not in t: screen_main.order_list[i].time = f"{t} AM" self.scroll_grid.add_widget( Button( text= f"{screen_main.order_list[i].details}{screen_main.order_list[i].food}" f"{screen_main.order_list[i].to_go} | [b]{screen_main.order_list[i].time}[/b]", size_hint_y=None, height=40, background_color=[1.8, 0.8, 0, 3], markup=True, on_release=self.itemFinished)) if len(screen_main.order_list) > 0: self.scroll_grid.add_widget(self.div) def generatePastOrders(self, instance=None, text=None): self.cancelOrder() for i in range(len(screen_main.live_orders_timed[-1])): t = screen_main.live_orders_timed[-1][i].time if int(t.split(':')[0]) > 12 and 'PM' not in t: hour = int(t.split(':')[0]) - 12 screen_main.live_orders_timed[-1][ i].time = f"{hour}{t[-3:]} PM" else: if 'AM' not in t and 'PM' not in t: screen_main.live_orders_timed[-1][i].time = f"{t} AM" self.scroll_grid.add_widget( Button( text= f"{screen_main.live_orders_timed[-1][i].details}{screen_main.live_orders_timed[-1][i].food}" f"{screen_main.live_orders_timed[-1][i].to_go} | [b]{screen_main.live_orders_timed[-1][i].time}[/b]", markup=True, size_hint_y=None, height=40, background_color=[1.8, 0.8, 0, 3], on_release=self.itemFinished)) if len(screen_main.txt_name.text) == 0: self.scroll_grid.add_widget( Button( text=f"[b]- - -[/b]", markup=True, size_hint_y=None, height=20, background_color=[0.4, 0.4, 0.4, 3], background_down='atlas://data/images/defaulttheme/button')) else: self.scroll_grid.add_widget( Button( text= f"[b]^ ^ ^ {screen_main.txt_name.text.capitalize()} ^ ^ ^[/b]", markup=True, size_hint_y=None, height=20, background_color=[0.4, 0.4, 0.4, 3], background_down='atlas://data/images/defaulttheme/button'))
class Workspace(ScrollView): """ Workspace is where user can view expression, configure them or simply choose to delete expressions. """ def __init__(self, **kwargs): super(Workspace, self).__init__(**kwargs) self.line_number = 1 self.expression_list = [] self.y_pos = .8 self.current_variable_names = [] self.layout = GridLayout(cols=1, padding=10, spacing=10, size_hint=(None, None), width = 500) self.layout.bind(minimum_height=self.layout.setter('height')) """ Draw the expression to the workspace layout """ def draw(self): self.add_widget(self.layout) """ Update the current list of variable names after a program is run """ def update_variable_names(self, var): self.current_variable_names = var """ "Clear the workspace when a new program is selected by the user """ def clear(self): self.expression_list = [] self.y_pos = .8 self.line_number = 1 self.layout.clear_widgets() """ Create relevant expression according to the expression buttons clicked in the command panel """ def add_expression(self, instance): #exp = LetLayout(line, size_hint=(None, None), pos_hint={'x':.2,'y':self.y_pos}) if instance.text == 'LET': exp = LetLayout(self.line_number, self.current_variable_names, pos_hint={'x': .2, 'y': self.y_pos}) elif instance.text == 'PRINT': exp = PrintLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos}) elif instance.text == 'GOTO': exp = GotoLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos}) elif instance.text == 'IF': exp = IfLayout(self.line_number, self.current_variable_names, pos_hint={'x': .2, 'y': self.y_pos}) elif instance.text == 'GOSUB': exp = GoSubLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos}) elif instance.text == 'RETURN': exp = ReturnLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos}) elif instance.text == 'END': exp = EndLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos}) self.line_number += 1 # bind the delete event when user clicks on the delete button exp.btn_delete.fbind('on_press', self.delete_expression, expression=exp) exp.draw() self.layout.add_widget(exp) self.y_pos -= .1 self.expression_list.append(exp) def on_touch_down(self, t): super(Workspace, self).on_touch_down(t) #t.apply_transform_2d(self.layout.to_local) # for widget in self.layout.walk(): #print widget.on_touch_down(t) # print t #if widget.id == 'LET': # print widget.on_touch_down(t) # print "\n" # print widget.collide_point(*t.pos) # print widget # print t # print widget.x # print widget.y #if self.collide_point(*t.pos): # for widget in self.layout.walk(): # #if widget.collide_point(*t.pos): # if widget.id == 'LET': # print widget.on_touch_down(t) #print widget.get_line_number() #print("\n{} -> {}".format("Line number", widget.get_line_number())) """ Delete each expression from the workspace. This method is triggered when delete button is clicked """ def delete_expression(self, instance, expression): self.layout.remove_widget(expression) self.expression_list.remove(expression) #self.line_number -= 1 """ Get all the expressions from the workspace """ def get_expressions(self): return self.expression_list
class Core(Button): """Core object that contains all information about a single core.""" def __init__(self, index, manyman, **kwargs): self.index = index self.manyman = manyman if index in self.manyman.chip_orientation[0]: self.core_type = "ARM" else: self.core_type = "Epiphany" self.load = 0.0 self.viz_load = 0.0 self.move_speed = 0.0 self.info_built = False self.info_showing = False self._frequency = 600 self._freq_table = [self.frequency] self._voltage = 1. self.tasks = dict() # Number of tasks RUNNING on the core. self.pending_count = 0 # Always increasing, for determining task color. self.task_count = 0 self.c = None self.r = None self.info = None self.fs = None self.frequency_label = None self.voltage_label = None self.cpu_graph = None self.mem_graph = None self.task_list = None settings = { 'text': self.info_text(), 'background_normal': manyman.settings['core_background'], 'background_down': manyman.settings['core_background_active'], 'border': manyman.settings['core_border'], 'size_hint_y': manyman.settings['core_size_y_%s' % self.core_type], 'halign': 'center' } if self.core_type == 'Epiphany': # settings['background_normal'] = manyman.settings['core_background'] # settings['background_down'] = manyman.settings['core_background_active'] settings['background_color'] = [0.5, 0.5, 1, 1] settings.update(kwargs) super(Core, self).__init__(**settings) self.build() def build(self): """Render the core widget.""" with self.canvas: # Add the color overlay self.c = Color( self.manyman.settings['core_color_range'][0], 1, 1, .7, mode='hsv' ) p = self.manyman.settings['core_padding'] self.r = Rectangle( pos=[self.pos[0] + p, self.pos[1] + p], size=[ self.width - 2 * p, max(0, self.height * self.viz_load - 2 * p) ] ) # Initialize the popup containing detailed core information if self.core_type == 'Epiphany': display_index = self.index -2 else: display_index = self.index self.info = InfoPopup( title="%s Core %d" % (self.core_type, display_index), size_hint=(None, None), size=(600, 450) ) self.info.bind(on_show=self.info_show, on_dismiss=self.info_dismiss) # Initialize the performance graphs of that popup self.cpu_graph = PerfGraph("CPU", container=self) self.mem_graph = PerfGraph("MEM", container=self) def build_info(self): """Render the popup containing detailed core information.""" layout = BoxLayout(orientation='vertical', spacing=10) controls = BoxLayout(spacing=10, size_hint_y=None, height=50) # layout.add_widget(controls) # Add frequency control slider frequency_control = BoxLayout(orientation='vertical', spacing=2) controls.add_widget(frequency_control) self.frequency_label = Label(text='Frequency: %s MHz' % self.frequency) frequency_control.add_widget(self.frequency_label) self.fs = ValueSlider( min=self._freq_table[-1], max=self._freq_table[0], value=self.frequency, values=self._freq_table ) self.fs.bind(on_change=self.frequency_changed) self.fs.bind(on_release=self.frequency_set) frequency_control.add_widget(self.fs) # Add voltage control slider voltage_control = BoxLayout(orientation='vertical', spacing=2) controls.add_widget(voltage_control) self.voltage_label = Label(text='Voltage: %.3fV' % self.voltage) voltage_control.add_widget(self.voltage_label) content = BoxLayout(spacing=10) layout.add_widget(content) # Render the performance graphs graphs = BoxLayout( orientation='vertical', spacing=10, padding=5 ) graphs.add_widget(self.cpu_graph) graphs.add_widget(self.mem_graph) content.add_widget(graphs) # Render the task list tasks = BoxLayout( orientation='vertical', spacing=10, padding=5, size_hint_x=None, width=300 ) scroll = ScrollView(do_scroll_x=False) self.task_list = GridLayout(cols=1, spacing=5, size_hint_y=None) self.task_list.bind(minimum_height=self.task_list.setter('height')) scroll.add_widget(self.task_list) tasks.add_widget(scroll) content.add_widget(tasks) self.info.content = layout self.info_built = True def frequency_changed(self, ins): """Handler when the frequency slider is moved.""" self.frequency_label.text = "Frequency: %d MHz" % ins.val def frequency_set(self, ins): """Handler when the frequency is set.""" Logger.info("Core: Set frequency to: %s" % ins.val) self._frequency = ins.val self.manyman.comm.set_core_frequency(ins.val, self.index) def info_show(self, *largs): """Handler when the detailed core information popup is opened.""" if not self.info_built: # Render said popup self.build_info() self.info_showing = True def info_dismiss(self, instance): """Handler when the detailed core information popup is closed.""" self.info_showing = False def add_task(self, t): """Add a task to this core.""" t.hue = (self.task_count * .15) % 1 self.tasks[t.tid] = t self.task_list.add_widget(t) self.task_count += 1 # Add the task's performance lines self.cpu_graph.add_line(t.tid, t.hue) self.mem_graph.add_line(t.tid, t.hue) Logger.debug("Core: Added task %s to core %d" % (t.tid, self.index)) def remove_task(self, t): """Remove a task from this core.""" if not t.tid in self.tasks: return Logger.debug( "Core: Removing task %s from core %d" % (t.tid, self.index) ) self.tasks.pop(t.tid) self.task_list.remove_widget(t) # Remove the task's performance lines self.cpu_graph.remove_line(t.tid) self.mem_graph.remove_line(t.tid) def highlight(self): """Highlight this core.""" self.state = 'down' def dehighlight(self): """Dehighlight this core.""" self.state = 'normal' def update(self, dt): """Update the performance overlay.""" # Determine the new visible load if self.viz_load > self.load + 1e-3: self.viz_load -= self.move_speed elif self.viz_load < self.load - 1e-3: self.viz_load += self.move_speed else: self.viz_load = self.load # Determine the new color cr = self.manyman.settings['core_color_range'] self.c.h = cr[0] + self.viz_load * (cr[1] - cr[0]) self.c.a = 0.7 # Determine the new size p = self.manyman.settings['core_padding'] self.r.pos = [self.pos[0] + p, self.pos[1] + p] self.r.size = [ self.width - 2 * p, max(0, (self.height - 2 * p) * self.viz_load) ] def update_load(self, load): """Update this core's CPU load.""" self.load = load # Determine the speed at which the overlay will resize self.move_speed = abs(self.load - self.viz_load) / \ self.manyman.settings['framerate'] * 1.2 self.cpu_graph.update(load * 100) self.text = self.info_text() def update_mem(self, load): """Update this core's memory usage.""" self.mem_graph.update(load * 100) def info_text(self): """Retrieve the core's info text.""" if self.core_type == 'Epiphany': return "eCore %d\n(%d tasks)" % ( self.index-2, self.pending_count ) return "Core %d\n(%d tasks)" % ( self.index, self.pending_count ) def on_press(self): """Handler when the core is pressed. Opens the detailed info popup.""" self.info.show() def on_release(self): """Handler when the core is released. Does nothing.""" pass def get_frequency(self): """Getter for the core's frequency.""" return self._frequency def set_frequency(self, value): """Setter for the core's frequency.""" if not self.info_built or self.frequency == value: return self._frequency = value self.fs.val = value def get_voltage(self): """Getter for the core's voltage.""" return self._voltage def set_voltage(self, value): """Setter for the core's voltage.""" if not self.info_built or self.voltage == value: return self._voltage = value self.voltage_label.text = "Voltage: %.3fV" % value # Define getters and setters frequency = property(get_frequency, set_frequency) voltage = property(get_voltage, set_voltage)
class UserInterface: def __init__(self, client): # TODO handle connection errors properly self.client = client self.layout = GridLayout(cols = 2, pos_hint={'x': 0, 'y': 0}, size_hint=(1, 0.1)) self.client.layout.add_widget(self.layout, index = 1000) self.client.bind('connected', self.connected) self.client.bind('loaded', self.loaded) self.client.bind('registered', self.registered) if self.client.config.get('connection', 'autoconnect') == 'yes': self.auto = True self.client.connect(self.client.config.get('connection', 'server')) else: self.auto = False self.server_input = TextInput(text = self.client.config.get('connection', 'server')) self.server_button = Button(text = 'Connect', size_hint = (0.25, 1)) self.server_button.bind(on_press = self.do_connect) self.layout.add_widget(self.server_input) self.layout.add_widget(self.server_button) def do_connect(self, button): self.client.connect(self.server_input.text) self.layout.remove_widget(self.server_input) self.layout.remove_widget(self.server_button) del self.server_input, self.server_button self.connecting_label = Label(text = 'connecting...') self.layout.add_widget(self.connecting_label) def connected(self, event): if not self.auto: self.client.config.set('connection', 'server', self.client.server) self.connecting_label.text = 'loading...' def loaded(self, event): if self.auto: self.client.register(self.client.config.get('connection', '_id')) return self.layout.remove_widget(self.connecting_label) del self.connecting_label self.dropdown = DropDown() for stage in sorted(self.client.meteor.find('stages'), key=lambda x: x['title']): self.dropdown.add_widget(Label(text = stage['title'], size_hint_y = None, height = 40)) seen = [] for minion in sorted(self.client.meteor.find('minions', selector = {'stage': stage['_id'], 'type': 'media'}), key=lambda x: x['title']): # workaround for python-meteor bug if not minion['stage'] == stage['_id']: continue if minion['_id'] in seen: continue else: seen.append(minion['_id']) button = Button(text = minion['title'], size_hint_y = None, height = 30) button.minion_id = minion['_id'] button.bind(on_press = self.do_register) self.dropdown.add_widget(button) self.dropdown_button = Button(text = 'Select Minion') self.dropdown_button.bind(on_release = self.dropdown.open) self.layout.add_widget(self.dropdown_button) self.auto_checkbox = CheckBox() self.auto_label = Label(text = 'Connect automatically on start') self.layout.add_widget(self.auto_checkbox) self.layout.add_widget(self.auto_label) def do_register(self, button): self.client.config.set('connection', '_id', button.minion_id) self.client.config.set('connection', 'autoconnect', 'yes' if self.auto_checkbox.active else 'no') self.client.config.write() self.client.register(button.minion_id) self.dropdown.dismiss() self.layout.remove_widget(self.dropdown_button) self.layout.remove_widget(self.auto_checkbox) self.layout.remove_widget(self.auto_label) del self.dropdown_button, self.dropdown, self.auto_checkbox, self.auto_label self.registering_label = Label(text = 'registering...') self.layout.add_widget(self.registering_label) def registered(self, event): if not self.auto: self.layout.remove_widget(self.registering_label) del self.registering_label
class CreateClassListWidget(ScrollView): student_widgets = [] selected_index = -1 layout = None text_student_name = ObjectProperty(None) def __init__(self, **kwargs): super(CreateClassListWidget, self).__init__(**kwargs) self.layout = GridLayout(cols=1, spacing=5, size_hint_y=None, padding=5) self.layout.bind(minimum_height=self.layout.setter('height')) self.clear_widgets() self.add_widget(self.layout) # if enter is pressed Window.bind(on_key_down=self._on_keyboard_down) Window.bind(on_key_up=self._on_keyboard_up) def _on_keyboard_down(self, instance, keyboard, keycode, text, modifiers): if self.text_student_name.focus and keycode == 40: # 40 - Enter key pressed self.add_student(self.text_student_name.text) self.text_student_name.text = '' def _on_keyboard_up(self, instance, keyboard, keycode): if self.text_student_name.focus and keycode == 40: # 40 - Enter key pressed self.text_student_name.text = '' def add_student(self, name): if name.strip() != '': s = CreateClassStudentWidget(size_hint_y=None, height=40) s.index = len(self.student_widgets) s.parent_list = self s.name = name.strip() self.student_widgets.append(s) self.layout.add_widget(s) def remove_student(self): if 0 <= self.selected_index < len(self.student_widgets): print('removing', self.selected_index) for i in range(self.selected_index, len(self.student_widgets)): self.student_widgets[i].index = self.selected_index + i - 2 self.layout.remove_widget( self.student_widgets.pop(self.selected_index)) self.selected_index = -1 def select(self, index): for i in self.student_widgets: i.selected = False # already selected the same label if self.selected_index == index: self.selected_index = -1 else: self.selected_index = index for i in self.student_widgets: i.selected = False self.student_widgets[index].selected = True return True
class TabbedCEFBrowser(GridLayout): def __init__(self, urls=["http://www.rentouch.ch"], *largs, **dargs): super(TabbedCEFBrowser, self).__init__(cols=1, *largs, **dargs) gl = GridLayout(rows=1, size_hint=(1, None), height=controls_size) self.current_tab = None self.__tab_bar_scroll = ScrollView(size_hint=(1, 1)) self.__tab_bar_grid = GridLayout(rows=1, size_hint=(None, 1)) self.__tab_bar_grid.bind( minimum_width=self.__tab_bar_grid.setter("width")) last_tab = None for url in urls: this_tab = TabbedCEFBrowserTab(self, url, url) this_tab.last_tab = last_tab self.__tab_bar_grid.add_widget(this_tab) last_tab = this_tab self.current_tab = last_tab self.__tab_bar_scroll.add_widget(self.__tab_bar_grid) self.__tab_bar_scroll.bind(height=self.__tab_bar_grid.setter("height")) gl.add_widget(self.__tab_bar_scroll) self.__tab_bar_new = Button(text="+", font_size=controls_size / 2, size_hint=(None, 1), width=controls_size) self.__tab_bar_new.bind(on_press=self._on_new_tab) gl.add_widget(self.__tab_bar_new) self.__control_bar_grid = GridLayout(rows=1, size_hint=(1, None), height=controls_size) self._back_button = Button(text="<", font_size=controls_size / 2, size_hint=(None, 1), width=controls_size) self._back_button.bind(on_press=self._on_back_press) self._forward_button = Button(text=">", font_size=controls_size / 2, size_hint=(None, 1), width=controls_size) self._forward_button.bind(on_press=self._on_forward_press) self._url_input = TextInput(text="http://", font_size=controls_size / 2, size_hint=(1, 1), multiline=False) self._url_input.bind(focus=self._on_url_focus) self._url_input.bind(on_text_validate=self._on_url_validate) self._load_button = Button(text="Go", font_size=controls_size / 2, size_hint=(None, 1), width=controls_size) self._load_button.bind(on_press=self._on_load_button) self.__control_bar_grid.add_widget(self._back_button) self.__control_bar_grid.add_widget(self._forward_button) self.__control_bar_grid.add_widget(self._url_input) self.__control_bar_grid.add_widget(self._load_button) self._current_browser = CEFBrowser() self.add_widget(gl) self.add_widget(self.__control_bar_grid) self.add_widget(self._current_browser) self.select_first_tab() def _focus_url_input(self, *largs): self._url_input.focus = True def _on_new_tab(self, but): self.add_tab(TabbedCEFBrowserTab(self, "http://google.com", "Google")) Clock.schedule_once(self._focus_url_input, 0) def _on_back_press(self, back_button): self._current_browser.go_back() def _on_forward_press(self, forward_button): self._current_browser.go_forward() def _on_url_focus(self, url_input, new_focus): if new_focus: def fn(*largs): url_input.select_all() Clock.schedule_once(fn, 0) self._load_button.text = "Go" else: url_input.text = self._current_browser.url self._load_button.text = \ "x" if self._current_browser.is_loading else "r" def _on_url_validate(self, url_input): self._current_browser.url = self._url_input.text def _on_load_button(self, load_button): if self._url_input.focus: self._current_browser.url = self._url_input.text elif self._current_browser.is_loading: self._current_browser.stop_loading() else: self._current_browser.reload() def select_first_tab(self): for tab in self.__tab_bar_grid.children: tab.select() break @property def tabs(self): return self.__tab_bar_grid.children def add_tab(self, new_tab): self.__tab_bar_grid.add_widget(new_tab) new_tab.select() def remove_tab(self, remove_tab): self.__tab_bar_grid.remove_widget(remove_tab) self.current_tab = remove_tab.last_tab remove_tab.last_tab.select() def _set_tab(self, new_tab): if self.current_tab != new_tab: ct = self.current_tab tmp = ct while tmp: if tmp.last_tab == new_tab: tmp.last_tab = new_tab.last_tab tmp = tmp.last_tab new_tab.last_tab = ct self.current_tab = new_tab try: self._current_browser.unbind(url=self._url_input_set_text) except: pass Clock.schedule_once( functools.partial(self._old_tab_remove_keyboard, self._current_browser)) self.remove_widget(self._current_browser) self._url_input.text = new_tab.url self._current_browser = new_tab.cef_browser self.add_widget(self._current_browser) self._current_browser.bind(url=self._url_input_set_text) def _url_input_set_text(self, browser, url): self._url_input.text = url if self._url_input.focus: self._url_input.select_all() def _old_tab_remove_keyboard(self, browser, *largs): print("old_tab_remove_keyboard", browser) browser.focus = False
class MainScreen(Screen): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) import Tkinter root = Tkinter.Tk() self.WIN_WIDTH, self.WIN_HEIGHT = root.winfo_screenwidth( ), root.winfo_screenheight() self.MIL_WIDTH, self.MIL_HEIGHT = root.winfo_screenmmwidth( ), root.winfo_screenmmheight() self.PPC = 10. * (float(self.WIN_WIDTH) / self.MIL_WIDTH + float(self.WIN_HEIGHT) / self.MIL_HEIGHT) / 2. self.SCREEN_INFO = (self.WIN_WIDTH, self.WIN_HEIGHT, self.MIL_WIDTH, self.MIL_HEIGHT, self.PPC) self.capture = cv2.VideoCapture(0) self.capture.set(3, self.WIN_WIDTH) self.capture.set(4, self.WIN_HEIGHT) self.eyeTracker = None try: self.eyeTracker = pylink.EyeLink('100.1.1.1') except: self.eyeTracker = None print "Could not connect to eye tracker" ''' Layout the layouts ''' self.mainLayout = mainLayout = FloatLayout() with mainLayout.canvas.before: Color(.8, .8, .8, 1) self.background = Rectangle(size=self.size, pos=self.pos) mainLayout.bind(pos=self._updateBackground, size=self._updateBackground) hgap, vgap = 0.01, 0.01 self.topLeftLayout = topLeftLayout = PartialLayout( size_hint=(.5 - hgap / 2, 0.4 * (1 - 2 * vgap)), pos_hint={ 'center_x': 0.25 - hgap / 4, 'center_y': .804 }) self.middleLeftLayout = middleLeftLayout = PartialLayout( size_hint=(.5 - hgap / 2, 0.5 * (1 - 2 * vgap)), pos_hint={ 'center_x': 0.25 - hgap / 4, 'center_y': .353 }) self.bottomLeftLayout = bottomLeftLayout = PartialLayout( size_hint=(.5 - hgap / 2, 0.1 * (1 - 2 * vgap)), pos_hint={ 'center_x': 0.25 - hgap / 4, 'center_y': .049 }) self.rightLayout = rightLayout = PartialLayout(size_hint=(.5 - hgap / 2, 1), pos_hint={ 'center_x': 0.75 + hgap / 4, 'center_y': .5 }) self.add_widget(mainLayout) mainLayout.add_widget(topLeftLayout) mainLayout.add_widget(middleLeftLayout) mainLayout.add_widget(bottomLeftLayout) mainLayout.add_widget(rightLayout) ''' Top left layout ''' saveFolderLabel = Label(text='Save Folder', size_hint=(0.4, 0.25), pos_hint={ 'center_x': 0.2, 'center_y': 0.875 }) folderButton = Button(source='Assets/folder.png', size_hint=(None, None), size=(0.05 * self.WIN_HEIGHT, 0.05 * self.WIN_HEIGHT), pos_hint={ 'center_x': 0.45, 'center_y': 0.875 }) self.folderText = TextInput(size_hint=(0.5, 0.125), pos_hint={ 'center_x': 0.75, 'center_y': 0.875 }) subjectIDLabel = Label(text='Subject ID', size_hint=(0.5, 0.25), pos_hint={ 'center_x': 0.25, 'center_y': 0.625 }) self.subjectIDText = TextInput(size_hint=(0.5, 0.125), pos_hint={ 'center_x': 0.75, 'center_y': 0.625 }) calibButton = Button(text='Calibrate Eye Tracker', size_hint=(1, 0.25), pos_hint={ 'center_x': 0.5, 'center_y': 0.375 }) checkCamButton = Button(text='Check Camera', size_hint=(1, 0.25), pos_hint={ 'center_x': 0.5, 'center_y': 0.125 }) folderButton.background_normal = 'Assets/folder_normal.png' folderButton.background_down = 'Assets/folder_down.png' topLeftLayout.add_widget(saveFolderLabel) topLeftLayout.add_widget(folderButton) topLeftLayout.add_widget(self.folderText) topLeftLayout.add_widget(subjectIDLabel) topLeftLayout.add_widget(self.subjectIDText) topLeftLayout.add_widget(calibButton) topLeftLayout.add_widget(checkCamButton) ''' Middle Left Layout ''' designerLabel = Label(text='Experiment Designer', size_hint=(1, 0.2), pos_hint={ 'center_x': 0.5, 'center_y': 0.9 }) self.asd = asd = AntisaccadeDesigner(size_hint=(1, 0.39), pos_hint={ 'center_x': 0.5, 'center_y': 0.6 }) self.vsd = vsd = VisualSearchDesigner(size_hint=(1, 0.39), pos_hint={ 'center_x': 0.5, 'center_y': 0.2 }) middleLeftLayout.add_widget(designerLabel) middleLeftLayout.add_widget(asd) middleLeftLayout.add_widget(vsd) ''' Bottom Left Layout ''' startButton = Button(text='Start', size_hint=(0.5, 0.99), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }) bottomLeftLayout.add_widget(startButton) ''' Right Layout ''' self.stimGrid = GridLayout(cols=1, spacing=10, size_hint_y=None) self.stimGrid.bind(minimum_height=self.stimGrid.setter('height')) with self.stimGrid.canvas.before: Color(0, 0, 0, 1) self.gridRect = Rectangle(size=self.stimGrid.size, pos=self.stimGrid.pos) self.stimGrid.bind(pos=self._updateGridRect, size=self._updateGridRect) flowLabel = Label(text='Experiment Flow', size_hint=(1, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.95 }) scroller = ScrollView(size_hint=(1, 0.7), pos_hint={ 'center_x': 0.5, 'center_y': 0.55 }) showButton = Button(text='Hide', size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.25, 'center_y': 0.15 }) clearButton = Button(text='Clear', size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.75, 'center_y': 0.15 }) randButton = Button(text='Randomize', size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.25, 'center_y': 0.05 }) scroller.add_widget(self.stimGrid) rightLayout.add_widget(flowLabel) rightLayout.add_widget(scroller) rightLayout.add_widget(showButton) rightLayout.add_widget(clearButton) rightLayout.add_widget(randButton) ''' Other widgets ''' self.isVisible = True self.coverWidget = FloatLayout(size_hint=(1, 0.7), pos_hint={ 'center_x': 0.5, 'center_y': 0.55 }) with self.coverWidget.canvas.before: Color(0, 0, 0, 1) self.coverRect = Rectangle(size=self.coverWidget.size, pos=self.coverWidget.pos) self.coverWidget.bind(pos=self._updateCoverRect, size=self._updateCoverRect) self.coverWidget.add_widget( Label(text='Experiment flow is\ncurrently hidden.', size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 })) self.calibrationWidget = FloatLayout(size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }) with self.calibrationWidget.canvas.before: Color(0, 0, 0, 1) self.calibRect = Rectangle(size=self.calibrationWidget.size, pos=self.calibrationWidget.pos) self.calibrationWidget.bind(pos=self._updateCalibOverlay, size=self._updateCalibOverlay) self.coverWidget.add_widget( Label(text=CALIB_TEXT, size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 })) ''' Object Bindings ''' folderButton.bind(on_release=self.chooseRootFolder) checkCamButton.bind(on_release=self.toCheckCam) calibButton.bind(on_release=self.calibrateEyelink) self.asd.addButton.bind(on_release=self.addAntisaccade) self.vsd.addButton.bind(on_release=self.addVisualSearch) startButton.bind(on_release=self.startExperiment) showButton.bind(on_release=self.toggleGUI) clearButton.bind(on_release=self.clearExperiment) randButton.bind(on_release=self.randomizeOrder) def chooseRootFolder(self, _): pass def calibrateEyelink(self, _): if not self.eyeTracker is None: self.eyeTracker.doTrackerSetup() def toCheckCam(self, _): self.parent.transition.direction = 'left' self.parent.current = 'check_cam' def addAntisaccade(self, _): stimLabel = StimLabel(text='Antisaccade', size_hint_y=None, height=self.WIN_HEIGHT / 10) self.stimGrid.add_widget(stimLabel) stimLabel.buttonUp.bind(on_release=self.moveTaskUp) stimLabel.buttonDown.bind(on_release=self.moveTaskDown) stimLabel.buttonRemove.bind(on_release=self.removeTask) def addVisualSearch(self, _): text = 'Visual Search\nContrast(s): {}, Stimuli: {}'.format( self.vsd.mainContrastButton.text.split(' ')[0], self.vsd.mainConditionButton.text.split(' ')[0]) stimLabel = StimLabel(text=text, size_hint_y=None, height=self.WIN_HEIGHT / 10) self.stimGrid.add_widget(stimLabel) stimLabel.buttonUp.bind(on_release=self.moveTaskUp) stimLabel.buttonDown.bind(on_release=self.moveTaskDown) stimLabel.buttonRemove.bind(on_release=self.removeTask) def moveTaskUp(self, obj): index = self.stimGrid.children.index(obj.parent.parent) if index == len(self.stimGrid.children) - 1: return child = self.stimGrid.children[index] self.stimGrid.remove_widget(child) self.stimGrid.add_widget(child, index + 1) def moveTaskDown(self, obj): index = self.stimGrid.children.index(obj.parent.parent) if index == 0: return child = self.stimGrid.children[index] self.stimGrid.remove_widget(child) self.stimGrid.add_widget(child, index - 1) def removeTask(self, obj): self.stimGrid.remove_widget(obj.parent.parent) def startExperiment(self, _): if len(self.stimGrid.children) == 0: return def toggleGUI(self, _): if self.isVisible: self.rightLayout.add_widget(self.coverWidget) else: self.rightLayout.remove_widget(self.coverWidget) self.isVisible = not self.isVisible def clearExperiment(self, _): self.stimGrid.clear_widgets() def randomizeOrder(self, _): random.shuffle(self.stimGrid.children) def _updateBackground(self, instance, _): self.background.pos = instance.pos self.background.size = instance.size def _updateGridRect(self, instance, _): self.gridRect.pos = instance.pos self.gridRect.size = instance.size def _updateCoverRect(self, instance, _): self.coverRect.pos = instance.pos self.coverRect.size = instance.size def _updateCalibOverlay(self, instance, _): self.calibrationWidget.pos = instance.pos self.calibrationWidget.size = instance.size
class ReinforcementEditor(GridLayout, IObserver): ''' with the ReinforcementEditor you can add or edit new layer or bars to the selected cross-section-shape ''' # editLayer editLayer = ObjectProperty() # editBar editBar = ObjectProperty() addLayerStr = StringProperty('add layer') deleteLayerStr = StringProperty('delete layer') addBarStr = StringProperty('add bar') deleteBarStr = StringProperty('delete bar') ''' constructor ''' def __init__(self, **kwargs): super(ReinforcementEditor, self).__init__(**kwargs) self.cols, self.spacing = 2, Design.spacing self.editLayer = EditLayer(p=self) self.editBar = EditBar(p=self) self.barAreaVisible = False self.layerAreaVisible = False self.error = False self.containsView = False def create_gui(self): self.errorLbl = OwnLabel(text='[color=ff3333]error: wrong parameters[/color]', markup=True, size_hint_y=None, height=sp(20)) self.create_add_delete() self.create_material_options() ''' the method create_add_delete create the area where you can add new materials and delete materials from the cs_view ''' def create_add_delete(self): self.btnArea = GridLayout(cols=2, row_force_default=True, row_default_height=Design.btnHeight, height=Design.btnHeight, spacing=Design.spacing) # create btns addBtnLayer = OwnButton(text=self.addLayerStr) deleteBtnLayer = OwnButton(text=self.deleteLayerStr) addBtnBar = OwnButton(text=self.addBarStr) deleteBtnBar = OwnButton(text=self.deleteBarStr) # bind btns addBtnLayer.bind(on_press=self.show_add_layer_area) deleteBtnLayer.bind(on_press=self.delete_layer) addBtnBar.bind(on_press=self.show_add_bar_area) deleteBtnBar.bind(on_press=self.delete_bar) # fill the are with content self.btnArea.add_widget(addBtnLayer) self.btnArea.add_widget(deleteBtnLayer) self.btnArea.add_widget(addBtnBar) self.btnArea.add_widget(deleteBtnBar) self.add_widget(self.btnArea) ''' the method create_material_options create the popup where you can select the materials for the new layer ''' def create_material_options(self): self.layoutMaterials = GridLayout(cols=1, spacing=Design.spacing) self.materialEditor = MaterialCreater() self.materialEditor._parent = self self.popupMaterialEditor = OwnPopup(title='editor', content=self.materialEditor) for i in range(0, len(self.allMaterials.allMaterials)): btnMaterialA = OwnButton(text=self.allMaterials.allMaterials[i].name) btnMaterialA.bind(on_press=self.select_material) self.layoutMaterials.add_widget(btnMaterialA) self.btnMaterialEditor = OwnButton(text='create material') self.btnMaterialEditor.bind(on_press=self.popupMaterialEditor.open) self.layoutMaterials.add_widget(self.btnMaterialEditor) self.root = ScrollView() self.root.add_widget(self.layoutMaterials) popupContent = GridLayout(cols=1) popupContent.add_widget(self.root) self.popupMaterial = OwnPopup(title='material', content=popupContent) ''' the method add_layer add a new layer at the cross section it use the choosen percent value ''' def add_layer(self, y, csArea, material): self.cancel_editing_layer(None) self.csShape.add_layer(y, csArea, material) ''' edit the selected layer in the view ''' def edit_layer(self, y, csArea, material): self.cancel_editing_layer(None) self.csShape.edit_layer(y, csArea, material) ''' delete the selected layer in the focus view ''' def delete_layer(self, btn): self.view.delete_layer() ''' the method add_bar add a new layer at the cross section it use the choosen percent value ''' def add_bar(self, x, y, csArea, material): self.cancel_editing_bar(None) self.csShape.add_bar(x, y, csArea, material) ''' edit the selected bar in the view ''' def edit_bar(self, x, y, csArea, material): self.cancel_editing_bar(None) self.csShape.edit_bar(x, y, csArea, material) ''' delete the selected bar in the focus view ''' def delete_bar(self, btn): self.view.delete_bar() ''' show the area where you can add layers ''' def show_add_layer_area(self, btn): if not self.layerAreaVisible: self.layerAreaVisible = True self.editLayer.add = True self.remove_widget(self.btnArea) self.add_widget(self.editLayer.addArea) ''' cancel the editing ''' def cancel_editing_layer(self, btn): if self.layerAreaVisible: self.layerAreaVisible = False self.remove_widget(self.editLayer.addArea) self.add_widget(self.btnArea) ''' show the area where you can add bars ''' def show_add_bar_area(self, btn): if not self.barAreaVisible: self.barAreaVisible = True self.editBar.add = True self.remove_widget(self.btnArea) self.add_widget(self.editBar.addArea) ''' cancel the editing ''' def cancel_editing_bar(self, btn): if self.barAreaVisible: self.barAreaVisible = False self.remove_widget(self.editBar.addArea) self.add_widget(self.btnArea) ''' show the error message ''' def show_error_message(self): if not self.error: self.btnArea.add_widget(self.errorLbl) self.error = True ''' hide the error message ''' def hide_error_message(self): if self.error: self.btnArea.remove_widget(self.errorLbl) self.error = False ''' the method update_materials update the view of the materials. its make sure that the create material button is the last component of the gridlayout ''' def update(self): self.layoutMaterials.remove_widget(self.btnMaterialEditor) btnMaterialA = OwnButton(text=self.allMaterials.allMaterials[-1].name) btnMaterialA.bind(on_press=self.select_material) self.layoutMaterials.add_widget(btnMaterialA) self.layoutMaterials.add_widget(self.btnMaterialEditor) ''' the method cancel_edit_material cancel the editing of the material and reset the values of the materialEditor ''' def cancel_edit_material(self): self.popupMaterialEditor.dismiss() self.materialEditor.reset_editor() ''' the method will be called when the user selected a material the popup will be closed and the button text change to the material name ''' def select_material(self, btn): self.popupMaterial.dismiss() self.editLayer.materialBtn.text = btn.text self.editBar.materialBtn.text = btn.text ''' add the view at the left side of the editor ''' def add_view(self): self.view = self.cs.view self.containsView = True self.add_widget(self.view, 1) ''' update the view when the shape has changes ''' def update_view(self): if self.containsView: self.remove_widget(self.view) self.view = self.cs.view self.add_widget(self.view, 1) self.containsView = True ''' remove the view of the editor ''' def remove_view(self): if self.containsView: self.remove_widget(self.view) self.containsView = False ''' change the current cross section ''' def change_cross_section(self, shape): self.csShape = shape ''' the method set_cross_section was developed to say the view, which cross section should it use ''' def set_cross_section(self, cs): self.cs = cs self.allMaterials = self.cs.allMaterials self.allMaterials.add_listener(self) # default cross section rectangle self.csShape = cs.csRectangle self.rectangleInformation = RectangleInformation() self.shape = self.rectangleInformation self.rectangleInformation.csShape = self.csShape self.rectangleInformation.create_gui() self.create_gui() self.cs.set_reinforcement_editor(self)
class HongBao(PageLayout): def __init__(self, **kwargs): super(HongBao, self).__init__(**kwargs) self.filename = kivy.resources.resource_find( '/mnt/sdcard/com.hipipal.qpyplus/projects/hongbao/hb.jpg') self.init_ui() def add_arrt(self, gridLayout, attr_name, value): gridLayout.add_widget(Label(text=attr_name)) attr_input = TextInput(text=value, multiline=False) gridLayout.add_widget(attr_input) return attr_input def init_ui(self): self.gridLayout = GridLayout(cols=1, spacing=[0, 4]) self.gridLayout1 = GridLayout(cols=2, spacing=[0, 9]) self.color_min_input = self.add_arrt(self.gridLayout1, 'color_min', '20') self.color_max_input = self.add_arrt(self.gridLayout1, 'color_max', '120') self.fangcha_input = self.add_arrt(self.gridLayout1, 'fangcha', '15000') self.up_down_input = self.add_arrt(self.gridLayout1, 'up_down', '8') #self.left_right_input=self.add_arrt(self.gridLayout1,'left_right','0') self.jisuan_btn_a = Button(text='chick_a', ) self.gridLayout1.add_widget(self.jisuan_btn_a) self.jisuan_btn_b = Button(text='chick_b', ) self.gridLayout1.add_widget(self.jisuan_btn_b) self.gridLayout.add_widget(self.gridLayout1) self.jisuan_btn_a.bind(on_press=self.jisuan_a) self.jisuan_btn_b.bind(on_press=self.jisuan_b) self.image_hb = Image(source=self.filename) self.gridLayout.add_widget(self.image_hb) self.floatlayout = FloatLayout() self.fc = FileChooserListView() self.fc.path = '/mnt/sdcard/DCIM/' self.floatlayout.add_widget(self.fc) self.get_file_btn = Button(text='chick_a', size_hint=(0.2, .1), pos=(20, 20)) self.floatlayout.add_widget(self.get_file_btn) self.get_file_btn.bind(on_press=self.get_file) self.add_widget(self.floatlayout) self.add_widget(self.gridLayout) def get_file(self, instance): filename = os.path.join(os.path.dirname(self.filename), os.path.basename(self.fc.selection[0])) print self.fc.selection[0], ' -' * 20 im_tmp = PIL.Image.open(self.fc.selection[0]) w, h = im_tmp.size minx = int(w * 230.0 / 720) maxx = int(w * 487 / 720) miny = int(h * (1280 - 520) / 1280) maxy = int(h * (1280 - 264) / 1280) if h > 1000: im_tmp = im_tmp.crop([minx, miny, maxx, maxy]) im_tmp.save(filename, 'jpeg') self.filename = filename self.floatlayout.opacity = 0 self.updata_image() self.page = 1 print 'filename :', self.filename def remove_line(self, mode='a'): im2 = PIL.Image.open(self.filename) im3 = im2.copy() w2, h2 = im2.size im2_pix = im2.load() im3_pix = im3.load() color_min = int(self.color_min_input.text) color_max = int(self.color_max_input.text) fangcha_max = int(self.fangcha_input.text) up_down = int(self.up_down_input.text) black_in_line = False current_y = 0 for y in range(up_down + 1, h2): x_color_r = 0 x_color_g = 0 x_color_b = 0 for x in range(0, w2): r, g, b = im2_pix[x, y] x_color_r += r x_color_g += g x_color_b += b pingjun_r = x_color_r / w2 pingjun_g = x_color_g / w2 pingjun_b = x_color_b / w2 fangcha_r = 0 fangcha_g = 0 fangcha_b = 0 for x in range(0, w2): r, g, b = im2_pix[x, y] fangcha_r += abs(pingjun_r - r) fangcha_g += abs(pingjun_g - g) fangcha_b += abs(pingjun_b - b) if ( fangcha_r + fangcha_g + fangcha_b ) < fangcha_max and color_min < pingjun_r < color_max and color_min < pingjun_g < color_max and color_min < pingjun_b < color_max: #print y, '****' * 30, ' ', fangcha_r + fangcha_g + fangcha_b, pingjun_r, pingjun_g, pingjun_r if black_in_line == False: current_y = y black_in_line = True for x2 in range(0, w2): if mode == 'a': im3_pix[x2, y] = im2_pix[x2, current_y - 2] else: im3_pix[x2, y] = im2_pix[x2, y - up_down] else: if black_in_line == True: black_in_line = False if mode == 'a': for x2 in range(0, w2): im3_pix[x2, y] = im2_pix[x2, current_y - up_down] #print y, '----' * 30, ' ', fangcha_r + fangcha_g + fangcha_b, pingjun_r, pingjun_g, pingjun_r return im3 def jisuan_a(self, instance): im3 = self.remove_line().resize([600, 600]) filenamea = self.filename.rsplit('.', 1)[0] + 'a.jpg' im3.save(filenamea, 'jpeg') self.updata_image(filenamea) def jisuan_b(self, instance): im3 = self.remove_line('b').resize([600, 600]) filenamea = self.filename.rsplit('.', 1)[0] + 'a.jpg' im3.save(filenamea, 'jpeg') self.updata_image(filenamea) def updata_image(self, filenamea=None): if filenamea is None: filenamea = self.filename image_hb2 = Image(source=filenamea) self.gridLayout.remove_widget(self.image_hb) self.image_hb = image_hb2 self.gridLayout.add_widget(self.image_hb, 0) self.image_hb.reload()
class Spotlight(App): ''' This class represents the kivy app that will run the spotlight ''' def __init__(self, **kwargs): super(Spotlight, self).__init__(**kwargs) # fixed width of the app, will never change self._width = kwargs.get('width', 500) # tells how many entries can be displayed on the screen at the same time. The rest will be accessible via a scroller self._max_results_displayed = kwargs.get('max_results_displayed', 5) # gives the height of the separators that will be used between each entry self._sep_height = kwargs.get('sep_height', 1) # static height of the main search bar: SearchInput self._search_field_height = kwargs.get('search_field_height', 35) # height of each entry self._result_height = kwargs.get('result_height', 25) # this is the spacing between the search bar and the scroller containing the entries self._spacing = kwargs.get('spacing', 1) # this is the padding of the main window self._padding = 5 # this is the space between each separator/result in the dropdown list self._result_spacing = kwargs.get('result_spacing', 1) # color of a non-selected entry self._inactive_button_color = (.0, .0, .0, 0) # color of a selected entry self._active_button_color = (.4, .4, .4, 1) # store all the visible entries on the screen as a pair (button, separator) for convenience self._results = [] # index of the result that is currently highlighted self._highlight_index = -1 # these 3 variables are the 3 callbacks that the controller can input self._on_build = None self._on_enter = None self._on_text = None # this field holds a preset number of buttons for efficiency self._button_pool = [] # parse the callbacks passed in the constructor self.user_bind(**kwargs) self.build_window() # update the window size self.update_window() def user_bind(self, **kwargs): ''' this function saves the callbacks passed to this function into the 3 available holders ''' # this event is triggered when the application is drawn for the first time self._on_build = kwargs.get('on_build', self._on_build) # this event is triggered when the user presses enter self._on_enter = kwargs.get('on_enter', self._on_enter) # this even is triggered whenever the text in the search field is changed self._on_text = kwargs.get('on_text', self._on_text) def on_start(self): ''' when the window is drawn and the application started we update the size of the window ''' self.update_window() def build_window(self): ''' this function builds the whole app ''' self._search_field = SearchInput(multiline=False, focus=True, realdonly=False, height=self._search_field_height, size_hint=(1, None), markup=True, valign='middle', font_size=20, font_name='data/fonts/DejaVuSans.ttf') self._search_field.bind(focus=self._on_focus) self._search_field._keyboard.bind(on_key_down=self._on_keyboard_down) self._search_field.background_active = '' self._search_field.font_size = 20 self._search_field.bind(on_text_validate=self._on_text_validate) self._search_field.bind(text=self._on_new_text) self._search_field.text = '' self._drop_down_list = GridLayout(cols=1, width=self._width, spacing=self._result_spacing, size_hint=(None, None)) self._drop_down_list.bind( minimum_height=self._drop_down_list.setter('height')) self._scroller = ScrollView(scroll_distance=10, scroll_type=['bars'], do_scroll_x=False, bar_width=10, size_hint=(1, 1)) self._scroller.add_widget(self._drop_down_list) self._layout = ColoredGridLayout(cols=1, width=self._width, height=self._search_field_height, padding=(self._padding, self._padding), spacing=self._spacing * 2) self._layout.add_widget(self._search_field) self._layout.add_widget(self._scroller) if self._on_build: self._on_build() return self._layout def build(self): return self._layout def _unbind_all(self): self._search_field.unbind(focus=self._on_focus) self._search_field._keyboard.unbind(on_key_down=self._on_keyboard_down) self._search_field.unbind(on_text_validate=self._on_text_validate) self._search_field.unbind(text=self._on_new_text) self._drop_down_list.unbind( minimum_height=self._drop_down_list.setter('height')) for btn in self._button_pool: btn.unbind(width=button_width_setter) btn.unbind(on_press=self._on_click) btn.unbind(texture_size=btn.setter('text_size')) def _on_new_text(self, value, text): if self._on_text: self._on_text(self, value, text) def _on_text_validate(self, value): ''' when the user pressed enter, we forward the callback to the controller with the current hightlight index ''' if self._on_enter: ret = self._on_enter(value, self._highlight_index) if ret: self._unbind_all() self.stop() def _on_focus(self, instance, value): ''' this function is called whenever the focus of the search field changes. We do NOT allow defocus ''' if not value: self._search_field.focus = True # since the search field has to re-claim the keyboard, we re-bind our callback self._search_field._keyboard.bind( on_key_down=self._on_keyboard_down) def update_window(self, *args): ''' based on the current amount of entries shown, we adapt the size of the window ''' result_count = len(self._results) win_width = 2 * self._padding + self._width win_height = 2 * self._padding + self._search_field_height + self._spacing + ( self._result_spacing * 2 + self._result_height + self._sep_height) * result_count max_height = 2 * self._padding + self._search_field_height + self._spacing + ( self._result_spacing * 2 + self._result_height + self._sep_height) * self._max_results_displayed if self._app_window: self._app_window.size = win_width, min(win_height, max_height) def _on_keyboard_down(self, keyboard, keycode, text, modifiers): ''' we handle 3 keys: up (resp. down) to hightlight the entry above (resp. below) and escape to quit the application ''' if keycode[1] == 'up': self._highlight_up() elif keycode[1] == 'down': self._highlight_down() elif keycode[1] == 'escape': keyboard.release() self._unbind_all() self.stop() else: # mark the key press as not handled return False # mark the key press as handled return True def pre_allocate(self, number): self._button_pool = [] for _ in range(0, number): btn = Button(text='str', height=self._result_height, size_hint=(1, None), valign='middle', halign='left', background_color=self._inactive_button_color, markup=True, padding_x=0) btn.bind(width=button_width_setter) btn.bind(on_press=self._on_click) btn.bind(texture_size=btn.setter('text_size')) btn.background_normal = '' btn.background_down = btn.background_normal self._button_pool.append(btn) def _build_button(self): if self._button_pool: return self._button_pool.pop() btn = Button(text='str', height=self._result_height, size_hint=(1, None), valign='middle', halign='left', background_color=self._inactive_button_color, markup=True, padding_x=0) btn.bind(width=button_width_setter) btn.bind(on_press=self._on_click) btn.bind(texture_size=btn.setter('text_size')) btn.background_normal = '' btn.background_down = btn.background_normal return btn def _release_button(self, btn): btn.background_color = self._inactive_button_color self._button_pool.append(btn) def add_result(self, str, redraw=True): ''' add a new entry to the dropdown list; an index is returned ''' btn = self._build_button() btn.text = str sep = Separator(height=self._sep_height) self._drop_down_list.add_widget(sep) self._drop_down_list.add_widget(btn) self._results.append((btn, sep)) # we reset the highlight self._highlight_reset() if redraw: self.update_window() return len(self._results) - 1 def get_result(self, idx): ''' get a button object from an index - returned from a previous call to add_result ''' if not idx < len(self._results) or not idx >= 0: return e, _ = self._results[idx] return e def remove_result(self, idx, redraw=True): ''' remove a result object from its index - returned from a previous call to add_result ''' if not idx < len(self._results) or not idx >= 0: return e, sep = self._results[idx] if sep: self._drop_down_list.remove_widget(sep) self._drop_down_list.remove_widget(e) self._results.remove((e, sep)) self._release_button(e) # we reset the highlight self._highlight_reset() # resize the window accordingly if redraw: self.update_window() def clear_results(self, redraw=True): ''' clear all the results ''' for e, sep in self._results: self._release_button(e) self._drop_down_list.clear_widgets() self._results = [] # we reset the highlight self._highlight_reset() # resize the window accordingly if redraw: self.update_window() def _on_click(self, instance): ''' this callback is called whenever a click on a result is done; the highlight is adapted ''' for i in range(0, len(self._results)): e, _ = self._results[i] if e is instance: offset = i - self._highlight_index self._highlight_update(offset) self._on_text_validate(1) break def _scroll_update(self): ''' this function adapts the scroller to ensure that the highlighted object is visible ''' highlight_reverse_index = len( self._results) - 1 - self._highlight_index item_lb = highlight_reverse_index * ( self._result_spacing * 2 + self._sep_height + self._result_height) item_ub = item_lb + self._result_height + self._result_spacing * 2 + self._sep_height view_size = (self._result_spacing * 2 + self._result_height + self._sep_height) * self._max_results_displayed total_size = (self._result_spacing * 2 + self._result_height + self._sep_height) * len(self._results) lb = self._scroller.scroll_y * (total_size - view_size) ub = lb + view_size if item_lb < lb: self._scroller.scroll_y -= self._scroller.convert_distance_to_scroll( 0, lb - item_lb)[1] elif item_ub > ub: self._scroller.scroll_y += self._scroller.convert_distance_to_scroll( 0, item_ub - ub)[1] def _highlight_update(self, offset): ''' move the hightlight by `offset' amount ''' if self._highlight_index > -1 and self._highlight_index < len( self._results): e, sep = self._results[self._highlight_index] e.background_color = self._inactive_button_color self._highlight_index += offset self._highlight_index = min(self._highlight_index, len(self._results) - 1) if self._results: self._highlight_index = max(self._highlight_index, 0) else: self._highlight_index = max(self._highlight_index, 1) if self._highlight_index > -1 and self._highlight_index < len( self._results): e, sep = self._results[self._highlight_index] e.background_color = self._active_button_color self._scroll_update() def _highlight_reset(self): offset = -self._highlight_index self._highlight_update(offset) def _highlight_up(self): self._highlight_update(-1) def _highlight_down(self): self._highlight_update(+1) def on_stop(self): pygame.display.quit() pass
class FoodScreen(Screen): def __init__(self, **kwargs): super(FoodScreen, self).__init__(**kwargs) self.name = "food" if not connected(): self.add_widget(ConnErrorScreen()) return self.scrollView = ScrollView(do_scroll_x=False, do_scroll_y=True, size_hint=(1, .8), id="food_scroll") # Headers self.headers = GridLayout(cols=3, size_hint=(1, .1)) self.headers.add_widget( Label(text="Name", size_hint=(.4, 1), color=[0, 0, 0, 1])) self.headers.add_widget( Label(text="Time until Expiry", size_hint=(.4, 1), color=[0, 0, 0, 1])) self.headers.add_widget( RefreshButton(source=refresh_img, size_hint=(.2, 1))) # MainGrid containing everything self.mainGrid = GridLayout(rows=3) # FoodGrid containing FoodGrid rows containing food items self.foodGrid = GridLayout(cols=3, row_force_default=True, row_default_height=50, size_hint_y=None) for food in food_list: self.foodGrid.add_widget( Label(text=food[0], size_hint=(.4, .2), color=[0, 0, 0, 1])) self.foodGrid.add_widget( Label(text=time_to_expiry(food[1]), size_hint=(.4, .2), color=[0, 0, 0, 1])) if near_expiry(time_to_expiry(food[1])): self.foodGrid.add_widget( Image(source=expiring_img, size_hint=(.2, .2))) elif time_to_expiry(food[1]) == "Expired": self.foodGrid.add_widget( Image(source=expired_img, size_hint=(.2, .2))) else: self.foodGrid.add_widget( Label(text="", size_hint=(.2, .2), color=[0, 0, 0, 1])) # Make sure the height is such that there is something to scroll. self.foodGrid.bind(minimum_height=self.foodGrid.setter('height')) self.scrollView.add_widget(self.foodGrid) # Footer self.footer = GridLayout(cols=3, size_hint=(1, .1)) self.removeButton = Button(text="Remove", size_hint=(.3, 1), color=[0, 0, 0, 1]) self.buzzerButton = BuzzerButton(source=alarm_on_img, size_hint=(.4, 1)) self.buzzerButton.bind(pressed=self.remove_buzzer) self.homeButton = HomeButton(text="Home", size_hint=(.4, 1), color=[0, 0, 0, 1]) self.addButton = AddButton(text="Add new entry", size_hint=(.3, 1), color=[0, 0, 0, 1]) self.footer.add_widget(self.removeButton) if (True in [food[2] for food in food_list]): self.footer.add_widget(self.buzzerButton) else: self.footer.add_widget(self.homeButton) self.footer.add_widget(self.addButton) self.mainGrid.add_widget(self.headers) self.mainGrid.add_widget(self.scrollView) self.mainGrid.add_widget(self.footer) self.add_widget( Image(source=background_img, size_hint=(1, 1), keep_ratio=False, allow_stretch=True)) self.add_widget(self.mainGrid) def remove_buzzer(self, instance, value): self.footer.remove_widget(self.buzzerButton) self.footer.remove_widget(self.addButton) self.footer.add_widget(self.homeButton) self.footer.add_widget(self.addButton) def update_highlight(self, instance, value): instance.rect.pos = instance.pos instance.rect.size = instance.size
class DemoApp(App): """We create an application class called 'DemoApp' that subclasses from the Kivy 'App' class. It will inherit all of the 'App' class functionality and we override methods or add our own to introduce new functionality that's specific to our application. """ '''Here we declare class instance variables to hold onto widgets that we'll want to access throughout the class. It's not strictly necessary to declare these here since Python lets you declare new instance variables anywhere; however, it's considered good form to declare all instance variables here or in an '_init_()' method. If you create instance variables in random locations throughout the class, you can severely reduce readability. The underscore at the beginning of the variable name is a convention to indicate that the variable is 'private' to this class and not intended to be accessed outside of this class. This is also not strictly necessary and some Python developers might claim that private variables are an anti-pattern; however, I come from a C/C++ background, so I like the encapsulation and readability hints that private variables provide.''' _layout = None # This will hold our root layout widget _disappearing_label = None # This will hold the label widget def build(self): """build() is a method provided by the App class. The App object calls this during initialization after run() is called. We override build() to create our widget tree and we return the 'root' widget of our tree. The App object will embed this widget and all of its children in the main window. """ '''Create a Grid layout to hold our other widgets. A "layout" is a special type of Kivy widget that contains other widgets and determines where they appear relative to each other. Read more about the Grid layout here: https://kivy.org/docs/api-kivy.uix.gridlayout.html''' self._layout = GridLayout(cols=2) '''Create a label. We're going to attach this to the grid layout and then never reference it again, so we'll just use a local variable (no 'self') to temporarily hold onto it until we attach it to the layout. Note that, at this point, we've created a Label object in memory, but it's not attached to anything that will cause it to be displayed. If we did nothing else with this label, you'd never see it. Below, we'll attach the label to a layout, which will be attached to the main window. Note that even though the local variable 'text_label' will go out of scope at the end of this function, the Grid layout will hold a reference to the Label object after we attach it with 'add_widget()' below, so the Python garbage collector will not delete the Label object.''' text_label = Label(text="Text:", font_size=150) '''Create another label. We're going to attach this to the grid layout below. Later, we'll detach and reattach it repeatedly, so we want to hold onto it at the class level. (hence 'self')''' self._disappearing_label = Label(text="Hello!", font_size=150) '''Add the first label to the layout.''' self._layout.add_widget(text_label) '''Add the second label to the layout.''' self._layout.add_widget(self._disappearing_label) '''Return the grid layout as our root widget. Kivy will attach this to the main window, which will then display the layout and its children (the two labels).''' return self._layout def on_start(self): """Event handler for the `on_start` event which is fired after initialization (after build() has been called) but before the application has started running. We're going to use this event to schedule our timer that will modify the UI. We could have scheduled this in the 'build()' method above, but it's more proper to keep that method limited to code that constructs the UI and put other startup code in this 'on_start()' method instead. """ '''Schedule a Kivy timer to call our _update() method every 1 seconds.''' Clock.schedule_interval(self._update, 1.0) def _update(self, delta_time): """_update() is our own private method that Kivy's Clock will call periodically to add/remove the "disappearing" label. The Clock.schedule_interval() call expects a method with one parameter ('delta_time'). The Clock will pass the time elapsed since the last call (or the original scheduling in the case of the first call). We do not need this value for our purposes, so we'll just leave the parameter unused.""" if self._disappearing_label is None: '''If the '_disappearing_label' instance variable is 'None', then we assume the label has been removed from the Grid layout and deleted. Create a new Label and add it to the Grid layout.''' '''Add the label to the layout.''' self._disappearing_label = Label(text="Hello!", font_size=150) '''Add the label to the layout.''' self._layout.add_widget(self._disappearing_label) else: '''If the '_disappearing_label' instance variable is not 'None', then we assume the label is currently attached to the Grid layout. Remove it from the layout and delete it.''' '''Remove the label from the layout.''' self._layout.remove_widget(self._disappearing_label) '''Set the instance variable to 'None'. Now we've 'lost' the Label object since nothing points to it. The Python garbage collector will eventually detect this and free the orphaned 'Label' object from memory (but we don't have to worry about that).''' self._disappearing_label = None
class MXNApp(App): # switch to proof whether the explorer-component was created boolExplorer = BooleanProperty(True) # switch to proof whether the mxnEnvelope-component was created boolMXNEnvelope = BooleanProperty(True) # switch to proof whether the material-editor was created boolMaterialEditor = BooleanProperty(True) # switch to proof whether the reinforcement-editor was created boolReinforcementEditor = BooleanProperty(True) ''' Build the application ''' # constructor def build(self): self.content = GridLayout(cols=1, spacing=Design.spacing) bar = AppActionBar() self.content.add_widget(bar) self.cs = CrossSection(app=self) self.csShape = self.cs.csRectangle # cross-section-editor is the default view # view is the focus-component self.view = self.cs self.create_cross_section_editor() return self.content ''' create the material-editor ''' def create_material_editor(self): self.materialEditor = MaterialEditor(csShape=self.cs) ''' create the cross section-editor ''' def create_cross_section_editor(self): self.csEditor = CrossSectionEditor(cs=self.cs, csShape=self.cs.csRectangle, app=self) self.csEditor.add_view() self.content.add_widget(self.csEditor) self.view = self.csEditor ''' create the reinforcement-editor ''' def create_reinforcement_editor(self): self.reEditor = ReinforcementEditor() self.reEditor.set_cross_section(self.cs) ''' create the explorer where you can see the stress-strain-behavior of the cross section ''' def create_explorer(self): self.explorer = Explorer(csShape=self.csShape, bars=self.csShape.bars, layers=self.csShape.layers) self.cs.explorer = self.explorer ''' create the mxnEmelope ''' def create_mxnEnvelope(self): if self.boolExplorer: self.create_explorer() self.boolExplorer = False self.mxnEmelope = MXNEnvelop(explorer=self.explorer) ############################################################################# # Attention:When you want write a new show-method than make sure # # that actually component is remove from the widget and set # # the content to the showed component # ############################################################################# ''' show the material-editor ''' def show_material_editor(self): #if the material-editor has not been created if self.boolMaterialEditor: self.create_material_editor() #change the switch self.boolMaterialEditor = False self.content.remove_widget(self.view) self.content.add_widget(self.materialEditor) self.view = self.materialEditor ''' show the cs editor ''' def show_cross_section_editor(self): #if the reinforcement-editor has not been created if self.boolReinforcementEditor: self.create_reinforcement_editor() #change the switch self.boolReinforcementEditor = False self.reEditor.remove_view() if not self.csEditor.containsView: self.csEditor.add_view() self.content.remove_widget(self.view) self.content.add_widget(self.csEditor) self.view = self.csEditor ''' show the reinforcement-editor ''' def show_reinforcement_editor(self): #if the reinforcement-editor has not been created if self.boolReinforcementEditor: self.create_reinforcement_editor() #change the switch self.boolReinforcementEditor = False self.csEditor.remove_view() if not self.reEditor.containsView: self.reEditor.add_view() self.content.remove_widget(self.view) self.content.add_widget(self.reEditor) self.view = self.reEditor ''' show the strain-stress-explorer ''' def show_explorer(self): #if the explorer has not been created if self.boolExplorer: self.create_explorer() #change the switch self.boolExplorer = False self.csEditor.remove_view() self.content.remove_widget(self.view) self.content.add_widget(self.explorer) self.update_explorer() self.explorer.update_explorer() self.view = self.explorer ''' show the mxn-emelope ''' def show_mxnEmelope(self): #if the mxn-envelope has not been created if self.boolMXNEnvelope: self.create_mxnEnvelope() #change the switch self.boolMXNEnvelope = False self.csEditor.remove_view() self.content.remove_widget(self.view) self.content.add_widget(self.mxnEmelope) self.view = self.mxnEmelope self.update_explorer() self.mxnEmelope.calculation() ''' update the cross-section-information of the explorer ''' def update_explorer(self): if self.csEditor.csShape == self.cs.csDoubleT: self.explorer.update_csShape(self.cs.csDoubleT, self.cs.csDoubleT.get_total_height(), self.cs.csDoubleT.layers, self.cs.csDoubleT.bars) elif self.csEditor.csShape == self.cs.csCircle: self.explorer.update_csShape(self.cs.csCircle, self.cs.csCircle.d, self.cs.csCircle.layers, self.cs.csCircle.bars) elif self.csEditor.csShape == self.cs.csRectangle: self.explorer.update_csShape(self.cs.csRectangle, self.cs.csRectangle.ch, self.cs.csRectangle.layers, self.cs.csRectangle.bars) elif self.csEditor.csShape == self.cs.csT: self.explorer.update_csShape(self.cs.csT, self.cs.csT.get_total_height(),
class TabbedCEFBrowser(GridLayout): def __init__(self, urls=["http://www.rentouch.ch"], *largs, **dargs): super(TabbedCEFBrowser, self).__init__(cols=1, *largs, **dargs) gl = GridLayout(rows=1, size_hint=(1, None), height=controls_size) self.current_tab = None self.__tab_bar_scroll = ScrollView(size_hint=(1, 1)) self.__tab_bar_grid = GridLayout(rows=1, size_hint=(None, 1)) self.__tab_bar_grid.bind( minimum_width=self.__tab_bar_grid.setter("width")) last_tab = None for url in urls: this_tab = TabbedCEFBrowserTab(self, url, url) this_tab.last_tab = last_tab self.__tab_bar_grid.add_widget(this_tab) last_tab = this_tab self.current_tab = last_tab self.__tab_bar_scroll.add_widget(self.__tab_bar_grid) self.__tab_bar_scroll.bind(height=self.__tab_bar_grid.setter("height")) gl.add_widget(self.__tab_bar_scroll) self.__tab_bar_new = Button( text="+", font_size=controls_size/2, size_hint=(None, 1), width=controls_size) self.__tab_bar_new.bind(on_press=self._on_new_tab) gl.add_widget(self.__tab_bar_new) self.__control_bar_grid = GridLayout( rows=1, size_hint=(1, None), height=controls_size) self._back_button = Button( text="<", font_size=controls_size/2, size_hint=(None, 1), width=controls_size) self._back_button.bind(on_press=self._on_back_press) self._forward_button = Button( text=">", font_size=controls_size/2, size_hint=(None, 1), width=controls_size) self._forward_button.bind(on_press=self._on_forward_press) self._url_input = TextInput( text="http://", font_size=controls_size/2, size_hint=(1, 1), multiline=False) self._url_input.bind(focus=self._on_url_focus) self._url_input.bind(on_text_validate=self._on_url_validate) self._load_button = Button( text="Go", font_size=controls_size/2, size_hint=(None, 1), width=controls_size) self._load_button.bind(on_press=self._on_load_button) self.__control_bar_grid.add_widget(self._back_button) self.__control_bar_grid.add_widget(self._forward_button) self.__control_bar_grid.add_widget(self._url_input) self.__control_bar_grid.add_widget(self._load_button) self._current_browser = CEFBrowser() self.add_widget(gl) self.add_widget(self.__control_bar_grid) self.add_widget(self._current_browser) self.select_first_tab() def _focus_url_input(self, *largs): self._url_input.focus = True def _on_new_tab(self, but): self.add_tab(TabbedCEFBrowserTab( self, "http://google.com", "Google")) Clock.schedule_once(self._focus_url_input, 0) def _on_back_press(self, back_button): self._current_browser.go_back() def _on_forward_press(self, forward_button): self._current_browser.go_forward() def _on_url_focus(self, url_input, new_focus): if new_focus: def fn(*largs): url_input.select_all() Clock.schedule_once(fn, 0) self._load_button.text = "Go" else: url_input.text = self._current_browser.url self._load_button.text = \ "x" if self._current_browser.is_loading else "r" def _on_url_validate(self, url_input): self._current_browser.url = self._url_input.text def _on_load_button(self, load_button): if self._url_input.focus: self._current_browser.url = self._url_input.text elif self._current_browser.is_loading: self._current_browser.stop_loading() else: self._current_browser.reload() def select_first_tab(self): for tab in self.__tab_bar_grid.children: tab.select() break @property def tabs(self): return self.__tab_bar_grid.children def add_tab(self, new_tab): self.__tab_bar_grid.add_widget(new_tab) new_tab.select() def remove_tab(self, remove_tab): self.__tab_bar_grid.remove_widget(remove_tab) self.current_tab = remove_tab.last_tab remove_tab.last_tab.select() def _set_tab(self, new_tab): if self.current_tab != new_tab: ct = self.current_tab tmp = ct while tmp: if tmp.last_tab == new_tab: tmp.last_tab = new_tab.last_tab tmp = tmp.last_tab new_tab.last_tab = ct self.current_tab = new_tab try: self._current_browser.unbind(url=self._url_input_set_text) except: pass Clock.schedule_once(functools.partial( self._old_tab_remove_keyboard, self._current_browser)) self.remove_widget(self._current_browser) self._url_input.text = new_tab.url self._current_browser = new_tab.cef_browser self.add_widget(self._current_browser) self._current_browser.bind(url=self._url_input_set_text) def _url_input_set_text(self, browser, url): self._url_input.text = url if self._url_input.focus: self._url_input.select_all() def _old_tab_remove_keyboard(self, browser, *largs): print("old_tab_remove_keyboard", browser) browser.focus = False
class ScreenmixApp(App): # switch to proof whether the ack has been created boolACK = BooleanProperty(True) # switch to proof whether the material-editor has been created boolME = BooleanProperty(True) ''' Build the application ''' def build(self): bar = AppActionBar() self.content = GridLayout(cols=1, spacing=Design.spacing) self.content.add_widget(bar) self.cs = CrossSection() self.content.add_widget(self.cs) # Cross Section is the default view self.contentLayout = self.cs return self.content ''' create the ask_view ''' def create_ack_view(self): self.ack= Ack() self.cs.shapeRectangle.ack = self.ack.ackRect self.ack.ackRect.cs = self.cs.shapeRectangle self.ack.ackRect.create_gui() # when you add more shapes, make sure that the # shapes has a ownAck ''' create the material-editor ''' def create_material_editor(self): self.materialEditor = Material_Editor() self.materialEditor.set_cross_section(self.cs) ########################################################################## # Attention:When you want write a new show-method than you must make sure # # that actually component is remove from the widget and set # # the contentLayout to the showed component # ########################################################################## ''' show the ack-view ''' def show_ack_view(self): if self.boolACK: self.create_ack_view() self.boolACK=False self.ack.content.update() self.content.remove_widget(self.contentLayout) self.content.add_widget(self.ack) self.contentLayout = self.ack ''' show the cross section view ''' def show_cross_section_view(self): self.content.remove_widget(self.contentLayout) self.content.add_widget(self.cs) self.contentLayout = self.cs ''' show the material-editor ''' def show_material_editor(self): if self.boolME: self.create_material_editor() self.boolME=False self.content.remove_widget(self.contentLayout) self.content.add_widget(self.materialEditor) self.contentLayout = self.materialEditor
class ROACH(Empty): def __init__(self, **kwargs): super(ROACH, self).__init__(kwargs=kwargs) self.config_manager = LoadSaveConfig(os.path.dirname(os.path.realpath(__file__)) + '/roach_configurations') big_one = BoxLayout(orientation='vertical') self.reg_array = {} self.reg_cont = 0 self.bram_array = {} self.bram_cont = 0 #self.snapshot_array = {} #self.snapshot_cont = 0 self.prog_dev = False self.bof_path = '' self.sources = [] self.function = [] # reg layout roach_connection_info = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30)) roach_register = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,40)) ip_label = Label(text='IP :') port_label = Label(text='Port :') self.ip = TextInput(multiline=False) self.port = TextInput(multiline=False, Text='7417') roach_connection_info.add_widget(ip_label) roach_connection_info.add_widget(self.ip) roach_connection_info.add_widget(port_label) roach_connection_info.add_widget(self.port) clear_button = Button(text='clear', size_hint=(0.33,1)) save_button = Button(text='save', size_hint=(0.33,1)) clear_button.bind(on_press=self.clear_button) save_button.bind(on_press=self.button_save_all) self.program_button = ToggleButton(text='program', size_hint=(0.33,1)) buttons_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30)) buttons_layout.add_widget(clear_button) buttons_layout.add_widget(save_button) buttons_layout.add_widget(self.program_button) new_reg_label = Label(text='Initial Values', size_hint=(0.6,None), height=40) new_reg = Button(text='new reg', size_hint=(0.4,None), height=40) new_reg.bind(on_press=self.add_registers) roach_register.add_widget(new_reg_label) roach_register.add_widget(new_reg) ##### Regiter container self.reg_container = GridLayout(cols=1, spacing=0, size_hint_y=None)#row_default_height=30) self.reg_container.bind(minimum_height=self.reg_container.setter('height')) scroll_root = ScrollView(size_hint=(1,1), size=(1, 125)) scroll_root.add_widget(self.reg_container) #### free_running_label_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30)) add_free_running_label = Label(text="Free Running", size_hint=(0.45,1)) free_running_label_layout.add_widget(add_free_running_label) free_running = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30)) add_free_running_bram = Button(text = 'New BRAM', size_hint=(0.30,1)) add_free_running_reg = Button(text = 'New Reg', size_hint=(0.25,1)) add_free_running_snapshot = Button(text = 'SnapShot', size_hint=(0.25,1)) add_free_running_bram.bind(on_press=self.add_free_running) add_free_running_reg.bind(on_press=self.add_register_free_running) add_free_running_snapshot.bind(on_press=self.add_snapshot_free_running) free_running.add_widget(add_free_running_bram) free_running.add_widget(add_free_running_reg) free_running.add_widget(add_free_running_snapshot) #### free run container self.free_run_container = GridLayout(cols=1, spacing = 3,size_hint=(1,None), size=(1,30)) self.free_run_container.bind(minimum_height=self.free_run_container.setter('height')) scroll_root_free_run = ScrollView(size_hint=(1,1), size=(1,195), scroll_type=['bars']) scroll_root_free_run.add_widget(self.free_run_container) scroll_root_free_run.bar_width = 10 #### size_ = 30 name_config = Button(text='Name',size_hint=(0.25,None), height=size_) self.name_config_input = TextInput(size_hint=(0.5,None), height=size_) buton_bof_file = Button(text='Add bof',size_hint=(0.25,None), height=size_) print os.path.dirname(os.path.realpath(__file__)) + '/roach_configurations' name_config.bind(on_press=self.open_look_directory) fc = BofFileChooserIconView(self.set_bof_path) self.file_choose_popup = Popup(title='Choose Bof', auto_dismiss=False, content=fc,\ size_hint=(None, None), size=(400,400)) fc.set_popup(self.file_choose_popup) buton_bof_file.bind(on_press=self.file_choose_popup.open) name = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30)) name.add_widget(name_config) name.add_widget(self.name_config_input) name.add_widget(buton_bof_file) ## store or plot big_one.add_widget(name) big_one.add_widget(roach_connection_info) big_one.add_widget(buttons_layout) big_one.add_widget(roach_register) big_one.add_widget(scroll_root) big_one.add_widget(free_running_label_layout) big_one.add_widget(free_running) big_one.add_widget(scroll_root_free_run) padding_layout = BoxLayout() #big_one.add_widget(padding_layout) self.add_widget(big_one) self.do_extraction = None def open_look_directory(self, instance): fc_conf = BofFileChooserIconView(self.load_data, path=os.path.dirname(os.path.realpath(__file__)) + '/roach_configurations' , filter=['*.pkl']) self.file_roch_popup = Popup(title='Choose Configuration', auto_dismiss=False, content=fc_conf,\ size_hint=(None, None), size=(400,400)) fc_conf.set_popup(self.file_roch_popup) self.file_roch_popup.open() def add_register_free_running(self, instance): self.load_register_free_running('','') def load_register_free_running(self, value_, name_): bram = self.create_registers(value_, name_, self.free_run_container, self.remove_from_widget_list_free_run, \ str(self.bram_cont)) self.bram_array[str(self.bram_cont)] = bram bram.set_extraction_function(self.do_extraction) self.bram_cont += 1 def add_registers(self, instance): self.load_registers("","", self.reg_container) def load_registers(self, values_, name_, where_load_): reg_val = self.create_registers(values_, name_, where_load_, self.remove_from_widget_list_config, str(self.reg_cont)) self.reg_array[str(self.reg_cont)] = reg_val self.reg_cont += 1 def create_registers(self, values_, name_, where_load_, remove_function_, cont_key_): size_ = 30 data = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) label_name = Label(text='Name', size_hint=(0.225,None), height=size_) value_name = TextInput( size_hint=(0.225,None), height=size_) label_val = Label(text='Value', size_hint=(0.225,None), height=size_) value_val = TextInput( size_hint=(0.225,None), height=size_) delate = Button(text='-', size_hint=(0.1,None), height=size_) delate.bind(on_press=lambda instant:\ remove_function_(data, cont_key_))# where_load_.remove_widget(data)) data.add_widget(label_name) data.add_widget(value_name) data.add_widget(label_val) data.add_widget(value_val) data.add_widget(delate) value_name._set_text(name_) value_val._set_text(values_) where_load_.add_widget(data) return Register(value_name, value_val) def add_free_running(self, instance): self.load_free_running('i', '', [], '','') def is_active(self): return True def activate_extract(self, f): self.do_extraction = f def get_config(self): dic_return = {} regs = [] keys = self.reg_array.keys() keys.sort() for a_reg in keys: aux_data = self.reg_array[a_reg] reg_name = aux_data.get_name() reg_val = aux_data.get_value() regs.append((reg_name, reg_val)) dic_return['reg'] = regs brams = [] keys_ = self.bram_array.keys() keys_.sort() for bram in keys_: brams.append(self.bram_array[bram].info_dictionary()) dic_return['bram'] = brams dic_return['ip'] = self.ip._get_text() dic_return['port'] = self.port._get_text() dic_return['bof_path'] = self.bof_path dic_return['name'] = self.name_config_input._get_text() dic_return['progdev'] = True if self.program_button.state == 'down' else False source_dic_config = {} for a_source in self.sources: source_dic_config.update( a_source.save_config_dictionary()) dic_return['sources'] = source_dic_config function_dic_config = {} for a_function in self.function: function_dic_config.update(a_function.sava_config_dictionary()) dic_return['functions'] = function_dic_config dic_return['wich'] = self.which_roach() # this line saves the dictionary to file with pikle self.config_manager.store_dictionary(dic_return) dic_return['instance'] = self.get_controller_fpga_insctance() return dic_return def get_controller_fpga_insctance(self): pass def set_bof_path(self, path): if len(self.name_config_input.text) <1: Popup(content=Label(text='Enter Name'), size_hint=(None,None),size=(200,100)).open() return self.bof_path = self.config_manager.copy_bof_to_folder(path, self.name_config_input._get_text()) self.program_button.state = "down" def load_data(self, path): self.clean_all() dic = self.config_manager.load_dictionary(path) try: if dic['wich'] != self.which_roach(): return except: pass regs = dic['reg'] for a_reg in regs: self.load_registers(a_reg[1], a_reg[0], self.reg_container) brams = dic['bram'] for a_bram in brams: if a_bram['is_bram']: try: self.load_free_running(a_bram['data_type'],a_bram['size'],a_bram['bram_names'],a_bram['acc_len_reg'], \ a_bram['array_id'], a_bram['store'], a_bram['plot']) except: self.load_free_running(a_bram['data_type'],a_bram['size'],a_bram['bram_names'],a_bram['acc_len_reg'], \ a_bram['array_id']) else: if 'snap' in a_bram: self.load_snapshot_free_running(a_bram['name']) else: self.load_register_free_running(a_bram['reg_value'], a_bram['reg_name']) self.ip._set_text(dic['ip']) self.port._set_text(dic['port']) self.program_button.state = 'down' if dic['progdev'] else 'normal' self.bof_path = os.path.dirname(os.path.realpath(__file__)) + \ '/roach_configurations/' + dic['name'] + '/' + dic['name'] + '.bof' self.name_config_input._set_text(dic['name']) try: for a_source in self.sources: a_source.set_configuration(dic['sources']) except Exception as e: pass for a_function in self.function: a_function.set_configuration(dic['functions']) self.do_extraction() def load_free_running(self, a_data_type, array_size_, real_imag_list_, acc_len_reg_name_, array_label_, store_ = False, plot_ = False): size_ = 30 data = BoxLayout(orientation='vertical',size_hint=(1, None), size=(1,8*size_)) # plot_label = Label(text='Plot data:', size_hint=(0.4,1)) plot_toogle = ToggleButton(text='Plot Data', size_hint=(0.5,1)) store_data = ToggleButton(text='Store Data', size_hint=(0.5,1)) handle_data = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30)) handle_data.add_widget(plot_toogle) handle_data.add_widget(store_data) data_type_label = Label(text='Tipo de Dato', size_hint=(0.4,None), height=size_) data_type_spinner = Spinner( # default value shown text=a_data_type, # available values values=['c', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'f', 'd'], # just for positioning in our example size_hint=(0.3, None), size = (1, size_) ) delate_label = Label(text='Quitar', size_hint=(0.2,None), height=size_) delate_me = Button(text='-', size_hint=(0.1,None), height=size_) str_cont = str(self.bram_cont) delate_me.bind(on_press=lambda instance:self.remove_from_widget_list_free_run(data, str_cont)) id_label = Label(text='array name',size_hint=(0.45, None), height=size_) id_input = TextInput(size_hint=(0.45, None), height=size_) size_label = Label(text='size', size_hint=(0.45, None), height=size_) size_input = TextInput(size_hint=(0.45, None), height=size_) add_new_array_to_merge = Button(text='+',size_hint=(None, None), height=size_, wide = 3*size_) real_imag = GridLayout(cols=1, spacing = 3,size_hint=(1, None), size=(1,60)) real_imag.bind(minimum_height=real_imag.setter('height')) scroll_real_imag = ScrollView(size_hint=(0.8,None), size=(1,2*size_)) scroll_real_imag.add_widget(real_imag) acc_len_reg_name_label = Label(text='acc len reg_name',size_hint=(0.5,None), height=size_) acc_len_reg_name_input = TextInput(size_hint=(0.5, None), height=size_) data_type = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) data_type.add_widget(data_type_label) data_type.add_widget(data_type_spinner) data_type.add_widget(delate_label) data_type.add_widget(delate_me) data_id = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) data_id.add_widget(id_label) data_id.add_widget(id_input) data_size = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) data_size.add_widget(size_label) data_size.add_widget(size_input) data_add_merge_data = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) data_add_merge_data.add_widget(add_new_array_to_merge) data_name = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,2*size_)) data_name.add_widget(scroll_real_imag) data_acc_len_reg = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) data_acc_len_reg.add_widget(acc_len_reg_name_label) data_acc_len_reg.add_widget(acc_len_reg_name_input) data.add_widget(handle_data) data.add_widget(data_type) data.add_widget(data_id) data.add_widget(data_size) data.add_widget(data_add_merge_data) data.add_widget(data_name) data.add_widget(data_acc_len_reg) bram = BRAMArray( size_input, acc_len_reg_name_input,real_imag, id_input, data_type_spinner, store_data , plot_toogle) bram.set_extraction_function(self.do_extraction) add_new_array_to_merge.bind(on_press=lambda instance: bram.add_real_imag_widget()) self.bram_array[str(self.bram_cont)] = bram self.bram_cont += 1 self.free_run_container.add_widget(data) size_input._set_text(array_size_) acc_len_reg_name_input._set_text(acc_len_reg_name_) id_input._set_text(array_label_) store_data.state = 'down' if store_ else 'normal' plot_toogle.state = 'down' if plot_ else 'normal' for real_imag_pair in real_imag_list_: bram.load_real_imag_widget(real_imag_pair[0], real_imag_pair[1]) def remove_from_widget_list_free_run(self, widget_, list_cont_val_): self.free_run_container.remove_widget(widget_) del self.bram_array[list_cont_val_] def remove_from_widget_list_config(self, widget_, list_cont_val_): self.reg_container.remove_widget(widget_) del self.reg_array[list_cont_val_] def clean_all(self): self.free_run_container.clear_widgets() self.reg_container.clear_widgets() self.bram_array = {} self.reg_array = {} self.bram_cont = 0 self.reg_cont = 0 self.name_config_input.text = '' self.bof_path = '' self.ip.text = '' self.port.text = '' self.program_button.state = 'normal' def clear_button(self, inatance): self.clean_all() def button_save_all(self, instance): self.get_config() def pass_source(self, sources_): self.sources = sources_ def pass_functions(self, functions_): self.function = functions_ def which_roach(self): pass def add_snapshot_free_running(self, instance): self.load_snapshot_free_running('') def load_snapshot_free_running(self,snapshot_name_): size_ = 30 data = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_)) snap_name_label = Label(text='Snap Name',size_hint=(0.4,None), height=size_) snap_name_value = TextInput(size_hint=(0.4,None), height=size_) snap_name_value.text = snapshot_name_ delate_me = Button(text='-',size_hint=(0.1,None), height=size_) str_cont = str(self.bram_cont) delate_me.bind(on_press=lambda instance:\ self.remove_from_widget_list_free_run(data, str_cont)) snap = SnapShot(snap_name_value) snap.set_extraction_function(self.do_extraction) data.add_widget(snap_name_label) data.add_widget(snap_name_value) data.add_widget(delate_me) self.free_run_container.add_widget(data) self.bram_array[str(self.bram_cont)] = snap self.bram_cont += 1
class ContactScreen(Screen): def __init__(self, screen_manager, **kwargs): super(ContactScreen, self).__init__(**kwargs) self.screen_manager = screen_manager self.contacts_buttons = [] self.database = None self.client_transport = None self.new_messages = {} self.main_layout = GridLayout(cols=1) self.header_layout = GridLayout(cols=2, size_hint=(1, 0.1)) self.scroll_view = ScrollView(size_hint=(1, 0.8), size=(100, 100)) # Create menu self.menu_button = DropDown() for name in ['Add contact', 'Statistic']: btn = Button(text=f'{name}', size_hint_y=None, height=30) btn.bind(on_release=lambda btn: self.menu_button.select(btn.text)) self.menu_button.add_widget(btn) self.main_button = Button(text='Menu', size_hint=(.2, .5)) self.main_button.bind(on_release=self.menu_button.open) self.menu_button.bind( on_select=lambda instance, x: self.show_screen(x)) self.label = CLabel(size_hint=(0.9, 1)) self.contacts_layout = GridLayout(cols=1, size_hint_y=None, row_force_default=True, row_default_height=40) self.contacts_layout.bind( minimum_height=self.contacts_layout.setter('height')) self.header_layout.add_widget(self.main_button) self.header_layout.add_widget(self.label) self.scroll_view.add_widget(self.contacts_layout) self.main_layout.add_widget(self.header_layout) self.main_layout.add_widget(self.scroll_view) self.add_widget(self.main_layout) # Before show self.on_pre_enter = self.update_contact_list def update_contact_list(self, new_message=None): for button in self.contacts_buttons: self.contacts_layout.remove_widget(button) self.contacts_buttons.clear() contact_list = self.get_contact_list() for contact in contact_list: contact_grid = GridLayout(cols=2, size_hint=(1, 0.1)) button = Button(text=contact, id=contact, size_hint_y=None, height=40) contact_grid.add_widget(button) if contact in self.new_messages: col = self.new_messages[contact] if col: label = Label(text=str(col), size_hint=(.1, .1)) contact_grid.add_widget(label) self.contacts_buttons.append(contact_grid) self.contacts_layout.add_widget(contact_grid) button.on_press = partial(self.go_to_chat, contact) def go_to_chat(self, contact_name): self.screen_manager.current = 'chat' chat = self.screen_manager.get_screen('chat') chat.load_chat(contact_name) if contact_name in self.new_messages: self.new_messages[contact_name] = 0 def show_info_screen(self, *args): self.screen_manager.current = 'info' self.screen_manager.get_screen('info').set_message(*args) def set_objects(self, database, client_transport): self.database = database self.client_transport = client_transport self.label.text = f'Hello {self.client_transport.client_login}! ' \ f'Here is your contact list.' def get_contact_list(self): contacts_list = self.database.get_contacts() return contacts_list def show_label(self, *args): if self.screen_manager.current == 'contacts': sender = args[0] if not self.database.is_contact(sender): text_title = f'New message from {sender}' text_label = f'Received a new message from {sender}, ' \ f'add contact {sender} and open chat with him?' create_message_window(text_title, text_label, self.new_contact, sender) else: if sender in self.new_messages: self.new_messages[sender] += 1 else: self.new_messages[sender] = 1 self.update_contact_list(new_message=sender) def connect_contacts_signal(self, client_obj): client_obj.new_message_signal_contacts.connect(self.show_label) def show_screen(self, name): if name == 'Add contact': self.screen_manager.current = 'add_contact' elif name == 'Statistic': self.screen_manager.current = 'statistic' self.screen_manager.get_screen('statistic').get_database( self.database) def go_to_login(self): self.screen_manager.current = 'login' def new_contact(self, user): if self.client_transport.add_contact(user): self.update_contact_list() text_title = 'Success!' text_label = 'Contact successfully added.' create_message_window(text_title, text_label, self.go_to_chat, user) else: text_title = 'Error!' text_label = 'Lost server connection.' create_message_window(text_title, text_label, self.go_to_login)
class Add_User_Page(GridLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.output_path = 'Output/' self.cols = 2 self.flag = 0 self.padding = [100, 100, 100, 100] self.spacing = [20, 20] self.begin = Button(text='BEGIN', font_size=30, italic=True, background_color=[1, 255, 1, 1]) self.begin.bind(on_press=self.start) self.add_widget(self.begin) self.back = Button(text='GO BACK', font_size=30, italic=True, background_color=[255, 1, 1, 1]) self.back.bind(on_press=self.goback) self.add_widget(self.back) def start(self, instance): global camera_index self.flag = 1 self.img = Image() self.layout = BoxLayout() self.layout.add_widget(self.img) self.remove_widget(self.begin) self.remove_widget(self.back) self.add_widget(self.layout) self.name = TextInput(multiline=False, size_hint=(.2, None), height=40) add = Button(text='ADD ME', font_size=30, italic=True, background_color=[255, 1, 1, 1]) back = Button(text='GO BACK', font_size=30, italic=True, background_color=[1, 1, 255, 1]) self.label = Label(text='Add Yourself!!', font_size=38, color=[255, 255, 255, 1]) add.bind(on_press=self.add) back.bind(on_press=self.goback) self.button_layout = GridLayout(rows=4, spacing=[20, 20]) self.button_layout.add_widget(self.name) self.button_layout.add_widget(add) self.button_layout.add_widget(back) self.button_layout.add_widget(self.label) self.add_widget(self.button_layout) self.capture = cv2.VideoCapture(camera_index) self.event = Clock.schedule_interval(self.update, 1.0 / 33.0) def update(self, instance): _, self.frame = self.capture.read() self.frame = extract_all_faces(self.frame) buf1 = cv2.flip(self.frame, 0) buf = buf1.tostring() texture = Texture.create(size=(self.frame.shape[1], self.frame.shape[0]), colorfmt='bgr') texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.img.texture = texture def add(self, instance): if len(self.name.text) != 0: ts = datetime.datetime.now() img_name = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) img_path = self.output_path + img_name cv2.imwrite(img_path, self.frame) print("[INFO] saved {}".format(img_name)) if image_enhance == 'on': if image_enhance_use_gpu == 'on': os.system('sh image_enhance_gpu.sh') elif image_enhance_use_gpu == 'off': os.system('sh image_enhance_cpu.sh') embedding, flag = generate_embedding(img_path) os.system('rm ./Output/*') if flag == 1: insertBLOB(self.name.text, embedding) self.button_layout.remove_widget(self.label) self.label = Label(text=self.name.text + ' Added', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) else: self.button_layout.remove_widget(self.label) self.label = Label(text='Zero/Multiple Faces Detected', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) else: self.button_layout.remove_widget(self.label) self.label = Label(text='Enter UserName', font_size=38, color=[255, 255, 255, 1]) self.button_layout.add_widget(self.label) def goback(self, instance): global usernames, embeddings if self.flag == 1: self.event.cancel() self.capture.release() self.remove_widget(self.layout) self.remove_widget(self.button_layout) self.__init__() embeddings, usernames = readAllBlobData() for username in usernames: if username not in attendance.keys(): attendance[username] = 'Absent' print(attendance) UI_interface.screen_manager.current = "Home"
class CreateProjectWindow(Screen): created_steps = OrderedDict() current_popup = None current_edited_step = None def __init__(self, **kwargs): super(CreateProjectWindow, self).__init__(**kwargs) self.main_layout = GridLayout(cols=1, padding=20) self.project_grid = GridLayout(cols=2, size=SIZE_PROJECT_GRID, size_hint=(1, None)) self.projects_inputs = list() for field in PROJECT_FIELDS: self.project_grid.add_widget(Label(text=field.capitalize())) text_input = TextInput(text='', multiline=False) self.projects_inputs.append(text_input) self.project_grid.add_widget(text_input) self.steps_creation_layout = GridLayout(cols=2, row_force_default=True, row_default_height=40) self.steps_inputs = list() for field in STEP_FIELDS: self.steps_creation_layout.add_widget( Label(text=field.capitalize())) text_input = TextInput(text='', multiline=False) self.steps_inputs.append(text_input) self.steps_creation_layout.add_widget(text_input) self.steps_layout = GridLayout(cols=1, spacing=5, padding=(0, 10, 0, 0), size_hint_y=None) self.steps_layout.bind( minimum_height=self.steps_layout.setter('height')) scroll_steps_layour = ScrollView(size_hint=(1, None), height=SIZE_STEPS_GRID[1]) scroll_steps_layour.add_widget(self.steps_layout) button_close = Button(text='Validate') button_close.bind(on_press=self.validate_step_popup) self.step_popup = Popup(title='Add Step', content=self.steps_creation_layout, auto_dismiss=False, size=SIZE_ADD_STEP, size_hint=SIZE_HINT_ADD_STEP) self.steps_creation_layout.add_widget(button_close) self.main_layout.add_widget(self.project_grid) self.main_layout.add_widget(scroll_steps_layour) self.add_widget(self.main_layout) def _flaten_steps(self, result, steps_list): result.extend(list(steps_list.keys())) return result.extend(self._flaten_steps(steps_list.inner_steps)) def get_text_projects_inputs(self): return { PROJECT_FIELDS[count]: input_.text for count, input_ in enumerate(self.projects_inputs) } def get_text_steps_inputs(self): return { STEP_FIELDS[count]: input_.text for count, input_ in enumerate(self.steps_inputs) } def validate_step_popup(self, instance): if self.current_popup == ADD: self.add_step(instance) elif self.current_popup == EDIT: self.edit_step(instance) elif self.current_popup == INNER_ADD: self.add_inner_step(instance) def empty_steps_inputs(self): for step in self.steps_inputs: step.text = "" def regenerate_layout(self, steps_list): for step_id in steps_list.keys(): self.delete_step(instance=None, step_id=step_id, layout_only=True) steps_to_treat = copy(self.created_steps) while steps_to_treat: step_id = next(iter(steps_to_treat)) step = self.created_steps[step_id] step.generate_step_grid_layout(self) for inner_step_id in step.inner_steps: inner_step = self.created_steps[inner_step_id] step.layout.add_widget(inner_step.layout) del steps_to_treat[inner_step.id] self.steps_layout.add_widget(step.layout) del steps_to_treat[step.id] def delete_step(self, instance, step_id, layout_only=False): self.steps_layout.remove_widget(self.created_steps[step_id].layout) if not layout_only: self.created_steps.pop(step_id) def add_inner_step(self, instance): step = self.created_steps[self.current_edited_step] inner_step = TempStep(data=self.get_text_steps_inputs(), callback=self, given_width=.8) step.add_inner_steps(inner_step) self.created_steps[inner_step.id] = inner_step self.regenerate_layout(self.created_steps) self.step_popup.dismiss() def add_step(self, instance=None, step_object=None): if not instance and not step_object: return step = TempStep(data=self.get_text_steps_inputs() if not step_object else step_object, callback=self) self.created_steps[step.id] = step self.steps_layout.add_widget(step.layout) self.step_popup.dismiss() def edit_step(self, instance=None): step = self.created_steps[self.current_edited_step] step.set_parameters_from_input(self.get_text_steps_inputs()) self.current_edited_step = None self.step_popup.dismiss() def add_inner_step_window(self, instance, step_id): self.current_popup = INNER_ADD self.current_edited_step = step_id self.step_popup.open() def edit_step_window(self, instance, step_id): self.current_popup = EDIT self.current_edited_step = step_id for index, step_input in enumerate(self.steps_inputs): step_input.text = getattr(self.created_steps[step_id], STEP_FIELDS[index]) self.step_popup.open() def add_step_window(self, instance=None): self.current_popup = ADD self.empty_steps_inputs() self.step_popup.open() def set_parameters(self, parent): button_add_step = Button(text="Add Step") button_add_step.bind(on_press=self.add_step_window) button_create = Button(text='Create') button_create.bind(on_press=parent.create_project) self.project_grid.add_widget(Widget()) self.project_grid.add_widget(button_add_step) self.project_grid.add_widget(Widget()) self.project_grid.add_widget(button_create)
class ContextMenu(TabbedPanel): '''ContextMenu class. See module documentation for more information. :Events: `on_select`: data Fired when a selection is done, with the data of the selection as first argument. Data is what you pass in the :meth:`select` method as first argument. `on_dismiss`: .. versionadded:: 1.8.0 Fired when the ContextMenu is dismissed either on selection or on touching outside the widget. ''' container = ObjectProperty(None) '''(internal) The container which will be used to contain Widgets of main menu. :data:`container` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`~kivy.uix.boxlayout.BoxLayout`. ''' main_tab = ObjectProperty(None) '''Main Menu Tab of ContextMenu. :data:`main_tab` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' bubble_cls = ObjectProperty(MenuBubble) '''Bubble Class, whose instance will be used to create container of ContextMenu. :data:`bubble_cls` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`MenuBubble`. ''' header_cls = ObjectProperty(MenuHeader) '''Header Class used to create Tab Header. :data:`header_cls` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`MenuHeader`. ''' attach_to = ObjectProperty(allownone=True) '''(internal) Property that will be set to the widget on which the drop down list is attached to. The method :meth:`open` will automatically set that property, while :meth:`dismiss` will set back to None. ''' auto_width = BooleanProperty(True) '''By default, the width of the ContextMenu will be the same as the width of the attached widget. Set to False if you want to provide your own width. ''' dismiss_on_select = BooleanProperty(True) '''By default, the ContextMenu will be automatically dismissed when a selection have been done. Set to False to prevent the dismiss. :data:`dismiss_on_select` is a :class:`~kivy.properties.BooleanProperty`, default to True. ''' max_height = NumericProperty(None, allownone=True) '''Indicate the maximum height that the dropdown can take. If None, it will take the maximum height available, until the top or bottom of the screen will be reached. :data:`max_height` is a :class:`~kivy.properties.NumericProperty`, default to None. ''' __events__ = ('on_select', 'on_dismiss') def __init__(self, **kwargs): self._win = None self.add_tab = super(ContextMenu, self).add_widget self.bubble = self.bubble_cls(size_hint=(None, None)) self.container = None self.main_tab = self.header_cls(text='Main') self.main_tab.content = ScrollView(size_hint=(1, 1)) self.main_tab.content.bind(height=self.on_scroll_height) super(ContextMenu, self).__init__(**kwargs) self.bubble.add_widget(self) self.bind(size=self._reposition) self.bubble.bind(on_height=self._bubble_height) def _bubble_height(self, *args): '''Handler for bubble's 'on_height' event. ''' self.height = self.bubble.height def open(self, widget): '''Open the dropdown list, and attach to a specific widget. Depending the position of the widget on the window and the height of the dropdown, the placement might be lower or higher off that widget. ''' # if trying to open a non-visible widget if widget.parent is None: return # ensure we are not already attached if self.attach_to is not None: self.dismiss() # we will attach ourself to the main window, so ensure the widget we are # looking for have a window self._win = widget.get_parent_window() if self._win is None: raise ContextMenuException( 'Cannot open a dropdown list on a hidden widget') self.attach_to = widget widget.bind(pos=self._reposition, size=self._reposition) self.add_tab(self.main_tab) self.switch_to(self.main_tab) self.main_tab.show_arrow = False self._reposition() # attach ourself to the main window self._win.add_widget(self.bubble) self.main_tab.color = (0, 0, 0, 0) def on_select(self, data): '''Default handler for 'on_select' event. ''' pass def dismiss(self, *largs): '''Remove the dropdown widget from the window, and detach itself from the attached widget. ''' if self.bubble.parent: self.bubble.parent.remove_widget(self.bubble) if self.attach_to: self.attach_to.unbind(pos=self._reposition, size=self._reposition) self.attach_to = None self.switch_to(self.main_tab) for child in self.tab_list[:]: self.remove_widget(child) self.dispatch('on_dismiss') def select(self, data): '''Call this method to trigger the `on_select` event, with the `data` selection. The `data` can be anything you want. ''' self.dispatch('on_select', data) if self.dismiss_on_select: self.dismiss() def on_dismiss(self): '''Default event handler for 'on_dismiss' event. ''' pass def _set_width_to_bubble(self, *args): '''To set self.width and bubble's width equal. ''' self.width = self.bubble.width def _reposition(self, *largs): # calculate the coordinate of the attached widget in the window # coordinate sysem win = self._win widget = self.attach_to if not widget or not win: return wx, wy = widget.to_window(*widget.pos) wright, wtop = widget.to_window(widget.right, widget.top) # set width and x if self.auto_width: # Calculate minimum required width if len(self.container.children) == 1: self.bubble.width = max(self.main_tab.parent.parent.width, self.container.children[0].width) else: self.bubble.width = max(self.main_tab.parent.parent.width, self.bubble.width, *([i.width for i in self.container.children])) Clock.schedule_once(self._set_width_to_bubble, 0.01) # ensure the dropdown list doesn't get out on the X axis, with a # preference to 0 in case the list is too wide. # try to center bubble with parent position x = wx - self.bubble.width / 4 if x + self.bubble.width > win.width: x = win.width - self.bubble.width if x < 0: x = 0 self.bubble.x = x # bubble position relative with the parent center x_relative = x - (wx - self.bubble.width / 4) x_range = self.bubble.width / 4 # consider 25% as the range # determine if we display the dropdown upper or lower to the widget h_bottom = wy - self.bubble.height h_top = win.height - (wtop + self.bubble.height) def _get_hpos(): '''Compare the position of the widget with the parent to display the arrow in the correct position ''' _pos = 'mid' if x_relative == 0: _pos = 'mid' elif x_relative < -x_range: _pos = 'right' elif x_relative > x_range: _pos = 'left' return _pos if h_bottom > 0: self.bubble.top = wy self.bubble.arrow_pos = 'top_' + _get_hpos() elif h_top > 0: self.bubble.y = wtop self.bubble.arrow_pos = 'bottom_' + _get_hpos() else: # none of both top/bottom have enough place to display the widget at # the current size. Take the best side, and fit to it. height = max(h_bottom, h_top) if height == h_bottom: self.bubble.top = wy self.bubble.height = wy self.bubble.arrow_pos = 'top_' + _get_hpos() else: self.bubble.y = wtop self.bubble.height = win.height - wtop self.bubble.arrow_pos = 'bottom_' + _get_hpos() def on_touch_down(self, touch): '''Default Handler for 'on_touch_down' ''' if super(ContextMenu, self).on_touch_down(touch): return True if self.collide_point(*touch.pos): return True self.dismiss() def on_touch_up(self, touch): '''Default Handler for 'on_touch_up' ''' if super(ContextMenu, self).on_touch_up(touch): return True self.dismiss() def add_widget(self, widget, index=0): '''Add a widget. ''' if self.content is None: return if widget.parent is not None: widget.parent.remove_widget(widget) if self.tab_list and widget == self.tab_list[0].content or\ widget == self._current_tab.content or \ self.content == widget or\ self._tab_layout == widget or\ isinstance(widget, TabbedPanelContent) or\ isinstance(widget, TabbedPanelHeader): super(ContextMenu, self).add_widget(widget, index) return if not self.container: self.container = GridLayout(orientation='vertical', size_hint_y=None, cols=1) self.main_tab.content.add_widget(self.container) self.container.bind(height=self.on_main_box_height) self.container.add_widget(widget, index) if hasattr(widget, 'cont_menu'): widget.cont_menu = self widget.bind(height=self.on_child_height) widget.size_hint_y = None def remove_widget(self, widget): '''Remove a widget ''' if self.container and widget in self.container.children: self.container.remove_widget(widget) else: super(ContextMenu, self).remove_widget(widget) def on_scroll_height(self, *args): '''Event Handler for scollview's height. ''' if not self.container: return self.container.height = max(self.container.height, self.main_tab.content.height) def on_main_box_height(self, *args): '''Event Handler for main_box's height. ''' if not self.container: return self.container.height = max(self.container.height, self.main_tab.content.height) if self.max_height: self.bubble.height = min(self.container.height + self.tab_height + dp(16), self.max_height) else: self.bubble.height = self.container.height + \ self.tab_height + dp(16) def on_child_height(self, *args): '''Event Handler for children's height. ''' height = 0 for i in self.container.children: height += i.height self.main_tab.content.height = height self.container.height = height def add_tab(self, widget, index=0): '''To add a Widget as a new Tab. ''' super(ContextMenu, self).add_widget(widget, index)
class FieldGrid(BoxLayout): def __init__(self, back, **kwargs): super(FieldGrid, self).__init__(**kwargs) self.back = back self.back_image = 'back1.png' self.orientation = 'vertical' self.padding = 10 self.explosion = SoundLoader.load('explosion.wav') self.open = SoundLoader.load('open.wav') self.flag_on = SoundLoader.load('flag_on.wav') self.flag_off = SoundLoader.load('flag_off.wav') self.volume_button = Button(size_hint=(None, None), size=(28, 28), background_normal='volume_on.png', on_press=self.change_volume) self.lost_popup = Popup(title='You lost', title_align='center', title_size=20, content=Button( text=' Restart', size_hint=(None, None), size=(175, 90), font_size=25, on_press=self.refresh, background_normal='restart.png'), size_hint=(None, None), size=(200, 150), auto_dismiss=False, separator_height=0) self.win_popup = Popup(title='', title_align='center', title_size=15, content=Button(text=' Restart', size_hint=(None, None), size=(175, 90), font_size=25, on_press=self.refresh, background_normal='restart.png'), size_hint=(None, None), size=(200, 150), auto_dismiss=False, separator_height=0) self.dd = DropDown() self.time = 0 self.f = None self.flags = 10 self.clock = Clock self.b_easy = Button(text='Easy', size_hint=(None, None), size=(75, 22), on_press=self.refresh, background_normal='easy.png') self.b_medium = Button(text='Medium', size_hint=(None, None), size=(75, 22), on_press=self.refresh, background_normal='medium.png') self.b_hard = Button(text='Hard', size_hint=(None, None), size=(75, 22), on_press=self.refresh, background_normal='hard.png') self.mainbutton = Button(text='Difficulty', size_hint=(None, None), size=(75, 22), background_normal='difficulty.png') self.mainbutton.bind(on_release=self.dd.open) self.dd.add_widget(self.b_easy) self.dd.add_widget(self.b_medium) self.dd.add_widget(self.b_hard) self.dd.bind( on_select=lambda instance, x: setattr(self.mainbutton, 'text', x)) self.mines_list = [ Button(text=' ', background_normal='default.png', on_press=self.refresh) for x in range(64) ] self.triggered = 54 self.flag_label = Label( text=f'[color=000000]{str(self.flags)}[/color]', markup=True, size_hint=(.7, .7), font_size=20) self.time_label = Label(text='[color=000000]00:00[/color]', markup=True) self.bl = BoxLayout(size_hint=(1, 100 / (8 * 25 + 20 + 100)), spacing=2) self.al_left = AnchorLayout(anchor_x='left', anchor_y='top') self.al_left.add_widget(self.mainbutton) self.al_center = AnchorLayout(anchor_x='center', anchor_y='center') self.al_center.add_widget(self.time_label) self.bl_right = BoxLayout(orientation='vertical') self.al_flag = AnchorLayout(anchor_x='right', anchor_y='top') self.al_flag.add_widget(self.flag_label) self.al_volume = AnchorLayout(anchor_x='right', anchor_y='center') self.al_volume.add_widget(self.volume_button) self.bl_right.add_widget(self.al_flag) self.bl_right.add_widget(self.al_volume) self.bl.add_widget(self.al_left) self.bl.add_widget(self.al_center) self.bl.add_widget(self.bl_right) self.gl = GridLayout(cols=8, size_hint=(1, (8 * 25) / (8 * 25 + 20 + 100))) self.generate_field() self.add_widget(self.bl) self.add_widget(self.gl) def represent(self, num): whole = '0' + str(int(num // 60)) end = '0' + str(num - int(whole) * 60) return f'{whole[-2::]}:{end[-2::]}' def update_time(self, instance): if self.f is None: self.time += 1 self.time_label.text = f'[color=000000]{self.represent(self.time)}[/color]' return self.f def update_flags(self): self.flag_label.text = f'[color=000000]{str(self.flags)}[/color]' def change_volume(self, instance): if instance.background_normal == 'volume_on.png': instance.background_normal = 'volume_off.png' self.explosion.volume = 0 self.open.volume = 0 self.flag_on.volume = 0 self.flag_off.volume = 0 else: instance.background_normal = 'volume_on.png' self.explosion.volume = 1 self.open.volume = 1 self.flag_on.volume = 1 self.flag_off.volume = 1 def generate_mines(self, w_cells, h_cells, bombs, restricted_pos): mine_list = [None for i in range(w_cells * h_cells)] restricted_list = [ restricted_pos, restricted_pos + 1, restricted_pos - 1, restricted_pos + h_cells - 1, restricted_pos + h_cells, restricted_pos + h_cells + 1, restricted_pos - h_cells - 1, restricted_pos - h_cells, restricted_pos - h_cells + 1 ] bomb_pos = set() while len(bomb_pos) < bombs: b_pos = randrange(0, w_cells * h_cells) if b_pos not in restricted_list: bomb_pos.add(b_pos) bomb_pos = list(bomb_pos) for pos in bomb_pos: mine_list[pos] = Bomb(bomb_pos, pos, self) for pos in range(len(mine_list)): if not mine_list[pos]: mine_list[pos] = Mine(w_cells, pos, self) return mine_list def generate_field(self): for mine in self.mines_list: self.gl.add_widget(mine) def refresh(self, instance): for mine in self.mines_list: self.gl.remove_widget(mine) if instance.text == ' ': cells = int((len(self.mines_list))**(1 / 2)) if len(self.mines_list) == 484: bombs = 99 else: bombs = int(len(self.mines_list) / 6.4) trigger = self.mines_list.index(instance) self.mines_list = self.generate_mines(cells, cells, bombs, trigger) self.mines_list[trigger].pressed() self.f = None self.clock.schedule_interval(self.update_time, 1) else: if instance.text == 'Easy': self.mines_list = [ Button(text=' ', background_normal='default.png', on_press=self.refresh) for x in range(64) ] self.back_image = 'back1.png' self.f = False self.time = 0 self.update_time('instance') elif instance.text == 'Medium': self.mines_list = [ Button(text=' ', background_normal='default.png', on_press=self.refresh) for x in range(256) ] self.back_image = 'back2.png' self.f = False self.time = 0 self.update_time('instance') elif instance.text == 'Hard': self.mines_list = [ Button(text=' ', background_normal='default.png', on_press=self.refresh) for x in range(484) ] self.back_image = 'back3.png' self.f = False self.time = 0 self.update_time('instance') else: self.mines_list = [ Button(text=' ', background_normal='default.png', on_press=self.refresh) for x in range(len(self.mines_list)) ] cells = int((len(self.mines_list))**(1 / 2)) if len(self.mines_list) == 484: bombs = 99 else: bombs = int(len(self.mines_list) / 6.4) self.triggered = cells * cells - bombs self.flags = bombs self.update_flags() self.gl.cols = cells self.gl.size_hint = (1, (cells * 25) / (cells * 25 + 20 + 100)) self.bl.size_hint = (1, 100 / (cells * 25 + 20 + 100)) for mine in self.mines_list: self.gl.add_widget(mine) self.lost_popup.dismiss() self.win_popup.dismiss() Window.size = (cells * 25 + 20, cells * 25 + 20 + 100) self.back.source = self.back_image
class Spotlight(App): ''' This class represents the kivy app that will run the spotlight ''' def __init__(self, **kwargs): super(Spotlight, self).__init__(**kwargs) # fixed width of the app, will never change self._width = kwargs.get('width', 500) # tells how many entries can be displayed on the screen at the same time. The rest will be accessible via a scroller self._max_results_displayed = kwargs.get('max_results_displayed', 5) # gives the height of the separators that will be used between each entry self._sep_height = kwargs.get('sep_height', 1) # static height of the main search bar: SearchInput self._search_field_height = kwargs.get('search_field_height', 35) # height of each entry self._result_height = kwargs.get('result_height', 25) # this is the spacing between the search bar and the scroller containing the entries self._spacing = kwargs.get('spacing', 1) # this is the padding of the main window self._padding = 5 # this is the space between each separator/result in the dropdown list self._result_spacing = kwargs.get('result_spacing', 1) # color of a non-selected entry self._inactive_button_color = (.0,.0,.0, 0) # color of a selected entry self._active_button_color = (.4, .4, .4, 1) # store all the visible entries on the screen as a pair (button, separator) for convenience self._results = [] # index of the result that is currently highlighted self._highlight_index = -1 # these 3 variables are the 3 callbacks that the controller can input self._on_build = None self._on_enter = None self._on_text = None # this field holds a preset number of buttons for efficiency self._button_pool = [] # parse the callbacks passed in the constructor self.user_bind(**kwargs) self.build_window() # update the window size self.update_window() def user_bind(self, **kwargs): ''' this function saves the callbacks passed to this function into the 3 available holders ''' # this event is triggered when the application is drawn for the first time self._on_build = kwargs.get('on_build', self._on_build) # this event is triggered when the user presses enter self._on_enter = kwargs.get('on_enter', self._on_enter) # this even is triggered whenever the text in the search field is changed self._on_text = kwargs.get('on_text', self._on_text) def on_start(self): ''' when the window is drawn and the application started we update the size of the window ''' self.update_window() def build_window(self): ''' this function builds the whole app ''' self._search_field = SearchInput(multiline=False, focus=True, realdonly=False, height=self._search_field_height, size_hint=(1, None), markup=True, valign='middle', font_size = 20, font_name = 'data/fonts/DejaVuSans.ttf') self._search_field.bind(focus=self._on_focus) self._search_field._keyboard.bind(on_key_down=self._on_keyboard_down) self._search_field.background_active = '' self._search_field.font_size = 20 self._search_field.bind(on_text_validate = self._on_text_validate) self._search_field.bind(text = self._on_new_text) self._search_field.text = '' self._drop_down_list = GridLayout(cols=1, width=self._width, spacing=self._result_spacing, size_hint = (None, None)) self._drop_down_list.bind(minimum_height = self._drop_down_list.setter('height')) self._scroller = ScrollView(scroll_distance=10, scroll_type=['bars'], do_scroll_x=False, bar_width=10, size_hint=(1, 1)) self._scroller.add_widget(self._drop_down_list) self._layout = ColoredGridLayout(cols=1, width=self._width, height=self._search_field_height, padding=(self._padding, self._padding), spacing=self._spacing*2) self._layout.add_widget(self._search_field) self._layout.add_widget(self._scroller) if self._on_build: self._on_build() return self._layout def build(self): return self._layout def _unbind_all(self): self._search_field.unbind(focus=self._on_focus) self._search_field._keyboard.unbind(on_key_down=self._on_keyboard_down) self._search_field.unbind(on_text_validate = self._on_text_validate) self._search_field.unbind(text = self._on_new_text) self._drop_down_list.unbind(minimum_height = self._drop_down_list.setter('height')) for btn in self._button_pool: btn.unbind(width = button_width_setter) btn.unbind(on_press=self._on_click) btn.unbind(texture_size=btn.setter('text_size')) def _on_new_text(self, value, text): if self._on_text: self._on_text(self, value, text) def _on_text_validate(self, value): ''' when the user pressed enter, we forward the callback to the controller with the current hightlight index ''' if self._on_enter: ret = self._on_enter(value, self._highlight_index) if ret: self._unbind_all() self.stop() def _on_focus(self, instance, value): ''' this function is called whenever the focus of the search field changes. We do NOT allow defocus ''' if not value: self._search_field.focus = True # since the search field has to re-claim the keyboard, we re-bind our callback self._search_field._keyboard.bind(on_key_down=self._on_keyboard_down) def update_window(self, *args): ''' based on the current amount of entries shown, we adapt the size of the window ''' result_count = len(self._results) win_width = 2*self._padding + self._width win_height = 2*self._padding + self._search_field_height + self._spacing + (self._result_spacing * 2 + self._result_height + self._sep_height) * result_count max_height = 2*self._padding + self._search_field_height + self._spacing + (self._result_spacing * 2 + self._result_height + self._sep_height) * self._max_results_displayed if self._app_window: self._app_window.size = win_width, min(win_height, max_height) def _on_keyboard_down(self, keyboard, keycode, text, modifiers): ''' we handle 3 keys: up (resp. down) to hightlight the entry above (resp. below) and escape to quit the application ''' if keycode[1] == 'up': self._highlight_up() elif keycode[1] == 'down': self._highlight_down() elif keycode[1] == 'escape': keyboard.release() self._unbind_all() self.stop() else: # mark the key press as not handled return False # mark the key press as handled return True def pre_allocate(self, number): self._button_pool = [] for _ in range(0, number): btn = Button(text='str', height=self._result_height, size_hint=(1, None), valign='middle', halign='left', background_color=self._inactive_button_color, markup = True, padding_x = 0) btn.bind(width = button_width_setter) btn.bind(on_press=self._on_click) btn.bind(texture_size=btn.setter('text_size')) btn.background_normal = '' btn.background_down = btn.background_normal self._button_pool.append(btn) def _build_button(self): if self._button_pool: return self._button_pool.pop() btn = Button(text='str', height=self._result_height, size_hint=(1, None), valign='middle', halign='left', background_color=self._inactive_button_color, markup = True, padding_x = 0) btn.bind(width = button_width_setter) btn.bind(on_press=self._on_click) btn.bind(texture_size=btn.setter('text_size')) btn.background_normal = '' btn.background_down = btn.background_normal return btn def _release_button(self, btn): btn.background_color = self._inactive_button_color self._button_pool.append(btn) def add_result(self, str, redraw = True): ''' add a new entry to the dropdown list; an index is returned ''' btn = self._build_button() btn.text = str sep = Separator(height = self._sep_height) self._drop_down_list.add_widget(sep) self._drop_down_list.add_widget(btn) self._results.append((btn, sep)) # we reset the highlight self._highlight_reset() if redraw: self.update_window() return len(self._results)-1 def get_result(self, idx): ''' get a button object from an index - returned from a previous call to add_result ''' if not idx < len(self._results) or not idx >= 0: return e, _ = self._results[idx] return e def remove_result(self, idx, redraw = True): ''' remove a result object from its index - returned from a previous call to add_result ''' if not idx < len(self._results) or not idx >= 0: return e, sep = self._results[idx] if sep: self._drop_down_list.remove_widget(sep) self._drop_down_list.remove_widget(e) self._results.remove((e, sep)) self._release_button(e) # we reset the highlight self._highlight_reset() # resize the window accordingly if redraw: self.update_window() def clear_results(self, redraw = True): ''' clear all the results ''' for e, sep in self._results: self._release_button(e) self._drop_down_list.clear_widgets() self._results = [] # we reset the highlight self._highlight_reset() # resize the window accordingly if redraw: self.update_window() def _on_click(self, instance): ''' this callback is called whenever a click on a result is done; the highlight is adapted ''' for i in range(0, len(self._results)): e, _ = self._results[i] if e is instance: offset = i-self._highlight_index self._highlight_update(offset) self._on_text_validate(1) break def _scroll_update(self): ''' this function adapts the scroller to ensure that the highlighted object is visible ''' highlight_reverse_index = len(self._results) - 1 - self._highlight_index item_lb = highlight_reverse_index * (self._result_spacing*2 + self._sep_height + self._result_height) item_ub = item_lb + self._result_height + self._result_spacing*2 + self._sep_height view_size = (self._result_spacing * 2 + self._result_height + self._sep_height) * self._max_results_displayed total_size = (self._result_spacing * 2 + self._result_height + self._sep_height) * len(self._results) lb = self._scroller.scroll_y * (total_size - view_size) ub = lb + view_size if item_lb < lb: self._scroller.scroll_y -= self._scroller.convert_distance_to_scroll(0, lb - item_lb)[1] elif item_ub > ub: self._scroller.scroll_y += self._scroller.convert_distance_to_scroll(0, item_ub - ub)[1] def _highlight_update(self, offset): ''' move the hightlight by `offset' amount ''' if self._highlight_index > -1 and self._highlight_index < len(self._results): e, sep = self._results[self._highlight_index] e.background_color = self._inactive_button_color self._highlight_index += offset self._highlight_index = min(self._highlight_index, len(self._results)-1) if self._results: self._highlight_index = max(self._highlight_index, 0) else: self._highlight_index = max(self._highlight_index, 1) if self._highlight_index > -1 and self._highlight_index < len(self._results): e, sep = self._results[self._highlight_index] e.background_color = self._active_button_color self._scroll_update() def _highlight_reset(self): offset = -self._highlight_index self._highlight_update(offset) def _highlight_up(self): self._highlight_update(-1) def _highlight_down(self): self._highlight_update(+1) def on_stop(self): pygame.display.quit() pass
class BookmarksScreen(ActionBarScreen): STR_BOOKMARKS = StringProperty() STR_NO_BOOKMARKS = StringProperty() STR_MOD = StringProperty() STR_VERSION = StringProperty() STR_SERVER = StringProperty() def __init__(self, **kwargs): # inicializace self.root = kwargs['root'] self.root.insertStrings.append((self, )) super(BookmarksScreen, self).__init__(**kwargs) self.layout = GridLayout(cols=1, size_hint_y=None, size_hint_x = 1, spacing=10) self.layout.bind(minimum_height=self.layout.setter('height')) self.scrollview.add_widget(self.layout) def on_pre_enter(self, *args): # Před vstupem na obrazovku načte seznam oblíbených serverů if len(self.layout.children) == 0: bookmarks = self.root.Cfg[-1] if len(bookmarks) == 0: self.layout.add_widget(Label(text=self.STR_NO_BOOKMARKS, font_name='font/Roboto-Regular.ttf', font_size='18dp', size_hint_y = None, text_size=(self.width*3, None))) else: head = BoxLayout(size_hint=(1,None), height=50) head.add_widget(Label(text=self.STR_SERVER, font_name='font/Roboto-Bold.ttf', size_hint=(None,1), font_size="20dp", width = self.width*1.9, text_size=(self.width*1.9, None))) head.add_widget(Label(text=self.STR_MOD, font_name='font/Roboto-Bold.ttf', size_hint=(1,1), font_size="15dp", width = self.width, text_size=(self.width, None))) head.add_widget(DelButton(opacity=0, size_hint=(None, 1))) self.layout.add_widget(head) for y, server in enumerate(bookmarks): srvr = Bookmark(size_hint=(1,None), height = 50) for i, cell in enumerate(server): if i == 0: lbl = Label(text="[ref={0}]{1}[/ref]".format(y,cell), markup=True, font_name='font/Roboto-Regular.ttf', size_hint=(None,1), font_size="20dp", text_size=(None, None)) lbl.bind(on_ref_press=self.connectBookmark) srvr.add_widget(lbl) elif i == 1: pass elif i == 2: lbl = Label(text="[ref={0}]{1}[/ref]".format(y,cell), markup=True, font_name='font/Roboto-Regular.ttf', size_hint=(1,1), font_size="20dp") lbl.bind(on_ref_press=self.connectBookmark) srvr.add_widget(lbl) btn = DelButton(OBJ=srvr, ID=y, background_normal="crop/delete.png", background_down="crop/delete.png",size_hint=(None, 1)) btn.bind(on_press=self.removeBookmark) srvr.add_widget(btn) self.layout.add_widget(srvr) def removeBookmark(self, *args): # Odstranění serveru z oblíbených print args[0].ID self.layout.remove_widget(args[0].OBJ) self.root.Cfg[-1].pop(args[0].ID) self.root.refreshCfg() def connectBookmark(self, instance, value): # Připojení k serveru ze záložky self.root.server = self.root.Cfg[-1][int(value)][0] self.root.version = self.root.Cfg[-1][int(value)][1] if self.root.Cfg[-1][int(value)][2] == 'classic': self.root.tetrifast = False else: self.root.tetrifast = True self.root.connect_to_server() self.root.overlay.setSize() self.root.sm.current = "GameScreen" if self.root.onAndroid(): self.root.vibrate(0.05)
class AnnotationPanelWidget(ScrollView): def __init__(self, videoEventDispatcher, **kwargs): super(AnnotationPanelWidget, self).__init__(**kwargs) self.do_scroll_x = False self.effect_cls = DampedScrollEffect self.videoEventDispatcher = videoEventDispatcher self.videoEventDispatcher.bind(on_annotation_add=self.handleOnAnnotationAdd) self.videoEventDispatcher.bind(on_annotation_update=self.handleOnAnnotationUpdate) self.videoEventDispatcher.bind(on_item_delete=self.handleOnItemDelete) self.videoEventDispatcher.bind(on_load_annotations=self.handleOnLoadAnnotations) self.videoEventDispatcher.bind(on_key_delete=self.handleOnKeyDelete) self.layout = GridLayout(cols=1, spacing=50, size_hint_x=1, size_hint_y=None) self.layout.size = (100, 200) self.layout.padding = 10 self.layout.bind(minimum_height=self.layout.setter('height')) self.add_widget(self.layout) def addAnnotationItem(self, annotation, frame): annotationItemWidget = AnnotationItemWidget(frame, self.videoEventDispatcher) annotationItemWidget.setCategory(annotation.category) annotationItemWidget.setId(str(annotation.id)) annotationItemWidget.refreshLabels() self.layout.add_widget(annotationItemWidget) return annotationItemWidget def findItemWidgetForAnnotation(self, annotation): annotationItemWidgets = self.layout.children for itemWidget in annotationItemWidgets: if str(itemWidget.topWidget.category) == str(annotation.category) \ and str(itemWidget.topWidget.id) == str(annotation.id): return itemWidget def handleOnAnnotationAdd(self, obj, *args): addedAnnotation = args[0] addedFrame = args[1] addedItemWidget = self.addAnnotationItem(addedAnnotation, addedFrame) def handleOnItemDelete(self, obj, *args): deleteCategory = args[0] deleteId = args[1] itemDeleted = False for itemWidget in self.layout.children: if str(itemWidget.topWidget.category) == str(deleteCategory) \ and str(itemWidget.topWidget.id) == str(deleteId): self.layout.remove_widget(itemWidget) itemDeleted = True if itemDeleted: self.videoEventDispatcher.dispatchOnAnnotationDelete(deleteCategory, deleteId) def handleOnAnnotationUpdate(self, obj, *args): updatedAnnotation = args[0] updatedFrame = args[1] widgetItemForAnnotation = self.findItemWidgetForAnnotation(updatedAnnotation) widgetItemForAnnotation.addKey(updatedFrame) def handleOnLoadAnnotations(self, obj, annotationDict): for category in annotationDict: idFrameDict = annotationDict[category] for idx in idFrameDict: frameDict = idFrameDict[idx] firstFrameAdded = False for frame in frameDict: annotation = frameDict[frame] if firstFrameAdded: self.handleOnAnnotationUpdate(None, annotation, frame) else: self.handleOnAnnotationAdd(None, annotation, frame) firstFrameAdded = True return def handleOnKeyDelete(self, obj, category, idx, frame): placeHolderAnnotation = Annotation(-1, -1, -1, -1, category, idx) widgetItemToUpdate = self.findItemWidgetForAnnotation(placeHolderAnnotation) widgetItemToUpdate.removeKey(frame) if len(widgetItemToUpdate.getKeys()) == 0: self.layout.remove_widget(widgetItemToUpdate)
class CrossSectionEditor(GridLayout): ''' the cross section editor is the component where you can select the shape with the shape-selection-component and set the size-properties of the shapes ''' # application-main app = ObjectProperty() # cross section cs = ObjectProperty() # cross-section-shape csShape = ObjectProperty() circle = StringProperty('circle') rectangle = StringProperty('rectangle') ishape = StringProperty('I-shape') tshape = StringProperty('T-shape') shapeStr = StringProperty('shape') ''' constructor ''' def __init__(self, **kwargs): super(CrossSectionEditor, self).__init__(**kwargs) self.cols, self.spacing = 2, Design.spacing self.content = GridLayout(cols=1, spacing=Design.spacing) self.create_gui() self.add_widget(self.content) ''' create the gui ''' def create_gui(self): self.create_informations() shapeContent = ShapeSelection(information=self) self.shapeSelection = OwnPopup(title=self.shapeStr, content=shapeContent) self.create_selection_menu() self.content.add_widget(self.rectangleInformation, 0) ''' create all informations of the shapes ''' def create_informations(self): # create the rectangle-information self.rectangleInformation = RectangleInformation(csShape=self.cs.csRectangle) self.rectangleInformation.create_gui() self.focusInformation = self.rectangleInformation self.shape = self.rectangleInformation # create double-t-information self.doubleTInformation = DoubleTInformation(csShape=self.cs.csDoubleT) self.doubleTInformation.create_gui() # create circle-information self.circleInformation = CircleInformation(csShape=self.cs.csCircle) self.circleInformation.create_gui() # create t-information self.tInformation = TInformation(csShape=self.cs.csT) self.tInformation.create_gui() ''' create the layout where you can select the cross-section-shape ''' def create_selection_menu(self): selectionContent = GridLayout(cols=2, spacing=Design.spacing, size_hint_y=None, row_force_default=True, row_default_height=Design.btnHeight, height=Design.btnHeight) self.lblSelection = OwnLabel(text=self.shapeStr) self.btnSelection = OwnButton(text=self.rectangle) self.btnSelection.bind(on_press=self.shapeSelection.open) selectionContent.add_widget(self.lblSelection) selectionContent.add_widget(self.btnSelection) self.content.add_widget(selectionContent) ''' cancel the shape selection and close the shape-editor-popup ''' def cancel_shape_selection(self, btn): self.shapeSelection.dismiss() ''' look which shape the user has selected ''' def finished_shape_selection(self, btn): if btn.text == self.circle: self.show_circle_shape(btn) elif btn.text == self.rectangle: self.show_rectangle(btn) elif btn.text == self.ishape: self.show_double_t(btn) elif btn.text == self.tshape: self.show_t(btn) self.btnSelection.text = btn.text self.shapeSelection.dismiss() ''' change the current cross section ''' def change_cross_section(self, shape): self.view = shape.view self.csShape = shape ''' add the view at the left side of the editor ''' def add_view(self): self.view = self.cs.view self.containsView = True self.add_widget(self.view, 1) ''' update the view when the shape has changes ''' def update_view(self): if self.containsView: self.remove_widget(self.view) self.view = self.cs.view self.add_widget(self.view, 1) self.containsView = True ''' remove the view of the editor ''' def remove_view(self): if self.containsView: self.remove_widget(self.view) self.containsView = False ################################# # show-methods of the shapes # ################################# ''' show the rectangle-shape ''' def show_rectangle(self, btn): self.csShape = self.cs.csRectangle self.cs.view = self.csShape self.remove_widget(self.shape) self.shape = self.rectangleInformation self.content.remove_widget(self.focusInformation) self.content.add_widget(self.rectangleInformation, 0) self.focusInformation = self.rectangleInformation self.cs.show_rectangle_shape() if self.app.boolExplorer: self.app.create_explorer() self.app.boolExplorer = False self.cs.explorer.update_csShape(self.cs.csRectangle, self.cs.csRectangle.ch, self.cs.csRectangle.layers, self.cs.csRectangle.bars) self.update_view() ''' show the doubleT-shape ''' def show_double_t(self, btn): self.csShape = self.cs.csDoubleT self.cs.view = self.csShape self.remove_widget(self.shape) self.shape = self.doubleTInformation self.content.remove_widget(self.focusInformation) self.content.add_widget(self.doubleTInformation, 0) self.focusInformation = self.doubleTInformation self.cs.show_doublet_shape() if self.app.boolExplorer: self.app.create_explorer() self.app.boolExplorer = False self.cs.explorer.update_csShape(self.cs.csDoubleT, self.cs.csDoubleT.get_total_height(), self.cs.csDoubleT.layers, self.cs.csDoubleT.bars) self.update_view() ''' show the circle-shape ''' def show_circle_shape(self, btn): self.csShape = self.cs.csCircle self.cs.view = self.csShape self.remove_widget(self.shape) self.shape = self.circleInformation self.content.remove_widget(self.focusInformation) self.content.add_widget(self.circleInformation, 0) self.focusInformation = self.circleInformation self.cs.show_circle_shape() if self.app.boolExplorer: self.app.create_explorer() self.app.boolExplorer = False self.cs.explorer.update_csShape(self.cs.csCircle, self.cs.csCircle.d, self.cs.csCircle.layers, self.cs.csCircle.bars) self.update_view() ''' show the t-shape ''' def show_t(self, btn): self.csShape = self.cs.csT self.cs.view = self.csShape self.remove_widget(self.shape) self.shape = self.tInformation self.content.remove_widget(self.focusInformation) self.content.add_widget(self.tInformation, 0) self.focusInformation = self.tInformation self.cs.show_tshape() if self.app.boolExplorer: self.app.create_explorer() self.app.boolExplorer = False self.cs.explorer.update_csShape(self.cs.csT, self.cs.csT.get_total_height(), self.cs.csT.layers, self.cs.csT.bars) self.update_view()
class LoginScreen(FloatLayout): def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) #gc.disable() self.DropdownObjects = [] self.add_widget(Label(text= "Wilkommen [color=ff3333] [sub] bei der [/sub][/color][color=3333ff][b] Bonierungs[sup][color=#098125ff]App[/sup][/b][/color]", markup = True, pos_hint={'top': 1.2}, font_size='20sp')) self.GridlayoutS1 = GridLayout(cols = 2, size_hint_y = 1/5, pos_hint={'top': 0.6}) self.add_widget(self.GridlayoutS1) self.GridlayoutS1.add_widget(Label(text='User Name')) #, size_hint_x = 0.2, size_hint_y = 0.2)) self.username = TextInput(multiline=False) #, size_hint_x = 0.2, size_hint_y = 0.2) self.username.bind(on_text_validate=self.on_enter) self.GridlayoutS1.add_widget(self.username) self.GridlayoutS1.add_widget(Label(text='password')) #,size_hint_x = 0.2, size_hint_y = 0.2)) self.password = TextInput(password=True, multiline=False) #, size_hint_x = 0.2, size_hint_y = 0.2) self.GridlayoutS1.add_widget(self.password) self.BenutzerListe = {"": ""}; self.add_widget(Button(text='Einloggen', size_hint_y= 1/5, pos_hint={'top': 0.4}, on_release = self.AbfrageLogin)) self.LabelLoginanzeiger = Label(size_hint_y= 1/5) self.add_widget(self.LabelLoginanzeiger) def on_enter(self, instance): print('User pressed enter in', instance) self.password.focus = True def AbfrageLogin(self, widget): Username = self.username.text Passwort = self.password.text if Username in self.BenutzerListe and Passwort == self.BenutzerListe[Username]: self.LabelLoginanzeiger.text = 'Login korrekt' self.clear_widgets() self.HauptProgramm() else: self.LabelLoginanzeiger.text = 'Login inkorrekt' def HauptProgramm(self, *args): print 'das ist das Hauptprogramm' self.BilderListeVorlaeufer = [] self.BilderListeVorlaeufer = os.listdir(os.getcwd() + '/pictures') self.Pfade = [] for i in self.BilderListeVorlaeufer: Pfad = os.path.join('pictures', i) self.Pfade.append(Pfad) self.HauptCarousel = Carousel(scroll_timeout = 100) self.add_widget(self.HauptCarousel) #################################################################################################### ### Erste Seite im HauptCarousel momentan mit den produktbildern self.HauptCarousel.FloatLayout = FloatLayout() self.HauptCarousel.add_widget(self.HauptCarousel.FloatLayout) self.HauptCarousel.FloatLayout.GridLayout = GridLayout(cols=3, pos_hint={'x': 0,'y': 0}, size_hint=[1,0.9]) self.HauptCarousel.FloatLayout.add_widget(self.HauptCarousel.FloatLayout.GridLayout) for i in range(9): button = Button(background_normal = self.Pfade[i], background_down= 'pictures/bilder_oberflaeche/1361740537_Ball Green_mitHaken.png', mipmap= True) self.HauptCarousel.FloatLayout.GridLayout.add_widget(button) ## self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test')) ## self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test2')) ##################################################################################################### ### 2 Seite im Hauptcarousel mit testbutton zur datei Erstellung ### 2 Page in MainCarousel with testbutton for creating /exporting to a file self.HauptCarousel2 = BoxLayout(orientation='vertical') ###############self.HauptCarousel.add_widget(self.HauptCarousel2) self.HauptCarousel2.Texteingabe = TextInput(multiline=True) self.HauptCarousel2.add_widget(self.HauptCarousel2.Texteingabe) self.HauptCarousel2.ButtonSchreiben = Button(text="datei schreiben", on_release = self.datenpickeln) self.HauptCarousel2.add_widget(self.HauptCarousel2.ButtonSchreiben) ####################################################################### ### 3 Seite im Hauptcarousel momentan mit Datei Auslesefunktion ### 3 Page in MainCarousel atm with functionality to read from file self.HauptCarousel3 = BoxLayout(orientation='vertical') ######################self.HauptCarousel.add_widget(self.HauptCarousel3) self.HauptCarousel3.Textausgabe = TextInput(multiline=True, readonly = True) self.HauptCarousel3.add_widget(self.HauptCarousel3.Textausgabe) self.HauptCarousel3.ButtonLesen = Button(text="datei auslesen", on_release = self.datenentpickeln) self.HauptCarousel3.add_widget(self.HauptCarousel3.ButtonLesen) ####################################################################### ### 4 Seite im Hauptcarousel momentan mit Tischmanager ### 4 Page in Maincarousel atm with some kind of Table Manager BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] self.CustomLayout = CustomLayout() self.HauptCarousel.add_widget(self.CustomLayout) #self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=#098125ff]Organizer[/sup][/b][/color]', markup = True, #halign= 'left', valign= 'top', text_size= self.size, pos_hint={'x':0, 'y': 0}, font_size= '30sp') self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=#098125ff]Organizer[/sup][/b][/color]', markup = True, halign= 'left', font_size= '30sp') #self.CustomLayout.add_widget(self.CustomLayout.TopLabel) self.CustomLayout.BoxLayout = BoxLayout (orientation = 'horizontal', size_hint = [1,0.05], pos_hint={'x':0, 'y': 0.95}) self.CustomLayout.add_widget(self.CustomLayout.BoxLayout) self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.TopLabel) ButtonMenu1 = self.DropdownbuttonCreator() self.CustomLayout.BoxLayout.Button1 = ButtonMenu1 ## self.CustomLayout.BoxLayout.Button2 = Button(text = 'Tisch+' , on_release = self.tischhinzufuegen) ## self.CustomLayout.BoxLayout.Button3 = Button(text = 'Spalte+', on_release = self.spaltehinzufuegen) ## self.CustomLayout.BoxLayout.Button4 = Button(text = 'Zeile+', on_release = self.zeilehinzufuegen) self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button1) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button2) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button3) ## self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button4) self.CustomLayoutGridLayout = GridLayout(cols = 3, rows = 4, padding = [20,20], spacing = [30,30], size_hint = [1,0.95], pos_hint={'x':0, 'y': 0}) #cGridLayout = StackLayout(orientation = "tb-lr", padding = [20,20], spacing = [30,30], size_hint = [1,0.9], pos_hint={'x':0, 'y': 0}) self.CustomLayout.add_widget(self.CustomLayoutGridLayout) self.Tischliste = [] Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] AnzahlTische = 12 Zielwidget = self.CustomLayoutGridLayout self.tischerstellung(Zielwidget,AnzahlTische, Auswahlliste, BackgroundcolorListe) ##################################################################### ### Versuch eines Dropdown Buttons ### Try to implement a dropdown Button, probably better than a Spinner ############################### #### Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] #### BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] #### self.dropdownobjects = [] #### for i in range(12): #### TischButtonText = "T " + str(i+1) #### DropdownObjekt = CustomDropDown() #von kovak hinzugefuegt #### DropdownObjektButton = CustomButton(text = TischButtonText, background_color = (201./255.,99./255.,23./255.,1)) #### cGridLayout.add_widget(DropdownObjektButton) #### DropdownObjektButton.bind(on_release=DropdownObjekt.open) #### self.dropdownobjects.append(DropdownObjekt) #von kovak hinzugefuegt #### #### for x in range(len(Auswahlliste)): #### #### DropdownUnterbutton = Button(text=Auswahlliste[x], font_size = 15, size_hint_y=None, height=60, background_color = BackgroundcolorListe[x]) #### DropdownObjekt.add_widget(DropdownUnterbutton) #### #### #print' button', i, 'unterbutton', x #### #### #### #### DropdownObjektButton.text= TischButtonText #### TischButtondict = {'Nummer':(i),'Objekt':DropdownObjektButton} #### self.Tischliste.append(TischButtondict) ## for i in range(12): ## TischButtonText = "T " + str(i+1) ## #TischButton = Button(text=(''), on_release = self.tischmanipulieren) ## TischButton = Spinner(text='', values = ("Bestellung", "Abrechnung", "Best. Aendern", "Bennenen")) ## cGridLayout.add_widget(TischButton) ## TischButton.text= TischButtonText ## TischButtondict = {(i),TischButton} ## self.Tischliste.append(TischButtondict) ## for index, item in enumerate(self.Tischliste): ## print index, item def DropdownbuttonCreator(self): Auswahlliste = ["Tisch +", "Tisch -", "Spalte + ", "Spalte -", "Reihe + ", "Reihe -"] BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(1,0,0,1),(0,1,0,1),(1,0,0,1),(0,1,0,1)] Aktionsliste = [self.tischhinzufuegen, self.tischentfernen, self.spaltehinzufuegen, self.spalteentfernen, self.zeilehinzufuegen, self.zeileentfernen] DropdownObjekt = CustomDropDown() DropdownObjektButton = CustomButton(text = "Menue", #DropdownObjektButton = ToggleButton(text="Menue", size_hint=[1,1], background_color = (0.8, 0.8, 0.00, 1), background_normal='pictures/white2.png', background_down='pictures/white3.png') #self.CustomLayout.add_widget(DropdownObjektButton) DropdownObjektButton.bind(on_release=DropdownObjekt.open) self.DropdownObjects.append(DropdownObjekt) for x in range(len(Auswahlliste)): DropdownUnterbutton = Button(text=Auswahlliste[x], font_size = 15, size_hint_y=None, height=60, background_color = BackgroundcolorListe[x], background_normal='pictures/white2.png', background_down='pictures/white3.png', opacity = 0.8, on_release = Aktionsliste[x]) DropdownObjekt.add_widget(DropdownUnterbutton) ButtonMenu1 = DropdownObjektButton return ButtonMenu1 def tischerstellung (self, Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe): Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] Aktionsliste = [self.bestellung, self.abrechnung, self.bestellungaendern, self.tischbenennen] #self.DropdownObjects = [] for i in range(AnzahlTische): if self.Tischliste != []: LetzterTisch = self.Tischliste[-1]['Nummer'] ## print LetzterTisch + 1 else: LetzterTisch = 0 TischNr = str(LetzterTisch+1) TischButtonText = "T " + TischNr DropdownObjekt = CustomDropDown() #von kovak hinzugefuegt #DropdownObjektButton = CustomButton(text = TischButtonText, DropdownObjektButton = ToggleButton(text = TischButtonText, group='Tische', background_normal='pictures/white2.png', background_down='pictures/white4.png', background_color = (0.79, 0.39, 0.09, 0.6)) Zielwidget.add_widget(DropdownObjektButton) DropdownObjektButton.bind(on_release=DropdownObjekt.open) self.DropdownObjects.append(DropdownObjekt) #von kovak hinzugefuegt for x in range(len(Auswahlliste)): DropdownUnterbutton = Button(text=Auswahlliste[x], id = TischNr, #auto_width='False', #width = '200sp', font_size = 15, size_hint_y=None, height=60, background_normal='pictures/white2.png', background_down='pictures/white3.png', background_color = BackgroundcolorListe[x], on_release = Aktionsliste[x]) DropdownObjekt.add_widget(DropdownUnterbutton) #print' button', i, 'unterbutton', x DropdownObjektButton.text= TischButtonText self.TischButtondict = {'Nummer':(LetzterTisch + 1),'Objekt':DropdownObjektButton} self.Tischliste.append(self.TischButtondict) def garbagecollectortracking(self, widget): for i in self.Tischliste: a = i print gc.is_tracked(a) ### function for Editing a Table####################################### #def tischmanipulieren(self, widget): # widget.text = 'mein text' #### function for adding an extra table to layout ########################## def tischhinzufuegen(self, widget): if len(self.Tischliste) >= 1: if hasattr(self, 'CustomLayoutBottomLabel'): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) AnzahlTische = 1 Zielwidget = self.CustomLayoutGridLayout Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"] BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)] LetzterTisch = self.Tischliste[-1]['Nummer'] if (self.CustomLayoutGridLayout.cols * self.CustomLayoutGridLayout.rows) <= (LetzterTisch +1): self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1 self.tischerstellung(Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe) def tischentfernen(self, widget): self.Warnlabel = 0 if len(self.Tischliste) <= 1: if hasattr(self, 'CustomLayoutBottomLabel'): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel=1 print 'das ist der Letzte Tisch, der kann nicht entfernt werden' if self.Warnlabel == 0: self.CustomLayoutBottomLabel= Label(text='Das ist der Letzte Tisch,\n der kann nicht \n entfernt werden', text_size = self.size) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: Zielwidget = self.CustomLayoutGridLayout Zielwidget.remove_widget(self.Tischliste[-1]['Objekt']) del self.Tischliste[-1] LetzterTisch = self.Tischliste[-1]['Nummer'] print 'die anzahl der Tische ist nun:', LetzterTisch pass #### function for adding a column to layout #################################### def spaltehinzufuegen(self, widget): if self.CustomLayoutGridLayout.cols >= 1: if hasattr(self, 'CustomLayoutBottomLabel'): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) self.WarnLabel = 0 self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols + 1 print 'Zeile hinzufuegen' def spalteentfernen(self, widget): self.Warnlabel = 0 if self.CustomLayoutGridLayout.cols <= 1: if hasattr(self, 'CustomLayoutBottomLabel'): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel=1 print 'das ist die letzte Tischreihe, sie kann nicht entfernt werden' if self.Warnlabel == 0: self.CustomLayoutBottomLabel= Label(text='Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden', text_size = self.size) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: TischanzahlVerbleibend = (self.CustomLayoutGridLayout.cols -1) * self.CustomLayoutGridLayout.rows for i in range(len(self.Tischliste[TischanzahlVerbleibend:])): self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend+ i]['Objekt']) del self.Tischliste[TischanzahlVerbleibend:] self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols - 1 #### function for adding a row to layout #################################### def zeilehinzufuegen(self, widget): if self.CustomLayoutGridLayout.rows >= 1: if hasattr(self, 'CustomLayoutBottomLabel'): self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel) self.WarnLabel = 0 self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1 print 'Zeile hinzufuegen' def zeileentfernen(self, widget): self.Warnlabel = 0 if self.CustomLayoutGridLayout.rows <= 1: if hasattr(self, 'CustomLayoutBottomLabel'): # obj.attr_name exists. if self.CustomLayoutBottomLabel in self.CustomLayout.children: self.Warnlabel=1 print 'das ist die letzte Tischreihe, sie kann nicht entfernt werden' if self.Warnlabel == 0: self.CustomLayoutBottomLabel= Label(text='Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden', text_size = self.size) self.CustomLayout.add_widget(self.CustomLayoutBottomLabel) else: TischanzahlVerbleibend = (self.CustomLayoutGridLayout.rows -1) * self.CustomLayoutGridLayout.cols for i in range(len(self.Tischliste[TischanzahlVerbleibend:])): self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend+ i]['Objekt']) del self.Tischliste[TischanzahlVerbleibend:] self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows - 1 def bestellung(self, widget): TischNr = widget.id PopupFloatLayout = FloatLayout() popup = Popup(title='Bestellung für Tisch ' + str(TischNr), content=PopupFloatLayout,size_hint=(1, 1) ) ButtonExit = Button(text="Exit", pos_hint={'x': 0.8, 'y': 1.005}, size_hint = [0.2,0.065], on_release = popup.dismiss) PopupBoxLayout = BoxLayout(orientation='vertical', size_hint = [1.05, 1]) PopupFloatLayout.add_widget(PopupBoxLayout) ButtonKasse = Button(text='Kasse', size_hint = [1,0.08]) PopupBoxLayout.add_widget(ButtonKasse) HoeheUebrig = PopupFloatLayout.height - sum(child.height for child in PopupFloatLayout.children) print PopupFloatLayout.height print ButtonKasse.height print HoeheUebrig # create a default grid layout with custom width/height ScrollviewGridLayout = GridLayout(cols=1,size_hint=(1, None), spacing = 10) # when we add children to the grid layout, its size doesn't change at # all. we need to ensure that the height will be the minimum required to # contain all the childs. (otherwise, we'll child outside the bounding # box of the childs) ScrollviewGridLayout.bind(minimum_height=ScrollviewGridLayout.setter('height')) # add button into that grid for i in range(30): ScrollViewBoxLayout = BoxLayout(size_hint = [1, None], size_y=50) button1 = Button(text='button1') button2 = Button(text='button2') ButtonBoxLayout = BoxLayout(orientation='vertical') button3_1 = Button(text='+') button3_2 = Button(text='-') ButtonBoxLayout.add_widget(button3_1) ButtonBoxLayout.add_widget(button3_2) button4 = Button(text='button4') ScrollViewBoxLayout.add_widget(button1) ScrollViewBoxLayout.add_widget(button2) ScrollViewBoxLayout.add_widget(ButtonBoxLayout) ScrollViewBoxLayout.add_widget(button4) ## btn = Button(text=str(i), size=(480, 40), ## size_hint=(None, None)) ScrollviewGridLayout.add_widget(ScrollViewBoxLayout) # create a scroll view, with a size < size of the grid PopupScrollView = ScrollView(size_hint=(1, 1), pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False, scroll_timeout = 80) PopupScrollView.add_widget(ScrollviewGridLayout) PopupBoxLayout.add_widget(PopupScrollView) ## PopupGridLayout = GridLayout(cols = 4) ## PopupBoxLayout.add_widget(PopupGridLayout) ## button1 = Button(text='button1') ## button2 = Button(text='button2') ## button3 = Button(text='button3') ## button4 = Button(text='button4') ## PopupGridLayout.add_widget(button1) ## PopupGridLayout.add_widget(button2) ## PopupGridLayout.add_widget(button3) ## PopupGridLayout.add_widget(button4) PopupFloatLayout.add_widget(ButtonExit) popup.open() def abrechnung(self, widget): TischNr = widget.id ScreenmanagerPopup = CustomScreenManager() popup = Popup(title='Abrechnung für ' + str(TischNr), content=ScreenmanagerPopup,size_hint=(1, 1) ) popup.open() def bestellungaendern(self, widget): pass def tischbenennen(self, widget): TischNr = widget.id PopupBox1LayoutTischBennenen = BoxLayout(orientation = 'vertical') popup = Popup(title='Tisch Nr. ' + str(TischNr) + 'benennen', content=PopupBox1LayoutTischBennenen, size_hint=(0.75, 0.5)) EingabeTextfeld = TextInput(text='hier Tischbezeichnung eintragen - Funktion muss noch eingebaut werden') PopupBox1LayoutTischBennenen.add_widget(EingabeTextfeld) PopupBoxLayoutTischBenennen = BoxLayout(orientation = 'horizontal', size_hint=(1,1)) ButtonAbbrechenTischBenennen = Button(text="Abbrechen", size_hint=(0.5, 0.5)) ButtonAbbrechenTischBenennen.bind(on_press=popup.dismiss) ButtonOkTischBenennen = Button(text="OK", size_hint=(0.5, 0.5)) ButtonOkTischBenennen.bind(on_press=popup.dismiss) PopupBox1LayoutTischBennenen.add_widget(PopupBoxLayoutTischBenennen) PopupBoxLayoutTischBenennen.add_widget(ButtonAbbrechenTischBenennen) PopupBoxLayoutTischBenennen.add_widget(ButtonOkTischBenennen) #popup.add_widget popup.open() pass #### function for exporting Data to file #################################### def datenpickeln(self, widget): BonListe = self.HauptCarousel2.Texteingabe.text '''function to pickle data to make it ready for sending''' try: with open('bonliste.txt', 'w+b') as BonListeDaten_File: pickle.dump(BonListe, BonListeDaten_File) except IOError as err: print('Dateifehler: ' + str(err)) except pickle.PickleError as perr: print('Pickling Fehler: ' + str(perr)) #### function for importing Data to file #################################### def datenentpickeln(self, widget): with open('bonliste.txt', 'rb') as BonListeDaten_File_entpickelt: BonListeWiederhergestellt = pickle.load(BonListeDaten_File_entpickelt) print 'die entpickelte BinListe ist: ' print BonListeWiederhergestellt BonListe = BonListeWiederhergestellt self.HauptCarousel3.Textausgabe.text = BonListe
class MyApp(App): def build(self): self.title = 'Big Bang Factory' #--:Initiating plot pan self.fig, self.ax, self.canvas = self.PlotPan() self.fig0, self.ax0, self.canvas0 = self.PlotPan() #--: Home Page self.img = mpimg.imread('BBF_frontpage.png') self.ax.imshow(self.img) self.anim_running = True self.anim_compare = True self.settings_running = True self.lensing_running = True #--: Widgets btn_user = IconButton(source='./icons/user.png', text='', size_hint_x=None, width=50) btn_user.bind(on_release=self.show_popup_user) btn_sim = IconButton(source='./icons/sim.png', size_hint_x=None, width=50) btn_sim.bind(on_release=self.show_popup_sim) btn_lens = IconButton(source='./icons/lens.png', size_hint_x=None, width=50) btn_lens.bind(on_release=self.lensing_icons) btn_settings = IconButton(source='./icons/settings.png', size_hint_x=None, width=50) btn_settings.bind(on_release=self.settings_icons) btn_home = IconButton(source='./icons/home.png', size_hint_x=None, width=50) btn_home.bind(on_release=self.clean) self.btn_pause = IconButton(source='./icons/pause.png', size_hint_x=None, width=50) self.btn_pause.bind(on_press=self.pause) self.btn_compare = IconButton(source='./icons/compare.ico', size_hint_x=None, width=50) self.btn_compare.bind(on_press=self.compare) self.btn_stop = IconButton(source='./icons/stop.png', size_hint_x=None, width=50) self.btn_stop.bind(on_press=self.sim_stop) self.btn_sim_save = IconButton(source='./icons/save.png', size_hint_x=None, width=50) self.btn_sim_save.bind(on_release=self.save_movie) self.btn_send = IconButton(source='./icons/send.ico', size_hint_x=None, width=50) self.btn_send.bind(on_release=self.send_movie) self.btn_database = IconButton(source='./icons/database.png', size_hint_x=None, width=50) self.btn_database.bind(on_release=self.show_popup_simselect) self.btn_savedir = IconButton(source='./icons/savedir.png', size_hint_x=None, width=50) self.btn_savedir.bind(on_release=self.show_popup_dirselect) self.btn_halo = IconButton(source='./icons/halo.png', size_hint_x=None, width=50) self.btn_halo.bind(on_release=self.HaloLensedImage) self.btn_cluster = IconButton(source='./icons/cluster.gif', size_hint_x=None, width=50) self.btn_cluster.bind(on_release=self.MapLensedImage) self.slider_comdist = Slider(min=0.0, max=100.0, value=10.0, step=10.0, orientation='horizontal', value_track=True, value_track_color=[1, 0, 0, 1], size_hint_x=None, width=150) #--:Page Layout #--- Page 1 Pages = PageLayout(orientation="vertical") self.Box_sim = BoxLayout(orientation="horizontal") self.Box_sim.add_widget(self.canvas) self.label_status = Label(text='Welcome to BBF', size_hint_y=None, height='28dp') self.BigBox_sim = BoxLayout(orientation="vertical") self.BigBox_sim.add_widget(self.Box_sim) self.BigBox_sim.add_widget(self.label_status) Pages.add_widget(self.BigBox_sim) #--- Page 2 self.Settings_Page = GridLayout(cols=1, row_force_default=True, row_default_height=40) self.subSettings_Page = GridLayout(cols=1, row_force_default=True, row_default_height=40) self.Settings_Page.add_widget(btn_user) self.Settings_Page.add_widget(btn_sim) self.Settings_Page.add_widget(btn_lens) self.Settings_Page.add_widget(btn_settings) self.Settings_Page.add_widget(self.btn_send) self.Settings_Page.add_widget(btn_home) self.Box_icons = BoxLayout(orientation='vertical') self.Box_icons.add_widget(self.Settings_Page) self.Box_icons.add_widget(self.subSettings_Page) Pages.add_widget(self.Box_icons) return Pages def PlotPan(self): #--:PLot Pan fig = plt.Figure(facecolor='0.7', frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) canvas = FigureCanvasKivyAgg(fig) return fig, ax, canvas def compare(self, *args): if self.anim_compare: self.Box_sim.add_widget(self.canvas0) self.anim_compare = False else: self.Box_sim.remove_widget(self.canvas0) self.anim_compare = True def show_popup_user(self, *args): self.label_name = Image(source='./icons/name.png') self.input_name = TextInput(text='', multiline=False, size_hint_x=None, width=200) self.label_email = Image(source='./icons/email.png') self.input_email = TextInput(text='', multiline=False, size_hint_x=None, width=200) self.btn_cam = IconButton(source='./icons/photo.png') self.btn_cam.bind(on_release=self.show_popup_cam) Settings_content = BoxLayout(orientation='horizontal') subSettings_content = BoxLayout(orientation='vertical') user_content = GridLayout(cols=2, size_hint_y=None, height='58dp') user_content.add_widget(self.label_name) user_content.add_widget(self.input_name) user_content.add_widget(self.label_email) user_content.add_widget(self.input_email) subSettings_content.add_widget(Image(source='./icons/sir.png')) subSettings_content.add_widget(user_content) Settings_content.add_widget(subSettings_content) Settings_content.add_widget(self.btn_cam) self.popup = Popup(title='', size_hint=(None, None), size=(500, 200), content=Settings_content, auto_dismiss=True, separator_height=0) self.popup.open() def lensing_icons(self, *args): self.Box_sim.add_widget(self.canvas0) self.subSettings_Page.remove_widget(self.btn_pause) self.subSettings_Page.remove_widget(self.btn_compare) #self.subSettings_Page.remove_widget(self.btn_preview) self.subSettings_Page.remove_widget(self.btn_sim_save) if self.lensing_running: self.subSettings_Page.add_widget(self.btn_halo) self.subSettings_Page.add_widget(self.btn_cluster) self.subSettings_Page.add_widget(self.slider_comdist) self.lensing_running = False else: self.subSettings_Page.remove_widget(self.btn_halo) self.subSettings_Page.remove_widget(self.btn_cluster) self.subSettings_Page.remove_widget(self.slider_comdist) self.lensing_running = True def settings_icons(self, *args): if self.settings_running: self.subSettings_Page.add_widget(self.btn_savedir) self.subSettings_Page.add_widget(self.btn_database) self.settings_running = False else: self.subSettings_Page.remove_widget(self.btn_savedir) self.subSettings_Page.remove_widget(self.btn_database) self.settings_running = True def show_popup_dirselect(self, *args): self.dirselect = FileChooserListView(dirselect=True) box_dir = BoxLayout(orientation='vertical') box_dir.add_widget(self.dirselect) btn_select = IconButton(source='./icons/select.ico', size_hint_y=None, height='48dp') btn_select.bind(on_release=self.selectdir) box_dir.add_widget(btn_select) self.popup_dirselect = Popup(title='', size_hint=(.680, .460), content=box_dir, auto_dismiss=True, separator_height=0) self.popup_dirselect.open() def show_popup_simselect(self, *args): self.simselect = FileChooserListView(dirselect=True) box_dir = BoxLayout(orientation='vertical') box_dir.add_widget(self.simselect) sim_select = IconButton(source='./icons/select.ico', size_hint_y=None, height='48dp') sim_select.bind(on_release=self.simselectdir) box_dir.add_widget(sim_select) self.popup_dirselect = Popup(title='', size_hint=(.680, .460), content=box_dir, auto_dismiss=True, separator_height=0) self.popup_dirselect.open() def selectdir(self, *args): self.savedir = self.dirselect.selection[0] print self.savedir self.popup_dirselect.dismiss() def simselectdir(self, *args): self.simdir = self.simselect.selection[0] print self.simdir self.popup_dirselect.dismiss() def show_popup_preview(self, *args): player = Video(source=self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_mux_movie.mp4", state='play', options={'allow_stretch': True}) videobox = BoxLayout() videobox.add_widget(player) self.popup_player = Popup(title='', size_hint=(.680, .460), content=videobox, auto_dismiss=True, separator_height=0) self.popup_player.open() def show_popup_sim(self, *args): self.btn_sim_start = IconButton(source='./icons/play.png', text='', size_hint_y=None, height='48dp') self.btn_sim_start.bind(on_release=self.sim_start) self.image_dm = Image(source='./icons/dm.png') self.value_dm = Label(text='0.25') self.image_de = Image(source='./icons/de.png') self.value_de = Label(text='0.75') self.slider_dm = Slider(min=0.0, max=1.0, value=0.25, step=0.25, orientation='vertical', value_track=True, value_track_color=[1, 0, 0, 1], size_hint_y=None, height='160dp') self.slider_dm.bind(value=self.update_dm) self.slider_de = Slider(min=0.0, max=1.0, value=0.75, step=0.25, orientation='vertical', value_track=True, value_track_color=[1, 0, 0, 1], size_hint_y=None, height='160dp') self.slider_de.bind(value=self.update_de) self.label_dm = Label(text=text_dict['t24']) self.label_de = Label(text=text_dict['t20']) self.label_png = Label(text=text_dict['t27']) self.label_gvr = Label(text=text_dict['t31']) self.spinner_dm = Spinner(text=text_dict['t54'], values=(text_dict['t25'], text_dict['t26'])) self.spinner_de = Spinner(text=text_dict['t54'], values=(text_dict['t21'], text_dict['t22'], text_dict['t23'])) self.spinner_png = Spinner(text=text_dict['t54'], values=(text_dict['t28'], text_dict['t29'], text_dict['t30'])) self.spinner_gvr = Spinner(text=text_dict['t54'], values=(text_dict['t32'], text_dict['t33'])) Settings_content = BoxLayout(orientation='horizontal') slider_dm_content = GridLayout(cols=1) slider_dm_content.add_widget(self.image_dm) slider_dm_content.add_widget(self.value_dm) slider_dm_content.add_widget(self.slider_dm) slider_de_content = GridLayout(cols=1) slider_de_content.add_widget(self.image_de) slider_de_content.add_widget(self.value_de) slider_de_content.add_widget(self.slider_de) subSettings_content = GridLayout(cols=2, size_hint_x=None, width=350) subSettings_content.add_widget(self.label_dm) subSettings_content.add_widget(self.spinner_dm) subSettings_content.add_widget(self.label_de) subSettings_content.add_widget(self.spinner_de) subSettings_content.add_widget(self.label_png) subSettings_content.add_widget(self.spinner_png) subSettings_content.add_widget(self.label_gvr) subSettings_content.add_widget(self.spinner_gvr) Settings_content.add_widget(subSettings_content) Settings_content.add_widget(slider_dm_content) Settings_content.add_widget(slider_de_content) Settings_content.add_widget(self.btn_sim_start) self.popup_sim = Popup(title='', size_hint=(None, None), size=(600, 280), content=Settings_content, auto_dismiss=True, separator_height=0) self.popup_sim.open() def update_dm(self, instance, value): if value == 0.0: self.value_dm.text = str(0.1) else: self.value_dm.text = str(value) def update_de(self, instance, value): self.value_de.text = str(value) def show_popup_cam(self, *args): self.cam = Camera(resolution=(640, 480)) content = BoxLayout(orientation='vertical') btn_capture = IconButton(source='./icons/shot.png', text='', size_hint_y=None, height='48dp') btn_capture.bind(on_release=self.camera) content.add_widget(self.cam) content.add_widget(btn_capture) self.popup = Popup(title='', size_hint=(None, None), size=('540dp', '480dp'), content=content, auto_dismiss=True, separator_height=0) self.popup.open() def clean(self, *args): self.ax.clear() self.ax.axis('off') self.ax.imshow(self.img) self.canvas.draw() self.subSettings_Page.remove_widget(self.btn_pause) self.subSettings_Page.remove_widget(self.btn_compare) self.subSettings_Page.remove_widget(self.btn_sim_save) self.subSettings_Page.remove_widget(self.btn_stop) self.subSettings_Page.remove_widget(self.btn_halo) self.subSettings_Page.remove_widget(self.btn_cluster) self.subSettings_Page.remove_widget(self.slider_comdist) self.Box_sim.remove_widget(self.canvas0) def camera(self, *args): self.cam.play = not self.cam.play self.img_filename = self.input_name.text self.img_filenamedir = ''.join(e for e in self.img_filename if e.isalnum()) try: os.stat(CWD + "/tmp") except: os.mkdir(CWD + "/tmp") try: os.stat(self.savedir + "/" + self.img_filenamedir) except: os.mkdir(self.savedir + "/" + self.img_filenamedir) self.cam.export_to_png(CWD + "/tmp/" + self.img_filenamedir + "_image.jpg") self.btn_cam.source = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg" self.popup.dismiss() def sim_start(self, *args): self.ax.clear() self.ax.axis('off') self.canvas.draw() self.ax0.clear() self.ax0.axis('off') self.canvas0.draw() self.sim_nonStand() self.sim_stand() self.subSettings_Page.add_widget(self.btn_pause) self.subSettings_Page.add_widget(self.btn_compare) self.subSettings_Page.add_widget(self.btn_stop) self.subSettings_Page.add_widget(self.btn_sim_save) self.popup_sim.dismiss() def sim_stop(self, *args): self.subSettings_Page.remove_widget(self.btn_pause) self.subSettings_Page.remove_widget(self.btn_compare) self.subSettings_Page.remove_widget(self.btn_stop) self.subSettings_Page.remove_widget(self.btn_sim_save) self.ax.clear() self.ax.axis('off') self.canvas.draw() self.ax0.clear() self.ax0.axis('off') self.canvas0.draw() def sim_stand(self): Simu_Dir = "BBF_Lambda_0.25-0.75" + "/Dens-Maps/" cosmo = wCDM(70.3, 0.25, 0.75, w0=-1.0) filenames = sorted(glob.glob(self.simdir + "/" + Simu_Dir + '*.npy')) lga = np.linspace(np.log(0.05), np.log(1.0), 300) a = np.exp(lga) z = 1. / a - 1.0 lktime = cosmo.lookback_time(z).value def animate(filename): image = np.load(filename) indx = filenames.index( filename ) #; image=ndimage.gaussian_filter(image, sigma= sigmaval, truncate=truncateval, mode='wrap') im.set_data(image + 1) #; im.set_clim(image.min()+1.,image.max()+1.) self.time0.set_text('%s %s' % (round(lktime[indx], 4), text_dict['t49'])) return im dens_map = np.load( filenames[0] ) #; dens_map=ndimage.gaussian_filter(dens_map, sigma= sigmaval, truncate=truncateval, mode='wrap') #; dens_map0 = load(filenames[-1]); #print dens_map0.min()+1, dens_map0.max()+1. im = self.ax0.imshow(dens_map + 1, cmap=cm.magma, norm=colors.LogNorm(vmin=1., vmax=1800., clip=True), interpolation="bicubic") #, clim = (1, 1800.+1.)) self.time0 = self.ax0.text(0.1, 0.05, text_dict['t43'] + ' %s Gyr' % round(lktime[0], 4), horizontalalignment='left', verticalalignment='top', color='white', transform=self.ax0.transAxes, fontsize=10) arr_hand = mpimg.imread(CWD + "/tmp/" + self.img_filenamedir + "_image.jpg") imagebox = OffsetImage(arr_hand, zoom=.1) xy = (0.1, 0.15) # coordinates to position this image ab = AnnotationBbox(imagebox, xy, xybox=(0.1, 0.15), xycoords='axes fraction', boxcoords='axes fraction', pad=0.1) self.ax0.add_artist(ab) arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = (0.9, 0.9) # coordinates to position this image ab1 = AnnotationBbox(imagebox1, xy, xybox=(0.9, 0.9), xycoords='axes fraction', boxcoords='axes fraction', pad=0.1) self.ax0.add_artist(ab1) #iMpc = lambda x: x*1024/125 #x in Mpc, return in Pixel *3.085e19 ob = AnchoredHScaleBar(size=0.1, label="10Mpc", loc=4, frameon=False, pad=0.6, sep=2, color="white", linewidth=0.8) self.ax0.add_artist(ob) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], text_dict['t50'], text_dict['t20'], text_dict['t21'], text_dict['t24'], text_dict['t25'], text_dict['t27'], text_dict['t28'], text_dict['t31'], text_dict['t32']) print sim_details_text self.ax0.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax0.transAxes, alpha=0.5) self.ani0 = animation.FuncAnimation(self.fig0, animate, filenames, repeat=False, interval=25, blit=False) self.ax0.axis('off') self.ax0.get_xaxis().set_visible(False) self.ax0.get_yaxis().set_visible(False) self.canvas0.draw() def sim_nonStand(self): Simu_Dir = self.model_select() + "/Dens-Maps/" cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0) filenames = sorted(glob.glob(self.simdir + "/" + Simu_Dir + '*.npy')) lga = np.linspace(np.log(0.05), np.log(1.0), 300) a = np.exp(lga) z = 1. / a - 1.0 lktime = cosmo.lookback_time(z).value def animate(filename): image = np.load(filename) indx = filenames.index( filename ) #; image=ndimage.gaussian_filter(image, sigma= sigmaval, truncate=truncateval, mode='wrap') im.set_data(image + 1) #; im.set_clim(image.min()+1.,image.max()+1.) self.time.set_text('%s %s' % (round(lktime[indx], 4), text_dict['t49'])) return im dens_map = np.load( filenames[0] ) #; dens_map=ndimage.gaussian_filter(dens_map, sigma= sigmaval, truncate=truncateval, mode='wrap') #; dens_map0 = load(filenames[-1]); #print dens_map0.min()+1, dens_map0.max()+1. im = self.ax.imshow(dens_map + 1, cmap=cm.magma, norm=colors.LogNorm(vmin=1., vmax=1800., clip=True), interpolation="bicubic") #, clim = (1, 1800.+1.)) self.time = self.ax.text(0.1, 0.05, text_dict['t43'] + ' %s Gyr' % round(lktime[0], 4), horizontalalignment='left', verticalalignment='top', color='white', transform=self.ax.transAxes, fontsize=10) arr_hand = mpimg.imread(CWD + "/tmp/" + self.img_filenamedir + "_image.jpg") imagebox = OffsetImage(arr_hand, zoom=.1) xy = (0.1, 0.15) # coordinates to position this image ab = AnnotationBbox(imagebox, xy, xybox=(0.1, 0.15), xycoords='axes fraction', boxcoords='axes fraction', pad=0.1) self.ax.add_artist(ab) arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = (0.9, 0.9) # coordinates to position this image ab1 = AnnotationBbox(imagebox1, xy, xybox=(0.9, 0.9), xycoords='axes fraction', boxcoords='axes fraction', pad=0.1) self.ax.add_artist(ab1) #iMpc = lambda x: x*1024/125 #x in Mpc, return in Pixel *3.085e19 ob = AnchoredHScaleBar(size=0.1, label="10Mpc", loc=4, frameon=False, pad=0.6, sep=2, color="white", linewidth=0.8) self.ax.add_artist(ob) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax.transAxes, alpha=0.5) self.ani = animation.FuncAnimation(self.fig, animate, filenames, repeat=False, interval=25, blit=False) self.ax.axis('off') self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.canvas.draw() def pause(self, *args): if self.anim_running: self.btn_pause.source = './icons/play.png' self.ani.event_source.stop() self.ani0.event_source.stop() self.anim_running = False else: self.btn_pause.source = './icons/pause.png' self.ani.event_source.start() self.ani0.event_source.start() self.anim_running = True def save_movie(self, *args): print 'Saving movie ....' self.label_status.text = 'Saving movie ....' simulate = multiprocessing.Process(None, self.moviesave) simulate.start() def moviesave(self): writer = animation.writers['ffmpeg']( fps=15) #, bitrate=16000, codec='libx264') self.ani.save(self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_movie.mp4", writer=writer, dpi=dpi) #, savefig_kwargs={'dpi' : 200} video_file = self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_movie.mp4" muxvideo_file = self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_mux_movie.mp4" audio_file = "ChillingMusic.wav" cmd = 'ffmpeg -i ' + video_file + ' -i ' + audio_file + ' -shortest ' + muxvideo_file subprocess.call(cmd, shell=True) print('Saving and Muxing Done') self.label_status.text = 'Saving and Muxing Done!!' self.muxvideo = self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_mux_movie.mp4" os.remove(video_file) def MapLensedImage(self, *args): self.ax.clear() self.ax.axis('off') fileimage = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg" Simu_Dir = self.model_select() + "/Lens-Maps/" filelens = self.simdir + "/" + Simu_Dir + self.model_name + 'kappaBApp_2.fits' image, xsize, ysize = readimage(fileimage) image_arr = np.array(image) alpha1, alpha2 = buildlens(filelens) cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0) self.maplensedimage = deflect(image_arr, alpha1, alpha2, xsize, ysize, self.slider_comdist.value, cosmo, "LSS") self.ax.imshow(self.maplensedimage) arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = [950.0, 85.0] ab1 = AnnotationBbox(imagebox1, xy, xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.1) self.ax.add_artist(ab1) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax.transAxes, alpha=0.5) self.ax.axis('off') self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.canvas.draw() #imsave(self.savedir + "/" + self.img_filename + "_LensedMap_Photo.jpg", self.maplensedimage) self.fig.savefig(self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_LensedMap_Photo.png") self.LensedMap_Photo = self.img_filename + "_LensedMap_Photo.png" self.showlensMap() def HaloLensedImage(self, *args): self.ax.clear() self.ax.axis('off') fileimage = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg" Simu_Dir = self.model_select() + "/Lens-Maps/" filelens = self.simdir + "/" + Simu_Dir + self.model_name + '_Halo.fits' image, xsize, ysize = readimage(fileimage) image_arr = np.array(image) alpha1, alpha2 = buildlens(filelens) cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0) self.halolensedimage = deflect(image_arr, alpha1, alpha2, xsize, ysize, self.slider_comdist.value, cosmo, "HALO") self.ax.imshow(self.halolensedimage) arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = [950.0, 85.0] ab1 = AnnotationBbox(imagebox1, xy, xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.1) self.ax.add_artist(ab1) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax.transAxes, alpha=0.5) self.ax.axis('off') self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.canvas.draw() #imsave(self.savedir + "/" + self.img_filename + "_LensedHalo_Photo.jpg", self.halolensedimage) self.fig.savefig(self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_LensedHalo_Photo.png") self.LensedHalo_Photo = self.img_filename + "_LensedHalo_Photo.png" self.showlenscluster() def showlensMap(self): self.ax0.clear() self.ax0.axis('off') Simu_Dir = self.model_select() + "/Lens-Maps/" filename = self.simdir + "/" + Simu_Dir + self.model_name + 'kappaBApp_2.fits' self.Lens_map = fits.getdata(filename, ext=0) LenImg = self.ax0.imshow( self.Lens_map + 1, cmap=matplotlib.cm.magma, norm=matplotlib.colors.LogNorm(), interpolation="bicubic") #vmin=1., vmax=1800., clip = True arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = [950.0, 85.0] ab1 = AnnotationBbox(imagebox1, xy, xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.1) self.ax0.add_artist(ab1) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax0.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax0.transAxes, alpha=0.5) self.ax0.axis('off') self.ax0.get_xaxis().set_visible(False) self.ax0.get_yaxis().set_visible(False) self.canvas0.draw() #imsave(self.savedir + "/" + self.img_filename + "_LensedMap.jpg", log(self.Lens_map + 1), cmap=matplotlib.cm.magma) self.fig0.savefig(self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_LensedMap.png") self.LensedMap = self.img_filename + "_LensedMap.png" def showlenscluster(self): self.ax0.clear() self.ax0.axis('off') Simu_Dir = self.model_select() + "/Lens-Maps/" filename = self.simdir + "/" + Simu_Dir + self.model_name + '_Halo.fits' self.Halo_map = fits.getdata(filename, ext=0) HaloImg = self.ax0.imshow( self.Halo_map + 1, cmap=matplotlib.cm.magma, norm=matplotlib.colors.LogNorm(), interpolation="bicubic") #vmin=1., vmax=1800., clip = True arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = [950.0, 85.0] ab1 = AnnotationBbox(imagebox1, xy, xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.1) self.ax0.add_artist(ab1) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax0.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax0.transAxes, alpha=0.5) self.ax0.axis('off') self.ax0.get_xaxis().set_visible(False) self.ax0.get_yaxis().set_visible(False) self.canvas0.draw() #imsave(self.savedir + "/" + self.img_filename + "_LensedHalo.jpg", log(self.Halo_map + 1), cmap=matplotlib.cm.magma) self.fig0.savefig(self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_LensedHalo.png") self.LensedHalo = self.img_filename + "_LensedHalo.png" def model_select(self): SimDict = { text_dict['t21']: 'Lambda_', text_dict['t22']: 'Quint_', text_dict['t23']: 'Phantom_', text_dict['t25']: 'Lambda_', text_dict['t26']: 'wDM_0.1-', text_dict['t28']: 'Lambda_', text_dict['t29']: 'LocalPNG_1000-', text_dict['t30']: 'LocalPNG_-1000-', text_dict['t32']: 'Lambda_', text_dict['t33']: 'MGfR_1.2-' } if self.spinner_de.text != text_dict['t21']: run_type = SimDict[self.spinner_de.text] elif self.spinner_dm.text != text_dict['t25']: run_type = SimDict[self.spinner_dm.text] elif self.spinner_png.text != text_dict['t28']: run_type = SimDict[self.spinner_png.text] elif self.spinner_gvr.text != text_dict['t32']: run_type = SimDict[self.spinner_gvr.text] else: run_type = SimDict[self.spinner_de.text] if self.slider_dm.value == 0.0: Omega_m = 0.1 else: Omega_m = self.slider_dm.value Omega_k = 1. - (Omega_m + self.slider_de.value) if Omega_k == 0: self.SC_Type = text_dict['t50'] elif Omega_k > 0: self.SC_Type = text_dict['t52'] else: self.SC_Type = text_dict['t51'] model = "BBF_" + run_type + str(Omega_m) + "-" + str( self.slider_de.value) self.model_name = run_type + str(Omega_m) + "-" + str( self.slider_de.value) print model return model def send_movie(self, *args): print 'Sending ....' self.label_status.text = 'Sending ....' Thread(target=self.moviesend).start() def moviesend(self): #files=sorted(glob.glob(self.img_filename + '/*')) files = os.listdir(self.savedir + "/" + self.img_filenamedir) From = '*****@*****.**' PWD = 'unibo2018' emailling(self.input_name.text, From, self.input_email.text, PWD, self.savedir + "/" + self.img_filenamedir, files) self.label_status.text = 'Mail Sent !!'