class LoginScreen(GridLayout): def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) self.cols = 2 x =Label(text='Utilizator ') self.add_widget(x) self.username = TextInput(multiline=False) self.add_widget(self.username) self.add_widget(Label(text='Parola')) self.password = TextInput(password=True, multiline=False) self.add_widget(self.password) self.password.bind(on_text_validate= self.verific_user_si_parola) def verific_user_si_parola(self,t): print t,"instanta" text_user = self.username.text text_pass = self.password.text if (text_user == "test" and text_pass=="test"): self.clear_widgets() self.add_widget(Label(text='Bine ai venit!')) else: self.username.select_all() self.username.delete_selection() self.password.select_all() self.password.delete_selection()
def download(self,instance): print "Download music" k = instance.parent.parent.parent.children[0] k.clear_widgets() h = TextInput(multiline = False) h.bind(on_text_validate = self.on_enter) k.add_widget(h)
class TwistedClientApp(App): connection = None def build(self): root = self.setup_gui() self.connect_to_server() return root def setup_gui(self): self.textbox = TextInput(size_hint_y=.1, multiline=False) self.textbox.bind(on_text_validate=self.send_message) self.label = Label(text='connecting...\n') self.layout = BoxLayout(orientation='vertical') self.layout.add_widget(self.label) self.layout.add_widget(self.textbox) return self.layout def connect_to_server(self): reactor.connectTCP('localhost', 8000, EchoFactory(self)) def on_connection(self, connection): self.print_message("connected succesfully!") self.connection = connection def send_message(self, *args): msg = self.textbox.text if msg and self.connection: self.connection.write(str(self.textbox.text)) self.textbox.text = "" def print_message(self, msg): self.label.text += msg + "\n"
class AddBlockButton(Button): def __init__(self, *args, **kwargs): super(AddBlockButton, self).__init__(*args, **kwargs) self.bind(on_release=self.openPopup) box=BoxLayout(padding=10) self.Input=TextInput(text="New Block", multiline=False, font_size=18) self.Input.bind(on_text_validate=self.addBlock) b=Button(text="Add it") b.bind(on_release=self.addBlock) box.add_widget(self.Input) box.add_widget(b) self.addPopup = Popup(title="Add A New Block", size_hint=(None,None), size=(400,115), separator_color=[.9,.4,.2,1], background_color=[0,0,0,.6], content=box ) def openPopup(self,*args): self.addPopup.open() def addBlock(self,*args): tree = self.parentLayout.ids["blockstree"] b=TreeViewBlock(text=self.Input.text,is_open=True) b.parentTree=tree tree.add_node(b) blocks= createBlockDicts(tree.iterate_all_nodes()) #Update Blocks updateConfig({"blocks":blocks}) self.addPopup.dismiss()
# A simple kivy App, with a textbox to enter messages, and # a large label to display all the messages received from # the server class TwistedClientApp(App): #connection = None def build(self): root = self.setup_gui() self.connect_to_server() return root def setup_gui(self): self.textbox = TextInput(size_hint_y=.1, multiline=False) self.textbox.bind(on_text_validate=self.send_message) self.label = Label(text='server started\n') self.layout = BoxLayout(orientation='vertical') self.layout.add_widget(self.label) self.layout.add_widget(self.textbox) return self.layout def connect_to_server(self): reactor.listenTCP(8000, EchoFactory(self)) def on_connection(self, connection, clients): self.print_message("connected succesfully!") self.connection = connection self.clients = clients def send_message(self, *args): msg = self.textbox.text #if msg and self.connection:
class FArgument(Widget): """ the argument section of an fBlock """ def __init__(self, text="__", **kwargs): self.name = text super(self.__class__,self).__init__(**kwargs) with self.canvas: Color(0.6,0.4,0.4) self.bg = Rectangle(size=self.size, pos=self.pos) self.layout = BoxLayout(padding=[10,10,10,10]) self.textbox = TextInput(text=self.name) self.layout.add_widget(self.textbox) self.add_widget(self.layout) self.bind(size=self.redoLayout, pos=self.redoLayout) self.textbox.bind(text=self.updateText) def redoLayout(self, instance, value): self.bg.size = self.size self.bg.pos = self.pos self.layout.size = self.size self.layout.pos = self.pos def updateText(self, instance, value): self.name = self.textbox.text def __repr__(self): return self.name
class ConnectionScreen(Screen): def __init__(self, **kwargs): super(ConnectionScreen, self).__init__(**kwargs) self.root = Accordion() roleItem = AccordionItem(title='Role') self.root.add_widget(roleItem) serverItem = AccordionItem(title='Server') self.root.add_widget(serverItem) self.dmBtn = ToggleButton(text="DM", group="role") self.pcBtn = ToggleButton(text="Player", group="role", state="down") self.textinput = TextInput(text='John-LAPTOP', multiline=False) self.textinput.bind(on_text_validate=self.on_confirm) roleItem.add_widget(self.dmBtn) roleItem.add_widget(self.pcBtn) serverItem.add_widget(self.textinput) self.add_widget(self.root) def on_confirm(self, instance): global Combatants if self.dmBtn.state == "down": Combatants = Roster() t = threading.Thread(target = self.startServer) t.start() global isDM isDM = True elif self.pcBtn.state == "down": nameserver = Pyro4.locateNS(host=self.textinput.text) Combatants = Pyro4.Proxy("PYRONAME:Combatants") SS = SelectionScreen(name="Selection Screen") sm.add_widget(SS) self.manager.current = 'Selection Screen' def startServer(self): Pyro4.Daemon.serveSimple({Combatants: "Combatants"}, host=socket.gethostname(), ns=True)
def redraw(self, *args): self.clear_widgets() if self.child_name and self.child_name in self.parent_o.partner_data: self.add_widget(Label(text="Name:", halign='right')) self.add_widget(Label(text=self.child_name, height=25)) for attribute in partner_attributes: self.add_widget(Label(text="{0}:".format(attribute), halign='right')) #print "REDRAW", self.child_name, attribute, self.parent_o.partner_data if attribute in self.parent_o.partner_data[self.child_name]: pdata = self.parent_o.partner_data[self.child_name] if pdata[attribute]: value = pdata[attribute].encode('utf-8') else: value = '' else: value = '' c = TextInput(text=value, height='29px',size_hint_y=None, multiline=False) c.attribute = attribute c.bind(text = self.update_textinput) self.add_widget(c) #c.size_hint_y = 0.1 c.set_height = '25px'
class HomePage(PageBase): """HomePage of the App. This is the first page that the user will see.""" def __init__(self, app): """Constructor""" # Call the base. super(HomePage, self).__init__(app) # Load the backend self.backend = SpecialBackend(FlatfileBackend()) # Create a body manually, overriding the default. self.body = AnchorLayout(anchor_x='center', anchor_y='center') stack_layout = StackLayout(size_hint=(0.95, 0.6)) self.body.add_widget(stack_layout) text_layout = BoxLayout(anchor_x='left', anchor_y='center', size_hint=(0.8, None)) text_layout.height = '35px' stack_layout.add_widget(text_layout) def on_enter(sender): self._on_search(sender, self.query.text) self.query = TextInput(text='', multiline=False, hint_text='Type here...') self.query.bind(on_text_validate=on_enter) text_layout.add_widget(self.query) button_layout = BoxLayout(anchor_x='right', anchor_y='center', size_hint=(0.2, None)) button_layout.height = '35px' stack_layout.add_widget(button_layout) def on_search_press(sender): self._on_search(self.query, self.query.text) search = Button(text='Search!') search.width = '50px' search.bind(on_press=on_search_press) button_layout.add_widget(search) self.search_results = RichPage.get_page(app, [self], self.backend, 'search') def on_category_press(sender): RichPage.get_page(app, [self], self.backend, 'categories').show(self) self.hide() category = Button(text='Categories', size_hint=(None, None), height='35px') category.width = '100px' category.bind(on_press=on_category_press) self.body.add_widget(category) def _on_search(self, sender, value): """Called when the user trys to search.""" query = value self.query.text = '' self.backend.cached_search(query) self.search_results.reload() self.hide() self.search_results.show(self)
def build(self): """config = ConfigParser() config.read('conf.ini') self.config = Settings() # s.add_json_panel('My custom panel', config, 'settings_custom.json')""" self.icon = 'images/ic_launcher.png' self.osc_activities = [] self.speechs = [] self.osc_id = osc.listen(ipAddr='0.0.0.0', port=activity_port) self.count_requests = 0 self.timer_value = "40.10.10.1" if platform == 'android': from android import AndroidService service = AndroidService('Mentor Service', 'running') service.start('service started') self.service = service self.folder_music = "/storage/emulated/legacy/Music/PerAttivita" elif platform == 'win': self.folder_music = "C:\\Mao\\Progetti\\Musica\\MusicaSuNexus\\PerAttivita" else: self.folder_music = ".\\music" Logger.info("Folder music: {}".format(self.folder_music)) self.sequences = mentor_lib.Sequences() self.sequences.load_sequences() self.root = MentorWidget() text_input = TextInput(text=self.timer_value, font_size=40, multiline=False) #, size_hint=(None, None)) # font_size=20, text_input.foreground_color = [1, 1, 1, 1] text_input.background_color = [0, 0, 0, 0] text_input.shorten_from = 'center' #text_input.center_x = True #text_input.center_y = True text_input.bind(text=self.on_text_input_text) self.root.ids.grid_main.add_widget(text_input) btn = Button(text="Custom Timer") #, size_hint_y=None, height=40) #btn.height = text_input.content_height btn.bind(on_press=partial(self.start_sequence, "timer")) self.root.ids.grid_main.add_widget(btn) for title in self.sequences.titles: btn = Button(text=title)#, size_hint_y=None, height=40) btn.bind(on_press=partial(self.start_sequence, title)) self.root.ids.grid_main.add_widget(btn) #if len(self.sequences.titles)%2: # btn = Button(text="_ _", id='pippo') #, size_hint_y=None, height=40) # self.root.ids.grid_main.add_widget(btn) #self.start_sequence_ok = False #self.sequence_buttons = [] #for i in self.sequences.titles: #self.sequence_buttons.append(Button(text=str(i))) #self.sequence_buttons[-1].bind(on_press=self.start_sequence(str(i))) #self.sequence_buttons[-1].bind(on_release=self.start_sequence(str(i))) #btn.bind(state=self.start_sequence(str(i))) #btn.bind(on_release=self.root.start_sequence(btn.text)) #self.root.ids.grid_main.add_widget(self.sequence_buttons[-1]) #self.root.ids.grid_main.add_widget(Button(text=str(i), on_press=self.start_sequence(str(i)))) #self.start_sequence_ok = True osc.init() osc.bind(self.osc_id, self.msg_from_server, '/msg') osc.bind(self.osc_id, self.root.write_cockpit, '/osd') Clock.schedule_interval(self.timed_ops, .1) return self.root
def build(self): layout_main = BoxLayout( orientation='vertical', ) text_input = TextInput( font_size=150, height=200, size_hint_y=None, text='default', ) layout = FloatLayout() scatter = Scatter() label = Label( text="default", font_size=150, ) text_input.bind(text=label.setter('text')) layout.add_widget(scatter) scatter.add_widget(label) # Order is important - first is top/left layout_main.add_widget(text_input) layout_main.add_widget(layout) return layout_main
class GuessScreen(GridLayout): def __init__(self, **kwargs): super(GuessScreen, self).__init__(**kwargs) self.cols = 1 self.rows = 4 self.someone = self.get_someone() self.photo = AsyncImage(source=self.someone['image']) self.add_widget(self.photo) self.guess = TextInput(multiline=False, focus=True ) self.guess.bind(on_text_validate=self.on_enter) self.add_widget(self.guess) def get_someone(self): n_people = random.randint(0,len(people)-1) return people[n_people] def on_enter(self, value): print "Now guessing: ", self.someone['first_name'] if self.guess.text == self.someone['first_name']: print "Yay" self.someone = self.get_someone() self.photo.source = self.someone['image'] self.guess.text = "" else: print 'Boooo'
def build(self): topic = 'Python' layout = GridLayout(cols=2, size_hint_y=None, spacing=10, padding=(10,10,10,10)) layout.bind(minimum_height=layout.setter('height')) message = fetch(topic) for data in message: l = Button(text=data, text_size=(300, None), size_hint_y=None, padding=(5, 5), bold=True) # calculating height here before = l._label.render() l.text_size=(300, None) after = l._label.render() l.height = 60 + (after[1]/before[1])*before[1] # ammount of rows * single row height # end layout.add_widget(l) sub = ScrollView() sub.add_widget(layout) root = GridLayout(cols=1) title = Label(text='Facebook Mining Topic: ' + topic, font_size=30, size_hint_y=None, height=100) root.add_widget(title) textinput = TextInput(hint_text='Search ...', multiline=False, size_hint_y=None, height=40) textinput.bind(on_text_validate=on_enter) root.add_widget(textinput) root.add_widget(sub) return root
class TwistedClientApp(App): connection = None def build(self): root = self.setup_gui() self.connect_to_server() return root def setup_gui(self): self.textbox = TextInput(size_hint_y=.1, multiline=False) self.textbox.bind(on_text_validate=self.send_message) self.label = Label(text='connecting...\n') self.comm = BoxLayout(orientation='vertical') self.comm.add_widget(self.label) self.comm.add_widget(self.textbox) self.indicator = Label(text='System State\n') self.layout = BoxLayout(orientation='horizontal') self.layout.add_widget(self.indicator) self.layout.add_widget(self.comm) return self.layout def connect_to_server(self): reactor.connectTCP('localhost', 8000, EchoFactory(self)) def on_connection(self, connection, send_function): self.print_message("connected succesfully!") self.connection = connection self.send = send_function def send_message(self, *args): msg = self.textbox.text if msg and self.connection: self.send(str(self.textbox.text)) self.textbox.text = "" if not self.connection: self.connect_to_server() self.label.text += "Please try again." + "\n" def handle_message(self, msg): self.label.text += msg + "\n" print "handle_message called" if 'SET' in msg: response = self.handle_command(msg) return response def handle_command(self, msg): if 'SET' in msg: print "handling command" try: self.indicator.text = "SYSTEM:" + msg.split()[2] return "200" except: self.label.text += "Malformed message received." + "\n" return "Error 400" def print_message(self, msg): self.label.text += msg + "\n"
def on_widget(self, *args): for name in sorted(self.widget._Widget__properties): title = Label(text=name+":", size_hint=(None,1), width=150, halign='left') textval = TextInput(text=str(getattr(self.widget, name))) validate = functools.partial(self.set_value, name, textval) textval.bind(text=validate) self.add_widget(title) self.add_widget(textval)
def btn_filter_state(self, instance, value): print "btn", instance, value if value == 'down': txt = TextInput(multiline=False, focus=True, size_hint=(1, 0.1)) txt.bind(on_text_validate=self.btn_filter_state_enter) self.mainw.add_widget(txt, 0) elif value == 'normal': self.mainw.remove_widget(self.mainw.children[0])
class TwistedClientApp(App): connection = None def build(self): root = self.setup_gui() self.connect_to_server() return root def setup_gui(self): self.textbox = TextInput(size_hint_y=.1, multiline=False) self.textbox.bind(on_text_validate=self.send_message) self.label = Label(text='connecting...\n') self.layout = BoxLayout(padding=5, orientation='vertical') self.away_layout = BoxLayout(padding=5, orientation='horizontal') self.home_layout = BoxLayout(padding=5, orientation='horizontal') self.hand_layout = BoxLayout(padding=5, orientation='horizontal') self.hand_layout.add_widget(Button(text='haaai')) self.play_button = Button(text='Play a Card') self.play_button.bind(on_press=self.send_card) self.layout.add_widget(self.label) self.layout.add_widget(self.textbox) self.hand_layout.add_widget(self.play_button) self.layout.add_widget(self.away_layout) self.layout.add_widget(self.home_layout) self.layout.add_widget(self.hand_layout) self.away_layout.add_widget(Button(text='enemy cards')) self.home_layout.add_widget(Button(text='friendly cards')) self.hand_layout.add_widget(Button(text='your hand')) self.hand_1 = Button(text='Plaaaay') self.hand_1.bind(on_press=self.enemy_playcard) self.hand_layout.add_widget(self.hand_1) # self. return self.layout def connect_to_server(self): reactor.connectTCP('localhost', 8000, EchoFactory(self)) def on_connection(self, connection): self.print_message("connected succesfully!") self.connection = connection def send_card(self, *args): msg = "client1 playing_card 120 3" if msg and self.connection: self.connection.write(str(msg)) def send_message(self, *args): msg = self.textbox.text if msg and self.connection: self.connection.write(str(self.textbox.text)) self.textbox.text = "" def print_message(self, msg): self.label.text += msg + "\n" def enemy_playcard(self, *args): self.away_layout.add_widget(Button(text='Heheheheeeehe')) def update_checker(self, data, *args): if type data is dict: hand = data['hand']
def get_message_text(instance): text = TextInput(text=' ', multiline=False) def send_message(instance): print 'Text input text is: %s' % instance.text print 'Sending to number: %s' % number send(number, instance.text) add_entry_to_sent(number, instance.text) text.bind(on_text_validate=send_message) holder.add_widget(text)
def _get_body(self): txt = TextInput(id='filename', text=self.filename, multiline=False, size_hint_y=None, height=metrics.dp(30)) txt.bind(text=self.setter('filename')) self.bind(filename=txt.setter('text')) layout = super(XFileSave, self)._get_body() layout.add_widget(txt) return layout
def __init__(self, **kwargs): super(FullDisplay, self).__init__(**kwargs) self.ser = serial.Serial("/dev/ttyUSB0", 19200) self.display = DataDisplay(self.ser, size_hint=(1, 0.9), pos_hint={"y": 0.1}) self.add_widget(self.display) term = TextInput(multiline=False, size_hint=(1, 0.1)) term.bind(on_text_validate=self.on_enter) self.add_widget(term) Clock.schedule_interval(self.display.updateSerial, 1 / 25.0)
def updateJob(self,instance): #print self.dataCarousel.children[0].children if self.job_popup is None: self.job_popup = Popup(attach_to=self, title='Survey Name',title_align = 'center',size_hint=(0.5,None),padding=10) job = TextInput(multiline= False) job.bind(on_text_validate = lambda t: self.updateJobName(t.text)) self.job_popup.content = job if self.app.config.get('locks','lockSurvey') == 'False': self.job_popup.open()
def comment_pop(instance): """ Creates a Popup to Log Task into timesheet """ con=lite.connect('TimeTracker.db') with con: cur=con.cursor() cur.execute("SELECT DISTINCT TASK FROM Timesheet ORDER BY TASK ") rows = cur.fetchall() task_list=['OTHER'] for row in rows: task_list.append(row[0]) if con: con.close() f=FloatLayout() global popup1 popup1 = Popup(title='Task Desciption', content=f, size_hint=(1.0, 0.6), size=(400, 400)) g=GridLayout(cols=2,row_force_default=True, row_default_height=40, padding=(1,0,1,0)) g.add_widget(Label(text="SELECT TASK ",pos=(400,800))) global task task=TextInput(size_hint=(1,0.75),write_tab=False,text_size=(2,None)) dropdown = DropDown() for index in range(len(rows)+1): btn = Button(text=task_list[index], size_hint_y=None, height=44) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) global mainbutton mainbutton = Button(text='TASK', size_hint=(None, None),size=(100, 44), pos_hint={'center_x': .5, 'center_y': .5}) mainbutton.bind(on_release=dropdown.open) dropdown.bind(on_select=MyApp.select_task) g.add_widget(mainbutton) g.add_widget(Label(text="ADD TASK",pos=(400,600))) g.add_widget(task) g.add_widget(Label(text="COMMENTS",pos=(400,400))) global comment comment=TextInput(size_hint=(1,0.75),write_tab=False) g.add_widget(comment) global msg msg=Label(text="Please enter the task and comment to save the task \n", pos=(popup1.width-350,popup1.height-200)) comment.bind(on_text= msg.setter("Please enter the task and comment to save the task \n")) btn1=Button(text='SAVE',size_hint=(0.2,0.1),pos=(popup1.width-350, popup1.height-250)) btn1.bind(on_press=MyApp.update_timesheet) btn2=Button(text='CANCEL',size_hint=(0.2,0.1), pos=(popup1.width-50,popup1.height-250)) f.add_widget(msg) f.add_widget(btn1) f.add_widget(btn2) f.add_widget(g) popup1.open() btn2.bind(on_press=popup1.dismiss)
class CrossbarKivyApp(App): """ A simple kivy App, with a textbox to enter messages, and a large label to display all the messages received from Crossbar.io. """ def build(self): """ Entry point of Kivy UI component. """ # WAMP session self.session = None # run our WAMP application component runner = ApplicationRunner(url = u"ws://localhost:8080/ws", realm = u"realm1", extra = dict(ui=self)) runner.run(MyComponent, start_reactor=False) # setup the Kivy UI root = self.setup_gui() return root def setup_gui(self): """ Setup Kivy UI. """ self.textbox = TextInput(size_hint_y=.1, multiline=False) self.textbox.bind(on_text_validate=self.send_message) self.label = Label(text='connecting...\n') self.layout = BoxLayout(orientation='vertical') self.layout.add_widget(self.label) self.layout.add_widget(self.textbox) return self.layout def on_session(self, session): """ Called from WAMP session when attached to router. """ self.print_message("WAMP session connected!") self.session = session def send_message(self, *args): """ Called from UI when user has entered text and pressed RETURN. """ msg = self.textbox.text if msg and self.session: self.session.publish(u"com.example.kivy", str(self.textbox.text)) self.textbox.text = "" def print_message(self, msg): """ Called from WAMP app component when message was received in a PubSub event. """ self.label.text += msg + "\n"
class FileDialog(FloatLayout): path = ObjectProperty(None) file = ObjectProperty(None) def __init__(self, **kwargs): self.mode = kwargs.get('mode') super(FileDialog, self).__init__(**kwargs) self.register_event_type('on_cancel') self.register_event_type('on_submit') vbox = self.vbox = BoxLayout(orientation='vertical') self.add_widget(vbox) self.chooser = FileChooserListView(path=self.path) vbox.add_widget(self.chooser) self.text_input = TextInput(size_hint_y=None, height=30, multiline=False) if self.file: self.text_input.text = self.file vbox.add_widget(self.text_input) hbox = BoxLayout(size_hint_y=None, height=30) vbox.add_widget(hbox) self.cancel_btn = Button(text='Cancel') hbox.add_widget(self.cancel_btn) self.confirm_btn = Button(text=self.mode.title()) hbox.add_widget(self.confirm_btn) self.text_input.bind(text=self.on_text_input_text) self.chooser.bind(path=self.on_chooser_path, selection=self.on_chooser_selection, on_submit=self.on_chooser_submit) self.cancel_btn.bind(on_release=self.on_cancel_btn_release) self.confirm_btn.bind(on_release=self.on_confirm_btn_release) def do_layout(self, *args): if self.parent is not None: self.pos = self.parent.pos self.size = self.parent.size self.vbox.pos = self.parent.pos self.vbox.size = self.parent.size super(FileDialog, self).do_layout(*args) def on_text_input_text(self, instance, value): if not self.text_input.focus: return self.file = value def on_chooser_path(self, instance, value): self.path = value def on_chooser_selection(self, instance, value): self.file = value[0] self.text_input.text = self.file def on_chooser_submit(self, *args): self.dispatch('on_submit') def on_cancel_btn_release(self, *args): self.dispatch('on_cancel') def on_confirm_btn_release(self, *args): if self.file: self.dispatch('on_submit') def on_cancel(self, *args): pass def on_submit(self, *args): pass
class Sizer(BoxLayout): section = StringProperty() label = StringProperty() value = NumericProperty() low = NumericProperty() high = NumericProperty() inputbox = ObjectProperty() def __init__(self, **kwargs): super().__init__(**kwargs) self.value = self.get() label = Label(text=self.label) self.add_widget(label) controls = BoxLayout() minus = Button(text='-') minus.bind(on_press=self.minus) controls.add_widget(minus) self.inputbox = TextInput(text=str(self.get()), multiline=False, input_filter='int', input_type='number') self.inputbox.bind(on_text_validate=self.set) controls.add_widget(self.inputbox) plus = Button(text='+') plus.bind(on_press=self.plus) controls.add_widget(plus) self.add_widget(controls) def get(self): return app.config.getint(self.section, self.label) def set(self, value): if isinstance(value, TextInput): self.value = int(self.inputbox.text) self.inputbox.text = str(self.value) app.config.set(self.section, self.label, self.value) if self.section == 'MIDI' and self.label == 'Instrument': self.set_prog() else: app.resize_grid() def plus(self, value): if self.low <= self.value < self.high: self.value += 1 self.set(value) def minus(self, value): if self.low < self.value <= self.high: self.value -= 1 self.set(value) def set_prog(self): instrument = int(self.inputbox.text) if app.config.getboolean('Expression', 'Pitchbend'): for channel in range(16): midi.set_instrument(instrument, channel) else: midi.set_instrument(instrument, app.config.getint('MIDI', 'Channel'))
class TwistedClientApp(App): connection = None def build(self): root = self.setup_gui() connect_gui_and_client(self) return root def setup_gui(self): self.textbox = TextInput(size_hint_y=.1, multiline=False) self.textbox.bind(on_text_validate=self.send_message) self.label = Label(text='connecting...\n') self.layout = GridLayout(cols=1,orientation='vertical', size_hint_y=1) self.layout.add_widget(self.label) self.layout.add_widget(self.textbox) bottom_row=GridLayout(cols=4, row_force_default=True, row_default_height=40) self.start_button = Button(text='start') self.start_button.bind(on_press=self.start_timer) self.stop_button = Button(text='stop') self.stop_button.bind(on_press=self.stop_timer) self.play_button = Button(text='>') self.play_button.bind(on_press=self.play) self.pause_button = Button(text='||') self.play_button.bind(on_press=self.pause) bottom_row.add_widget(self.start_button) bottom_row.add_widget(self.stop_button) bottom_row.add_widget(self.play_button) bottom_row.add_widget(self.pause_button) self.layout.add_widget(bottom_row) return self.layout def on_connection(self, connection): self.print_message("connected succesfully!") self.connection = connection def send_message(self, *args): msg = self.textbox.text if msg and self.connection: self.connection.write(str(self.textbox.text)) self.textbox.text = "" def start_timer(self, *args): self.connection.write("start") def stop_timer(self, *args): self.connection.write("stop") def play(self, *args): self.connection.write("play") def pause(self, *args): self.connection.write("pause") def print_message(self, msg): self.label.text += msg + "\n"
def prepare(self, args): self.clear_widgets() filter_station = TextInput(pos_hint={"top":1}, hint_text='Почніть вводити назву станції', size_hint_y=0.07, font_size='20sp') filter_station.bind(text=self.on_filter_changed) dict_adapter = self.prepare_stations_dict_adapter(self.stations, '') self.list_view = ListView(pos_hint={"top":0.93}, adapter=dict_adapter) self.add_widget(filter_station) self.add_widget(self.list_view)
def create_filepath_input(): def on_enter(instance): global filepath filepath = instance.text print(filepath) filepath_input = TextInput(size_hint_x = 0.8, multiline = False, text = '/home/pi/Desktop/photos/test.jpg') filepath_input.bind(on_text_validate = on_enter) return filepath_input
def NewTopic(self): if self.sentence_box.selection_text == '': textinput = TextInput(multiline=False, focus=True) textinput.bind(on_text_validate=self.SetNewTopic) self.popup = Popup(title='Please enter the current topic.', content=textinput, size_hint=(.5, .5)) self.popup.open() else: self.topic = 'Insert Current topic:\n%s' %(self.sentence_box.selection_text) self.topic_raw = self.sentence_box.selection_text
class ChangeNameBar(BoxLayout): '''for word processing, change name ....''' def __init__(self, **kwargs): super(ChangeNameBar, self).__init__(**kwargs) self.input = TextInput() to_ascii_btn = MyButton(text='Không Dấu', font_size=14) to_ascii_btn.bind(on_release=self.toAscii) to_upper_btn = MyButton(text='Chữ Hoa', font_size=14) to_upper_btn.bind(on_release=self.toUpper) to_lower_btn = MyButton(text='Chữ Thường', font_size=14) to_lower_btn.bind(on_release=self.toLower) to_title_form_btn = MyButton(text='Chữ Đầu In Hoa', font_size=14) to_title_form_btn.bind(on_release=self.toTitleForm) button_box = GridLayout(cols=2, size_hint=(.4, 1)) button_box.add_widget(to_ascii_btn) button_box.add_widget(to_title_form_btn) button_box.add_widget(to_upper_btn) button_box.add_widget(to_lower_btn) self.add_widget(self.input) self.add_widget(button_box) def setText(self, value): # implicit method self.input.text = value def getText(self): # implicit method return self.input.text def setInputTextCallback(self, func): # implicit method self.input.bind(text=func) def toAscii(self, *args): '''from vietnamese char to ascci char''' translateDict = {'ă ắ ằ ẳ ẵ ặ â ấ ầ ẳ ẵ ặ á à ả ã ạ': 'a', 'é è ẻ ẽ ẹ ê ế ề ể ễ ệ': 'e', 'í ì ỉ ĩ ị': 'i', 'ó ò ỏ õ ọ ô ố ồ ổ ỗ ộ ơ ớ ờ ở ỡ ợ': 'o', 'ú ù ủ ũ ụ ư ứ ừ ử ữ ự': 'u', 'ý ỳ ỷ ỹ ỵ': 'y'} for set_of_char in translateDict: for char in set_of_char.split(' '): if char in self.input.text: self.input.text = self.input.text.replace(char, translateDict[set_of_char]) def toUpper(self, *args): self.input.text = self.input.text.upper() def toLower(self, *args): self.input.text = self.input.text.lower() def toTitleForm(self, *args): self.input.text = self.input.text.title()
class SearchLayout(GridLayout): ''' Here's a custom layout. Contain a show layout and text layout ''' def __init__(self, sg=None, **kwargs): super(SearchLayout, self).__init__(**kwargs) self.cols = 2 self.sg_t = sg self.search_keyword = TextInput(multiline=False, size_hint_y=None, height=40) self.search_keyword.bind(text=self.name_get_text) self.search_button = Button(text='Search Entity', size_hint_y=None, height=40, size_hint_x=None, width=250) self.search_button.bind(on_press=self.search) #print("Hello") #runTouchApp(self.search_button) #self.search_button = Button(text = 'Search Entity') #self.search_button.bind(on_press = self.search) self.add_widget(self.search_keyword) #row=9 self.add_widget(self.search_button) #row=10 def name_get_text(self, instance, value): ''' Get value from input box ''' self.name_text = value #print(")((**") def search(self, instance): ''' search articles (as well as attributes) in the graph ''' if self.name_text == '': pass else: self.dropdown = DropDown() file = open('..\\IdWithTitle.csv', 'r', encoding='utf-8') lines = file.readlines() file.close() show_text = '' self.idWithTitle = {} for line in lines: temp = line.split('\t') if self.name_text.lower() in temp[1].lower(): #print("!!!!") self.idWithTitle[temp[0]] = temp[1] show_text += temp[1] for k, v in self.idWithTitle.items(): #print(v) btn = Button(text=v, size_hint_y=None, height=35) btn.bind(on_release=lambda btn: self.dropdown.select(btn.text)) btn.bind(on_press=self.graphSearch) self.dropdown.add_widget(btn) self.search_button.bind(on_release=self.dropdown.open) self.dropdown.bind(on_select=lambda instance, x: setattr( self.search_button, 'text', x)) #self.sg_t.frequency.text = show_text def graphSearch(self, instance): #print(instance) #print(value) #self.sg_t.frequency.text = instance.text file = open('..\\idWithAliasWithUniverse.csv', 'r', encoding='utf-8') lines = file.readlines() file.close() file1 = open('..\\Full_Info_Data.csv', 'r', encoding='utf-8') person = file1.readlines() file1.close() #print(instance.text) self.universe = '' self.pid = '' self.alias = '' self.universeWithCharacters = {} for line in person: temp = line.split('\t') if temp[1] in instance.text: self.pid = temp[0] for line in lines: temp = line.split('\t') if self.pid == temp[0]: self.universe = temp[2].replace('\n', '') self.alias = temp[1] for line in lines: temp = line.split('\t') if temp[2].replace('\n', '') in self.universe.replace( '\n', '') and temp[0] != self.pid: self.universeWithCharacters[temp[0]] = [temp[1]] for line in person: temp = line.split('\t') if temp[1].replace('\n', '') in instance.text.replace('\n', ''): self.sg_t.frequency.text = "<id>\t" + temp[0] + "\n<title>\t" + temp[ 1] + "<RealName>\t" + temp[2] + "\n<CurrentAlias>\t" + temp[ 3] + "\n<Affiliation>\t" + temp[4] + "\n<Relatives>\t" + temp[ 5] + "\n<Universe>\t" + temp[6] + "\n<Gender>\t" + temp[ 7] + "\n<Height>\t" + temp[ 8] + "\n<Weight>\t" + temp[ 9] + "\n<Eyes>\t" + temp[ 10] + "\n<Hair>\t" + temp[ 11] + "\n<Citizenship>\t" + temp[ 12] + "\n<Quotation>\t" + temp[ 13] + "\n" for line in person: temp = line.split('\t') if temp[0] in self.universeWithCharacters.keys(): tempName = self.universeWithCharacters[temp[0]] self.universeWithCharacters[temp[0]] = [tempName, temp[5]] #print(self.universe) #print(self.pid) #print(self.alias) #print("I'm here") count1 = 0 #count2 = 0 sgraph = igraph.Graph() sgraph.add_vertex(name=self.alias.replace('\n', ''), label=self.alias.replace('\n', ''), size=150, color='red') sgraph.add_vertex(name=self.universe.replace('\n', ''), label=self.universe.replace('\n', ''), size=200, color='orange') sgraph.add_edge(self.universe.replace('\n', ''), self.alias.replace('\n', '')) for k, v in self.universeWithCharacters.items(): #print(v[0]) count1 += 1 if self.alias.replace('\n', '') in v[1].replace('\n', ''): sgraph.add_vertex(name=v[0][0].replace('\n', ''), label=v[0][0].replace('\n', ''), size=100, color='blue') sgraph.add_edge(v[0][0].replace('\n', ''), self.alias.replace('\n', '')) sgraph.add_edge(self.universe.replace('\n', ''), v[0][0].replace('\n', '')) elif count1 < 25: sgraph.add_vertex(name=v[0][0].replace('\n', ''), label=v[0][0].replace('\n', ''), size=50, color='grey') sgraph.add_edge(self.universe.replace('\n', ''), v[0][0].replace('\n', '')) layout = sgraph.layout("kk") igraph.plot(sgraph, layout=layout, bbox=(1300, 1000), margin=100, edge_width=10, vertex_label_size=50).save( self.alias.replace('\n', '') + self.universe + "_search.png") self.sg_t.picture.source = self.alias.replace( '\n', '') + self.universe + "_search.png"
class Game(BoxLayout): game_title = 'Chess Chase: No turns, no sight!' def __init__(self, **kwargs): super(Game, self).__init__(**kwargs) self.game_model = GameModel() self.game_model.king_captured = self.king_captured self.game_model.on_message.append(self.update_label) self.net_engine = NetEngine(self.game_model) self.score = [0, 0] self.board_view = BoardView(self.game_model) self.add_widget(self.board_view) self.game_model.on_init.append(self.board_view.reset) self.game_model.on_init.append(self.on_game_init) self.info_pane = BoxLayout(orientation='vertical', size_hint_min_y=500) self.add_widget(self.info_pane) row_args = {'size_hint': (1, 0), 'size_hint_min_y': 70} if not env.is_mobile: self.info_pane.add_widget( WrappedLabel(halign='center', text=self.game_title, **row_args)) self.button_pane = BoxLayout(orientation='vertical', size_hint=(1, .4)) self.info_pane.add_widget(self.button_pane) self.button_pane.add_widget( WrappedButton(halign='center', text='Tutorial: How to play', on_press=self.start_tutorial)) self.button_pane.add_widget( WrappedButton(halign='center', text='Start Game' if env.is_mobile else 'Start Game: Play with friends', on_press=self.start_game)) self.score_label = WrappedLabel(halign='center', **row_args) self.info_pane.add_widget(self.score_label) self.label = WrappedLabel(halign='center', valign='bottom') self.info_pane.add_widget(self.label) self.text_input = TextInput(multiline=False, text_validate_unfocus=env.is_mobile, **row_args) self.text_input.bind(on_text_validate=self.handle_text_input) if env.is_mobile: self.text_input.keyboard_mode = 'managed' def on_focus(*args): if self.text_input.focus: self.text_input.show_keyboard() else: def on_focus(*args): if not self.text_input.focus: # Steal focus self.text_input.focus = True self.text_input.bind(focus=on_focus) self.info_pane.add_widget(self.text_input) self.game_model.add_message('') self.game_model.add_message( self.game_title if env.is_mobile else 'Welcome to Chess Chase!') self.bind(size=self.resized) Clock.schedule_interval(self.on_clock, 1 / 30) @mainthread def on_game_init(self): if env.is_mobile and self.game_model.mode == 'play': self.text_input.hide_keyboard() def stop_net_engine(self): if not self.net_engine: return self.net_engine.should_stop = True def restart_net_engine(self): self.stop_net_engine() self.net_engine = NetEngine(self.game_model) def start_game(self, _): self.text_input.focus = True if env.is_mobile: self.text_input.show_keyboard() self.game_model.mode = 'connect' self.score = [0, 0] self.restart_net_engine() self.game_model.messages.clear() self.game_model.add_message('Establishing server connection...') self.game_model.init() self.net_engine.start() def start_tutorial(self, i): if env.is_mobile: self.text_input.hide_keyboard() self.game_model.mode = 'tutorial' self.game_model.reset() self.restart_net_engine() self.game_model.messages.clear() self.game_model.add_message( 'Move the chess pieces and see what happens!') self.game_model.tutorial_messages = [ 'Keep moving the pieces at your own pace.', 'Each piece has its own color, and the board is painted to show where it can move.', 'You only see where your pieces can move', 'You will also see any piece that threatens the king.', 'Note that unlike classic chess, the king can move to a threatened position!', 'There are no turns!', 'There are cool-downs (rate limits) instead.', 'You win the game by capturing the opponent king', 'The game is played with friends over the internet.', 'To start a game both you and your friend need to click "Start Game".', 'Then either you or the friend should type the game identifier that the other was given.', 'This concludes our tutorial!', ] self.game_model.init() self.game_model.players[self.game_model.my_id] = 0 self.net_engine.iter_actions = {} def update_label(self): self.score_label.text = 'White: %d Black: %d' % tuple(self.score) self.label.text = '\n'.join(self.game_model.messages[-num_msg_lines:]) def resized(self, *args): self.orientation = 'horizontal' if self.size[0] > self.size[ 1] else 'vertical' p = 1 / 3 if self.orientation == 'horizontal': self.info_pane.size_hint = (p, 1) self.board_view.size_hint = (self.game_model.num_boards, 1) self.button_pane.orientation = 'vertical' self.button_pane.size_hint = (1, .4) self.button_pane.size_hint_min_y = 140 else: self.info_pane.size_hint = (1, p) self.board_view.size_hint = (1, 1 / self.game_model.num_boards) self.button_pane.orientation = 'horizontal' self.button_pane.size_hint = (1, .4) self.button_pane.size_hint_min_y = 70 def handle_text_input(self, entry): if env.is_mobile: self.text_input.hide_keyboard() command = entry.text entry.text = '' if not command: return if command[:1] == '/': if command == '/help': self.game_model.help() return self.game_model.add_action(*command[1:].split()) return if self.game_model.mode in [None, 'connect']: self.net_engine.connect(command) return # Chat self.game_model.add_action('msg', command) def king_captured(self, who): if self.game_model.mode == 'replay': return winner = 1 - who % 2 self.score[winner] += 1 self.game_model.add_message('') self.game_model.add_message('%s King Captured!' % self.game_model.player_str(who)) self.game_model.add_message('%s wins!' % self.game_model.player_str(winner)) self.net_engine.start_replay() def on_clock(self, _interval): self.net_engine.iteration() self.board_view.update_dst() self.board_view.show_board()
def on_enter(self, *l): '''When the user press enter and wants to run a command ''' self.unbind(on_subprocess_done=self.on_enter) if self.command_status == 'started': self.kill_process() self.bind(on_subprocess_done=self.on_enter) return txtinput_command_line = self.txtinput_command_line add_to_cache = self.add_to_cache command_history = self.command_history def remove_command_interaction_widgets(*l): '''command finished:remove widget responsible for interaction ''' parent.remove_widget(self.interact_layout) self.interact_layout = None # enable running a new command try: parent.add_widget(self.txtinput_command_line) except: self._initialize(0) self._focus(txtinput_command_line, True) Clock.schedule_once(self._change_txtcache, -1) self.command_status = 'closed' self.dispatch('on_subprocess_done') def run_cmd(*l): '''Run the command ''' # this is run inside a thread so take care, avoid gui ops try: _posix = True if sys.platform[0] == 'w': _posix = False cmd = shlex.split(str(command), posix=_posix)\ if not self.shell else command except Exception as err: cmd = '' self.add_to_cache(u''.join((str(err), ' <', command, ' >\n'))) if len(cmd) > 0: prev_stdout = sys.stdout sys.stdout = self.stdout try: # execute command self.popen_obj = popen = subprocess.Popen( cmd, bufsize=0, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=None, close_fds=False, shell=self.shell, cwd=self.cur_dir, env=self.environment, universal_newlines=False, startupinfo=None, creationflags=0) popen_stdout_r = popen.stdout.readline popen_stdout_flush = popen.stdout.flush txt = popen_stdout_r() plat = platform() while txt != '': # skip flush on android if plat[0] != 'a': popen_stdout_flush() add_to_cache(txt.decode('utf8')) txt = popen_stdout_r() except (OSError, ValueError) as err: add_to_cache(u''.join((str(err.strerror), ' < ', command, ' >\n'))) self.command_status = 'closed' sys.stdout = prev_stdout self.popen_obj = None Clock.schedule_once(remove_command_interaction_widgets, 0) # append text to textcache add_to_cache(u''.join((self.txtinput_command_line.text, '\n'))) command = txtinput_command_line.text[len(self.prompt()):] if command == '': self.txtinput_command_line_refocus = True return # store command in command_history if self.command_history_pos > 0: self.command_history_pos = len(command_history) if command_history[self.command_history_pos - 1] != command: command_history.append(command) else: command_history.append(command) len_command_history = len(command_history) self.command_history_pos = len(command_history) # on reaching limit(cached_lines) pop first command if len_command_history >= self.cached_commands: self.command_history = command_history[1:] # replce $PATH with command = os.path.expandvars(command) # if command = cd change directory if command == 'clear' or command == 'cls': self.clear() txtinput_command_line.text = self.prompt() self.txtinput_command_line_refocus = True self.command_status = 'closed' self.dispatch('on_subprocess_done') return if command.startswith('cd ') or command.startswith('export '): if command[0] == 'e': e_q = command[7:].find('=') _exprt = command[7:] if e_q: os.environ[_exprt[:e_q]] = _exprt[e_q + 1:] self.environment = os.environ.copy() else: try: command = re.sub('[ ]+', ' ', command) if command[3] == os.sep: os.chdir(command[3:]) else: os.chdir(self.cur_dir + os.sep + command[3:]) if sys.version_info >= (3, 0): self.cur_dir = os.getcwd() else: self.cur_dir = os.getcwdu() except OSError as err: Logger.debug('Shell Console: err:' + err.strerror + ' directory:' + command[3:]) add_to_cache(u''.join((err.strerror, '\n'))) txtinput_command_line.text = self.prompt() self.txtinput_command_line_refocus = True self.command_status = 'closed' self.dispatch('on_subprocess_done') return txtinput_command_line.text = self.prompt() # store output in textcache parent = txtinput_command_line.parent # disable running a new command while and old one is running parent.remove_widget(txtinput_command_line) # add widget for interaction with the running command txtinput_run_command = TextInput(multiline=False, font_size=self.font_size) def interact_with_command(*l): '''Text input to interact with the running command ''' popen_obj = self.popen_obj if not popen_obj: return txt = l[0].text + u'\n' popen_obj_stdin = popen_obj.stdin popen_obj_stdin.write(txt) popen_obj_stdin.flush() self.txtinput_run_command_refocus = True self.txtinput_run_command_refocus = False txtinput_run_command.bind(on_text_validate=interact_with_command) txtinput_run_command.bind(focus=self.on_focus) btn_kill = Button(text="Stop", width=60, size_hint=(None, 1)) self.interact_layout = il = GridLayout(rows=1, cols=2, height=27, size_hint=(1, None)) btn_kill.bind(on_press=self.kill_process) il.add_widget(txtinput_run_command) il.add_widget(btn_kill) parent.add_widget(il) txtinput_run_command.focus = True self.command_status = 'started' thread.start_new_thread(run_cmd, ())
def enter_state(self, context=None): print 'ShowingSearchScreen/enter_state' if not 'Search' in self.statechart.app.sm.screen_names: self.search_results = [] self.app = self.statechart.app self.search_criteria = {} view = BoxLayout(orientation='vertical', spacing=10) toolbar = BoxLayout(size_hint=(1.0, None), height=50) button = Button(text='Lists') button.bind(on_press=self.go_to_lists) toolbar.add_widget(button) label = Label(text='Search', color=[.8, .8, .8, .8], bold=True) toolbar.add_widget(label) button = Button(text='Data') button.bind(on_press=self.go_to_data) toolbar.add_widget(button) button = Button(text='Detail') button.bind(on_press=self.go_to_detail) toolbar.add_widget(button) view.add_widget(toolbar) body_view = BoxLayout() left_view = BoxLayout(size_hint=(0.7, 1.0), orientation='vertical') left_view.add_widget( Label(size_hint=(1.0, 0.2), text="""[b]Search Criteria:[/b] Enter the lower and upper bounds of search criteria in the text entry boxes. Each time you hit the [i]ENTER[/i] key in a text entry box, the search results shown in the list on the right will be updated.""", markup=True)) search_criteria_view = BoxLayout(orientation='vertical') props = [ prop for prop in self.statechart.data['Apple'] if prop != 'name' ] for prop in sorted(props): search_box_view = BoxLayout(size_hint=(1.0, None), height=40) text_input = TextInput(text='', multiline=False) text_input.id = "<: {0}".format(prop) text_input.bind(on_text_validate=self.criterion_entered) search_box_view.add_widget(text_input) search_box_view.add_widget(Label(text="> {0} <".format(prop))) text_input = TextInput(text='', multiline=False) text_input.id = ">: {0}".format(prop) text_input.bind(on_text_validate=self.criterion_entered) search_box_view.add_widget(text_input) search_criteria_view.add_widget(search_box_view) left_view.add_widget(search_criteria_view) body_view.add_widget(left_view) right_view = BoxLayout(size_hint=(0.3, 1.0), orientation='vertical') right_view.add_widget( Label(size_hint=(1.0, 0.2), text="Search Results (red):")) self.all_fruits = sorted(self.statechart.data.keys()) self.results_fruits_dict_adapter = DictAdapter( sorted_keys=self.all_fruits, data=self.statechart.data, args_converter=self.list_item_args_converter, selection_mode='none', allow_empty_selection=True, cls=ListItemLabel) right_view.add_widget( ListView(size_hint=(1.0, 0.8), adapter=self.results_fruits_dict_adapter)) body_view.add_widget(right_view) view.add_widget(body_view) screen = Screen(name='Search') screen.add_widget(view) self.app.sm.add_widget(screen) if self.app.sm.current != 'Search': self.app.sm.current = 'Search'
class MyDictionary(App): savefile = ObjectProperty(None) def build(self): Config.set('kivy', 'window_icon', '{0}/favicon.png'.format(images_dir)) dictionary = db.DictionaryBuilder() self.qhandler = qh.Questionnaire_Handler() self.dictionaryhandler = dh.DictionaryHandler() self.searchhandler = sh.SearchHandler() # ============== root layout ============== root = BoxLayout(orientation='vertical', size=(800, 800)) with root.canvas.before: self.root_rect = Rectangle( source='{0}/background-dict.jpg'.format(images_dir), allow_strech=True, keep_ratio=True, size=root.size, size_hint=(1, 1), pos=root.pos) root.bind(pos=self.update_root_rect, size=self.update_root_rect) # ============== nav bar ============== lay_nav = BoxLayout(orientation='horizontal', size_hint=(1, .1)) btn_nav_search = Button( text='[b]Search Dictionary[/b]', size_hint=(1, 1), markup=True, font_size=20, background_normal='{0}/button_nav.png'.format(images_dir)) btn_nav_create_dict = Button( text='[b]Create Dictionary[/b]', size_hint=(1, 1), markup=True, font_size=20, background_normal='{0}/button_nav.png'.format(images_dir)) lay_nav.add_widget(btn_nav_search) lay_nav.add_widget(btn_nav_create_dict) # ============== container ============== lay_container = BoxLayout(orientation='vertical', size_hint=(1, .9), padding=[20, 20]) # ============== search the password in the dictionary ============== lay_search = BoxLayout(orientation='vertical', padding=[10, 10], spacing=10) lay_search_load = BoxLayout(orientation='horizontal', spacing=10, size_hint=(1, .15)) lay_search_btn_filename = BoxLayout(orientation='horizontal', spacing=10, size_hint=(1, .1)) lbl_search_header = Label( text= '[b][size=15][color=4d4d4d]Enter your password and we will check if it is in the dictionary builded for you.[/size]' '\nDont worry! We do not store your passwords or using them in any way.[/b]', size_hint=(1, .2), markup=True, ) inp_pass = TextInput(text='', size_hint=(.6, 1), hint_text='Your password here', font_size=15, password=True, padding_y=15) btn_load_file = Button( text='[b][color=4d4d4d]Load file[/b]', size_hint=(.2, 1), markup=True, background_normal='{0}/fbli_search_button.png'.format(images_dir), background_down='{0}/fbli_search_button_back.png'.format( images_dir)) btn_search = Button( text='[b][color=4d4d4d]Search[/b]', size_hint=(1, 1), markup=True, background_normal='{0}/fbli_search_button.png'.format(images_dir), background_down='{0}/fbli_search_button_back.png'.format( images_dir)) self.lbl_search_filename = Label(text='', size_hint=(1, 1), color=(77, 77, 77, 1), markup=True) lbl_pass_result = Label(text='', size_hint=(1, .8), markup=True) with lbl_pass_result.canvas: self.pass_result_rect = Rectangle( size=lbl_pass_result.size, pos=lbl_pass_result.pos, allow_strech=True, keep_ratio=True, source='{0}/search_answer.png'.format(images_dir)) lbl_pass_result.bind(pos=self.update_pass_result_rect, size=self.update_pass_result_rect) self.pb_search = ProgressBar(size_hint=(1, .1)) btn_search.bind( on_press=partial(self.handle_search, inp_pass, self.pb_search, lbl_pass_result, self.lbl_search_filename)) btn_load_file.bind(on_press=partial(self.searchhandler.load_file, self.lbl_search_filename)) lay_search_load.add_widget(inp_pass) lay_search_load.add_widget(btn_load_file) lay_search_btn_filename.add_widget(btn_search) lay_search_btn_filename.add_widget(self.lbl_search_filename) lay_search.add_widget(lbl_search_header) lay_search.add_widget(lay_search_load) lay_search.add_widget(lay_search_btn_filename) lay_search.add_widget(self.pb_search) lay_search.add_widget(lbl_pass_result) # ============== create a dictionary ============== # dict layout: lay_dict = BoxLayout(orientation='horizontal', spacing=10) # buttons and list layouts: lay_dict_btns = BoxLayout(orientation='vertical', padding=[30, 30], spacing=10) lay_dict_list = BoxLayout(orientation='vertical', padding=[10, 10], spacing=10) with lay_dict_list.canvas: self.wordlist_rect = Rectangle( size=lay_dict_list.size, pos=lay_dict_list.pos, allow_strech=True, keep_ratio=True, source='{0}/wordlist.png'.format(images_dir)) lay_dict_list.bind(pos=self.update_wordlist_rect, size=self.update_wordlist_rect) # list: lay_dict_list.add_widget( Label(text='[b][color=4d4d4d]Current list:[/b]', size_hint=(1, .1), markup=True, font_size=18)) lbl_list_box = Label(text='No Words in the list', size_hint=(1, 1), color=(0, 0, 0, 1)) btn_clean_list = Button(text='Clean List', size_hint=(1, .1), on_press=partial(self.clean_list, dictionary, lbl_list_box)) lay_dict_list.add_widget(lbl_list_box) lay_dict_list.add_widget(btn_clean_list) # buttons: btn_calc_dict = Button( text='[b][color=4d4d4d]Make me a dictionary![/b]', size_hint=(1, .2), markup=True, font_size=20, background_normal='{0}/make_me_dictionary.png'.format(images_dir), background_down='{0}/make_me_dictionary_back.png'.format( images_dir)) btn_calc_dict.bind(on_press=partial( self.dictionaryhandler.popup_dictionary, dictionary)) btn_open_quest = Button( text='[b][color=4d4d4d]Questionnaire[/b]', size_hint=(1, .1), markup=True, font_size=15, background_normal='{0}/questionnaire_button.png'.format( images_dir), background_down='{0}/questionnaire_button_back.png'.format( images_dir)) btn_open_quest.bind(on_press=partial(self.qhandler.questionnaire, dictionary, lbl_list_box)) btn_linkedin_search = Button( text='[b][color=4d4d4d]LinkedIn Search[/b]', size_hint=(1, .1), markup=True, font_size=15, background_normal='{0}/li_search_button.png'.format(images_dir), background_down='{0}/li_search_button_back.png'.format(images_dir)) btn_linkedin_search.bind(on_press=partial( self.web_scrap, dictionary, lbl_list_box, "LinkedIn profile URL:\n" "Example: https://www.linkedin.com/in/<PROFILE NAME>/", e.LinkedIn_Search)) btn_facebook_search = Button( text='[b][color=4d4d4d]Facebook Search[/b]', size_hint=(1, .1), markup=True, font_size=15, background_normal='{0}/fb_search_button.png'.format(images_dir), background_down='{0}/fb_search_button_back.png'.format(images_dir)) btn_facebook_search.bind(on_press=partial( self.web_scrap, dictionary, lbl_list_box, "Facebook profile URL:\n" "Example: https://www.facebook.com/<PROFILE NAME>/", e.Facebook_Search)) lay_dict_btns.add_widget(btn_facebook_search) lay_dict_btns.add_widget(btn_linkedin_search) lay_dict_btns.add_widget(btn_open_quest) lay_dict_btns.add_widget(btn_calc_dict) # adding all to the dict layout: lay_dict.add_widget(lay_dict_btns) lay_dict.add_widget(lay_dict_list) # ============================================= # bind nav bar function btn_nav_search.bind(on_press=partial(self.navigate, lay_container, lay_search, lay_dict)) btn_nav_create_dict.bind(on_press=partial(self.navigate, lay_container, lay_dict, lay_search)) # add widgets to the root layout lay_container.add_widget(lay_dict) root.add_widget(lay_nav) root.add_widget(lay_container) return root # ======================= update rects ======================= def update_root_rect(self, instance, value): self.root_rect.pos = instance.pos self.root_rect.size = instance.size def update_wordlist_rect(self, instance, value): self.wordlist_rect.pos = instance.pos self.wordlist_rect.size = instance.size def update_pass_result_rect(self, instance, value): self.pass_result_rect.pos = instance.pos self.pass_result_rect.size = instance.size # ============================================================= def clean_list(self, dictionary, lbl_list_box, instance): dictionary.lists.cleanLists() lbh.printto_lbllist(None, lbl_list_box) def handle_search(self, inp_password, progressbar, pass_result, lbl_search_filename, instance): self.searchhandler.set_vars(inp_password, progressbar, pass_result, lbl_search_filename) search_thread = threading.Thread( target=self.searchhandler.start_search) search_thread.start() def handle_questionnaire(self, dictionary, lbl_list_box, instance): self.qhandler.questionnaire(dictionary, lbl_list_box, instance) # nav function def navigate(self, layout, lay_to, *lay_from): for c in list(layout.children): if c == lay_to: return if lay_from is not None: for lay in lay_from: layout.remove_widget(lay) if lay_to is not None: layout.add_widget(lay_to) def set_scrapers(self, dictionary, lbl_list, website, popup, instance): with open('creds.txt') as f: lemail = f.readline() lpassword = f.readline() if website == e.LinkedIn_Search: self.scraper = ls.LinkedinScraper(lemail, lpassword) self.scraper.scrap(self.etr_url.text) dictionary.extend_dictionary(self.scraper.lists.words, e.Mode_Words) dictionary.extend_dictionary(self.scraper.lists.numbers, e.Mode_Numbers) lbh.printto_lbllist( dictionary.lists.words + dictionary.lists.numbers, lbl_list) elif website == e.Facebook_Search: self.get_FB_credentials(dictionary, lbl_list) popup.dismiss() def scrap_website(self, scraper): pass # ========================== get credentials for Facebook ======================== def get_FB_credentials(self, dictionary, lbl_list): lay_get_credentials = BoxLayout(orientation='vertical', spacing=15, padding=[15, 15]) title = "Your Facebook credentials:" popup = Popup(title=title, content=lay_get_credentials, size=(500, 250), size_hint=(None, None)) self.inp_fusername = TextInput(text='', size_hint=(1, .1), hint_text='Email', multiline=False) self.inp_fpassword = TextInput(text='', size_hint=(1, .1), hint_text='Password', password=True, multiline=False) btn_submit_creds = Button(text="Start", size_hint=(.5, .1), pos_hint={'x': .25}, on_press=partial(self.set_FB_creds_and_scrap, dictionary, lbl_list, popup)) lay_get_credentials.add_widget(self.inp_fusername) lay_get_credentials.add_widget(self.inp_fpassword) lay_get_credentials.add_widget(btn_submit_creds) popup.open() def set_FB_creds_and_scrap(self, dictionary, lbl_list, popup, instance): self.fusername = self.inp_fusername.text self.fpassword = self.inp_fpassword.text if self.fusername != '' and self.fpassword != '': self.scraper = fs.FacebookScraper(self.fusername, self.fpassword) self.scraper.scrap(self.etr_url.text) dictionary.extend_dictionary(self.scraper.lists.words, e.Mode_Words) dictionary.extend_dictionary(self.scraper.lists.numbers, e.Mode_Numbers) lbh.printto_lbllist( dictionary.lists.words + dictionary.lists.numbers, lbl_list) popup.dismiss() def web_scrap(self, dictionary, lbl_list, text_to_show, website, instance): lay_web_scrap = BoxLayout(orientation='vertical', spacing=10) title = "LinkedIn Search" if website == e.LinkedIn_Search else "Facebook Search" popup = Popup(title=title, content=lay_web_scrap, size=(500, 250), size_hint=(None, None)) lay_web_scrap.add_widget(Label(text=text_to_show, size_hint=(1, .6))) self.etr_url = TextInput(text='', size_hint=(1, .2), multiline=False) self.etr_url.bind(on_text_validate=partial( self.set_scrapers, dictionary, lbl_list, website, popup)) btn_scrap_start = Button(text="Start", size_hint=(1, .2), on_press=partial(self.set_scrapers, dictionary, lbl_list, website, popup)) lay_web_scrap.add_widget(self.etr_url) lay_web_scrap.add_widget(btn_scrap_start) popup.open()
class BoxLayoutMosaicColor(BoxLayoutMosaic): def prepare_numpy_array(self): self.clean_scratch(self.pathtoscratch_numpy) for i in np.arange(len(self.listimage)): image_B, image_G, image_R = [ pyfits.open(self.pathtofile + self.listimage[i])[0].data, pyfits.open(self.pathtofile + self.listimage[i])[1].data, pyfits.open(self.pathtofile + self.listimage[i])[2].data ] image = np.array([image_B, image_G, image_R]) np.save(self.pathtoscratch_numpy + str(self.listimage[i]), image) def scale_val(self, image_array): if len(np.shape(image_array)) == 2: image_array = [image_array] vmin = np.min([ self.background_rms_image(5, image_array[i]) for i in range(len(image_array)) ]) xl, yl = np.shape(image_array[0]) box_size = 14 # in pixel xmin = int((xl) / 2 - (box_size / 2)) xmax = int((xl) / 2 + (box_size / 2)) vmax = np.max([ image_array[i][xmin:xmax, xmin:xmax] for i in range(len(image_array)) ]) return vmin, vmax def showplot_rgb(self, rimage, gimage, bimage): vmin, vmax = self.scale_val([rimage, gimage, bimage]) img = np.zeros((rimage.shape[0], rimage.shape[1], 3), dtype=float) img[:, :, 0] = self.sqrt_sc(rimage, scale_min=vmin, scale_max=vmax) img[:, :, 1] = self.sqrt_sc(gimage, scale_min=vmin, scale_max=vmax) img[:, :, 2] = self.sqrt_sc(bimage, scale_min=vmin, scale_max=vmax) return img def sqrt_sc(self, inputArray, scale_min=None, scale_max=None): # imageData = np.array(inputArray, copy=True) if scale_min is None: scale_min = imageData.min() if scale_max is None: scale_max = imageData.max() imageData = imageData.clip(min=scale_min, max=scale_max) imageData = imageData - scale_min indices = np.where(imageData < 0) imageData[indices] = 0.00001 imageData = np.sqrt(imageData) imageData = imageData / np.sqrt(scale_max - scale_min) return imageData def draw_image(self, name, scale_state, defaultvalue=True, max=1, min=0): try: image_B = np.load(self.pathtoscratch_numpy + name)[0] image_G = np.load(self.pathtoscratch_numpy + name)[1] image_R = np.load(self.pathtoscratch_numpy + name)[2] image = self.showplot_rgb(image_R, image_G, image_B) except FileNotFoundError: image = np.ones((44, 44, 3)) * 0.0000001 return image def prepare_png(self, number): start = self.counter for i in np.arange(start, start + number + 1): try: img = self.draw_image(self.listimage[i], self.scale_state) # print('prepare png',self.listimage[i]) except IndexError: img = self.draw_image('not_existing.fits', self.scale_state) image = Image.fromarray(np.uint8(img * 255), 'RGB') image = image.resize((150, 150), Image.ANTIALIAS) image.save( self.pathtoscratch + str(i + 1) + self.scale_state + str(start) + '.png', 'PNG') self.counter = self.counter + 1 def build(self): self.pathds9 = 'C:\\SAOImageDS9\\ds9.exe' # self.pathtofile = './files_to_visualize/' self.pathtoscratch = './scratch_png/' self.pathtoscratch_numpy = './scratch_numpy/' self.path_background = 'green.png' # self.listimage = sorted([os.path.basename(x) for x in glob.glob(self.pathtofile + '*.fits')]) self.listimage = sorted([ os.path.basename(x) for x in glob.glob(self.pathtoscratch_numpy + '*.npy') ]) # print(self.listimage[0]) if len(sys.argv) > 1: self.random_seed = sys.argv[1] else: print("Random seed set to default value 42") self.random_seed = 42 if len(sys.argv) > 2: self.fraction = float(sys.argv[2]) else: print("No repeated objects") self.fraction = 0 if len(sys.argv) > 3: self.numpy_computing = sys.argv[3] self.repeat_random_objects(self.fraction) random.Random(self.random_seed).shuffle(self.listimage) self.clean_scratch(self.pathtoscratch) self.start_image_number = 0 self.counter = 0 self.scale_min = 0 self.scale_max = 1 self.limit_max = 1 self.limit_min = 0 self.step = (self.scale_max - self.scale_min) / 10. self.scale_state = 'linear' self.number_per_frame = 100 self.total_n_frame = int(len(self.listimage) / 100.) self.forward_backward_state = 0 self.dataframe = self.create_df() self.prepare_png(self.number_per_frame) allbox = BoxLayout(orientation='vertical') buttonbox = BoxLayout(orientation='horizontal', size_hint_y=0.1) superbox = GridLayout(cols=10, size_hint_y=0.9) self.list_of_buttons = [] for i in np.arange(self.number_per_frame): try: if self.dataframe['classification'][i] == 0: self.list_of_buttons.append( CustomButton(0, source=self.pathtoscratch + str(i + 1) + self.scale_state + str(0) + '.png')) else: self.list_of_buttons.append( CustomButton(1, source=self.path_background)) self.dataframe['Grid_pos'].iloc[100 * self.forward_backward_state + i] = i + 1 except KeyError: self.list_of_buttons.append( CustomButton(1, source=self.pathtoscratch + str(i + 1) + self.scale_state + str(0) + '.png')) self.list_of_buttons[i].bind(on_press=partial(self.on_click, i)) for button in self.list_of_buttons: superbox.add_widget(button) allbox.add_widget(superbox) buttonscale1 = Button(text="Linear") buttonscale2 = Button(text="Sqrt") buttonscale3 = Button(text="Log") buttonscale4 = Button(text="Asinh") buttonscale1.bind(on_press=partial(self.change_scale, 'linear')) buttonscale2.bind(on_press=partial(self.change_scale, 'sqrt')) buttonscale3.bind(on_press=partial(self.change_scale, 'log')) buttonscale4.bind(on_press=partial(self.change_scale, 'asinh')) bforward = Button(text=" --> ") bbackward = Button(text=" <-- ") bforward.bind(on_press=self.forward) bbackward.bind(on_press=self.backward) self.textnumber = TextInput(text=str(self.forward_backward_state), multiline=False, font_size=25) self.textnumber.bind(on_text_validate=self.change_number) tnumber = Label(text=str(' / ' + str(self.total_n_frame)), font_size=25) buttonbox.add_widget(buttonscale1) buttonbox.add_widget(buttonscale2) buttonbox.add_widget(buttonscale3) buttonbox.add_widget(buttonscale4) buttonbox.add_widget(bbackward) buttonbox.add_widget(bforward) buttonbox.add_widget(self.textnumber) buttonbox.add_widget(tnumber) allbox.add_widget(buttonbox) return allbox
class GUI(App): def build(self): # self.theme_cls.theme_style = "Dark" print(Path("images", "cat_loader.gif").absolute().__str__()) assert Path("images", "cat_loader.gif").exists() self.loading_gif = AsyncImage(source=Path("images", "cat_loader.gif").__str__(), anim_delay=0.03, mipmap=True) self.popup = None self.main_layout = GridLayout(cols=2) self.songs = {} self.quest_local_ip = None self.lhs = GridLayout(cols=1) self.textinput = TextInput( hint_text='Please enter Soundcloud and/or YouTube playlists/songs ', multiline=True, size_hint_x=0.7, # background_color=(0, 0, 0, 0), # foreground_color=(0.3, 0.4, 0.5, 1) ) self.lhs.add_widget(self.textinput) self.ip_input = TextInput(hint_text='Please enter Quest IP', multiline=False, size_hint_y=0.08) self.lhs.add_widget(self.ip_input) self.ip_input.bind(on_text_validate=self.get_ip) self.main_layout.add_widget(self.lhs) self.rhs = GridLayout(cols=1, size_hint_y=None) self.rhs.bind(minimum_height=self.rhs.setter('height')) get_details_btn = WrapButton(text="Get song details") get_details_btn.bind(on_press=self.details_thread) self.rhs.add_widget(get_details_btn) get_levels_btn = WrapButton(text="Get song beatsage levels") get_levels_btn.bind(on_press=self.levels_thread) self.rhs.add_widget(get_levels_btn) upload_commit_btn = WrapButton(text="Upload and commit levels") upload_commit_btn.bind(on_press=self.upload_commit_thread) self.rhs.add_widget(upload_commit_btn) root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) root.add_widget(self.rhs) self.main_layout.add_widget(root) return self.main_layout def get_ip(self, instance): ip_pat = re.compile(r"^(\d{3}\.\d{3}\.\d+\.\d+)$") text = instance.text check_ip = re.match(ip_pat, text) if check_ip: self.quest_local_ip = text else: popup = Popup( title='Warning', content=Label( text='Incorrect IP input.\n Please enter a valid lan IP'), size_hint=(None, None), size=(400, 200)) popup.open() def show_selected_value(self, spinner, text): spinner.text = self.spinner_text print('The spinner', spinner, 'has text', text) def get_text(self, instance, text): self.spinner_text = instance.text print(self.spinner_text) def details_thread(self, instance): threading.Thread(None, target=self.get_details).start() def loading_popup(self, title="Loading"): if self.popup is None: self.popup = Popup(title=title, content=self.loading_gif, size_hint=(None, None), size=(400, 200)) self.popup.bind(on_press=self.popup.dismiss) else: self.popup.title = title self.popup.open() def get_details(self): self.loading_popup(title="Loading Song Details") song_urls = self.textinput.text.split("\n") self.song_urls = get_song_urls(song_urls) print(self.song_urls) details = async_get_details(tuple(self.song_urls)) for det in details: spinner = WrapSpinner( status="Details Received", details=det, title=det.get("title"), text=det.get("title"), values=( f"Artist: {det.get('author') if det.get('author') is not None else 'Unable to determine'}", f'Uploader: {det.get("uploader")}', f'Platform: {det.get("extractor")}', f'View Count: {det.get("view_count")}', f'Like Count: {det.get("like_count")}', ), size_hint_y=None, height=40, background_color=[1, 0, 0, 1]) if det.get("title") not in self.songs.keys(): self.songs[det.get("title")] = spinner spinner.bind(on_touch_down=self.get_text) spinner.bind(text=self.show_selected_value) self.rhs.add_widget(spinner) self.check_status() self.popup.dismiss() def check_status(self, completed=False): for song in self.songs.values(): if completed: self.songs.get(song.title).status = "Level Synced" self.songs.get(song.title).background_color = [0, 1, 0, 1] else: level_file = Path("levels", get_sanitized_filename(song.title)) if level_file.exists() and level_file.is_file(): self.songs.get(song.title).status = "Level Downloaded" self.songs.get( song.title).background_color = [1, 0.65, 0, 1] self.songs.get(song.title).level_path = level_file def levels_thread(self, instance): threading.Thread(None, target=self.get_levels).start() def get_levels(self): self.loading_popup( "Downloading Levels (will take 2-5 minutes per song)") details = [ song.details for song in self.songs.values() if song.status == "Details Received" ] level_paths = async_get_levels(self.song_urls, details) for d in level_paths: title = list(d.keys())[0] level_path = d[title] self.songs[title].level_path = level_path self.check_status() self.popup.dismiss() def upload_commit_thread(self, instance): if self.quest_local_ip is None: popup = Popup( title='Warning', content=Label( text= 'No Oculus Quest IP address input.\n Please enter IP address.' ), size_hint=(None, None), size=(400, 200)) popup.open() else: threading.Thread(None, target=self.upload_commit).start() def upload_commit(self): self.loading_popup("Committing to Quest") level_paths = [ song.level_path for song in self.songs.values() if song.status in ["Level Downloaded", "Level Synced"] ] async_upload_levels_to_quest(level_paths, quest_local_ip=self.quest_local_ip) time.sleep(1) commit_to_quest(self.quest_local_ip) self.check_status(completed=True) self.popup.dismiss()
class PlayerPanel(BoxLayout): ''' Callback to update the panels periodically :dt The time increment ''' def updatePanels(self,dt): # Does the song list need a refresh (because new song is discovered) if self.songsNeedRefresh: self.populateSongList(self.songs) self.songsNeedRefresh = False # Update the player if it exists if self._player: self.timeSlider.value = self._player.getTime() ''' Callback if some text has been entered in the genre text field :instance The instance of the genre text field :value The value entered ''' def onGenreText(self,instance, value): genres = self.getGenres(value) self.genreListAdapter.data = genres ''' Callback if some text has been entered in the song name text field :instance The instance of the song name text field :value The value entered ''' def onSongTitleText(self,instance, value): self.titleFilter = value self.songs = self.getFilteredSongs(self.titleFilter,self.bandFilter) self.populateSongList(self.songs) ''' Callback if some text has been entered in the band name text field :instance The instance of the band text field :value The value entered ''' def onBandNameText(self,instance, value): self.bandFilter = value self.songs = self.getFilteredSongs(self.titleFilter,self.bandFilter) self.populateSongList(self.songs) ''' Fill the GUI with the songs that have been found :songs list of songs ''' def bpmToStars(self, bpm, lowerBound, upperBound): rng = upperBound - lowerBound offset = bpm - lowerBound starOffset = offset * 5.0 / rng stars = min(max(1, int(starOffset)+2),5) return "*" * stars def getBpmRange(self,genre): if genre in self.library.metadb.data: return self.library.metadb.data[genre] return [120,180] def populateSongList(self,songs): print ("populating") self.songListGrid.clear_widgets() index = 0 lastBtn = None for song in songs: songBtn = ToggleButton(text=song.title, size_hint_y=None, height=25,group='song') songBtn.bind(on_release=self.songSelectionChanged) songBtn.item=song songBtn.index = index songBtn.previousBtn = lastBtn if lastBtn: lastBtn.nextBtn = songBtn lastBtn = songBtn index+=1 bandLbl = Label(text=song.band,size_hint_x=0.4, width=150) durationLbl = Label(text=song.duration(),size_hint_x=None, width=70) bpmRange = self.getBpmRange(song.genre) spdTxt = self.bpmToStars(song.bpm, bpmRange[0], bpmRange[1]) speedLbl = Label(text=spdTxt,size_hint_x=0.4, width=40) self.songListGrid.add_widget(songBtn) self.songListGrid.add_widget(bandLbl) self.songListGrid.add_widget(durationLbl) self.songListGrid.add_widget(speedLbl) print ("populating done") def getGenres(self,filterString=""): genres = sorted(genre for genre in list(self.library.lookupTable) if filterString in genre) return genres def getFilteredSongs(self,nameFilterString="",bandFilterString=""): if self.selectedGenre in self.library.lookupTable: songList = [song for song in self.library.lookupTable[self.selectedGenre] if nameFilterString in song.title and bandFilterString in song.band] else: songList = [song for songs in list(self.library.lookupTable) for song in self.library.lookupTable[songs] if nameFilterString in song.title and bandFilterString in song.band] songs = sorted(songList) return songs def selectionChanged(self, *args): if len(args[0].selection)>0: self.selectedGenre = args[0].selection[0].text else: self.selectedGenre = "" self.songs = self.getFilteredSongs(self.titleFilter,self.bandFilter) self.populateSongList(self.songs) def onCheckboxActive(self,checkbox,value): self._player.setFastSpeedChange(value) def songSelectionChanged(self, button): global song self.selectedSong = button button.state = "down" self.selectedSongIndex = button.index if (self.selectedGenre): for testSong in self.library.lookupTable[self.selectedGenre]: if testSong.title == self.selectedSong.item.title: song = testSong break else: for key,value in self.library.lookupTable.items(): for testSong in value: if testSong.title == self.selectedSong.item.title: song = testSong break self.newSong = True self.timeSlider.value=0 self.startSong() def onLibraryLoaded(self,nbOfSongs,nbOfGenres): genres = self.getGenres() self.genreListAdapter.data = genres self.songs = self.getFilteredSongs() self.songsNeedRefresh = True if self._popup: self._popup.dismiss() print ("Found {:d} songs and {:d} dances".format(nbOfSongs,nbOfGenres)) def onSongFound(self,nbOfSongs,nbOfGenres): if self._popup: self._popup.content.text = "Found {:d} songs and {:d} dances".format(nbOfSongs,nbOfGenres) genres = self.getGenres() self.genreListAdapter.data = genres self.songs = self.getFilteredSongs() self.songsNeedRefresh = True def showPopup(self,ev): self._popup.open() def __init__(self, **kwargs): print("__init__") super(PlayerPanel, self).__init__(**kwargs) # Init all member variables self.titleFilter = "" self.bandFilter = "" self.newSong = False self.songIndex = -1 self.selectedGenre="" self.library = None self.selectedSongIndex=0 self.allowSetTime = False self.orientation = "vertical" self.speed = 1.0 self._popup = None self.songsNeedRefresh = False # Attach keyboard self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) # Setup layout mainPanel = BoxLayout() self.add_widget(mainPanel) controlPanel = BoxLayout(orientation='vertical',size_hint=(.3,1)) mainPanel.add_widget(controlPanel) dataPanel = BoxLayout(orientation='vertical',size_hint=(.7,1)) mainPanel.add_widget(dataPanel) filterPanel = BoxLayout() filterPanel.size=(300,30) filterPanel.size_hint=(1,None) dataPanel.add_widget(filterPanel) self.genreInput = TextInput(text='', multiline=False,height=30) self.genreInput.bind(text=self.onGenreText) controlPanel.add_widget(self.genreInput) self.genreListAdapter = ListAdapter(data=[],cls=ListItemButton,selection_mode='single') self.genreListAdapter.bind(on_selection_change=self.selectionChanged) self.genreList = ListView(adapter=self.genreListAdapter) controlPanel.add_widget(self.genreList) self.genreInput.size=(300,30) self.genreInput.size_hint=(1,None) self.songInput = TextInput(text='') self.songInput.bind(text=self.onSongTitleText) filterPanel.add_widget(self.songInput) self.bandInput = TextInput(text='', multiline=False,size=(300,30),size_hint=(.4,None)) self.bandInput.bind(text=self.onBandNameText) filterPanel.add_widget(self.bandInput) placeholder = Label(size_hint_x=None, width=70) filterPanel.add_widget(placeholder) self.songListGrid = GridLayout(cols=4, size_hint_y=None) self.songListGrid.bind(minimum_height=self.songListGrid.setter('height')) self.songListView = ScrollView() dataPanel.add_widget(self.songListView) self.songListView.add_widget(self.songListGrid) self._player = AudioPlayer() self._player.endReachedCallback = self.songEndReachedCallback self._player.loadedCallback = self.songLoadedCallback speedBox = BoxLayout(size=(300,30),size_hint=(1,None)) self.add_widget(speedBox) self.speedSpinner = Spinner(np.arange(0.5,2.1,0.1),5) self.speedSpinner.indexChangeCallback = self.speedChangeCallback speedBox.add_widget(self.speedSpinner) speedChkBox = BoxLayout(size=(200,30),size_hint=(1,None)) speedBox.add_widget(speedChkBox) speedChkLabel = Label(text="Fast speed change",halign="right") speedChkBox.add_widget(speedChkLabel) self.fastSpeedChangeChk = CheckBox(size=(30,30),size_hint=(None,None),active=True) self.fastSpeedChangeChk.bind(active=self.onCheckboxActive) speedChkBox.add_widget(self.fastSpeedChangeChk) self.timeSlider = TimeSlider(max=100,size=(30,60),size_hint=(1,None)) self.timeSlider.on_value=self.onSliderValueChange self.add_widget(self.timeSlider) # Create and show loading popup self._popup = Popup(title="Loading library", content=Label(text="Loading library"), size_hint=(0.8, 0.8)) self._popup.open() # Load music library if musicPath: self.library = MusicLibrary(musicPath) self.library.onLibraryLoaded = self.onLibraryLoaded self.library.onSongFound = self.onSongFound # Attach clock callback for gui updates event = Clock.schedule_interval(self.updatePanels, 1 / 30.) # Attach clock callback for loading of music event = Clock.schedule_once(self.loadMusic,1) #if self._popup: #self._popup.dismiss() def loadMusic(self,dt): self.library.loadMusic() def speedChangeCallback(self,speed): self.speed = speed def onSliderValueChange(self,instance,value): self._player.setTime(value) def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def pause(self): if self._player: self._player.togglePause() def backward(self): if self._player: self._player.setTime(self._player.getTime()-1) def forward(self): if self._player: self._player.set_time(self._player.getTime()+1) def playPrevious(self): if self.selectedSong: self.selectedSong = self.selectedSong.previousBtn self.selectedSong.trigger_action() def playNext(self): if self.selectedSong: self.selectedSong = self.selectedSong.nextBtn self.selectedSong.trigger_action() def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'spacebar' or keycode[1] == 'numpadenter': self.pause() elif keycode[1] == 'left': if len(modifiers)>0 and modifiers[0] == 'shift': self.backward() else: self.playPrevious() elif keycode[1] == 'right': if len(modifiers)>0 and modifiers[0] == 'shift': self.forward() else: self.playNext() elif keycode[1] == 'down': self.backward() elif keycode[1] == 'up': self.forward() return True def songEndReachedCallback(self,ev): self.playNext() def songLoadedCallback(self): self.timeSlider.max = self._player.trackLength/1000.0 def playSong(self): self._player.loadAndPlay(song,self.speed) def startSong(self): self.playSong()
class AddItems(FloatLayout): title = 'KAKABOKA' def __init__(self, **kwargs): super(AddItems, self).__init__() try: self.category = kwargs["category"] root = self root.bind(size=self._update_rect, pos=self._update_rect) self.bar_str = '' self.qty_str = '' # Product name label label_qty = Label(text='Product', color=(0, 0, 0, 0.25), font_size=20, pos_hint={ 'center_x': 0.175, 'center_y': 0.9 }) root.add_widget(label_qty) # barcode label label_bar = Label(text='Barcode', color=(0, 0, 0, 0.25), font_size=20, pos_hint={ 'center_x': 0.175, 'center_y': 0.8 }) root.add_widget(label_bar) # quantity label label_qty = Label(text='Quantity', color=(0, 0, 0, 0.25), font_size=20, pos_hint={ 'center_x': 0.175, 'center_y': 0.7 }) root.add_widget(label_qty) # price label label_price = Label(text='Price', color=(0, 0, 0, 0.25), font_size=20, pos_hint={ 'center_x': 0.175, 'center_y': 0.6 }) root.add_widget(label_price) # price label label_man = Label(text='Manufacturer', color=(0, 0, 0, 0.25), font_size=20, pos_hint={ 'center_x': 0.175, 'center_y': 0.5 }) root.add_widget(label_man) # Category label label_category = Label(text="Category", color=(0, 0, 0, 0.25), font_size=20, pos_hint={ 'center_x': 0.175, 'center_y': 0.4 }) root.add_widget(label_category) # text box for Product name self.itemname = TextInput(hint_text='Name', multiline=False, pos_hint={ 'center_x': 0.5, 'center_y': 0.9 }, size_hint=(0.5, 0.075)) root.add_widget(self.itemname) # text box for barcode self.barcode = TextInput(hint_text='barcode', multiline=False, pos_hint={ 'center_x': 0.5, 'center_y': 0.8 }, size_hint=(0.5, 0.075), on_text_validate=self.fetch) def on_text(instance, value): # use try to check if value in database self.bar_str = self.barcode.text self.barcode.bind(text=on_text) root.add_widget(self.barcode) # text box for quantity self.quantity = TextInput(text='1', multiline=False, hint_text="Quantity", pos_hint={ 'center_x': 0.5, 'center_y': 0.7 }, size_hint=(0.5, 0.075)) root.add_widget(self.quantity) # text box for Price self.price = TextInput(hint_text='USD', multiline=False, pos_hint={ 'center_x': 0.5, 'center_y': 0.6 }, size_hint=(0.5, 0.075)) root.add_widget(self.price) # text box for Manufacturer self.man = TextInput(hint_text='Brand', multiline=False, pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, size_hint=(0.5, 0.075)) root.add_widget(self.man) self.category_entry = TextInput(hint_text='Product Category', multiline=False, disabled=True, text=self.category, pos_hint={ 'center_x': 0.5, 'center_y': 0.4 }, size_hint=(0.5, 0.075)) root.add_widget(self.category_entry) # company name self.company = Button(text='KAKABOKA', color=(0, 0, 0, 1), background_color=(0, 0, 0, 0), font_size=30, size_hint=(.25, .07), pos_hint={ 'center_x': 0.12, 'center_y': 0.95 }) root.add_widget(self.company) # Done button donebtn = Button(text='Done', size_hint=(0.2, 0.15), pos_hint={ 'center_x': 0.5, 'center_y': 0.2 }) def callback2(instance): print("Callback 2") donebtn.bind(on_press=self.addItem) root.add_widget(donebtn) with root.canvas.before: base_folder = os.path.dirname(__file__) image_path = os.path.join(base_folder, 'background.png') self.rect = Rectangle(source=image_path, size=root.size, pos=root.pos) # return root except: messagebox(message="Category Not provided", title="Error!") def _update_rect(self, instance, value): self.rect.pos = instance.pos self.rect.size = instance.size def addItem(self, event): try: itemname = self.itemname.text itembarcode = self.barcode.text price = float(self.price.text) manufacturer = self.man.text quantity = int(self.quantity.text) item = models.Inventory(itemname=itemname, price=price, barcode=str(itembarcode), manufacturer=manufacturer, quantity=quantity, sold=0, category=self.category) saved = item.save(insert=True) if saved == 1: messagebox( title="Success", message="Item {} added successfully".format(itemname)) self.itemname.text = "" self.barcode.text = "" self.price.text = "" self.man.text = "" self.quantity.text = "" models.log(activity="Item Addition", transactiontype="additem", amount=0, barcode=itembarcode, time=str(datetime.datetime.now())) else: messagebox(title="Failed", message="Could not add {}".format(itemname)) except ValueError: messagebox(title="Warning", message="Price, quantity, barcode must be a Numbers") except pymysql.err.IntegrityError: # messagebox.showinfo(title="Error", # message="Item with same barcode cannot be added multiple times. Use update button to update the item details ") # p = Popup(title="Are you sure?", # content=Label( # text="Are you sure to overwrite the existing data for {}".format(self.itemname.text)), # size_hint=(None, None), size=(400, 200)) # p.open() # itembarcode = self.barcode.text # inventory_db = models.InventoryDB() # record = inventory_db.getInventoryRecodeByBarcode(itembarcode)[0] # self.quantity_update = str(record.quantity) # self.category_entry.text = record.category # self.category = record.category self.addItem_cascade() def addItem_cascade(self): try: itemname = self.itemname.text itembarcode = self.barcode.text price = float(self.price.text) manufacturer = self.man.text quantity = int(self.quantity.text) quantity = int(self.quantity_update) + quantity item = models.Inventory(itemname=itemname, price=price, barcode=str(itembarcode), manufacturer=manufacturer, quantity=quantity, sold=0, id=self.id, category=self.category) saved = item.save(update=True) if saved == 1 or saved == 0: # messagebox.showinfo(title="Success", message="Item {} updated successfully".format(itemname)) popup = Popup( title='Success', content=Label( text="Item {} updated successfully".format(itemname)), size_hint=(None, None), size=(400, 400)) popup.open() self.itemname.text = "" self.barcode.text = "" self.price.text = "" self.man.text = "" self.quantity.text = "" models.log(activity="Item modification", transactiontype="modify", amount=0, barcode=itembarcode, time=str(datetime.datetime.now())) else: messagebox(title="Failed", message="Nothing to update in {}".format(itemname)) except ValueError: messagebox(title="Warning", message="Price, quantity, barcode must be a Numbers") except AttributeError: messagebox( title="Oops!", message= "Seems like the item is already present in the database. \n" "Please fill in the barcode field and press \"Enter\" key to get all the details" "\nof the item and update corresponding fields") def fetch(self, event): itembarcode = self.barcode.text inventory_db = models.InventoryDB() record = inventory_db.getInventoryRecodeByBarcode(itembarcode) if record == []: messagebox(title="Failed", message="Item with this barcode does not exist") return record = record[0] # self.category_entry.text = record. # self.price.delete(0, END) # self.productname.delete(0, END) # self.productname.focus() # self.quantity.delete(0, END) # self.manufacturer.delete(0, END) # self.category_entry.delete(0, END) self.id = record.id self.price.text = str(record.price) self.itemname.text = record.itemname self.quantity.text = str(1) self.man.text = record.manufacturer self.category_entry.text = record.category self.category = record.category self.quantity_update = str(record.quantity)
class ConditionItem(BoxLayout): def __init__(self, *args, parent_device=None, **kwargs): self.orientation = "vertical" self.parent_device = parent_device self.height = 300 self.size_hint_y = None super(ConditionItem, self).__init__() self.conditional = Conditional() self.top_container = BoxLayout(size_hint_y=1) self.env_container = BoxLayout(orientation="vertical") self.set_container = BoxLayout(orientation="vertical") self.post_container = BoxLayout(orientation="vertical", size_hint_y=None, height=60) self.top_container.add_widget(self.env_container) self.top_container.add_widget(self.set_container) self.name_input = TextInput(hint_text="name", multiline=False, height=30, size_hint_y=None) self.name_input.bind(on_text_validate=lambda widget: setattr( self.conditional, "name", widget.text)) self.add_widget(self.name_input) self.add_widget(self.top_container) self.add_widget(self.post_container) store_button = Button(text="store", height=30, size_hint_y=None) store_button.bind(on_press=lambda widget: self.store()) self.add_widget(store_button) remove_button = Button(text="remove", height=30, size_hint_y=None) remove_button.bind(on_press=lambda widget: [ self.conditional.keys(remove_only=True), self.parent.remove_widget(self), ]) self.add_widget(remove_button) self.update() def update_from_conditional(self): self.name_input.text = str(self.conditional.name) self.env_input.text = "" if self.conditional.pre_contents: self.env_input.text = self.conditional.pre_contents[0] self.set_input.text = "" for k, v in self.conditional.set_contents.items(): self.set_input.text += "{} = {}\n".format(k, v) self.post_input.text = "" if self.conditional.post_contents: self.post_input.text = self.conditional.post_contents[0] def update(self): self.env_container.clear_widgets() self.set_container.clear_widgets() self.env_input = TextInput(hint_text="add conditions (keyling)") self.set_input = TextInput( hint_text="add settings (newline delimited 'foo = bar')") self.post_input = TextInput(hint_text="add post calls (keyling)") # on_validate does not call for multiline # env_input.bind(on_text_validate=lambda widget: self.validate_keyling(widget.text, widget)) # set_input.bind(on_text_validate=lambda widget: self.validate_setting(widget.text, widget)) # post_input.bind(on_text_validate=lambda widget: self.validate_keyling(widget.text, widget)) self.env_container.add_widget(self.env_input) self.set_container.add_widget(self.set_input) preview_button = Button(text="preview", height=30, size_hint_y=None) preview_button.bind(on_press=lambda widget: self.parent_device.preview( settings=self.validate_setting(self.set_input.text))) self.set_container.add_widget(preview_button) self.post_container.add_widget(self.post_input) def store(self): self.validate_keyling(self.env_input.text, set_on_valid="pre_contents", widget=self.env_input) self.validate_setting(self.set_input.text, set_on_valid="set_contents", widget=self.set_input) self.validate_keyling(self.post_input.text, set_on_valid="post_contents", widget=self.post_input) self.conditional.keys() def validate_keyling(self, text, set_on_valid=None, widget=None): current_background = [1, 1, 1, 1] try: # validate model keyling.model(text) if widget: anim = Animation( background_color=[0, 1, 0, 1], duration=0.5) + Animation( background_color=current_background, duration=0.5) anim.start(widget) if set_on_valid: setattr(self.conditional, set_on_valid, [text]) except Exception as ex: if widget: anim = Animation( background_color=[1, 0, 0, 1], duration=0.5) + Animation( background_color=current_background, duration=0.5) anim.start(widget) def validate_setting(self, text, set_on_valid=None, widget=None): # simple parsing for # key = value newline delimited text = text.strip() settings = {} current_background = [1, 1, 1, 1] valid = False for line in text.split("\n"): line = line.strip() try: key, value = line.split("=") key = key.strip() value = value.strip() valid = True settings[key] = value except Exception as ex: valid = False if valid: if widget: anim = Animation( background_color=[0, 1, 0, 1], duration=0.5) + Animation( background_color=current_background, duration=0.5) anim.start(widget) if set_on_valid: setattr(self.conditional, set_on_valid, settings) return settings else: if widget: anim = Animation( background_color=[1, 0, 0, 1], duration=0.5) + Animation( background_color=current_background, duration=0.5) anim.start(widget)
class DeviceItem(BoxLayout): def __init__(self, *args, app=None, **kwargs): self.orientation = "vertical" self.device = Device() self.app = app # by default open previewed with dzz self.default_view_call = "dzz-ui --size=1500x900 -- --db-host {host} --db-port {port} --db-key {thing} --db-key-field {thing_field}" self.state_key_template = "device:state:{uid}" self.setting_prefix = "SETTING_" super(DeviceItem, self).__init__() self.details_container = BoxLayout(orientation="vertical") self.conditions_container = BoxLayout(orientation="vertical", size_hint_y=None, height=1000, minimum_height=200) self.conditions_frame = BoxLayout(orientation="horizontal") self.settings_widgets = [] self.conditional_widgets = [] self.add_widget(self.details_container) create_condition_button = Button(text="new\ncond", width=60, size_hint_x=None) create_condition_button.bind( on_press=lambda widget: self.add_conditional()) self.conditions_frame.add_widget(create_condition_button) conditions_scroll = ScrollView(bar_width=20) conditions_scroll.add_widget(self.conditions_container) self.conditions_frame.add_widget(conditions_scroll) self.add_widget(self.conditions_frame) def update_conditions(self): self.conditions_container.clear_widgets() db_port = redis_conn.connection_pool.connection_kwargs["port"] db_host = redis_conn.connection_pool.connection_kwargs["host"] key_template = "settings:{step}:{name}:{device}:{host}:{port}" template_values = { "name": "*", "device": self.device.details["uid"], "host": db_host, "port": db_port, } found = {} for step in ["pre", "set", "post"]: template_values.update({"step": step}) pattern = key_template.format_map(template_values) print(pattern) for found_keys in redis_conn.scan_iter(match=pattern): _, _, name, uid, _, _ = found_keys.split(":") if name not in found: found[name] = {} found[name][step] = found_keys for conditional_name, step in found.items(): c = ConditionItem() c.conditional.device = self.device.details["uid"] c.parent_device = self c.conditional.name = conditional_name for step_name, step_key in step.items(): contents = None try: contents = redis_conn.lrange(step_key, 0, -1) except Exception as ex: try: contents = redis_conn.hgetall(step_key) except Exception as ex: pass if contents: setattr(c.conditional, "{}_contents".format(step_name), contents) c.update_from_conditional() self.add_conditional(c) def add_conditional(self, conditional=None): if conditional is None: conditional = ConditionItem() conditional.conditional.device = self.device.details["uid"] conditional.parent_device = self self.conditions_container.add_widget(conditional) self.conditions_container.parent.scroll_to(conditional) self.conditions_container.height += conditional.height def update_details(self): self.details_container.clear_widgets() self.settings_widgets = [] connected_color = [.5, .5, .5, 1] connected_text = "not connected" if self.device.connected: connected_color = [0, 1, 0, 1] connected_text = "connected" status_row = BoxLayout() connected_button = Button( text=connected_text, background_color=connected_color, height=30, size_hint_y=None, ) connected_button.bind( on_press=lambda widget: self.app.update_devices()) remove_button = Button(text="clear", height=30, size_hint_y=None) remove_button.bind( on_press=lambda widget: [self.parent.remove_widget(self)]) status_row.add_widget(connected_button) status_row.add_widget(remove_button) self.details_container.add_widget(status_row) # device information for k, v in self.device.details.items(): row = BoxLayout(height=30, size_hint_y=None) key = Label(text=str(k)) value = Label(text=str(v)) row.add_widget(key) row.add_widget(value) self.details_container.add_widget(row) # add adjustable values from the db # the db material is generated from xml # see enn-db and reference.xml try: # incorrect keys will be stored/reloaded from xml if "scripts" not in self.device.details: self.device.details["scripts"] = redis_conn.hget( "device:script_lookup", self.device.details["name"]) reference = redis_conn.hgetall("scripts:{}".format( self.device.details["scripts"])) for attribute, _ in reference.items(): row = BoxLayout(height=30, size_hint_y=None) key = Label(text=str(attribute)) value = TextInput(multiline=False) try: value.text = self.device.settings[attribute] except KeyError as ex: print(ex) pass value.bind( on_text_validate=lambda widget, attribute=attribute: self. set_device_setting(attribute, widget.text, widget)) # store to get set_device_setting before preview value.attribute = attribute self.settings_widgets.append(value) row.add_widget(key) row.add_widget(value) self.details_container.add_widget(row) except Exception as ex: print(ex) # preview self.view_call_input = TextInput(text=self.default_view_call, multiline=False, height=30, size_hint_y=None) self.view_call_input.bind( on_text_validate=lambda widget: self.check_call()) preview_button = Button( text="preview", background_color=connected_color, height=60, size_hint_y=None, ) preview_button.bind(on_press=lambda widget: self.preview()) get_state_button = Button(text="get state", height=30, size_hint_y=None) set_state_button = Button(text="set state", height=30, size_hint_y=None) get_state_button.bind(on_press=lambda widget: self.get_state()) set_state_button.bind(on_press=lambda widget: self.set_state()) get_set_state_row = BoxLayout(height=30, size_hint_y=None) load_state_from_row = BoxLayout(height=30, size_hint_y=None) load_state_from_button = Button(text="load state from", height=30, size_hint_y=None) load_state_from_input = TextInput(hint_text="db key", multiline=False, height=30, size_hint_y=None) load_state_from_button.bind( on_press=lambda widget, state_source=load_state_from_input: self. load_state(load_state_from_input.text)) get_set_state_row.add_widget(get_state_button) get_set_state_row.add_widget(set_state_button) self.details_container.add_widget(get_set_state_row) load_state_from_row.add_widget(load_state_from_button) load_state_from_row.add_widget(load_state_from_input) self.details_container.add_widget(load_state_from_row) self.details_container.add_widget(self.view_call_input) self.details_container.add_widget(preview_button) self.update_conditions() def get_state(self): state = redis_conn.hgetall( self.state_key_template.format_map(self.device.details)) if state: self.device.settings = state else: self.device.settings = {} self.update_details() def set_state(self): redis_conn.hmset( self.state_key_template.format_map(self.device.details), self.device.settings, ) def load_state(self, state_source): # try to load state from fields of a glworb possible_state_source_fields = redis_conn.hgetall(state_source) # only use if correct scripts try: if (possible_state_source_fields["{}scripts".format( self.setting_prefix)] == self.device.details["scripts"]): for k, v in possible_state_source_fields.items(): if k.startswith(self.setting_prefix): # remove prefix before adding self.device.settings[k[len(self.setting_prefix):]] = v self.update_details() except KeyError: pass def set_device_setting(self, attribute, value, widget=None): self.device.settings[attribute] = value if widget: current_background = [1, 1, 1, 1] anim = Animation( background_color=[0, 1, 0, 1], duration=0.5) + Animation( background_color=current_background, duration=0.5) anim.start(widget) def check_call(self): if not self.view_call_input.text: self.view_call_input.text = self.default_view_call def preview(self, settings=None): if settings is None: for widget in self.settings_widgets: self.set_device_setting(widget.attribute, widget.text, widget) settings = self.device.settings # apply settings for setting, setting_value in settings.items(): if setting_value: print(setting, setting_value, self.device.details) try: self.app.device_classes[ self.device.details["discovery"]].set_setting( self.device.details, setting, setting_value) except Exception as ex: print("setting: ", ex) # call may result in: [-108] File not found # if usb address has changed # # update devices again before calling self.app.update_devices() metadata = self.device.settings_prefixed(self.setting_prefix) slurped = self.app.device_classes[ self.device.details["discovery"]].slurp(device=self.device.details, metadata=metadata) view_call = self.view_call_input.text for thing in slurped: call_dict = { "host": self.app.db_host, "port": self.app.db_port, "thing": thing, "thing_field": "binary_key", } view_call = view_call.format_map(call_dict) subprocess.Popen(view_call.split(" "))
class menuPage(GridLayout, Screen): def __init__(self, **kwargs): super().__init__(**kwargs) self.cols = 2 self.box = BoxLayout(orientation='vertical', spacing=20, size_hint=(.5, .1)) self.buttons = BoxLayout(orientation='vertical', spacing=10, size_hint=(.99, .9)) self.popup = Popup( title='Test popup', content=Label( text="Will start typing in [color=#33cc33]3[/color] seconds", font_size="17sp", markup=True), size_hint=(None, None), size=(400, 400)) self.label = Label(text="", size_hint=(.5, .99)) self.typing = TextInput(hint_text='Write here', size_hint=(.99, .1), multiline=False) self.typing.bind(on_text_validate=self.addToList) self.add = Button(text='Add', size_hint=(.99, .1)) self.add.bind(on_press=self.addToList) self.start = Button(text='Start Typing', size_hint=(.99, .1)) self.start.bind(on_press=self.startTyping) self.save = Button(text='Save List', size_hint=(.99, .1)) self.save.bind(on_press=self.saveList) self.load = Button(text='Load Saved List', size_hint=(.99, .1)) self.load.bind(on_press=self.loadFromSaved) self.startL = Button(text='Start Listening', size_hint=(.99, .1)) self.startL.bind(on_press=self.listenScreen) self.removelast = Button(text='Remove Last item', size_hint=(.99, .1)) self.removelast.bind(on_press=self.removeLast) self.box.add_widget(Label(size_hint=(.5, .001))) self.box.add_widget(self.typing) self.box.add_widget(self.buttons) self.buttons.add_widget(self.add) self.buttons.add_widget(self.start) self.buttons.add_widget(self.save) self.buttons.add_widget(self.load) self.buttons.add_widget(self.startL) self.buttons.add_widget(self.removelast) self.buttons.add_widget(BoxLayout(size_hint=(.99, .6))) self.add_widget(self.label) self.add_widget(self.box) def addToList(self, instance): tempInt = 0 for c in self.typing.text: tempInt += ord(c) if tempInt % 32 != 0: self.label.text += "{}\n".format(self.typing.text) self.typing.text = "" else: pass def setList(self, saveFile): with open(resource_path("{}.txt".format(saveFile)), "r") as f: self.label.text += "{}".format(f.read()) f.close() def saveList(self, instance): n = 0 while True: try: with open(resource_path("save{}.txt".format(n)), "r") as f: n += 1 f.close() except: with open(resource_path("save{}.txt".format(n)), "w") as file: file.write(self.label.text) file.close() break def setListFromListener(self, text): self.label.text += "{}\n".format(text) def loadFromSaved(self, instance): subprocess.run([ "C:\\Users\\dusha\\miniconda3\\python.exe", resource_path("LoadFromSaved.py") ]) with open(resource_path("Clist.txt"), "r") as file: self.label.text += file.read() file.close() with open(resource_path("Clist.txt"), "w") as file: file.close() def listenScreen(self, instance): DushansMusicBOT.screenmanager.current = "listenPage" Listener() def startTyping(self, instance): self.popup.open() try: with open(resource_path("Clist.txt"), "a") as f: f.write(self.label.text) f.close() except: with open(resource_path("Clist.txt"), "w") as f: f.write(self.label.text) f.close() os.startfile(resource_path("DiscordMusicBot\\KivyzTyping.exe")) def removeLast(self, instance): listaPesni = self.label.text listaPesniKakoList = listaPesni.split("\n") if listaPesniKakoList[len(listaPesniKakoList) - 1] == "": listaPesniKakoList.pop() listaPesniKakoList.pop() else: listaPesniKakoList.pop() listaKakoString = "\n".join(str(e) for e in listaPesniKakoList) listaKakoString += "\n" self.label.text = listaKakoString
def show_property(self, instance, value, key=None, index=-1, *l): # normal call: (tree node, focus, ) # nested call: (widget, prop value, prop key, index in dict/list) if value is False: return content = None if key is None: # normal call nested = False widget = instance.widget key = instance.key prop = widget.property(key) value = getattr(widget, key) else: # nested call, we might edit subvalue nested = True widget = instance prop = None dtype = None if isinstance(prop, AliasProperty) or nested: # trying to resolve type dynamicly if type(value) in (str, str): dtype = 'string' elif type(value) in (int, float): dtype = 'numeric' elif type(value) in (tuple, list): dtype = 'list' if isinstance(prop, NumericProperty) or dtype == 'numeric': content = TextInput(text=str(value) or '', multiline=False) content.bind( text=partial(self.save_property_numeric, widget, key, index)) elif isinstance(prop, StringProperty) or dtype == 'string': content = TextInput(text=value or '', multiline=True) content.bind( text=partial(self.save_property_text, widget, key, index)) elif (isinstance(prop, ListProperty) or isinstance(prop, ReferenceListProperty) or isinstance(prop, VariableListProperty) or dtype == 'list'): content = GridLayout(cols=1, size_hint_y=None) content.bind(minimum_height=content.setter('height')) for i, item in enumerate(value): button = Button(text=repr(item), size_hint_y=None, height=44) if isinstance(item, Widget): button.bind( on_release=partial(self.highlight_widget, item, False)) else: button.bind(on_release=partial(self.show_property, widget, item, key, i)) content.add_widget(button) elif isinstance(prop, OptionProperty): content = GridLayout(cols=1, size_hint_y=None) content.bind(minimum_height=content.setter('height')) for option in prop.options: button = ToggleButton( text=option, state='down' if option == value else 'normal', group=repr(content.uid), size_hint_y=None, height=44) button.bind( on_press=partial(self.save_property_option, widget, key)) content.add_widget(button) elif isinstance(prop, ObjectProperty): if isinstance(value, Widget): content = Button(text=repr(value)) content.bind(on_release=partial(self.highlight_widget, value)) elif isinstance(value, Texture): content = Image(texture=value) else: content = Label(text=repr(value)) elif isinstance(prop, BooleanProperty): state = 'down' if value else 'normal' content = ToggleButton(text=key, state=state) content.bind(on_release=partial(self.save_property_boolean, widget, key, index)) self.content.clear_widgets() if content: self.content.add_widget(content)
class PartylineScreen(SideScreen): def __init__(self, **kwargs): # inicializace super(PartylineScreen, self).__init__(**kwargs) self.root.insertStrings.append((self, "STR_PARTYLINE")) self.input = TextInput(size_hint=(.8, .07), pos_hint={ 'x': .08, 'y': .024 }) self.output = Label(markup=True, font_name='font/Roboto-Regular.ttf', font_size='16dp', size_hint_y=None) self.SLayout = GridLayout(size_hint_y=None, cols=1, spacing=0) self.SLayout.bind(minimum_height=self.SLayout.setter('height')) self.scroll = ScrollView(size_hint=(1, .9), pos_hint={ 'center_x': .58, 'y': .125 }, scroll_timeout=10000) self.scroll.do_scroll_x = False self.scroll.add_widget(self.SLayout) self.SLayout.add_widget(self.output) self.layout = RelativeLayout(size_hint=(.75, .83), pos_hint={ 'center_x': .437, 'y': .02 }) self.send = DelButton(color=(1, 1, 1, 0), text='SEND', size_hint=(None, .1), pos_hint={ 'x': .88, 'y': .022 }, background_normal='crop/icons/send.png', background_down='crop/icons/send.png') self.send.bind(on_press=self.sendMsg) self.input.bind(focus=self.on_focus) self.layout.content.add_widget(self.scroll) self.layout.content.add_widget(self.input) self.layout.content.add_widget(self.send) self.add_widget(self.layout) if self.root.onAndroid(): self.LayouFocusOn = Animation(size_hint_y=.5, pos_hint={ 'center_x': .437, 'y': .38 }, duration=.2) self.LayouFocusOut = Animation(size_hint_y=.83, pos_hint={ 'center_x': .437, 'y': .02 }, duration=.2) def on_pre_enter(self, *args): # Voláno těsně před zobrazením obrazovky self.output.text_size = (self.root.root.size[0] * 0.75, None) def sendMsg(self, instance): # Odeslat zprávu do chatu if len(self.input.text) > 0: out = "pline " + str(self.root.id) + " " + self.input.text.replace( "\n", " ") self.root.send_message(out) self.root.print_message("{0}\xff".format(out)) self.input.text = "" def on_focus(self, instance, value): # Při označení vstupního pole if self.root.onAndroid(): if value: self.LayouFocusOn.start(self.layout) else: self.LayouFocusOut.start(self.layout) def prev(self): # Metoda pro návrat na předchozí obrazovku if self.input.focus: self.input.focus = False self.root.sm.transition = SlideTransition(direction="left") self.root.sm.current = 'GameScreen'
class MainApp(FloatLayout): def __init__(self, **kwargs): super().__init__(**kwargs) # background,toolbar self.title = Label(text="Gestionale", font_size=50, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.5, "center_y": 0.966 }) self.background = Button(background_color=(1, 1, 1, 1), background_normal="", background_down="") self.toolbar = Button(background_color=(64 / 255, 121 / 255, 191 / 255, 1), background_normal="", background_down="", size_hint=(1, 0.07), pos_hint={ "center_x": 0.5, "top": 1 }) self.new_customer = Button( text="nuovo cliente", font_size=30, pos_hint={ "center_x": 0.93, "center_y": 0.966 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.alertus) self.new_customer.bind(size=self.resize) self.options = Button(text="opzioni", font_size=30, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", pos_hint={ "center_x": 0.07, "center_y": 0.966 }, size_hint=(0.1, 0.06), on_press=self.add_options_liv) self.customer_number = Label( text=f"Numero di clienti : {customer_numberz}", font_size=40, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.3, "center_y": 0.866 }) self.search = TextInput(size_hint=(0.2, 0.05), pos_hint={ "center_x": 0.7, "center_y": 0.866 }, multiline=False, on_text_validate=self.search_fn) self.search_text = Label(text="Cerca", font_size=40, outline_color=(0, 0, 0, 1), outline_width=2, pos_hint={ "center_x": 0.55, "center_y": 0.866 }) self.all_button = Button( text="Tutti", font_size=30, size_hint=(0.05, 0.05), background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", pos_hint={ "center_x": 0.85, "center_y": 0.866 }, on_press=self.refresh) self.add_widget(self.background) self.add_widget(self.toolbar) self.add_widget(self.title) self.add_widget(self.new_customer) self.add_widget(self.options) self.add_widget(self.customer_number) self.add_widget(self.search) self.add_widget(self.search_text) self.add_widget(self.all_button) # customers navigation self.widgets() self.add_widget(self.root) # new customer self.alertliv = RelativeLayout() self.alertliv.add_widget( Button(background_color=(0, 0, 0, 0.2), background_down="", background_normal="", on_press=self.alertus)) self.alertliv.add_widget( Button(size_hint=(0.3, 0.3), background_down="assets/Button_white.png", background_normal="assets/Button_white.png", pos_hint={ "center_x": 0.5, "center_y": 0.5 })) self.labellotxt = Label(text=" Digita il nome\ndel nuovo cliente", outline_color=(0, 0, 0, 1), outline_width=2, font_size=40, pos_hint={ "center_x": 0.5, "center_y": 0.61 }) self.labello = TextInput(size_hint=(0.2, 0.05), pos_hint={ "center_x": 0.5, "center_y": 0.52 }, multiline=False) self.labello.bind(on_text_validate=self.save) self.ex = Button(text="Salva", pos_hint={ "center_x": 0.5, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", font_size=40, size_hint=(0.1, 0.1), on_press=self.save) self.alertliv.add_widget(self.labello) self.alertliv.add_widget(self.ex) self.alertliv.add_widget(self.labellotxt) # customer_view self.livello1 = RelativeLayout() self.title2 = Label(text="Gestionale", font_size=50, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.5, "center_y": 0.966 }) self.background2 = Button(background_color=(1, 1, 1, 1), background_normal="", background_down="") self.toolbar2 = Button(background_color=(191 / 255, 83 / 255, 64 / 255, 1), background_normal="", background_down="", size_hint=(1, 0.07), pos_hint={ "center_x": 0.5, "top": 1 }) self.exit = Button(text="Indietro", font_size=30, pos_hint={ "center_x": 0.93, "center_y": 0.966 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.add_customer_view) self.edit = Button(text="Elimina cliente", font_size=30, pos_hint={ "center_x": 0.07, "center_y": 0.966 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.alert3) self.works = TextInput(multiline=False, pos_hint={ "center_x": 0.5, "center_y": 0.35 }, size_hint=(0.9, 0.65), on_text_validate=self.validatee) self.customer_namez = Label(text=f"Cliente : {customer_name}", font_size=35, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.08, "center_y": 0.83 }) self.customer_namez.bind(text=self.text_input_change) self.livello1.add_widget(self.background2) self.livello1.add_widget(self.toolbar2) self.livello1.add_widget(self.exit) self.livello1.add_widget(self.edit) self.livello1.add_widget(self.title2) self.livello1.add_widget(self.works) self.livello1.add_widget(self.customer_namez) # work details self.text_work = TextInput(size_hint=(0.1, 0.03), multiline=False, pos_hint={ "center_x": 0.31, "center_y": 0.83 }) self.text_work_imp = TextInput(size_hint=(0.1, 0.03), multiline=False, pos_hint={ "center_x": 0.58, "center_y": 0.83 }) self.text_work_date = TextInput(size_hint=(0.1, 0.03), multiline=False, pos_hint={ "center_x": 0.86, "center_y": 0.83 }) self.text_work_details = TextInput(size_hint=(0.5, 0.03), multiline=False, pos_hint={ "center_x": 0.5, "center_y": 0.73 }) self.text_worK_text = Label(text="Lavoro", font_size=35, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.22, "center_y": 0.83 }) self.text_worK_text_imp = Label(text="Importo", font_size=35, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.49, "center_y": 0.83 }) self.text_worK_text_date = Label(text="Data", font_size=35, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.77, "center_y": 0.83 }) self.text_worK_text_details = Label(text="Dettagli", font_size=35, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.21, "center_y": 0.73 }) self.livello1.add_widget(self.text_work) self.livello1.add_widget(self.text_work_imp) self.livello1.add_widget(self.text_work_date) self.livello1.add_widget(self.text_worK_text) self.livello1.add_widget(self.text_work_details) self.livello1.add_widget(self.text_worK_text_imp) self.livello1.add_widget(self.text_worK_text_date) self.livello1.add_widget(self.text_worK_text_details) # work details save self.work_save = Button(text="Salva", font_size=30, pos_hint={ "center_x": 0.08, "center_y": 0.73 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.save_work) self.livello1.add_widget(self.work_save) #generate file.txt with customer details self.work_file = Button(text="Crea file.txt", font_size=30, pos_hint={ "center_x": 0.92, "center_y": 0.73 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.add_filechos) self.livello1.add_widget(self.work_file) # delete alert self.alertliv3 = RelativeLayout() self.alertliv3.add_widget( Button(background_color=(0, 0, 0, 0.2), background_down="", background_normal="")) self.alertliv3.add_widget( Button(size_hint=(0.3, 0.3), background_down="assets/Button_white.png", background_normal="assets/Button_white.png", pos_hint={ "center_x": 0.5, "center_y": 0.5 })) self.labello3 = Label( text="Vuoi davvero eliminare\n il cliente e i relativi dati?", outline_color=(0, 0, 0, 1), outline_width=2, font_size=40, pos_hint={ "center_x": 0.5, "center_y": 0.58 }) self.ex3 = Button(text="Si", pos_hint={ "center_x": 0.43, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", font_size=40, size_hint=(0.1, 0.1), on_press=self.deletez) self.ex3_1 = Button(text="No", pos_hint={ "center_x": 0.57, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", font_size=40, size_hint=(0.1, 0.1), on_press=self.alert3) self.alertliv3.add_widget(self.labello3) self.alertliv3.add_widget(self.ex3) self.alertliv3.add_widget(self.ex3_1) #general alert self.alertliv4 = RelativeLayout() self.alertliv4.add_widget( Button(background_color=(0, 0, 0, 0.2), background_down="", background_normal="", on_press=self.add_generical_alert)) self.alertliv4.add_widget( Button(size_hint=(0.3, 0.3), background_down="assets/Button_white.png", background_normal="assets/Button_white.png", pos_hint={ "center_x": 0.5, "center_y": 0.5 }, on_press=self.add_generical_alert)) self.labello4 = Label(text="", outline_color=(0, 0, 0, 1), outline_width=2, font_size=40, pos_hint={ "center_x": 0.5, "center_y": 0.58 }) self.ex4 = Button(text="Ok", pos_hint={ "center_x": 0.5, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", font_size=40, size_hint=(0.1, 0.1), on_press=self.add_generical_alert) self.alertliv4.add_widget(self.labello4) self.alertliv4.add_widget(self.ex4) #delete_all_customers extension self.yep = Button(text="Si", pos_hint={ "center_x": 0.42, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", font_size=40, size_hint=(0.1, 0.1), on_press=self.delete_all_customers_fn) self.nope = Button(text="No", pos_hint={ "center_x": 0.58, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", font_size=40, size_hint=(0.1, 0.1), on_press=self.add_generical_alert) #filechooser to get the path self.file_livl = RelativeLayout() self.title3 = Label(text="Gestionale", font_size=50, outline_color=(0, 0, 0, 0), outline_width=2, pos_hint={ "center_x": 0.5, "center_y": 0.966 }) self.backr = Button(background_color=(64 / 255, 121 / 255, 191 / 255, 1), background_normal="", background_down="", pos_hint={ "center_x": 0.5, "center_y": 0.5 }) self.toolbar3 = Button(background_color=(191 / 255, 83 / 255, 64 / 255, 1), background_normal="", background_down="", size_hint=(1, 0.07), pos_hint={ "center_x": 0.5, "top": 1 }) self.filechos = FileChooserIconView(pos_hint={ "center_x": 0.5, "center_y": 0.4 }) self.exit_fl = Button(text="Indietro", font_size=30, pos_hint={ "center_x": 0.93, "center_y": 0.966 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.add_filechos) self.get_file_b = Button( text="Genera file", font_size=30, pos_hint={ "center_x": 0.5, "center_y": 0.1 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.get_file) self.file_livl.add_widget(self.backr) self.file_livl.add_widget(self.toolbar3) self.file_livl.add_widget(self.title3) self.file_livl.add_widget(self.exit_fl) self.file_livl.add_widget(self.filechos) self.file_livl.add_widget(self.get_file_b) #options label self.alertliv5 = RelativeLayout() self.alertliv5.add_widget( Button(background_color=(0, 0, 0, 0.2), background_down="", background_normal="", on_press=self.add_options_liv)) self.alertliv5.add_widget( Button(size_hint=(0.3, 0.3), background_down="assets/Button_white.png", background_normal="assets/Button_white.png", pos_hint={ "center_x": 0.5, "center_y": 0.5 }, on_press=self.add_options_liv)) self.alertliv5.add_widget( Label(text="Opzioni", outline_color=(0, 0, 0, 1), outline_width=2, font_size=40, pos_hint={ "center_x": 0.5, "center_y": 0.6 })) self.alertliv5.add_widget( Button(text="Elimina clienti", font_size=30, pos_hint={ "center_x": 0.5, "center_y": 0.52 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.delete_all_customers)) self.alertliv5.add_widget( Button(text="Aggiorna app", font_size=30, pos_hint={ "center_x": 0.5, "center_y": 0.42 }, background_down="assets/Button_orange_2.png", background_normal="assets/Button_orange_2.png", size_hint=(0.1, 0.06), on_press=self.update)) # functions def text_input_change(self, *args): self.works.text = data_storage.get(customer_name)["data"] def resize(self, *args): if Window.size[0] < 955: self.new_customer.text = "nuovo\ncliente" self.edit.text = "Elimina\ncliente" # adapt button test in function of window size else: self.new_customer.text = "nuovo cliente" self.edit.text = "Elimina cliente" def alertus(self, *args): global check if check == False: self.add_widget(self.alertliv) check = True # add or remove the layout with "new_customer" else: self.remove_widget(self.alertliv) check = False def refresh(self, *args): self.layout.clear_widgets() self.widgets() self.remove_widget( self.root) # refresh scrollview (removes and adds it) self.add_widget(self.root) def search_fn(self, *args): self.layout.clear_widgets() self.widgets2() self.remove_widget( self.root) # refresh scrollview (removes and adds it) self.add_widget(self.root) self.search.text = "" def save(self, *args): global data_storage if len(self.labello.text) == 0: self.add_generical_alert( "Non puoi aggiungere un\n cliente senza nome!") else: if not self.labello.text in data_storage: data_storage.put(self.labello.text, data="") self.alertus() self.labello.text = "" # creates new customer and refreshes scrollview self.refresh() self.cus_num() else: self.add_generical_alert( " Il cliente che cerchi\ndi aggiungere esiste già!") def widgets(self, *args): global customer_name self.layout = GridLayout(cols=1, spacing=30, size_hint_y=None) self.root = ScrollView(size_hint=(0.77, 0.7), pos_hint={ "center_x": 0.5, "center_y": 0.42 }) self.layout.bind(minimum_height=self.layout.setter('height')) var = [] for i in data_storage: var.append(i) var = sorted(var) # creates scrollview with customers for i in var: def press(self, *args): global customer_name customer_name = self.text self.layout.bind(minimum_height=self.layout.setter('height')) self.sol = RelativeLayout(size_hint_y=None, height=50) self.btn = Button(text=i, font_size=30, size_hint_y=None, height=50, background_down="assets/Button_sky_4.png", background_normal="assets/Button_sky_4.png") self.btn_text = Label(text=i, font_size=30, outline_color=(0, 0, 0, 0), outline_width=2) self.sol.add_widget(self.btn) self.sol.add_widget(self.btn_text) self.layout.add_widget(self.sol) self.btn.bind(on_press=self.add_customer_view) self.btn.bind(on_press=press) self.root.add_widget(self.layout) def widgets2(self, *args): self.layout = GridLayout(cols=1, spacing=30, size_hint_y=None) self.root = ScrollView(size_hint=(0.77, 0.7), pos_hint={ "center_x": 0.5, "center_y": 0.42 }) self.layout.bind(minimum_height=self.layout.setter('height')) var = [] for i in data_storage: if self.search.text in i: var.append(i) var = sorted(var) # creates scrollview with customers for i in var: def press(self, *args): global customer_name customer_name = self.text self.layout.bind(minimum_height=self.layout.setter('height')) self.sol = RelativeLayout(size_hint_y=None, height=50) self.btn = Button(text=i, font_size=30, size_hint_y=None, height=50, background_down="assets/Button_sky_4.png", background_normal="assets/Button_sky_4.png") self.btn_text = Label(text=i, font_size=30, outline_color=(0, 0, 0, 0), outline_width=2) self.sol.add_widget(self.btn) self.sol.add_widget(self.btn_text) self.layout.add_widget(self.sol) self.btn.bind(on_press=self.add_customer_view) self.btn.bind(on_press=press) self.root.add_widget(self.layout) def add_customer_view(self, *args): global check1, customer_name if check1 == False: self.customer_namez.text = f"Cliente : {customer_name}" if len(customer_name) > 8: self.customer_namez.text = f"Cliente :\n{customer_name}" self.add_widget(self.livello1) check1 = True # adds layout with customer datas and options else: self.remove_widget(self.livello1) check1 = False def alert3(self, *args): global check2 if check2 == False: self.add_widget(self.alertliv3) check2 = True # adds a layout with "do you want really delete this customer?" else: self.remove_widget(self.alertliv3) check2 = False def deletez(self, *args): global customer_name data_storage.delete(customer_name) self.refresh() # function that deletes customer self.alert3() self.add_customer_view() self.cus_num() def cus_num(self, *args): global customer_numberz customer_numberz = len(data_storage) self.customer_number.text = f"Numero di clienti : {customer_numberz}" def save_work(self, *args): if self.works.text.endswith("\n") or len(self.works.text) == 0: self.works.text = self.works.text + self.text_work_date.text + " - " + self.text_work.text + " - " + self.text_work_imp.text + " - " + self.text_work_details.text + "\n" else: self.works.text = self.works.text + "\n" + self.text_work_date.text + " - " + self.text_work.text + " - " + self.text_work_imp.text + " - " + self.text_work_details.text + "\n" data_storage.put(customer_name, data=self.works.text) self.text_work.text = "" self.text_work_imp.text = "" self.text_work_date.text = "" self.text_work_details.text = "" def validatee(self, *args): data_storage.put(customer_name, data=self.works.text) def get_file(self, *args): global customer_name, file_path file_path = self.filechos.path file = open(f"{file_path}/{customer_name}.txt", "w") file.write(self.works.text) file.close() self.add_customer_view() self.add_filechos() if len(file_path) > 14: file_path = file_path.split("/") varx = len(file_path) varx = 1 / 2 * varx end_path = [] for x in file_path: if file_path.index(x) > varx: end_path.append(x) file_path.pop() file_path = "/".join(file_path) print(file_path) end_path = "/".join(end_path) print(end_path) self.add_generical_alert( f"file creato nella\ndirectory {file_path}/\n{end_path}") else: self.add_generical_alert( f"file creato nella\ndirectory {file_path}") def add_generical_alert(self, txt): global check3 if check3 == False: self.labello4.text = txt self.add_widget(self.alertliv4) check3 = True else: self.remove_widget(self.alertliv4) check3 = False try: self.alertliv4.add_widget(self.ex4) self.alertliv4.remove_widget(self.yep) self.alertliv4.remove_widget(self.nope) except: pass def add_filechos(self, *args): global check4 if check4 == False: self.add_widget(self.file_livl) check4 = True else: self.remove_widget(self.file_livl) check4 = False def add_options_liv(self, *args): global check5 if check5 == False: self.add_widget(self.alertliv5) check5 = True else: self.remove_widget(self.alertliv5) check5 = False def delete_all_customers(self, *args): self.add_options_liv() self.alertliv4.remove_widget(self.ex4) self.add_generical_alert( "Vuoi veramente eliminare\n tutti i clienti?") self.alertliv4.add_widget(self.yep) self.alertliv4.add_widget(self.nope) def delete_all_customers_fn(self, *args): data_storage for x in data_storage: data_storage.delete(x) self.refresh() self.add_generical_alert("") def update(self, *args): global version try: self.add_options_liv() filee = open("version.txt", "r") file1 = filee.read() filee.close() file1 = file1.replace("\n", "") version = float(file1) os.system("rm -rf version.txt") os.system("git clone https://github.com/Stef-deb/Version") os.system("mv Version/version.txt version.txt") os.system("rm -rf Version") filez = open("version.txt", "r") filez1 = filez.read() filez.close() file1 = filez1.replace("\n", "") final_version = float(filez1) if final_version > version: subprocess.Popen("./update.sh") sys.exit() else: self.add_generical_alert( f"L'app è alla versione\npiù aggiornata! {final_version}") except Exception as e: self.add_generical_alert(e)
class GUIReplay(GridLayout): def __init__(self, cls_game_layout, manager, **kwargs): super(GUIReplay, self).__init__(**kwargs) self.manager = manager self.auto_event = False self.cols = 1 self.game_layout = cls_game_layout(game=self.manager.wrapper.game) self.add_widget(self.game_layout) # control area self.control_area = GridLayout(cols=3) self.control_area.size_hint_y = None self.control_area.height = 200 self.btn_backward = Button(text='<|') self.set_position_input_text = TextInput( hint_text='set (0 <= position <= {}'.format( self.manager.get_max_position()), multiline=False, input_filter="int") self.btn_forward = Button(text='|>') self.btn_set_begin = Button(text='<<<') self.btn_auto_toggle = Button(text='AUTO') self.btn_set_end = Button(text='>>>') def on_enter(instance): pos = int(instance.text) if self.manager.set_position(pos): instance.text = '' else: print(pos) self.set_position_input_text.bind(on_text_validate=on_enter) self.control_area.add_widget(self.btn_backward) self.control_area.add_widget(self.set_position_input_text) self.control_area.add_widget(self.btn_forward) self.control_area.add_widget(self.btn_set_begin) self.control_area.add_widget(self.btn_auto_toggle) self.control_area.add_widget(self.btn_set_end) self.add_widget(self.control_area) def toggle_forward(self, dt): if self.auto_event and self.manager.forward(): Clock.schedule_once(self.toggle_forward, .5) self.btn_auto_toggle.text = 'STOP' return True else: self.btn_auto_toggle.text = 'AUTO' return False def on_touch_down(self, touch): if self.btn_forward.collide_point(*touch.pos): self.manager.forward() return True elif self.btn_backward.collide_point(*touch.pos): self.manager.backward() return True elif self.btn_set_begin.collide_point(*touch.pos): self.manager.set_position(0) return True elif self.btn_set_end.collide_point(*touch.pos): self.manager.set_position(self.manager.get_max_position()) return True elif self.btn_auto_toggle.collide_point(*touch.pos): if self.auto_event: self.auto_event = False else: Clock.schedule_once(self.toggle_forward, .1) self.auto_event = True return True else: return super(GUIReplay, self).on_touch_down(touch)
def simular_tab(instance): def pesquisa_forms_func(instance, value): pesquisa_forms.clear_widgets() cursor_forms.execute( "SELECT nome FROM forms WHERE nome LIKE '%{}%'".format( form.text)) nomes = cursor_forms.fetchall() for i in nomes: for z in i: pesquisa_forms.add_widget(Label(text=str(z))) def enviar_simulacao(instance): def comitar(instance): validar = True for i in range(len(valor_quando_abater)): if valor_quando_abater[i] < 0: validar = False if validar == True: for i in range(len(valor_quando_abater)): lista_pro_db = [ valor_quando_abater[i], nomes_pigmentos_lista[i] ] conn.execute( "UPDATE pigmentos SET estoque = ? WHERE nome = ?", lista_pro_db) conn.commit() try: valor_quando_abater = [] cursor.execute("SELECT nome FROM pigmentos") nomes_pigmentos = cursor.fetchall() nomes_pigmentos_lista = [] for i in nomes_pigmentos: for j in i: nomes_pigmentos_lista.append(j) for i in range(len(nomes_pigmentos_lista)): nome_pro_db = [nomes_pigmentos_lista[i]] cursor.execute( "SELECT estoque FROM pigmentos WHERE nome = ?", nome_pro_db) valor_antigo = cursor.fetchone() for z in valor_antigo: valor_antigo_fora_do_tuple = z valor_quando_abater.append( valor_antigo_fora_do_tuple - tabela_simulacao_cores[i]) # print(float(valor_antigo_fora_do_tuple)) # print(float(tabela_simulacao_cores[i])) layout_mostrar_simulacao = GridLayout(cols=2) layout_mostrar_simulacao.add_widget( Label(text="NOME PGMENTO")) layout_mostrar_simulacao.add_widget( Label(text="VALOR DEPOIS DA SIMULAÇÃO")) for i in range(len(valor_quando_abater)): layout_mostrar_simulacao.add_widget( Label(text=str(nomes_pigmentos_lista[i]))) if valor_quando_abater[i] >= 0: layout_mostrar_simulacao.add_widget( Label(text=str(valor_quando_abater[i]))) else: layout_mostrar_simulacao.add_widget( Label(text=str(valor_quando_abater[i]), color=[1, 0, 0, 1])) layout_mostrar_simulacao_btt_enviar = Button( text="enivar") layout_mostrar_simulacao_btt_enviar.bind( on_press=comitar) layout_mostrar_simulacao.add_widget( layout_mostrar_simulacao_btt_enviar) layout_mostrar_simulacao_btt_cancelar = Button( text="cancelar") layout_mostrar_simulacao.add_widget( layout_mostrar_simulacao_btt_cancelar) layout_mostrar_simulacao_popup = Popup( title="SIMULAÇÃO", content=layout_mostrar_simulacao, size_hint=(0.85, 0.85)) layout_mostrar_simulacao_popup.open() except: print("deu não mano") cursor_forms.execute("SELECT pgmts FROM forms") tamanho_lista = cursor_forms.fetchall() for i in tamanho_lista: for z in i: a = z.split('\n') try: tabela_simulacao_cores = [0] * (int(len(a) / 2)) except: pass def adicionar_cor(instance): def refresh_simu(): layout_mostrar_simulacao.clear_widgets() try: valor_quando_abater = [] valor_antes_abater = [] cursor.execute("SELECT nome FROM pigmentos") nomes_pigmentos = cursor.fetchall() nomes_pigmentos_lista = [] for i in nomes_pigmentos: for j in i: nomes_pigmentos_lista.append(j) for i in range(len(nomes_pigmentos_lista)): nome_pro_db = [nomes_pigmentos_lista[i]] cursor.execute( "SELECT estoque FROM pigmentos WHERE nome = ?", nome_pro_db) valor_antigo = cursor.fetchone() for z in valor_antigo: valor_antigo_fora_do_tuple = z valor_quando_abater.append( valor_antigo_fora_do_tuple - tabela_simulacao_cores[i]) valor_antes_abater.append( valor_antigo_fora_do_tuple) # print(float(valor_antigo_fora_do_tuple)) # print(float(tabela_simulacao_cores[i])) for i in range(len(valor_quando_abater)): if valor_quando_abater[ i] != valor_antes_abater[i]: layout_mostrar_simulacao.add_widget( Label(text=str( nomes_pigmentos_lista[i]))) if valor_quando_abater[i] >= 0: layout_mostrar_simulacao.add_widget( Label(text=str( valor_quando_abater[i]))) else: layout_mostrar_simulacao.add_widget( Label(text=str( valor_quando_abater[i]), color=[1, 0, 0, 1])) else: print("{} não alterou".format( nomes_pigmentos_lista[i])) except: print("sei lá qq deu") if form.text == '' or form.text == " ": print("vai dar nao") else: formula = [form.text] cursor_forms.execute( "SELECT pgmts FROM forms WHERE nome = ?", formula) lista_pgmt = cursor_forms.fetchall() lista_formatada = [] for i in lista_pgmt: for z in i: lista_formatada_pre = z.split("\n") try: for xyz in lista_formatada_pre: if xyz.isnumeric(): lista_formatada.append(xyz) forms_enviados.add_widget( Label(text=form.text + " X {}".format(qnt.text))) except: print("existe essa cor nao") for asd in range(len(lista_formatada)): try: tabela_simulacao_cores[asd] += (float( lista_formatada[asd])) * int(qnt.text) except: pass form.text = "" qnt.text = "1" refresh_simu() def abater_formula(instance): if form.text == "" or form.text == " ": print("vai dar nao tbm") else: form_name = [form.text] cursor_forms.execute( "SELECT * FROM forms WHERE nome=?", form_name) test = cursor_forms.fetchall() nomes = [] valores = [] for i in test: for j in test: for z in range(len(j)): s = j[z].split("\n") for zx in range(len(s)): if zx % 2 == 0: nomes.append(s[zx]) else: valores.append("-" + s[zx]) try: nomes.remove(nomes[0]) except: print("essa parada nao exist nao") for i in range(len(nomes)): nome_tabela = [nomes[i]] cursor.execute( "SELECT estoque FROM pigmentos WHERE nome = ?", nome_tabela) result = cursor.fetchone() for z in result: estoque_antigo = z novo_estoque = float( valores[i]) + float(estoque_antigo) incremento_estoque = [novo_estoque, nomes[i]] conn.execute( "UPDATE pigmentos SET estoque = ? WHERE nome = ?", incremento_estoque) conn.commit() def limpar_sim(instance): # entendi direito como funciona não simular_tab(instance) layout_simular_tab_full_mais_full_ainda = GridLayout(cols=2) layout_simular_tab_full = GridLayout(rows=2) layout_simular_tab = GridLayout(cols=2) layout_simular_tab.add_widget(Label(text='formula')) form = TextInput(multiline=False) form.bind(text=pesquisa_forms_func) layout_simular_tab.add_widget(form) layout_simular_tab.add_widget(Label(text='Quantidade')) qnt = TextInput(multiline=False, input_filter='float', text="1") layout_simular_tab.add_widget(qnt) pesquisa_forms = GridLayout(cols=2) forms_enviados = GridLayout(cols=2) layout_simular_tab.add_widget(pesquisa_forms) layout_simular_tab.add_widget(forms_enviados) layout_simular_tab_full.add_widget(layout_simular_tab) simular_tab_btts_bottom = GridLayout(cols=3, size_hint=(1, 0.3)) simular_tab_btts_bottom_btt_simular = Button(text="simular") simular_tab_btts_bottom_btt_simular.bind( on_press=enviar_simulacao) simular_tab_btts_bottom.add_widget( simular_tab_btts_bottom_btt_simular) simular_tab_btts_bottom_btt_adicionar_cor = Button( text="adicionar cor") simular_tab_btts_bottom_btt_adicionar_cor.bind( on_press=adicionar_cor) simular_tab_btts_bottom.add_widget( simular_tab_btts_bottom_btt_adicionar_cor) simular_tab_btts_bottom_btt_abater_estoque = Button( text="abater no estoque") simular_tab_btts_bottom_btt_abater_estoque.bind( on_press=abater_formula) simular_tab_btts_bottom.add_widget( simular_tab_btts_bottom_btt_abater_estoque) simular_tab_btts_bottom_btt_limpar = Button(text="LIMPAR") simular_tab_btts_bottom_btt_limpar.bind(on_press=limpar_sim) simular_tab_btts_bottom.add_widget( simular_tab_btts_bottom_btt_limpar) layout_simular_tab_full.add_widget(simular_tab_btts_bottom) layout_simular_tab_full_mais_full_ainda.add_widget( layout_simular_tab_full) try: valor_quando_abater = [] cursor.execute("SELECT nome FROM pigmentos") nomes_pigmentos = cursor.fetchall() nomes_pigmentos_lista = [] for i in nomes_pigmentos: for j in i: nomes_pigmentos_lista.append(j) for i in range(len(nomes_pigmentos_lista)): nome_pro_db = [nomes_pigmentos_lista[i]] cursor.execute( "SELECT estoque FROM pigmentos WHERE nome = ?", nome_pro_db) valor_antigo = cursor.fetchone() for z in valor_antigo: valor_antigo_fora_do_tuple = z valor_quando_abater.append(valor_antigo_fora_do_tuple - tabela_simulacao_cores[i]) # print(float(valor_antigo_fora_do_tuple)) # print(float(tabela_simulacao_cores[i])) layout_mostrar_simulacao = GridLayout(cols=2) layout_mostrar_simulacao.add_widget( Label(text="NOME PGMENTO")) layout_mostrar_simulacao.add_widget( Label(text="VALOR DEPOIS DA SIMULAÇÃO")) for i in range(len(valor_quando_abater)): layout_mostrar_simulacao.add_widget( Label(text=str(nomes_pigmentos_lista[i]))) if valor_quando_abater[i] >= 0: layout_mostrar_simulacao.add_widget( Label(text=str(valor_quando_abater[i]))) else: layout_mostrar_simulacao.add_widget( Label(text=str(valor_quando_abater[i]), color=[1, 0, 0, 1])) except: print("sei lá qq deu") layout_simular_tab_full_mais_full_ainda.add_widget( layout_mostrar_simulacao) layout_simular_tab_full_popup = Popup( title="ABA DE SIMULAÇÃO?", content=layout_simular_tab_full_mais_full_ainda, size_hint=(0.85, 0.85)) layout_simular_tab_full_popup.open()
class ExerciseRunningInputWidget( GridLayout ): def __init__( self, exercise_running, current_training_screen, **kwargs ): super( ExerciseRunningInputWidget, self ).__init__( **kwargs ) self.cols = 1 self.spacing = 1 self.row_default_height = 40 self.row_force_default = True self.size_hint_y = None self.bind( minimum_height = self.setter('height') ) self.exercise_name = exercise_running.description['name'] title_layout = BoxLayout( orientation = 'horizontal', spacing = 30 ) excercise_label = Label( text = self.exercise_name ) title_layout.add_widget( excercise_label ) title_layout.add_widget( Label( text = "Distance (km)" ) ) title_layout.add_widget( Label( text = "Time" ) ) del_excercise_btn = Button( text = "Del Exc", size_hint_x = 0.3 ) del_excercise_btn.on_press = \ lambda: current_training_screen.remove_exercise( self ) title_layout.add_widget( del_excercise_btn ) self.add_widget( title_layout ) self.add_dist_time_intervals_from_exercise( exercise_running, current_training_screen ) add_interval_btn_layout = BoxLayout( orientation = 'horizontal', spacing = 30 ) add_interval_btn_layout.add_widget( Label( text='', size_hint = (0.30, 1.0) ) ) add_interval_btn_layout.add_widget( Button( text = 'Add interval', size_hint = (0.775, 1.0), on_press = lambda x: self.add_dist_time_interval( current_training_screen, index_in_layout = 2 ) ) ) self.add_widget( add_interval_btn_layout ) comment_text = exercise_running.description.get( 'comment', 'Comment Exercise') self.comment = TextInput( hint_text = comment_text ) self.comment.bind( text = current_training_screen.update_training_from_user_input ) self.add_widget( self.comment ) def add_dist_time_intervals_from_exercise( self, exercise_running, current_training_screen ): for (dist, time) in zip( exercise_running.description['distances'], exercise_running.description['times'] ): self.add_dist_time_interval( current_training_screen, dist, time ) def add_dist_time_interval( self, current_training_screen, hint_dist = '1.0', hint_time = '4:00', index_in_layout = 0 ): interval_layout = GridLayout( rows = 1, spacing = 30 ) interval_layout.height = 30 pos_shift = Label( text='' ) interval_layout.add_widget( pos_shift ) distance = TextInput( hint_text = str( hint_dist ) ) interval_layout.add_widget( distance ) time = TextInput( hint_text = str( hint_time ) ) interval_layout.add_widget( time ) distance.bind( text = current_training_screen.update_training_from_user_input ) time.bind( text = current_training_screen.update_training_from_user_input ) del_button = Button( text = "Del Int", size_hint_x = 0.3 ) del_button.on_press = lambda: self.remove_interval_widget( current_training_screen, interval_layout ) interval_layout.add_widget( del_button ) self.add_widget( interval_layout, index = index_in_layout ) def exercise_from_user_input( self ): # todo: add input check intervals = len( self.children[2:-1] ) distances = [] times = [] for dist_time_interval in self.children[2:-1]: dist_input = dist_time_interval.children[2].text time_input = dist_time_interval.children[1].text if dist_input is not None: distances.insert( 0, dist_input ) if time_input is not None: times.insert( 0, time_input ) comment = self.comment.text exc = ExerciseRunning( name = self.exercise_name, intervals = intervals, distances = distances, times = times, description_dict = { 'comment': comment } ) return( exc ) def remove_interval_widget( self, current_training_screen, interval_layout ): self.remove_widget( interval_layout ) current_training_screen.update_training_from_user_input() print( 'deleting' )
class Login(Screen): def __init__(self, **kwargs): super(Login, self).__init__(**kwargs) self.app = App.get_running_app() self.build_layout() def build_layout(self): self.welcome = Label( color=(.17,.34,.52,1), font_size='45dp', text='Hello,', pos_hint={'center_x': .42, 'center_y': .805} ) self.add_widget(self.welcome) self.welcome2 = Label( color=(.17,.34,.52,.5), font_size='30dp', text='welcome to\nDate Master.', pos_hint={'center_x': .5, 'center_y': .73} ) self.add_widget(self.welcome2) self.email = TextInput( padding=(50,75,0,0), multiline=False, background_color=(.17,.34,.52,.5), foreground_color=(0.231, 0.647, 0.541, 1), font_size='30dp', hint_text='Email', size_hint=(.95, .1), pos_hint={'center_x': .5, 'center_y': .6} ) self.add_widget(self.email) self.password = TextInput( padding=(50,75,0,0), multiline=False, background_color=(.17,.34,.52,.5), foreground_color=(0.231, 0.647, 0.541, 1), font_size='30dp', hint_text='Password', password=True, size_hint=(.95, .1), pos_hint={'center_x': .5, 'center_y': .48} ) self.password.bind(on_text_validate=self.login) self.add_widget(self.password) self.error_msg = Label( color=(0,1,0,1), font_size='30dp', size_hint=(.1, .1), pos_hint={'center_x': .5, 'center_y': .9} ) self.add_widget(self.error_msg) self.login_btn = Button( color=(0.752, 0.607, 0.349, 1), background_color=(.90,.63,.47,1), text='Login', font_size='40dp', size_hint=(.8, .1), pos_hint={'center_x': .5, 'center_y': .36} ) self.login_btn.bind(on_release=self.login) self.add_widget(self.login_btn) self.try_btn = Button( color=(0.752, 0.607, 0.349, 1), background_color=(.90,.63,.47,1), text='Try Again', font_size='40dp', size_hint=(.8, .1), pos_hint={'center_x': .5, 'center_y': .27} ) self.try_btn.bind(on_press=self.retry_refresh_token) def login(self, event): self.error_msg.test='' # For testing if self.email.text == 't': self.email.text = '*****@*****.**' self.password.text = '123456' elif self.email.text == 's': self.email.text = '*****@*****.**' self.password.text = '123456' # req = self.app.fb.sign_in(self.email.text, self.password.text, self.error_msg) if req['success']: print('calling app.login') self.app.login(1) elif self.error_msg.text == '': self.error_msg.text = 'Problem connecting' def on_enter(self): self.email.text = '' self.password.text = '' def retry_refresh_token(self, event): filename = join(self.app.user_data_dir, "refresh_token.txt") with open(filename, 'r') as f: refresh_token = f.read() # if refresh_token and data req = self.app.fb.exchange_refresh_token(refresh_token) if req['success']: self.app.id_token = req['id_token'] self.app.local_id = req['local_id'] self.app.login() else: self.error_msg.text='Expired Token' def back_pressed(self): self.app.stop()
class Mama_lay(FloatLayout): def __init__(self, **kwargs): super(Mama_lay, self).__init__(**kwargs) Window.bind(on_resize=self.window_size_changed) self.sataurebi_lay = BoxLayout(orientation="horizontal", size_hint_x=.85, size_hint_y=.15, pos_hint={ 'x': .0, 'y': .80 }) self.add_widget(self.sataurebi_lay) self.sataurebi = [ "N", "დასახელება", "არჩევა", "გაცემის-თარიღი", "საბოლოო ვადა", "მიმდინარე სტატუსი", ] for i in self.sataurebi: self.sataurebi_lay.add_widget( Label(text=str('{}'.format(i)), size_hint_y=None, height=40, font_name="bpg_arial_2009", font_size=20)) self.pirovneba_box = BoxLayout(size_hint_x=.50, size_hint_y=.06, pos_hint={ 'x': .30, 'y': .90 }) self.add_widget(self.pirovneba_box) self.name_label = Label(text="სახელი", font_name="bpg_arial_2009", font_size=24) self.pirovneba_box.add_widget(self.name_label) self.name_text = TextInput(hint_text="სახელი", font_name="bpg_arial_2009", font_size=20) self.name_text.bind(text=self.on_text_name) self.pirovneba_box.add_widget(self.name_text) self.surname_label = Label(text="გვარი", font_name="bpg_arial_2009", font_size=24) self.pirovneba_box.add_widget(self.surname_label) self.surname_text = TextInput(hint_text="გვარი", font_name="bpg_arial_2009", font_size=20) self.surname_text.bind(text=self.on_text_surname) self.pirovneba_box.add_widget(self.surname_text) self.add_widget(Scroll_Boxv2()) def on_text_name(self, instance, value): Functionation_class.person["saxeli"] = value print(Functionation_class.person["saxeli"]) def on_text_surname(self, instance, value): Functionation_class.person["gvari"] = value print(Functionation_class.person["gvari"]) def window_size_changed(self, window, width, height): for shvilebi in self.sataurebi_lay.children: shvilebi.font_size = width / 68.3 for shvilebi in self.pirovneba_box.children: shvilebi.font_size = width / 68.3
class Formulario(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.orientation = 'vertical' self.padding = 20 # define grelha para label e txt grid_label_txt = GridLayout(cols=2) self.add_widget(grid_label_txt) # ------ grid_label_txt.add_widget(Label(text='Nome')) self.txt_nome = TextInput(multiline=False) grid_label_txt.add_widget(self.txt_nome) self.txt_nome.bind() # ------ grid_label_txt.add_widget(Label(text='Email')) self.txt_email = TextInput(multiline=False) grid_label_txt.add_widget(self.txt_email) # ------ grid_label_txt.add_widget(Label(text='Tem carro')) self.chk_carro = CheckBox() grid_label_txt.add_widget(self.chk_carro) # ------ grid_label_txt.add_widget(Label(text='Sexo')) sex_grid = GridLayout(cols=2) sex_grid.add_widget(Label(text = 'Masculino')) self.sexo_m = CheckBox(group='sexo') sex_grid.add_widget(self.sexo_m) sex_grid.add_widget(Label(text = 'Feminino')) self.sexo_f = CheckBox(group='sexo') sex_grid.add_widget(self.sexo_f) grid_label_txt.add_widget(sex_grid) # ------ grid_label_txt.add_widget(Label(text='País')) self.spinner_pais = Spinner( text='Nacionalidade', values=('Portugal', 'Espanha', 'França', 'Itália') ) grid_label_txt.add_widget(self.spinner_pais) # define outra grelha para os 4 botões grid_bts = GridLayout(cols=5) self.add_widget(grid_bts) self.bt_novo = Button(text='Novo') self.bt_novo.bind(on_release=self.botao_clicado) grid_bts.add_widget(self.bt_novo) self.bt_apaga = Button(text='Apaga') self.bt_apaga.bind(on_release=self.botao_clicado) grid_bts.add_widget(self.bt_apaga) self.bt_grava = Button(text='Grava') self.bt_grava.bind(on_release=self.botao_clicado) grid_bts.add_widget(self.bt_grava) self.bt_anterior = Button(text='Anterior') self.bt_anterior.bind(on_release=self.botao_clicado) grid_bts.add_widget(self.bt_anterior) self.bt_proximo = Button(text='Próximo') self.bt_proximo.bind(on_release=self.botao_clicado) grid_bts.add_widget(self.bt_proximo) self.barra_de_progresso = ProgressBar(max=100, value=0) self.add_widget(self.barra_de_progresso) self.utilizadores = [ {'nome': 'ze', 'email': '*****@*****.**', 'carro': True, 'pais': 'Portugal'}, {'nome': 'quim', 'email': '*****@*****.**', 'carro': False, 'pais': 'Espanha'} ] self.idx = 0 self.atualiza_formulario() def atualiza_formulario(self): print(self.idx) if self.idx >= 0: self.txt_nome.text = self.utilizadores[self.idx]['nome'] self.txt_email.text = self.utilizadores[self.idx]['email'] self.barra_de_progresso.value = ( self.idx + 1.) / len(self.utilizadores) * 100 self.chk_carro.active = self.utilizadores[self.idx]['carro'] self.spinner_pais.text = self.utilizadores[self.idx]['pais'] else: self.txt_nome.text = 'Sem registos.' self.txt_email.text = 'Sem registos.' def botao_clicado(self, instance): if instance == self.bt_novo: self.utilizadores.append({'nome': '?', 'email': '?', 'carro': '?', 'pais': '?'}) self.idx = len(self.utilizadores) - 1 elif instance == self.bt_apaga: if self.idx >= 0: del self.utilizadores[self.idx] self.idx = self.idx if self.idx < len(self.utilizadores) else len(self.utilizadores) - 1 elif instance == self.bt_grava: if self.idx >= 0: self.utilizadores[self.idx]['nome'] = self.txt_nome.text self.utilizadores[self.idx]['email'] = self.txt_email.text self.utilizadores[self.idx]['carro'] = self.chk_carro.active self.utilizadores[self.idx]['pais'] = self.spinner_pais.text elif instance == self.bt_anterior: self.idx -= 1 if self.idx < 0: self.idx = len(self.utilizadores) - 1 elif instance == self.bt_proximo: self.idx += 1 if self.idx >= len(self.utilizadores): self.idx = - 1 if len(self.utilizadores) == 0 else 0 else: self.idx = -1 print("Algo correu mal!!!") self.atualiza_formulario()
txtinput_run_command = TextInput(multiline=False, font_size=self.font_size, font_name=self.font_name) def interact_with_command(*l): popen_obj = self.popen_obj if not popen_obj: return txt = l[0].text + u'\n' popen_obj_stdin = popen_obj.stdin popen_obj_stdin.write(txt.encode('utf-8')) popen_obj_stdin.flush() self.txtinput_run_command_refocus = True self.txtinput_run_command_refocus = False txtinput_run_command.bind(on_text_validate=interact_with_command) txtinput_run_command.bind(focus=self.on_focus) btn_kill = Button(text="kill", width=27, size_hint=(None, 1)) def kill_process(*l): self.popen_obj.kill() self.interact_layout = il = GridLayout(rows=1, cols=2, height=27, size_hint=(1, None)) btn_kill.bind(on_press=kill_process) il.add_widget(txtinput_run_command) il.add_widget(btn_kill) parent.add_widget(il)
def test_focusable_when_disabled(self): ti = TextInput() ti.disabled = True ti.focused = True ti.bind(focus=self.on_focused)
def buildTextInput(callback, size_hint=None): widgetSizeHint = (1.0, 1.0) if size_hint == None else size_hint widget = TextInput(size_hint=widgetSizeHint) widget.bind(on_text_validate=callback) return widget
def build(self): self.uhd_fft = UhdFft(center_freq=796e6, bandwidth=10e6, gain=38) self.canvas = self.new_canvas() layout = BoxLayout(orientation='horizontal') layout.add_widget(self.canvas) settings = BoxLayout(orientation='vertical', size_hint_x=.3) settings.add_widget( Label(text='Time resolution', size_hint_y=None, height=30)) self.time_res_label = Label(text='NaN', size_hint_y=None, height=30) settings.add_widget(self.time_res_label) settings.add_widget( Label(text='Frequency resolution', size_hint_y=None, height=30)) self.freq_res_label = Label(text='NaN', size_hint_y=None, height=30) settings.add_widget(self.freq_res_label) self.update_resolutions() settings.add_widget( Label(text='Maximum Power', size_hint_y=None, height=30)) vmax_input = TextInput( text=str(self.uhd_fft.vmax), multiline=False, size_hint_y=None, height=30) vmax_input.bind(on_text_validate=self.on_vmax_enter) settings.add_widget(vmax_input) settings.add_widget( Label(text='Mimimum Power', size_hint_y=None, height=30)) vmin_input = TextInput( text=str(self.uhd_fft.vmin), multiline=False, size_hint_y=None, height=30) vmin_input.bind(on_text_validate=self.on_vmin_enter) settings.add_widget(vmin_input) settings.add_widget( Label(text='FFT Size', size_hint_y=None, height=30)) fft_size_input = TextInput( text=str(self.uhd_fft.fft_size), multiline=False, size_hint_y=None, height=30) fft_size_input.bind(on_text_validate=self.on_fft_size_enter) settings.add_widget(fft_size_input) settings.add_widget( Label(text='Frequency', size_hint_y=None, height=30)) cf_input = TextInput( text=str(self.uhd_fft.center_freq), multiline=False, size_hint_y=None, height=30) cf_input.bind(on_text_validate=self.on_cf_enter) settings.add_widget(cf_input) settings.add_widget( Label(text='Bandwidth', size_hint_y=None, height=30)) bw_input = TextInput(text=str(self.uhd_fft.bandwidth), multiline=False, size_hint_y=None, height=30) bw_input.bind(on_text_validate=self.on_bw_enter) settings.add_widget(bw_input) settings.add_widget(Label(text='Gain', size_hint_y=None, height=30)) gain_input = TextInput( text=str(self.uhd_fft.gain), multiline=False, size_hint_y=None, height=30) gain_input.bind(on_text_validate=self.on_gain_enter) settings.add_widget(gain_input) dropdown = DropDown() for antenna_name in self.uhd_fft.antennas: btn = Button(text=antenna_name, size_hint_y=None, height=30) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) antenna_dd_btn = Button(text='Antenna', size_hint_y=None, height=30) antenna_dd_btn.bind(on_release=dropdown.open) def dropdown_select(instance, val): setattr(antenna_dd_btn, 'text', val) self.uhd_fft.antenna_name = val self.request_fft() dropdown.bind(on_select=dropdown_select) settings.add_widget(antenna_dd_btn) btn_update = Button(text='Update', size_hint_y=None, height=30) btn_update.bind(on_press=self.on_btn_update) self.btn_run = Button(text='Run', size_hint_y=None, height=30) self.btn_run.bind(on_press=self.on_btn_run) settings.add_widget(btn_update) settings.add_widget(self.btn_run) layout.add_widget(settings) return layout
def build(self): self.random_word = getRandomWord() self.count_attempts = 0 self.count_corrects = 0 self.max_attempts = 6 b = BoxLayout(orientation='vertical') t = TextInput(text='', font_size=150, size_hint_y=None, height=200, multiline=False) f = FloatLayout() s = Scatter() l = Label(text='', font_size=70) l.color = (1, 0, 0, 1) b.add_widget(t) b.add_widget(l) b2 = BoxLayout(orientation='vertical') l2 = Label(text='What word?', font_size=100) b2.add_widget(l2) b.add_widget(b2) self.found_letters = [] for i in range(0, len(self.random_word)): self.found_letters.append('_') self.found_str = "".join(self.found_letters) l.text = self.found_str def callback(instance, value): self.random_word = getRandomWord() self.count_attempts = 0 self.count_corrects = 0 self.found_letters = [] for i in range(0, len(self.random_word)): self.found_letters.append('_') self.found_str = "".join(self.found_letters) l.text = self.found_str t.text = '' restart_button = Button(text='Restart?') restart_button.bind(state=callback) b.add_widget(restart_button) def on_text(instance, value): if (len(t.text) > 0): letter = t.text[-1] if letter not in self.random_word: self.count_attempts += 1 l2.text = str(self.count_attempts) else: for i in range(0, len(self.random_word)): if self.random_word[i] == letter: self.found_letters[i] = letter self.count_corrects += 1 self.found_str = "".join(self.found_letters) l.text = self.found_str if (self.count_corrects == len(self.random_word)): l.font_size = 20 l.text = f"Congratulation you won! The word is {self.random_word}" if (self.count_attempts == self.max_attempts): l2.font_size = 20 l2.text = f"Game Over the correct answer was {self.random_word}" t.bind(text=on_text) return b
class SaveAsPopup(Popup): def __init__(self, font_name, chisel): self.font_name = font_name self.chisel = chisel self.save_type = None self.choices = {"background": ".png " + _("(with background)"), "transparent": ".png " + _("(transparent)"), "project": PROJECT_EXTENSION, "all": _("All")} layout = BoxLayout(orientation="vertical", spacing=dp(34), padding=(dp(20), dp(15))) self.file_chooser = FileChooserListView(path=get_saves_path(), filters=[self._filter_file], size_hint=(1, 0.75)) sublayout = BoxLayout(orientation="horizontal", spacing=dp(10), size_hint=(1, 0.1)) self.text_input = TextInput(text="Untitled", multiline=False, font_name=font_name, font_size=sp(16), size_hint_x=0.6) self.save_type_btn = KivyButton(text=_("Select file type"), font_name=font_name, size_hint_x=0.4) sublayout.add_widget(self.text_input) sublayout.add_widget(self.save_type_btn) self.save_btn = Button(_("Please select a file type."), font_name=font_name, disabled=True, font_size=sp(16), size_hint=(1, 0.15)) self.file_chooser.bind(path=self._change_title, selection=self._set_text) self.text_input.bind(text=self._on_text_input, on_text_validate=self._save_file) self.save_type_btn.bind(on_release=self.open_save_type_popup) self.save_btn.bind(on_release=self._save_file) for widget in (self.file_chooser, sublayout, self.save_btn): layout.add_widget(widget) super().__init__("", font_name, layout, size_hint=(0.7, 0.9)) self._change_title() @staticmethod def _filter_file(folder, filename): return filename.endswith(PROJECT_EXTENSION) or filename.endswith(".png") def get_maybe_shortened_filename(self): filename = self.get_resolved_filename() if len(filename) > 24: filename, _, ext = filename.rpartition(".") if ext: return f"{filename[:6]}...{filename[-5:]}.{ext}" return f"{filename[:6]}...{filename[-5:]}" return filename def get_resolved_filename(self): filename = self.text_input.text ext = self._get_file_extension() if ext is None: return filename if not filename.endswith(ext): return filename + ext return filename def _change_title(self, *args): path = self.file_chooser.path self.title = _("Save to {path}").format(path=path) def _set_text(self, *args): selection = self.file_chooser.selection if selection: self.text_input.text = Path(selection[0]).name def _on_text_input(self, *args): text = self.text_input.text if len(text) > MAX_FILENAME_LENGTH: self.text_input.text = text[:MAX_FILENAME_LENGTH] if self.save_type: current_ext = self._get_file_extension() if current_ext == ".png" and self.text_input.text.endswith(PROJECT_EXTENSION): self._set_save_type(None, "project") elif current_ext == PROJECT_EXTENSION and self.text_input.text.endswith(".png"): self._set_save_type(None, "background") else: if self.text_input.text.endswith(PROJECT_EXTENSION): self._set_save_type(None, "project") elif self.text_input.text.endswith(".png"): self._set_save_type(None, "background") self._change_btn_name() def _change_btn_name(self, *args): if self.save_type is None: return filename = self.get_maybe_shortened_filename() self.save_btn.text = _('Save as "{filename}"').format(filename=filename) def _save_file(self, *args): if self.save_type is None: return try: self._do_saves() except OSError: open_error_popup(_("The file could not be saved due to an error " "raised by the operating system.\nCommon " "issue: Illegal characters in the file name."), self.font_name) self.dismiss() def open_save_type_popup(self, *args): popup = SelectionPopup(_("Select file type"), self.font_name, self.choices) popup.bind(choice=self._set_save_type) popup.open() def _set_save_type(self, instance, choice): self.save_type_btn.text = self.choices[choice] self.save_btn.disabled = False if self.save_type is not None: old_ext = self._get_file_extension() if old_ext and self.text_input.text.endswith(old_ext): self.text_input.text = self.text_input.text[:-len(old_ext)] self.save_type = choice new_ext = self._get_file_extension() if new_ext and not self.text_input.text.endswith(new_ext): self.text_input.text += new_ext self._change_btn_name() def _get_file_extension(self): extensions = {"background": ".png", "transparent": ".png", "project": PROJECT_EXTENSION, "all": None} return extensions[self.save_type] def _do_saves(self): filename = self.get_resolved_filename() path = Path(self.file_chooser.path) ext = self._get_file_extension() if ext is None: bg_path = path / (filename + ".png") trans_path = path / (filename + "_transparent.png") project_path = path / (filename + PROJECT_EXTENSION) else: bg_path = trans_path = project_path = path / filename def bg_func(): self.chisel.export_png(bg_path, transparent=False) def trans_func(): self.chisel.export_png(trans_path, transparent=True) def project_func(): self.chisel.save(project_path) def all_func(): bg_func() trans_func() project_func() functions = {"background": bg_func, "transparent": trans_func, "project": project_func, "all": all_func} functions[self.save_type]() def on_dismiss(self, *args): self.file_chooser.cancel()
class SevenTest(Test): """Last, Finally, thanks god, #nomoretabletapps, everything is app... appdate... i hate my life""" def __init__(self, screen, **kwargs): super(SevenTest, self).__init__(screen, **kwargs) self.desc = "Odečítání sedmiček" self.instruction = "Odečtěte od čísla 100 číslo 7 a pak pokračujte v odčítání 7." self.instruction_audio = "sounds/ins7.mp3" self.points = 0 self.pomoc1 = 0 self.pomoc2 = 0 self.pomoc3 = 0 self.pomoc4 = 0 self.pomoc5 = 0 self.test_field = GridLayout(cols=1, size_hint=(.2, .8), pos_hint={"x": .4}) self.prvni = TextInput(hint=u"první", font_size="60px", size_hint_y=.6) self.druhy = TextInput(hint=u"druhy", font_size="60px", size_hint_y=.6) self.treti = TextInput(hint=u"třetí", font_size="60px", size_hint_y=.6) self.ctvrty = TextInput(hint=u"čtvrtý", font_size="60px", size_hint_y=.6) self.paty = TextInput(hint=u"pátý", font_size="60px", size_hint_y=.6) self.number_list = ListView(item_strings=[]) self.prvni.bind(text=self.prvni_callback) self.druhy.bind(text=self.druhy_callback) self.treti.bind(text=self.treti_callback) self.ctvrty.bind(text=self.ctvrty_callback) self.paty.bind(text=self.paty_callback) with self.canvas.before: Color(0, 0, 0, 1) self.rec = Rectangle(size=Window.size) def prvni_callback(self, instance, text): if text == "93": self.pomoc1 = 1 else: self.pomoc1 = 0 self.calc() def druhy_callback(self, instance, text): if text == "86": self.pomoc2 = 1 else: self.pomoc2 = 0 self.calc() def treti_callback(self, instance, text): if text == "79": self.pomoc3 = 1 else: self.pomoc3 = 0 self.calc() def ctvrty_callback(self, instance, text): if text == "72": self.pomoc4 = 1 else: self.pomoc4 = 0 self.calc() def paty_callback(self, instance, text): if text == "65": self.pomoc5 = 1 else: self.pomoc5 = 0 self.calc() def calc(self): if self.pomoc1 + self.pomoc2 + self.pomoc3 + self.pomoc4 + self.pomoc5 == 1: self.points = 1 elif self.pomoc1 + self.pomoc2 + self.pomoc3 + self.pomoc4 + self.pomoc5 == 2 or self.pomoc1 + self.pomoc2 + self.pomoc3 + self.pomoc4 + self.pomoc5 == 3: self.points = 2 elif self.pomoc1 + self.pomoc2 + self.pomoc3 + self.pomoc4 + self.pomoc5 == 4 or self.pomoc1 + self.pomoc2 + self.pomoc3 + self.pomoc4 + self.pomoc5 == 5: self.points = 3 else: self.points = 0 def draw_uix(self): self.test_field.add_widget(utils.microgrid(False, self.prvni)) self.test_field.add_widget(utils.microgrid(False, self.druhy)) self.test_field.add_widget(utils.microgrid(False, self.treti)) self.test_field.add_widget(utils.microgrid(False, self.ctvrty)) self.test_field.add_widget(utils.microgrid(False, self.paty)) self.test_field.add_widget(self.number_list) self.add_widget(self.test_field) super(SevenTest, self).draw_uix() # nemyslim ze funguje def export_layout(self): return utils.microgrid(True, Label(text=self.desc), Label(text=str(self.points)))
class MainPage(BoxLayout): def __init__(self, **kwargs): super(MainPage, self).__init__(**kwargs) self.user_price = None self.orientation = 'vertical' self.current_coin = [''] self.graph_period = 1 self.alerts_log = [] self.output_content = [] self.alert_symbol_log = [] self.alerts_log_scroll = None self.new_alerts_scrollable_label = None self.new_alerts_scrollable_label = None self.coin_alerts_less_than = {} self.coin_alerts_more_than = {} self.alert_symbol = "" popup_message = "" self.popup_message = popup_message # later in dev the coin names will be read from API bitcoin_page_button = Button(text='Bitcoin') cardano_page_button = Button(text='Cardano') ethereum_page_button = Button(text='Ethereum') # add bind to coin functions to set currency to the particular coin, # this is then used in the graph function via Coin gecko function bitcoin_page_button.bind(on_release=self.bitcoin_alerts) cardano_page_button.bind(on_release=self.cardano_alerts) ethereum_page_button.bind(on_release=self.ethereum_alerts) self.add_widget(bitcoin_page_button) self.add_widget(cardano_page_button) self.add_widget(ethereum_page_button) # tickers to show on the plot self.tickers_on_plot = self.current_coin # red, yellow, purple, light blue, green | line colors for plot self.plot_colors = [[1, 1, 0, 1], [1, 0, 0, 1], [1, 0, 1, 1], [0.5, .75, .9, 1], [0, 1, 0.3, 1]] # class for particular coin pages - # allows user to set alerts and review price def coin_page(self): mainview = ModalView(size_hint=(0.75, 0.75)) grid = GridLayout( rows=2, cols=1, padding=[10, 15, 10, 30] # left, top, right, bottom ) # Area to contain price graphs located at the top half of the screen. graph_box = BoxLayout(orientation="vertical", size_hint_y=0.5, size_hint_x=.6) # Will contain the alerts below graph - once user sets them alarm_box = GridLayout(cols=2, size_hint_x=1, size_hint_y=.5) # First row of alerts box contains current price. self.current_price = coin_gecko.get_crypto_fiat_price( cryptoCurrency=self.current_coin) live_price_text = 'The current price is $' \ + str(self.current_price) live_price_label = Label(text="", size_hint_x=.5) dummy_label = Label(text=live_price_text, size_hint_x=.5) alarm_box.add_widget(live_price_label) alarm_box.add_widget(dummy_label) # Second row of alerts box contains alerts input box set_alarm_label = Label(text='Set Target Price: ', size_hint_x=0.5) self.alarm_textinput = TextInput(multiline=False, size_hint_x=0.5) # method actioned to check text input self.alarm_textinput.bind(text=self.on_text) alarm_box.add_widget(set_alarm_label) alarm_box.add_widget(self.alarm_textinput) # Third row of alerts box to contain buttons to set alerts alarm_button_less_than = Button(text="<", size_hint_x=1) alarm_button_more_than = Button(text=">", size_hint_x=1) alarm_box.add_widget(alarm_button_less_than) alarm_box.add_widget(alarm_button_more_than) # methods called on press of third row buttons, and then alerts added to log alarm_button_less_than.bind(on_release=self.alert_callback_less_than) alarm_button_more_than.bind(on_release=self.alert_callback_more_than) # Fourth row of alerts box will contain the alerts log. # self.scroll_label = ScrollableLabel(size_hint_x=1) #shown as self.history in sentdex tutorial # how to use self for input/label while not using self for old alerts # existing alerts scrollable_label = ScrollableLabel(size_hint_x=1) # existing alerts alarm_box.add_widget(scrollable_label) # new alerts self.new_alerts_scrollable_label = ScrollableLabel(size_hint_x=1) alarm_box.add_widget(self.new_alerts_scrollable_label) self.price_chart() # Fourth row of alerts box continued graph_tabs = TabbedPanel(pos_hint={'center_x': .5, 'center_y': 1}) graph_tabs.default_tab_text = '24hr' graph_tabs.default_tab.bind = self.one_day_chart() graph_tabs.default_tab_content = self.graph # graph title seven_days_tab = TabbedPanelHeader(text='7 days') seven_days_tab.bind = self.seven_day_chart() seven_days_tab.content = self.graph graph_tabs.add_widget(seven_days_tab) # make the actual plots graph_box.add_widget(graph_tabs) grid.add_widget(graph_box) grid.add_widget(alarm_box) # grid.add_widget(scrollable_label) mainview.add_widget(grid) mainview.open() parsedatabase.check_alerts(scrollable_label) def price_chart(self): self.plot_dates, self.plot_price = coin_gecko.get_market_chart( cryptoCurrency=self.current_coin, fiatCurrency='usd', chart_period=self.graph_period) self.graph = coin_gecko.make_plot( self.plot_price, self.plot_dates, self.tickers_on_plot, self.plot_colors, xlabel=self.current_coin.capitalize()) def one_day_chart(self): self.graph_period = 1 print(self.graph_period) self.price_chart() def seven_day_chart(self): self.graph_period = 7 print(self.graph_period) self.price_chart() def bitcoin_alerts(self, event): self.current_coin = 'bitcoin' self.coin_page() # parsedatabase.check_alerts() def cardano_alerts(self, event): self.current_coin = 'cardano' self.coin_page() def ethereum_alerts(self, event): self.current_coin = 'ethereum' self.coin_page() def alert_callback_less_than(self, event): self.alert_symbol = 'l' self.add_item() def alert_callback_more_than(self, event): self.alert_symbol = 'm' self.add_item() @staticmethod def alert_popup(popup_message): print('popup activated') # add popup when target criteria met - # perhaps change to email notification in the future content = GridLayout( cols=1, padding=10) # not being added after going to parsepage?? content.add_widget(Label(text=popup_message)) # content.add_widget(Label( # text='Price is ' + self.alert_symbol # + ' $' + str(self.user_price) # )) # popup = Popup( # title=self.current_coin.capitalize() # + ' Price Alert', # size_hint=(0.5, 0.3), content=content # ) popup = Popup(size_hint=(0.8, 0.3), content=content) popup.open() def add_item(self, *args): if self.alarm_textinput.text != "": price_target = self.alarm_textinput.text coin = self.current_coin symbol = self.alert_symbol db.add_alert(coin, symbol, price_target) # add other formatted constraints - only valid numbers etc # Get text and clear input box # alarm figure similar to message = self.new_message.text # in sentdex tutorial alarm_figure = self.alarm_textinput.text # clear text inputbox self.reset() self.new_alerts_scrollable_label.update_alert_history(alarm_figure) # need to send scrollable_label into method?? # scrollable_label.update_alert_history(alarm_figure) # was self.scroll_label self.output_content.append(alarm_figure) self.alert_symbol_log.append(self.alert_symbol) # scrollable_label.text += alarm_figure self.new_alerts_scrollable_label.text += alarm_figure print(self.output_content, self.alert_symbol_log) else: print("not working") def reset(self): self.alarm_textinput.text = "" def on_text(self, value, second_value): try: self.user_price = int(second_value) except: print(second_value) # just for debugging
class LSystemsEdit(Screen): def __init__(self, **kwargs): super(LSystemsEdit, self).__init__(**kwargs) self.name = "edit" self.main_layout = BoxLayout(orientation='horizontal') self.edit_layout = BoxLayout(orientation='vertical', size_hint_x=.4) #Text boxes self.name_input = TextInput(multiline=False, size_hint_y=None, height=sp(30)) self.name_input.bind(text=self.on_text) self.angle = TextInput(multiline=False, size_hint_y=None, height=sp(30)) self.angle.bind(text=self.on_text) self.axiom = TextInput(multiline=False, size_hint_y=None, height=sp(30)) self.axiom.bind(text=self.on_text) self.rules = TextInput(multiline=True, size_hint=(1, .4)) self.rules.bind(text=self.on_text) self.rule_chooser = GridLayout(cols=6, size_hint=(1, .2)) #buttons for changing number of iterations self.iterations_buttons = BoxLayout(orientation='horizontal', size_hint_y=None, height=sp(30)) self.minus = Button(text="-") self.iter_label = Label(text="1") self.plus = Button(text="+") self.minus.bind(on_press=self.iter_press) self.plus.bind(on_press=self.iter_press) self.iterations_buttons.add_widget(self.minus) self.iterations_buttons.add_widget(self.iter_label) self.iterations_buttons.add_widget(self.plus) self.image = LSystemImage() self.edit_layout.add_widget( Label(text="[b]Name[/b]", markup=True, size_hint_y=None, height=sp(30))) self.edit_layout.add_widget(self.name_input) self.edit_layout.add_widget( Label(text="[b]Angle[/b]", markup=True, size_hint_y=None, height=sp(30))) self.edit_layout.add_widget(self.angle) self.edit_layout.add_widget( Label(text="[b]Axiom[/b]", markup=True, size_hint_y=None, height=sp(30))) self.edit_layout.add_widget(self.axiom) self.edit_layout.add_widget( Label(text="[b]Rules[/b]", markup=True, size_hint_y=None, height=sp(30))) self.edit_layout.add_widget(self.rules) self.edit_layout.add_widget( (Label(text="[b]Choose rule to visualise[/b]", markup=True, size_hint_y=None, height=sp(30)))) self.edit_layout.add_widget(self.rule_chooser) self.edit_layout.add_widget( (Label(text="[b]Change number of iterations[/b]", markup=True, size_hint_y=None, height=sp(30)))) self.edit_layout.add_widget(self.iterations_buttons) self.edit_layout.add_widget((Label(text="[b]L-systems syntax[/b]", markup=True, size_hint_y=None, height=sp(30)))) syntax_label = ScrollableLabel() syntax_label.text = syntax # def f(*args,**kwargs): syntax_label.text_size = syntax_label.size # syntax_label.bind(size = f) self.edit_layout.add_widget(syntax_label) self.main_layout.add_widget(self.edit_layout) self.main_layout.add_widget(self.image) #self.load_lsystem(('quartet', ('fb', {'a': 'fbfa+hfa+fb-fa', 'h': '-', 'b': 'fb+fa-fb-jfbfa', 'j': '+', 'f': ''}, 90.0))) self.add_widget(self.main_layout) def iter_press(self, instance, *args): if instance.text == "+": iteration = int(self.iter_label.text) + 1 else: iteration = int(self.iter_label.text) - 1 if iteration < 0: iteration = 0 self.image.set_iterations(iteration) self.iter_label.text = str(iteration) def set_rule_chooser(self): if self.lsystem: name, (axiom, rules, angle) = self.lsystem else: rules = {} self.rule_chooser.clear_widgets() for name in ["axiom"] + sorted(rules.keys()): btn = ToggleButton(text=name, group='rules', size_hint_y=None, height=sp(30)) if name == 'axiom': btn.state = 'down' btn.bind(on_press=self.on_rule_choose) self.rule_chooser.add_widget(btn) def on_rule_choose(self, instance, *args): if self.lsystem: name, (axiom, rules, angle) = self.lsystem new_axiom = instance.text if instance.text != "axiom" else axiom self.image.set_lsystem((new_axiom, rules, angle)) def on_text(self, instance, *args): self.get_lsystem() if self.lsystem: self.image.set_lsystem(self.lsystem[1]) #self.image.set_iterations(1) self.set_rule_chooser() def load_lsystem(self, lsystem): name, (axiom, rules, angle) = lsystem self.name_input.text = name self.axiom.text = axiom self.angle.text = str(angle) self.rules.text = '\n'.join( ["%s=%s" % (k, v) for (k, v) in sorted(rules.items())]) def get_lsystem(self): name = self.name_input.text axiom = self.axiom.text.replace(" ", "") angle = '' try: angle = float(self.angle.text) except: angle = 0 try: rules = dict([ x.split("=") for x in self.rules.text.replace(" ", "").split("\n") if x ]) except: rules = {} self.lsystem = name, (axiom, rules, angle)