Ejemplo n.º 1
0
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})
Ejemplo n.º 2
0
    def on_channels(self, instance, value):
        '''
        Set the list of available channels for this view.
        Uses the Kivy ListAdapter to adapt the string channel name into a data structure that can track selection in the UI.
        '''
        data = []
        channel_list = self.ids.channelList
        for channel in self.channels:
            data.append({'text': str(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='multiple' if self.multi_select else 'single',
            allow_empty_selection=True)

        channel_list.adapter = list_adapter
        list_adapter.bind(on_selection_change=self.on_select)
Ejemplo n.º 3
0
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, **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())
Ejemplo n.º 5
0
	def update_display(self):
		self._sounds = []
		if self._categorie is None:
			return
		self.title_button.text = "Sound Box / " + self._categorie
		
		os.chdir("sounds")
		os.chdir(self._categorie)
		for aFilename in glob.glob("*"):
			self._sounds.append(aFilename[:-4])
		os.chdir("../..")
		
		list_item_args_converter = \
			lambda row_index, obj: {'text': obj,
									'index': row_index,
									'is_selected': False
									}
		
		my_adapter = ListAdapter(data = self._sounds,
									args_converter=list_item_args_converter,
									selection_mode='single',
									allow_empty_selection=True,
									template='CustomListItemSound')
		
		my_adapter.bind(on_selection_change=self.item_changed)
		self.containerListView.adapter = my_adapter
Ejemplo n.º 6
0
    def on_pre_enter(self, *args):
        members = list(self.network.hashgraph.known_members.values())
        members.sort(key=lambda x: x.formatted_name)
        self.data = [{'member': m, 'is_selected': False} for m in members if m != self.network.me]

        def args_converter(row_index, rec):
            return {
                'text': rec['member'].formatted_name,
                'height': 40
            }

        list_adapter = ListAdapter(data=self.data,
                                   args_converter=args_converter,
                                   cls=self.MemberListItemButton,
                                   selection_mode='single',
                                   propagate_selection_to_data=True,
                                   allow_empty_selection=True)

        def selection_change_callback(adapter):
            if len(adapter.selection) == 1:
                self.ids.send_button.disabled = False

        list_adapter.bind(on_selection_change=selection_change_callback)

        self.list_view = ListView(adapter=list_adapter, size_hint_x=0.8)

        self.ids.receiver_layout.add_widget(self.list_view)
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
0
    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(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
        for available_channel, channelMeta in settings.systemChannels.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
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 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)
Ejemplo n.º 12
0
class MovieListView(ListView):
    '''MovieListView displays the titles of local movie files.'''
    def __init__(self, **kwargs):
        '''Initialize MovieListView object.'''
        super(MovieListView, self).__init__(**kwargs)
        self.set_adapter()
        self.current_idx = 0

    def set_adapter(self):
        '''Set ListAdapter properties and selection change binding.'''
        self.adapter = ListAdapter(data=playlist,
                                   selection_mode='single',
                                   allow_empty_selection=False,
                                   cls=ListItemButton)
        self.adapter.bind(on_selection_change=self.selection_change)

    def selection_change(self, adapter, *args):
        '''Update the display when a new movie is selected.'''
        views = self.adapter.cached_views
        for key in views:
            view = views[key]
            new_idx = view.index
            if view.is_selected and self.current_idx <> new_idx:
                self.current_idx = new_idx
                app.app_window.update_display()
Ejemplo n.º 13
0
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()
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
 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))
Ejemplo n.º 16
0
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()
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
 def set_passwords(self, passwords_raw):
     passwords = []
     for password_raw in passwords_raw:
         password = password_raw
         password.update({
             "title": self.decrypt(password_raw["title"]),
             "body": self.decrypt(password_raw["body"])
         })
         passwords.append(password)
     self.passwords = passwords
     adapter_items = []
     for password in passwords:
         mylist_item = password
         mylist_item.update({"is_selected": False})
         adapter_items.append(mylist_item)
     args_converter = lambda row_index, rec: {
         'text': rec['title'],
         'size_hint_y': None,
         'height': 25
     }
     list_adapter = ListAdapter(data=adapter_items,
                                args_converter=args_converter,
                                propagate_selection_to_data=True,
                                cls=ListItemButton,
                                selection_mode='single')
     list_adapter.bind(on_selection_change=self.set_password_detail)
     self.ids.listview_mylist_items.adapter = list_adapter
Ejemplo n.º 19
0
    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))
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
	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()
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
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)
Ejemplo n.º 25
0
    def initialize(self, passphrase):
        self.block = False

        # Make instance of Manager
        manager = Manager(passphrase)
        if not manager.load():
            print('error: Data load failed on initialization. exit.')
            exit()
        self.manager = manager

        # Initialize FILE listview
        def file_args_converter(index, rec):
            return {
                'text': rec.title,
                'size_hint_y': None,
                'height': 60
            }
        file_adapter = ListAdapter(
            data=manager.files,
            args_converter=file_args_converter,
            selection_mode='single',
            allow_empty_selection=False,
            cls=Factory.MyListItem
        )
        file_adapter.bind(on_selection_change=self.file_changed)
        self.ids['lvfile'].adapter = file_adapter

        # Initialize ITEM listview
        def item_args_converter(index, rec):
            return {
                'text': rec.key + ': ' + rec.value,
                'size_hint_y': None,
                'height': 60
            }
        list_adapter = ListAdapter(
            data=[],
            args_converter=item_args_converter,
            selection_mode='single',
            allow_empty_selection=False,
            cls=Factory.MyListItem
        )
        list_adapter.bind(on_selection_change=self.list_changed)
        self.ids['lvitem'].adapter = list_adapter

        # Make drop-down menu( config )
        self.config_menu = Factory.ConfigMenu()
        self.ids['f_config'].bind(on_release=self.config_menu.open)
        def on_select(menu, item):
            if item == 'm_change':
                self.on_change_password()
        self.config_menu.bind(on_select=on_select)

        # Select first file
        self.listview_select(file_adapter, 0)
Ejemplo n.º 26
0
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
Ejemplo n.º 27
0
class RegDictView(BoxLayout):
    """Register dictionary view. Should be replaced by RecycleView after kivy 1.9.2"""

    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 reg_selection_changed(self, list_adapter, *args):
        if not list_adapter.selection:
            Logger.debug('No selection')
        else:
            self.slider_view.redraw(list_adapter.selection[0].index)

    def prep_adpter_data(self, info_dict):
        self.info_dict = info_dict
        info_list_of_dicts = [info_dict[key] for key in sorted(info_dict.keys())]
        reg_data_items = [RegSelectItem(**d) for d in info_list_of_dicts]
        return reg_data_items

    def update(self, data, has_virtual=False):
        data = {k: v for k, v in data.items() if v['virtual'] == has_virtual}
        self.list_adapter.data = self.prep_adpter_data(data)
Ejemplo n.º 28
0
    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 )
Ejemplo n.º 29
0
 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()
Ejemplo n.º 30
0
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]
        cached = [args[0].get_view(a).text for a in args[0].cached_views]
        new_list = []
        #for not deleting/deleting already added apps
        for a in d_cfg.get()["dock-apps"]:
            if a in l:
                new_list.append(a)
            elif a not in l:
                #Either removed or not cached
                if a in cached:
                    pass  #don't add it
                elif a not in cached:
                    new_list.append(a)
        #for new apps
        for a in l:
            if a in new_list:
                pass
            else:
                new_list.append(a)
        #Update
        updateConfig({'dock-apps': new_list})
Ejemplo n.º 31
0
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"])
Ejemplo n.º 32
0
    def updateDisplay(self):
        list_item_args_converter = \
         lambda row_index, obj: {'text': obj.loclbnom,
               'index': row_index,
               'id': "itemindex_%d" % row_index,
               'is_selected': False,
               'size_hint_y': None,
               'height': 25}

        my_adapter = ListAdapter(data=self.allItems.itervalues(),
                                 args_converter=list_item_args_converter,
                                 selection_mode='single',
                                 allow_empty_selection=True,
                                 template='CustomListItemLocality')

        my_adapter.bind(on_selection_change=self.item_changed)
        self.containerListView.adapter = my_adapter
	def updateDisplay(self):
		list_item_args_converter = \
			lambda row_index, obj: {'text': obj.loclbnom,
									'index': row_index,
									'id': "itemindex_%d" % row_index, 
									'is_selected': False,
									'size_hint_y': None,
									'height': 25}
		
		my_adapter = ListAdapter(data = self.allItems.itervalues(),
									args_converter=list_item_args_converter,
									selection_mode='single',
									allow_empty_selection=True,
									template='CustomListItemLocality')
		
		my_adapter.bind(on_selection_change=self.item_changed)
		self.containerListView.adapter = my_adapter
Ejemplo n.º 34
0
    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
Ejemplo n.º 35
0
	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
Ejemplo n.º 36
0
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]
		cached= [ args[0].get_view(a).text  for a in args[0].cached_views]
		new_list=[]
		#for not deleting/deleting already added apps
		for a in d_cfg.get()["dock-apps"]:
			if a in l:
				new_list.append(a)
			elif a not in l:
				#Either removed or not cached
				if a in cached:
					pass#don't add it
				elif a not in cached:
					new_list.append(a)
		#for new apps		
		for a in l:
			if a in new_list:
				pass
			else:
				new_list.append(a)
		#Update
		updateConfig({'dock-apps':new_list})
Ejemplo n.º 37
0
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)
Ejemplo n.º 38
0
 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()
class MyListView(BoxLayout):

    data_list = ObjectProperty([])

    def __init__(self, **kwargs):
        super(MyListView, self).__init__(**kwargs)

        self.list_adapter = ListAdapter(
            data=self.data_list,
            args_converter=self.converter,
            selection_mode='single',
            allow_empty_selection=True,
            cls=MyListItemButton)

        self.list_adapter.bind(on_selection_change=self.selection_change)
        self.list_view = ListView(adapter=self.list_adapter)

        #  滑动bar
        self.list_view.container.parent.bar_color = [1, 1, 1, 0.7]
        self.list_view.container.parent.bar_inactive_color = [1, 1, 1, 0.3]
        self.list_view.container.parent.bar_width = 3
        self.list_view.container.parent.bar_margin = 0

        self.add_widget(self.list_view)

        global_.task_lists.append(self.list_view)

    def selection_change(self, adapter, *args):
        if (adapter.selection):
            selected_obj = adapter.selection[0]            

    def refresh(self, new_data_list):
        self.list_view.adapter.data = new_data_list
        self.list_view._trigger_reset_populate()

    def on_data_list(self, instance, new_data_list):
        self.refresh(new_data_list)

    def converter(self, row_index, obj):
        kwargs = {}
        kwargs['meta'] = obj
        kwargs['list_view_index'] = row_index
        kwargs['list_view'] = self.list_view
        return kwargs
Ejemplo n.º 40
0
    def update_display(self):
        self._read_categories()
        #print(self._categories)
        list_item_args_converter = \
         lambda row_index, obj: {'text': obj,
               'index': 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.item_changed)
        self.containerListView.adapter = my_adapter
Ejemplo n.º 41
0
	def update_display(self):
		self._read_categories()
		#print(self._categories)
		list_item_args_converter = \
			lambda row_index, obj: {'text': obj,
									'index': 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.item_changed)
		self.containerListView.adapter = my_adapter
Ejemplo n.º 42
0
class ViewSelectionList(BoxLayout):
    def __init__(self, **kwargs):
        super(ViewSelectionList, self).__init__(**kwargs)
        self.selection = []
        data_items = []
        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=True,
                    allow_empty_selection=True,
                    cls=ListItemButton)

        self.list_adapter.bind(on_selection_change=self.reload)

    def update_list_data(self, path, filename):
            items = self.list_adapter.data
            item = DataItem(name=filename[0])
            items.append(item)

    def clear(self):
        print "Clear"
        self.list_adapter.data = []

    def remove(self, path):
        for j in self.list_adapter.data:
            if j.name is path:
                self.list_adapter.data.remove(j)

    def reload(self, *args):
        self.selection = []
        for i in self.list_adapter.selection:
            self.selection.append(i)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            touch.push()
            touch.apply_transform_2d(self.to_local)
            ret = super(ViewSelectionList, self).on_touch_down(touch)
            touch.pop()
            print self.parent
            return ret
Ejemplo n.º 43
0
    def test_list_adapter_selection_handle_selection(self):
        list_adapter = ListAdapter(data=fruit_data_items,
                                   args_converter=self.args_converter,
                                   selection_mode='single',
                                   propagate_selection_to_data=True,
                                   allow_empty_selection=False,
                                   cls=ListItemButton)

        selection_observer = FruitSelectionObserver()
        list_adapter.bind(
                on_selection_change=selection_observer.on_selection_change)

        list_view = ListView(adapter=list_adapter)

        self.assertEqual(selection_observer.call_count, 0)

        # From the check for initial selection, we should have apple selected.
        self.assertEqual(list_adapter.selection[0].text, 'Apple')
        self.assertEqual(len(list_adapter.selection), 1)

        # Go through the tests routine to trigger selection of banana.
        # (See notes above about triggering selection in tests.)
        self.assertEqual(fruit_data_items[2].name, 'Banana')
        fruit_data_items[2].is_selected = True
        banana = list_view.adapter.get_view(2)  # does selection
        self.assertTrue(banana.is_selected)

        # Now unselect it with handle_selection().
        list_adapter.handle_selection(banana)
        self.assertFalse(banana.is_selected)

        # But, since we have allow_empty_selection=False, Apple will be
        # reselected.
        self.assertEqual(selection_observer.fruit_name, 'Apple')

        # Call count:
        #
        # Apple got selected initally (0), then unselected when Banana was
        # selected (1). Then banana was unselected, causing reselection of
        # Apple (3). len should be 1.
        self.assertEqual(selection_observer.call_count, 3)
        self.assertEqual(len(list_adapter.selection), 1)
Ejemplo n.º 44
0
    def test_list_adapter_selection_handle_selection(self):
        list_adapter = ListAdapter(data=fruit_data_items,
                                   args_converter=self.args_converter,
                                   selection_mode='single',
                                   propagate_selection_to_data=True,
                                   allow_empty_selection=False,
                                   cls=ListItemButton)

        selection_observer = FruitSelectionObserver()
        list_adapter.bind(
            on_selection_change=selection_observer.on_selection_change)

        list_view = ListView(adapter=list_adapter)

        self.assertEqual(selection_observer.call_count, 0)

        # From the check for initial selection, we should have apple selected.
        self.assertEqual(list_adapter.selection[0].text, 'Apple')
        self.assertEqual(len(list_adapter.selection), 1)

        # Go through the tests routine to trigger selection of banana.
        # (See notes above about triggering selection in tests.)
        self.assertEqual(fruit_data_items[2].name, 'Banana')
        fruit_data_items[2].is_selected = True
        banana = list_view.adapter.get_view(2)  # does selection
        self.assertTrue(banana.is_selected)

        # Now unselect it with handle_selection().
        list_adapter.handle_selection(banana)
        self.assertFalse(banana.is_selected)

        # But, since we have allow_empty_selection=False, Apple will be
        # reselected.
        self.assertEqual(selection_observer.fruit_name, 'Apple')

        # Call count:
        #
        # Apple got selected initally (0), then unselected when Banana was
        # selected (1). Then banana was unselected, causing reselection of
        # Apple (3). len should be 1.
        self.assertEqual(selection_observer.call_count, 3)
        self.assertEqual(len(list_adapter.selection), 1)
Ejemplo n.º 45
0
    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))
Ejemplo n.º 46
0
    def on_channels(self, instance, value):    
        '''
        Set the list of available channels for this view.
        Uses the Kivy ListAdapter to adapt the string channel name into a data structure that can track selection in the UI.
        '''
        data = []
        channel_list = self.ids.channelList
        for channel in self.channels:
            data.append({'text': str(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= 'multiple' if self.multi_select else 'single',
                           allow_empty_selection=True)

        channel_list.adapter=list_adapter
        list_adapter.bind(on_selection_change=self.on_select)
Ejemplo n.º 47
0
class ReplayChooser(Screen):
    recent_adpt = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        self.recent_adpt = ListAdapter(data=squeeze.local_replay_ids(), 
                                       cls=ListItemButton, 
                                       selection_mode='single')
        self.recent_adpt.bind(on_selection_change=self.on_select)
        super(ReplayChooser, self).__init__(*args, **kwargs)

    def load(self, filename):
        filename = filename[0]
        squeeze.dump_demo(filename)
        demo_num = os.path.split(filename)[-1].strip('.dem')

        d2rp.init_d2rp(os.path.join(squeeze.PARSER_PATH, 'json', demo_num))

        s_mgr.current = 's_match_perf'

    def on_select(self, selected):
        print selected.selection[0].text 
Ejemplo n.º 48
0
class BaseListScreen(BaseScreen):
    def __init__(self, ws, **kwargs):
        super(BaseListScreen, self).__init__(ws, **kwargs)
        self.adapter = ListAdapter(data=[],
                                   cls=MopidyListItem,
                                   args_converter=self.args_converter)
        self.adapter.selection_mode = 'single'
        self.adapter.selection_limit = 1
        self.ids.list_view.adapter = self.adapter
        self.adapter.bind(on_selection_change=self.on_selection_change)

    def args_converter(self, row_index, x):
        return {
            'text': Utils.get_title_string(x),
            'size_hint_y': None,
            'height': 45
        }

    def clear_list_item_selection(self):
        if len(self.adapter.selection) > 0:
            view = self.adapter.selection[0]
            self.adapter.deselect_item_view(view)
Ejemplo n.º 49
0
  def __init__(self, ola_listener, selected_universe_service, **kwargs):
    """Initializes the listview that contains the universe selection.

       Args:
         ola_listener: an OLAListener object to pass tasks to
         selected_universe_service: this UniverseSelectedService object manages 
           the universe selected by the user.
    """
    super(MainScreen, self).__init__(**kwargs)
    self.ola_listener = ola_listener
    self.selected_universe_service = selected_universe_service
    universe_converter = \
      lambda row_index, selectable: {'text': selectable.name,
                                     'size_hint_y': None,
                                     'height': '25dp'}
    list_adapter = ListAdapter(data=[],
                               args_converter=universe_converter,
                               selection_mode='single',
                               allow_empty_selection=False,
                               cls=ListItemButton)
    list_adapter.bind(on_selection_change=self.change_selected_universe)
    self.ids.universe_list_view.adapter = list_adapter
Ejemplo n.º 50
0
    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)
Ejemplo n.º 51
0
    def __init__(self, **kwargs):
        self.site = kwargs['site']
        self.name = util.short_id(self.site.id)+'-transfer'
        
        mid = MidPanel()
        
        print self.site.stuff
        
        list_adapter = ListAdapter(data=self.site.stuff,
                           args_converter=args_converter,
                           cls=CustomListItem,
                           selection_mode='multiple',
                           allow_empty_selection=True)

        list_view = ListView(adapter=list_adapter)
        list_adapter.bind(on_selection_change = mid.ships_changed)
    

        resv = resource_views.ResourceSelector(resources=self.site.resources)
        resv.bind(res_changed = mid.res_changed)

        left = LeftPanel()
        left.ids['shipchoicepanel'].add_widget(list_view)
        left.ids['resourcepanel'].add_widget(resv)
        
        right = RightPanel()
        dest_tree = TransferTree()
        dest_tree.bind(selected_site = mid.dest_selected)
        
        right.ids['treepanel'].add_widget(dest_tree)
        
        super(TransferView, self).__init__(**kwargs)                    

        self.ids['mainpanel'].add_widget(left)
        self.ids['mainpanel'].add_widget(mid)
        self.ids['mainpanel'].add_widget(right)
Ejemplo n.º 52
0
class TeamsView(ListView):

    name = StringProperty()

    def __init__(self, **kwargs):
        super(TeamsView, self).__init__(**kwargs)
        self.fetch_teams_from_database()
        self.set_adapter()
        self.save_bean()

    def fetch_teams_from_database(self):
        self.teams = [{
            'team': 'Pogoń Szczecin',
            'score': '55'
        }, {
            'team': 'Arizona State',
            'score': '32'
        }, {
            'team': 'Idaho',
            'score': '44'
        }, {
            'team': 'Nebraska',
            'score': '48'
        }, {
            'team': 'Accrington Stanley',
            'score': '2'
        }, {
            'team': 'Nottingham Forest',
            'score': '3'
        }]

    def set_adapter(self):
        self.adapter = ListAdapter(data=self.teams,
                                   args_converter=self.args_converter,
                                   selection_mode='single',
                                   allow_empty_selection=True,
                                   cls=ListItemButton)

        self.adapter.bind(on_selection_change=self.on_selection_change)

    def args_converter(self, row_index, item):
        return {'text': item['team'], 'size_hint_y': None, 'height': 50}

    def on_selection_change(self, adapter):
        team_score, team_name = self.get_team(adapter)
        team_score = '[size=50]' + team_score + '[/size]'

        beans['score_grid'].ids[self.name + '_name'].text =\
            team_name + ' score:'
        beans['score_grid'].ids[self.name + '_score'].text =\
            team_score

    def get_team(self, adapter):
        try:
            for team in self.teams:
                if team['team'] in adapter.selection[0].text:
                    return team['score'], team['team']
        except IndexError:
            return '', ''

    @mainthread
    def save_bean(self):
        beans[self.name + 'list'] = self.proxy_ref
Ejemplo n.º 53
0
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`
    '''

    __events__ = ('on_select', 'on_cancel')

    def __init__(self, **kwargs):
        super(NewProjectDialog, self).__init__(**kwargs)
        item_strings = NEW_PROJECTS.keys()
        self.adapter = ListAdapter(cls=Factory.DesignerListItemButton, data=item_strings,
                                   selection_mode='single',
                                   allow_empty_selection=False)
        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_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 = dirname(designer.__file__)
        _dir = split(_dir)[0]
        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)

    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 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)
Ejemplo n.º 55
0
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']
                }
            }]
        }
Ejemplo n.º 56
0
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}}]}
Ejemplo n.º 57
0
    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[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)
Ejemplo n.º 58
0
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        global unsortedPlayerNames
        global sortedPlayerNames
        fp_list = list()
        sp_list = list()
        tp_list = list()
        f2p_list = list()
        initp_list = list()
        wpp_list = list()
        initp_list = list()
        spp_list = list()
        stp_list = list()
        skp_list = list()
        sap_list = list()

        f3p_list = list()
        zp_list = list()
        playerList = list()
        playerNames = list()
        unsortedPlayerNames = list()
        sortedPlayerNames = list()
        initData = list()
        dmgData = list()
        saData = list()
        wpData = list()
        skData = list()
        stData = list()
        playerDic = dict()
        initFlag = False

        ##################### Importing Player data Json File ######################
        with open('player.json') as data_file:
            data = json.load(data_file)

        for item in data:
            playerList.append(Player(item))

        for item in playerList:
            playerNames.append(item.playerName)
            initData.append(("%s  =     0" % item.playerName))
            playerDic[item.playerName] = item

        if len(playerNames) > 1:
            global currentPlayer
            currentPlayer = playerDic[playerNames[0]]

        ############################################################################

        global pageNum
        pageNum = 1
        setting = 0  ## 0 = no preference
        ## 1 = manual calculation
        ## 2 = automatic calculation

        KIVY_FONTS = [{
            "name": "custom",
            "fn_regular": "data/fonts/RobotoCondensed-Light.ttf",
            "fn_bold": "data/fonts/RobotoCondensed-Regular.ttf",
            "fn_italic": "data/fonts/RobotoCondensed-LightItalic.ttf",
            "fn_bolditalic": "data/fonts/RobotoCondensed-Italic.ttf"
        }]

        skData = [
            "Acrobatics", "Animal Handling", "Arcana", "Athletics",
            "Deception", "History", "Insight", "Intimidation", "Investigation",
            "Medicine", "Nature", "Perception", "Performance", "Persuasion",
            "Religion", "Sleight of Hand", "Stealth", "Survival"
        ]
        skDataS = [
            "dex", "wis", "int", "str", "cha", "int", "wis", "cha", "int",
            "wis", "int", "wis", "cha", "cha", "int", "dex", "dex", "wis"
        ]
        ##
        stData = [
            "Strength", "Dexterity", "Constitution", "Intelligence", "Wisdom",
            "Charisma"
        ]

        numData = ["1", "2", "3", "4", "5", "6"]

        diceData = ["d4", "d6", "d8", "d10", "d12", "d20"]

        ################################# First page widgets! ##############################################################################

        def backPage(instance):
            global die
            global selected1
            global pageNum
            global currentSetting
            if pageNum == 2:
                if currentPage == 3:
                    for item in wpp_list:
                        self.remove_widget(item)
                elif currentPage == 1:
                    for item2 in initp_list:
                        self.remove_widget(item2)
                elif currentPage == 5:
                    for item2 in spp_list:
                        self.remove_widget(item2)
                elif currentPage == 2:
                    for item2 in stp_list:
                        self.remove_widget(item2)
                elif currentPage == 4:
                    for item2 in skp_list:
                        self.remove_widget(item2)
                elif currentPage == 6:
                    for item2 in sap_list:
                        self.remove_widget(item2)
                else:
                    for item in sp_list:
                        self.remove_widget(item)

                for item2 in fp_list:
                    self.add_widget(item2)

                die = 0
                pageNum = 1
                dLabel.text = ('Select your Die!')

            elif pageNum == 3:
                for item in tp_list:
                    self.remove_widget(item)

                for item2 in sp_list:
                    self.add_widget(item2)
                pageNum = 2

            elif pageNum == 4:
                for item in f2p_list:
                    self.remove_widget(item)
                for item in f3p_list:
                    self.remove_widget(item)

                for item2 in tp_list:
                    self.add_widget(item2)
                pageNum = 3

        def changePageNum(num):
            global pageNum
            pageNum = num

        def manualSelection(instance):
            if instance == clearButton:
                totalManLabel.text = "The total value = 0"
            else:
                num = int(instance.text)
                mylist = totalManLabel.text.split(" ")
                num2 = int(mylist[len(mylist) - 1])
                num2 = num2 + num
                totalManLabel.text = ("The total Value = %d" % num2)

        def exitB(instance):
            App.get_running_app().stop()

        def dieSelect(instance):
            global die
            global selected1
            global pageNum
            global initFlag
            global currentPage
            flag = True
            data = None

            if instance == initButton:
                dLabel.text = ('%s is selected!' % instance.text)
                sLabel5.text = "Initiative"
                data = [{'text': i, 'is_selected': False} for i in playerNames]
                list_adapter2.data = data
                list_view2.populate()
                data = [{'text': i, 'is_selected': False} for i in []]
                list_adapter3.data = data
                list_view3.populate()
                sLabel3.text = '0'
                sLabel2.text = '0'
                sLabel.text = '0'
                initFlag = True
                currentPage = 1
                die = 1
            elif instance == stButton:
                dLabel.text = ('%s is selected!' % instance.text)
                sLabel5.text = "Saving Throw"
                sLabel2.text = '0'
                sLabel3.text = '0'
                sLabel.text = '0'
                attack.source = "./images/Field_Save.png"
                data = [{'text': i, 'is_selected': False} for i in stData]
                initFlag = False
                currentPage = 2
                die = 2
            elif instance == wpButton:
                dLabel.text = ('%s is selected!' % instance.text)
                sLabel5.text = "Weapons"
                wpData = []
                for item in playerDic[currentPlayer.playerName].weapons:
                    wpData.append(item[0])
                attack.source = "./images/Field_Attack.png"
                data = [{'text': i, 'is_selected': False} for i in wpData]
                sLabel2.text = '0'
                sLabel3.text = '0'
                sLabel.text = '0'
                sLabel4.text = '0'
                initFlag = False
                currentPage = 3
                die = 3
            elif instance == skButton:
                dLabel.text = ('%s is selected!' % instance.text)
                sLabel5.text = "Skills"
                skData = []
                for item in playerDic[currentPlayer.playerName].skills:
                    skData.append(item)
                attack.source = "./images/Field_Attack.png"
                data = [{'text': i, 'is_selected': False} for i in skData]
                sLabel2.text = '0'
                sLabel3.text = '0'
                sLabel.text = '0'
                skStatLabel.text = '--'
                initFlag = False
                currentPage = 4
                die = 4
            elif instance == spButton:
                dLabel.text = ('%s is selected!' % instance.text)
                spData = playerDic[currentPlayer.playerName].spells
                data = [{'text': i, 'is_selected': False} for i in spData]
                attack.source = "./images/Field_Attack.png"
                sLabel5.text = "Spells"

                sLabel2.text = '0'
                sLabel3.text = '0'
                sLabel.text = '0'
                initFlag = False
                currentPage = 5
                die = 5
            elif instance == saButton:
                dLabel.text = ('%s is selected!' % instance.text)
                sLabel5.text = "Special Ability"
                attack.source = "./images/Field_Attack.png"
                saData = playerDic[currentPlayer.playerName].special
                data = [{'text': i, 'is_selected': False} for i in saData]
                sLabel2.text = '0'
                sLabel3.text = '0'
                sLabel.text = '0'
                initFlag = False
                currentPage = 6
                die = 6
            elif instance == manualButton:
                flag = False
                selected1 = list_adapter.selection
                if not selected1:
                    sLabel.text = "Select!"
                    sLabel.color = (1, 0, 0, 1)
                else:
                    if initFlag:
                        selectedItem = list_adapter.selection[0].text
                        sLabel.color = (0, 0, 0, 1)
                        sLabel.text = selectedItem

                    else:
                        if currentPage == 3:
                            selectedItem = list_adapter.selection[0].text
                            sLabel.color = (0, 0, 0, 1)
                            txt = sLabel4.text
                            myList = txt.split("d")
                            myList2 = myList[1].split("+")

                            ran = random.randint(1, 20)
                            sLabel.text = str(ran + int(sLabel3.text))
                            sLabel2.text = str(ran + int(myList2[1]))
                        else:
                            ran = random.randint(1, 20)
                            selectedItem = list_adapter.selection[0].text
                            sLabel.color = (0, 0, 0, 1)
                            sLabel.text = str(ran + int(sLabel3.text))

            elif instance == autoButton:
                flag = False
                selected1 = list_adapter.selection
                if not selected1:
                    sLabel.text = "Select!"
                    sLabel.color = (1, 0, 0, 1)
                else:
                    if initFlag:
                        selectedItem = list_adapter.selection[0].text
                        sLabel.color = (0, 0, 0, 1)
                        sLabel.text = selectedItem

                    else:
                        selectedItem = list_adapter.selection[0].text
                        sLabel.color = (0, 0, 0, 1)
                        reslt = get_num_from_dice()
                        print(reslt)
                        print(sum(reslt))
                        sLabel.text = str(sum(reslt) + int(sLabel3.text))

            elif instance == autoButton2:
                flag = False
                selected1 = list_adapter.selection
                if not selected1:
                    sLabel2.text = "Select!"
                    sLabel2.color = (1, 0, 0, 1)
                else:
                    if initFlag:
                        selectedItem = list_adapter.selection[0].text
                        sLabel.color = (0, 0, 0, 1)
                        sLabel.text = selectedItem

                    else:
                        selectedItem = list_adapter.selection[0].text
                        txt = sLabel4.text
                        myList = txt.split("d")
                        myList2 = myList[1].split("+")
                        reslt = get_num_from_dice()
                        print(reslt)
                        print(sum(reslt))
                        sLabel2.text = str(sum(reslt) + int(myList2[1]))

            elif instance == tieButton:
                flag = False
                if len(list_adapter3.data) > 0:
                    if len(list_adapter3.data) == len(playerNames):
                        previous = -1
                        prevItem = None
                        probList = list()
                        finalList = list()

                        index = 0
                        minI = -1
                        maxI = len(list_adapter3.data)
                        flg = False

                        for item in list_adapter3.data:
                            if previous == -1:
                                prevItem = item
                                previous = int(item['text'].split(' ')[0])
                            else:
                                if previous == int(item['text'].split(' ')[0]):
                                    if len(probList) == 0:
                                        probList.append(prevItem['text'])
                                        probList.append(item['text'])
                                    else:
                                        probList.append(item['text'])
                                    if (minI < 0 and not flg):
                                        flg = True
                                        minI = index - 2
                                    prevItem = item
                                    previous = int(item['text'].split(' ')[0])
                                    maxI = index
                                else:
                                    prevItem = item
                                    previous = int(item['text'].split(' ')[0])
                            index = index + 1

                        shuffle(probList)
                        if len(probList) != 0:

                            index = 0
                            once = 0
                            finalList.append("!!Final Order!!")
                            for item in list_adapter3.data:
                                if index <= minI:
                                    finalList.append(
                                        "%s. %s" %
                                        (str(index + 1),
                                         item['text'].split(' ')[2]))
                                elif (index > minI and once == 0):
                                    num = index
                                    for item2 in probList:
                                        finalList.append("%s. %s" %
                                                         (str(num + 1),
                                                          item2.split(' ')[2]))
                                        num = num + 1
                                    once = 1

                                elif index > maxI:
                                    finalList.append(
                                        "%s. %s" %
                                        (str(index + 1),
                                         item['text'].split(' ')[2]))
                                index = index + 1
                            data = [{
                                'text': i,
                                'is_selected': False
                            } for i in finalList]
                            list_adapter3.data = data
                            list_view3.populate()

            elif instance == rollButton:
                flag = False
                selected1 = list_adapter.selection
                if not selected1:
                    sLabel.text = "Select!"
                    sLabel.color = (1, 0, 0, 1)
                else:
                    if initFlag:
                        selectedItem = list_adapter.selection[0].text
                        sLabel.color = (0, 0, 0, 1)
                        sLabel.text = selectedItem
                    else:
                        selectedItem = list_adapter.selection[0].text
                        sLabel.color = (0, 0, 0, 1)
                        reslt = get_num_from_dice()
                        print(reslt)
                        print(sum(reslt))
                        sLabel.text = str(sum(reslt) + int(sLabel3.text))

            else:
                print('what is this?')

            if flag:
                list_adapter.data = data
                list_view.populate()
                for item in fp_list:
                    self.remove_widget(item)

                if currentPage == 3:
                    for item2 in wpp_list:
                        self.add_widget(item2)
                elif currentPage == 1:
                    for item2 in initp_list:
                        self.add_widget(item2)
                elif currentPage == 5:
                    for item2 in spp_list:
                        self.add_widget(item2)
                elif currentPage == 2:
                    for item2 in stp_list:
                        self.add_widget(item2)
                elif currentPage == 4:
                    for item2 in skp_list:
                        self.add_widget(item2)
                elif currentPage == 6:
                    for item2 in sap_list:
                        self.add_widget(item2)
                else:
                    for item2 in sp_list:
                        self.add_widget(item2)

            pageNum = 2

        def show_selected_value(spinner, text):
            global currentPlayer
            currentPlayer = playerDic[text]
            if pageNum == 2:
                if currentPage == 1:
                    data = [{
                        'text': i,
                        'is_selected': False
                    } for i in initData]

                elif currentPage == 2:
                    data = [{'text': i, 'is_selected': False} for i in stData]

                if currentPage == 3:
                    wpData = []
                    for item in playerDic[currentPlayer.playerName].weapons:
                        wpData.append(item[0])
                    data = [{'text': i, 'is_selected': False} for i in wpData]

                elif currentPage == 4:
                    skData = []
                    for item in playerDic[currentPlayer.playerName].skills:
                        skData.append(item)
                    data = [{'text': i, 'is_selected': False} for i in skData]

                elif currentPage == 5:
                    spData = currentPlayer.spells
                    data = [{'text': i, 'is_selected': False} for i in spData]

                elif currentPage == 6:
                    saData = currentPlayer.special
                    data = [{'text': i, 'is_selected': False} for i in saData]
                list_adapter.data = data
                list_view.populate()

        def listSelected(instance):
            if len(list_adapter.selection) > 0:
                selectedItem = list_adapter.selection[0].text
                if currentPage == 3:
                    for item in currentPlayer.weapons:
                        if item[0] == selectedItem:
                            sLabel3.text = item[1]
                            sLabel4.text = item[2]
                elif currentPage == 2:
                    profstat = currentPlayer.profStats
                    stat = selectedItem[:3].lower()
                    if stat in profstat:
                        sLabel3.text = str(currentPlayer.prof)
                    else:
                        sLabel3.text = "0"
                elif currentPage == 4:
                    ind = skData.index(str(selectedItem))
                    skStatLabel.text = skDataS[ind].upper()

                    stat = ""
                    if skDataS[ind] == "str":
                        stat = currentPlayer.str
                    elif skDataS[ind] == "dex":
                        stat = currentPlayer.dex
                    elif skDataS[ind] == "con":
                        stat = currentPlayer.con
                    elif skDataS[ind] == "int":
                        stat = currentPlayer.int
                    elif skDataS[ind] == "wis":
                        stat = currentPlayer.wis
                    elif skDataS[ind] == "cha":
                        stat = currentPlayer.cha
                    sLabel3.text = str(stat)

                elif currentPage == 5:
                    sLabel3.text = str(currentPlayer.int)

                elif currentPage == 6:
                    sLabel3.text = str(currentPlayer.con)

            elif len(list_adapter2.selection) > 0:
                if currentPage == 1:
                    selectedItem = list_adapter2.selection[0].text
                    newList = list()
                    newList2 = list()
                    newList2Names = list()
                    if len(list_adapter2.data) > 0:
                        for item in list_adapter2.data:
                            if item['text'] != list_adapter2.selection[0].text:
                                newList.append(item['text'])
                    data = [{'text': i, 'is_selected': False} for i in newList]
                    list_adapter2.data = data
                    list_view2.populate()
                    tempDic = list()
                    reslt = get_num_from_dice()
                    print(reslt)
                    print(sum(reslt))
                    ran = sum(reslt)
                    if len(list_adapter3.data) > 0:
                        for item in list_adapter3.data:
                            if item['text'] != selectedItem:
                                newList2.append(item['text'])
                                tempDic.append(
                                    (item['text'],
                                     int(item['text'].split(' ')[0])))
                    dexx = playerDic[selectedItem].dex
                    ran = ran + dexx

                    tempDic.append((("%d - %s" % (ran, selectedItem)), ran))
                    newList2.append("%d - %s" % (ran, selectedItem))
                    newList2.sort()
                    sList = sorted(tempDic,
                                   key=lambda dic: dic[1],
                                   reverse=True)
                    fList = list()
                    for item in sList:
                        fList.append(item[0])
                    data = [{'text': i, 'is_selected': False} for i in fList]
                    list_adapter3.data = data
                    list_view3.populate()


################################# 0 page widgets! ########################################################################################

        spinner = Spinner(text=currentPlayer.playerName,
                          values=playerNames,
                          size_hint=(0.175, 0.05),
                          pos_hint={
                              'center_x': .9,
                              'center_y': .95
                          })
        spinner.bind(text=show_selected_value)
        self.add_widget(spinner)
        ################################# First page widgets! ####################################################################################
        exitButton = Button(text='Exit',
                            size_hint=(0.175, 0.05),
                            pos_hint={
                                'center_x': .5,
                                'center_y': .95
                            })

        exitButton.bind(on_press=exitB)

        self.add_widget(exitButton)

        def get_scalex_and_y(target_width, width, height):
            screen_width = 480.0
            screen_height = 800.0
            x_s = target_width / screen_width
            y_s = (target_width * height / width) / screen_height
            return x_s, y_s

        get_scalex_and_y(50, 5, 10)

        dImg1 = Image(source='./images/box.png',
                      pos_hint={
                          'center_x': .5,
                          'center_y': .35
                      },
                      size_hint=(.9, .7))

        initButton = Button(size_hint=(get_scalex_and_y(125, 125, 125)[0],
                                       get_scalex_and_y(125, 125, 125)[1]),
                            background_normal="./images/button_init.png",
                            pos_hint={
                                'center_x': .20,
                                'center_y': .4
                            })

        initButton.bind(on_press=dieSelect)

        stButton = Button(size_hint=(get_scalex_and_y(125, 125, 125)[0],
                                     get_scalex_and_y(125, 125, 125)[1]),
                          background_normal="./images/button_saving_throw.png",
                          pos_hint={
                              'center_x': .5,
                              'center_y': .4
                          })

        stButton.bind(on_press=dieSelect)

        wpButton = Button(size_hint=(get_scalex_and_y(125, 125, 125)[0],
                                     get_scalex_and_y(125, 125, 125)[1]),
                          background_normal="./images/button_weapons.png",
                          pos_hint={
                              'center_x': .8,
                              'center_y': .4
                          })

        wpButton.bind(on_press=dieSelect)

        skButton = Button(size_hint=(get_scalex_and_y(125, 125, 125)[0],
                                     get_scalex_and_y(125, 125, 125)[1]),
                          background_normal="./images/button_skills.png",
                          pos_hint={
                              'center_x': .2,
                              'center_y': .2
                          })

        skButton.bind(on_press=dieSelect)

        spButton = Button(size_hint=(get_scalex_and_y(125, 125, 125)[0],
                                     get_scalex_and_y(125, 125, 125)[1]),
                          background_normal="./images/button_spell.png",
                          pos_hint={
                              'center_x': .5,
                              'center_y': .2
                          })

        spButton.bind(on_press=dieSelect)

        saButton = Button(size_hint=(get_scalex_and_y(125, 125, 125)[0],
                                     get_scalex_and_y(125, 125, 125)[1]),
                          background_normal="./images/button_special.png",
                          pos_hint={
                              'center_x': .8,
                              'center_y': .20
                          })

        saButton.bind(on_press=dieSelect)

        tLabel = Label(text='DnD Dice Tower!',
                       color=(0, 0, 0, 1),
                       font_size='75sp',
                       font_name='./images/Captain_Redemption.ttf',
                       pos_hint={
                           'center_x': .5,
                           'center_y': .765
                       })
        self.add_widget(tLabel)

        dragon = Image(source="./images/Dragon_Title.png",
                       pos_hint={
                           'center_x': .5,
                           'center_y': .78
                       })

        self.add_widget(dragon)

        dLabel = Label(text='Select your Option!',
                       color=(0, 0, 0, 1),
                       font_size='45sp',
                       font_name='./images/Captain_Redemption.ttf',
                       pos_hint={
                           'center_x': .5,
                           'center_y': .6
                       })

        ################################# Second page widgets! ##############################################################################

        dImg2 = Image(source='./images/box2.png',
                      pos_hint={
                          'center_x': .48,
                          'center_y': .45
                      },
                      size_hint=(.16, .16))

        dImg3 = Image(source='./images/box2.png',
                      pos_hint={
                          'center_x': .48,
                          'center_y': .25
                      },
                      size_hint=(.16, .16))
        dImg4 = Image(source='./images/DiceRoll.png',
                      pos_hint={
                          'center_x': .5,
                          'center_y': .35
                      },
                      size_hint=(.9, .7))

        backButton = Button(text='Back',
                            color=(1, 1, 1, 1),
                            size_hint=(0.175, 0.05),
                            pos_hint={
                                'center_x': .1,
                                'center_y': .95
                            })
        backButton.bind(on_press=backPage)

        manualButton = Button(text="Random",
                              color=(255, 255, 255, 1),
                              size_hint=(0.175, 0.05),
                              pos_hint={
                                  'center_x': .25,
                                  'center_y': .1
                              })
        manualButton.bind(on_press=dieSelect)

        autoButton = Button(text="Roll Atk",
                            color=(255, 255, 255, 1),
                            size_hint=(0.175, 0.05),
                            pos_hint={
                                'center_x': .5,
                                'center_y': .1
                            })
        autoButton.bind(on_press=dieSelect)

        autoButton2 = Button(text="Roll Dmg",
                             color=(255, 255, 255, 1),
                             size_hint=(0.175, 0.05),
                             pos_hint={
                                 'center_x': .75,
                                 'center_y': .1
                             })
        autoButton2.bind(on_press=dieSelect)

        attack = Image(source="./images/Field_Attack.png",
                       pos_hint={
                           'center_x': .25,
                           'center_y': .43
                       })

        Damage = Image(source="./images/Field_Damage.png",
                       pos_hint={
                           'center_x': .25,
                           'center_y': .23
                       })

        sLabel = Label(text='0',
                       color=(0, 0, 0, 1),
                       font_size='40sp',
                       font_name='./images/Captain_Redemption.ttf',
                       pos_hint={
                           'center_x': .25,
                           'center_y': .45
                       })

        sLabel2 = Label(text='0',
                        color=(0, 0, 0, 1),
                        font_size='40sp',
                        font_name='./images/Captain_Redemption.ttf',
                        pos_hint={
                            'center_x': .25,
                            'center_y': .25
                        })

        sLabel3 = Label(text='0',
                        color=(0, 0, 0, 1),
                        font_size='25sp',
                        font_name='./images/Captain_Redemption.ttf',
                        pos_hint={
                            'center_x': .48,
                            'center_y': .45
                        })

        sLabel4 = Label(text='0',
                        color=(0, 0, 0, 1),
                        font_size='25sp',
                        font_name='./images/Captain_Redemption.ttf',
                        pos_hint={
                            'center_x': .48,
                            'center_y': .25
                        })
        sLabel5 = Label(text='Yes',
                        color=(0, 0, 0, 1),
                        font_size='25sp',
                        font_name='./images/Captain_Redemption.ttf',
                        pos_hint={
                            'center_x': .23,
                            'center_y': .6
                        })

        data = [{'text': i, 'is_selected': False} for i in wpData]

        args_converter = lambda row_index, rec: {
            'text': rec['text'],
            'size_hint_x': 10,
            'size_hint_y': None,
            'font_size': 15,
            'selected_color': (.5, .5, .5, .25),
            'deselected_color': (50, 50, 50, 1),
            'color': (0, 0, 0, 1),
            'height': 45
        }

        list_adapter = ListAdapter(data=data,
                                   args_converter=args_converter,
                                   cls=ListItemButton,
                                   selection_mode='single',
                                   allow_empty_selection=True)

        list_adapter.bind(on_selection_change=listSelected)

        list_view = ListView(adapter=list_adapter,
                             pos_hint={
                                 'center_x': .75,
                                 'center_y': .37
                             },
                             size_hint=(0.25, 0.35))
        list_view.background_normal = (0, 0, 0, 0)

        ################################# Init page widgets! ####################################################################################

        unsortedPalyerNames = playerNames

        data = [{'text': i, 'is_selected': False} for i in playerNames]

        args_converter = lambda row_index, rec: {
            'text': rec['text'],
            'size_hint_x': 10,
            'size_hint_y': None,
            'font_size': 15,
            'selected_color': (.5, .5, .5, .25),
            'deselected_color': (50, 50, 50, 1),
            'color': (0, 0, 0, 1),
            'height': 45
        }

        list_adapter2 = ListAdapter(data=data,
                                    args_converter=args_converter,
                                    cls=ListItemButton,
                                    selection_mode='single',
                                    allow_empty_selection=True)

        list_adapter2.bind(on_selection_change=listSelected)

        list_view2 = ListView(adapter=list_adapter2,
                              pos_hint={
                                  'center_x': .25,
                                  'center_y': .28
                              },
                              size_hint=(0.25, 0.5))
        list_view2.background_normal = (0, 0, 0, 0)

        sortedPlayerList = []

        data3 = [{'text': i, 'is_selected': False} for i in sortedPlayerList]

        args_converter3 = lambda row_index, rec: {
            'text': rec['text'],
            'size_hint_x': 10,
            'size_hint_y': None,
            'font_size': 15,
            'selected_color': (.5, .5, .5, .25),
            'deselected_color': (50, 50, 50, 1),
            'color': (0, 0, 0, 1),
            'height': 45
        }

        list_adapter3 = ListAdapter(data=data3,
                                    args_converter=args_converter3,
                                    cls=ListItemButton,
                                    selection_mode='single',
                                    allow_empty_selection=True)

        list_adapter3.bind(on_selection_change=listSelected)

        list_view3 = ListView(adapter=list_adapter3,
                              pos_hint={
                                  'center_x': .75,
                                  'center_y': .28
                              },
                              size_hint=(0.25, 0.5))
        list_view3.background_normal = (0, 0, 0, 0)

        tieButton = Button(text="Tie Breaker",
                           color=(255, 255, 255, 1),
                           size_hint=(0.175, 0.05),
                           pos_hint={
                               'center_x': .5,
                               'center_y': .1
                           })
        tieButton.bind(on_press=dieSelect)

        totalValLabel = Label(text='??',
                              color=(0, 0, 0, 1),
                              font_size='80sp',
                              font_name='./images/Captain_Redemption.ttf',
                              pos_hint={
                                  'center_x': .5,
                                  'center_y': .5
                              })

        rollButton = Button(text="Roll",
                            color=(255, 255, 255, 1),
                            size_hint=(0.175, 0.05),
                            pos_hint={
                                'center_x': .75,
                                'center_y': .1
                            })
        rollButton.bind(on_press=dieSelect)

        skStatLabel = Label(text='--',
                            color=(0, 0, 0, 1),
                            font_size='33sp',
                            font_name='./images/Captain_Redemption.ttf',
                            pos_hint={
                                'center_x': .48,
                                'center_y': .37
                            })

        #################################################################################################################################

        fp_list.append(dImg1)
        fp_list.append(initButton)
        fp_list.append(stButton)
        fp_list.append(spButton)
        fp_list.append(skButton)
        fp_list.append(saButton)
        fp_list.append(wpButton)
        fp_list.append(dLabel)

        sp_list.append(backButton)
        sp_list.append(list_view)
        sp_list.append(attack)
        sp_list.append(Damage)
        sp_list.append(sLabel)
        sp_list.append(sLabel2)
        sp_list.append(sLabel3)
        sp_list.append(sLabel4)
        sp_list.append(manualButton)
        sp_list.append(autoButton)
        sp_list.append(autoButton2)
        sp_list.append(dImg4)
        sp_list.append(sLabel5)

        wpp_list.append(dImg2)
        wpp_list.append(dImg3)
        wpp_list.append(dImg4)
        wpp_list.append(backButton)
        wpp_list.append(list_view)
        wpp_list.append(attack)
        wpp_list.append(Damage)
        wpp_list.append(sLabel)
        wpp_list.append(sLabel2)
        wpp_list.append(sLabel3)
        wpp_list.append(sLabel4)
        wpp_list.append(manualButton)
        wpp_list.append(autoButton)
        wpp_list.append(autoButton2)
        wpp_list.append(sLabel5)

        initp_list.append(dImg4)
        initp_list.append(sLabel5)
        initp_list.append(list_view2)
        initp_list.append(backButton)
        initp_list.append(list_view3)
        initp_list.append(tieButton)

        spp_list.append(dImg2)
        spp_list.append(dImg4)
        spp_list.append(backButton)
        spp_list.append(list_view)
        spp_list.append(attack)
        spp_list.append(sLabel)
        spp_list.append(sLabel3)
        spp_list.append(sLabel5)
        spp_list.append(manualButton)
        spp_list.append(rollButton)

        stp_list.append(dImg2)
        stp_list.append(dImg4)
        stp_list.append(backButton)
        stp_list.append(list_view)
        stp_list.append(attack)
        stp_list.append(sLabel)
        stp_list.append(sLabel5)
        stp_list.append(sLabel3)
        stp_list.append(manualButton)
        stp_list.append(rollButton)

        skp_list.append(dImg2)
        skp_list.append(dImg4)
        skp_list.append(backButton)
        skp_list.append(list_view)
        skp_list.append(attack)
        skp_list.append(sLabel)
        skp_list.append(sLabel5)
        skp_list.append(sLabel3)
        skp_list.append(manualButton)
        skp_list.append(rollButton)
        skp_list.append(skStatLabel)

        sap_list.append(dImg2)
        sap_list.append(dImg4)
        sap_list.append(backButton)
        sap_list.append(list_view)
        sap_list.append(attack)
        sap_list.append(sLabel)
        sap_list.append(sLabel3)
        sap_list.append(sLabel5)
        sap_list.append(manualButton)
        sap_list.append(rollButton)

        tp_list.append(backButton)
        f2p_list.append(backButton)

        for item2 in fp_list:
            self.add_widget(item2)
Ejemplo n.º 59
0
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(constants.NEW_TEMPLATE_IMAGE_PATH, name)
        image_source = join(get_kd_data_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'))