Exemplo n.º 1
0
class Options(GridLayout):
    def __init__(self, **kwargs):
        super(Options, self).__init__(**kwargs)
        self.rows = 1
        self.spinner = Spinner(text='Easy',values=('Easy', 'Medium', 'Hard'))
        self.add_widget(self.spinner)
        self.spinner.bind(text=self.show_selected_value)
        startBtn = Button(text = "start")
        self.add_widget(startBtn)
        startBtn.bind(on_release=self.start)
        stopBtn = Button(text = "stop")
        self.add_widget(stopBtn)
        stopBtn.bind(on_press=self.stop)

    def stop(self,*args):
        App.get_running_app().root.children[1].stop()

    def start(self,ins,*args):
        app = App.get_running_app().root.children[1]
        if ins.text == "continue":
            app.continue_move()
        elif ins.text == "start":
            app.start()
            ins.text = "continue"


    def show_selected_value(self, ins,text):
        if text == 'Easy':
            pass
        elif text == 'Medium':
            pass
        elif text == 'Hard':
            pass
Exemplo n.º 2
0
class DrpDwnList(BoxLayout):

    def __init__(self, caption, values, action=None, s_text='..select..',
                 **kwargs):
        self.values = values
        self.action = action
        super(DrpDwnList, self).__init__(padding=0, spacing=0,
                                         size_hint=(1,None),
                                         orientation='vertical', **kwargs)
        lbl = Label(
            # height: 10
            # font_size: 12
            size_hint=(1, .5), text=caption)
        self.add_widget(lbl)
        self.spinner = Spinner(
            # default value shown
            text=s_text,
            # available values
            values=values,
            # just for positioning in our example
            size_hint=(1, .5),
            #size=(100, 44),
            #pos_hint={'center_x': .5, 'center_y': .5}
                )
        if action is not None:
            self.spinner.bind(text=self.use_selected_value)
        self.add_widget(self.spinner)

    def use_selected_value(self, spinner, text):
        self.action(text)
    def titlebar(self):
        layout=BoxLayout(padding='2sp',size_hint=(1,None),height='65sp')
        layout.orientation='horizontal'

        #credentials = self.accept_credentials()
        self.submit_popup = Popup(title='Enter credentials',content=self.accept_credentials(),size_hint=(0.6, 0.35))
        #credentials.children[1].bind(on_press=self.submit_popup.dismiss)

        submit = Button(text='Submit',size_hint=(0.4,1))
        if self.element.read_token(self):
            submit.bind(on_press=partial(self.submit_assignment))
        else:
            submit.bind(on_press=self.submit_popup.open)

        run = Button(text='Run',size_hint=(0.4,1))
        run.bind(on_press=self.run)

        ex_dropdown = Spinner(text=self.current_ex,size_hint=(1,1))
        ex_dropdown.values = os.listdir('./res/')
        ex_dropdown.bind(text=self.updateExercise)

        layout.add_widget(run)
        layout.add_widget(ex_dropdown)
        layout.add_widget(submit)

        return layout
Exemplo n.º 4
0
    def build(self):
        b = BoxLayout(orientation='vertical')
        languages = Spinner(
            text='language',
            values=sorted(['KvLexer', ] + list(lexers.LEXERS.keys())))

        languages.bind(text=self.change_lang)

        menu = BoxLayout(
            size_hint_y=None,
            height='30pt')
        fnt_size = Spinner(
            text='12',
            values=list(map(str, list(range(5, 40)))))
        fnt_size.bind(text=self._update_size)

        fonts = [
            file for file in LabelBase._font_dirs_files
            if file.endswith('.ttf')]

        fnt_name = Spinner(
            text='RobotoMono',
            option_cls=Fnt_SpinnerOption,
            values=fonts)
        fnt_name.bind(text=self._update_font)
        mnu_file = Spinner(
            text='File',
            values=('Open', 'SaveAs', 'Save', 'Close'))
        mnu_file.bind(text=self._file_menu_selected)
        key_bindings = Spinner(
            text='Key bindings',
            values=('Default key bindings', 'Emacs key bindings'))
        key_bindings.bind(text=self._bindings_selected)

        menu.add_widget(mnu_file)
        menu.add_widget(fnt_size)
        menu.add_widget(fnt_name)
        menu.add_widget(languages)
        menu.add_widget(key_bindings)
        b.add_widget(menu)

        self.codeinput = CodeInputWithBindings(
            lexer=KivyLexer(),
            font_size=12,
            text=example_text,
            key_bindings='default',
        )

        b.add_widget(self.codeinput)

        return b
Exemplo n.º 5
0
class MenuWidget(FloatLayout):
        def __init__(self, **kwargs):
                super(MenuWidget, self).__init__(**kwargs)

                default_choice = "demo_tiles"
                self.choices = {
                        "demo_text": "Text drawing",
                        "demo_bounce": "Basic physics simulation",
                        "demo_starship": "'Endless' scrolling background and animation",
                        "demo_tiles": "Tile map scrolling",
                        "demo_pong": "Simple Pong game",
                        "demo_breakout": "Breakout implemented with physical mover",
                        "demo_collision": "Optimized collision checking demo/test",
                        "demo_collision_1": "Simple collision test case",
                        "demo_control_1": "Demonstrates a more complex control scheme",
                        }

                layout = StackLayout(orientation="tb-lr", padding=[10, 20, 10, 20])

                layout.add_widget(Image(source="assets/img/ui/logo.png", size_hint=(1, 0.4)))

                layout.add_widget(Label(text="Choose demo:", size_hint=(1, 0.1)))

                self.spinner = Spinner(text=default_choice, values=[x for x in self.choices.iterkeys()], size_hint=(1, 0.1))
                layout.add_widget(self.spinner)
                self.spinner.bind(text=self.show_selected_value)

                self.description_label = Label(text=self.choices[default_choice], valign="middle", halign="center", size_hint=(1, 0.3))
                self.description_label.bind(size=self.description_label.setter("text_size"))
                layout.add_widget(self.description_label)

                run_button = Button(text="Run", size_hint=(1, 0.1))
                run_button.bind(state=self.on_run)
                layout.add_widget(run_button)

                self.add_widget(layout)

        def show_selected_value(self, spinner, value):
                self.description_label.text = self.choices[value]

        def on_run(self, instance, value):
                if self.parent:
                        parent = self.parent
                        parent.remove_widget(self)

                        state = None
                        exec("state = %s.create(float(Window.width), float(Window.height), float(tile_size))" % self.spinner.text)

                        parent.add_widget(ScreenWidget(state))
Exemplo n.º 6
0
    def getUI(self):
        """get the ui element"""
        if 'enum' in self._typeInfo:
            result = Spinner()
            result.values = self._typeInfo['enum']
        elif self._typeInfo['type'].lower() == 'boolean':
            result = Spinner()
            result.values = ['true', 'false']
        else:
            result = TextInput()
        if self.value:
            result.text = self.value.lower()
        skin = sm.getSkin('text', self.asset)
        result.size = sm.getControlSize(skin, self.asset)

        self.uiEl = result
        self.prepareUiElement()
        result.bind(text=self.value_changed)
        return result
Exemplo n.º 7
0
    def __init__(self, *args, **kwargs):
        super(MapBrowser, self).__init__(**kwargs)

        mapview = MapView(lat=50.6394,
                          lon=3.057,
                          zoom=8,
                          cache_dir="cache")
        
        self.add_widget(mapview)

        mapview.add_widget(MapMarker(lat=50.6394, lon=3.057))
        mapview.add_widget(MapMarker(lat=-33.867, lon=151.206))

        top_bar = Toolbar(pos_hint={'top': 1})

        def center_on(lat, lon, instance):
            mapview.center_on(lat, lon)
            label_lat.text = "Latitude: {}".format(mapview.lat)
            label_lon.text = "Longitude: {}".format(mapview.lon)

        btn_lille = Button(text="Move to Lille, France")
        btn_lille.bind(on_release=partial(center_on, 50.6394, 3.057))
        top_bar.add_widget(btn_lille)

        btn_sydney = Button(text="Move to Sydney, Autralia")
        btn_sydney.bind(on_release=partial(center_on, -33.867, 151.206))
        top_bar.add_widget(btn_sydney)

        spinner_src = Spinner(text="mapnik", values=MapSource.providers.keys())
        def set_source(instance, selected_text):
            mapview.map_source = selected_text
        spinner_src.bind(text=set_source)
        top_bar.add_widget(spinner_src)

        bottom_bar = Toolbar()
        label_lon = Label(text="Longitude: {}".format(mapview.lon))
        label_lat = Label(text="Latitude: {}".format(mapview.lat))
        bottom_bar.add_widget(label_lon)
        bottom_bar.add_widget(label_lat)

        self.add_widget(top_bar)
        self.add_widget(bottom_bar)
Exemplo n.º 8
0
 def show_personal_info(self):
     content = BoxLayout(orientation='vertical')
     scroll_view = ScrollView(do_scroll_x=False)
     self.personal_info_bottom_layout = GridLayout(cols=2, spacing='5dp', size_hint_x=1, size_hint_y=None,
                                                   row_default_height='30dp', row_force_default=True)
     self.personal_info_bottom_layout.bind(minimum_height=self.personal_info_bottom_layout.setter('height'))
     key_dropdown = Spinner(values=[key['public'] for key in json.load(open('api_keys.json'))], size_hint=(1, None),
                            height=50, text='Choose an API Key')
     key_dropdown.bind(text=self.load_personal_info)
     content.add_widget(key_dropdown)
     scroll_view.add_widget(self.personal_info_bottom_layout)
     content.add_widget(scroll_view)
     button_layout = BoxLayout(size_hint=(1, 0.1))
     button = Button(text=self.PlungeApp.get_string('Close'), size_hint=(1, None), height=50)
     button_layout.add_widget(button)
     content.add_widget(button_layout)
     title = "Personal Stats"
     self.info = Popup(title=title, content=content, auto_dismiss=False, size_hint=(.7, .7))
     button.bind(on_press=self.close_info)
     self.info.open()
     return
Exemplo n.º 9
0
    def __init__(self, **kwargs):
        kwargs['orientation'] = 'vertical'
        super(MainWindow, self).__init__(**kwargs)

        spinner = Spinner(
            # default value shown
            text='Home',
            # available values
            values=('Home', 'Test', 'AddWord'),
            # just for positioning in our example
            size_hint=(1, None),
            size=(100, 44),
            pos_hint={'center_x': .5, 'center_y': .5})

        spinner.bind(text=self.set_page_vidget)

        self.add_widget(spinner)

        self.work_area = BoxLayout()
        self.work_area.add_widget(Home())
        self.add_widget(self.work_area)
Exemplo n.º 10
0
    def build_alarm_popup(self):
        layout = BoxLayout(orientation='horizontal')

        hourspin = Spinner(text=str(self.hour), 
                           values=list(map(str, list(range(1, 25)))), 
                           sync_height=True, 
                           font_size=(self.height/4.0), 
                           option_cls=SpinnerButton)

        hourspin.bind(text=self.set_hour)

        minspin = Spinner(text=str(self.minutes), 
                          values=list(map(str, list(range(1, 60)))), 
                          sync_height=True, 
                          font_size=(self.height/4.0), 
                          option_cls=SpinnerButton)

        minspin.bind(text=self.set_minute)

        layout.add_widget(hourspin)
        layout.add_widget(minspin)

        return layout
Exemplo n.º 11
0
    def add_row(self, instance):
        """
        Add a row to the main exchange screen
        :param instance:
        :return:
        """
        self.num_rows += 1
        keys_button = Button(text='Keys', size_hint_x=0.2, id='%d' % self.num_rows)
        keys_button.bind(on_release=self.enter_keys)
        self.content.add_widget(keys_button)
        self.keys_button.append(keys_button)
        address = TextInput(size_hint_x=0.2, padding=[6, 10, 6, 10],
                            multiline=False, font_size=18, id='%d' % self.num_rows)
        address.bind(text=self.check_address)
        self.content.add_widget(address)
        self.address.append(address)
        unit = Spinner(values=self.currencies, text=self.currencies[0], size_hint_x=0.2, id='%d' % self.num_rows)
        self.selected_unit = self.currencies[0]
        unit.bind(text=self.set_unit)
        self.content.add_widget(unit)
        self.unit.append(unit)
        rates = Button(text='Rates', size_hint_x=0.2, id='%d' % self.num_rows)
        rates.bind(on_release=self.enter_rates)
        self.content.add_widget(rates)
        self.rates.append(rates)
        bot = Spinner(values=self.bots, text=self.bots[0], size_hint_x=0.2, id='%d' % self.num_rows)
        self.selected_bot = self.bots[0]
        bot.bind(text=self.set_bot)
        self.content.add_widget(bot)
        self.bot.append(bot)

        if isinstance(instance, dict):
            keys_button.text = instance['public'][:8] + ' / ' + instance['secret'][:8]
            address.text = instance['address']
            unit.text = instance['unit']
            rates.text = instance['ask'] + ' | ' + instance['bid']
            bot.text = instance['bot']
Exemplo n.º 12
0
    def build(self):
        b = BoxLayout(orientation='vertical')
        languages = Spinner(
            text='language',
            values=sorted(['KvLexer', ] + list(lexers.LEXERS.keys())))

        languages.bind(text=self.change_lang)

        menu = BoxLayout(
            size_hint_y=None,
            height='30pt')
        fnt_size = Spinner(
            text='12',
            values=list(map(str, list(range(5, 40)))))
        fnt_size.bind(text=self._update_size)
        fnt_name = Spinner(
            text='DroidSansMono',
            option_cls=Fnt_SpinnerOption,
            values=sorted(map(str, fonts.get_fonts())))
        fnt_name.bind(text=self._update_font)
        mnu_file = Spinner(
            text='File',
            values=('Open', 'SaveAs', 'Save', 'Close'))
        mnu_file.bind(text=self._file_menu_selected)

        menu.add_widget(mnu_file)
        menu.add_widget(fnt_size)
        menu.add_widget(fnt_name)
        menu.add_widget(languages)
        b.add_widget(menu)

        self.codeinput = CodeInput(
            lexer=KivyLexer(),
            font_name='data/fonts/DroidSansMono.ttf', font_size=12,
            text=example_text)

        b.add_widget(self.codeinput)

        return b
Exemplo n.º 13
0
    def start_server(self, dt):
        '''
        initializes the client connection, and gets image data
        '''
        hostname = "0.0.0.0"
        if not self._started:
            count = 0
            while True:  # Keep trying in case server is not up yet
                import socket
                try:
                    from xmlrpclib import ServerProxy
                    # connect to meta server first
                    prox = \
                        ServerProxy("http://" + hostname + ":5007")
                    # get servers address from the meta server
                    self._ros_uri = prox.startProcess()
                    Logger.info('Server Address\n <%s>', self._ros_uri[0])
#                    self._client = \
#                    KeyboardInterface(self._ros_uri,
#                    self._args.image_updates)
                    self._started = True
                    Logger.info('Client Connected...')
                    # use double quote for subscriber name
                    # TODO: convert get_image_data into a list, so
                    # that each key is the image data of a robot
                    self._ros_uri.pop(0)            # remove ROS uri
                    self._im_string = self._ros_uri 
                    val = []     # store las byte of robot's address
                    for i in range(len(self._ros_uri)): 
                        self._robot_id = \
                            self._ros_uri[i].split('.')[3]
                        rospy.Subscriber(
                            "/output/image_raw/compressed"+
                            self._robot_id, CompressedImage,
                            self.get_image_data)
                        val.append(self._robot_id)
                    self._robot_id = val[0]
                    # create a robot selection menu
                    robot_menu = Spinner(
                        # default robot showed
                        text=self._ros_uri[0].split('.')[3],
                        # available robots/values
                        values = val,
                        # just for positioning in our example
                        size_hint=(None, None),
                        size=(100, 44),
                        pos_hint={'center_x': .1, 'center_y': .8})
                    self.add_widget(robot_menu)
                    robot_menu.bind(text=self.selected_robot)
                    robot_menu_label = \
                        Label(text='Select a robot:', 
                        pos_hint={'center_x': .1, 'center_y': .87})
                    self.add_widget(robot_menu_label)
                    from threading import Thread
                    spin_thread = Thread(target=lambda: rospy.spin())
                    spin_thread.start()
                    break
                except socket.error:
                    count += 1
                    import time
                    time.sleep(.5)

                if count > 100:
                    waiting = 'Waiting for meta server at %s'
                    uri="http://" + hostname + ":12345"
                    Logger.info(waiting, uri)
Exemplo n.º 14
0
	def build(self):
		global notesChange
		global octaveSet
		global keySet
		global scaleSet
		global allScales
		global currentNotes
		
		#the title that appears at the top
		header = Label(text='DJ Slate')
		
		#create binding function to set octave
		#create octave spinner, add four choices
		def setOctaves(spinner, oct):
			global notesChange
			global octaveSet
			octaveSet = int(oct.split(' ')[0]) #get N from 'N Octaves'
			notesChange = True
		
		octaves = Spinner(
			text = '2 Octaves', 
			values = ('1 Octave', '2 Octaves', '3 Octaves', '4 Octaves'),
			background_color = (1,1,1,0)
		)
		
		octaves.bind(text=setOctaves)
		
		#create setKey binding function
		#create key spinner, add keys
		def setKey(spinner, base):
			global notesChange
			global keySet
			keySet = base
			notesChange = True
		
		key = Spinner(
			text = 'C', 
			values = ('C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'),
			background_color = (1,1,1,0)
		)
		
		key.bind(text=setKey)
		
		#process midi.txt
		list = open('midi.txt').read()
		list = list.splitlines()
		instrumentNames = []
		
		#add instruments to spinner, bind select
		#number = 1, 2, 3, etc..
		#sound = Acoustic Grand Piano, etc...
		#instrumentNames[number-1] = sound
		for item in list:
			item = item.split(' ')
			number = int(item[0])
			sound = ' '.join(item[1:])
			instrumentNames.append(sound)
		
		instrument = Spinner(
			text = instrumentNames[0],
			values = tuple(instrumentNames),
			background_color = (1,1,1,0)
		)
		
		def setInstrument(spinner, inst):
			fluidsynth.set_instrument(1, instrumentNames.index(inst))
		
		instrument.bind(text=setInstrument)
		
		#process scales.txt
		list = open('scales.txt').read()
		list = list.splitlines()
		scaleNames = {}
		rawNames = [] #used to preserve name order
		
		#add scales to spinner, bind select
		#scaleNames[name_of_scale] = [type, notes]
		for item in list:
			item = item.split(' ')
			sname = item[0].replace('_',' ')
			type = item[1]
			notes = item[2:]
			rawNames.append(sname)
			scaleNames[sname] = [type, notes]
		
		scale = Spinner(
			text = 'Major',
			values = tuple(rawNames),
			background_color = (1,1,1,0)
		)
		
		def setScale(spinner, val):
			global notesChange
			global scaleSet
			scaleSet = val
			notesChange = True
		
		allScales = scaleNames
		scale.bind(text=setScale)
		
		#Create three parts of screen
		label = BoxLayout(size_hint=(1, .1))#, pos=(0, Window.height*.9))
		slate = SlateWidget(size_hint=(1, .8))#, pos=(0, Window.height*.2))
		buttons = BoxLayout(size_hint=(1, .1))#,  pos=(0, 0))
		
		#Add subsidiary buttons + slate
		buttons.add_widget(instrument)
		buttons.add_widget(scale)
		label.add_widget(octaves)
		label.add_widget(header)
		label.add_widget(key)
		
		#Add to window and return
		root = BoxLayout(orientation='vertical') #FloatLayout()
		root.add_widget(label)
		root.add_widget(slate)
		root.add_widget(buttons)
		
		'''def reposition(*args):
			labelMove = Animation(x=0, y=Window.height*.9, duration=0.1, t='instant')
			labelMove.start(label)
			
			slateMove = Animation(x=0, y=Window.height*.2, duration=0.1, t='instant')
			slateMove.start(slate)
		
		Window.bind(on_resize=reposition)'''
		
		return root
Exemplo n.º 15
0
class EditPopup(Popup):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.size_hint = (0.45, 0.5)
        self.title = 'Edit'
        self.title_align = 'center'
        self.title_color = get_color_from_hex('#00FF00')
        self.title_size = 19

        self.inlayout = FloatLayout(size_hint=(1, 1),
                                    pos_hint={
                                        'x': 0,
                                        'y': 0
                                    })

        self.labels = [
            txt.upper() for txt in AmountsField.existing_amounts_dict.keys()
        ]

        self.to_be_edited = Spinner(size_hint=(0.45, 0.25),
                                    pos_hint={
                                        'x': 0.05,
                                        'y': 0.6
                                    },
                                    values=self.labels,
                                    text=self.labels[0],
                                    sync_height=True)
        self.to_be_edited.bind(on_press=self.on_spinner_text)

        self.inlayout.add_widget(self.to_be_edited)
        self.add_widget(self.inlayout)

        # Plus Box.
        self.plus_box = BoxLayout(size_hint=(0.25, 0.1),
                                  orientation='horizontal',
                                  pos_hint={
                                      'x': 0.55,
                                      'y': 0.77
                                  })

        self.plus_checkbox = CheckBox(size_hint=(0.2, 1), group='plusminus')
        self.plus_box.add_widget(self.plus_checkbox)

        self.plus_label = Label(text='Plus', size_hint=(0.2, 1), font_size=19)
        self.plus_box.add_widget(self.plus_label)
        self.inlayout.add_widget(self.plus_box)

        # Minus Box.
        self.minus_box = BoxLayout(size_hint=(0.25, 0.1),
                                   orientation='horizontal',
                                   pos_hint={
                                       'x': 0.55,
                                       'y': 0.62
                                   })

        self.minus_checkbox = CheckBox(size_hint=(0.2, 1), group='plusminus')
        self.minus_box.add_widget(self.minus_checkbox)

        self.minus_label = Label(text='Minus',
                                 size_hint=(0.2, 1),
                                 font_size=19)
        self.minus_box.add_widget(self.minus_label)
        self.inlayout.add_widget(self.minus_box)

        # Price change.
        self.price_box = BoxLayout(size_hint=(0.35, 0.1),
                                   orientation='horizontal',
                                   pos_hint={
                                       'x': 0.555,
                                       'y': 0.47
                                   })

        self.price_checkbox = CheckBox(size_hint=(0.2, 1), group='plusminus')
        self.price_box.add_widget(self.price_checkbox)

        self.price_label = Label(text='Price Change',
                                 size_hint=(0.4, 1),
                                 font_size=19)
        self.price_box.add_widget(self.price_label)
        self.inlayout.add_widget(self.price_box)

        self.input_label = Label(pos_hint={
            'x': 0.16,
            'y': 0.33
        },
                                 size_hint=(0, 0),
                                 text='[b][u]Amount[/u]:[/b]',
                                 markup=True,
                                 font_size=20)
        self.inlayout.add_widget(self.input_label)

        self.input_num = ModifiedTextInput(input_filter='float',
                                           pos_hint={
                                               'x': 0.05,
                                               'y': 0.15
                                           },
                                           size_hint=(0.5, 0.12))
        self.inlayout.add_widget(self.input_num)

        self.popup_btn = Button(pos_hint={
            'x': 0.7,
            'y': 0.1
        },
                                size_hint=(0.25, 0.2),
                                text='Apply',
                                font_size=20)
        self.inlayout.add_widget(self.popup_btn)

        self.popup_btn.bind(on_press=self.on_popup_btn_press)
        self.price_checkbox.bind(on_press=self.price_cb_onpress)

    def on_spinner_text(self, spn):
        self.price_checkbox.state = 'normal'

    def price_cb_onpress(self, ins):
        self.input_num.text = str(AmountsField.existing_amounts_dict[
            self.to_be_edited.text.lower()][1])

    def on_popup_btn_press(self, btn):

        self.edited_title = self.to_be_edited.text.lower()
        self.current_value = AmountsField.existing_amounts_dict[
            self.edited_title]

        try:
            edit_number = float(self.input_num.text)
        except ValueError:
            edit_number = 1

        if self.edited_title in ['alfa days', 'touch days'
                                 ] and self.price_checkbox.state != "down":
            days_add_text = '[b]Cannot Add/Remove Days![/b]'
            return self._label_popup('Error', days_add_text)

        elif self.minus_checkbox._get_active():
            self.current_value[0] -= edit_number
            self._update_text()

        elif self.plus_checkbox._get_active():
            self.current_value[0] += edit_number
            self._update_text()

        elif self.price_checkbox._get_active():
            self.current_value[1] = float(self.input_num.text)

        else:
            empty_field_text = 'Please Choose [b]Minus[/b], [b]Plus[/b]\nor [b]Change Price[/b]'
            return self._label_popup('Error', empty_field_text)

        with open('.storage.json', 'w') as f:
            json.dump(AmountsField.existing_amounts_dict, f)

    def _update_text(self):
        what_text = self.edited_title
        if what_text in ['alfa dollars', 'touch dollars']:
            text_to_be = f'{what_text.capitalize()}: {format(self.current_value[0], ".2f")}'
        else:
            text_to_be = f'{what_text.capitalize()}: {int(self.current_value[0])}'
        AmountsField.labels_dict[self.edited_title].text = text_to_be

    def _label_popup(self, title, text):
        return Popup(title=title,
                     size_hint=(0.35, 0.35),
                     content=Label(text=text, font_size=20,
                                   markup=True)).open()
Exemplo n.º 16
0
class ZipFindApp(App):
    def build(self):
        self.root = NiceBoxLayout(orientation="vertical")
        self.api = "http://www.afsusa.org/site/searchStudents/?zipcode={0}"

        self.title = "AFS USA Student Finder"

        from data import zips

        self.shelf = {"data":  [],
                      "bios":      [],
                      "zips_done": [],
                      "zips_todo": zips.zips[:],
                      "justrun:":  True}

        self.students = []

        random.shuffle(self.shelf["zips_todo"])
        del zips

        self.toolbar = BoxLayout(orientation="horizontal", padding=5, spacing=5, height=45, size_hint=(1, None))
        self.filterbar = BoxLayout(orientation="horizontal", padding=5, spacing=5, height=45, size_hint=(1, None))

        self.resultslist = GridLayout(cols=1, padding=5, spacing=5, size_hint=(1, None))
        self.resultslist.bind(minimum_height=self.resultslist.setter('height'))

        scroll = ScrollView(pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False, size_hint=(1, 1))
        scroll.add_widget(self.resultslist)

        self.root.add_widget(self.toolbar)
        self.root.add_widget(scroll)
        self.root.add_widget(self.filterbar)

        # Working ZIP code for testing purposes: 98058
        self.zipentry = TextInput(text='ZIP Code', font_size=20, height=45, multiline=False, on_text_validate=self.ui_search)
        self.nameentry = TextInput(text='Name', font_size=20, height=45, multiline=False, on_text_validate=self.ui_autosearch)
        self.nameentry.bind(text=self.filter)
        self.helpbutton = Button(on_press=hide_keyboard, on_release=self.show_help, height=40, width=40, size_hint=(None, None), background_normal=os.path.join(curdir, "images/help_normal.png"), background_down=os.path.join(curdir, "images/help_down.png"))
        self.autosearchbutton = Button(on_press=hide_keyboard, on_release=self.ui_autosearch, height=40, width=40, size_hint=(None, None), background_normal=os.path.join(curdir, "images/autosearch_normal.png"), background_down=os.path.join(curdir, "images/autosearch_down.png"))
        self.searchbutton = Button(on_press=hide_keyboard, on_release=self.ui_search, height=40, width=40, size_hint=(None, None), background_normal=os.path.join(curdir, "images/search_normal.png"), background_down=os.path.join(curdir, "images/search_down.png"), background_disabled_normal=os.path.join(curdir, "images/search_disabled.png"), background_disabled_down=os.path.join(curdir, "images/search_disabled.png"))
        self.toolbar.add_widget(self.zipentry)
        self.toolbar.add_widget(self.nameentry)
        self.toolbar.add_widget(self.helpbutton)

        if persistence:
            self.persbutton = Button(on_press=hide_keyboard, on_release=self.ui_load_persistence, height=40, width=40, size_hint=(None, None), background_normal=os.path.join(curdir, "images/persistence_normal.png"), background_down=os.path.join(curdir, "images/persistence_down.png"))

        self.toolbar.add_widget(self.persbutton)
        self.toolbar.add_widget(self.autosearchbutton)
        self.toolbar.add_widget(self.searchbutton)

        self.sports = Spinner(
            text='Any sport',
            values=["Any sport", 'Badminton', 'Baseball', 'Basketball', 'Bicycling', 'Boating', 'Cheerleading', 'Dance', 'Diving', 'Field Hockey', 'Football', 'Golf', 'Gymnastics', 'Handball', 'Horseback Riding', 'Ice Hockey', 'Martial Arts', 'Running', 'Skating', 'Skiing', 'Soccer', 'Softball', 'Swimming', 'Tennis', 'Track', 'Volleyball'],
            size_hint=(None, None),
            height=40)
        self.sports.bind(text=self.filter)
        self.music = Spinner(
            text='Any music',\
            values=["Any music", "Guitar", "Piano", "Singing"],
            size_hint=(None, None),
            height=40)
        self.music.bind(text=self.filter)
        self.genders = Spinner(
            text='Any gender',
            values=("Any gender", "Male", "Female"),
            size_hint=(None, None),
            height=40)
        self.genders.bind(text=self.filter)
        self.interests = Spinner(
            text='Any interest',
            values=["Any interest", 'Computer', 'Cooking', 'Environment', 'Fishing', 'Games/cards', 'Gardening', 'Movies', 'Museums', 'Photography', 'Reading', 'Shopping', 'Television', 'Theater', 'Travel', 'Video Games', 'Volunteering'],
            size_hint=(None, None),
            height=40)
        self.interests.bind(text=self.filter)
        self.countries = Spinner(
            text="Any country",
            values=("Any country", 'Albania', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahrain', 'Bangladesh', 'Belgium', 'Bolivia', 'Bosnia and Herzegovina', 'Brazil', 'Bulgaria', 'Cameroon', 'Canada', 'Chile', 'China', 'Colombia', 'Costa Rica', 'Croatia', 'Czech Republic', 'Denmark', 'Dominican Republic', 'Ecuador', 'Egypt', 'Finland', 'France', 'Gaza', 'Georgia', 'Germany', 'Ghana', 'Greenland', 'Guatemala', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Israel', 'Italy', 'Japan', 'Kazakhstan', 'Kenya', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Latvia', 'Lebanon', 'Liberia', 'Libya', 'Macedonia', 'Malaysia', 'Mali', 'Mexico', 'Moldova', 'Morocco', 'Mozambique', 'Netherlands', 'New Zealand', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Panama', 'Paraguay', 'Peru', 'Philippines', 'Portugal', 'Qatar', 'Russia', 'Saudi Arabia', 'Senegal', 'Sierra Leone', 'Slovakia', 'Slovenia', 'South Africa', 'South Korea', 'Spain', 'Sweden', 'Switzerland', 'Tajikistan', 'Tanzania', 'Thailand', 'Tunisia', 'Turkey', 'Turkmenistan', 'Ukraine', 'West Bank', 'Yemen', "Any country"),
            size_hint=(None, None),
            height=40)
        self.countries.bind(text=self.filter)
        self.group_names = {
            "Interests":    self.interests,
            "Music":        self.music,
            "Sports":       self.sports
        }
        self.filterbar.add_widget(Widget(size_hint=(1, None)))
        self.filterbar.add_widget(self.sports)
        self.filterbar.add_widget(self.music)
        self.filterbar.add_widget(self.genders)
        self.filterbar.add_widget(self.interests)
        self.filterbar.add_widget(self.countries)

        self.bind(on_start=self.post_build_init, on_stop=self.pre_close)

        self.resultslist.add_widget(Label(text="\n\nSearch something to start.", halign="center"))

        return self.root

    def ui_search(self, *args):
        self.resultslist.clear_widgets()
        self.resultslist.add_widget(Label(text="\n\nLoading...", halign="center"))
        thr = thread.start_new_thread(self.search_thread, ())

    def search_thread(self):
        self.shelf["justrun"] = False
        studs = self.load_zip(self.zipentry.text)
        self.resultslist.clear_widgets()
        self.shelf["bios"] = []
        self.students = []

        if not studs:
            self.resultslist.add_widget(Label(text="\n\nNo results found.", halign="center"))
        elif type(studs) == type(str()):
           self.resultslist.add_widget(Label(text="\n\n" + studs, halign="center")) 
        else:
            for stud in studs:
                self.shelf["data"].append(stud)
                #print self.shelf["data"]
                self.process_stud(stud, self.zipentry.text)
        return None

    def process_stud(self, stud, zipcode):
        stud["zipcode"] = zipcode
        for i in stud["interests"]:
            try:
                if not i["name"] in self.group_names[i["group_names"]].values:
                    self.group_names[i["group_names"]].values.append(i["name"])
            except KeyError:
                pass
        if not stud["bio"] in self.shelf["bios"]:
            student = Student(data=stud)
            if self.to_add(student):
                self.resultslist.add_widget(student)
            self.shelf["bios"].append(stud["bio"])
            self.students.append(student)

    def load_zip(self, zipcode):
        try:
            with contextlib.closing(urllib.urlopen(self.api.format(zipcode))) as f:
                js = json.loads(f.read())
            if not js["success"]:
                return None
            else:
                return js["students"]
        except IOError:
            return "Couldn't connect to AFS. Please check your connection."


    def ui_autosearch(self, *args):
        if self.shelf["zips_done"] == 0:
            self.resultslist.clear_widgets()
        self.searchbutton.background_disabled_normal=os.path.join(curdir, "images/search_disabled.png")
        self.searchbutton.background_disabled_down=os.path.join(curdir, "images/search_disabled.png")
        self.searchbutton.unbind(on_release=self.ui_search)
        self.autosearchbutton.background_disabled_normal=os.path.join(curdir, "images/autosearch_disabled.png")
        self.autosearchbutton.background_disabled_down=os.path.join(curdir, "images/autosearch_disabled.png")
        self.autosearchbutton.unbind(on_release=self.ui_autosearch)
        self.autosearchthread = thread.start_new_thread(self.autosearch_thread, ())

    def on_search_finished(self):
        self.searchbutton.background_normal=os.path.join(curdir, "images/search_normal.png")
        self.searchbutton.background_down=os.path.join(curdir, "images/search_down.png")
        self.searchbutton.bind(on_release=self.ui_search)
        self.autosearchbutton.background_normal=os.path.join(curdir, "images/autosearch_normal.png")
        self.autosearchbutton.background_down=os.path.join(curdir, "images/autosearch_down.png")
        self.autosearchbutton.bind(on_release=self.ui_autosearch)
        self.root.remove_widget(self.statlabel)
        self.root.remove_widget(self.progressbox)

    def autosearch_thread(self):
        self.shelf["justrun"] = False
        self.statlabel = Label(halign="center", size_hint_y=None, height="16dp")
        self.progressbox = BoxLayout(orientation="horizontal", height="7dp", size_hint_y=None, padding=[6, 0, 6, 2])
        self.statprogress = ProgressBar(max=len(self.shelf["zips_done"])+len(self.shelf["zips_todo"]), size_hint_y=None, height="5dp")
        self.progressbox.add_widget(self.statprogress)
        self.root.add_widget(self.statlabel, 2)
        self.root.add_widget(self.progressbox, 3)

        count = 0

        while len(self.shelf["zips_todo"]) > 0:
            zipcode = self.shelf["zips_todo"][0][:]
            self.shelf["zips_todo"].remove(zipcode)
            self.shelf["zips_done"].append(zipcode)
            count += 1
            time1 = time.time()
            if count <= 3:
                self.statlabel.text = "Checking {0}... ({1}/{2})".format(zipcode, len(self.shelf["zips_done"]), len(self.shelf["zips_todo"]))
            else:

                humantime = self.humanize_time(deltaT * len(self.shelf["zips_todo"]))
                self.statlabel.text = "Checking {0}... ({1}/{2}, {4} ZIPs/sec, ETA {3})".format(zipcode, len(self.shelf["zips_done"]), len(self.shelf["zips_todo"]), humantime, round(deltaT, 2))
            self.statprogress.value = len(self.shelf["zips_done"])
            studs = self.load_zip(zipcode)
            if not studs:
                time2 = time.time()
                continue
            elif type(studs) == type(str()):
                self.resultslist.add_widget(Label(text="\n\n" + studs, halign="center"), len(self.resultslist.children))
                break
            else:
                for stud in studs:
                    self.shelf["data"].append(stud)
                    self.process_stud(stud, zipcode)
            time2 = time.time()
            deltaT = time2-time1
        self.on_search_finished()
        return None

    def humanize_time(self, time):
        sec = int(round(time))
        mins = 0
        hours = 0
        strtime = ""
        if sec / 60. > 1:
            mins = (sec - (sec % 60)) / 60
            sec = sec % 60
        if mins / 60. > 1:
            hours = (mins - (mins % 60)) / 60
            mins = mins % 60
        if hours > 0:
            strtime += "{0} h ".format(hours)
        if mins > 0 or hours != 0:
            strtime += "{0} m ".format(mins)
        if (sec > 0 and hours == 0) or mins != 0:
            strtime += "{0} s".format(sec)
        else:
            strtime = strtime[:-1]
        return strtime

    def filter(self, *args):
        try:
            if not self.shelf["justrun"]:
                #print "filtering"
                studs = self.students[:]
                self.resultslist.clear_widgets()
                for stud in studs:
                    if self.to_add(stud):
                        self.resultslist.add_widget(stud)
        except KeyError:
            pass

    def to_add(self, stud):
        to_add = False
        for i in stud.data["interests"]:
            try:
                if (i["name"] == self.group_names[i["group_name"]].text or "Any" in self.group_names[i["group_name"]].text) and i["group_name"] == "Music":
                    to_add = True
            except KeyError:
                pass
        if not to_add: return False

        to_add = False
        for i in stud.data["interests"]:
            try:
                if (i["name"] == self.group_names[i["group_name"]].text or "Any" in self.group_names[i["group_name"]].text) and i["group_name"] == "Interests":
                    to_add = True
            except KeyError:
                pass
        if not to_add: return False

        to_add = False
        for i in stud.data["interests"]:
            try:
                if (i["name"] == self.group_names[i["group_name"]].text or "Any" in self.group_names[i["group_name"]].text) and i["group_name"] == "Sports":
                    to_add = True
            except KeyError:
                pass
        if not to_add: return False

        if stud.data["sex"] != self.genders.text and not "Any" in self.genders.text:
            return False
        if stud.data["country_name"] != self.countries.text and not "Any" in self.countries.text:
            return False
        if not self.nameentry.text.lower() in stud.data["name"].lower() and not self.nameentry.text == "Name":
            return False
        return True

    def ui_load_persistence(self, *args):
        content = BoxLayout(orientation="vertical", padding=5, spacing=5)
        popup = Popup(size_hint=(.9, .9), content=content, title="Select persistence file")
        self.chooser = DavChooser()
        self.chooser.fileentry.bind(on_text_validate=self.on_load_persistence)

        checkboxbox = BoxLayout(orientation="horizontal", spacing=5, size_hint_x=None)#, height="25dp")
        self.resetcheckbox = CheckBox(size_hint_x=None)
        label = Label(text="Reset file content", size_hint_x=None)
        checkboxbox.add_widget(self.resetcheckbox)
        checkboxbox.add_widget(label)


        buttonbox = BoxLayout(orientation="horizontal", size_hint_y=None, spacing=5, height="50dp")
        load = Button(on_press=hide_keyboard, text="Load", on_release=self.on_load_persistence, height="40dp", size_hint=(None, None))
        cancel = Button(on_press=hide_keyboard, text="Cancel", on_release=popup.dismiss, height="40dp", size_hint=(None, None))
        buttonbox.add_widget(checkboxbox)
        buttonbox.add_widget(Widget(size_hint_y=None))
        buttonbox.add_widget(cancel)
        buttonbox.add_widget(load)

        content.add_widget(self.chooser)
        content.add_widget(buttonbox)

        global container
        container.popup = popup
        def onopen(*args, **kwargs):
            global container
            container.shown = True
        def ondismiss(*args, **kwargs):
            global container
            container.shown = False
        self.bind(on_open=onopen, on_dismiss=ondismiss)
        popup.open()

    def on_load_persistence(self, *args):
        container.popup.dismiss()
        self.load_persistence(os.path.join(self.chooser.path, self.chooser.filename), self.resetcheckbox.active)

    def load_persistence(self, shelf, reset):
        #print "load_persistence"
        realshelf = shelve.open(shelf, writeback=True)

        if reset or not "data" in realshelf.keys():
            realshelf["data"] = self.shelf["data"][:]

        if reset or not "zips_done" in realshelf.keys():
            realshelf["zips_done"] = self.shelf["zips_done"][:]

        if reset or not "zips_todo" in realshelf.keys():
            realshelf["zips_todo"] = self.shelf["zips_todo"][:]

        realshelf["bios"] = self.shelf["bios"][:]

        self.shelf = realshelf
        self.shelf["justrun"] = len(self.shelf["zips_done"]) == 0 and len(self.shelf["data"]) == 0
        print len(self.shelf["zips_done"]) == 0 and len(self.shelf["data"]) == 0

        if not self.shelf["justrun"]:
            self.resultslist.clear_widgets()
        for i in self.shelf["data"]:
            self.process_stud(i, i["zipcode"])


    def show_help(self, *args):
        popup = Popup(size_hint=(.8, .8), auto_dismiss=True, title="Help")
        popup.content = BoxLayout(orientation="vertical", spacing=5, padding=5)
        scroll = ScrollView(pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False, size_hint=(1, 1))
        popup.content.add_widget(scroll)
        scrollbox = GridLayout(cols=1, padding=5, spacing=5, size_hint=(1, None))
        scrollbox.bind(minimum_height=scrollbox.setter('height'))
        scroll.add_widget(scrollbox)
        close = Button(on_press=hide_keyboard, text="Close", on_release=popup.dismiss, height="40dp", size_hint=(1, None))
        popup.content.add_widget(close)

        def on_ref(instance, value):
            if value == "email":
                open_url("mailto:[email protected]")
            elif value == "site":
                open_url("http://davideddu.altervista.org/software/")
            elif value == "gpl":
                open_url("http://gnu.org/licenses/gpl.html")
            elif value == "donate":
                open_url("http://davideddu.altervista.org/blog/donate/")

        label = Label(markup=True, size_hint_y=None, halign="center", on_ref_press=on_ref)

        label.height = int((215. * len(label.text)) / 600)# * (596. / self.label.width))
        def setsize(instance, value):
            #print len(instance.text), instance.text.split("\n", 1)[0], instance.width
            instance.text_size[0] = value[0]
            instance.texture_size[1] = value[1]
            instance.height = int((215. * len(label.text)) / 600 * (596. / instance.width))
        label.bind(size=setsize)  #self.label.setter("texture_size"))

        oses = {"linux":    "Linux",
                "android":  "Android",
                "macosx":   "Mac OS X",
                "win":      "Windows (use this program on Linux for best performance)"}

        label.text = """[size=24dp][b]AFS USA Student Finder[/b] {version}[/size]
by [ref=email][color=#32A4CE]Davide Depau[/color][/ref] - [ref=site][color=#32A4CE]Homepage[/color][/ref]
Running on {0}

AFS USA Student Finder is Free Software, but its development takes precious time.
You can [ref=donate][color=#32A4CE]donate[/color][/ref] to help its development.

[size=20dp][b]How to use the application[/b][/size]
Use this application as you would with any touch app: to scroll, don't use the mouse wheel, just drag the items, like you would do with your phone.

[size=16dp][b]Normal search[/b][/size]
It is like in the AFS website: just write a zip code in the first box, and tap the "search" button (the one with the lens).
Wait a few seconds, and it will show a list of students going near to the ZIP you put. You can filter them using the menus on the bottom, or using the "Name" box. Tapping the "Show more" button will show a lot of information, most of which is not available in AFS website.

[size=16dp][b]Automatic search[/b][/size]
When you click the "Autosearch" button, the program will check one by one all the ZIP codes. This might be useful if you are going to go the USA with AFS and you want to find your profile.
Please note that:
- this operation requires a lot of time (if you are lucky, about ten hours...)
- once started the operation cannot be stopped/paused unless you close the application
- slow PCs or phones may become very slow while running this software
- your carrier may charge you if you use it with mobile broadband
- the application cannot manage very big amounts of data, so you should enable some filters (like the country, the gender and the name) before starting the operation

If you are running this application on a mobile phone/tablet, please also note that if you do something else while the app is working, the Android OS might close the app to free some resources needed by the other applications.

[size=16dp][b]Persistence[/b][/size]
«Automatic search is very slow and takes a lot of hours! Can I close the application and make it start where it had finished?»
Of course you can! When you open the app, [b]before searching anything[/b], click on the "persistence" button (the floppy). Choose a file; you can create a new one or choose an existing one. Then click "Load". If you previously used the same file, the program will automatically load the old student list. You can then start autosearch: it will continue from the point it has been stopped.
If you want to create a new list on the same file, enable "Reset file content" before clicking "Load".

Pros:
- You don't have to keep the PC turned on to parse the entire list of ZIPs
- You don't lose your list if the app crashes for any reason

Cons:
- It doesn't work on Android
- The persistence may become very big

[size=12dp]I am not in any way related to AFS, AFS USA or other associations/companies. Every trademark is of his respective owner. I decline every responsibility due to the use of this program to the user.
Copyright © Davide Depau 2013.  This program is licensed under a GNU GPL version 3 license or later [ref=gpl]<[color=#32A4CE]http://gnu.org/licenses/gpl.html[/color]>\[/ref].
This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.[/size]""".format(oses[opsys], version=__version__)

        scrollbox.add_widget(label)

        global container
        container.popup = popup
        def onopen(*args, **kwargs):
            global container
            container.shown = True
        def ondismiss(*args, **kwargs):
            global container
            container.shown = False
        self.bind(on_open=onopen, on_dismiss=ondismiss)
        popup.open()

    def on_pause(self, *args):
        return True

    def on_resule(self, *args):
        pass

    def post_build_init(self, ev):
        # Map Android keys
        if opsys == 'android':
            android.map_key(android.KEYCODE_MENU, 1000)
            android.map_key(android.KEYCODE_BACK, 1001)
            android.map_key(android.KEYCODE_SEARCH, 1002)
            win = self._app_window
            def _key_handler(a, key, b, c, d):
                global container
                if key == 1001:
                    android.hide_keyboard() 
                    if container.shown:
                        try:
                            container.popup.dismiss()
                        except:
                            sys.exit(0)
                    else:
                        global taptime
                        t = time.time()
                        if t - taptime <= 1:
                            # Double tap
                            sys.exit(0)
                        else:
                            label = Label(text="Press Back again to exit", halign="center", size_hint=(1, None), height=20)
                            self.root.add_widget(label, 1)
                            container.label = label
                            def rmlabel(*args, **kwargs):
                                global container
                                self.root.remove_widget(container.label)
                                del container.label
                            Clock.schedule_once(rmlabel, 1)
                        taptime = t
                elif key == 1000:
                    if not container.shown:
                        self.show_help()
                    else: container.popup.dismiss()
            win.bind(on_keyboard=_key_handler)

    def pre_close(self, *args):
        try:
            self.shelf.close()
        except AttributeError:
            pass
class AimaUI(App):
    """Class to manage aima agents and environments."""

    def __init__(self, argAgent=None, argMap=None):
        """Initialize the user interface."""
        App.__init__(self)
        self.scoreA = 0
        self.scoreB = 0
        self.agentA = "Agent A"
        self.agentAImgDef = "img/agentA_v0.png"
        self.agentAImg = None
        self.agentB = "Agent B"
        self.agentBImgDef = "img/agentB_v0.png"
        self.agentBImg = None
        self.wall_img = Image(source="img/wall.png")
        self.trash_img = Image(source="img/trash.png")
        self.map = None
        self.running = False
        self.env = None
        self.counter_steps = 0
        self.initialized = False

        self.argAgent = argAgent
        self.argMap = argMap

        self.agentA_spinner = False
        self.maps_spinner = False

    def __initialize_env(self):
        """Initialize aima environment."""
        if self.env is not None:
            del self.env
            self.env = None
        if self.map is not None:
            if self.map.find("map") != -1:
                self.env = ALL_MAPS[self.map](chosen=self.map)
            else:
                self.env = ALL_MAPS[self.map]()
        if self.agentA in ALL_AGENTS:
            agent_A = TraceAgent(ALL_AGENTS[self.agentA]())
            if agent_A.img is not None and check_img(agent_A.img):
                self.agentAImg = Image(
                    source=path.join("agents_dir", path.join("img", agent_A.img)))
            else:
                self.agentAImg = Image(source=self.agentAImgDef)
            self.env.add_thing(agent_A, location=self.env.start_from)
        if self.agentB in ALL_AGENTS:
            agent_B = TraceAgent(ALL_AGENTS[self.agentB]())
            if agent_B.img is not None and check_img(agent_B.img):
                self.agentBImg = Image(
                    source=path.join("agents_dir", path.join("img", agent_B.img)))
            else:
                self.agentBImg = Image(source=self.agentBImgDef)
            self.env.add_thing(agent_B, location=self.env.start_from)

        # this need to save map
        self.myWid.set_env(self.env)

    def get_scores(self):
        """Get agents' scores."""
        return ("ScoreA = {0:d}".format(self.scoreA),
                "ScoreB = {0:d}".format(self.scoreB))

    def update_canvas(self, labels, wid, *largs):
        """Update the canvas to respect the environment."""
        wid.canvas.clear()
        self.counter.text = str(self.counter_steps)
        n_x, n_y = max([thing.location for thing in self.env.things])
        tile_x = wid.width / (n_x + 1)
        tile_y = wid.height / (n_y + 1)
        labelA, labelB = labels
        with wid.canvas:
            for thing in [thing for thing in self.env.things
                          if isinstance(thing, Dirt) or
                          isinstance(thing, Clean)]:
                pos_y, pos_x = thing.location
                if isinstance(thing, Dirt):
                    Color(0.5, 0, 0)
                    Rectangle(
                        pos=(
                            pos_x * tile_x + wid.x,
                            n_y * tile_y - pos_y * tile_y + wid.y),
                        size=(tile_x, tile_y))
                    Color(1, 1, 1, 1)
                    Rectangle(texture=self.trash_img.texture,
                              pos=(
                                  pos_x * tile_x + wid.x + (tile_x / 4),
                                  n_y * tile_y - pos_y *
                                  tile_y + wid.y + (tile_y / 4)
                              ),
                              size=(tile_x / 2, tile_y / 2))
                elif isinstance(thing, Clean):
                    Color(0.1, 0.5, 0.1)
                    Rectangle(
                        pos=(
                            pos_x * tile_x + wid.x,
                            n_y * tile_y - pos_y * tile_y + wid.y),
                        size=(tile_x, tile_y))
            for thing in [thing for thing in self.env.things
                          if isinstance(thing, Wall)]:
                pos_y, pos_x = thing.location
                Color(1, 1, 1, 1)
                Rectangle(texture=self.wall_img.texture,
                          pos=(pos_x * tile_x + wid.x,
                               n_y * tile_y - pos_y * tile_y + wid.y),
                          size=(tile_x, tile_y))
            for thing in [thing for thing in self.env.things
                          if isinstance(thing, ALL_AGENTS.get(self.agentA, Agent)) or
                          isinstance(thing, ALL_AGENTS.get(self.agentB, Agent))]:
                pos_y, pos_x = thing.location
                if self.agentA in ALL_AGENTS and\
                   isinstance(thing, ALL_AGENTS[self.agentA]):
                    self.scoreA = thing.performance
                    labelA.text = self.get_scores()[0]
                    Color(1, 1, 1, 1)
                    Rectangle(texture=self.agentAImg.texture,
                              pos=(pos_x * tile_x + wid.x,
                                   n_y * tile_y - pos_y * tile_y + wid.y),
                              size=(tile_x, tile_y))
                if self.agentB in ALL_AGENTS and\
                   isinstance(thing, ALL_AGENTS[self.agentB]):
                    self.scoreB = thing.performance
                    labelB.text = self.get_scores()[1]
                    Color(1, 1, 1, 1)
                    Rectangle(texture=self.agentBImg.texture,
                              pos=(pos_x * tile_x + wid.x,
                                   n_y * tile_y - pos_y * tile_y + wid.y),
                              size=(tile_x, tile_y))

    def load_env(self, labels, wid, *largs):
        """Load and prepare the environment with my Agent"""
        self.running = False
        self.counter_steps = 0
        change_boolSavedMap(False)

        if self.argMap is not None and self.map is None or self.map == "Maps":
                self.map = self.maps_spinner.text = self.argMap
        else:
            if self.map is None or self.map == "Maps":
                gen_popup("Error!", "No map selected...").open()
                return

        if self.argAgent is not None and self.agentA not in ALL_AGENTS:
            self.agentA = self.agentA_spinner.text = self.argAgent
        else:
            if self.agentA not in ALL_AGENTS and self.agentB not in ALL_AGENTS:
                gen_popup("Error!", "You must choose at least one agent...").open()
                return

        self.__initialize_env()
        self.initialized = True
        self.update_canvas(labels, wid)

    def running_step(self, labels, wid, n_step=None, *largs):
        """Run the program of the environment, called from run."""
        if self.env is not None:
            if n_step is not None:
                if self.counter_steps == n_step:
                    self.running = False
                    self.btn_100step.state = "normal"
                    self.counter_steps = 0
                    return False
                else:
                    self.counter_steps += 1
            if not self.running:
                    return False
            self.env.step()
            self.update_canvas(labels, wid)

    def btn_step(self, labels, wid, *largs):
        """Update the environment one step."""
        if not self.initialized:
            gen_popup("Error!", "You must load a map...").open()
            return
        elif self.agentA == "Agent A" and self.agentB == "Agent B":
            popup = gen_popup(
                "Error!", "Agent not selected, reset required...", False).open()
            Clock.schedule_once(popup.dismiss, timeout=2)
            Clock.schedule_once(self.partial_reset, timeout=2)
            return
        if self.env is not None:
            self.env.step()
            self.update_canvas(labels, wid)

    def btn_100step(self, function, labels, wid, *largs):
        """Update the environment one step."""
        if not self.initialized:
            gen_popup("Error!", "You must load a map...").open()
            self.btn_100step.state = "normal"
            return
        elif self.agentA == "Agent A" and self.agentB == "Agent B":
            popup = gen_popup(
                "Error!", "Agent not selected, reset required...", False).open()
            Clock.schedule_once(popup.dismiss, timeout=2)
            Clock.schedule_once(self.partial_reset, timeout=2)
        self.btn_100step.state = "down"
        self.running = True
        Clock.schedule_interval(partial(function, labels, wid, 100), 1 / 30.)

    def btn_run(self, function, labels, wid, *largs):
        """Run a function for the update."""
        if not self.initialized:
            gen_popup("Error!", "You must load a map...").open()
            self.btn_run.state = "normal"
            return
        elif self.agentA == "Agent A" and self.agentB == "Agent B":
            popup = gen_popup(
                "Error!", "Agent not selected, reset required...", False).open()
            Clock.schedule_once(popup.dismiss, timeout=2)
            Clock.schedule_once(self.partial_reset, timeout=2)
        self.btn_run.state = "down"
        self.running = True
        Clock.schedule_interval(partial(function, labels, wid), 1 / 30.)

    def btn_stop(self, function, *largs):
        """Stop a specific fuction."""
        if not self.initialized:
            gen_popup("Error!", "You must load a map...").open()
            return
        elif self.agentA == "Agent A" and self.agentB == "Agent B":
            popup = gen_popup(
                "Error!", "Agent not selected, reset required...", False).open()
            Clock.schedule_once(popup.dismiss, timeout=2)
            Clock.schedule_once(self.partial_reset, timeout=2)
        self.running = False
        self.counter_steps = 0
        self.btn_run.state = "normal"
        self.btn_100step.state = "normal"
        Clock.unschedule(function)

    @staticmethod
    def reset_popup(popup, *largs):
        popup.dismiss()
        gen_popup("INFO", "Reset done!!!").open()

    def reset_all(self, labels, spinners, wid, *largs):
        """Clear the entire environment."""
        popup = gen_popup("WARNING!", "I'm deleting everything!!!", False)
        popup.open()
        self.initialized = False
        self.agentA = "Agent A"
        self.agentB = "Agent B"
        self.map = None
        self.running = False
        self.counter_steps = 0
        self.scoreA = 0
        self.scoreB = 0
        self.__initialize_env()
        wid.canvas.clear()
        labelA, labelB = labels
        labelA.text = self.get_scores()[0]
        labelB.text = self.get_scores()[1]
        reload(envs_list)
        reload(agents_list)
        global ALL_AGENTS
        global ALL_MAPS
        ALL_AGENTS = agents_list.ALL_AGENTS
        ALL_MAPS = envs_list.ALL_MAPS
        spinnerA, spinnerB, spinnerMap = spinners
        spinnerA.values = sorted(
            [agent for agent in ALL_AGENTS.keys()]) + ["Agent A"]
        spinnerB.values = sorted(
            [agent for agent in ALL_AGENTS.keys()]) + ["Agent B"]
        spinnerMap.values = sorted([map for map in ALL_MAPS.keys()]) + ["Maps"]
        spinnerA.text = "Agent A"
        spinnerB.text = "Agent B"
        spinnerMap.text = "Maps"
        self.counter.text = str(self.counter_steps)
        Clock.schedule_once(partial(self.reset_popup, popup), timeout=1)

    def on_resize(self, width, eight):
        self.update_canvas()

    def select_agent_A(self, spinner, text):
        self.agentA = text

    def select_agent_B(self, spinner, text):
        self.agentB = text

    def select_map(self, spinner, text):
        self.map = text

    # serve per ridimensionare a mano la finestra quando è già aperta
    def on_resize(self, width, eight, test):
        if self.initialized:
            Clock.schedule_once(
                partial(self.update_canvas, self.labels, self.wid))

    def build(self):
        """Build the user interface."""

        wid = Widget()
        self.myWid = MyWidget()
        wid.add_widget(self.myWid)

        self.counter = Label(text="0")
        labelA = Label(text=self.get_scores()[0])
        labelB = Label(text=self.get_scores()[1])
        labels = (labelA, labelB)
        self.labels = labels
        self.wid = wid

        self.agentA_spinner = Spinner(
            text='Agent A',
            text_size=(95, None),
            haligh="center",
            shorten=True,
            values=sorted([agent for agent in ALL_AGENTS.keys()]) +
            ["Agent A"],
            size=(100, 44)
        )

        agentB_spinner = Spinner(
            text='Agent B',
            text_size=(95, None),
            shorten=True,
            values=sorted([agent for agent in ALL_AGENTS.keys()]) +
            ["Agent B"],
            size=(100, 44)
        )

        self.maps_spinner = Spinner(
            text='Maps',
            text_size=(95, None),
            shorten=True,
            values=sorted([map for map in ALL_MAPS.keys()]) + ["Maps"],
            size=(100, 44)
        )

        self.agentA_spinner.bind(text=self.select_agent_A)
        agentB_spinner.bind(text=self.select_agent_B)
        self.maps_spinner.bind(text=self.select_map)

        btn_load = Button(text='Load',
                          on_press=partial(self.load_env, labels, wid))

        btn_step = Button(text='Step >',
                          on_press=partial(self.btn_step, labels, wid))

        self.btn_100step = ToggleButton(text='100 Step >',
                                        on_press=partial(self.btn_100step,
                                                         self.running_step,
                                                         labels,
                                                         wid))

        self.btn_run = ToggleButton(
            text='Run >>', on_press=partial(self.btn_run,
                                            self.running_step,
                                            labels,
                                            wid))

        btn_stop = Button(text='Stop [ ]',
                          on_press=partial(self.btn_stop,
                                           self.running_step))

        self.partial_reset = partial(self.reset_all,
                                     labels,
                                     (self.agentA_spinner,
                                      agentB_spinner, self.maps_spinner),
                                     wid)

        btn_reset = Button(text='Reset',
                           on_press=self.partial_reset)

        Window.bind(on_resize=self.on_resize)

        action_layout = BoxLayout(size_hint=(1, None), height=50)
        action_layout.add_widget(btn_load)
        action_layout.add_widget(btn_step)
        action_layout.add_widget(self.btn_100step)
        action_layout.add_widget(self.counter)
        action_layout.add_widget(self.btn_run)
        action_layout.add_widget(btn_stop)
        action_layout.add_widget(btn_reset)

        agents_layout = BoxLayout(size_hint=(1, None), height=50)
        agents_layout.add_widget(self.agentA_spinner)
        agents_layout.add_widget(labelA)
        agents_layout.add_widget(agentB_spinner)
        agents_layout.add_widget(labelB)
        agents_layout.add_widget(self.maps_spinner)

        root = BoxLayout(orientation='vertical')
        root.add_widget(wid)
        root.add_widget(action_layout)
        root.add_widget(agents_layout)

        return root
Exemplo n.º 18
0
 def make_spinner_with_values( values, text, id, callback ): 
     spinner = Spinner(text=text, values=values, id=id)
     find_and_destroy_widget( layout, id )
     spinner.bind(text=callback)
     layout.add_widget( spinner )
     return spinner
    def build(self):
        self._wid = Renderer()

        ##
        # First row
        label_steps = Label(
            text='{0}'.format(self._step), color=(0.1, 1, 0.1, 1))

        btn_load = Button(text='Load')

        btn_step = Button(text='Step >')

        btn_100step = Button(text='100 Step >')

        spinn_map = Spinner(
            text='Maps',
            shorten=True,
            shorten_from='right',
            halign='left',
            text_size=(64, None),
            values=["Maps"]
        )

        label_random_pos = Label(
            text='rand p', size=(100, 42), size_hint=(None, 1))
        t_btn_random = ToggleButton(size=(64, 42), size_hint=(None, 1))

        btn_reset = Button(text='Reset')

        lay_splitter = BoxLayout(orientation='vertical')

        ##
        # Second row
        spinn_agent_01 = Spinner(
            id='agent_1',
            text='agent_1',
            shorten=True,
            shorten_from='right',
            text_size=(200, None),
            values=["agent_1"]
        )

        label_agent_01 = Label(text='0')

        spinn_agent_02 = Spinner(
            id='agent_2',
            text='agent_2',
            shorten=True,
            shorten_from='right',
            text_size=(200, None),
            values=["agent_1"]
        )

        label_agent_02 = Label(text='0')

        ##
        # Third row
        spinn_agent_03 = Spinner(
            id='agent_3',
            text='agent_3',
            shorten=True,
            shorten_from='right',
            text_size=(200, None),
            values=["agent_1"]
        )

        label_agent_03 = Label(text='0')

        spinn_agent_04 = Spinner(
            id='agent_4',
            text='agent_4',
            shorten=True,
            shorten_from='right',
            text_size=(200, None),
            values=["agent_1"]
        )

        label_agent_04 = Label(text='0')

        ##
        # Layout
        lay_actions = BoxLayout()
        lay_actions.add_widget(btn_load)
        lay_actions.add_widget(btn_step)
        lay_actions.add_widget(btn_100step)
        lay_actions.add_widget(label_steps)
        lay_actions.add_widget(spinn_map)
        lay_actions.add_widget(label_random_pos)
        lay_actions.add_widget(t_btn_random)
        lay_actions.add_widget(btn_reset)

        lay_splitter.add_widget(lay_actions)

        lay_agent_row_0 = BoxLayout()
        lay_agent_row_0.add_widget(spinn_agent_01)
        lay_agent_row_0.add_widget(label_agent_01)
        lay_agent_row_0.add_widget(label_agent_02)
        lay_agent_row_0.add_widget(spinn_agent_02)

        lay_agent_row_1 = BoxLayout()
        lay_agent_row_1.add_widget(spinn_agent_03)
        lay_agent_row_1.add_widget(label_agent_03)
        lay_agent_row_1.add_widget(label_agent_04)
        lay_agent_row_1.add_widget(spinn_agent_04)

        lay_splitter.add_widget(lay_agent_row_0)
        lay_splitter.add_widget(lay_agent_row_1)

        splitter = Splitter(sizable_from='top')
        splitter.add_widget(lay_splitter)
        splitter.min_size = 128
        splitter.size_hint_y = 0.16

        root = BoxLayout(orientation='vertical')
        root.add_widget(self._wid)
        root.add_widget(splitter)

        Window.minimum_width = 640
        Window.minimum_height = 480

        ##
        # Events
        Window.bind(on_resize=self.on_resize)

        btn_load.on_press = partial(self.load_agents_and_maps,
                                    [spinn_agent_01,
                                     spinn_agent_02,
                                     spinn_agent_03,
                                     spinn_agent_04],
                                    spinn_map)

        btn_step.on_press = partial(self.evt_step,
                                    label_steps=label_steps,
                                    label_agents={
                                        'agent_1': label_agent_01,
                                        'agent_2': label_agent_02,
                                        'agent_3': label_agent_03,
                                        'agent_4': label_agent_04,
                                    })

        btn_100step.on_press = partial(self.evt_100_steps, 100,
                                       label_steps=label_steps,
                                       btn_100step=btn_100step,
                                       label_agents={
                                           'agent_1': label_agent_01,
                                           'agent_2': label_agent_02,
                                           'agent_3': label_agent_03,
                                           'agent_4': label_agent_04,
                                       })

        btn_reset.on_press = partial(self.reset,
                                     spinn_map,
                                     t_btn_random,
                                     label_steps,
                                     [
                                         spinn_agent_01,
                                         spinn_agent_02,
                                         spinn_agent_03,
                                         spinn_agent_04
                                     ],
                                     [
                                         label_agent_01,
                                         label_agent_02,
                                         label_agent_03,
                                         label_agent_04,
                                     ])

        spinn_map.bind(
            text=partial(self.select_map, t_btn_random, label_steps))
        spinn_agent_01.bind(
            text=partial(self.select_agent, spinn_agent_01.id, t_btn_random,))
        spinn_agent_02.bind(
            text=partial(self.select_agent, spinn_agent_02.id, t_btn_random,))
        spinn_agent_03.bind(
            text=partial(self.select_agent, spinn_agent_03.id, t_btn_random,))
        spinn_agent_04.bind(
            text=partial(self.select_agent, spinn_agent_04.id, t_btn_random,))

        splitter.on_press = partial(self.splitter_on_press)
        splitter.on_release = partial(self.splitter_on_release)

        return root
Exemplo n.º 20
0
class LoginScreen(FloatLayout):
    
    #x = ListProperty([])
    
    #print x
    

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        #gc.disable()
        self.DropdownObjects = []

        self.add_widget(Label(text= "Wilkommen [color=ff3333] [sub] bei der [/sub][/color][color=3333ff][b] Bonierungs[sup][color=#098125ff]App[/sup][/b][/color]",
                              markup = True, pos_hint={'top': 1.2}, font_size='20sp'))


        self.GridlayoutS1 = GridLayout(cols = 2, size_hint_y = 1/5, pos_hint={'top': 0.6})
        self.add_widget(self.GridlayoutS1)
        self.GridlayoutS1.add_widget(Label(text='User Name')) #, size_hint_x = 0.2, size_hint_y = 0.2))
        self.username = TextInput(multiline=False) #, size_hint_x = 0.2, size_hint_y = 0.2)
        self.username.bind(on_text_validate=self.on_enter)
        self.GridlayoutS1.add_widget(self.username)
        self.GridlayoutS1.add_widget(Label(text='password')) #,size_hint_x = 0.2, size_hint_y = 0.2))
        self.password = TextInput(password=True, multiline=False) #, size_hint_x = 0.2, size_hint_y = 0.2)
        self.GridlayoutS1.add_widget(self.password)
        self.BenutzerListe = {"": ""};

        self.add_widget(Button(text='Einloggen', size_hint_y= 1/5, pos_hint={'top': 0.4}, on_release = self.AbfrageLogin))

        self.LabelLoginanzeiger = Label(size_hint_y= 1/5)
        self.add_widget(self.LabelLoginanzeiger)

    def on_enter(self, instance):
        print('User pressed enter in', instance)
        self.password.focus = True







    def AbfrageLogin(self, widget):
        Username = self.username.text
        Passwort = self.password.text
        if Username in self.BenutzerListe and Passwort == self.BenutzerListe[Username]:
              self.LabelLoginanzeiger.text = 'Login korrekt'
              self.clear_widgets()
              self.HauptProgramm()

        else:
              self.LabelLoginanzeiger.text = 'Login inkorrekt'


    def HauptProgramm(self, *args):
        self.SpinnerButtonZustand = 'Alle'
        App.AuswahlHauptlisteAlt = []
        print 'das ist das Hauptprogramm'
        self.BilderListeVorlaeufer = []
        self.BilderListeVorlaeufer = os.listdir(os.getcwd() + '/pictures')
        self.Pfade = []
        for i in self.BilderListeVorlaeufer:
            Pfad = os.path.join('pictures', i)
            if os.path.isfile(Pfad) == True:
                self.Pfade.append(Pfad)
        self.HauptCarousel = Carousel(scroll_timeout = 100)
        App.Pfade = self.Pfade
        self.add_widget(self.HauptCarousel)
        ####################################################################################################
        ### Erste Seite im HauptCarousel momentan mit den produktbildern
        self.HauptCarousel.FloatLayout = FloatLayout()
        self.HauptCarousel.add_widget(self.HauptCarousel.FloatLayout)
        self.HauptCarousel.FloatLayout.GridLayout = GridLayout(cols=3, pos_hint={'x': 0,'y': 0}, size_hint=[1,0.9])
        self.HauptCarousel.FloatLayout.add_widget(self.HauptCarousel.FloatLayout.GridLayout)
        for i in range(2):
            button = Button(background_normal = self.Pfade[i], background_down= 'bilder_oberflaeche/1361740537_Ball Green_mitHaken.png', mipmap= True)
            self.HauptCarousel.FloatLayout.GridLayout.add_widget(button)
##        self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test'))
##        self.HauptCarousel.FloatLayout.GridLayout.add_widget(Button(text='test2'))

        #####################################################################################################
        ### 2 Seite im Hauptcarousel mit testbutton zur datei Erstellung
        ### 2 Page in MainCarousel with testbutton for creating /exporting to a file
        self.HauptCarousel2 = BoxLayout(orientation='vertical')
        ###self.HauptCarousel.add_widget(self.HauptCarousel2)
        self.HauptCarousel2.Texteingabe = TextInput(multiline=True)
        self.HauptCarousel2.add_widget(self.HauptCarousel2.Texteingabe)

        self.HauptCarousel2.ButtonSchreiben = Button(text="datei schreiben", on_release = self.datenpickeln)
        self.HauptCarousel2.add_widget(self.HauptCarousel2.ButtonSchreiben)
        #######################################################################
        ### 3 Seite im Hauptcarousel momentan mit Datei Auslesefunktion
        ### 3 Page in MainCarousel atm with functionality to read from file
        self.HauptCarousel3 = BoxLayout(orientation='vertical')
        ###self.HauptCarousel.add_widget(self.HauptCarousel3)
        self.HauptCarousel3.Textausgabe = TextInput(multiline=True, readonly = True)
        self.HauptCarousel3.add_widget(self.HauptCarousel3.Textausgabe)

        self.HauptCarousel3.ButtonLesen = Button(text="datei auslesen", on_release = self.datenentpickeln)
        self.HauptCarousel3.add_widget(self.HauptCarousel3.ButtonLesen)
        #######################################################################
        ### 4 Seite im Hauptcarousel momentan mit Tischmanager
	### 4 Page in Maincarousel atm with some kind of Table Manager
        BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)]
        self.CustomLayout = CustomLayout()
        self.HauptCarousel.add_widget(self.CustomLayout)
        #self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=#098125ff]Organizer[/sup][/b][/color]',  markup = True,
                                            #halign= 'left', valign= 'top', text_size= self.size, pos_hint={'x':0, 'y': 0}, font_size= '30sp')
        self.CustomLayout.TopLabel = Label(text = 'Tisch[sup][color=18ea1d]Organizer[/sup][/b][/color]',  markup = True,  # alte farbe: #098125ff
                                           halign= 'left',  font_size= '30sp')
        #self.CustomLayout.add_widget(self.CustomLayout.TopLabel)
        self.CustomLayout.BoxLayout = BoxLayout (orientation = 'horizontal', size_hint = [1,0.05], pos_hint={'x':0, 'y': 0.95})
        self.CustomLayout.add_widget(self.CustomLayout.BoxLayout)
        self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.TopLabel)
        ButtonMenu1 = self.DropdownbuttonCreator()
        
        self.CustomLayout.BoxLayout.Button1 = ButtonMenu1
##        self.CustomLayout.BoxLayout.Button2 = Button(text = 'Tisch+' , on_release = self.tischhinzufuegen)
##        self.CustomLayout.BoxLayout.Button3 = Button(text = 'Spalte+', on_release = self.spaltehinzufuegen)
##        self.CustomLayout.BoxLayout.Button4 = Button(text = 'Zeile+', on_release = self.zeilehinzufuegen)
        self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button1)
##        self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button2)
##        self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button3)
##        self.CustomLayout.BoxLayout.add_widget(self.CustomLayout.BoxLayout.Button4)
        self.CustomLayoutGridLayout = GridLayout(cols = 3, rows = 4, padding = [20,20], spacing = [30,30], size_hint = [1,0.95], pos_hint={'x':0, 'y': 0})
        #cGridLayout = StackLayout(orientation = "tb-lr", padding = [20,20], spacing = [30,30], size_hint = [1,0.9], pos_hint={'x':0, 'y': 0})

        self.CustomLayout.add_widget(self.CustomLayoutGridLayout)
        self.Tischliste = []
        
        Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"]
        
        AnzahlTische = 12
        Zielwidget = self.CustomLayoutGridLayout
        self.tischerstellung(Zielwidget,AnzahlTische, Auswahlliste, BackgroundcolorListe)
       
        self.Box=BoxLayout(oreintation='vertical')
        self.CustomScrollviewProduktOrganizerInstanz = CustomScrollviewProduktOrganizer()      #########
                                             #########
        self.ProduktOrganizerInstanz = ProduktOrganizer()
        self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer.bind(text=self.produktorganizerfilter)
        self.Box.add_widget(self.ProduktOrganizerInstanz)
        self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.HauptListeDictonaries
        self.HauptCarousel.add_widget(self.Box)
        #self.HauptCarousel.add_widget(self.ProduktOrganizerInstanz)
        self.ButtonHinzufuegen = self.ProduktOrganizerInstanz.ids.ProduktlisteButtonHinzufuegen
        self.ButtonHinzufuegen.on_release = self.produkthinzufuegen

        self.PopupDateiAuswaehlenInst= PopupDateiAuswaehlenProduktorganizer()
        PopupDateiauswahl = self.PopupDateiAuswaehlenInst.ids.b.ids.a
        self.LadeButton = self.ProduktOrganizerInstanz.ids.LadeButton
        self.LadeButton.on_release = PopupDateiauswahl.open
        self.PopupDateiAuswaehlenInst.ids.b.ids.OkButtonFilechooser.on_release = self.datenentpickeln
        self.PopupDateiAuswaehlenInst.ids.b.ids.LayoutPopup.add_widget(Label
                                                                       (text='[b][color=ff3333]Achtung, nicht gespeicherte Eingaben gehen verloren![/b][/color]',
                                                                        size_hint= (1,0.1),
                                                                        markup = True,
                                                                        font_size = 14))

        self.PopupDateiAuswaehlenSpeichernInst = PopupDateiAuswaehlenProduktorganizer()
        PopupDateiauswahlSpeichern = self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.a
        
        
        self.SpeicherButton = self.ProduktOrganizerInstanz.ids.SpeicherButton
        self.SpeicherButton.on_release = PopupDateiauswahlSpeichern.open
        self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.OkButtonFilechooser.on_release = self.datenpickeln
        
        
        
       
        
        
        

        #print 'tempChildernListe',TempChildrenList
        
        #self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.add_widget(TextInput(multiline=False, size_hint= (1,0.15)))
        self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.add_widget(Label
                                                                       (text='[b][color=ff3333]Achtung, der Inhalt der Datei wird ueberschrieben![/b][/color]',
                                                                        size_hint= (1,0.1),
                                                                        markup = True,
                                                                        font_size = 14))
        TempChildrenList = []
        for q in self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.children:
            TempChildrenList.append(q)
        
        
            
        self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.clear_widgets()
        
        FileSaveLabelTextInput = Label(text='Zur Erstellung einer neuen Datei,einen Namen angeben',size_hint= (1,0.15), font_size=16)
        self.FileSaveTextInput = TextInput(multiline=False,size_hint= (1,0.15))

        
        TempChildrenList.sort(reverse=True)

        print "vor dem Einfuegen"
        for index, item in enumerate(TempChildrenList):
                print index, item
        
        TempChildrenList.insert(2, FileSaveLabelTextInput)
        TempChildrenList.insert(3, self.FileSaveTextInput)
        
        for i in TempChildrenList:
            #i.parent = None
            self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.LayoutPopup.add_widget(i)

        print "nach dem Einfuegen und sortieren"
            
        for index, item in enumerate(TempChildrenList):
                print index, item
        
        
        
        #self.LadeButton.bind(on_release = self.datenentpickeln)
        Spinner =self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer
        SpinnerText = Spinner.text
        self.LadeButton.bind(on_release = self.produktorganizerfilter)

        #self.ButtonHinzufuegen.on_release = self.inputdata

        #self.Box.add_widget(Button(size_hint= (1,0.1),text='inputdata', on_release=self.inputdata))

                                            

        
        self.PopupInst = PopupBildAuswaehlenProduktorganizer()
        popup = self.PopupInst.ids.a
        self.ProduktOrganizerInstanz.ids.ProduktBildAuswaehlen.on_release = popup.open


        self.PersonalOrganizerInstanz = PersonalOrganizer()
        self.HauptCarousel.add_widget(self.PersonalOrganizerInstanz)

        self.ZeitOrganizerInstanz = ZeitOrganizer()
        self.HauptCarousel.add_widget(self.ZeitOrganizerInstanz)

##    def inputdata(self):
##        print 'inputdadat runs'
##        #self.CustomScrollviewProduktOrganizerInstanz.data = [str(i) for i in range(5)]
##        self.ProduktOrganizerInstanz.ids.custScrlInst.data = [str(i) for i in range(5)]
      
        
   
        
    def produkthinzufuegen(self):
        #App.AuswahlHauptlisteAlt = App.AuswahlHauptliste
        NeuesDict ={}
    
        WertEingabeFeldBezeichnung = self.ProduktOrganizerInstanz.ids.EingabeFeldBezeichnung.text
        WertEingabeFeldPreis = self.ProduktOrganizerInstanz.ids.EingabeFeldPreis.text
##        StatusCheckBoxVerkauf = self.ProduktOrganizerInstanz.ids.CheckBoxVerkauf.active
        WertSpinnerKategorie = str(self.ProduktOrganizerInstanz.ids.SpinnerKategorie.text)
        filechooser = self.PopupInst.ids.filechooser
        DateiAuswahl = (str(filechooser.selection))[((str(filechooser.selection)).find('pictures')):-2]
        #print 'hallo', WertEingabeFeldBezeichnung, WertEingabeFeldPreis,DateiAuswahl,WertSpinnerKategorie
        ID = len(App.HauptListeDictonaries)
        NeuesDict = {'ID': ID,
                     'Bezeichnung':WertEingabeFeldBezeichnung,
                     'Preis':WertEingabeFeldPreis,
                     'Bild':DateiAuswahl,
                     'Kategorie':WertSpinnerKategorie}

        #print 'len(App.HauptListeDictonaries)', (len(App.HauptListeDictonaries))
##        if len(App.HauptListeDictonaries)<1:
##            App.HauptListeDictonaries.append(NeuesDict)
##            print 'Fall 1'
##        else:
        Treffer = False
        for i in range(len(App.HauptListeDictonaries[:])):
            print 'App.HauptListeDictonaries[i][Bezeichnung] ist', App.HauptListeDictonaries[i]['Bezeichnung']
            Bezeichnungdict = str(App.HauptListeDictonaries[i]['Bezeichnung'])
            Bezeichnungneuesdict = str(NeuesDict['Bezeichnung'])
            if Bezeichnungdict  == Bezeichnungneuesdict:
               
                Treffer = True
                break
            else:
                Treffer = False
        if Treffer == True:
            #print 'Dieses Produkt existiert schon'
            ButtonVerstanden = Button(text='Verstanden')
            popup = Popup(title='Dieses Produkt existiert bereits ',
                          size_hint = (0.5, 0.25),
                          content= ButtonVerstanden)
            popup.open()
            ButtonVerstanden.on_release = popup.dismiss
        else:
            App.HauptListeDictonaries.append(NeuesDict)
            
            #self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.clear_widgets()
##            print len(App.HauptListeDictonaries)
##            for index, item in enumerate(App.HauptListeDictonaries):
##                print index, item

                


            #self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.HauptListeDictonaries
            #self.ProduktOrganizerInstanz.ids.custScrlInst.data  = App.AuswahlHauptliste
            #AktuelleWidgetsInDerListe = self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.children
            #print 'App.AuswahlHauptlisteAlt', App.AuswahlHauptlisteAlt
            #AktuelleWidgetsInDerListe = self.CustomScrollviewProduktOrganizerInstanz.ids.content2.children
            #print AktuelleWidgetsInDerListe
            
            #self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.add_widget(Button(text='testmanuellereinfuegung'))
            
            AktuellerSpinnerWert = self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer.text
            self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.clear_widgets()
            
            App.AuswahlHauptliste = []    
            if AktuellerSpinnerWert == 'Alle':
                #self.CustomScrollviewProduktOrganizerInstanz.ids.content2.clear_widgets()
                print 'haha'
                App.AuswahlHauptliste = []
                for i in App.HauptListeDictonaries:
                    if i not in App.AuswahlHauptlisteAlt:
                        pass
                        
                        App.AuswahlHauptliste = App.HauptListeDictonaries
                        App.AuswahlHauptlisteAlt = []
                
            else:
                if self.SpinnerButtonZustand == 'Alle':
                    App.AuswahlHauptlisteAlt = []
                else:
                    pass
                
                for i in App.HauptListeDictonaries:
                    if i not in App.AuswahlHauptlisteAlt:
                        if i['Kategorie'] == AktuellerSpinnerWert:
                             
                            App.AuswahlHauptliste.append(i)
                        else:
                            continue
                    else:
                        continue

            self.ProduktOrganizerInstanz.ids.custScrlInst.data  = App.AuswahlHauptliste

    def produktorganizerfilter(self,  spinner, text='Alle'):
        spinner =self.ProduktOrganizerInstanz.ids.SpinnerProduktOrganizer
        
        text = spinner.text
        
        self.ProduktOrganizerInstanz.ids.custScrlInst.data = []
        #print 'produktorganizerfilter, App.AuswahlHauptlisteAlt', App.AuswahlHauptlisteAlt
        
        if self.SpinnerButtonZustand == 'Alle':
            App.AuswahlHauptlisteAlt = []
        else:
            App.AuswahlHauptlisteAlt = App.AuswahlHauptliste

        #custScrlInst
        self.ProduktOrganizerInstanz.ids.custScrlInst.ids.content2.clear_widgets()
        #self.CustomScrollviewProduktOrganizerInstanz.ids.content2.clear_widgets()
        App.AuswahlHauptliste=[]
        if text == 'Alle':
            
           App.AuswahlHauptliste = App.HauptListeDictonaries
           self.SpinnerButtonZustand = 'Alle'
           if self.ProduktOrganizerInstanz.ids.custScrlInst.data == App.AuswahlHauptliste:
               self.ProduktOrganizerInstanz.ids.custScrlInst.data = []
           
           
        else:
            self.SpinnerButtonZustand = 'Anders'
            for i in App.HauptListeDictonaries:
                if i not in App.AuswahlHauptlisteAlt: 
                    #print i['Kategorie']
                    if i['Kategorie'] == text:
                        App.AuswahlHauptliste.append(i)
                    else:
                        continue
                else:
                    continue

            
                

        #print 'Auswahl Hauptliste ist nun', App.AuswahlHauptliste
        self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.AuswahlHauptliste

                
                
            

       
                    
   

        
        
        
        




    def DropdownbuttonCreator(self):
        Auswahlliste = ["Tisch +", "Tisch -", "Spalte + ", "Spalte -", "Reihe + ", "Reihe -"]
        BackgroundcolorListe = [(0,1,0,1),(1,0,0,1),(0,1,0,1),(1,0,0,1),(0,1,0,1),(1,0,0,1)]
        Aktionsliste = [self.tischhinzufuegen, self.tischentfernen, self.spaltehinzufuegen, self.spalteentfernen, self.zeilehinzufuegen, self.zeileentfernen]
        DropdownObjekt = CustomDropDown()
        DropdownObjektButton = CustomButton(text = "Menue",
        #DropdownObjektButton = ToggleButton(text="Menue",
                                            size_hint=[1,1],
                                            background_color = (0.8, 0.8, 0.00, 1),
                                            background_normal='bilder_oberflaeche/white2.png',
                                            background_down='bilder_oberflaeche/white3.png')
        #self.CustomLayout.add_widget(DropdownObjektButton)
        DropdownObjektButton.bind(on_release=DropdownObjekt.open)
        self.DropdownObjects.append(DropdownObjekt)
        for x in range(len(Auswahlliste)):

                DropdownUnterbutton = Button(text=Auswahlliste[x], font_size = 15, size_hint_y=None, height=60,
                                             background_color = BackgroundcolorListe[x],
                                             background_normal='bilder_oberflaeche/white2.png',
                                             background_down='bilder_oberflaeche/white3.png',
                                             opacity = 0.8,
                                             on_release = Aktionsliste[x])
                DropdownObjekt.add_widget(DropdownUnterbutton)

        
        ButtonMenu1 = DropdownObjektButton
        return ButtonMenu1 


        
    def tischerstellung (self, Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe):
        Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"]
        BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)]
        Aktionsliste = [self.bestellung, self.abrechnung, self.bestellungaendern, self.tischbenennen]
        
        #self.DropdownObjects = []
        for i in range(AnzahlTische):
            if self.Tischliste != []:
                LetzterTisch = self.Tischliste[-1]['Nummer']
##                print LetzterTisch + 1
            else:
                LetzterTisch = 0
            
            TischNr = str(LetzterTisch+1)
            TischButtonText = "T " + TischNr
            DropdownObjekt = CustomDropDown() #von kovak hinzugefuegt
            #DropdownObjektButton = CustomButton(text = TischButtonText,
            DropdownObjektButton = ToggleButton(text = TischButtonText,
                                                group='Tische',
                                                #background_normal='bilder_oberflaeche/white2.png',
                                                background_normal='bilder_oberflaeche/buttonbackground_normal_gruenrandaussenbraun.png',
                                                background_down='bilder_oberflaeche/buttonbackground_normal_weissrandaussenbraun.png',
                                                #background_down='bilder_oberflaeche/white4.png',
                                                #background_color = (0.79, 0.39, 0.09, 1))#0.6))
                                                background_color = (1, 1, 1, 1))#0.6))
            Zielwidget.add_widget(DropdownObjektButton)
            DropdownObjektButton.bind(on_release=DropdownObjekt.open)
            self.DropdownObjects.append(DropdownObjekt) #von kovak hinzugefuegt

            for x in range(len(Auswahlliste)):

                DropdownUnterbutton = Button(text=Auswahlliste[x],
                                             id = TischNr,
                                             #auto_width='False',
                                             #width = '200sp',
                                             font_size = 15,
                                             size_hint_y=None,
                                             height=60,
                                             background_normal='bilder_oberflaeche/white2.png',
                                             background_down='bilder_oberflaeche/white3.png',
                                             background_color = BackgroundcolorListe[x],
                                             on_release = Aktionsliste[x])
                DropdownObjekt.add_widget(DropdownUnterbutton)

                #print' button', i, 'unterbutton', x



            DropdownObjektButton.text= TischButtonText
            self.TischButtondict = {'Nummer':(LetzterTisch + 1),'Objekt':DropdownObjektButton}
            self.Tischliste.append(self.TischButtondict)
            
        
    def garbagecollectortracking(self, widget):
        for i in self.Tischliste:
            a = i
            print gc.is_tracked(a)
        
        
### function for Editing a Table#######################################
    #def tischmanipulieren(self, widget):
     #   widget.text = 'mein text'
        
#### function for adding an extra table to layout ##########################

    def tischhinzufuegen(self, widget):
        
        if len(self.Tischliste) >= 1:
            if hasattr(self, 'CustomLayoutBottomLabel'):
                self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel)
               
            
        AnzahlTische = 1
        Zielwidget = self.CustomLayoutGridLayout
        Auswahlliste = ["Bestellung", "Abrechnung", "Best. Aendern", "Bennenen"]
        BackgroundcolorListe = [(1,0,0,1),(0,1,0,1),(0,0,1,1),(1,1,0,1)]
        LetzterTisch = self.Tischliste[-1]['Nummer']
        if (self.CustomLayoutGridLayout.cols * self.CustomLayoutGridLayout.rows) <= (LetzterTisch +1):
            self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1
        self.tischerstellung(Zielwidget, AnzahlTische, Auswahlliste, BackgroundcolorListe)

    def tischentfernen(self, widget):
        self.Warnlabel = 0 
        if len(self.Tischliste) <= 1:
            if hasattr(self, 'CustomLayoutBottomLabel'):
                # obj.attr_name exists.
                
                if self.CustomLayoutBottomLabel in self.CustomLayout.children:
                    self.Warnlabel=1    
            print 'das ist der Letzte Tisch, der kann nicht entfernt werden'
            if self.Warnlabel == 0:
                
                self.CustomLayoutBottomLabel= Label(text='Das ist der Letzte Tisch,\n der kann nicht \n entfernt werden', text_size = self.size)
                self.CustomLayout.add_widget(self.CustomLayoutBottomLabel)
            
        else:
            Zielwidget = self.CustomLayoutGridLayout
            Zielwidget.remove_widget(self.Tischliste[-1]['Objekt'])
            
            del self.Tischliste[-1]
            LetzterTisch = self.Tischliste[-1]['Nummer']
            print 'die anzahl der Tische ist nun:', LetzterTisch
        
        

        
        pass
#### function for adding a column to layout ####################################

    def spaltehinzufuegen(self, widget):
        if self.CustomLayoutGridLayout.cols >= 1:
            if hasattr(self, 'CustomLayoutBottomLabel'):
                self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel)
                self.WarnLabel = 0 
        self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols + 1
        print 'Zeile hinzufuegen'
        

    def spalteentfernen(self, widget):
        self.Warnlabel = 0
        if self.CustomLayoutGridLayout.cols <= 1:
            if hasattr(self, 'CustomLayoutBottomLabel'):
                # obj.attr_name exists.
                if self.CustomLayoutBottomLabel in self.CustomLayout.children:
                    self.Warnlabel=1    
            print 'das ist die letzte Tischreihe, sie kann nicht entfernt werden'
            if self.Warnlabel == 0:
                
                self.CustomLayoutBottomLabel= Label(text='Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden', text_size = self.size)
                self.CustomLayout.add_widget(self.CustomLayoutBottomLabel)

        else:
            TischanzahlVerbleibend = (self.CustomLayoutGridLayout.cols -1) * self.CustomLayoutGridLayout.rows
                           
            for i in range(len(self.Tischliste[TischanzahlVerbleibend:])):
                self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend+ i]['Objekt'])
                
            del self.Tischliste[TischanzahlVerbleibend:]
            self.CustomLayoutGridLayout.cols = self.CustomLayoutGridLayout.cols - 1

       
#### function for adding a row to layout ####################################

    def zeilehinzufuegen(self, widget):
        if self.CustomLayoutGridLayout.rows >= 1:
            if hasattr(self, 'CustomLayoutBottomLabel'):
                self.CustomLayout.remove_widget(self.CustomLayoutBottomLabel)
                self.WarnLabel = 0 
        self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows + 1
        print 'Zeile hinzufuegen'
        

        

    def zeileentfernen(self, widget=None):
        self.Warnlabel = 0
        if self.CustomLayoutGridLayout.rows <= 1:
            if hasattr(self, 'CustomLayoutBottomLabel'):
                # obj.attr_name exists.
                if self.CustomLayoutBottomLabel in self.CustomLayout.children:
                    self.Warnlabel=1    
            print 'das ist die letzte Tischreihe, sie kann nicht entfernt werden'
            if self.Warnlabel == 0:
                
                self.CustomLayoutBottomLabel= Label(text='Das ist die letzte Tischreihe,\n sie kann nicht \n entfernt werden', text_size = self.size)
                self.CustomLayout.add_widget(self.CustomLayoutBottomLabel)

        else:
            TischanzahlVerbleibend = (self.CustomLayoutGridLayout.rows -1) * self.CustomLayoutGridLayout.cols
                           
            for i in range(len(self.Tischliste[TischanzahlVerbleibend:])):
                self.CustomLayoutGridLayout.remove_widget(self.Tischliste[TischanzahlVerbleibend+ i]['Objekt'])
                
            del self.Tischliste[TischanzahlVerbleibend:]
            self.CustomLayoutGridLayout.rows = self.CustomLayoutGridLayout.rows - 1

    
        
    def bestellung(self, widget):
        App.my_index = -1
        
        TischNr = widget.id
        PopupFloatLayout = FloatLayout(size_hint=(1, 1))
        
        self.PopupScrollview = CustomScrollviewPopupContent()
        self.PopupScrollviewItem = CustomButton2()
        
        App.AuswahlHauptliste = App.HauptListeDictonaries
        self.PopupScrollview.data = App.AuswahlHauptliste
        
        
        #content = self.PopupScrollview.ids.content
        #item = self.PopupScrollviewItem
               
        popup = Popup(title='Bestellung für Tisch ' + str(TischNr),
                      content= PopupFloatLayout)
       
             

        BoxTop = BoxLayout(size_hint= [0.52,0.065],pos_hint={'x': 0.5, 'y': 1.005}, spacing = 5)
        ButtonExit = Button(text="Exit",
                            #pos_hint={'x': 0.825, 'y': 1.005},
                            #size_hint = [0.2,0.065],
                            size_hint = [0.3,1],
                            #on_release = self.zeromyindex,
                            
                            on_release = popup.dismiss)
        #myindexzero = 0
        #ButtonExit.bind(on_release=ButtonExit.setter('myindexzero'))
        #print App.my_index

        self.ButtonSpinner =Spinner(text= "Alle",
                               values= ("Mittag-Essen", "Getraenke", "AlcGetraenke", "Essen Alltime", "Alle"),
                               size_hint= [0.7,1],
                               #pos_hint={'x': 0.625, 'y': 1.005}
                               )
        self.ButtonSpinner.bind(text=self.show_selected_value)        
        #halign: 'right'
        #valign: 'top'

        #PopupFloatLayout.add_widget(ButtonExit)
        #PopupFloatLayout.add_widget(ButtonSpinner)
        
        BoxTop.add_widget(self.ButtonSpinner)
        BoxTop.add_widget(ButtonExit)
        PopupFloatLayout.add_widget(BoxTop)
        
        self.PopupScrollview.size_hint = [1.05,1.017]
        self.PopupScrollview.center = popup.center
        PopupFloatLayout.add_widget(self.PopupScrollview)
        for i in App.ScrollviewButtons:
            i.ids.customID.on_release = self.Optionsfenster
        
       
        popup.open()
        print App.ScrollviewButtons
    
        

##        
##    def on_data(self, instance, value):
##        content_add = self.PopupScrollview.ids.content.add_widget
##        for item in value:
##            print item
##            content_add(CustomButton2(text=item))

        #return CustomScrollviewPopupContent()

        
    def show_selected_value(self, spinner, text):
        print 'The spinner', spinner, 'have text', text
        App.AuswahlHauptliste=[]
        if text == 'Alle':
            App.AuswahlHauptliste = App.HauptListeDictonaries
            self.PopupScrollview.data = App.AuswahlHauptliste
        else:
            for i in App.HauptListeDictonaries:
                if i['Kategorie'] == text:
                    App.AuswahlHauptliste.append(i)
                else:
                    continue

            self.PopupScrollview.data = App.AuswahlHauptliste
        
            
    

   


        
    def zeromyindex(self, widget):
        App.my_index = (-1)
        

    def Optionsfenster(self):
        self.OptionenPopupBestellungen = OptionenPopupBestellungen()
        
        print 'App.AktuelleBestellungProduktAnzahlzaehler', App.AktuelleBestellungProduktAnzahlzaehler
        for i in range(App.AktuelleBestellungProduktAnzahlzaehler):
            self.OptionenPopupBestellungen.ids.OptionsPopupContent.add_widget(ToggleButton(text=i))

        self.OptionenPopupBestellungen.open()
        
        
            
            
               

        

    def groesse(self,widget):
        print 'die buttongroesse ist:', widget.size

    

    def abrechnung(self, widget):
        TischNr = widget.id
        PopupFloatLayout = FloatLayout()       
        self.ScreenmanagerPopup = CustomScreenManager()
        self.ScreenPopup = CustomScreen
        
        for x in xrange(4):
            self.ScreenmanagerPopup.add_widget(self.ScreenPopup(name='Screen %d' % x))
        #popup = Popup(title='Abrechnung für ' + str(TischNr),
        #              content=self.ScreenmanagerPopup,size_hint=(1, 1) )
        popup = Popup(title='Abrechnung für Tisch' + str(TischNr),
                      content=PopupFloatLayout)#,
                      #size_hint=(1, 1),
                      #pos_hint={'x': 0.5, 'y': 0.5} )

        self.ScreenmanagerPopup.pos_hint = {'x': 0, 'y': 0} 
        PopupFloatLayout.add_widget(self.ScreenmanagerPopup)

        ButtonExit = Button(text="Exit",
                            pos_hint={'x': 0.8, 'y': 1.005},
                            size_hint = [0.2,0.065],
                            on_release = popup.dismiss)
        PopupFloatLayout.add_widget(ButtonExit)

        popup.open()
        

    def bestellungaendern(self, widget):
        pass

    def tischbenennen(self, widget):
        TischNr = widget.id
        PopupBox1LayoutTischBennenen = BoxLayout(orientation = 'vertical')
        popup = Popup(title='Tisch Nr. ' + str(TischNr) + 'benennen',
                      content=PopupBox1LayoutTischBennenen,
                      size_hint=(0.75, 0.5))
        EingabeTextfeld = TextInput(text='hier Tischbezeichnung eintragen - Funktion muss noch eingebaut werden')            
        PopupBox1LayoutTischBennenen.add_widget(EingabeTextfeld)
        PopupBoxLayoutTischBenennen = BoxLayout(orientation = 'horizontal', size_hint=(1,1))
        ButtonAbbrechenTischBenennen = Button(text="Abbrechen", size_hint=(0.5, 0.5))
        ButtonAbbrechenTischBenennen.bind(on_press=popup.dismiss)
        ButtonOkTischBenennen = Button(text="OK", size_hint=(0.5, 0.5))
        ButtonOkTischBenennen.bind(on_press=popup.dismiss)
        PopupBox1LayoutTischBennenen.add_widget(PopupBoxLayoutTischBenennen)
        PopupBoxLayoutTischBenennen.add_widget(ButtonAbbrechenTischBenennen)
        PopupBoxLayoutTischBenennen.add_widget(ButtonOkTischBenennen)
        #popup.add_widget
        popup.open()
        
        pass

      



#### function for exporting Data to file ####################################

    def datenpickeln(self):
        
        filechooser = self.PopupDateiAuswaehlenSpeichernInst.ids.b.ids.filechooser
        AusgewaehlteDatei = str(filechooser.selection)
        AusgewaehlteDatei = (AusgewaehlteDatei)[AusgewaehlteDatei.find('Produktlisten'):-2]
        if self.FileSaveTextInput.text != '':
            print 'Du hast einen Dateinamen eingegeben'
            AusgewaehlteDatei = 'Produktlisten/'+(str(self.FileSaveTextInput.text))
        print 'Daten Speichern ausgefuehrt'
        print AusgewaehlteDatei
        SicherungsItem1 = self.HauptCarousel2.Texteingabe.text
        SicherungsItem2 = App.HauptListeDictonaries
        Sicherungsliste = [SicherungsItem1, SicherungsItem2]
        
        '''function to pickle data to make it ready for sending'''
        try:
            with open(AusgewaehlteDatei, 'w+b') as SicherungslisteDaten_File:
                pickle.dump(Sicherungsliste, SicherungslisteDaten_File)
        except IOError as err:
            print('Dateifehler: ' + str(err))
        except pickle.PickleError as perr:
            print('Pickling Fehler: ' + str(perr))

	#### function for importing Data to file ####################################

    def datenentpickeln(self):
        filechooser = self.PopupDateiAuswaehlenInst.ids.b.ids.filechooser
        AusgewaehlteDatei = str(filechooser.selection)
        print 'Daten Laden ausgefuehrt'
        print AusgewaehlteDatei
        AusgewaehlteDatei = (AusgewaehlteDatei)[AusgewaehlteDatei.find('Produktlisten'):-2]
        #App.datenentpickeln = self(datenentpickeln(widget = None))
        with open(AusgewaehlteDatei, 'rb') as SicherungslisteDaten_File_entpickelt:
            SicherungslisteWiederhergestellt = pickle.load(SicherungslisteDaten_File_entpickelt)
            #self.HauptCarousel3.Textausgabe.text = SicherungslisteWiederhergestellt[0]
            App.HauptListeDictonaries = SicherungslisteWiederhergestellt[1]
##            App.AuswahlHauptListe = App.HauptListeDictonaries
##            self.ProduktOrganizerInstanz.ids.custScrlInst.data = App.AuswahlHauptListe
        self.produktorganizerfilter(self) 
        print 'die daten wurden wieder hergestellt'
Exemplo n.º 21
0
class EqScr(Screen):
    def __init__(self, **kwargs):
        super(EqScr, self).__init__(**kwargs)
        self.head = self.ids['head']
        self.armor = self.ids['armor']
        self.eq = []
        self.eq_n = []
        self.eq_weapon = []
        self.eq_armor = []
        self.eq_armor_n = []
        self.get_hero_eq()
        self.print_armor()
        self.print_lhand()

        Clock.schedule_interval(self.update, 1 / 1.0)

    def get_hero_eq(self):
        if len(Hero.Magni.eq) != len(self.eq):
            self.eq.clear()
            self.eq_n.clear()
            for x in range(len(Hero.Magni.eq)):
                self.eq.append(Hero.Magni.return_full_eq(x))
            for x in range(len(self.eq)):
                if type(self.eq[x]) is Item.Weapon:
                    self.eq_n.append(str(self.eq[x].name))
                    self.eq_weapon.append(Hero.Magni.return_full_eq(x))
                elif type(self.eq[x]) is Item.Armor:
                    self.eq_armor_n.append(str(self.eq[x].name))
                    self.eq_armor.append(Hero.Magni.return_full_eq(x))

    def print_lhand(self):
        self.head.clear_widgets()
        self.spinner = Spinner(
            text='Left Hand',
            values=map(str, self.eq_n),
            size_hint=(None, None),
            size=(150, 44),
            pos_hint={'center_x': .5, 'center_y': .5})

        def show_selected_value(spinner, text):
            print('The spinner', self.spinner, 'have text', text)
            print(self.eq_n.index(text))
            index = self.eq_n.index(text)
         #
            try:
                if self.all_same(self.eq_weapon, Hero.Magni.lhand_weapon ):
                    Hero.Magni.remove_weapon("left", self.old_weapon, Hero.Magni)
                Hero.Magni.add_weapon("left", self.eq_weapon[index], Hero.Magni)
                self.old_weapon = self.eq_weapon[index]
                Hero.Magni.print_eq2()
            except:
                print("errror")

        self.spinner.bind(text=show_selected_value)
        self.head.add_widget(self.spinner)

    def print_armor(self):
        self.armor.clear_widgets()
        self.a_spinner = Spinner(
            text='Armor',
            values=map(str, self.eq_armor_n),
            size_hint=(None, None),
            size=(150, 44),
            pos_hint={'center_x': .5, 'center_y': .5})

        def show_selected_value(spinner, text):
            print('The spinner', self.spinner, 'have text', text)
            print(self.eq_armor_n.index(text))
            index = self.eq_armor_n.index(text)
            try:
                if self.all_same(self.eq_armor, Hero.Magni.armory):
                    Hero.Magni.remove_armor(self.old_arm, Hero.Magni)
                Hero.Magni.add_armor(self.eq_armor[index], Hero.Magni)
                self.old_arm = self.eq_armor[index]
                Hero.Magni.print_armor()
            except:
                print("d")

        self.a_spinner.bind(text=show_selected_value)
        self.armor.add_widget(self.a_spinner)

    def all_same(self, itm1, itm2):
        for i in set(itm1) & set(itm2):
            return True

    def update(self, *args):
        if len(Hero.Magni.eq) != len(self.eq):
            self.get_hero_eq()
            self.print_lhand()
            self.print_armor()
Exemplo n.º 22
0
class MainLayout(GridLayout):
    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)
        self.Interpreter = Interpreter()
        self.command_stack = []

        self.cols = 2
        self.orientation = "vertical"
        self.padding = 10

        self.workspace = Workspace()
        self.command_panel = CommandPanel(self.workspace)
        self.output = Output()

        self.spn_menu = Spinner(text='Menu', values=('New', 'Save', 'RUN', 'Exit'), size_hint =(None, None), size=(200, 44), pos_hint={'x': .1, 'y': .9})
        self.spn_menu.bind(text=self.menu_option_selected_event)
        
        self.command_panel.draw(self.spn_menu)
        self.command_panel.add_expression_btn('LET')
        self.command_panel.add_expression_btn('PRINT')
        self.command_panel.add_expression_btn('GOTO')
        self.command_panel.add_expression_btn('IF')
        self.command_panel.add_expression_btn('GOSUB')
        self.command_panel.add_expression_btn('RETURN')
        self.command_panel.add_expression_btn('END')
        self.add_widget(self.command_panel)

        self.orientation = "horizontal"
        self.workspace.draw()
        self.add_widget(self.workspace)
        
        self.output.draw()
        self.add_widget(self.output)

    #def on_touch_down(self, touch):
    #    super(MainLayout, self).on_touch_down(touch)
    #    for widget in self.workspace.layout.walk():
    #        if widget.id == 'LET':
    #            x = (touch.x- self.command_panel.x)
    #            y = (touch.y - self.command_panel.y)
    #            print widget.collide_point(x,y )
    #            print x
    #            print y

    """
    This is where the the program is run when user clicks Run from menu
    """
    def run_app(self):
        i = self.Interpreter

        has_expressions = False
        error_msgs = []

        for each_exp in self.workspace.get_expressions():
            expression_line = each_exp.get_expression()
            has_expressions = True
            if expression_line[0] is "Error":
                error_msgs.append(expression_line[1])
            else:            
                
                i.add_line(each_exp.get_line_number(), expression_line)

        if has_expressions is False:
            self.output.clear()
            self.output.write_error(["Nothing to run"])
            return 0

        if len(error_msgs) > 0:
            self.output.clear()
            self.output.write_error(error_msgs)
            return 0           
        i.clear_output()
        i.run()
        output = i.get_output()
        variables = i.get_variables()
        self.workspace.update_variable_names(sorted(variables))

        self.output.add_text("\n Output : \n")
        for value in output:
            self.output.add_text(' ' + str(value)+'\n')

        self.output.add_text('\n Memory: \n')
        self.output.add_text(' Variable \t Value \n')
        for var in sorted(variables):
            value = ' \t' + var + ' \t\t\t ' + str(variables[var]) + '\n'
            self.output.add_text(' ' + str(value))
        self.output.add_text('-------------------------------------------')
    
    """
    When user selects a menu option from the spinner
    """
    def menu_option_selected_event(self, instance, option):
        
        if option == 'New':
            self.spn_menu.text = 'Menu'
            self.workspace.clear()
            #self.Interpreter = Interpreter()
            
        elif option == 'Exit':
            sys.exit()
        elif option == 'RUN':
            self.spn_menu.text = 'Menu'
            self.run_app()
Exemplo n.º 23
0
    def build(self):
        """Build the user interface."""

        wid = Widget()

        self.counter = Label(text="0")
        labelA = Label(text=self.get_scores()[0])
        labelB = Label(text=self.get_scores()[1])
        labels = (labelA, labelB)
        self.labels = labels
        self.wid = wid

        agentA_spinner = Spinner(
            text='Agent A',
            text_size=(95, None),
            haligh="center",
            shorten=True,
            values=sorted([agent for agent in ALL_AGENTS.keys()]) +
            ["Agent A"],
            size=(100, 44)
        )

        agentB_spinner = Spinner(
            text='Agent B',
            text_size=(95, None),
            shorten=True,
            values=sorted([agent for agent in ALL_AGENTS.keys()]) +
            ["Agent B"],
            size=(100, 44)
        )

        maps_spinner = Spinner(
            text='Maps',
            text_size=(95, None),
            shorten=True,
            values=sorted([map for map in ALL_MAPS.keys()]) + ["Maps"],
            size=(100, 44)
        )

        agentA_spinner.bind(text=self.select_agent_A)
        agentB_spinner.bind(text=self.select_agent_B)
        maps_spinner.bind(text=self.select_map)

        btn_load = Button(text='Load',
                          on_press=partial(self.load_env, labels, wid))

        btn_step = Button(text='Step >',
                          on_press=partial(self.btn_step, labels, wid))

        self.btn_100step = ToggleButton(text='100 Step >',
                                        on_press=partial(self.btn_100step,
                                                         self.running_step,
                                                         labels,
                                                         wid))

        self.btn_run = ToggleButton(
            text='Run >>', on_press=partial(self.btn_run,
                                            self.running_step,
                                            labels,
                                            wid))

        btn_stop = Button(text='Stop [ ]',
                          on_press=partial(self.btn_stop,
                                           self.running_step))

        self.partial_reset = partial(self.reset_all,
                                     labels,
                                     (agentA_spinner,
                                      agentB_spinner, maps_spinner),
                                     wid)

        btn_reset = Button(text='Reset',
                           on_press=self.partial_reset)

        Window.bind(on_resize=self.on_resize)

        action_layout = BoxLayout(size_hint=(1, None), height=50)
        action_layout.add_widget(btn_load)
        action_layout.add_widget(btn_step)
        action_layout.add_widget(self.btn_100step)
        action_layout.add_widget(self.counter)
        action_layout.add_widget(self.btn_run)
        action_layout.add_widget(btn_stop)
        action_layout.add_widget(btn_reset)

        agents_layout = BoxLayout(size_hint=(1, None), height=50)
        agents_layout.add_widget(agentA_spinner)
        agents_layout.add_widget(labelA)
        agents_layout.add_widget(agentB_spinner)
        agents_layout.add_widget(labelB)
        agents_layout.add_widget(maps_spinner)

        root = BoxLayout(orientation='vertical')
        root.add_widget(wid)
        root.add_widget(action_layout)
        root.add_widget(agents_layout)

        return root
Exemplo n.º 24
0
    def build(self):
        self.robot = Robot(status_display=self, code_display=self,
                           on_disconnect=self._on_disconnect,
                           on_stiffness=self._on_chain_stiffness_from_robot)

        # building Kivy Interface
        b = BoxLayout(orientation='vertical')

        menu = BoxLayout(
            size_hint_y=None,
            height='30pt')
        fnt_name = Spinner(
            text='DroidSansMono',
            option_cls=Fnt_SpinnerOption,
            values=sorted(map(str, fonts.get_fonts())))
        fnt_name.bind(text=self._update_font)

        # file menu
        mnu_file = Spinner(
            text=localized_text('file_menu_title'),
            values=(localized_text('file_connect'),
                    localized_text('file_open'),
                    localized_text('file_save_as'),
                    localized_text('file_save'),
                    localized_text('file_close')))
        mnu_file.bind(text=self._file_menu_selected)

        # motors on/off
        btn_motors = ToggleButton(text=localized_text('motors_on'),
                                  state='normal',
                                  background_down='stiff.png',
                                  background_normal='relaxed.png')
        btn_motors.bind(on_press=self._on_motors)
        self._motor_toggle_button = btn_motors

        btn_speech = ToggleButton(text=localized_text('speech_recognition'),
                                         state='down' if self.robot.is_speech_recognition_enabled else 'normal')
        btn_speech.bind(on_press=self._on_toggle_speech_recognition)

        btn_touch_sensors = ToggleButton(text=localized_text('touch_sensors'),
                                         state='down' if self.robot.is_touch_sensors_enabled else 'normal')
        btn_touch_sensors.bind(on_press=self._on_toggle_touch_sensors)

        # run script
        btn_run_script = Button(text=localized_text('run_script'))
        btn_run_script.bind(on_press=self._on_run_script)
        self.btn_run_script = btn_run_script

        # root actions menu
        robot_actions = Spinner(
            text=localized_text('action_menu_title'),
            values=sorted(self.robot.postures()))
        robot_actions.bind(text=self.on_action)

        # add to menu
        menu.add_widget(mnu_file)
        menu.add_widget(btn_speech)
        menu.add_widget(btn_touch_sensors)
        menu.add_widget(btn_motors)
        menu.add_widget(btn_run_script)
        menu.add_widget(robot_actions)
        b.add_widget(menu)

        controls = BoxLayout(
            size_hint_y=None,
            height='30pt')

        # add keyframe
        btn_add_keyframe = Button(text=localized_text('add_keyframe'))
        btn_add_keyframe.bind(on_press=self._on_add_keyframe)
        controls.add_widget(btn_add_keyframe)

        # set read joint angles to enable animation to start from known position
        btn_update_joints = Button(text=localized_text('read_joints'))
        btn_update_joints.bind(on_press=self._on_read_joints)
        controls.add_widget(btn_update_joints)

        kf_duration_label = Label(text=localized_text('keyframe_duration_colon'))
        controls.add_widget(kf_duration_label)

        kf_duration_input = TextInput(text=str(self.robot.keyframe_duration), multiline=False)
        kf_duration_input.bind(text=self._on_keyframe_duration)
        controls.add_widget(kf_duration_input)

        # allow user to select which translator to use
        active_translator = Spinner(
            text=self.robot.get_translator_name(),
            values=get_translator_names())
        active_translator.bind(text=self._on_translator_changed)
        controls.add_widget(active_translator)
        self.active_translator = active_translator
        self.is_translator_cancel = False

        b.add_widget(controls)

        m = BoxLayout()
        code_status = BoxLayout(orientation='vertical', size_hint=(0.6, 1))

        # code input
        self.codeinput = CodeInput(
            lexer=lexers.PythonLexer(),
            font_name='data/fonts/DroidSansMono.ttf', font_size=12,
            text="nao.say('hi')")
        code_status.add_widget(self.codeinput)

        # status window
        self.status = TextInput(text="", readonly=True, multiline=True, size_hint=(1.0, 0.25))
        code_status.add_widget(self.status)


        m.add_widget(code_status)
        self.joints_ui = NaoJoints(size_hint=(0.4, 1),
                                   on_joint_selection=self._on_joint_selection,
                                   on_chain_stiffness=self._on_chain_stiffness,
                                   on_hand_open_close=self._on_hand_open_close)
        m.add_widget(self.joints_ui)

        b.add_widget(m)
        return b
Exemplo n.º 25
0
class MenuWidget(FloatLayout):
        def __init__(self, **kwargs):
                super(MenuWidget, self).__init__(**kwargs)

                self.choices = {
                        "demo_bounce": "Basic physics simulation",
                        "demo_breakout": "Breakout demo",
                        "demo_gauntlet": "Top down tile map game",
                        "demo_starship": "'Endless' scrolling background and animation",
                        "demo_text": "Text drawing",
                        "demo_tiles": "Tile map scrolling",
                        "demo_pinball": "Simple pinball demo",
                        "demo_squares": "Random set of falling physical objects",
                        "demo_car": "Top down car driving game",
                        "demo_sprites": "Draw a large amount of sprites",
                        }

                layout = StackLayout(orientation="tb-lr", padding=[10, 20, 10, 20])

                layout.add_widget(Image(source="assets/img/ui/logo.png", size_hint=(1, 0.4), allow_stretch = True,))

                layout.add_widget(Label(text="Choose demo:", size_hint=(1, 0.1)))

                self.spinner = Spinner(text=DEFAULT_START_CHOICE, values=[x for x in self.choices.iterkeys()], size_hint=(1, 0.1))
                layout.add_widget(self.spinner)
                self.spinner.bind(text=self.show_selected_value)

                self.description_label = Label(text=self.choices[DEFAULT_START_CHOICE], valign="middle", halign="center", size_hint=(1, 0.2))
                self.description_label.bind(size=self.description_label.setter("text_size"))
                layout.add_widget(self.description_label)

                run_button = Button(text="Run", size_hint=(1, 0.1))
                run_button.bind(state=self.on_run)
                layout.add_widget(run_button)

                debug_layout = BoxLayout(orientation='horizontal', size_hint=(1, 0.1))
                debug_layout.add_widget(Label(text=" "))
                self.debug_checkbox = CheckBox()
                self.debug_checkbox.active = False
                debug_layout.add_widget(self.debug_checkbox)
                debug_layout.add_widget(Label(text="Show debug info", valign="middle", halign="center"))
                debug_layout.add_widget(Label(text=" "))
                debug_layout.add_widget(Label(text=" "))
                self.add_widget(debug_layout)

                self.add_widget(layout)

                if platform == 'win' or platform == 'linux' or platform == 'macosx':
                        Window.bind(on_key_up=self._on_keyboard_up)

        def _on_keyboard_up(self, window, keycode, scancode):
                self.on_run(None, None)

        def show_selected_value(self, spinner, value):
                self.description_label.text = self.choices[value]

        def on_run(self, instance, value):
                if self.parent:
                        parent = self.parent
                        parent.remove_widget(self)

                        state = None
                        module_name = self.spinner.text
                        global DEFAULT_START_CHOICE
                        DEFAULT_START_CHOICE = module_name

                        exec("import %s" % module_name)
                        exec("state = %s.create(SCREEN_LOGICAL_WIDTH, SCREEN_LOGICAL_HEIGHT, TILE_SIZE)" % self.spinner.text)

                        parent.add_widget(ScreenWidget(state,
                                                       self.on_exit_game,
                                                       self.debug_checkbox.active
                                                       )
                                          )

        def on_exit_game(self, state, parent_widget):
                parent_widget.add_widget(MenuWidget())
Exemplo n.º 26
0
from kivy.uix.spinner import Spinner
from kivy.base import runTouchApp

spinner = Spinner(
    text='Home',
    values=('Home', 'Work', 'Other', 'Custom'),
    size_hint=(None, None), size=(100, 44),
    pos_hint={'center_x': .5, 'center_y': .5})


def show_selected_value(spinner, text):
    print('The spinner', spinner, 'have text', text)


spinner.bind(text=show_selected_value)

runTouchApp(spinner)
Exemplo n.º 27
0
class bippyApp(App):
	"""
		Main Application Class required for Kivy
	"""

	def getCur(self, instance, value=False):
		"""
			From the currency longName returned by the UI
			return the Abbreviation understood by the rest of the application
		"""
		if value == '----------Currencies below are not currently available at woodwallets.io----------':
			instance.text = self.selectedCurrencyLongName
			return
		for cur in currencies:
			if cur['longName'] == value:
				self.selectedCurrency = str(cur['currency'])
				self.selectedCurrencyLongName = str(cur['longName'])
				return

	def checkPrivK(self, instance, value=False):
		"""
			Perform various checks on the private key data and act accordingly
			This is called whenever the Private Key entry box looses focus
		"""

		if value:
			return
		testKey = instance.text
		self.PasswordEnter.text = ''
		self.entropyImage.unbind(on_touch_move=self.draw)
		self.prog.value = 0
		self.entropyImage.canvas.remove_group('ellipses')

		#Test if it is an electrum seed
		if key.isElectrumSeed(testKey):
			self.MainLabel.text = 'It looks like you entered an Electrum seed.\n\nEnter a Passphrase to encrypt it.'
			self.PrivKLabel.text = 'Electrum Seed'
			self.PassLabel.text = 'Enter\nPassphrase'
			return

		#Test if it is an encrypted electrum Seed
		if key.isEncElectrumSeed(testKey):
			self.MainLabel.text = 'It looks like you\'ve entered an encrypted Electrum Seed.\n\nEnter your Passphrase to decrypt it.'
			self.PrivKLabel.text = 'Encrypted\nElectrum Seed'
			self.PassLabel.text = 'Enter Passphrase'
			return

		#Test if its a BIP encrypted Key
		if key.isBip(testKey, self.selectedCurrency):
			self.MainLabel.text = 'It looks like you entered a BIP0038 encrypted Private Key.\n\nEnter your Passphrase to decrypt it.'
			self.PrivKLabel.text = 'Encrypted Key'
			self.PassLabel.text = 'Encryption\nPassphrase'
			return

		#Test if it's a Private key
		if key.isWif(testKey, self.selectedCurrency) or key.isHex(testKey) or key.isBase64(testKey) or key.isBase6(testKey):
			self.MainLabel.text = 'You\'ve entered a Private Key.\n\nEnter a Passphrase to encrypt it.'
			self.PrivKLabel.text = 'Private Key'
			self.PassLabel.text = 'Enter\nPassphrase'
			return

		#reset to standard if the box is empty
		if testKey == '':
			self.MainLabel.text = '[b]Welcome to bippy[/b]\n\nTo get started choose a currency and enter an encryption passphrase.\n\nIf you already have a private key you would like to encrypt or decrypt,\n\nenter it in the \'Private Key\' box below'
			self.PrivKLabel.text = 'Private Key\n(optional)'
			self.PassLabel.text = 'Passphrase'
			return

		#otherwise let the user know that they haven't entered a recognised Private Key
		self.MainLabel.text = 'bippy can\'t recognise what you entered as a private key.\n\nAcceptable formats are:\nCompressed WIF, HEX, Base64, Base6, BIP Encrypted'
		self.PrivKLabel.text = 'Private Key\n(optional)'
		self.PassLabel.text = 'Passphrase'
		return

	def checkPassword(self, instance, value=False):
		"""
			This is called whenever the password field looses focus
			perform checks and validation on the password field and initiate encryption/decryption if data is correct
		"""
		if value:
			return

		self.Password = instance.text

		if gen.verifyPassword(self.Password) is False:
			self.MainLabel.text = 'Passphrases must be 7 characters or longer'
			self.entropyImage.unbind(on_touch_move=self.draw)
			self.prog.value = 0
			self.entropyImage.canvas.remove_group('ellipses')
			return
		#need to have some sort of password length and complexity check here

		self.PrivateKey = self.PrivK.text

		#it could be a BIP key in which case we show the Decrypt button
		if key.isBip(self.PrivateKey, self.selectedCurrency):
			self.MainLabel.text = 'Hit the \'Decrypt\' button to start the decryption.'
			self.rightBox.remove_widget(self.prog)
			self.rightBox.add_widget(self.decButton)
			return

		#It could be an Electrum Seed in which case we show the Electrum encrypt button
		if key.isElectrumSeed(self.PrivateKey):
			self.MainLabel.text = 'Hit the \'Encrypt\' button to start the encryption of your Electrum Seed'
			self.rightBox.remove_widget(self.prog)
			self.rightBox.add_widget(self.encElectrumButton)
			return

		#It could be an encrypted Electrum seed in which case weshow the Electrum Decrypt button
		if key.isEncElectrumSeed(self.PrivateKey):
			self.MainLabel.text = 'Hit the \'Decrypt\' button to decrypt your Electrum Seed'
			self.rightBox.remove_widget(self.prog)
			self.rightBox.add_widget(self.decElectrumButton)
			return

		#otherwise check that the entry isn't a WIF, HEX B64 or B6 key
		#if there is no valid privatekey we ask for entropy to be entered
		#This then generates a new key pair
		if not key.isWif(self.PrivateKey, self.selectedCurrency) and not key.isHex(self.PrivateKey) and not key.isBase64(self.PrivateKey) and not key.isBase6(self.PrivateKey):
			self.PrivK.text = ''
			self.PrivateKey = None
			self.MainLabel.text = 'To generate a BIP0038 encrypted key you need to generate some randomness.\n\nHold your left mouse button down and move it about on the image to the right to do this and fill up the bar.'
			self.entropy = []
			self.entropyImage.bind(on_touch_move=self.draw)
			return

		#otherwise there is a user supplied private key so we offer to generate a BIP key
		self.MainLabel.text = 'Hit the \'Encrypt\' button to start the encryption of your private key'
		self.rightBox.remove_widget(self.prog)
		self.rightBox.add_widget(self.encButton)
		return

	def draw(self, instance, value):
		"""
			This function is enabled when only a password has been entered.
			It allows the user to draw on the image shown to the right of the UI
			This is the method by which entropy is gathered for generation of key pairs
		"""
		with self.entropyImage.canvas:
			Color(0, 0.86667, 1)
			d = 5.
			if self.entropyImage.collide_point(value.x, value.y):
				Ellipse(pos=(value.x - d / 2, value.y - d / 2), size=(d, d), group='ellipses')
				self.entropy.append((int(value.x),int(value.y)))
				self.prog.value += 1
		if self.prog.value == 550:
			self.entropyImage.unbind(on_touch_move=self.draw)
			self.prog.value = 0
			self.entropyImage.canvas.remove_group('ellipses')
			#got everything we need. replace the progress bar with a generate button
			self.rightBox.remove_widget(self.prog)
			self.rightBox.add_widget(self.encButton)
			self.MainLabel.text='You have generated enough Randomness.\n\nHit the \'Encrypt\' button to start the encryption.\n\n(bippy may become unresponsive for ~10 seconds while encryption takes place)'
		return

	def generateBIP(self, instance, value=False):
		"""
			Generate the BIP Private Key
		"""
		self.MainLabel.text='Starting BIP0038 Encryption'
		#use clock to delay the start of the encryption otherwise the message above is never shown
		Clock.schedule_once(self.genBIP, 0.5)
		return

	def genBIP(self, dt):
		"""
			This is the second part of the generate BIP method.
			It's split into two like this as otherwise the UI doesn't update to show that encryption has started
		"""
		if self.PrivateKey is None:
			BIP, Address = gen.genBIPKey(self.selectedCurrency, self.Password, self.entropy)
		else:
			BIP, Address = gen.encBIPKey(self.PrivateKey, self.selectedCurrency, self.Password)
		self.setBIP(BIP, Address)
		return

	def decryptBIP(self, instance, value=False):
		"""
			Decrypt the BIP key
		"""
		self.MainLabel.text='Starting BIP0038 Decryption'
		#use clock to delay the start of the encryption otherwise the message above is never shown
		Clock.schedule_once(self.decBIP, 0.5)
		return

	def decBIP(self, dt):
		"""
			Second part of the decryption routine to allow UI to update
		"""
		PrivateKey, PublicAddress = gen.decBIPKey(self.PrivateKey, self.Password, self.selectedCurrency)
		if PrivateKey is False:
			self.MainLabel.text = 'BIP0038 Decryption was unsuccessful.\n\nAre you sure the passphrase was correct?'
			self.rightBox.remove_widget(self.prog)
			self.rightBox.remove_widget(self.decButton)
			self.rightBox.add_widget(self.resetButton)
			return
		self.MainLabel.text = 'BIP0038 Decryption was successful.\n\nSee below for your private key and address.'
		self.PrivKLabel.text = 'Decrypted\nPrivate Key'
		self.PassLabel.text = 'Address'
		self.PasswordEnter.password = False
		self.PrivK.text = PrivateKey
		self.PasswordEnter.text = PublicAddress
		#unbind the private key and password entry boxes so that the user can copy out the key and address
		self.PrivK.unbind(focus=self.checkPrivK)
		self.PasswordEnter.unbind(focus=self.checkPassword)
		self.rightBox.remove_widget(self.prog)
		self.rightBox.remove_widget(self.decButton)
		self.rightBox.add_widget(self.resetButton)
		return

	def setBIP(self, BIP, Address):
		"""
			This method updates the UI with the output of encryption
		"""
		#re-shuffle the visible widgets so that the links become available
		self.leftBox.remove_widget(self.MainLabel)
		self.leftBox.remove_widget(self.entryPane)
		self.leftBox.add_widget(self.LinksTab)
		self.leftBox.add_widget(self.entryPane)
		self.PrivKLabel.text = 'BIP0038 Key'
		self.PassLabel.text = 'Address'
		self.DoubleLink.text = 'https://woodwallets.io/product/woodwallet-private-key-and-public-address?dbl_addr=' + Address + '&dbl_pvtkey=' + BIP + '&dbl_coin=' + self.selectedCurrency + '&orig=bippy'
		self.PrivateLink.text = 'https://woodwallets.io/product/one-side-private-key-only?pvt_pvtkey=' + BIP + '&pvt_coin=' + self.selectedCurrency + '&orig=bippy'
		self.PublicLink.text = 'https://woodwallets.io/product/woodwallet-public-address?pub_addr=' + Address + '&pub_coin=' + self.selectedCurrency + '&orig=bippy'

		self.PasswordEnter.password = False
		self.PrivK.text = BIP
		self.PasswordEnter.text = Address
		#unbind the private key and password enty boxes so that the user can copy out the key and address
		self.PrivK.unbind(focus=self.checkPrivK)
		self.PasswordEnter.unbind(focus=self.checkPassword)
		self.rightBox.remove_widget(self.prog)
		self.rightBox.remove_widget(self.encButton)
		self.rightBox.add_widget(self.resetButton)
		return

	def resetUI(self, instance, value=False):
		"""
			This is called when the reset button is pressed.
			The UI is restored to its initial state
		"""
		self.leftBox.remove_widget(self.LinksTab)
		self.leftBox.remove_widget(self.MainLabel)
		self.leftBox.remove_widget(self.entryPane)
		self.leftBox.add_widget(self.MainLabel)
		self.leftBox.add_widget(self.entryPane)
		self.MainLabel.text='[b]Welcome to bippy[/b]\n\nTo get started choose a currency and enter an encryption passphrase.\n\nIf you already have a private key you would like to encrypt or decrypt,\n\nenter it in the \'Private Key\' box below'
		self.PrivKLabel.text='Private Key\n(optional)'
		self.PrivK.text = ''
		self.PassLabel.text='Passphrase'
		self.PasswordEnter.password = True
		self.PasswordEnter.text = ''
		#rebind the private key and password entry boxes
		self.PrivK.bind(focus=self.checkPrivK)
		self.PasswordEnter.bind(focus=self.checkPassword)
		self.rightBox.remove_widget(self.resetButton)
		self.rightBox.remove_widget(self.encButton)
		self.rightBox.remove_widget(self.decButton)
		self.rightBox.add_widget(self.prog)
		return

	def encryptElectrum(self, instance, value=False):
		"""
			Encrypt the Electrum Seed
		"""
		self.MainLabel.text='Starting Encryption of Electrum Seed'
		#use clock to delay the start of the encryption otherwise the message above is never shown
		self.PrivK.text = ''
		Clock.schedule_once(self.encElectrum, 0.5)
		return

	def encElectrum(self, dt):
		"""
			Begin encryption of the supplied Electrum Seed
		"""
		encryptedSeed = electrum.encrypt(self.PrivateKey, self.Password)
		self.MainLabel.text = 'Encryption was successful.\n\nSee below for your encrypted seed'
		self.PrivKLabel.text = 'Encrypted\nElectrum Seed'
		self.PassLabel.text = ''
		self.PrivK.text = encryptedSeed
		self.PasswordEnter.text = ''
		#unbind the private key and password entry boxes so that the user can copy out the key and address
		self.PrivK.unbind(focus=self.checkPrivK)
		self.PasswordEnter.unbind(focus=self.checkPassword)
		self.rightBox.remove_widget(self.prog)
		self.rightBox.remove_widget(self.encElectrumButton)
		self.rightBox.add_widget(self.resetButton)
		return

	def decryptElectrum(self, instance, value=False):
		"""
			Start the decryption of the Electrum Seed
		"""
		self.MainLabel.text='Starting the Decryption of your Electrum seed'
		#use clock to delay the start of the decryption otherwise the message above is never shown
		self.PrivK.text = ''
		self.PasswordEnter.text = ''
		Clock.schedule_once(self.decElectrum, 0.5)
		return

	def decElectrum(self, dt):
		"""
			Perform the actual decryption of the Electrum Seed
		"""
		decryptedSeed = electrum.decrypt(self.PrivateKey, self.Password)
		if decryptedSeed is False:
			self.MainLabel.text = 'Decryption was not successful.\n\nAre you sure you entered the correct passphrase?\n\nReset to try again'
			self.rightBox.remove_widget(self.prog)
			self.rightBox.remove_widget(self.decElectrumButton)
			self.rightBox.add_widget(self.resetButton)
			return
		self.MainLabel.text = 'Decryption was successful.\n\nSee below for your Electrum Seed.'
		self.PrivKLabel.text = 'Decrypted\nElectrum Seed'
		self.PassLabel.text = ''
		self.PasswordEnter.password = False
		self.PrivK.text = decryptedSeed
		self.PasswordEnter.text = ''
		#unbind the private key and password entry boxes so that the user can copy out the key and address
		self.PrivK.unbind(focus=self.checkPrivK)
		self.PasswordEnter.unbind(focus=self.checkPassword)
		self.rightBox.remove_widget(self.prog)
		self.rightBox.remove_widget(self.decElectrumButton)
		self.rightBox.add_widget(self.resetButton)
		return

	def build(self):
		"""
			Build the UI
		"""

		#root layout is a horizontal box layout
		self.root = BoxLayout(spacing=10, padding=[5,5,5,5])

		#the right box has another BoxLayout.
		self.rightBox = BoxLayout(orientation='vertical', size_hint=(.25, 1))

		#the image goes in the top part
		self.entropyImage = AsyncImage(source='woodFORbippy.png', size_hint=(1, .9), allow_stretch=True, keep_ratio=True)
		self.rightBox.add_widget(self.entropyImage)
		#the progress bar in the bottom
		self.prog = ProgressBar(max=550, size_hint=(.9,.1), pos_hint={'right':.95})
		self.rightBox.add_widget(self.prog)
		#the encrypt button.
		#this isn't added to the UI until Entropy has been collected
		#the first version is for BIP 38 keys. The second is for Electrum Seeds
		self.encButton = Button(text='Encrypt', size_hint=(.9,.1), pos_hint={'right':.95})
		self.encButton.bind(on_press=self.generateBIP)
		self.encElectrumButton = Button(text='Encrypt', size_hint=(.9,.1), pos_hint={'right':.95})
		self.encElectrumButton.bind(on_press=self.encryptElectrum)
		#the decrypt button.
		#this isn't added to the UI until decryption possibilities have been noticed
		self.decButton = Button(text='Decrypt', size_hint=(.9,.1), pos_hint={'right':.95})
		self.decButton.bind(on_press=self.decryptBIP)
		self.decElectrumButton = Button(text='Decrypt', size_hint=(.9,.1), pos_hint={'right':.95})
		self.decElectrumButton.bind(on_press=self.decryptElectrum)
		#the reset button.
		#this isn't added to the UI until Encryption has taken place
		self.resetButton = Button(text='Reset', size_hint=(.9,.1), pos_hint={'right':.95})
		self.resetButton.bind(on_press=self.resetUI)

		#within the left hand box we split into a vertical box layout
		self.leftBox = BoxLayout(orientation='vertical', size_hint=(.7,1))

		#the top of the left hand box is a label
		self.MainLabel = Label(text_size=(720,150), font_size=15, shorten=True, halign='center', valign='middle', markup=True, text='[b]Welcome to bippy[/b]\n\nTo get started choose a currency and enter an encryption passphrase.\n\nIf you already have a private key you would like to encrypt or decrypt,\n\nenter it in the \'Private Key\' box below', size_hint=(1, .4))
		self.leftBox.add_widget(self.MainLabel)

		#for displaying the links we have an accordion layout
		#build it here even though it is only attached after encryption has taken place
		self.LinksTab = Accordion(size_hint=(1, .4))
		self.Links = AccordionItem(title='Links', )
		self.LinksGrid = GridLayout(cols=2, padding=(10, 10, 10, 10), spacing=(10, 20))
		self.LinksGrid.add_widget(Label(text='Double Sided', font_size=11, size_hint=(.3,1), text_size=(100,50), halign='center', valign='middle'))
		self.DoubleLink = TextInput(multiline=False, size_hint_y=None, height=30)
		self.LinksGrid.add_widget(self.DoubleLink)
		self.LinksGrid.add_widget(Label(text='Single Sided Private Key', font_size=11, size_hint=(.3,1), text_size=(100,50), halign='center', valign='middle'))
		self.PrivateLink = TextInput(multiline=False, size_hint_y=None, height=30)
		self.LinksGrid.add_widget(self.PrivateLink)
		self.LinksGrid.add_widget(Label(text='Single Sided Public Address', font_size=11, size_hint=(.3,1), text_size=(100,50), halign='center', valign='middle'))
		self.PublicLink = TextInput(multiline=False, size_hint_y=None, height=30)
		self.LinksGrid.add_widget(self.PublicLink)
		self.Links.add_widget(self.LinksGrid)
		self.Message = AccordionItem(title='Complete', )
		self.MessageLabel = Label(halign='center', valign='middle', text='BIP0038 encryption is complete\n\nSee below for your encrypted private key and address\n\nSee the \'Links\' tab to the left for direct links to purchase Wood Wallets')
		self.Message.add_widget(self.MessageLabel)
		#add the two 'tabs' to the main accordion widget
		self.LinksTab.add_widget(self.Links)
		self.LinksTab.add_widget(self.Message)

		#the bottom of the left hand pane is a grid layout
		self.entryPane = GridLayout(cols=2, size_hint=(1, .6), padding=(10, 40, 10, 40), spacing=(10, 40))
		#within this pane we have the Text Input boxes and labels
		#Currency
		self.entryPane.add_widget(Label(text='Currency', size_hint_x=None, width=100))
		self.Currency = Spinner(text='Bitcoin', values=currencyLongNamesList, size_hint_x=None, size_hint_y=None, height=40, width=50)
		self.Currency.bind(text=self.getCur)
		self.selectedCurrency = 'BTC'
		self.selectedCurrencyLongName = 'Bitcoin'
		self.entryPane.add_widget(self.Currency)
		#Private Key
		self.PrivKLabel = Label(text='Private Key\n(optional)', size_hint_x=None, width=100)
		self.entryPane.add_widget(self.PrivKLabel)
		self.PrivK = TextInput(size_hint_y=None, height=30, multiline=False)
		self.PrivK.bind(focus=self.checkPrivK)
		self.entryPane.add_widget(self.PrivK)
		#Password
		self.PassLabel = Label(text='Passphrase', size_hint_x=None, width=100)
		self.entryPane.add_widget(self.PassLabel)
		self.PasswordEnter = TextInput(size_hint_y=None, height=30, multiline=False, password=True)
		self.PasswordEnter.bind(focus=self.checkPassword)
		self.entryPane.add_widget(self.PasswordEnter)

		#add the entry pane to the left box
		self.leftBox.add_widget(self.entryPane)
		#add the left box to the root widget
		self.root.add_widget(self.leftBox)
		#add the rightbox to the root widget
		self.root.add_widget(self.rightBox)

		return self.root
Exemplo n.º 28
0
    def build(self):

        ## main and data settings layout
        btn_run = Button(text='Run',
                         on_press=partial(self.async_train, self.canvas,
                                          self.output))

        self.spinner_func.bind(text=self.set_func)
        self.draw_base_func()

        slider_layout_points = BoxLayout(orientation='vertical')
        slider_points = Slider(min=5,
                               max=200,
                               value=50,
                               step=1,
                               value_track=True,
                               id='points')
        slider_points.bind(value=self.OnSliderValueChange)

        slider_layout_points.add_widget(slider_points)
        slider_layout_points.add_widget(self.label_points)

        slider_layout_noise = BoxLayout(orientation='vertical')
        slider_noise = Slider(min=0,
                              max=10,
                              value=3,
                              step=0.1,
                              value_track=True,
                              id='noise')
        slider_noise.bind(value=self.OnSliderValueChange)

        slider_layout_noise.add_widget(slider_noise)
        slider_layout_noise.add_widget(self.label_noise)

        self.output.readonly = True
        self.output.text += "Press 'Run' to train the Neural Network\nLOG:\n"

        ## Neural network settings layout

        spinner_activation = Spinner(text='ELU',
                                     values=('ELU', 'Sigmoid', 'Softplus',
                                             'Tanh'),
                                     id='activ')
        spinner_out_activation = Spinner(text='Linear',
                                         values=('ELU', 'Linear', 'Sigmoid',
                                                 'Softplus', 'Tanh'),
                                         id='out_activ')
        spinner_activation.bind(text=self.set_activation)
        spinner_out_activation.bind(text=self.set_activation)

        slider_layout_epochs = BoxLayout(orientation='vertical')
        slider_epochs = Slider(min=1000,
                               max=50000,
                               value=self.EPOCHS,
                               step=200,
                               value_track=True,
                               id='epochs')
        slider_epochs.bind(value=self.OnSliderValueChange)
        slider_layout_epochs.add_widget(slider_epochs)
        slider_layout_epochs.add_widget(self.label_epochs)

        slider_layout_learning = BoxLayout(orientation='vertical')
        slider_learning = Slider(min=0.0001,
                                 max=0.01,
                                 value=self.LEARNING_RATE,
                                 step=0.0001,
                                 value_track=True,
                                 id='learning_rate')
        slider_learning.bind(value=self.OnSliderValueChange)
        slider_layout_learning.add_widget(slider_learning)
        slider_layout_learning.add_widget(self.label_learning)

        slider_layout_lambda = BoxLayout(orientation='vertical')
        slider_lambda = Slider(min=0.0,
                               max=0.5,
                               value=self.LAMBDA,
                               step=0.0001,
                               value_track=True,
                               id='lambda')
        slider_lambda.bind(value=self.OnSliderValueChange)
        slider_layout_lambda.add_widget(slider_lambda)
        slider_layout_lambda.add_widget(self.label_lambda)

        ## all layouts added to root lyout

        layout = BoxLayout(size_hint=(1, 0.25))
        layout.add_widget(self.nn_shape)
        layout.add_widget(self.spinner_func)
        layout.add_widget(slider_layout_points)
        layout.add_widget(slider_layout_noise)
        layout.add_widget(btn_run)

        layout_nn = BoxLayout(size_hint=(1, 0.25))

        layout_nn.add_widget(spinner_activation)
        layout_nn.add_widget(spinner_out_activation)
        layout_nn.add_widget(slider_layout_epochs)
        layout_nn.add_widget(slider_layout_learning)
        layout_nn.add_widget(slider_layout_lambda)

        root = BoxLayout(orientation='vertical')
        root.add_widget(self.canvas)
        root.add_widget(layout)
        root.add_widget(layout_nn)
        root.add_widget(self.output)

        return root
Exemplo n.º 29
0
class SettingsSlot(GridLayout):

    logic = ObjectProperty(None)
    label = ObjectProperty(None)
    changer = ObjectProperty(None)
    value = ObjectProperty(None)

    def __init__(self, **kwargs):
        # XXX: strange super() behaviour here!
        # super().__init__()
        GridLayout.__init__(self)
        self.setting_value = kwargs.get('setting_value')
        self.setting_min = kwargs.get('setting_min')
        self.setting_max = kwargs.get('setting_max')
        self.setting_type = kwargs.get('setting_type')
        self.label_text = kwargs.get('label_text')
        self.items = kwargs.get('items', [])
        self.size_hint = kwargs.get('size_hint', (1, None))
        self.rows = 1

        self.build_interface()

    def on_value(self, instance, value):

        if self.setting_type == 'number':
            self.changer.value = value
        elif self.setting_type == 'bool':
            self.changer.pressed = value
            if not value:
                self.changer.source = self.changer.realtexture
                self.changer.reload()
            else:
                self.changer.source = self.changer.realtexture_pressed
                self.changer.reload()
        elif self.setting_type == 'select':
            self.changer.text = value

    def build_interface(self):
        self.label = Label(
            text=self.label_text,
            text_size=(self.width * 4, None),
            halign='left',
            valign='middle'
        )

        if self.setting_type == 'number':
            self.changer = Slider(
                min=self.setting_min,
                max=self.setting_max,
                value=self.setting_value
            )
            self.changer.bind(value=self.change_value)
        elif self.setting_type == 'bool':
            self.changer = RealToggleButton(
                './media/icons/delete.png',
                './media/icons/check.png',
                self.change_value,
                source='./media/icons/delete.png',
                always_release=True
            )
        elif self.setting_type == 'select':
            self.changer = Spinner(
                text='Something',
                values=self.items
            )
            self.changer.bind(text=self.change_value)

        self.add_widget(self.label)
        self.add_widget(self.changer)

    def change_value(self, instance, value=0):
        if self.setting_type == 'number':
            self.value = value
        elif self.setting_type == 'bool':
            self.value = instance  # not self.changer.pressed
        elif self.setting_type == 'select':
            self.value = value
            self.changer.text = value
Exemplo n.º 30
0
    def constructVideoScreen(self, videoScreenLayout):
        changeToMainButton = Button(text="Go back to main",
                                    size_hint=(.5, .9),
                                    pos_hint={
                                        'center_x': .5,
                                        'center_y': 0.7
                                    })
        changeToMainButton.bind(on_press=MainApp.changeToMainScreenFromVideo)

        firstButtonLayout = BoxLayout(orientation='vertical',
                                      size_hint=(.4, .6),
                                      pos_hint={
                                          'center_x': 0.1,
                                          'center_y': 0.6
                                      })

        secondButtonLayout = BoxLayout(orientation='vertical',
                                       size_hint=(.4, .6),
                                       pos_hint={
                                           'center_x': 0.1,
                                           'center_y': 0.6
                                       })

        blurSliderLabel = Label(text='blur slider')
        blurSlider = Slider(min=0, max=255, value=Settings["blur"], step=1)
        blurSlider.bind(value=MainApp.onVideoBlurSliderValueChange)

        firstButtonLayout.add_widget(changeToMainButton)

        firstButtonLayout.add_widget(blurSliderLabel)
        firstButtonLayout.add_widget(blurSlider)

        erodeSliderLabel = Label(text='erode slider')
        erodeSlider = Slider(min=0, max=255, value=Settings["erode"], step=1)
        erodeSlider.bind(value=MainApp.onVideoErodeSliderValueChange)

        firstButtonLayout.add_widget(erodeSliderLabel)
        firstButtonLayout.add_widget(erodeSlider)

        dilateSliderLabel = Label(text='dilate slider')
        dilateSlider = Slider(min=0, max=255, value=Settings["dilate"], step=1)
        dilateSlider.bind(value=MainApp.onVideoDilateSliderValueChange)

        firstButtonLayout.add_widget(dilateSliderLabel)
        firstButtonLayout.add_widget(dilateSlider)

        spinner = Spinner(
            # default value shown
            text='Choose color',
            # available values
            values=('Skin', 'Red', 'Orange', 'Black'),
            # just for positioning in our example
            size_hint=(None, None),
            size=(100, 44),
            pos_hint={
                'center_x': .5,
                'center_y': .5
            })

        def changeHSVToGivenText(spinner, text):
            if text == "Skin":
                writeHSVToSettings(20, 255, 255, 0, 48, 80)
            if text == "Red":
                writeHSVToSettings(10, 255, 255, 0, 50, 50)
            if text == "Orange":
                writeHSVToSettings(15, 255, 255, 5, 50, 50)
            if text == "Black":
                writeHSVToSettings(180, 255, 35, 0, 0, 0)

        def writeHSVToSettings(u, ups, upv, l, ds, dv):
            Settings["upper"] = u
            pickle.dump(Settings, open(".config", "w"))
            Settings["filterUpS"] = ups
            pickle.dump(Settings, open(".config", "w"))
            Settings["filterUpV"] = upv
            pickle.dump(Settings, open(".config", "w"))
            Settings["lower"] = l
            pickle.dump(Settings, open(".config", "w"))
            Settings["filterDownS"] = ds
            pickle.dump(Settings, open(".config", "w"))
            Settings["filterDownV"] = dv
            pickle.dump(Settings, open(".config", "w"))

        spinner.bind(text=changeHSVToGivenText)

        firstButtonLayout.add_widget(spinner)

        checkBoxMouseLabel = Label(text='Mouse on', value=Settings["mouseOn"])
        checkBoxMouse = CheckBox()
        checkBoxMouse.bind(active=MainApp.onVideoMouseSwitchValueChange)

        firstButtonLayout.add_widget(checkBoxMouseLabel)
        firstButtonLayout.add_widget(checkBoxMouse)

        checkBoxMusicLabel = Label(text='Music control on',
                                   value=Settings["controlMusic"])
        checkBoxMusic = CheckBox()
        checkBoxMusic.bind(active=MainApp.onVideoControlMusicSwitchValueChange)

        firstButtonLayout.add_widget(checkBoxMusicLabel)
        firstButtonLayout.add_widget(checkBoxMusic)

        checkBoxWorkspaceLabel = Label(text='Control workspace',
                                       value=Settings["switchWorkspace"])
        checkBoxWorkspace = CheckBox()
        checkBoxWorkspace.bind(
            active=MainApp.onVideoControlWorkspaceSwitchValueChange)

        firstButtonLayout.add_widget(checkBoxWorkspaceLabel)
        firstButtonLayout.add_widget(checkBoxWorkspace)

        checkBoxMouseActionLabel = Label(text='Control mouse action',
                                         value=Settings["actionMouse"])
        checkBoxMouseAction = CheckBox()
        checkBoxMouseAction.bind(
            active=MainApp.onVideoControlMouseActionSwitchValueChange)

        firstButtonLayout.add_widget(checkBoxMouseActionLabel)
        firstButtonLayout.add_widget(checkBoxMouseAction)

        upperHueSliderLabel = Label(text='upper hue slider')
        upperHueSlider = Slider(min=0,
                                max=180,
                                value=Settings["upper"],
                                step=1)
        upperHueSlider.bind(value=MainApp.onVideoUpperHueChange)
        secondButtonLayout.add_widget(upperHueSliderLabel)
        secondButtonLayout.add_widget(upperHueSlider)

        upperSaturationSliderLabel = Label(text='upper saturation slider')
        upperSaturationSlider = Slider(min=0,
                                       max=255,
                                       value=Settings["filterUpS"],
                                       step=1)
        upperSaturationSlider.bind(value=MainApp.onVideoUpperSaturationChange)
        secondButtonLayout.add_widget(upperSaturationSliderLabel)
        secondButtonLayout.add_widget(upperSaturationSlider)

        upperValueSliderLabel = Label(text='upper value slider')
        upperValueSlider = Slider(min=0,
                                  max=255,
                                  value=Settings["filterUpV"],
                                  step=1)
        upperValueSlider.bind(value=MainApp.onVideoUpperValueChange)
        secondButtonLayout.add_widget(upperValueSliderLabel)
        secondButtonLayout.add_widget(upperValueSlider)

        downHueSliderLabel = Label(text='down hue slider')
        downHueSlider = Slider(min=0, max=180, value=Settings["lower"], step=1)
        downHueSlider.bind(value=MainApp.onVideoDownHueChange)
        secondButtonLayout.add_widget(downHueSliderLabel)
        secondButtonLayout.add_widget(downHueSlider)

        downSaturationSliderLabel = Label(text='down saturation slider')
        downSaturationSlider = Slider(min=0,
                                      max=255,
                                      value=Settings["filterDownS"],
                                      step=1)
        downSaturationSlider.bind(value=MainApp.onVideoDownSaturationChange)
        secondButtonLayout.add_widget(downSaturationSliderLabel)
        secondButtonLayout.add_widget(downSaturationSlider)

        downValueSliderLabel = Label(text='down value slider')
        downValueSlider = Slider(min=0,
                                 max=255,
                                 value=Settings["filterDownV"],
                                 step=1)
        downValueSlider.bind(value=MainApp.onVideoDownValueChange)
        secondButtonLayout.add_widget(downValueSliderLabel)
        secondButtonLayout.add_widget(downValueSlider)

        videoScreenLayout.add_widget(firstButtonLayout)
        videoScreenLayout.add_widget(secondButtonLayout)
Exemplo n.º 31
0
class MainLayout(GridLayout):
    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)  
        self.command_stack = []
        self.cols = 2
        self.orientation = "vertical"
        self.padding = 10
        self.y_pos= .8
       
        self.left_layout = GridLayout(cols=1,  pos=(5,-10))      

        self.spinner = Spinner( text = 'Menu', values =('New', 'Save', 'Clear Message Box','Exit'), size_hint =(None, None), size=(200,44), pos_hint={'x':.1, 'y':.9})
        self.left_layout.add_widget(self.spinner)

        self.let_button = Button(text="LET", size_hint =(None, None), size=(200,44),pos_hint={'x':.1, 'y':.7})
        self.left_layout.add_widget(self.let_button)
        
        self.print_button = Button(text="PRINT", size_hint =(None, None), size=(200,44),pos_hint={'x':.1, 'y':.6})
        self.left_layout.add_widget(self.print_button) 

        self.run_button = Button(text="RUN", size_hint =(None, None), size=(200,44),pos_hint={'x':.1, 'y':.6})
        self.left_layout.add_widget(self.run_button)
         
        self.add_widget(self.left_layout)

        self.orientation = "horizontal"

        self.grid_layout = GridLayout(cols=1,  padding=10, spacing=10, size_hint=(None, None), width=500)
        self.grid_layout.bind(minimum_height=self.grid_layout.setter('height'))
        self.right_layout = ScrollView(size_hint=(None, None),size=(500, 380), pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False, do_scroll_y=True)
        self.add_widget(self.right_layout)
        
       
        self.right_layout.add_widget(self.grid_layout)
        
        #self.right_layout = FloatLayout(pos=(200, -10) ,  size_hint=(.5,1))
        #self.right_layout = GridLayout(cols=1, pos=(300,-10))  
        #self.add_widget(self.right_layout)

        self.bottom_layout = GridLayout()
        self.comment = TextInput(text='Output is shown here..', width= 800, height=200)    
        
        self.bottom_layout.add_widget(self.comment)
        #self.bottom_layout.add_widget(TextInput())
        
        self.add_widget(self.bottom_layout)       
        
        self.let_button.bind(on_press =self.add_let)
        self.print_button.bind(on_press = self.add_print)
        self.spinner.bind(text = self.new_program_option)
        self.run_button.bind(on_press = self.run_app)
   

    def new_program_option(self, instance, option):
        if option == 'New':
             self.new_program()
             self.spinner.text = 'Menu'
             self.command_stack=[]
        elif option == 'Exit':
            sys.exit()
        elif option == 'Clear Message Box':
            self.spinner.text = 'Menu'
            self.comment.text=""

    def new_program(self):
        self.grid_layout.clear_widgets() # clear just the widgets inside the grid layout
        self.y_pos = .8

    def add_let(self, instance):
        line = len(self.command_stack) + 1
        command = LetLayout(line,size_hint=(None, None),  pos_hint={'x':.2,'y':self.y_pos})
        self.grid_layout.add_widget(command)
        self.y_pos -= .1
        self.command_stack.append(command)

    def add_print(self, instance):
        line = len(self.command_stack) + 1
        command = PrintLayout(line, size_hint=(None, None),  pos_hint={ 'x':.2,'y':self.y_pos})
        self.grid_layout.add_widget(command)
        self.y_pos -= .1
        self.command_stack.append(command)


    def run_app(self, instance):
        i = Interpreter()
        line_number = 1
        for cmd in self.command_stack:
            line = cmd.get_command()
            i.add_line(line_number, line)
            line_number = line_number + 1

        i.run()
        output = i.get_output()
        variables = i.get_variables()

        self.comment.text = ""
        self.comment.insert_text('\n Output : \n')
        for value in output:
            self.comment.insert_text(' ' + str(value)+ '\n')

        self.comment.insert_text('\n Memory: \n')
        self.comment.insert_text(' Variable \t Value \n')
        for var in variables.keys():
            value = ' \t' + var + ' \t\t\t ' + str(variables[var]) + '\n'
            self.comment.insert_text(' ' + str(value))



    def get_command_stack(self):
        return self.command_stack
Exemplo n.º 32
0
    def show_first_form(self):
        global STORAGE

        ip_tab = []
        if netifaces:
            interfaces = netifaces.interfaces()
            for interface in interfaces:
                if interface[:2] in ('wl', 'en', 'et'):
                    ifaddress = netifaces.ifaddresses(interface)
                    if netifaces.AF_INET in ifaddress:
                        inets = ifaddress[netifaces.AF_INET]
                        for inet in inets:
                            if 'addr' in inet:
                                addr = inet['addr']
                                if len(addr.split('.')) == 4:
                                    ip_tab.append(addr)
        else:
            try:
                ip_address = get_ip_address(b'wlan0')
                ip_tab.append(ip_address)
            except:
                pass

        if ip_tab:
            ip_address = ', '.join(ip_tab)
        else:
            ip_address = '-'

        label = Label(text=f"[size=18sp][color=88f][b]PYTIGON - select the application:[/b][/color][/size]\n[size=15sp][color=448](my ip addresses: {ip_address})[/b][/color][/size]",
                      markup=True, halign = 'center')
        self.add_widget(label)

        if not check_permission(Permission.WRITE_EXTERNAL_STORAGE):
            ret = request_permissions(PERMISSION)
            print("python::pytigon::request_permissions", ret)

        init("_schall", schserw_settings.ROOT_PATH, schserw_settings.DATA_PATH, schserw_settings.PRJ_PATH,
             schserw_settings.STATIC_APP_ROOT, [schserw_settings.MEDIA_ROOT, schserw_settings.UPLOAD_PATH])

        base_apps_path = os.path.join(os.path.join(STORAGE, "pytigon"), "prj")
        l = [pos for pos in os.listdir(base_apps_path) if not pos.startswith('_')]
        apps = []
        for prj in l:
            base_apps_path2 = os.path.join(base_apps_path, prj)
            try:
                x = __import__(prj + ".apps")
                if hasattr(x.apps, 'PUBLIC') and x.apps.PUBLIC:
                    apps.append(prj)
            except:
                print("Error importing module: ", prj + ".apps")

        if len(apps) > 1:
            if len(apps) > MAX_SEL_APP:
                dy = MAX_SEL_APP - 1
            else:
                dy = len(apps)

            for pos in apps[:dy]:
                button = Button(id=pos, text=pos, size_hint=(1, 1))
                button.bind(on_release=self.chose_callback)
                self.add_widget(button)

            if len(apps) > MAX_SEL_APP:
                spinner = Spinner(
                    text='Other applications',
                    values=apps[dy:],
                    size_hint=(.5, 1),
                    pos_hint={'center_x': 0.5, }
                )
                spinner.bind(text=self.spinner_callback)
                self.add_widget(spinner)
        else:
            if len(apps) > 0:
                self.on_app_chosen(apps[0])
            else:
                self.on_app_chosen()
Exemplo n.º 33
0
            post_response = api_requests.add_sensor(url_text.text, login_text.text, pass_text.text, type_id, type_name, device_name, device_id)

            if checkbox.active is True:
                added_device_id = api_requests.get_device_id(url_text.text, login_text.text, pass_text.text, post_response[3])
                print(post_response[3], added_device_id)
                add_to_hub_resp = api_requests.add_to_hub(url_text.text, login_text.text, pass_text.text, hub_id, added_device_id)
                textbox.text = "SENT QUERY: \n" + str(post_response[0]) + "\nSERVER REPLY: " + str(post_response[1]) + "\nADD TO PORTAL: "\
                               + str(post_response[2]) + "\nADDED TO HUB: " + str(add_to_hub_resp)
            else:
                textbox.text = "SENT QUERY: \n" + str(post_response[0]) + "\nSERVER REPLY: " + str(post_response[1]) + "\nADD TO PORTAL: "\
                               + str(post_response[2])

# ACTIONS

button1.bind(on_press=get_types_pressed)
button2.bind(on_press=add_device_action)
type_spinner.bind(text=spinner_clicked)


# MAIN CLASS

class IoTHelperApp(App):
    def build(self):
        return layout

# BASE PROGRAM

if __name__ == "__main__":
    IoTHelperApp().run()
Exemplo n.º 34
0
class SettingStringExchange(SettingString):
    """
    Overrides the SettingString class to provide a customised popup suitable for exchange data input
    """

    num_rows = 0
    exchange = None
    chosen_api_key_pair = None
    ask_max = None
    bid_max = None
    utils = utils.utils('')
    keys_button = []
    address = []
    unit = []
    rates = []
    bot = []
    logger = logging.getLogger('Plunge')
    currencies = ['btc', 'ltc', 'eur', 'usd', 'ppc']
    bots = ['nubot', 'pybot', 'none']
    config = ConfigParser()

    def on_panel(self, instance, value):
        if value is None:
            return
        self.bind(on_release=self._create_popup)

    def _dismiss(self, *largs):
        if self.textinput:
            self.textinput.focus = False
        if self.popup:
            self.popup.dismiss()
        self.popup = None
        self.num_rows = 0
        self.keys_button = []
        self.address = []
        self.unit = []
        self.rates = []
        self.bot = []

    def _validate(self, instance):
        with open('user_data.json', 'a+') as user_data:
            try:
                saved_data = json.load(user_data)
            except ValueError:
                saved_data = {}
        user_data.close()
        saved_data[self.exchange] = []
        good_records = 0
        content = TextInput(multiline=True, text='Saving...', background_color=[0.13725, 0.12157, 0.12549, 0],
                            foreground_color=[1, 1, 1, 1])
        popup = Popup(title='Saving Data for %s' % self.exchange, content=content,
                      size_hint=(None, None), size=(300, 500))
        popup.open()
        for x in range(0, self.num_rows, 1):
            self.logger.info("saving row %d for %s" % (x+1, self.exchange))
            content.text = '%s\nSaving row %d' % (content.text, x+1)
            this_row = {}
            public, secret = self.get_keys(self.keys_button[x].text)
            if public is None or secret is None:
                self.logger.warn("API Keys not set correctly")
                content.text = '%s\n=> API Keys not set correctly' % content.text
                continue
            this_row['public'] = public
            this_row['secret'] = secret
            this_row['address'] = self.address[x].text
            if not self.utils.check_checksum(this_row['address']) or not this_row['address'][:1] == 'B':
                self.logger.warn("Invalid payout address %s" % this_row['address'])
                content.text = '%s\n=> Invalid payout address' % content.text
                continue
            this_row['unit'] = self.unit[x].text
            rates = self.rates[x].text
            if "|" not in rates:
                self.logger.warn("no rates set")
                content.text = '%s\n=> No rates set' % content.text
                continue
            rate = rates.split(' | ')
            this_row['ask'] = rate[0]
            this_row['bid'] = rate[1]
            if this_row['ask'] == 0.00:
                this_row['ask'] = self.ask_max
            if this_row['bid'] == 0.00:
                this_row['bid'] = self.bid_max
            this_row['bot'] = self.bot[x].text
            if this_row in saved_data[self.exchange]:
                self.logger.warn("data already exists")
                content.text = '%s\n=> Data already exists' % content.text
                continue
            saved_data[self.exchange].append(this_row)
            good_records += 1
            content.text = '%s\nRow %d saved' % (content.text, x+1)
            self.logger.info(str(this_row))
        with open('user_data.json', 'w') as user_data:
            user_data.write(json.dumps(saved_data))
        user_data.close()
        content.text = '%s\nData Saved' % content.text
        self._dismiss()
        value = str(good_records)
        self.value = value

    def _create_popup(self, instance):
        """
        Create the main Exchange popup to which new rows can be added
        :param instance:
        :return:
        """
        self.exchange = self.key
        main_layout = BoxLayout(orientation='vertical', spacing='5dp')
        scroll_view = ScrollView(do_scroll_x=False)
        header = GridLayout(cols=5, spacing='5dp', row_default_height='50dp', row_force_default=True,
                            size_hint_y=None, height='50dp')
        header.add_widget(Label(text='API', valign='top', size_hint_x=0.2))
        header.add_widget(Label(text='NBT', valign='top', size_hint_x=0.2))
        header.add_widget(Label(text='Cur', valign='top', size_hint_x=0.2))
        header.add_widget(Label(text='rates', valign='top', size_hint_x=0.2))
        header.add_widget(Label(text='Bot', valign='top', size_hint_x=0.2))
        self.content = GridLayout(cols=5, spacing='5dp', row_default_height='50dp', row_force_default=True,
                                  size_hint_x=1, size_hint_y=None)
        self.content.bind(minimum_height=self.content.setter('height'))
        main_layout.add_widget(header)
        scroll_view.add_widget(self.content)
        main_layout.add_widget(scroll_view)
        self.popup = popup = Popup(
            title=self.title, content=main_layout)

        # construct the content, widget are used as a spacer
        main_layout.add_widget(SettingSpacer())

        # buttons are created for accept or cancel the current value
        btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
        btn = Button(text='Ok')
        btn.bind(on_release=self._validate)
        btnlayout.add_widget(btn)
        btn = Button(text='Cancel')
        btn.bind(on_release=self._dismiss)
        btnlayout.add_widget(btn)
        btn = Button(text='Add Row')
        btn.bind(on_release=self.add_row)
        btnlayout.add_widget(btn)
        main_layout.add_widget(btnlayout)

        self.load_data()

        # all done, open the popup !
        popup.open()

    def load_data(self):
        with open('user_data.json', 'a+') as data_file:
            try:
                data = json.load(data_file)
            except ValueError:
                data = {}
        data_file.close()
        if self.exchange not in data:
            self.add_row(None)
            return
        if len(data[self.exchange]) == 0:
            self.add_row(None)
            return
        for datum in data[self.exchange]:
            self.add_row(datum)

    def add_row(self, instance):
        """
        Add a row to the main exchange screen
        :param instance:
        :return:
        """
        self.num_rows += 1
        keys_button = Button(text='Keys', size_hint_x=0.2, id='%d' % self.num_rows)
        keys_button.bind(on_release=self.enter_keys)
        self.content.add_widget(keys_button)
        self.keys_button.append(keys_button)
        address = TextInput(size_hint_x=0.2, padding=[6, 10, 6, 10],
                            multiline=False, font_size=18, id='%d' % self.num_rows)
        address.bind(text=self.check_address)
        self.content.add_widget(address)
        self.address.append(address)
        unit = Spinner(values=self.currencies, text=self.currencies[0], size_hint_x=0.2, id='%d' % self.num_rows)
        self.selected_unit = self.currencies[0]
        unit.bind(text=self.set_unit)
        self.content.add_widget(unit)
        self.unit.append(unit)
        rates = Button(text='Rates', size_hint_x=0.2, id='%d' % self.num_rows)
        rates.bind(on_release=self.enter_rates)
        self.content.add_widget(rates)
        self.rates.append(rates)
        bot = Spinner(values=self.bots, text=self.bots[0], size_hint_x=0.2, id='%d' % self.num_rows)
        self.selected_bot = self.bots[0]
        bot.bind(text=self.set_bot)
        self.content.add_widget(bot)
        self.bot.append(bot)

        if isinstance(instance, dict):
            keys_button.text = instance['public'][:8] + ' / ' + instance['secret'][:8]
            address.text = instance['address']
            unit.text = instance['unit']
            rates.text = instance['ask'] + ' | ' + instance['bid']
            bot.text = instance['bot']

    def enter_keys(self, instance):
        """
        Show a pop-up in which previously entered api keys can be selected from a drop down
        There are edit and add buttons on the bottom which fire other methods
        :param instance:
        :return:
        """
        self.calling_keys_button = instance
        content = BoxLayout(orientation='vertical', spacing=10)
        top = BoxLayout(orientation='vertical', size_hint=(1, 0.7))
        top.add_widget(Label(text='API Key Pair', size_hint=(1, None), height='70dp'))
        self.api_key_spinner = Spinner(size_hint=(1, None), height='40dp')
        top.add_widget(self.api_key_spinner)
        self.api_key_spinner.bind(text=self.enable_edit)
        top.add_widget(BoxLayout())
        btnlayout = BoxLayout(spacing='5dp', size_hint=(1, 0.15))
        btn = Button(text='Ok', size_hint_y=None, height='50dp')
        btn.bind(on_release=self.close_api_keys_popup)
        btnlayout.add_widget(btn)
        btn = Button(text='Cancel', size_hint_y=None, height='50dp')
        btn.bind(on_release=self.close_api_keys_popup)
        btnlayout.add_widget(btn)
        self.edit_keys_button = Button(text='Edit Keys', size_hint_y=None, height='50dp', disabled=True)
        self.edit_keys_button.bind(on_release=self.edit_keys)
        btnlayout.add_widget(self.edit_keys_button)
        self.add_keys_button = Button(text='Add Keys', size_hint_y=None, height='50dp')
        self.add_keys_button.bind(on_release=self.add_keys)
        btnlayout.add_widget(self.add_keys_button)
        content.add_widget(top)
        content.add_widget(SettingSpacer())
        content.add_widget(btnlayout)
        popup_width = min(0.95 * Window.width, dp(500))
        self.enter_keys_popup = Popup(title='API Keys', content=content, auto_dismiss=False,
                                      size_hint=(None, None), size=(popup_width, '250dp'))
        self.update_api_spinners()
        if instance.text != 'Keys':
            self.api_key_spinner.text = instance.text
        self.enter_keys_popup.open()

    def enable_edit(self, instance, value):
        """
        The Edit button on the 'enter_api_keys' popup starts disabled.
        It is only enabled when a selection is made in the spinner
        :param instance:
        :param value:
        :return:
        """
        if value == '':
            self.edit_keys_button.disabled = True
        else:
            self.edit_keys_button.disabled = False
            self.edit_keys_button.id = value
            self.chosen_api_key_pair = value

    def edit_keys(self, instance):
        """
        Simply shows the add_keys popup with edit mode enabled
        :param instance:
        :return:
        """
        self.add_keys(instance, True)

    def add_keys(self, instance, edit=False):
        """
        Show a different pop-up into which api_keys can be entered.
        In edit mode the fields are pre-populated and a delete button is shown
        :param instance:
        :param edit:
        :return:
        """
        content = BoxLayout(orientation='vertical', spacing=10)
        grid = GridLayout(cols=2, spacing=10, size_hint=(1, 0.85))
        grid.add_widget(Label(text='Public', size_hint_x=None, width='100dp'))
        self.add_public_key = TextInput(size_hint=(1, None), height='40dp')
        self.add_public_key.bind(text=self.tab_switch)
        grid.add_widget(self.add_public_key)
        grid.add_widget(Label(text='Secret', size_hint_x=None, width='100dp'))
        self.add_secret_key = TextInput(size_hint=(1, None), height='40dp')
        self.add_secret_key.bind(text=self.tab_switch)
        grid.add_widget(self.add_secret_key)
        btnlayout = BoxLayout(spacing='5dp', size_hint=(1, 0.15))
        ok_btn = Button(text='Ok', size_hint_y=None, height='50dp')
        ok_btn.bind(on_release=self.save_api_keys)
        btnlayout.add_widget(ok_btn)
        btn = Button(text='Cancel', size_hint_y=None, height='50dp')
        btn.bind(on_release=self.save_api_keys)
        btnlayout.add_widget(btn)
        self.edit_public, self.edit_secret = None, None
        if edit is True:
            self.edit_public, self.edit_secret = self.get_keys(instance.id)
            if self.edit_public is None and self.edit_secret is None:
                return
            self.add_public_key.text = self.edit_public
            self.add_secret_key.text = self.edit_secret
            btn = Button(text='Delete', size_hint_y=None, height='50dp')
            btn.bind(on_release=self.delete_api_keys)
            btnlayout.add_widget(btn)

        content.add_widget(SettingSpacer())
        content.add_widget(grid)
        content.add_widget(btnlayout)
        self.add_keys_popup = Popup(title='Add API Keys', content=content, auto_dismiss=False,
                                    size_hint=(1, None), height='250dp')
        self.add_keys_popup.open()
        self.add_public_key.focus = True

    def tab_switch(self, instance, value):
        """
        tab switches from public to secret and back
        :return:
        """
        if '\t' not in value:
            return
        instance.text = value.replace('\t', '')
        if instance == self.add_public_key:
            self.add_secret_key.focus = True
        else:
            self.add_public_key.focus = True



    def update_api_spinners(self):
        """
        Populate the api_key selection spinner on the 'enter_api_keys' popup
        :return:
        """
        api_keys = self.fetch_api_keys_from_file()
        self.api_key_spinner.values = []
        self.api_key_spinner.text = ''
        for key_set in api_keys:
            if key_set['exchange'] != self.exchange:
                continue
            self.api_key_spinner.values.append(key_set['public'][:8] + ' / ' + key_set['secret'][:8])
        if self.chosen_api_key_pair is not None:
            self.api_key_spinner.text = self.chosen_api_key_pair

    def get_keys(self, keys):
        """
        When supplied truncated keys (as shown in the selection spinner)
        Get the full keys from the data file, ready for editting or saving
        :param keys:
        :return:
        """
        public = None
        secret = None
        if keys == 'Keys':
            return public, secret
        keys = keys.split(' / ')
        pub_key = keys[0]
        sec_key = keys[1]
        api_keys = self.fetch_api_keys_from_file()
        for key_set in api_keys:
            if key_set['exchange'] == self.exchange and key_set['public'][:8] == pub_key and key_set['secret'][:8] == sec_key:
                public = key_set['public']
                secret = key_set['secret']
        return public, secret

    def close_api_keys_popup(self, instance):
        """
        close the "enter_api_keys" popup.
        Cancel has no effect.
        OK saves the api key selection in te main data file
        :param instance:
        :return:
        """
        if instance.text == "Ok" and self.api_key_spinner.text != '':
            self.calling_keys_button.text = self.chosen_api_key_pair
        self.chosen_api_key_pair = None
        self.enter_keys_popup.dismiss()

    def save_api_keys(self, instance):
        """
        Save the Api Keys entered into the 'add_api_keys' popup
        These are saved to their own file for separate parsing
        :param instance:
        :return:
        """
        if instance.text == "Cancel" or self.add_public_key.text == "" or self.add_secret_key.text == "":
            self.add_keys_popup.dismiss()
            return
        api_keys = self.fetch_api_keys_from_file()
        if self.edit_public is not None and self.edit_secret is not None:
            for key_set in api_keys:
                if key_set['exchange'] == self.exchange and key_set['public'] == self.edit_public and key_set['secret'] == self.edit_secret:
                    key_set['public'] = self.add_public_key.text
                    key_set['secret'] = self.add_secret_key.text
        else:
            this_keys = {'exchange': self.exchange,
                         'public': self.add_public_key.text,
                         'secret': self.add_secret_key.text}
            for key_set in api_keys:
                if key_set == this_keys:
                    return

            api_keys.append(this_keys)

        self.save_api_keys_to_file(api_keys)

        self.chosen_api_key_pair = self.add_public_key.text[:8] + ' / ' + self.add_secret_key.text[:8]
        self.update_api_spinners()
        self.add_keys_popup.dismiss()

    def delete_api_keys(self, instance):
        """
        remove the chosen api key selection from the saved list
        :param instance:
        :return:
        """
        with open('api_keys.json', 'r') as api_keys_file:
            try:
                api_keys = json.load(api_keys_file)
            except ValueError:
                api_keys = []
            api_keys_file.close()
        if self.edit_public is not None and self.edit_secret is not None:
            new_api_keys = []
            for key_set in api_keys:
                if key_set['exchange'] == self.exchange and key_set['public'] == self.edit_public and key_set['secret'] == self.edit_secret:
                    continue
                new_api_keys.append(key_set)
        with open('api_keys.json', 'w+') as api_keys_file:
            api_keys_file.write(json.dumps(new_api_keys))
            api_keys_file.close()

        if self.calling_keys_button.text == self.edit_public[:8] + " / " + self.edit_secret[:8]:
            self.calling_keys_button.text = 'Keys'

        self.chosen_api_key_pair = None
        self.update_api_spinners()
        self.add_keys_popup.dismiss()

    def fetch_api_keys_from_file(self):
        """
        get all api_keys currently saved in the api_keys.json file
        :return:
        """
        config_ini = App.get_running_app().get_application_config()
        self.config.read(config_ini)

        api_keys = self.config.getdefault('user_data', 'api_keys', '')
        if api_keys == '':
            api_keys = []
        else:
            api_keys = list(api_keys)
        self.logger.info("got api keys %s" % str(api_keys))
        return api_keys

    def save_api_keys_to_file(self, api_keys):
        """
        save the api_keys json instance back to the file
        :param api_keys:
        :return:
        """
        config_ini = App.get_running_app().get_application_config()
        self.config.read(config_ini)
        self.logger.info("set api keys %s" % str(api_keys))
        self.config.set('user_data', 'api_keys', str(api_keys))

    def check_address(self, instance, value):
        """
        validate an entered address by checking the checksum an ensuring the first character is 'B'
        :param instance:
        :param value:
        :return:
        """
        if self.utils.check_checksum(value) and value[:1] == 'B':
            instance.foreground_color = (0, 0, 0, 1)
        else:
            instance.foreground_color = (0.93725, 0.31176, 0.17843, 1)

    def set_unit(self, instance, value):
        self.selected_unit = value

    def set_bot(self, instance, value):
        self.selected_bot = value

    def set_pool_maximum_rate(self, req, result):
        if self.exchange not in result:
            self.rates_error(req, result)
            return
        if self.selected_unit.lower() not in result[self.exchange]:
            self.rates_error(req, result)
            return
        self.ask_max = (result[self.exchange][self.selected_unit.lower()]['ask']['rate'] * 100)
        self.bid_max = (result[self.exchange][self.selected_unit.lower()]['bid']['rate'] * 100)
        self.ask_slider.max = self.ask_max
        self.bid_slider.max = self.bid_max


    def rates_error(self, req, result):
        self.rates_content.add_widget(Label(text='Unable to get Maximum rate data from the server'))
        self.ask_slider.max = 0
        self.bid_slider.max = 0

    def enter_rates(self, instance):
        """
        Show a pop-up in which minimum interest rates can be entered on sliders
        :param instance:
        :return:
        """
        self.calling_rates_button = instance
        self.rates_content = BoxLayout(orientation='vertical')
        config_ini = App.get_running_app().get_application_config()
        self.config.read(config_ini)
        url = "http://%s:%s/exchanges" % (self.config.get('server', 'host'), self.config.get('server', 'port'))
        self.ask_slider = Slider(step=0.01, size_hint=(0.9, 1))
        self.bid_slider = Slider(step=0.01, size_hint=(0.9, 1))
        req = UrlRequest(url, self.set_pool_maximum_rate, self.rates_error, self.rates_error)
        self.ask_slider.bind(on_touch_down=self.update_slider_values)
        self.ask_slider.bind(on_touch_up=self.update_slider_values)
        self.ask_slider.bind(on_touch_move=self.update_slider_values)
        self.bid_slider.bind(on_touch_down=self.update_slider_values)
        self.bid_slider.bind(on_touch_up=self.update_slider_values)
        self.bid_slider.bind(on_touch_move=self.update_slider_values)
        self.rates_content.add_widget(Label(text='Minimal Ask Rate'))
        ask_layout = BoxLayout()
        ask_layout.add_widget(self.ask_slider)
        self.ask_value = Label(size_hint=(0.1, 1))
        ask_layout.add_widget(self.ask_value)
        self.rates_content.add_widget(ask_layout)
        self.rates_content.add_widget(Label(text='Minimal Bid Rate'))
        bid_layout = BoxLayout()
        bid_layout.add_widget(self.bid_slider)
        self.bid_value = Label(size_hint=(0.1, 1))
        bid_layout.add_widget(self.bid_value)
        self.rates_content.add_widget(bid_layout)
        if instance.text != 'Set Rates':
            rates = instance.text.split(' | ')
            self.ask_slider.value = float(rates[0])
            self.bid_slider.value = float(rates[1])
        self.update_slider_values(None, None)
        btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
        btn = Button(text='Ok')
        btn.bind(on_release=self.close_rates_popup)
        btnlayout.add_widget(btn)
        btn = Button(text='Cancel')
        btn.bind(on_release=self.close_rates_popup)
        btnlayout.add_widget(btn)
        self.rates_content.add_widget(btnlayout)
        popup_width = min(0.95 * Window.width, dp(500))
        self.rates_popup = Popup(title='Minimal Interest Rates', content=self.rates_content, auto_dismiss=False,
                                 size_hint=(None, None), size=(popup_width, '300dp'))
        self.rates_popup.open()

    def update_slider_values(self, instance, value):
        self.ask_value.text = str(self.ask_slider.value)
        self.bid_value.text = str(self.bid_slider.value)

    def close_rates_popup(self, instance):
        if instance.text == "Ok":
            self.calling_rates_button.text = str(self.ask_slider.value) + ' | ' + str(self.bid_slider.value)
        self.rates_popup.dismiss()
Exemplo n.º 35
0
    def show_first_form(self):
        global STORAGE

        ip_tab = []
        if netifaces:
            interfaces = netifaces.interfaces()
            for interface in interfaces:
                if interface[:2] in ("wl", "en", "et"):
                    ifaddress = netifaces.ifaddresses(interface)
                    if netifaces.AF_INET in ifaddress:
                        inets = ifaddress[netifaces.AF_INET]
                        for inet in inets:
                            if "addr" in inet:
                                addr = inet["addr"]
                                if len(addr.split(".")) == 4:
                                    ip_tab.append(addr)
        else:
            try:
                ip_address = get_ip_address(b"wlan0")
                ip_tab.append(ip_address)
            except:
                pass

        if ip_tab:
            ip_address = ", ".join(ip_tab)
        else:
            ip_address = "-"

        label = Label(
            text=f"[size=18sp][color=88f][b]PYTIGON - select the application:[/b][/color][/size]\n[size=15sp][color=448](my ip addresses: {ip_address})[/b][/color][/size]",
            markup=True,
            halign="center",
        )
        self.add_widget(label)

        if not check_permission(Permission.WRITE_EXTERNAL_STORAGE):
            ret = request_permissions(PERMISSION)
            print("python::pytigon::request_permissions", ret)

        init(
            "_schall",
            schserw_settings.ROOT_PATH,
            schserw_settings.DATA_PATH,
            schserw_settings.PRJ_PATH,
            schserw_settings.STATIC_ROOT,
            [schserw_settings.MEDIA_ROOT, schserw_settings.UPLOAD_PATH],
        )

        base_apps_path = os.path.join(os.path.join(STORAGE, "pytigon"), "prj")
        l = [pos for pos in os.listdir(base_apps_path) if not pos.startswith("_")]
        apps = []
        for prj in l:
            base_apps_path2 = os.path.join(base_apps_path, prj)
            try:
                x = __import__(prj + ".apps")
                if hasattr(x.apps, "PUBLIC") and x.apps.PUBLIC:
                    apps.append(prj)
            except:
                print("Error importing module: ", prj + ".apps")

        if len(apps) > 1:
            if len(apps) > MAX_SEL_APP:
                dy = MAX_SEL_APP - 1
            else:
                dy = len(apps)

            for pos in apps[:dy]:
                button = Button(id=pos, text=pos, size_hint=(1, 1))
                button.bind(on_release=self.chose_callback)
                self.add_widget(button)

            if len(apps) > MAX_SEL_APP:
                spinner = Spinner(
                    text="Other applications",
                    values=apps[dy:],
                    size_hint=(0.5, 1),
                    pos_hint={
                        "center_x": 0.5,
                    },
                )
                spinner.bind(text=self.spinner_callback)
                self.add_widget(spinner)
        else:
            if len(apps) > 0:
                self.on_app_chosen(apps[0])
            else:
                self.on_app_chosen()