def test_list_view_with_list_of_integers_scrolling(self): data = [{'text': str(i), 'is_selected': False} for i in xrange(100)] args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': 25} list_adapter = ListAdapter(data=data, args_converter=args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) list_view = ListView(adapter=list_adapter) list_view.scroll_to(20) self.assertEqual(list_view._index, 20)
def __init__(self, **kwargs): self.data = list() for x in range(0, len(Active.cl.c_list)): self.data.append({ 'hostname': Active.cl.c_list[x].name, 'ip': Active.cl.c_list[x].ip }) self.list_adapter = ListAdapter(data=self.data, args_converter=self.formatter, cls=ClCompositeListItem, selection_mode='single', allow_empty_selection=False) super(ListViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(self.list_view) if len(self.data) is 0: detail_view = ClientDetailView(cl_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = ClientDetailView(cl_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind( on_selection_change=detail_view.cl_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 5)
def __init__(self): super(Widg, self).__init__(orientation='vertical', spacing=20) self.s = "" self.txt = TextInput(multiline=False, font_size=24) self.bsel = Button(text='select files', font_size=24, background_color=[0.8, 0.2, 0.1, 1]) self.bfrq = Button(text='compute frequency', font_size=24, background_color=[0.2, 0.8, 0.1, 1]) self.lsel = ListView(item_strings=[""]) self.lles = ListView(item_strings=[""]) self.lmos = ListView(item_strings=[""]) self.f = FileChooserListView(path=path, filters=['*.txt'], multiselect=True) self.bsel.bind(on_release=self.on_files) self.bfrq.bind(on_release=self.on_conv) self.bb = BoxLayout(size_hint=(1, 0.2)) self.ff = BoxLayout() self.lm = BoxLayout(size_hint=(1, 0.6)) self.ff.add_widget(self.f) self.ff.add_widget(self.lsel) self.bb.add_widget(self.bsel) self.bb.add_widget(self.bfrq) self.lm.add_widget(self.lles) self.lm.add_widget(self.lmos) self.add_widget(self.lm) self.add_widget(self.bb) self.add_widget(self.ff)
def test_dict_adapter_selection_cascade(self): # Categories of fruits: # categories = sorted(fruit_categories.keys()) categories_dict_adapter = \ DictAdapter(sorted_keys=categories, data=fruit_categories, args_converter=self.args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) fruit_categories_list_view = \ ListView(adapter=categories_dict_adapter, size_hint=(.2, 1.0)) # Fruits, for a given category, are shown based on the fruit category # selected in the first categories list above. The selected item in # the first list is used as the key into a dict of lists of list # items to reset the data in FruitsDictAdapter's # fruit_category_changed() method. # # data is initially set to the first list of list items. # fruits_dict_adapter = \ FruitsDictAdapter( sorted_keys=fruit_categories[categories[0]]['fruits'], data=fruit_data, args_converter=self.args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) categories_dict_adapter.bind( on_selection_change=fruits_dict_adapter.fruit_category_changed) fruits_list_view = ListView(adapter=fruits_dict_adapter, size_hint=(.2, 1.0)) # List views should have adapters set. self.assertEqual(fruit_categories_list_view.adapter, categories_dict_adapter) self.assertEqual(fruits_list_view.adapter, fruits_dict_adapter) # Each list adapter has allow_empty_selection=False, so each should # have one selected item. self.assertEqual(len(categories_dict_adapter.selection), 1) self.assertEqual(len(fruits_dict_adapter.selection), 1) # The selected list items should show is_selected True. self.assertEqual(categories_dict_adapter.selection[0].is_selected, True) self.assertEqual(fruits_dict_adapter.selection[0].is_selected, True) # And they should be red, for background_color. self.assertEqual(categories_dict_adapter.selection[0].background_color, [1.0, 0., 0., 1.0]) self.assertEqual(fruits_dict_adapter.selection[0].background_color, [1.0, 0., 0., 1.0])
def init(self, simulate=False, time_interval=1, **kwargs): """ Initializes Datamodel """ self.minval = kwargs.get("minval", self.minval) self.maxval = kwargs.get("maxval", self.maxval) self.blockname = kwargs.get("blockname", self.blockname) self.clear_widgets() self.simulate = simulate self.time_interval = time_interval dict_adapter = DictAdapter(data={}, args_converter=self.arg_converter, selection_mode='single', allow_empty_selection=True, cls=CompositeListItem ) # Use the adapter in our ListView: self.list_view = ListView(adapter=dict_adapter) self.add_widget(self.list_view) self.dispatcher = UpdateEventDispatcher() self._parent = kwargs.get('_parent', None) self.simulate_timer = BackgroundJob( "simulation", self.time_interval, self._simulate_block_values )
def build(self): # screen manager steup sm = ScreenManager() # main menu setup main_menu = # define Spell screen spell_layout = BoxLayout() # add big_layout to ScreenManger sm.add_widget(spell_layout) left_box = BoxLayout(orientation='vertical', spacing=10, size_hint=(.3, 1)) right_box = StackLayout(size_hint=(.7, 1)) left_top_box = ListView(size_hint=(1, .8)) left_bottom_box = BoxLayout(size_hint=(1, .2)) rb = Label(text='right box') ltb = Label(text='left top box') btn_rest = Button(text='Rest') btn_main = Button(text='Main Menu') btn_quit = Button(text='Quit') spell_layout.add_widget(left_box) spell_layout.add_widget(right_box) left_box.add_widget(left_top_box) left_box.add_widget(left_bottom_box) right_box.add_widget(rb) left_top_box.add_widget(ltb) left_bottom_box.add_widget(btn_rest) left_bottom_box.add_widget(btn_main) left_bottom_box.add_widget(btn_quit) return sm
def __init__(self, *args, **kwargs): super(LoadScreen, self).__init__(*args, **kwargs) list_item_args_converter = lambda row_index, obj: { 'root_path': obj.root_path, 'item_id': obj.item_id, 'text': obj.text, 'pdbFile': obj.pdbFile, 'remove_item': obj.remove_item, 'zoom_item': obj.zoom_item, 'list_id': obj.list_id } self.list_adapter_receptor = LoadAdapter( data=[], args_converter=list_item_args_converter, template='LoadListItem') pdb_list_1 = ListView(adapter=self.list_adapter_receptor, divider_height=1, id='pdb_list_1') self.boxlist_1.add_widget(pdb_list_1) self.list_adapter_ligand = LoadAdapter( data=[], args_converter=list_item_args_converter, template='LoadListItem') pdb_list_2 = ListView(adapter=self.list_adapter_ligand, divider_height=1, id='pdb_list_2') self.boxlist_2.add_widget(pdb_list_2)
def listaCaes(self, a): box = GridLayout(cols=1, rows=5, spacing=[0, 10]) nao_adotados = self.dados.getDoguinhosNaoAdotados() adotados = self.dados.getDoguinhosAdotados() box.add_widget(Label(text='Cães Não Adotados', size_hint_y=0.15)) dados_nao_adotados = [] for dog in nao_adotados: dog_infos = dog.getInfos() dados_nao_adotados.append("ID: {0} Nome: {1}".format( dog_infos[0], dog_infos[1])) dados_nao_adotados.append("Raça: {0} Sexo: {1}".format( dog_infos[2], dog_infos[3])) dados_nao_adotados.append("Porte: {0} Idade: {1}".format( dog_infos[4], dog_infos[5])) if dog_infos[6] == "1": stat = "Apto para adoção." else: stat = "Inapto para adoção." dados_nao_adotados.append("Status: {0}".format(stat)) dados_nao_adotados.append("{0}".format(dog_infos[7])) dados_nao_adotados.append('') dados_nao_adotados.append('') simple_list_adapter = SimpleListAdapter(data=dados_nao_adotados, cls=Label) list_view1 = ListView(adapter=simple_list_adapter) box.add_widget(list_view1) box.add_widget(Label(text='Cães Adotados', size_hint_y=0.15)) dados_adotados = [] for dog in adotados: dog_infos = dog.getInfos() dados_adotados.append("ID: {0} Nome: {1}".format( dog_infos[0], dog_infos[1])) dados_adotados.append("Raça: {0} Sexo: {1}".format( dog_infos[2], dog_infos[3])) dados_adotados.append("Porte: {0} Idade: {1}".format( dog_infos[4], dog_infos[5])) dados_adotados.append("{0}".format(dog_infos[7])) dados_adotados.append('') dados_adotados.append('') simple_list_adapter2 = SimpleListAdapter(data=dados_adotados, cls=Label) list_view2 = ListView(adapter=simple_list_adapter2) box.add_widget(list_view2) fechar_botao = Button(text='Fechar', size_hint_y=0.2) box.add_widget(fechar_botao) self.popupListaCaes = Popup(title='Lista de Cães', content=box, size_hint=(None, None), size=(600, 600)) fechar_botao.bind(on_press=self.popupListaCaes.dismiss) self.popupListaCaes.open()
def __init__(self, **kwargs): super(MainLayout, self).__init__(**kwargs) self.args_converter = lambda row_index, rec: \ {'size_hint_y': None, 'height': 30, 'spacing':8, 'is_selected':False, 'cls_dicts': [{'cls':ListItemLabel, 'kwargs': {'text': rec['firstname'],'size_hint_x': .2,'size_hint_y': None,'height': 25, 'font_size': '12sp'}}, {'cls': ListItemLabel, 'kwargs': {'text': rec['lastname'],'size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp'}}, {'cls': ListItemLabel, 'kwargs': {'text': rec['role'],'size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp'}}, {'cls': MyListItemButton, 'kwargs': {'text': u'edit','size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp', 'disabled': False, 'on_press':self.find_user}}, {'cls': MyListItemButton, 'kwargs': {'text': u'delete','size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp','disabled': False, 'on_press':self.delete_user}}, ]} self.list_adapter = ListAdapter(data=[], args_converter=self.args_converter, selection_mode='none', allow_empty_selection=True, cls=CompositeListItem) list_view = ListView(adapter=self.list_adapter) self.lv_users_box.add_widget(list_view) self.args_converter_order = lambda row_index, rec: \ {'size_hint_y': None, 'height': 30, 'spacing':8, 'is_selected':False, 'cls_dicts': [{'cls':ListItemLabel, 'kwargs': {'text': str(row_index+1),'size_hint_x': .2,'size_hint_y': None,'height': 25, 'font_size': '12sp'}}, {'cls': ListItemLabel, 'kwargs': {'text': rec['table'],'size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp'}}, {'cls': ListItemLabel, 'kwargs': {'text': rec['status'],'size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp'}}, {'cls': ListItemLabel, 'kwargs': {'text': str(rec['total']),'size_hint_x': .2,'size_hint_y': None,'height': 25,'font_size': '12sp'}}, ]} self.order_adapter = ListAdapter( data=[], args_converter=self.args_converter_order, selection_mode='none', allow_empty_selection=True, cls=CompositeListItem) self.list_view_order = ListView(adapter=self.order_adapter) self.lv_orders_box.add_widget(self.list_view_order) self.choice_role_user() #dropdown
def __init__(self, **kwargs): kwargs['cols'] = 3 super(CascadingView, self).__init__(**kwargs) list_item_args_converter = \ lambda row_index, rec: {'text': rec['name'], 'size_hint_y': None, 'height': 25} # Fruit categories list on the left: # categories = sorted(fruit_categories.keys()) fruit_categories_list_adapter = \ DictAdapter( sorted_keys=categories, data=fruit_categories, args_converter=list_item_args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) fruit_categories_list_view = \ ListView(adapter=fruit_categories_list_adapter, size_hint=(.2, 1.0)) self.add_widget(fruit_categories_list_view) # Fruits, for a given category, in the middle: # image_list_item_args_converter = \ lambda row_index, rec: {'text': rec['name'], 'size_hint_y': None, 'height': 32} fruits_list_adapter = \ FruitsDictAdapter( sorted_keys=fruit_categories[categories[0]]['fruits'], data=fruit_data, args_converter=image_list_item_args_converter, selection_mode='single', allow_empty_selection=False, template='ThumbnailedListItem') fruits_list_view = \ ListView(adapter=fruits_list_adapter, size_hint=(.2, 1.0)) fruit_categories_list_adapter.bind( on_selection_change=fruits_list_adapter.fruit_category_changed) self.add_widget(fruits_list_view) # Detail view, for a given fruit, on the right: # detail_view = FruitImageDetailView( fruit_name=fruits_list_adapter.selection[0].fruit_name, size_hint=(.6, 1.0)) fruits_list_adapter.bind( on_selection_change=detail_view.fruit_changed) self.add_widget(detail_view)
def enter_state(self, context=None): print 'ShowingListsScreen/enter_state' if not 'Lists' in self.statechart.app.sm.screen_names: # Convenience references: self.app = self.statechart.app view = BoxLayout(orientation='vertical', spacing=10) toolbar = BoxLayout(size_hint=(1.0, None), height=50) label = Label(text='Lists', color=[.8, .8, .8, .8], bold=True) toolbar.add_widget(label) button = Button(text='Search') button.bind(on_press=self.go_to_search) toolbar.add_widget(button) 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) lists_view = GridLayout(cols=3, size_hint=(1.0, 1.0)) lists_view.add_widget( ListView(adapter=self.statechart.fruit_categories_dict_adapter, size_hint=(.2, 1.0))) lists_view.add_widget( ListView(adapter=self.statechart.fruits_dict_adapter, size_hint=(.2, 1.0))) selected_fruit = \ self.statechart.fruits_dict_adapter.selection[0].text self.detail_view = FruitDetailView(fruit_name=selected_fruit, size_hint=(.6, 1.0)) lists_view.add_widget(self.detail_view) view.add_widget(lists_view) self.create_adapter_bindings() screen = Screen(name='Lists') screen.add_widget(view) self.app.sm.add_widget(screen) if self.app.sm.current != 'Lists': self.app.sm.current = 'Lists'
def __init__(self, **kwargs): self.qrdata = list() # FOR NETWORK Active.qrList.clear() try: Active.qrList = Active.qr_task.get_qr_list(Active.client) except QrException as qr: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=qr.value)) popup.bind(on_press=popup.dismiss) popup.title = qr.title popup.open() except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() for x in range(0, len(Active.qrList)): self.qrdata.append({ 'filename': Active.qrList[x].f_name, 'old_path': Active.qrList[x].o_path }) self.list_adapter = ListAdapter(data=self.qrdata, args_converter=self.formatter, selection_mode='single', allow_empty_selection=False, cls=QrCompositeListItem) super(QuarantineViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(self.list_view) if len(self.qrdata) is 0: detail_view = QrDetailView(qr_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = QrDetailView( qr_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind(on_selection_change=detail_view.qr_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 60) Clock.schedule_interval(self.callback2, 5)
def connect_popup(self): popup = Popup(title='Connecter deux sommets', size_hint=(0.9, 0.9), auto_dismiss=False) bl = BoxLayout(orientation='vertical') confirm_button = Button(text="Confirmer") confirm_button.disabled = True gl_inputs = GridLayout(cols=2) gl_inputs.add_widget(Label(text="Sommet 1")) gl_inputs.add_widget(Label(text="Sommet 2")) list_adapter1 = ListAdapter(data=[ str(i + 1) + "- " + self.g.get_sommets()[i].nom for i in range(len(self.g.get_sommets())) ], cls=ListItemButton, sorted_keys=[]) list_adapter1.bind(on_selection_change=lambda a: self.selection_change( list_adapter1, 0, list_adapter2, confirm_button)) list_view1 = ListView(adapter=list_adapter1) gl_inputs.add_widget(list_view1) list_adapter2 = ListAdapter(data=[ str(i + 1) + "- " + self.g.get_sommets()[i].nom for i in range(len(self.g.get_sommets())) ], cls=ListItemButton, sorted_keys=[]) list_adapter2.bind(on_selection_change=lambda a: self.selection_change( list_adapter2, 1, list_adapter1, confirm_button)) list_view2 = ListView(adapter=list_adapter2) gl_inputs.add_widget(list_view2) bl.add_widget(gl_inputs) confirm_button.bind(on_press=lambda a: self.connect(popup)) cancel_button = Button(text="Annuler") cancel_button.bind(on_press=lambda a: popup.dismiss()) bl.add_widget(confirm_button) bl.add_widget(cancel_button) popup.content = bl popup.open()
def listaTut(self, a): box = GridLayout(cols=1, rows=3) box.add_widget(Label(text='Lista de Tutores', size_hint_y=0.15)) tutores = self.dados.getTutores() dados = [] for tut in tutores: tutInfos = tut.getInfos() dados.append("ID: {0} Nome: {1} CPF: {2}".format( tutInfos[0], tutInfos[1], tutInfos[3])) telefone = tutInfos[4] telefone = telefone[:-4] + "-" + telefone[-4:] dados.append("Endereço: {0} Telefone: {1}".format( tutInfos[2], telefone)) dados.append('') dados.append('') simple_list_adapter = SimpleListAdapter(data=dados, cls=Label) list_view1 = ListView(adapter=simple_list_adapter) box.add_widget(list_view1) botao = Button(text='Fechar', size_hint_y=0.2) box.add_widget(botao) self.popupListaTutores = Popup(title='Lista de Tutores', content=box, size_hint=(None, None), size=(600, 600)) botao.bind(on_press=self.popupListaTutores.dismiss) self.popupListaTutores.open()
def start_app(self): labels = [LabelModel() for _ in range(100)] self.image = Factory.MainImage(ImageModel()) self.root.ids.image_box.add_widget(self.image) self.exif = Factory.GetExifData(ButtonModel(image=self.image, labels=labels)) self.root.ids.button_box.add_widget(self.exif) right = Factory.RotateRight(self.exif.model) self.root.ids.button_box.add_widget(right) left = Factory.RotateLeft(self.exif.model) self.root.ids.button_box.add_widget(left) loc = Factory.GetLocation(self.exif.model) self.root.ids.button_box.add_widget(loc) next = Factory.NextImage(self.exif.model) self.root.ids.cycle_box.add_widget(next) prev = Factory.PreviousImage(self.exif.model) self.root.ids.cycle_box.add_widget(prev) get = Factory.OpenImage(self.exif.model) self.root.ids.button_box.add_widget(get) lab = Factory.ExifLabel(LabelModel()) self.root.ids.exif_container.add_widget(lab) list_adapter = SimpleListAdapter( data=labels, args_converter=lambda row, model: {'model': model, 'size_hint_y': None, 'height':100}, cls=Factory.ExifTags) self.root.ids.exif_container.add_widget(ListView(adapter=list_adapter))
def lookup_item(self, item): if not item or not item.get('uri'): return uri = item['uri'] logger.debug('Browsing on URI: %s', uri) info = self.mopidy.library.browse(uri=uri, timeout=40) info_tracks = format_nice(info, format='browse').split('\n') title = '[%s] %s (%d items)' % (item['type'], item['name'], len(info_tracks)) lv = ListView(item_strings=info_tracks, halign='left') btn = Button(text='Close', size_hint_y=None, height=50) cnt = BoxLayout(orientation='vertical') cnt.add_widget(lv) cnt.add_widget(btn) popup = Popup(title=title, content=cnt, size_hint=(0.8, 0.8), title_size=22,) btn.bind(on_press=popup.dismiss) popup.open()
def listaAdoc(self, a): box = GridLayout(cols=1, rows=3) box.add_widget(Label(text='Lista de Adoções', size_hint_y=0.15)) adocoes = self.dados.getAdocoes() dados = [] for ad in adocoes: adInfos = ad.getInfos() for dog in self.dados.doguinhos: if dog.getId() == adInfos[0]: nome = dog.getNome() for tutor in self.dados.tutores: if tutor.getId() == adInfos[1]: nome_tutor = tutor.getNome() dados.append("ID do cão: {0} Nome do cão: {1}".format( adInfos[0], nome)) dados.append("ID do tutor: {0} Nome do tutor: {1}".format( adInfos[1], nome_tutor)) dados.append("Data de adoção: {0}".format(adInfos[2])) dados.append('') dados.append('') simple_list_adapter = SimpleListAdapter(data=dados, cls=Label) list_view1 = ListView(adapter=simple_list_adapter) box.add_widget(list_view1) botao = Button(text='Fechar', size_hint_y=0.2) box.add_widget(botao) self.popupListaAdoc = Popup(title='Lista de Adoções', content=box, size_hint=(None, None), size=(600, 600)) botao.bind(on_press=self.popupListaAdoc.dismiss) self.popupListaAdoc.open()
def __init__(self, items, **kwargs): kwargs['cols'] = 2 kwargs['size_hint'] = (1.0, 1.0) super(MasterDetailView, self).__init__(**kwargs) list_item_args_converter = \ lambda row_index, rec: {'text': rec['name'], 'size_hint_y': None, 'height': 25} dict_adapter = DictAdapter(sorted_keys=sorted(fruit_data.keys()), data=fruit_data, args_converter=list_item_args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) master_list_view = ListView(adapter=dict_adapter, size_hint=(.3, 1.0)) self.add_widget(master_list_view) detail_view = FruitDetailView( fruit_name=dict_adapter.selection[0].text, size_hint=(.7, 1.0)) dict_adapter.bind(on_selection_change=detail_view.fruit_changed) self.add_widget(detail_view)
def __init__(self, **kwargs): def items_args_converter(row_index, rec): return { 'text': rec.name, 'value': str(rec.value), 'unit': rec.unit, 'size_hint_y': None, 'height': 20, 'cls_dicts': [{ 'cls': ListItemButton, 'kwargs': { 'text': rec.name, 'size_hint_x': 0.6, 'is_representing_cls': True}}, {'cls': ListItemLabel, 'kwargs': {'text': str(rec.value)[:6], 'size_hint_x': 0.3}}, {'cls': ListItemLabel, 'kwargs': {'text': rec.unit, 'size_hint_x': 0.1}}]} self.list_adapter = ListAdapter( data={}, args_converter=items_args_converter, selection_mode='single', allow_empty_selection=True, propagate_selection_to_data=True, cls=CompositeListItem) self.list_adapter.bind(on_selection_change=self.reg_selection_changed) super(RegDictView, self).__init__(**kwargs) self.add_widget(ListView(adapter=self.list_adapter)) self.slider_view = RegSliderView(reg_index=0, list_adapter=self.list_adapter) self.add_widget(self.slider_view)
def videoArchiveBtnCallback(self): setDisplaySleepTime(9999,1) data = getVideoList() listData = [] for d in data: listData.append(d.id + " " + d.time.strftime('%d. %b - %H:%M:%S')) list_adapter = ListAdapter(data=listData, cls=VideoListItemButton, selection_mode='single', allow_empty_selection=False) player = VideoPlayer(source=data[0].path, state='play', options={'allow_stretch': True}) root = GridLayout(cols=2) popup = Popup(title='Video archív - '+data[0].time.strftime('%d. %b - %H:%M:%S'), content=root, size_hint=(1, 1)) list_adapter.bind(on_selection_change=partial(videoArchiveItemSelected,player, popup)) layout1 = BoxLayout(orientation='vertical') layout2 = BoxLayout(orientation='vertical') videoList = ListView(adapter=list_adapter) btn = Button(text='Zatvoriť', size_hint_y=0.2) layout1.add_widget(videoList) layout2.add_widget(player) layout2.add_widget(btn) root.add_widget(layout1) root.add_widget(layout2) btn.bind(on_press=partial(videoArchiveExitBtnCallback,popup)) popup.open()
def __init__(self, **kwargs): super(PlayersList, self).__init__(**kwargs) player_args_coverter = lambda row_index, nick: { "nick": nick, "size_hint_y": None, "height": "30dp", "pos_hint_y": 0.9 } list_adapter = ListAdapter(data=["Ginaria", "Celestia"], args_converter=player_args_coverter, selection_mode='single', allow_empty_selection=True, cls=PlayersListItem) list_view = ListView(adapter=list_adapter, size_hint=(1.0, 1.0), pos_hint={'center_x': 0.5}) def data_changed(instance, value): list_adapter.data = value self.bind(items=data_changed) self.add_widget(list_view)
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 __init__(self, *args, **kwargs): super(EditProducts, self).__init__(*args, **kwargs) args_converter_edit = lambda row_index, rec: \ {'size_hint_y': None, 'height': 30, 'spacing':8, 'is_selected':True, 'text':rec['text'], 'active':rec['active'], 'cls_dicts': [{'cls':ListItemLabel, 'kwargs': {'text':rec['text'], 'color': [0,0,0, 0.95], 'size_hint_x': .2,'size_hint_y': None,'height': 25, 'font_size': '12sp'}}, {'cls':MyCheckBox, 'kwargs': {'active':rec['active'], 'size_hint_x': .2,'size_hint_y': None,'height': 25, 'font_size': '12sp', 'on_press': self.on_active}} ]} self.choices_adapter = ListAdapter( data=[], #edit_adapter args_converter=args_converter_edit, selection_mode='none', allow_empty_selection=True, cls=CompositeListItem) self.list_view_choices = ListView(adapter=self.choices_adapter) self.choices_oprop.add_widget(self.list_view_choices)
def build(self): args_converter = lambda row_index, rec: \ {'text': rec['text'], 'size_hint_y': None, 'height': 25, 'cls_dicts': [{'cls': ListItemButton, 'kwargs': {'text': rec['text']}}, {'cls': ListItemLabel, 'kwargs': {'text': "Middle-{0}".format(rec['text']), 'is_representing_cls': True}}, {'cls': ListItemButton, 'kwargs': {'text': rec['text']}}]} item_strings = ["{0}".format(index) for index in range(100)] integers_dict = \ {str(i): {'text': str(i), 'is_selected': False} for i in range(100)} dict_adapter = DictAdapter(sorted_keys=item_strings, data=integers_dict, args_converter=args_converter, selection_mode='single', allow_empty_selection=False, cls=CompositeListItem) list_view = ListView(adapter=dict_adapter) return list_view
def test_list_adapter_selection_mode_single(self): list_adapter = ListAdapter(data=fruit_data_items, args_converter=self.args_converter, selection_mode='single', propagate_selection_to_data=True, allow_empty_selection=True, cls=ListItemButton) list_view = ListView(adapter=list_adapter) # The reason why len(selection) == 0 here is because ListView, # at the end of its __init__(), calls check_for_empty_selection() # and does NOT trigger the initial selection, because we set # allow_empty_selection = True. self.assertEqual(len(list_adapter.selection), 0) list_adapter.check_for_empty_selection() # Nothing should have changed by that call, because still we have # allow_empty_selection = True, so no action in that check. self.assertEqual(len(list_adapter.selection), 0) # Still no selection, but triggering a selection should make len = 1. # So, first we need to select the associated data item. self.assertEqual(fruit_data_items[0].name, 'Apple') fruit_data_items[0].is_selected = True apple = list_view.adapter.get_view(0) self.assertEqual(apple.text, 'Apple') self.assertTrue(apple.is_selected) self.assertEqual(len(list_adapter.selection), 1)
class DeleteProfileScreen(Screen): user_dict = {} userKey = ListProperty() users_list = ListView() sel_usr = StringProperty() def __init__(self, **kwargs): super(DeleteProfileScreen, self).__init__(**kwargs) self.sel_usr = '******' def on_enter(self, *args): print('on_enter called for delete profile screen') del self.userKey[:] self.user_dict.clear() self.userKey = fn.reload_dictionary(self.user_dict) if self.userKey != None: list_adapter = ListAdapter(data=self.userKey, selection_mode='single', allow_empty_selection=False, cls=myListItemButton) self.sel_usr = self.userKey[0] self.users_list.adapter = list_adapter self.users_list.adapter.bind(on_selection_change=self.callback) self.users_list._trigger_reset_populate() def callback(self, adapter): if len(adapter.selection) == 0: self.sel_usr = '******' print "No selected item" else: print adapter.selection[0].text self.sel_usr = adapter.selection[0].text
def init_selector(self, _height): """ Initializer the selector :param _height: Height of the selector :return: An instance of the selector """ _list_adapter = ListAdapter(data=self.get_values_hosts(), args_converter=list_item_args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) _selector = ListView(adapter=_list_adapter) _selector.height = _height _selector.adapter.bind(on_selection_change= self.set_selector_text) return _selector
def __init__(self, **kwargs): super(MainView, self).__init__(**kwargs) data_items = [] data_items.append(DataItem()) data_items.append(DataItem()) data_items.append(DataItem()) list_item_args_converter = lambda row_index, obj: { 'text': obj.name, 'size_hint_y': None, 'height': 25 } self.list_adapter = \ ListAdapter(data=data_items, args_converter=list_item_args_converter, selection_mode='single', propagate_selection_to_data=False, allow_empty_selection=False, cls=ListItemButton) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(self.list_view) self.toggle = 'adding' Clock.schedule_interval(self.update_list_data, 1)
def view_student(self): self.update_info() if self.grade12s_list.adapter.selection: # getting selected item name selection = self.grade12s_list.adapter.selection[0].text # creating layout for tab content = GridLayout(cols=2) col1 = GridLayout(cols=1) col2 = GridLayout(cols=1) col1.add_widget(Label(text="Student Name: " + selection)) for i in self.grade12_list: if i[1] == selection: col1.add_widget(Label(text="Grade: " + i[2])) col1.add_widget(Label(text="Student ID: " + str(i[4]))) col1.add_widget( Label(text="Accumulated Points: " + str(i[3]))) simple_list_adapter = SimpleListAdapter( data=i[6].split('.')[1:], cls=Label) col2.add_widget( Label(text='Student Rewards History', size_hint_y=None, height=40)) activity_history = ListView(adapter=simple_list_adapter) col2.add_widget(activity_history) content.add_widget(col1) content.add_widget(col2) popup = Popup(title=selection, content=content, size_hint=(None, None), size=(800, 500)) popup.open()
def __init__(self, **kwargs): kwargs['cols'] = 2 super(MainView, self).__init__(**kwargs) list_view = ListView(item_strings=[str(index) for index in range(100)]) self.add_widget(list_view)
def __init__(self, *, choices, default): self._selection_callbacks = [] class _ListAdapter(ListAdapter): selected = StringProperty('') def on_selection(_self, item, value): if value: _self.selected = value[0].text for callback in self._selection_callbacks: callback() def select(self, choice): v = self.get_view(self.data.index(choice)) if v is not None: self.handle_selection(v) self._adapter = _ListAdapter( data=choices, args_converter=_args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False, ) self._element = ListView(adapter=self._adapter) self._adapter.select(default)
def __init__(self, **kwargs): super(MapChoice, self).__init__(**kwargs) self.root = Builder.load_string(kv) self.map_items = kwargs.get('map_items', []) list_item_args_converter = \ lambda row_index, selectable: {'name': selectable.name, 'max_zoom': selectable.max_zoom, 'description': selectable.description, 'size_hint_y': None, 'is_selected': selectable.is_selected, 'select_change_callback': selectable.on_selection_change, 'calibration_callback': selectable.on_calibration, 'index': row_index} map_list_adapter = \ ListAdapter(data=self.map_items, args_converter=list_item_args_converter, selection_mode='single', allow_empty_selection=False, template='CustomListItem') list_view = ListView(adapter=map_list_adapter) # map_list_adapter.bind(on_selection_change=self.callback_function) self.add_widget(list_view)
def test_list_view_with_list_of_integers_scrolling(self): data = [{"text": str(i), "is_selected": False} for i in xrange(100)] args_converter = lambda row_index, rec: {"text": rec["text"], "size_hint_y": None, "height": 25} list_adapter = ListAdapter( data=data, args_converter=args_converter, selection_mode="single", allow_empty_selection=False, cls=ListItemButton, ) list_view = ListView(adapter=list_adapter) list_view.scroll_to(20) self.assertEqual(list_view._index, 20)
def __init__(self, *args, **kwargs): super(ReceptorScreen, self).__init__(*args, **kwargs) list_item_args_converter = lambda row_index, obj: {'root_path': obj.root_path, 'item_id': obj.item_id, 'text': obj.text, 'pdbFile': obj.pdbFile, 'list_id': obj.list_id, 'number_chain': obj.number_chain, 'zoom_item': obj.zoom_item} self.list_adapter_receptor = ReceptorAdapter(data=[], args_converter=list_item_args_converter, template='GroupListItem') self.recetor_lv = ListView(adapter=self.list_adapter_receptor, divider_height= 1, id='receptor_lv') self.receptorList.add_widget(self.recetor_lv)
def __init__(self, **kwargs): self.scdata = list() self.orientation = 'vertical' # FOR NETWORK Active.scanList.clear() try: Active.scanList = Active.scan_task.get_scan_list(Active.client) except ScanException as se: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=se.value)) popup.bind(on_press=popup.dismiss) popup.title = se.title popup.open() return except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() for x in range(0, len(Active.scanList)): self.scdata.append({'path': Active.scanList[x].path, 'options': Active.scanList[x].options}) self.list_adapter = ListAdapter(data=self.scdata, args_converter=self.formatter, cls=ScCompositeListItem, selection_mode='single', allow_empty_selection=False) super(ScannerViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(HeaderBox()) self.add_widget(self.list_view) if len(self.scdata) is 0: detail_view = ScDetailView(sc_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = ScDetailView(sc_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind( on_selection_change=detail_view.sc_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 60) Clock.schedule_interval(self.callback2, 5)
def __init__(self, **kwargs): self.qrdata = list() # FOR NETWORK Active.qrList.clear() try: Active.qrList = Active.qr_task.get_qr_list(Active.client) except QrException as qr: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=qr.value)) popup.bind(on_press=popup.dismiss) popup.title = qr.title popup.open() except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() for x in range(0, len(Active.qrList)): self.qrdata.append({'filename': Active.qrList[x].f_name, 'old_path': Active.qrList[x].o_path}) self.list_adapter = ListAdapter(data=self.qrdata, args_converter=self.formatter, selection_mode='single', allow_empty_selection=False, cls=QrCompositeListItem) super(QuarantineViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(self.list_view) if len(self.qrdata) is 0: detail_view = QrDetailView(qr_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = QrDetailView(qr_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind( on_selection_change=detail_view.qr_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 60) Clock.schedule_interval(self.callback2, 5)
def __init__(self): super(GameMenu, self).__init__() self.w_start_button.bind(on_release = self.start_game) self.w_join_button.bind(on_release = self.find_network_game) args_converter = lambda row_index, rec: {'text': '%s on %s:%s'%(rec['game_name'],str(rec['ip_address']),str(rec['port'])) , 'size_hint_y': 0.1} adapter = ListAdapter(data = [], args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=True) self.w_join_game_list_view = ListView(size_hint = (0.6, 0.6), pos_hint = {'center_x':0.5, 'center_y':0.6}, adapter = adapter) self.w_join_game_box.add_widget(self.w_join_game_list_view) self.w_join_game_list_view.adapter.bind(on_selection_change = self.network_game_join) self.player_spec = [] self.server = None self.disconnected = False
class ReceptorScreen(Screen): root_path = os.path.dirname(__file__) pymol = ObjectProperty(None) list_adapter_receptor = ObjectProperty(None) receptorList = ObjectProperty(None) recetor_lv = ListView() def __init__(self, *args, **kwargs): super(ReceptorScreen, self).__init__(*args, **kwargs) list_item_args_converter = lambda row_index, obj: {'root_path': obj.root_path, 'item_id': obj.item_id, 'text': obj.text, 'pdbFile': obj.pdbFile, 'list_id': obj.list_id, 'number_chain': obj.number_chain, 'zoom_item': obj.zoom_item} self.list_adapter_receptor = ReceptorAdapter(data=[], args_converter=list_item_args_converter, template='GroupListItem') self.recetor_lv = ListView(adapter=self.list_adapter_receptor, divider_height= 1, id='receptor_lv') self.receptorList.add_widget(self.recetor_lv) def setupView(self): data = [] global ItemId ItemId = 0 pdbFiles = Variable.parsepdb.Receptors for pdbFile in pdbFiles: ItemId+=1 filename = os.path.basename(pdbFile.file_path) chainname = os.path.splitext(filename)[0] # zoom to recepter pymol_thread = Thread(target = self.pymol_zoom, args = (chainname, )) pymol_thread.start() # Find number of chain avarible for kivy height number_chain = 0 for chain in pdbFile.chains: if(chain.is_selected): number_chain += 1 pymol_thread = Thread(target = self.pymol_spectrum, args = (chain, chainname, chain.resindices, )) pymol_thread.start() filename = os.path.basename(pdbFile.file_path) data.append(DataItem(root_path=self.root_path, item_id=ItemId, text=filename, pdbFile=pdbFile , list_id = 'receptor_lv', number_chain = number_chain, zoom_item = self.zoom_item)) ligands = Variable.parsepdb.Ligands for ligand in ligands: filename = os.path.basename(ligand.file_path) chainname = os.path.splitext(filename)[0] chains = ligand.chains for chain in chains: print str(chain.chain_view) pymol_thread = Thread(target = self.pymol_hide, args = (chain, chainname, )) pymol_thread.start() self.recetor_lv.adapter.data = data self.recetor_lv._trigger_reset_populate() def set_pymol(self, pym): self.pymol = pym self.list_adapter_receptor.set_data(self.pymol) def pymol_zoom(self, chainname): self.pymol.cmd.zoom(chainname) def pymol_spectrum(self, chain, chainname, value): if chain.chain_type == 'protein': # self.pymol.cmd.color('gray', str(chain.chain_view) + ' & ' + chainname + '& resi '+str(chain.chain_view.getResnums()[0])+'-'+str(chain.chain_view.getResnums()[len(chain.chain_view.getResnums())-1]) ) self.pymol.cmd.color('gray', str(chain.chain_view) + ' & ' + chainname) self.pymol.cmd.spectrum('count', 'rainbow', str(chain.chain_view) + ' & ' + chainname +' & resi '+str(value)) else: self.pymol.cmd.hide('sticks', 'resname ' + str(chain.chain_view.getResnames()[0]) + ' & ' + chainname) def pymol_hide(self, chain, chainname): if chain.chain_type == 'protein': self.pymol.cmd.hide('cartoon', str(chain.chain_view) + ' & ' + chainname) else: self.pymol.cmd.hide('sticks', 'resname ' + str(chain.chain_view.getResnames()[0]) + ' & ' + chainname) def zoom_item(self, pdbFile): filename = os.path.basename(pdbFile.file_path) chainname = os.path.splitext(filename)[0] self.pymol.cmd.zoom(chainname)
class ScannerViewModal(BoxLayout): ## Constructor # @exception ScanException # @exception EmptyListException def __init__(self, **kwargs): self.scdata = list() self.orientation = 'vertical' # FOR NETWORK Active.scanList.clear() try: Active.scanList = Active.scan_task.get_scan_list(Active.client) except ScanException as se: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=se.value)) popup.bind(on_press=popup.dismiss) popup.title = se.title popup.open() return except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() for x in range(0, len(Active.scanList)): self.scdata.append({'path': Active.scanList[x].path, 'options': Active.scanList[x].options}) self.list_adapter = ListAdapter(data=self.scdata, args_converter=self.formatter, cls=ScCompositeListItem, selection_mode='single', allow_empty_selection=False) super(ScannerViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(HeaderBox()) self.add_widget(self.list_view) if len(self.scdata) is 0: detail_view = ScDetailView(sc_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = ScDetailView(sc_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind( on_selection_change=detail_view.sc_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 60) Clock.schedule_interval(self.callback2, 5) ## Callback on clock schedule to update list def callback(self, dt): self.update_list() ## Callback on clock schedule to update list def callback2(self, dt): global update if update != 0: update = 0 Clock.schedule_once(lambda dt: self.update_list(), 0.1) if Active.changed['sc'] != 0: Active.changed['sc'] = 0 Clock.schedule_once(lambda dt: self.update_list(), 0.1) ## Updates the Scanner list # @exception ScanException # @exception EmptyListException def update_list(self): try: Active.scanList = Active.scan_task.get_scan_list(Active.client) except ScanException as se: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=se.value)) popup.bind(on_press=popup.dismiss) popup.title = se.title popup.open() return except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() self.scdata.clear() for x in range(0, len(Active.scanList)): self.scdata.append({'path': Active.scanList[x].path, 'options': Active.scanList[x].options}) self.list_adapter.data = self.scdata if hasattr(self.list_view, '_reset_spopulate'): self.list_view._reset_spopulate() ## The args converter def formatter(self, rowindex, scdata): return {'text': scdata['path'], 'size_hint_y': None, 'height': 50, 'cls_dicts': [{'cls': ListItemButton, 'kwargs': {'text': scdata['path'], 'size_hint_x': 0.5}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['BR_S']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['DUP_S']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['DUP_F']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['INTEGRITY']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['CL_TEMP']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['BACKUP_OLD']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['DEL_F_OLD']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['BACKUP']) else False, 'size_hint_x': 0.1}}, {'cls': ScCheckBox, 'kwargs': {'disabled': True, 'active': True if bool(scdata['options']['DEL_F_SIZE']) else False, 'size_hint_x': 0.1}}]}
class GameMenu(ScreenManager): player_count = NumericProperty() players = ListProperty() disconnected = BooleanProperty() w_game = ObjectProperty() w_start_button = ObjectProperty() w_join_button = ObjectProperty() w_join_game_box = ObjectProperty() w_join_game_adapter = ObjectProperty() def __init__(self): super(GameMenu, self).__init__() self.w_start_button.bind(on_release = self.start_game) self.w_join_button.bind(on_release = self.find_network_game) args_converter = lambda row_index, rec: {'text': '%s on %s:%s'%(rec['game_name'],str(rec['ip_address']),str(rec['port'])) , 'size_hint_y': 0.1} adapter = ListAdapter(data = [], args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=True) self.w_join_game_list_view = ListView(size_hint = (0.6, 0.6), pos_hint = {'center_x':0.5, 'center_y':0.6}, adapter = adapter) self.w_join_game_box.add_widget(self.w_join_game_list_view) self.w_join_game_list_view.adapter.bind(on_selection_change = self.network_game_join) self.player_spec = [] self.server = None self.disconnected = False def find_network_game(self, *args): print('looking for network games') import msocket self.w_join_game_list_view.adapter.data = [] self.server = msocket.BroadcastClient(game_id, BROADCAST_PORT, callback = self.network_broadcaster_callback) self.current = 'join_game' def stop_server(self): if self.server is not None: self.server.stop() self.server = None def network_broadcaster_callback(self, *args): Clock.schedule_once(functools.partial(self.network_game_found, *args)) def network_game_found(self, *args): (ip, bport), (game_id, game_name, gport), dt = args data = self.w_join_game_list_view.adapter.data[:] data.append({'ip_address': ip, 'game_name': game_name, 'port': gport}) self.w_join_game_list_view.adapter.data = data self.w_join_game_list_view.populate() def network_game_join(self, adapter): if len(adapter.selection) == 0: return sel = adapter.selection[0] data = adapter.data[sel.index] gname = data['game_name'] ip = data['ip_address'] gport = data['port'] import msocket self.stop_server() try: self.server = msocket.TurnBasedClient(game_id, gname, ip, gport, self.server_callback) except: #TODO: NOTIFY USER THAT CLIENT COULDN'T CONNECT return self.disconnected = False self.server.send('hello',None) def start_network_server(self): import msocket self.server = msocket.TurnBasedServer(game_id, game_name, BROADCAST_PORT, GAME_PORT, self.num_network_players, callback = self.server_callback) self.disconnected = False def server_callback(self, *args): Clock.schedule_once(functools.partial(self.server_msg, *args)) def server_msg(self, *args): msg, data, dt = args board = self.w_game.children[0] if msg == 'players_joined': #all players have joined net_players = [x for x in range(self.player_count) if self.players[x]==2] self.server.queue.put(('player_ids',net_players)) self.start_network_game(self.player_spec) elif msg == 'hello': #remote player says hello, send the initial game data player_id, data = data players_id = [x for x in range(len(board.players))] board.players[player_id].queue.put(('s_hello', (player_id, players_id))) elif msg == 's_hello': #data contains this players id and a list of player id's in turn order player_id, players_id = data spec = [] for x in range(len(players_id)): ps = PlayerSpec('Player '+str(x), color_lookup[x], 0 if players_id[x] == player_id else 2) spec.append(ps) self.start_network_game(spec) elif msg == 'select': #player wants to select a die player_id, (pid, die_num) = data p = board.players[pid] die = p.dice[die_num] board.select_die(die) #self.server.send(player_id, True, die_num, die.value) elif msg == 's_select': #notify player whether they have selected a die and the roll result player_id, die_num, roll_value = data p = board.players[player_id] die = p.dice[die_num] board.select_die(die, roll_value) elif msg == 'place': #player wants to place a die player_id, (pid, hex_pos) = data t = board.tiles[hex_pos] board.place_die(t) #self.server.send(True, hex_pos) elif msg == 's_place': #notify player whether the die has been placed success, hex_pos = data t = board.tiles[hex_pos] board.place_die(t, False) elif msg == 's_restart': #resposne to the game restart # data is success self.start_network_game() elif msg == 's_quitgame': #response to the game quit # data is success self.server.stop() self.server = None self.current = 'main' elif msg == 'connection_error': board.w_state_label.color = white # board.w_state_label.bg_color = grey board.w_state_label.text = 'Disconnected - game over' board.game_over = True self.server = None self.disconnected = True def start_network_game(self, spec = None): if spec is not None: self.player_spec = spec board = self.w_game.children[0] board.server = self.server board.setup_game(self.player_spec) board.start_game() self.current = 'game' try: net_players = [x for x in range(self.player_count) if self.players[x]==2] for x in range(len(net_players)): board.players[net_players[x]].queue = self.server.players[x].queue except AttributeError: pass def restart_game(self): if self.disconnected: return False if self.server is not None: try: self.server.notify_clients('s_restart',None) except AttributeError: return False board = self.w_game.children[0] board.setup_game(self.player_spec) board.start_game() try: net_players = [x for x in range(self.player_count) if self.players[x]==2] for x in range(len(net_players)): board.players[net_players[x]].queue = self.server.players[x].queue except AttributeError: pass self.current = 'game' def join_game(self, *args): pass def start_game(self, *args): self.player_spec = [] self.num_network_players = 0 for x in range(self.player_count): ps = PlayerSpec('Player '+str(x+1), color_lookup[x], self.players[x]) if ps.type == 2: self.num_network_players += 1 self.player_spec.append(ps) if self.num_network_players > 0: self.start_network_server() self.current = 'host_wait' else: board = self.w_game.children[0] board.server = None board.setup_game(self.player_spec) board.start_game() self.current = 'game'
class QuarantineViewModal(BoxLayout): ## Constructon # @exception QrException # @exception EmptyListException def __init__(self, **kwargs): self.qrdata = list() # FOR NETWORK Active.qrList.clear() try: Active.qrList = Active.qr_task.get_qr_list(Active.client) except QrException as qr: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=qr.value)) popup.bind(on_press=popup.dismiss) popup.title = qr.title popup.open() except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() for x in range(0, len(Active.qrList)): self.qrdata.append({'filename': Active.qrList[x].f_name, 'old_path': Active.qrList[x].o_path}) self.list_adapter = ListAdapter(data=self.qrdata, args_converter=self.formatter, selection_mode='single', allow_empty_selection=False, cls=QrCompositeListItem) super(QuarantineViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(self.list_view) if len(self.qrdata) is 0: detail_view = QrDetailView(qr_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = QrDetailView(qr_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind( on_selection_change=detail_view.qr_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 60) Clock.schedule_interval(self.callback2, 5) ## Callback on clock schedule to update list def callback(self, dt): self.update_list() ## Callback on clock schedule to update list def callback2(self, dt): global update if update != 0: update = 0 Clock.schedule_once(lambda dt: self.update_list(), 0.1) if Active.changed['qr'] != 0: Active.changed['qr'] = 0 Clock.schedule_once(lambda dt: self.update_list(), 1) ## Updates the Quarantine list # @exception QrException # @exception EmptyListException def update_list(self): try: Active.qrList = Active.qr_task.get_qr_list(Active.client) except QrException as qr: popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=qr.value)) popup.bind(on_press=popup.dismiss) popup.title = qr.title popup.open() return except EmptyListException as ee: global empty if empty is 0: empty = 1 popup = Popup(size_hint=(None, None), size=(400, 150)) popup.add_widget(Label(text=ee.value)) popup.bind(on_press=popup.dismiss) popup.title = ee.title popup.open() finally: self.qrdata.clear() for x in range(0, len(Active.qrList)): self.qrdata.append({'filename': Active.qrList[x].f_name, 'old_path': Active.qrList[x].o_path}) self.list_adapter.data = self.qrdata if hasattr(self.list_view, '_reset_spopulate'): self.list_view._reset_spopulate() ## The args converter def formatter(self, rowindex, qr_data): return {'text': qr_data['filename'], 'size_hint_y': None, 'height': 50, 'cls_dicts': [{'cls': ListItemButton, 'kwargs': {'text': qr_data['filename']}}, {'cls': ListItemLabel, 'kwargs': {'text': "Old Path:"}}, {'cls': ListItemLabel, 'kwargs': {'text': qr_data['old_path']}}]}
class DataModel(GridLayout): """ Uses :class:`CompositeListItem` for list item views comprised by two :class:`ListItemButton`s and one :class:`ListItemLabel`. Illustrates how to construct the fairly involved args_converter used with :class:`CompositeListItem`. """ minval = NumericProperty(0) maxval = NumericProperty(0) simulate = False time_interval = 1 dirty_thread = False dirty_model = False simulate_timer = None simulate = False dispatcher = None list_view = None _parent = None is_simulating = False blockname = "<BLOCK_NAME_NOT_SET>" def __init__(self, **kwargs): kwargs['cols'] = 2 kwargs['size_hint'] = (1.0, 1.0) super(DataModel, self).__init__(**kwargs) self.init() def init(self, simulate=False, time_interval=1, **kwargs): """ Initializes Datamodel """ self.minval = kwargs.get("minval", self.minval) self.maxval = kwargs.get("maxval", self.maxval) self.blockname = kwargs.get("blockname", self.blockname) self.clear_widgets() self.simulate = simulate self.time_interval = time_interval dict_adapter = DictAdapter(data={}, args_converter=self.arg_converter, selection_mode='single', allow_empty_selection=True, cls=CompositeListItem ) # Use the adapter in our ListView: self.list_view = ListView(adapter=dict_adapter) self.add_widget(self.list_view) self.dispatcher = UpdateEventDispatcher() self._parent = kwargs.get('_parent', None) self.simulate_timer = BackgroundJob( "simulation", self.time_interval, self._simulate_block_values ) def clear_widgets(self, make_dirty=False, **kwargs): """ Overidden Clear widget function used while deselecting/deleting slave :param make_dirty: :param kwargs: :return: """ if make_dirty: self.dirty_model = True super(DataModel, self).clear_widgets(**kwargs) def reinit(self, **kwargs): """ Re-initializes Datamodel on change in model configuration from settings :param kwargs: :return: """ self.minval = kwargs.get("minval", self.minval) self.maxval = kwargs.get("maxval", self.maxval) time_interval = kwargs.get("time_interval", None) try: if time_interval and int(time_interval) != self.time_interval: self.time_interval = time_interval if self.is_simulating: self.simulate_timer.cancel() self.simulate_timer = BackgroundJob("simulation", self.time_interval, self._simulate_block_values) self.dirty_thread = False self.start_stop_simulation(self.simulate) except ValueError: Logger.debug("Error while reinitializing DataModel %s" % kwargs) def update_view(self): """ Updates view with listview again :return: """ if self.dirty_model: self.add_widget(self.list_view) self.dirty_model = False def arg_converter(self, index, data): """ arg converter to convert data to list view :param index: :param data: :return: """ _id = self.list_view.adapter.sorted_keys[index] return { 'text': str(_id), 'size_hint_y': None, 'height': 30, 'cls_dicts': [ { 'cls': ListItemButton, 'kwargs': {'text': str(_id)} }, { 'cls': NumericTextInput, 'kwargs': { 'data_model': self, 'minval': self.minval, 'maxval': self.maxval, 'text': str(data), 'multiline': False, 'is_representing_cls': True, } }, ] } def add_data(self, data, item_strings): """ Adds data to the Data model :param data: :param item_strings: :return: """ self.update_view() last_index = len(item_strings) if last_index in item_strings: last_index = int(item_strings[-1]) + 1 item_strings.append(last_index) self.list_view.adapter.data.update({last_index: data}) self.list_view._trigger_reset_populate() return self.list_view.adapter.data, item_strings def delete_data(self, item_strings): """ Delete data from data model :param item_strings: :return: """ selections = self.list_view.adapter.selection items_popped = [] for item in selections: index_popped = item_strings.pop(item_strings.index(int(item.text))) data_popped = self.list_view.adapter.data.pop(int(item.text), None) self.list_view.adapter.update_for_new_data() self.list_view._trigger_reset_populate() items_popped.append(index_popped) return items_popped, self.list_view.adapter.data def on_selection_change(self, item): pass def on_data_update(self, index, data): """ Call back function to update data when data is changed in the list view :param index: :param data: :return: """ self.list_view.adapter.data.update({index: data}) self.list_view._trigger_reset_populate() self.dispatcher.dispatch('on_update', self._parent, self.blockname, self.list_view.adapter.data) def refresh(self, data={}): """ Data model refresh function to update when the view when slave is selected :param data: :return: """ self.update_view() self.list_view.adapter.data = data self.list_view.disabled = False self.list_view._trigger_reset_populate() def start_stop_simulation(self, simulate): """ Starts or stops simulating data :param simulate: :return: """ self.simulate = simulate if self.simulate: if self.dirty_thread: self.simulate_timer = BackgroundJob( "simulation", self.time_interval, self._simulate_block_values ) self.simulate_timer.start() self.dirty_thread = False self.is_simulating = True else: self.simulate_timer.cancel() self.dirty_thread = True self.is_simulating = False def _simulate_block_values(self): if self.simulate: data = self.list_view.adapter.data if data: for index, value in data.items(): data[index] = randint(self.minval, self.maxval) print self.minval, self.maxval, data[index] self.refresh(data) self.dispatcher.dispatch('on_update', self._parent, self.blockname, self.list_view.adapter.data)
def create_button_view(self, dt): import json import time # Make reference to app root widget sm = self._app.root # Check that JSON been recieved if re.match(r'^\{.*\}$', self._app.sm.json_sensors): try: j = json.loads(self._app.sm.json_sensors) except Exception as e: self._app.sm.json_sensors = 'Error in JSON' else: all_devices_boxlayout = BoxLayout(orientation='vertical', spacing=10) all_devices_boxlayout.add_widget(Label(text='')) all_devices_boxlayout.add_widget(Label(size_hint_y=0.2, text='[color=ff3333]Devices[/color]', font_size=40, markup=True)) all_devices_boxlayout.add_widget(Label(text='')) all_devices_screen = Screen(id='all_devices_buttons', name='all_devices_buttons') all_devices_screen.add_widget(all_devices_boxlayout) sm.add_widget(all_devices_screen) # Bulding new screens for list of devices and sensors based on json # For each device create its own Screen for device in j.keys(): Logger.info("Creating screen for device %s" % (device,)) self._app.log_list.append(get_date("Creating screen for device %s" % (device,))) screen_device = Screen(name=device) # Add button for device on all_devices_boxlayout b = Button(text=device) # This will call the function with 'device' as argument to switch Screen b.bind(on_press=partial(self.change_screen, device)) all_devices_boxlayout.add_widget(b) # Create Device Screen with sensors box_device = BoxLayout(orientation='vertical', spacing=10) box_device.add_widget(Label(text='')) box_device.add_widget(Label(size_hint_y=0.2, text='[color=ff3333]' + device + '[/color]', font_size=40, markup=True)) box_device.add_widget(Label(text='')) # Create Sensor Screen and button on device screen for sensor in j[device]: sensor_name = sensor.keys()[0] sensor_data = sensor[sensor_name] sensor_values = sensor_data['last_records'] sensor_dict = updates_to_plots(sensor_values) sensor_plots = sensor_dict['plots'] ymin = sensor_dict['min_y'] ymax = sensor_dict['max_y'] xmin = sensor_dict['min_x'] last_date, last_value = sensor_values[-1] # Determine suffix suffix = ' ' if re.match(r'.*temp.*', sensor_name, re.IGNORECASE): suffix = u"\u00b0C" if re.match(r'.*humid.*', sensor_name, re.IGNORECASE): suffix = " %" if re.match(r'.*smoke.*', sensor_name, re.IGNORECASE): suffix = " %" if re.match(r'.*stove.*', sensor_name, re.IGNORECASE): suffix = " %" sensor = device + '_' + sensor_name Logger.info(str(sensor)) Logger.info("Last data %s %s" % (last_date, last_value)) # Create history view screen_sensor_history = Screen(name=device + "_" + sensor_name + "_history") box_sensor_history = BoxLayout(orientation='vertical', spacing=10) box_sensor_history.add_widget(Label(size_hint_y=0.1, text='[color=B6BAB9]' + sensor_name + ' (' + device + ')[/color]', font_size=30, markup=True)) # Create history text text_history = [] for d, v in sensor_values: text_history.append(str("%s %s" % (d, v))) # Create left aligned list adapter = SimpleListAdapter(data=text_history, cls=MyLeftAlignedLabel) list_view = ListView(adapter=adapter) # Fix bug with ListView to refresh if required if(hasattr(list_view, '_reset_spopulate')): Logger.info("Refresh list_view") list_view._reset_spopulate() # Add ListView to Sensor History box_sensor_history.add_widget(list_view) back_button = Button(size_hint_y=0.1, font_size=20, text='Back') back_button.bind(on_press=partial(self.change_screen, device + "_" + sensor_name)) box_sensor_history.add_widget(back_button) screen_sensor_history.add_widget(box_sensor_history) sm.add_widget(screen_sensor_history) # Create sensor screen screen_sensor = Screen(name=device + "_" + sensor_name) box_sensor = BoxLayout(orientation='vertical') box_sensor.add_widget(Label(size_hint_y=0.1, text='[color=B6BAB9]' + sensor_name + ' (' + device + ')[/color]', font_size=30, markup=True)) # Add sensor value box_sensor.add_widget(Label(text=last_value + suffix, font_size=60)) # Add sensor date box_sensor.add_widget(Label(size_hint_y=0.1, markup=True, text='[b]Sensor last updated ' + last_date[:-3] + '[/b]\nPolled ' + get_date(None)[:-3], font_size=15)) # Add sensor graph Logger.info("Create plot for %s" % (sensor_name,)) Logger.info(str(sensor_plots)) plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1]) plot.points = sensor_plots sensor_graph = Graph(id='plots_' + sensor_name, precision='%0.0f', x_grid_label=True, y_grid_label=True, xmin=xmin, xmax=0, ymin=ymin, ymax=ymax, xlabel='days ago', ylabel=suffix, x_grid=True, y_grid=False, x_ticks_major=1, y_ticks_major=1) sensor_graph.add_plot(plot) box_sensor.add_widget(sensor_graph) # Add buttonbar for sensor box_buttons = BoxLayout(orientation='horizontal') # Create button for history history_button = Button(size_hint_y=0.2, font_size=20, text='History') history_button.bind(on_press=partial(self.change_screen, device + "_" + sensor_name + "_history")) # Create Back button back_button = Button(size_hint_y=0.2, font_size=20, text='Back') back_button.bind(on_press=partial(self.change_screen, device)) # Add buttons to row box_buttons.add_widget(back_button) box_buttons.add_widget(history_button) # Add row to screen box_sensor.add_widget(box_buttons) # Add all of it to screen screen_sensor.add_widget(box_sensor) sm.add_widget(screen_sensor) # Create button on device screen button_sensor = Button(text=sensor_name) button_sensor.bind(on_press=partial(self.change_screen, sensor)) box_device.add_widget(button_sensor) # Add Device Screen with all sensor buttons to ScreenManager back_button = Button(font_size=20, text='[b]Back[/b]', markup=True) back_button.bind(on_press=partial(self.change_screen, 'all_devices_buttons')) box_device.add_widget(back_button) screen_device.add_widget(box_device) sm.add_widget(screen_device) # Adding Back button to Devices screen back_button = Button(font_size=20, text='[b]Back[/b]', markup=True) back_button.bind(on_press=partial(self.change_screen, 'initial_screen')) all_devices_buttonrow = BoxLayout(orientation='horizontal') all_devices_buttonrow.add_widget(back_button) slide_all_button = ToggleButton(id='slide_all_button', font_size=20, text='Slideshow All Sensors') slide_all_button.bind(on_press=partial(self.control_slideshow_all_sensors, slide_all_button)) all_devices_buttonrow.add_widget(slide_all_button) all_devices_boxlayout.add_widget(all_devices_buttonrow) # Unschedule timer Clock.unschedule(self.create_button_view) # Return to buttons of all devices sm.current = 'all_devices_buttons' # Schedule updates from server Clock.schedule_interval(sm.update_views, int(self._app.sm.settings_dict['refresh_time'])) # Check if failed pause for error before return if re.match(r'.*fail.*', self._app.sm.connect_server_status) or re.match(r'.*error.*', self._app.sm.json_sensors): Clock.unschedule(self.create_button_view) time.sleep(2) self.port = self._app.config.get('network', 'port') self.server = self._app.config.get('network', 'ip') self._app.sm.connect_server_status = "Connecting to %s:%s" % (self.server, self.port) sm.current = 'initial_screen'
def __init__(self, data_ap, **kwargs): super(Table, self).__init__(**kwargs) self.app = App.get_running_app() ## first check if len data = 0 add label to alert user if len(data_ap) is 0: self.add_widget(Label(text="No Data", font_size='32dp')) return ######################## ## HEADER ######################## self.container_header = GridLayout(cols=3, size_hint_y=None, height=(self.app.row_height*0.55), spacing=10) listview_header_widgets = [Label(text="CHUNK"), Label(text="FOUND"), Label(text="SCORE", size_hint_x=0.2)] for x in range(3): self.container_header.add_widget(listview_header_widgets[x]) self.add_widget(self.container_header) ######################## ## GRID ######################## self.container_table = GridLayout(cols=2) # This is quite an involved args_converter, so we should go through the # details. A CompositeListItem instance is made with the args # returned by this converter. The first three, text, size_hint_y, # height are arguments for CompositeListItem. The cls_dicts list contains # argument sets for each of the member widgets for this composite: # ListItemButton and ListItemLabel. args_converter = \ lambda row_index, obj: \ {'text': obj.chunk, 'value': obj.chunk, 'size_hint_y': None, 'height': self.app.row_height * 0.5, 'cls_dicts': [{'cls': Cell, 'kwargs': {'text': obj.chunk, 'id': obj.chunk}}, {'cls': Cell, 'kwargs': {'text': obj.found, 'id': obj.chunk, 'is_representing_cls': True}}, {'cls': Cell, 'kwargs': {'text': str(obj.score), 'id': obj.chunk, 'size_hint_x': 0.2}}]} self.list_adapter = ListAdapter( data=self.first_fill(data_ap), args_converter=args_converter, selection_mode='single', propagate_selection_to_data=True, allow_empty_selection=False, cls=CompositeListItem) # Use the adapter in our ListView: self.list_view = ListView(adapter=self.list_adapter) print 'chunck selezionato: ', self.list_adapter.selection[0].children[2].text chunk = MarkupLabel(self.list_adapter.selection[0].children[2].text).markup print 'selected: ', self.list_adapter.selection[0].children[2].id self.detail_view = RowDetailView(chunk=self.list_adapter.selection[0].children[2].id) self.list_adapter.bind(on_selection_change=self.detail_view.row_changed) self.container_table.add_widget(self.list_view) self.add_widget(self.container_table) self.add_widget(self.detail_view)
class ListViewModal(BoxLayout): ## The data containing clients data = ListProperty() ## Constructor def __init__(self, **kwargs): self.data = list() for x in range(0, len(Active.cl.c_list)): self.data.append({ 'hostname': Active.cl.c_list[x].name, 'ip': Active.cl.c_list[x].ip }) self.list_adapter = ListAdapter(data=self.data, args_converter=self.formatter, cls=ClCompositeListItem, selection_mode='single', allow_empty_selection=False) super(ListViewModal, self).__init__(**kwargs) self.list_view = ListView(adapter=self.list_adapter) self.add_widget(self.list_view) if len(self.data) is 0: detail_view = ClientDetailView(cl_name="List is empty", size_hint=(.6, 1.0)) else: detail_view = ClientDetailView(cl_name=self.list_adapter.selection[0].text, size_hint=(.6, 1.0)) self.list_adapter.bind( on_selection_change=detail_view.cl_changed) self.add_widget(detail_view) Clock.schedule_interval(self.callback, 5) ## Callback on clock schedule to update list def callback(self, dt): global update if update != 0: update = 0 Clock.schedule_once(lambda dt: self.update_list(), 0.1) if Active.changed['cl'] != 0: Active.changed['cl'] = 0 Clock.schedule_once(lambda dt: self.update_list(), 0.1) ## The args converter def formatter(self, rowindex, data): return {'text': data['hostname'], 'size_hint_y': None, 'height': 40, 'cls_dicts': [{'cls': ListItemButton, 'kwargs': {'text': data['hostname']}}, {'cls': ListItemLabel, 'kwargs': {'text': data['ip']}}]} ## Updates the Client list # @exception QrException # @exception EmptyListException def update_list(self): self.data.clear() for x in range(0, len(Active.cl.c_list)): self.data.append({ 'hostname': Active.cl.c_list[x].name, 'ip': Active.cl.c_list[x].ip }) self.list_adapter.data = self.data if hasattr(self.list_view, '_reset_spopulate'): self.list_view._reset_spopulate()
def update_views(self, dt): ''' Method to be scheduled for updating from server ''' # Poll new JSON data Logger.info(str(self._app.connect_to_server())) # Clean records in log_screen if too many lines if len(self._app.log_list) > 100: self._app.log_list.append(get_date("Cleaning old records in log")) while len(self._app.log_list) > 100: self._app.log_list.pop(0) def return_screen_object(screen_name): # Iterate through all screens found = None for current_screen in self._app.sm.screens: if current_screen.name == screen_name: found = current_screen return found # For each device update Screen if re.match(r'^\{.*\}$', self._app.sm.json_sensors): try: j = json.loads(self._app.sm.json_sensors) except Exception as e: self._app.sm.json_sensors = 'Error in JSON' else: for device in j.keys(): Logger.info("Updating screen for device %s" % (device,)) self._app.log_list.append(get_date("Updating screen for device %s" % (device,))) # Create Device Screen with sensors box_device = BoxLayout(orientation='vertical', spacing=10) box_device.add_widget(Label(text='')) box_device.add_widget(Label(size_hint_y=0.2, text='[color=ff3333]' + device + '[/color]', font_size=40, markup=True)) box_device.add_widget(Label(text='')) # Create Sensor Screen and button on device screen for sensor in j[device]: sensor_name = sensor.keys()[0] sensor_data = sensor[sensor_name] sensor_values = sensor_data['last_records'] sensor_dict = updates_to_plots(sensor_values) sensor_plots = sensor_dict['plots'] ymin = sensor_dict['min_y'] ymax = sensor_dict['max_y'] xmin = sensor_dict['min_x'] last_date, last_value = sensor_values[-1] # Determine suffix suffix = ' ' if re.match(r'.*temp.*', sensor_name, re.IGNORECASE): suffix = u"\u00b0C" if re.match(r'.*humid.*', sensor_name, re.IGNORECASE): suffix = " %" if re.match(r'.*smoke.*', sensor_name, re.IGNORECASE): suffix = " %" if re.match(r'.*stove.*', sensor_name, re.IGNORECASE): suffix = " %" sensor = device + '_' + sensor_name Logger.info(str(sensor)) Logger.info("Last data %s %s" % (last_date, last_value)) # Create new history view box_sensor_history = BoxLayout(orientation='vertical', spacing=10) box_sensor_history.add_widget(Label(size_hint_y=0.1, text='[color=B6BAB9]' + sensor_name + ' (' + device + ')[/color]', font_size=30, markup=True)) # Create history text text_history = [] for d, v in sensor_values: text_history.append(str("%s %s" % (d, v))) # Create left aligned list adapter = SimpleListAdapter(data=text_history, cls=MyLeftAlignedLabel) list_view = ListView(adapter=adapter) # Fix bug with ListView to refresh if required if(hasattr(list_view, '_reset_spopulate')): Logger.info("Refresh list_view") list_view._reset_spopulate() # Add ListView to Sensor History box_sensor_history.add_widget(list_view) back_button = Button(size_hint_y=0.1, font_size=20, text='Back') back_button.bind(on_press=partial(self.change_screen, device + "_" + sensor_name)) box_sensor_history.add_widget(back_button) screen_sensor_history = return_screen_object(device + "_" + sensor_name + '_history') screen_sensor_history.clear_widgets() screen_sensor_history.add_widget(box_sensor_history) screen_sensor = return_screen_object(device + "_" + sensor_name) box_sensor = BoxLayout(orientation='vertical') box_sensor.add_widget(Label(size_hint_y=0.1, text='[color=B6BAB9]' + sensor_name + ' (' + device + ')[/color]', font_size=30, markup=True)) # Add sensor value box_sensor.add_widget(Label(text=last_value + suffix, font_size=60)) # Add sensor date box_sensor.add_widget(Label(size_hint_y=0.1, markup=True, text='[b]Sensor last updated ' + last_date[:-3] + '[/b]\nPolled ' + get_date(None)[:-3], font_size=15)) # Add sensor graph Logger.info("Create plot for %s" % (sensor_name,)) Logger.info(str(sensor_plots)) plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1]) plot.points = sensor_plots sensor_graph = Graph(id='plots_' + sensor_name, precision='%0.0f', x_grid_label=True, y_grid_label=True, xmin=xmin, xmax=0, ymin=ymin, ymax=ymax, xlabel='days ago', ylabel=suffix, x_grid=True, y_grid=False, x_ticks_major=1, y_ticks_major=1) sensor_graph.add_plot(plot) box_sensor.add_widget(sensor_graph) # Add buttonbar for sensor box_buttons = BoxLayout(orientation='horizontal') # Create button for history history_button = Button(size_hint_y=0.2, font_size=20, text='History') history_button.bind(on_press=partial(self.change_screen, device + "_" + sensor_name + "_history")) # Create Back button back_button = Button(size_hint_y=0.2, font_size=20, text='Back') back_button.bind(on_press=partial(self.change_screen, device)) # Add buttons to row box_buttons.add_widget(back_button) box_buttons.add_widget(history_button) # Add row to screen box_sensor.add_widget(box_buttons) # Add all of it to screen screen_sensor.clear_widgets() screen_sensor.add_widget(box_sensor)