class RollbackDialog(Popup): def __init__(self, oMainWidget, aRounds): self.turnadapt = ListAdapter(data=aRounds, args_converter=self.convert, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) self.turnadapt.bind(selection=self.selection) self.oMainWidget = oMainWidget self.sRound = aRounds[0] super(RollbackDialog, self).__init__() def convert(self, iRow, sText): return {'text': sText, 'size_hint_y': None, 'height': 25} def selection(self, oAdapt, *args): if self.turnadapt.selection: # We need this guard, since we're called twice on selection # changes - once with nothing selected and once with the # new selection self.sRound = self.turnadapt.selection[0].text def select(self): self.oMainWidget.rollback_to_round(self.sRound) self.dismiss()
def __init__(self, settings, channel, **kwargs): super(ChannelSelectView, self).__init__(**kwargs) self.register_event_type('on_channel_selected') self.register_event_type('on_channel_cancel') data = [] channel_list = self.ids.channelList available_channels = list(settings.runtimeChannels.get_active_channels().iterkeys()) available_channels.sort() try: for available_channel in available_channels: data.append({'text': available_channel, 'is_selected': False}) args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': dp(50)} list_adapter = ListAdapter(data=data, args_converter=args_converter, cls=ChannelItemButton, selection_mode='single', allow_empty_selection=True) channel_list.adapter = list_adapter #select the current channel index = 0 for item in list_adapter.data: if item['text'] == channel: view = list_adapter.get_view(index) view.trigger_action(duration=0) #duration=0 means make it an instant selection index += 1 list_adapter.bind(on_selection_change=self.on_select) self.channel = channel except Exception as e: Logger.error("ChannelSelectView: Error initializing: " + str(e))
class FontChooser(BoxLayout): font = StringProperty("") text = font def __init__(self, **kwargs): super(FontChooser, self).__init__(**kwargs) self.orientation = "vertical" self.fonts = sorted(map(str, fonts.get_fonts())) data = [{'text': str(i), 'is_selected': i == self.font} for i in self.fonts] args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': 25} self.list_adapter = ListAdapter(data=data, args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) self.list_view = ListView(adapter=self.list_adapter) self.list_adapter.bind(selection=self.on_font_select) self.label = Label(text="The quick brown fox jumps over the brown lazy dog. 0123456789", font_size="30dp", halign="center", size_hint_y=None) self.label.font_name = fonts.match_font(self.list_adapter.selection[0].text) self.label.bind(size=self.label.setter("text_size")) self.font = self.list_adapter.selection[0].text self.add_widget(self.list_view) self.add_widget(self.label) def on_font_select(self, instance, value): self.font = value[0].text self.label.font_name = fonts.match_font(value[0].text)
class SettingAreasList(ListView): def __init__(self, **kwargs): super().__init__(**kwargs) bins = controller.sort_bin(database_interface.get_data(database_interface.CONFIG.BINS, {})) areas = list() for area in bins: areas.append(controller.DataItem('Bin ' + str(area['bin']) + ': ' + area['name'].capitalize())) list_item_args_converter = lambda row_index, obj: { 'text': obj.text, 'font_size': 30, 'height': 100, 'selected_color': [0.2, 5, 0.5, 1.], 'deselected_color': [1, 1, 1, 1.], 'background_color': [1, 1, 1, 0.], 'background_normal': "Images/Box.png", 'color': [0, 0, 0, 1.], 'padding': (5, 5) } self.adapter = ListAdapter(data=areas, args_converter=list_item_args_converter, propagate_selection_to_data=True, allow_empty_selectio=False, cls=ListItemButton) self.adapter.bind(on_selection_change=controller.go_to_update)
class SettingContactList(ListView): def update_contacts(self): names = controller.database_interface.get_data(database_interface.CONTACT, {}) li = list() for name in names: li.append(controller.DataItem(str(name['name']))) list_item_args_converter = lambda row_index, obj: { 'text': obj.text, 'font_size': 30, 'height': 100, 'selected_color': [0.2, 5, 0.5, 1.], 'deselected_color': [1, 1, 1, 1.], 'background_color': [1, 1, 1, 0.], 'background_normal': "Images/Box.png", 'color': [0, 0, 0, 1.], 'padding': (5, 5) } self.adapter = ListAdapter(data=li, args_converter=list_item_args_converter, propagate_selection_to_data=True, allow_empty_selectio=False, cls=ListItemButton) self.adapter.bind(on_selection_change=controller.go_to_contact) def __init__(self, **kwargs): super().__init__(**kwargs) self.update_contacts()
class ListeVille(MainApp): def __init__(self, parent,**kwargs): super(MainApp, self).__init__(**kwargs) self.parent = parent self.orientation = 'vertical' self.ville_depart = None self.ville_arriver = None self.list_adapter = ListAdapter( data=gestion_bd.select_ville(), cls=ListItemButton, sorted_keys=[], selection_mode='multiple', ) self.list_adapter.bind(on_selection_change=self.selection_change) self.list_view = ListView(adapter=self.list_adapter) def selection_change(self, adapter, *args): for element in adapter.selection: x = element.index #index du truc selectionner print(adapter.data[x]) if self.ville_depart != None: self.ville_arriver = adapter.data[x] if self.ville_depart == None: self.ville_depart = adapter.data[x] self.list_adapter.data = gestion_bd.select_seconde_ville(str(adapter.data[x])) if self.ville_arriver != None: self.resultat() def resultat(self): self.retour = gestion_bd.select_horaire(self.ville_depart, self.ville_arriver) self.parent.remove_widget(self.list_view) affichage = Affichage(self.parent, self.ville_depart, self.ville_arriver, self.retour)
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 MainView(BoxLayout): def __init__(self, **kwargs): kwargs['cols'] = 2 super(MainView, self).__init__(**kwargs) #project_store = JsonStore('projectlist.json') lis, project_store = FApp().other() print lis print project_store self.list_adapter = ListAdapter(data=[("Project " + r + ' ' + project_store[r]['profile']['projecttitle']) for r in lis], cls=ListItemButton, sorted_keys=[]) self.list_adapter.bind(on_selection_change=self.callback) list_view = ListView(adapter=self.list_adapter) self.add_widget(list_view) def callback(self, instance): global PROJECT p_num= instance.selection[0].text.split(' ')[1] PROJECT = p_num print p_num print 'project' return PROJECT
class DockAppsList(ListView): def __init__(self, *args, **kwargs): super(DockAppsList, self).__init__(*args, **kwargs) the_apps = [DataItem(text=a["name"]) for a in APPS.info('')] args_converter = lambda row_index, obj: {'text': obj.text, 'is_selected':obj.is_selected, 'size_hint_y': None, 'height': 20, 'font_size':14, 'deselected_color':[0,0,0,0], 'selected_color':[.96,.56,.36,1], 'background_normal':"images/button.png", 'background_down':"images/buton.png", 'color':[.2,.2,.2,1]} self.adapter=ListAdapter(data = the_apps, selection_mode = 'multiple', args_converter=args_converter, allow_empty_selection = True, propagate_selection_to_data=True, cls = ListItemButton, sorted_keys=[]) #self.adapter.select_list(self.adapter.data,extend=False) self.adapter.bind(on_selection_change=self.on_select) def on_select(self, *args, **kwargs): l = [a.text for a in args[0].selection] updateConfig({'dock-apps':l})
def load(self, path, filename): try: if str(filename[0]).endswith('mp3'): # добавление в плейлист только мр3 файлов self.list_of_songs.append(os.path.join(path, filename[0])) else: self.warnings('This is not .mp3 file') # ___ создание плейлиста в виде ListItemButton item_strings = ["{0}".format(index) for index in self.list_of_songs] list_adapter = ListAdapter( data=self.list_of_songs, selection_mode='single', allow_empty_selection=False, cls=ListItemButton ) list_view = ListView(adapter=list_adapter) list_adapter.bind(on_selection_change=self.sound_load) global list_view print(self.list_of_songs[0]) except IndexError: self.warnings('Choose a song')
def __init__(self, **kwargs): super(TreeView, self).__init__(**kwargs) self.parent_and_uncles_list_adapter = ListAdapter( data=[El.get("TEXT") for El in parentMap[selectedParent]], selection_mode='single', allow_empty_selection=False, cls=ListItemButton) self.add_widget(ListView(adapter=self.parent_and_uncles_list_adapter)) self.parent_and_uncles_list_adapter.get_view(selectedIndexList[-2]).trigger_action(duration=0) self.main_list_adapter = ListAdapter( data=[El.get("TEXT") for El in selectedParent], selection_mode='single', allow_empty_selection=False, cls=ListItemButton) self.add_widget(ListView(adapter=self.main_list_adapter)) self.main_list_adapter.get_view(selectedIndexList[-1]).trigger_action(duration=0) child_list_adapter = ListAdapter( data=[El.get("TEXT") for El in selectedParent[selectedIndexList[-1]]], selection_mode='single', allow_empty_selection=True, cls=ListItemButton) self.add_widget(ListView(adapter=child_list_adapter))
def __init__(self, **kwargs): super(ChannelSelectView, self).__init__(**kwargs) self.register_event_type('on_channel_selected') self.register_event_type('on_channel_cancel') settings = kwargs.get('settings') type = kwargs.get('type') channel = kwargs.get('channel') data = [] channel_list = self.ids.channelList try: for available_channel,channelMeta in settings.runtimeChannels.channels.iteritems(): channel_type = channelMeta.type data.append({'text': available_channel, 'is_selected': False}) args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': dp(50)} list_adapter = ListAdapter(data=data, args_converter=args_converter, cls=ChannelItemButton, selection_mode='single', allow_empty_selection=True) channel_list.adapter=list_adapter list_adapter.bind(on_selection_change=self.on_select) self.channel = channel except Exception as e: Logger.error("ChannelSelectView: Error initializing: " + str(e))
def __init__(self, **kwargs): super().__init__(**kwargs) categories = list() words = list() for entry in database_interface.get_data(database_interface.GUIDELINES.SHELF_TIME, {}): if entry['type'].capitalize() not in words: categories.append(controller.DataItem(text=entry['type'].capitalize())) words.append(entry['type'].capitalize()) list_item_args_converter = lambda row_index, obj: { 'text': obj.text, 'height': 100, 'font_size': 30, 'selected_color': [0.2, 5, 0.5, 1.], 'deselected_color': [1, 1, 1, 1.], 'background_color': [1, 1, 1, 0.], 'background_normal': "Images/Box.png", 'color': [0, 0, 0, 1.], 'padding': (5, 5) } ad = ListAdapter(data=categories, args_converter=list_item_args_converter, propagate_selection_to_data=True, cls=ListItemButton) ad.bind(on_selection_change=self.show_bin_names) self.add_widget(ListView(adapter=ad)) self.add_widget(ListView())
class TestKVfile(BoxLayout): ind, tot = 0,0 def addUrl(self): print self.url_box.text url = newWidget() self.add_widget(url) url.hello.text = self.url_box.text self.url_box.text = "" self.list_adapter = ListAdapter(data=["Item #{0}".format(i) for i in range(10)], cls=ListItemButton, sorted_keys=[]) self.list_adapter.bind(on_selection_change=self.selection_change) list_view = ListView(adapter=self.list_adapter, multiselect=True) self.add_widget(list_view) def selection_change(self, args): print args def sayHello(self): print self.url_box.text print "Hellooooooo" self.ind += 1 if(self.ind == 5): self.ind, self.tot = 0, self.tot+1 self.current_progress.value, self.total_progress.value = self.ind, self.tot self.a = selectList() self.a.open()
def generate_start_screen(self, screen=None): # If we're going back to home after a session # TODO P2: make this more efficient (state last saved flag, for example) if self.cards: self.save_state() self.card_filename = None self.cards = [] self.card_list = [] self.current_card = None self.valid_cards = [] screen.clear_widgets() start_layout = GridLayout(size_hint=(1,1), cols=1, rows=2) self.load_card_lists() empty_cards_list = False if not self.card_list: empty_cards_list = True # No decks on device, so let's try copying over our samples # # This code is hideous because Android returns errors even when things succeed # So we can't trust thrown exceptions! sample_list = glob.glob("samples/*.tsv") if sample_list: for file in sample_list: try: shutil.copy2(file, self.user_data_dir) except: pass self.card_list.append(file[8:]) empty_cards_list = False else: empty_cards_list = True no_cards_label = Label(markup=True, pos=(0,0), font_name='img/ipag.ttf', size_hint=(1,.85), font_size=16, halign="center", text="No tsv files found in " + self.user_data_dir) start_layout.add_widget(no_cards_label) if not empty_cards_list: list_adapter = ListAdapter(data=self.card_list, cls=ListItemButton, args_converter=(lambda row_index, rec: {'text': rec,'height':75}), sorted_keys=[]) list_adapter.bind(on_selection_change=self.select_cards) card_list = ListView(item_strings=self.card_list, adapter=list_adapter, size_hint=(1,.85)) start_layout.add_widget(card_list) file_chooser_btn = Button(text='Import List', size_hint=(1,.15)) file_chooser_btn.bind(on_release=self.go_to_import_screen) start_layout.add_widget(file_chooser_btn) screen.add_widget(start_layout)
class DataScreen(Screen): def __init__(self, **kwargs): super(DataScreen, self).__init__(**kwargs) tab = TabbedPanel() self.th_chart_head = TabbedPanelHeader(text='Chart') tab.default_tab_text = 'Table' self.list_adapter = ListAdapter(data=[], args_converter=self.argsc, cls=TableItemView, selection_mode='single', allow_empty_selection=True) self.list_adapter.bind(on_selection_change=self.selection_changed) list_view = ListView(adapter=self.list_adapter) self.th_chart_head.content = GraphView() tab.default_tab_content = TableView(list_view) tab.add_widget(self.th_chart_head) button = Button(text='Add',size_hint_y=None,height=dp(50)) button.bind(on_release=self.addItem) layout = BoxLayout(orientation='vertical') layout.add_widget(tab) layout.add_widget(button) self.add_widget(layout) def selection_changed(self, *args): i = self.list_adapter.selection[0].parent self.manager.get_screen('editscreen').editEntry(i) self.manager.transition.direction = 'left' self.manager.current = 'editscreen' # self.selected_item = args[0].selection[0].text def addItem(self, *args): self.manager.transition.direction = 'left' self.manager.current = 'editscreen' def argsc(self, row_index, obj): return { 'entrydate': obj[0], 'amount': obj[1], 'gallons': obj[2], 'mileage': obj[3], 'size_hint_y': None, 'height': dp(25), 'index': row_index} def update_list(self, new_list, *args): self.list_adapter.data.append(new_list) temp = TableItemView(entrydate=new_list[0], amount=new_list[1], gallons=new_list[2], mileage=new_list[3], index=0) self.th_chart_head.content.add_point(temp)
def on_text(self, *args): #get text field text text_input_value = self.header_textinput.text #once user has type 3 letters and more, start substring search if len(text_input_value)>2: #if previous listview exists, remove it self.closeListView() #start search, put the response data in a list adapter suggestions = app.datamall_bus_stop.busnamesubstringSearch(text_input_value) #ListitemButton Behaviour args_converter = lambda row_index, rec: { 'text':rec['text'], 'size_hint':(None,None), 'height': '50dp', 'width': self.header_textinput.width } suggestion_listadapter = ListAdapter( data=suggestions, args_converter=args_converter, selection_mode='multiple', selection_limit=1, allow_empty_selection=True, cls=ListItemButton ) #binds each listview button to the autofill function suggestion_listadapter.bind(on_selection_change=self.selection_change) #Logger.info("heightheight"+str(dp(60))) #Logger.info("heightheight"+str(float(dp(50)*len(suggestions)/self.height))) self.suggestion_listview = ListView( adapter=suggestion_listadapter, size_hint_y=(float(dp(50)*len(suggestions)/self.height)) if (float(dp(50)*len(suggestions)/self.height))<0.4 else 0.4, width=self.header_textinput.width, pos_hint={"top":(self.height-self.header_textinput.height*1.3)/self.height}, x=self.header_textinput.x ) #The container is a GridLayout widget held within a ScrollView widget. #So we are giving the ScrollViewParent a custom scroll effect #ListView >> ScrollView >> GridLayout #effect_cls is an ObjectProperty and defaults to DampedScrollEffect. self.suggestion_listview.container.parent.effect_cls = self.scrolleffect #Timeout allowed to trigger the scroll_distance, in milliseconds. If the user has not moved scroll_distance within the timeout, the scrolling will be disabled, and the touch event will go to the children. self.suggestion_listview.container.parent.scroll_distance = 10 self.suggestion_listview.container.parent.scroll_timeout = 1000 self.listview_widget_collector.append(self.suggestion_listview) self.ids['searchbusscreen_floatlayout'].add_widget(self.suggestion_listview) else: #User is deleting his input, so naturally, we shall close the listview (if it exists) self.closeListView()
class ReplayBrowser(ModalView): replay_adpt = ObjectProperty(None) select_callback = ObjectProperty(None) fltr_cb_carry = ObjectProperty(None) fltr_cb_jungler = ObjectProperty(None) fltr_cb_nuker = ObjectProperty(None) fltr_cb_support = ObjectProperty(None) def __init__(self, *args, **kwargs): super(ReplayBrowser, self).__init__(*args, **kwargs) self._refresh_replays() def _refresh_replays(self, hero_types=None): if not hero_types: hero_types = dotalocal.HeroType.all() list_data = [r for r in squeeze.all_replays(squeeze.my_id, hero_types=hero_types, max_results=40)] self.replay_adpt = ListAdapter(data=list_data, args_converter=self._replay_adpt_converter, selection_mode='multiple', template='ReplayListItem') self.replay_adpt.bind(on_selection_change=self._on_replay_select) def _replay_adpt_converter(self, row_idx, record): owner = squeeze.player_from_replay(squeeze.my_id, record.match_id) if owner is not None: hero = dotalocal.hero[owner['hero']] team = owner['team'] else: hero = 'Unknown' team = 'Unknown' is_downloaded = record.match_id in squeeze.local_replay_ids() return {'id': str(record.match_id), 'played': str(record.when), 'hero': hero, 'team': team, 'is_local': is_downloaded} def on_hero_filter_change(self, checkbox): htypes = [] if self.fltr_cb_carry.checkbox.active: htypes.append(dotalocal.HeroType('carry')) if self.fltr_cb_jungler.checkbox.active: htypes.append(dotalocal.HeroType('jungler')) if self.fltr_cb_nuker.checkbox.active: htypes.append(dotalocal.HeroType('nuker')) if self.fltr_cb_support.checkbox.active: htypes.append(dotalocal.HeroType('support')) self._refresh_replays(htypes) def _on_replay_select(self, adpt): if len(adpt.selection) > 0: self.select_callback(adpt.selection[0].text)
class BaseListScreen(BaseScreen): def __init__(self, ws, **kwargs): super(BaseListScreen, self).__init__(ws, **kwargs) args_converter = lambda row_index, x: {'text': Utils.get_title_string(x), 'size_hint_y': None, 'height': 45} self.adapter = ListAdapter(data=[], cls=MopidyListItem, args_converter=args_converter) self.adapter.selection_mode = 'single' self.ids.list_view.adapter = self.adapter self.adapter.bind(on_selection_change=self.on_selection_change) def on_selection_change(self, adapter): pass
def show_choose_mylist(self): adapter_items = [] for dict_item in self.mylist_items: mylist_item = {"text": dict_item["name"], "is_selected": False} adapter_items.append(mylist_item) args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': 25} list_adapter = ListAdapter(data=adapter_items, args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) list_adapter.bind(on_selection_change=self.set_mylist_name) self.modal = ListViewModal(list_adapter) self.modal.open()
def init_list_adapter_alphabet(self): """'Initialise les données de la liste de l'alphabet""" self.list_adapter_alphabet = ListAdapter( data=[ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ], cls=ListItemButton, sorted_keys=[], selection_mode="multiple", )
def __init__(self, **kwargs): self.controller = kwargs.pop('controller', None) super(InputScreen, self).__init__(**kwargs) self.cols = 2 # Text input self.text = ShortcutTextInput(multiline=True, focus=True, keyboard_handler=self._on_keyboard_down) self.add_widget(self.text) self.text.bind(text=self._on_text) self.text.hint_text="Begin typing to test text prediction." # predictions obj_printer = lambda obj: "{} - {}".format(str(obj), self.current_prediction.get(obj, 0)) args_converter = lambda row_index, obj: {'text': obj_printer(obj), 'size_hint_y': None, 'height': 25} self.prediction_adapter = ListAdapter(data=[], args_converter=args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemLabel) self.prediction_list = ListView(adapter=self.prediction_adapter) self.add_widget(self.prediction_list) self.current_prediction = FreqDist() # Record history self.previous_record = None self.in_word = False
def __init__(self, **kwargs): super(CatanGUI, self).__init__(**kwargs) self.board = CatanBoard() self.mode = 'Thin' self.board.grid = self.board.ini_Grid() self.hexSize = 40 self.hexHeight = self.hexSize * 2 self.hexVert = 0.75 * self.hexHeight self.hexWidth = sqrt(3)/2 * self.hexHeight self.rows = 2 self.gridCanvas = Widget() self.gridCanvas.bind(pos=self.update_gridCanvas) self.gridCanvas.bind(size=self.update_gridCanvas) self.UI = GridLayout(cols=2, size_hint_y=0.2) self.randomiseButton = Button(text='Randomise') self.randomiseButton.bind(on_press=self.randomise_Grid) self.list_Adapter = ListAdapter(data=['Coastal', 'Thin Land Mass', 'Large Land Mass', 'Large Islands', 'Small Islands', 'Random'], cls=ListItemButton, selection_mode='single', allow_empty_selection=True) self.list_Adapter.bind(on_selection_change=self.item_Selected) self.random_Type = ListView(adapter=self.list_Adapter) self.UI.add_widget(self.random_Type) self.UI.add_widget(self.randomiseButton) self.add_widget(self.gridCanvas) self.add_widget(self.UI) self.startingX = self.gridCanvas.center_x self.startingY = self.gridCanvas.center_y + (self.gridCanvas.height * 6)
def init_list_adapter_alphabet(self): ''''Initialise les données de la liste de l'alphabet''' if self.status_ville_depart == None: self.list_adapter_alphabet = ListAdapter( data=gestion_bd.select_alphabet_ville_depart(), cls=ListItemButton, sorted_keys=[], selection_mode='multiple', ) else: self.list_adapter_alphabet = ListAdapter( data=gestion_bd.select_alphabet_ville_arriver(self.ville_depart), cls=ListItemButton, sorted_keys=[], selection_mode='multiple', )
def __init__(self, color=(0, 0, 0), **kwargs): super(Bluetooth_Screen, self).__init__(**kwargs) with self.canvas.before: Color(color[0] / 256., color[1] / 256., color[2] / 256.) self.rect = Rectangle(size=self.size) self.name_dict = {} args_converter = lambda row_index, data_item: {'text': data_item.name, 'mac_addr': data_item.mac_addr, 'size_hint_y': None, 'height': 25} self.adapter = ListAdapter(data=[], args_converter=args_converter, cls=CustomListItemButton, selection_mode='single') self.adapter.bind(on_selection_change=self.item_selected) self.discovered_list = ListView(size_hint=(.5, .5), adapter=self.adapter) self.add_widget(self.discovered_list) self.info_label = Label(size_hint=(.5, None), height=30) self.add_widget(self.info_label) self.connect_button = Button(text='Connect', disabled=True, size_hint=(None, None), width=100, height=30, pos_hint={'center_x': .5, 'y': 0}) self.connect_button.bind(on_press=self.connect) self.add_widget(self.connect_button) self.send_text = TextInput(text='Insert text to send', size_hint=(None, None), size=(200, 30), pos_hint={'center_x': .5}, multiline=False, disabled= True) self.send_text.bind(on_text_validate=self.send) self.add_widget(self.send_text) self.bind(size=self.update)
def __init__(self, **kwargs): super(DataScreen, self).__init__(**kwargs) tab = TabbedPanel() self.th_chart_head = TabbedPanelHeader(text='Chart') tab.default_tab_text = 'Table' self.list_adapter = ListAdapter(data=[], args_converter=self.argsc, cls=TableItemView, selection_mode='single', allow_empty_selection=True) self.list_adapter.bind(on_selection_change=self.selection_changed) list_view = ListView(adapter=self.list_adapter) self.th_chart_head.content = GraphView() tab.default_tab_content = TableView(list_view) tab.add_widget(self.th_chart_head) button = Button(text='Add',size_hint_y=None,height=dp(50)) button.bind(on_release=self.addItem) layout = BoxLayout(orientation='vertical') layout.add_widget(tab) layout.add_widget(button) self.add_widget(layout)
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)
class Thes(CustomScreen): currentCategorie = None def __init__(self, **kwargs): super(Thes, self).__init__(**kwargs) # initialisation avec liste vide self.initializeListAdapter( [] ) def initializeListAdapter(self, dataObject): list_item_args_converter = \ lambda row_index, obj: {'text': self.currentCategorie["teas"][obj]['tealbnom'], 'id': "theindex_%d" % row_index, 'is_selected': False, 'size_hint_y': None, 'height': 25} self.my_adapter = ListAdapter(data = dataObject, args_converter=list_item_args_converter, selection_mode='single', allow_empty_selection=True, template='CustomListItemThes') self.my_adapter.bind(on_selection_change=self.the_changed) self.containerListView.adapter = self.my_adapter def the_changed(self, adapter, *args): if len(adapter.selection) == 0: return theId = adapter.data[adapter.selection[0].parent.index] theSelectionne = self.currentCategorie["teas"][theId] adapter.selection[0].deselect() self.manager.go_next() self.manager.current_screen.chargeInfos(theSelectionne, self.currentCategorie["catlblib"]) def setCurrentCategorie(self, categorie): '''Mise à jour de la liste de thés disponibles ''' categoryId = categorie['catidcat'] categorie["teas"] = JsonToDataBase().getAllTeasForCategory(categoryId) self.currentCategorie = categorie self.nomcategorieLabel.text = "TeaTime > %s" % self.currentCategorie["catlblib"] self.initializeListAdapter( self.currentCategorie["teas"] ) self.logLabel.text = "Nombre de thés: %s" % len(self.currentCategorie["teas"])
def init_list_adapter_arret(self, donnee): '''Initialise les données de la liste des arrets''' self.list_adapter_arret = ListAdapter( data=donnee, cls=ListItemButton, sorted_keys=[], selection_mode='multiple', )
def updateDisplay(self): list_item_args_converter = \ lambda row_index, obj: {'text': self.categories[obj]['catlblib'], 'index': row_index, 'id': "categorieindex_%d" % row_index, 'is_selected': False, 'size_hint_y': None, 'height': 25} my_adapter = ListAdapter(data = self.categories, args_converter=list_item_args_converter, selection_mode='single', allow_empty_selection=True, template='CustomListItemCategories') my_adapter.bind(on_selection_change=self.categorie_changed) self.containerListView.adapter = my_adapter
def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.orientation = 'vertical' """ create the manager """ self.sm = ScreenManager(transition=RiseInTransition()) """ create a few screens """ self.mainMenu = Screen(name='mainMenu') self.serverKey = Screen(name='serverKey') self.listScreen = Screen(name='fileList') """ the menu screen manipulations """ self.menu = MainMenu() self.menu.serverKeyBut.bind(on_release=self.goto_serverKey) self.menu.uploadMainBut.bind(on_release=self.show_upload) self.menu.listMainBut.bind(on_release=self.show_list) """ the key screen manipulations """ self.key = ServerKey() self.key.textKey.text = state_handler.get_token() self.key.saveKey.bind(on_release=self.save_key) self.key.cancelKey.bind(on_release=self.cancel_key) """ the list screen manipulations """ self.listing = BoxLayout(orientation="vertical") sublistingMenu = BoxLayout(orientation="horizontal", size_hint_y=0.2) copyBut = Button(text="copy") sublistingMenu.add_widget(copyBut) copyBut.bind(on_release=self.copy_to_clipboard_files) refreshBut = Button(text="refresh") sublistingMenu.add_widget(refreshBut) refreshBut.bind(on_release=self.refresh_file_list) delBut = Button(text="del") sublistingMenu.add_widget(delBut) delBut.bind(on_release=self.delete_file_list) self.listing.add_widget(sublistingMenu) self.data_items = [] for key in state_handler.get_file_list().keys(): self.data_items.append(DataItem(text=key)) list_item_args_converter = lambda row_index, obj: { 'text': obj.text, 'size_hint_y': None, 'height': 25 } self.list_adapter = ListAdapter( data=self.data_items, args_converter=list_item_args_converter, selection_mode='multiple', propagate_selection_to_data=True, allow_empty_selection=True, cls=ListItemButton) self.list_view = ListView(adapter=self.list_adapter) self.listing.add_widget(self.list_view) cancelBut = Button(text="cancel", size_hint_y=0.2) cancelBut.bind(on_release=self.cancel_key) self.listing.add_widget(cancelBut) """ appending the screens to the screen manager """ self.mainMenu.add_widget(self.menu) self.serverKey.add_widget(self.key) self.listScreen.add_widget(self.listing) self.sm.add_widget(self.mainMenu) self.sm.add_widget(self.serverKey) self.sm.add_widget(self.listScreen) """ go directly to key screen if the key isn't set yet """ if state_handler.get_token() == "": self.sm.current = 'serverKey' else: self.sm.current = 'mainMenu' """ add all the widgets """ title = TitleBar() self.add_widget(title) self.add_widget(self.sm)
class PopupListView(FlatPopup): ''' When a click on this button occur, a popup will be shown to pick a value. Arguments named popup_* will be passed down to the popup for customizations. To customize ListItemButton selected_color and deselected_color please use kv lang. ''' item_row_height = NumericProperty(dp(40)) '''Height of rows shown by the popup .. versionadded:: 1.0 :attr:`item_row_height` is a :class:`~kivy.properties.NumericProperty`, default to 40. ''' selected = ObjectProperty(None) '''Data selected. .. versionadded:: 1.0 :attr:`selected` is a :class:`~kivy.properties.ObjectProperty`. ''' selected = ObjectProperty(None) '''Index of selected data. .. versionadded:: 1.0 :attr:`selected` is a :class:`~kivy.properties.ObjectProperty`. ''' on_selection = ObjectProperty(None) '''Called whenever a value is selected, see 'on_selection_change' method code. .. versionadded:: 1.0 :attr:`on_selection` is a :class:`~kivy.properties.ObjectProperty`. ''' def __init__(self, list_data, **kargs): super(PopupListView, self).__init__(**kargs) self.list_data = self.build_list_data(list_data) self.content = self._build_list_view(kargs) def _build_list_view(self, kargs): self._list_view = ListView(adapter=self._build_adapter(), propagate_selection_to_data=True) return self._list_view def build_list_data(self, data): if len(data) > 0: if data[0].__class__ == str: l2dict = [{ 'is_selected': False, 'rowid': 0, 'label': x } for x in data] return self.build_list_data(l2dict) else: result = data if 'is_selected' not in data[0].keys(): result = [] for x in data: x['is_selected'] = False result.append(x) return result return [] def show_choices(self, *args): self.open() def adapter_converter(self): return lambda i, o : { \ 'is_selected' : o['is_selected'], \ 'size_hint_y' : None, \ 'height' : self.item_row_height, \ 'text' : o['label'], \ 'rowid' : o['rowid'] \ } def _build_adapter(self): self.list_adapter = ListAdapter( cls=ListItemButton, data=self.list_data, args_converter=self.adapter_converter(), selection_mode='single', allow_empty_selection=True) self.list_adapter.bind(on_selection_change=self.on_selection_change) return self.list_adapter def on_selection_change(self, adapter, *args): if (adapter.selection): self.selected_index = adapter.selection[0].index self.selected = self.list_data[self.selected_index] if self.on_selection: self.on_selection(self, self.selected, self.selected_index) self.dismiss() def select(self, i): self.list_adapter.get_view(i).trigger_action(duration=0)
def update_tune_list(self): data = sorted(self.mma_library.get_match(self.selected_grooves())) self.tune_list.adapter = ListAdapter(data=data, selection_mode='single', allow_empty_selection=False, cls=ListItemButton)
class Watermark(Screen): loadfile = ObjectProperty(None) text_input = ObjectProperty(None) def __init__(self, **kwargs): super(Watermark, self).__init__(**kwargs) print(Window.size) # init and add grid layer # self.cols = 2 # self.layout = GridLayout(cols=self.cols) # self.add_widget(self.layout) # function to set the buttons based on the current window size # self.set_content(Window.width, Window.height) # bind above function to get called whenever the window resizes # Window.bind(on_resize=self.set_content) # self._popup = ObjectProperty(None) def load(self, path, filename): try: if not filename == []: print(os.path.join(os.path.realpath(path), filename[0])) self.text_input.text = "" self.save_input.text = "" self.text_input.text = str(os.path.join(os.path.realpath(path), filename[0])) print(str(os.path.realpath(path))+"/wmarked_"+str(filename[0])) self.save_input.text = str(os.path.realpath(path))+"/wmarked_"+str(filename[0]) self.img.source = self.text_input.text # self.img2.source = self.text_input.text print(self.img.image_ratio) else: print(os.path.realpath(path)) self.text_input.text = "" self.save_input.text = "" self.text_input.text = str(os.path.realpath(path)) self.save_input.text = str(os.path.realpath(path)) self.load_images(self) self.dismiss_popup() except Exception as ex: pass def show_load(self): content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def dismiss_popup(self): self._popup.dismiss() def wmark_text_clear(self): self.wmark.text = "" def watermark_work(self, filename,wmark_text,save_img): try: filters = ['jpg', 'png', 'jpeg', 'JPG', 'PNG'] filename = self.text_input.text for i in filters: if re.search(i,filename): main = Image.open(filename) else: for k in self.d: filename+="/"+k main=Image.open(filename) filename="" # Open the original image #main = Image.open(filename) # Create a new image for the watermark with an alpha layer (RGBA) # the same size as the original image watermark = Image.new("RGBA", main.size) # Get an ImageDraw object so we can draw on the image waterdraw = ImageDraw.ImageDraw(watermark, "RGBA") # Place the text at (10, 10) in the upper left corner. Text will be white. font_path = "Copperplate.ttc" font = ImageFont.truetype(font_path, 250) im = Image.open(filename) width, height = im.size print(height) print(width) waterdraw.text((width / 2, height / 2), wmark_text, fill=(255, 255, 255, 128), font=font) # Get the watermark image as grayscale and fade the image # See <http://www.pythonware.com/library/pil/handbook/image.htm#Image.point> # for information on the point() function # Note that the second parameter we give to the min function determines # how faded the image will be. That number is in the range [0, 256], # where 0 is black and 256 is white. A good value for fading our white # text is in the range [100, 200]. watermask = watermark.convert("L").point(lambda x: min(x, 255)) # Apply this mask to the watermark image, using the alpha filter to # make it transparent watermark.putalpha(watermask) # Paste the watermark (with alpha layer) onto the original image and save it main.paste(watermark, (0, 0), watermark) main.save(save_img) except Exception as ex: print(str(ex)) def load_images(self,adapter, *args): try: self.d = [] self.lview.item_strings.clear() filters= ['jpg', 'png', 'jpeg', 'JPG', 'PNG'] data =[{"text":str(i)} for i in os.listdir(self.text_input.text) for k in filters if re.search(k,i)] args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None,'height': 30} self.list_adapter = ListAdapter(data=data, args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) self.lview.adapter = self.list_adapter for i in range(self.list_adapter.get_count()): self.d.append(self.list_adapter.data[i]["text"]) self.list_adapter.adapter.bind(on_selected_item=self.callback) except: pass def callback(self,adapter,*args): if len(self.adapter.selection) == 0: print("No selected item") else: print(self.adapter.selection[0].text)
class CompletionBubble(Bubble): list_view = ObjectProperty(None, allownone=True) '''(internal) Reference a ListView with a list of SuggestionItems :data:`list_view` is a :class:`~kivy.properties.ObjectProperty` ''' adapter = ObjectProperty(None) '''(internal) Reference a ListView adapter :data:`adapter` is a :class:`~kivy.properties.ObjectProperty` ''' __events__ = ( 'on_complete', 'on_cancel', ) def __init__(self, **kwargs): super(CompletionBubble, self).__init__(**kwargs) Window.bind(on_touch_down=self.on_window_touch_down) def on_window_touch_down(self, win, touch): '''Disable the completion if the user clicks anywhere ''' if not self.collide_point(*touch.pos): self.dispatch('on_cancel') def _create_list_view(self, data): '''Create the ListAdapter ''' self.adapter = ListAdapter(data=data, args_converter=self._args_converter, cls=SuggestionItem, selection_mode='single', allow_empty_selection=False) self.adapter.bind(on_selection_change=self.on_selection_change) self.list_view = CompletionListView(adapter=self.adapter) self.add_widget(self.list_view) def _args_converter(self, index, completion): return { 'text': completion.name, 'is_selected': False, 'complete': completion.complete, 'selected_by_touch': self.selected_by_touch } def selected_by_touch(self, item): self.dispatch('on_complete', item.complete) def show_completions(self, completions, force_scroll=False): '''Update the Completion ListView with completions ''' if completions == []: fake_completion = type('obj', (object, ), { 'name': 'No suggestions', 'complete': '' }) completions.append(fake_completion) Window.bind(on_key_down=self.on_key_down) if not self.list_view: self._create_list_view(completions) else: self.adapter.data = completions if force_scroll: self.list_view.scroll_to(0) def on_selection_change(self, *args): pass def _scroll_item(self, new_index): '''Update the scroll view position to display the new_index item ''' item = self.adapter.get_view(new_index) if item: item.trigger_action(0) if new_index > 2 and new_index < len(self.adapter.data) - 1: self.list_view.scroll_to(new_index - 3) def on_key_down(self, instance, key, *args): '''Keyboard listener to grab key codes and interact with the Completion box ''' selected_item = self.adapter.selection[0] selected_index = selected_item.index if self.list_view.scrolled: # recreate list view after mouse scroll due to the bug kivy/#3418 self.remove_widget(self.list_view) self.list_view = None self.show_completions(self.adapter.data) return self.on_key_down(instance, key, args) if key == 273: # up if selected_index > 0: self._scroll_item(selected_index - 1) return True elif key == 274: # down if selected_index < len(self.adapter.data) - 1: self._scroll_item(selected_index + 1) return True elif key in [9, 13, 32]: # tab, enter or space self.dispatch('on_complete', selected_item.complete) return True else: # another key cancel the completion self.dispatch('on_cancel') return False def reposition(self, pos, line_height): '''Update the Bubble position. Try to display it in the best place of the screen ''' win = Window self.x = pos[0] - self.width / 2 self.y = pos[1] - self.height - line_height # fit in the screen horizontally if self.right > win.width: self.x = win.width - self.width if self.x < 0: self.x = 0 # fit in the screen vertically if self.y < 0: diff = abs(self.y) # check if we can move it to top new_y = pos[1] + line_height if new_y + self.height < win.height: # fit in the screen self.y = new_y else: # doesnt fit on top neither on bottom. Check the best place new_diff = abs(new_y + self.height - win.height) if new_diff < diff: # if we lose lest moving it to top self.y = new_y # compare the desired position with the actual position x_relative = self.x - (pos[0] - self.width / 2) x_range = self.width / 4 # consider 25% as the range def _get_hpos(): '''Compare the position of the widget with the parent to display the arrow in the correct position ''' _pos = 'mid' if x_relative == 0: _pos = 'mid' elif x_relative < -x_range: _pos = 'right' elif x_relative > x_range: _pos = 'left' return _pos if self.y == pos[1] - self.height - line_height: self.arrow_pos = 'top_' + _get_hpos() else: self.arrow_pos = 'bottom_' + _get_hpos() def on_complete(self, *args): '''Dispatch a completion selection ''' Window.unbind(on_key_down=self.on_key_down) def on_cancel(self, *args): '''Disable key listener on cancel ''' Window.unbind(on_key_down=self.on_key_down)
class Bluetooth_Screen(Screen): def __init__(self, color=(0, 0, 0), **kwargs): super(Bluetooth_Screen, self).__init__(**kwargs) with self.canvas.before: Color(color[0] / 256., color[1] / 256., color[2] / 256.) self.rect = Rectangle(size=self.size) self.name_dict = {} args_converter = lambda row_index, data_item: { 'text': data_item.name, 'mac_addr': data_item.mac_addr, 'size_hint_y': None, 'height': 25 } self.adapter = ListAdapter(data=[], args_converter=args_converter, cls=CustomListItemButton, selection_mode='single') self.adapter.bind(on_selection_change=self.item_selected) self.discovered_list = ListView(size_hint=(.5, .5), adapter=self.adapter) self.add_widget(self.discovered_list) self.info_label = Label(size_hint=(.5, None), height=30) self.add_widget(self.info_label) self.connect_button = Button(text='Connect', disabled=True, size_hint=(None, None), width=100, height=30, pos_hint={ 'center_x': .5, 'y': 0 }) self.connect_button.bind(on_press=self.connect) self.add_widget(self.connect_button) self.send_text = TextInput(text='Insert text to send', size_hint=(None, None), size=(200, 30), pos_hint={'center_x': .5}, multiline=False, disabled=True) self.send_text.bind(on_text_validate=self.send) self.add_widget(self.send_text) self.bind(size=self.update) def update(self, *args): self.rect.size = self.size self.discovered_list.pos_hint = {'center_x': .5, 'center_y': .5} self.info_label.pos_hint = {'center_y': .8, 'center_x': .5} self.send_text.y = self.y + 30 def builder(self): self.add_widget( Menu_Button(size_hint=[.1, .1], text='Go Back', screenmanager=self.manager, screen='menu')) self.discover_button = Menu_Button(size_hint=[.1, .1], pos_hint={'right': 1}, text='Discover') self.add_widget(self.discover_button) self.discover_button.bind(on_press=self.start_discover) def start_discover(self, *args): Clock.schedule_interval(self.discover, .5) def discover(self, *args): if not self.discover_button.disabled: self.discover_button.disabled = True self.info_label.text = "Discovering devices..." discover_thread = Thread(target=bluet.discover_thread, args=(queue, )) discover_thread.start() items = [] if not queue.empty(): discovered = queue.get() for x in discovered: items.append(DataItem(x, discovered[x])) self.adapter.data = items self.discover_button.disabled = False self.info_label.text = "Select device" Clock.unschedule(self.discover) def item_selected(self, *args): try: self.selected_item = args[0].selection[0] text = 'Device selected MAC: ' + self.selected_item.mac_addr self.info_label.text = text self.connect_button.disabled = False except: self.info_label.text = "No device selected" self.connect_button.disabled = True def connect(self, *args): self.bt_socket = bluet.connect(self.selected_item.mac_addr, 1) self.send_text.disabled = False self.info_label.text = 'Connected' def send(self, *args): self.bt_socket.send(self.send_text.text + '\n')
def __init__(self, **kwargs): kwargs['cols'] = 3 super(CascadingView, self).__init__(**kwargs) list_item_args_converter = \ lambda row_index, selectable: {'text': selectable.name, 'size_hint_y': None, 'height': 25} # Add a fruit categories list on the left. We use ListAdapter, for # which we set the data argument to the list of CategoryItem # instances from above. The args_converter only pulls the name # property from these instances, adding also size_hint_y and height. # selection_mode is single, because this list will "drive" the second # list defined below. allow_empty_selection is False, because we # always want a selected category, so that the second list will be # populated. Finally, we instruct ListAdapter to build list item views # using the provided cls, ListItemButton. # fruit_categories_list_adapter = \ ListAdapter(data=category_data_items, 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, are in a list in the middle, which # uses FruitsListsAdapter, defined above. FruitsListAdapter has a # fruit_changed() method that updates the data list. The binding # to the fruit_categories_list_adapter is set up after # instantiation of the fruit_list_adapter. # first_category_fruits = \ fruit_categories[list(fruit_categories.keys())[0]]['fruits'] first_category_fruit_data_items = \ [f for f in fruit_data_items if f.name in first_category_fruits] fruits_list_adapter = \ FruitsListAdapter(data=first_category_fruit_data_items, args_converter=list_item_args_converter, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) fruit_categories_list_adapter.bind( on_selection_change=fruits_list_adapter.fruit_category_changed) fruits_list_view = \ ListView(adapter=fruits_list_adapter, size_hint=(.2, 1.0)) self.add_widget(fruits_list_view) # Detail view, for a given fruit, on the right: # detail_view = FruitDetailView( fruit_name=fruits_list_adapter.selection[0].text, size_hint=(.6, 1.0)) fruits_list_adapter.bind(on_selection_change=detail_view.fruit_changed) self.add_widget(detail_view)
def createaccordion(self, orderstable): #accordion view orders app = App.get_running_app() self.myaccordion = Accordion(orientation='vertical', size_hint=(1.0, 1.0)) if type(orderstable) == list: #new orders save view accordion for element in orderstable: orderid = element['_id'] acc_item = MyAccordionItem(title='order') self.lv_accordion = ListView() #listview inside accordion args_converter_accordion = lambda row_index, rec: \ {'product':rec['product_name'], 'price':rec['price'], 'mychoices':rec['mychoices']} lvaccordion_adapter = ListAdapter( data=[], args_converter=args_converter_accordion, selection_mode='none', allow_empty_selection=True, cls='ManagerListItem') self.lv_accordion.adapter = lvaccordion_adapter acc_item.add_widget(self.lv_accordion) self.lv_accordion.adapter.data = element['items'] acc_item.add_widget( SqrYelButton(text='pay', pos_hint={ 'x': .2, 'y': .10 }, on_press=partial(self.pay_order, orderid))) acc_item.add_widget( SqrYelButton(text='edit', pos_hint={ 'x': .2, 'y': .10 }, on_press=partial(self.edit, orderid))) self.myaccordion.add_widget(acc_item) else: #view for update view accordion orderid = orderstable['_id'] acc_item = MyAccordionItem(title='order') self.lv_accordion = ListView() args_converter_accordion = lambda row_index, rec: \ {'product':rec['product_name'], 'price':rec['price'], 'mychoices':rec['mychoices']} lvaccordion_adapter = ListAdapter( data=[], args_converter=args_converter_accordion, selection_mode='none', allow_empty_selection=True, cls='ManagerListItem') self.lv_accordion.adapter = lvaccordion_adapter acc_item.add_widget(self.lv_accordion) self.lv_accordion.adapter.data = orderstable['items'] acc_item.add_widget( SqrYelButton(text='pay', pos_hint={ 'x': .2, 'y': .10 }, on_press=partial(self.pay_order, orderid))) acc_item.add_widget( SqrYelButton(text='edit', pos_hint={ 'x': .2, 'y': .10 }, on_press=partial(self.edit, orderid))) self.myaccordion.add_widget(acc_item) self.total_order() app.root.management_scr.items_acc.add_widget(self.myaccordion)
class NewProjectDialog(BoxLayout): listview = ObjectProperty(None) ''':class:`~kivy.uix.listview.ListView` used for showing file paths. :data:`listview` is a :class:`~kivy.properties.ObjectProperty` ''' select_button = ObjectProperty(None) ''':class:`~kivy.uix.button.Button` used to select the list item. :data:`select_button` is a :class:`~kivy.properties.ObjectProperty` ''' cancel_button = ObjectProperty(None) ''':class:`~kivy.uix.button.Button` to cancel the dialog. :data:`cancel_button` is a :class:`~kivy.properties.ObjectProperty` ''' adapter = ObjectProperty(None) ''':class:`~kivy.uix.listview.ListAdapter` used for selecting files. :data:`adapter` is a :class:`~kivy.properties.ObjectProperty` ''' image = ObjectProperty(None) '''Type of :class:`~kivy.uix.image.Image` to display image of selected new template. :data:`image` is a :class:`~kivy.properties.ObjectProperty` ''' list_parent = ObjectProperty(None) '''Parent of listview. :data:`list_parent` is a :class:`~kivy.properties.ObjectProperty` ''' prev_selection = NumericProperty(0) '''to memorize the previous selection. :attr:`prev_selection` is a :class: `~kivy.properties.NumericProperty`, defaults to (0). ''' __events__ = ('on_select', 'on_cancel') def __init__(self, **kwargs): super(NewProjectDialog, self).__init__(**kwargs) item_strings = list(NEW_PROJECTS.keys()) item_strings.sort() self.adapter = ListAdapter(cls=Factory.DesignerListItemButton, data=item_strings, selection_mode='single', allow_empty_selection=False) self.adapter.check_for_empty_selection = self.check_for_empty_selection self.adapter.bind(on_selection_change=self.on_adapter_selection_change) self.listview = ListView(adapter=self.adapter) self.listview.size_hint = (0.5, 1) self.listview.pos_hint = {'top': 1} self.list_parent.add_widget(self.listview, 1) self.on_adapter_selection_change(self.adapter) def on_parent(self, *args): if self.parent: Window.bind(on_key_down=self._on_keyboard_down) else: Window.unbind(on_key_down=self._on_keyboard_down) def _on_keyboard_down(self, keyboard, key, codepoint, text, modifier, *args): '''To detect which key is pressed ''' if modifier: return False key_str = Keyboard.keycode_to_string(Window._system_keyboard, key) if key_str == 'up': v = self.adapter.get_view(self.prev_selection - 1) if v is not None: self.adapter.handle_selection(v) return True if key_str == 'down': v = self.adapter.get_view(self.prev_selection + 1) if v is not None: self.adapter.handle_selection(v) return True if key_str == 'enter': self.dispatch('on_select') return True def check_for_empty_selection(self, *args): if not self.adapter.allow_empty_selection: if len(self.adapter.selection) == 0: # Select the first item if we have it. v = self.adapter.get_view(self.prev_selection) if v is not None: self.adapter.handle_selection(v) def on_adapter_selection_change(self, adapter): '''Event handler for 'on_selection_change' event of adapter. ''' name = adapter.selection[0].text.lower() + '.png' name = name.replace(' and ', '_') image_source = join(NEW_TEMPLATE_IMAGE_PATH, name) _dir = get_kd_dir() image_source = join(_dir, image_source) parent = self.image.parent parent.remove_widget(self.image) self.image = Image(source=image_source) parent.add_widget(self.image) self.prev_selection = adapter.data.index(adapter.selection[0].text) def on_touch_down(self, touch): '''Used to determine where touch is down and to detect double tap. ''' if touch.is_double_tap: self.dispatch('on_select') return super(NewProjectDialog, self).on_touch_down(touch) def on_select(self, *args): '''Default Event Handler for 'on_select' event ''' pass def on_cancel(self, *args): '''Default Event Handler for 'on_cancel' event ''' pass def on_select_button(self, *args): '''Event Handler for 'on_release' of select button. ''' self.select_button.bind(on_press=partial(self.dispatch, 'on_select')) def on_cancel_button(self, *args): '''Event Handler for 'on_release' of cancel button. ''' self.cancel_button.bind(on_press=partial(self.dispatch, 'on_cancel'))
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 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'] } }] }
def on_lect_select(self, dropdown, txt): """ This method updates GUI according to selected lecture. :param self: It is for handling class structure. :param dropdown: It is dropdown menu. :param txt: It is lecture code selected on dropdown menu. :return: """ try: self.check_live_exam.cancel() except: pass finally: Clock.schedule_once(partial(check_live_exam.is_active, self ) ) self.check_live_exam = Clock.schedule_interval(partial(check_live_exam.is_active, self ), 5.0 ) dropdown.select(txt) self.ids["txt_hint"].opacity = 0 self.ids["btn_exams"].disabled = False self.ids["btn_stats_personal"].disabled = False self.ids["txt_lect_code"].opacity = 1 self.ids["txt_lect_name"].opacity = 1 for lect in self.data: if txt in lect.replace("_", " ").upper(): self.ids["txt_lect_code"].text = txt self.ids["txt_lect_name"].text = " ".join(lect.split("_")[2:]).title() Cache.append("lect", "code", txt ) Cache.append("lect", "name", self.ids["txt_lect_name"].text ) break self.ids["layout_exams"].opacity = 1 self.data_exams = database_api.getExamsOfLecture(Cache.get("info", "token"), self.ids["txt_lect_code"].text ) args_converter = lambda row_index, x: {"text": x.replace("_", " ").title(), "selected_color": (.843, .82, .82, 1), "deselected_color": (.57, .67, .68, 1), "background_down": "data/img/widget_gray_75.png", "font_name": "data/font/CaviarDreams_Bold.ttf", "font_size": self.height / 25, "size_hint_y": None, "height": self.height / 10 } self.ids["list_exams"].adapter = ListAdapter(data=[i[1] for i in self.data_exams], cls=ListItemButton, args_converter=args_converter, allow_empty_selection=False ) self.ids["list_exams"].adapter.bind(on_selection_change=partial(on_exam_select, self ) )
class MainScreen(BoxLayout): list_adapter = ListAdapter(data="", cls=ListItemButton) list_view = ListView() _popup = Popup() counter = 0 def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.orientation = 'vertical' """ create the manager """ self.sm = ScreenManager(transition=RiseInTransition()) """ create a few screens """ self.mainMenu = Screen(name='mainMenu') self.serverKey = Screen(name='serverKey') self.listScreen = Screen(name='fileList') """ the menu screen manipulations """ self.menu = MainMenu() self.menu.serverKeyBut.bind(on_release=self.goto_serverKey) self.menu.uploadMainBut.bind(on_release=self.show_upload) self.menu.listMainBut.bind(on_release=self.show_list) """ the key screen manipulations """ self.key = ServerKey() self.key.textKey.text = state_handler.get_token() self.key.saveKey.bind(on_release=self.save_key) self.key.cancelKey.bind(on_release=self.cancel_key) """ the list screen manipulations """ self.listing = BoxLayout(orientation="vertical") sublistingMenu = BoxLayout(orientation="horizontal", size_hint_y=0.2) copyBut = Button(text="copy") sublistingMenu.add_widget(copyBut) copyBut.bind(on_release=self.copy_to_clipboard_files) refreshBut = Button(text="refresh") sublistingMenu.add_widget(refreshBut) refreshBut.bind(on_release=self.refresh_file_list) delBut = Button(text="del") sublistingMenu.add_widget(delBut) delBut.bind(on_release=self.delete_file_list) self.listing.add_widget(sublistingMenu) self.data_items = [] for key in state_handler.get_file_list().keys(): self.data_items.append(DataItem(text=key)) list_item_args_converter = lambda row_index, obj: { 'text': obj.text, 'size_hint_y': None, 'height': 25 } self.list_adapter = ListAdapter( data=self.data_items, args_converter=list_item_args_converter, selection_mode='multiple', propagate_selection_to_data=True, allow_empty_selection=True, cls=ListItemButton) self.list_view = ListView(adapter=self.list_adapter) self.listing.add_widget(self.list_view) cancelBut = Button(text="cancel", size_hint_y=0.2) cancelBut.bind(on_release=self.cancel_key) self.listing.add_widget(cancelBut) """ appending the screens to the screen manager """ self.mainMenu.add_widget(self.menu) self.serverKey.add_widget(self.key) self.listScreen.add_widget(self.listing) self.sm.add_widget(self.mainMenu) self.sm.add_widget(self.serverKey) self.sm.add_widget(self.listScreen) """ go directly to key screen if the key isn't set yet """ if state_handler.get_token() == "": self.sm.current = 'serverKey' else: self.sm.current = 'mainMenu' """ add all the widgets """ title = TitleBar() self.add_widget(title) self.add_widget(self.sm) """ start of callback foos """ def goto_serverKey(self, object): self.sm.current = "serverKey" def save_key(self, object): state_handler.store_token(self.key.textKey.text) self.sm.current = "mainMenu" def cancel_key(self, object): self.sm.current = "mainMenu" self.update_list() def show_list(self, object): self.sm.current = "fileList" def show_upload(self, object): content = uploadDialog(load=self.upload, cancel=self.dismiss_popup) self._popup = Popup(title="Upload", content=content, size_hint=(0.9, 0.9)) self._popup.open() def upload(self, path, filename): if len(filename) == 0: return self.dismiss_popup() file_name = os.path.join(path, filename[0]) #uploading file result = ioup.upload_file(state_handler.get_token(), file_name) if result == " ": self.error("Cannot upload file " + file_name) return droid.setClipboard(result.encode('utf-8')) #updating the list result2 = ioup.check_list(state_handler.get_token()) if result2 == {" ": " "}: self.error("Wasn't able to refresh list") return state_handler.store_file_list(result2) self.update_list() self.dismiss_popup() content = BoxLayout(orientation='vertical') content.add_widget( Label(text="Uploaded Successfully: \n" + file_name + "\n" + result)) closeButton = Button(text='OK', size_hint_y=0.15) content.add_widget(closeButton) self._popup = Popup(title='Uploaded', content=content, size_hint=(0.8, 0.8)) closeButton.bind(on_press=self._popup.dismiss) self._popup.open() def dismiss_popup(self): self.outputing = False self._popup.dismiss() def error(self, message): self.dismiss_popup() content = BoxLayout(orientation='vertical') content.add_widget(Label(text=message)) closeButton = Button(text='OK', size_hint_y=0.15) content.add_widget(closeButton) self._popup = Popup(title='Error', content=content, size_hint=(0.8, 0.8)) closeButton.bind(on_press=self._popup.dismiss) self._popup.open() def update_list(self): self.data_items = [] self.counter = self.counter + 1 for key in state_handler.get_file_list().keys(): self.data_items.append(DataItem(text=key)) self.list_adapter.data = self.data_items self.list_view.adapter = self.list_adapter def copy_to_clipboard_files(self, object): clipboard_data = "" for data in self.data_items: if data.is_selected: clipboard_data += "http://pub.iotek.org/" + state_handler.get_file_list( )[data.text] + " " droid.setClipboard(clipboard_data.encode('utf-8')) def refresh_file_list(self, object): result = ioup.check_list(state_handler.get_token()) if result == {" ": " "}: self.error("Wasn't able to refresh list") return state_handler.store_file_list(result) self.update_list() def delete_file_list(self, object): for data in self.data_items: if data.is_selected: result = ioup.remove_file( state_handler.get_token(), state_handler.get_file_list()[data.text]) if result == False: self.error("Could not remove file: \n" + data.text) return #updating the list result2 = ioup.check_list(state_handler.get_token()) if result2 == {" ": " "}: self.error("Wasn't able to refresh list") return state_handler.store_file_list(result2) self.update_list() self.dismiss_popup()
def on_headers(self, instance, value): if not self._from_widths: return if not (value and self.canvas and self.headers): return widths = self.widths if len(self.widths) != len(value): return #if widths is not None: # widths = ['%sdp' % i for i in widths] def generic_args_converter(row_index, item, is_header=True, getter=self.getter): cls_dicts = [] _widths = self.widths getter = self.getter on_context_menu = self.on_context_menu for i, header in enumerate(self.headers): kwargs = { 'padding': ('2dp','2dp'), 'halign': 'center', 'valign': 'middle', 'size_hint_y': None, 'shorten': True, 'height': '30dp', 'text_size': (_widths[i], dp(30)), 'text': getter(item, i), } kwargs['font_size'] = '9sp' if is_header: kwargs['deselected_color'] = kwargs['selected_color'] =\ [0, 1, 1, 1] else: # this is content kwargs['deselected_color'] = 1, 1, 1, 1 if on_context_menu is not None: kwargs['on_press'] = on_context_menu if widths is not None: # set width manually kwargs['size_hint_x'] = None kwargs['width'] = widths[i] cls_dicts.append({ 'cls': ListItemButton, 'kwargs': kwargs, }) return { 'id': item[-1], 'size_hint_y': None, 'height': '30dp', 'cls_dicts': cls_dicts, } def header_args_converter(row_index, item): return generic_args_converter(row_index, item) def content_args_converter(row_index, item): return generic_args_converter(row_index, item, is_header=False) self.ids.header_view.adapter = ListAdapter(data=[self.headers], args_converter=header_args_converter, selection_mode='single', allow_empty_selection=False, cls=CompositeListItem) self.ids.content_view.adapter = ListAdapter(data=self.data, args_converter=content_args_converter, selection_mode='single', allow_empty_selection=False, cls=CompositeListItem) self.content_adapter.bind_triggers_to_view(self.ids.content_view._trigger_reset_populate)
def _get_adapter(self, *args): if self.list_type == 'text': converter = lambda row_index, rec: { 'text': rec['text'], 'secondary_text': rec['secondary_text'] if 'secondary_text' in rec else '', 'tile_rows': self.tile_rows, 'text_color_selected': self.text_color_selected, 'background_color_selected': self.background_color_selected, 'background_color_disabled': self.background_color_disabled, 'divider_color': self.divider_color, 'size_hint_y': None, 'height': self._tile_height, 'callback': rec['callback'] if 'callback' in rec else None } adapter = ListAdapter(data=self.list_data, args_converter=converter, cls=TextTile) adapter.bind(selection=self.setter('selection')) self._list_view.adapter = adapter self._list_view.adapter.selection_mode = self.selection_mode self._list_view.adapter.selection_limit = self.selection_limit self._list_view.adapter.allow_empty_selection = self.allow_empty_selection if self.list_type == 'icon_text': converter = lambda row_index, rec: { 'icon': rec['icon'], 'text': rec['text'], 'secondary_text': rec['secondary_text'] if 'secondary_text' in rec else '', 'tile_rows': self.tile_rows, 'text_color_selected': self.text_color_selected, 'background_color_selected': self.background_color_selected, 'background_color_disabled': self.background_color_disabled, 'divider_color': self.divider_color, 'size_hint_y': None, 'height': self._tile_height, 'callback': rec['callback'] if 'callback' in rec else None } adapter = ListAdapter(data=self.list_data, args_converter=converter, cls=IconTextTile) adapter.bind(selection=self.setter('selection')) self._list_view.adapter = adapter self._list_view.adapter.selection_mode = self.selection_mode self._list_view.adapter.selection_limit = self.selection_limit self._list_view.adapter.allow_empty_selection = self.allow_empty_selection if self.list_type == 'avatar_text': converter = lambda row_index, rec: { 'avatar': rec['avatar'], 'text': rec['text'], 'secondary_text': rec['secondary_text'] if 'secondary_text' in rec else '', 'tile_rows': self.tile_rows, 'text_color_selected': self.text_color_selected, 'background_color_selected': self.background_color_selected, 'background_color_disabled': self.background_color_disabled, 'divider_color': self.divider_color, 'size_hint_y': None, 'height': self._tile_height, 'callback': rec['callback'] if 'callback' in rec else None } adapter = ListAdapter(data=self.list_data, args_converter=converter, cls=AvatarTextTile) adapter.bind(selection=self.setter('selection')) self._list_view.adapter = adapter self._list_view.adapter.selection_mode = self.selection_mode self._list_view.adapter.selection_limit = self.selection_limit self._list_view.adapter.allow_empty_selection = self.allow_empty_selection
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}}]}
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)
def rebuild(self): self.clear_all() b2 = BoxLayout(orientation='horizontal', size_hint=(1, 0.1)) b3 = BoxLayout(orientation='horizontal', size_hint=(1, 0.1)) but_off = Button(font_size=24, background_color=[0, 0.6, 0, 1], background_normal='', size_hint=(0.2, 1), on_release=self.restart) I1 = Image(source='E:\images\off2.png') but_off.add_widget(I1) b2.add_widget(but_off) self.titl = Button(text='Индикация параметров', halign='left', bold=True, font_size=24, background_color=[0, 0.6, 0, 1], background_normal='', background_down='') b2.add_widget(self.titl) but_set = Button(on_release=self.rebuild_set, font_size=24, background_color=[0, 0.6, 0, 1], background_normal='', size_hint=(0.2, 1)) I2 = Image(source='E:\images\set2.png') but_set.add_widget(I2) b2.add_widget(but_set) self.list_button = self.list_but self.list_adapter = ListAdapter(data=[], cls=self.list_button, allow_empty_selection=False) self.list_view = ListView(adapter=self.list_adapter) self.list_button.background_color = [1, 1, 1, 1] self.list_button.background_normal = '' self.list_button.on_release = self.show_popup self.list_view.container.spacing = 10 self.list_button.font_size = 24 self.list_button.font_name = 'arialbd' self.list_button.bold = True self.list_button.color = [0, 0, 0, 1] self.list_button.padding = 30 self.list_button.halign = 'left' self.list_button.text_size = (Window.width, 0) self.list_adapter.data = [] I1.x = 0 - I2.width * 0.125 I1.y = Window.height - I2.height * 0.9 I2.x = Window.width - I2.width * 0.9 I2.y = Window.height - I2.height * 0.9 self.root.add_widget(b2) self.root.add_widget(self.list_view) self.but_0x = Button(on_release=self.do_set, text='0x', bold=True, font_size=28, background_color=[0, 0.6, 0, 1], background_normal='') self.but_1x = Button(on_release=self.di_set, text='1x', bold=True, font_size=28, background_color=[0, 0.6, 0, 1], background_normal='') self.but_3x = Button(on_release=self.ai_set, text='3x', bold=True, font_size=28, background_color=[0, 0.6, 0, 1], background_normal='') self.but_4x = Button(on_release=self.hr_set, text='4x', bold=True, font_size=28, background_color=[0, 0.6, 0, 1], background_normal='') b3.add_widget(self.but_0x) b3.add_widget(self.but_1x) b3.add_widget(self.but_3x) b3.add_widget(self.but_4x) self.root.add_widget(b3) self.hr_set() Clock.schedule_interval(self.update, 1)
def makeMenu(self, selected): self.leftgrid_id.clear_widgets() buttons = ["Home", "Conversations", "People", "Notebooks"] detail = ["nothing"] sel = "" for b in buttons: b1 = Button(size_hint_y=None, height=50, text=b, id=b + "Button") b1.bind(on_press=self.buttonAction) self.leftgrid_id.add_widget(b1) if selected == b: self.sect = b gl = GridLayout(size_hint_y=1, cols=2) if b == "Home": la = ListAdapter(data=self.home, cls=ListItemButton, allow_empty_selection=False) la.bind(on_selection_change=self.la_callback) if b == "People": la = ListAdapter(data=self.contacts, cls=ListItemButton, allow_empty_selection=False) la.bind(on_selection_change=self.la_callback) if b == "Notebooks": la = ListAdapter(data=self.notebooks, cls=ListItemButton, allow_empty_selection=False) la.bind(on_selection_change=self.la_callback) if b == "Conversations": la = ListAdapter(data=self.conversations, cls=ListItemButton, allow_empty_selection=False) la.bind(on_selection_change=self.la_callback) lv = ListView(adapter=la, padding=10, spacing=10, size_hint_x=.8, size_hint_y=.8) sel = la.selection b2 = Label(size_hint_x=None, width=10, text=" ") gl.add_widget(b2) gl.add_widget(lv) self.leftgrid_id.add_widget(gl) self.drawMain(sel[0].text)
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()