Ejemplo n.º 1
0
class Switch_implementare(GridLayout):
    def __init__(self, **kwargs):
        super(Switch_implementare, self).__init__(**kwargs)
        self.cols = 1
        self.padding = 150
        self.switch1 = Switch()
        self.switch1.active = True
        self.add_widget(self.switch1)
        self.arata_volum = Label(text="volum: 10")
        self.add_widget(self.arata_volum)
        self.slide_muzica = Slider(min=0, max=100, value=10)
        self.slide_muzica.step = 5
        self.slide_muzica.orientation = "horizontal"  # alte optiuni 'vertical'
        self.add_widget(self.slide_muzica)
        self.switch1.bind(active=self.dezactiveaza_volum)
        self.slide_muzica.bind(value=self.valoare_volum)

    def valoare_volum(self, x, y):
        '''utilziat pentru a vedea volumul'''
        self.arata_volum.text = "volum: " + str(int(self.slide_muzica.value))

    def dezactiveaza_volum(self, x, y):
        '''utilziat pentru a acctiva sau a dezactiva slider-ul'''
        if (self.switch1.active == False):
            self.slide_muzica.disabled = True
        else:
            self.slide_muzica.disabled = False
            self.slide_muzica.value = 0
Ejemplo n.º 2
0
	def build(self):
		Config.set('graphics', 'width', 320)
		Config.set('graphics', 'height', 512)
		print(kivy.__version__)

		# -------- funciones -------------
		def sw(instance, value):
			print('the switch', instance, 'is', value)
			print(layout.size)
			if value:
				labelMensaje.text = "ACTIVADO."
				print(kivy.__version__)
			else:
				labelMensaje.text = "DESACTIVADO."

		# capas layout
		layout = BoxLayout(spacing=2, orientation="horizontal", padding=30)
		layout2 = BoxLayout(spacing=10, orientation="vertical", padding=30)
		
		# elementos widgets
		labelsw1 = Label(text="Luz del pasillo:")
		btn1 = Button(text='Entrar')
		labelMensaje = Label(text="DESACTIVADO.", font_size=30)
		switch = Switch()

		layout.add_widget(switch, index=0)
		layout.add_widget(labelsw1, index=1)
		layout2.add_widget(layout, index=2)
		layout2.add_widget(btn1, index=0)
		layout2.add_widget(labelMensaje, index=1)

		switch.bind(active=sw)

		return layout2
Ejemplo n.º 3
0
    def build(self):
        if platform ==  "android":
            from android import AndroidService
            service = AndroidService('desire sensors service', 'running')
            service.start('service started')
            self.service = service

        status_page = StatusPage()
        accelerometer.enable()
        compass.enable()
        self.gps = gps
        self.gps.configure(on_location=self.on_gps_location,
                           on_status=self.on_gps_status)
        self.gps.start()

        notification.notify(title="Hello",message="Just Checking")
        #vibrator.vibrate(0.2)  # vibrate for 0.2 seconds
        print("Hello World")
        status_page.gps_data = self.gps_data

#        Clock.schedule_interval(status_page.update, 1.0 / 10.0) # 10H
        Clock.schedule_interval(status_page.update, 1.0) # 1Hz


        button=Button(text='Service',size_hint=(0.12,0.12))
        button.bind(on_press=self.callback)
        status_page.add_widget(button)

        switch = Switch()
        switch.bind(active=self.callback)
        status_page.add_widget(switch)
        return status_page
Ejemplo n.º 4
0
    def build_overview(self):
        alarm_overview = self.ids['Alarm_Overview_Stack']
        alarm_overview.bind(minimum_height=alarm_overview.setter('height'))
        alarm_overview.clear_widgets(children=None)

        SortedAlarms = sorted(Alarms,
                              key=lambda Alarm: Alarm.MinutesAfterMidnight())
        for alarm in SortedAlarms:

            alarm_overview.add_widget(
                Label(text=alarm.to_string(),
                      font_size=25,
                      height=80,
                      size_hint=(0.4, None)))

            alarm_switch = Switch(active=alarm.IsActive,
                                  height=80,
                                  size_hint=(0.3, None))
            alarm_switch.bind(active=alarm.toggle_active)

            alarm_delete = Button(
                background_normal='images/AccordionSelected.png',
                height=64,
                size_hint=(0.2, None))
            alarm_delete.bind(on_press=partial(self.delete_alarm, alarm))

            alarm_overview.add_widget(alarm_switch)
            alarm_overview.add_widget(alarm_delete)
Ejemplo n.º 5
0
    def build(self):
        if platform == "android":
            from android import AndroidService
            service = AndroidService('desire sensors service', 'running')
            service.start('service started')
            self.service = service

        status_page = StatusPage()
        accelerometer.enable()
        compass.enable()
        self.gps = gps
        self.gps.configure(on_location=self.on_gps_location,
                           on_status=self.on_gps_status)
        self.gps.start()

        notification.notify(title="Hello", message="Just Checking")
        #vibrator.vibrate(0.2)  # vibrate for 0.2 seconds
        print("Hello World")
        status_page.gps_data = self.gps_data

        #        Clock.schedule_interval(status_page.update, 1.0 / 10.0) # 10H
        Clock.schedule_interval(status_page.update, 1.0)  # 1Hz

        button = Button(text='Service', size_hint=(0.12, 0.12))
        button.bind(on_press=self.callback)
        status_page.add_widget(button)

        switch = Switch()
        switch.bind(active=self.callback)
        status_page.add_widget(switch)
        return status_page
Ejemplo n.º 6
0
class FftWidget(GridLayout):
    def __init__(self, **kwargs):
        self.rows = 1
        self.cols = 1
        GridLayout.__init__(self, **kwargs)
        topLayout = BoxLayout(orientation="vertical")
        midLayout = BoxLayout(orientation="horizontal", size_hint=(1.0, 0.8))
        swLayout = BoxLayout(orientation="vertical", size_hint=(0.2, 1.0))
        swLayout.add_widget(Label(text="Zoom"))
        self.zs = Switch()
        self.zs.bind(active=self.zoomSwitchLogic)
        swLayout.add_widget(self.zs)
        swLayout.add_widget(Label(text="Pan"))
        self.ps = Switch()
        self.ps.bind(active=self.panSwitchLogic)
        swLayout.add_widget(self.ps)
        midLayout.add_widget(Renderer(self.zs, self.ps, size_hint=(0.8, 1.0)))
        midLayout.add_widget(swLayout)

        topLayout.add_widget(Button(text="first", size_hint=(1.0, 0.1)))
        #topLayout.add_widget(Renderer(size_hint=(1.0, 0.8)))
        topLayout.add_widget(midLayout)
        topLayout.add_widget(Button(text="second", size_hint=(1.0, 0.1)))
        self.add_widget(topLayout)

    def zoomSwitchLogic(self, a, b):
        if self.zs.active and self.ps.active:
            self.ps.active = False

    def panSwitchLogic(self, a, b):
        if self.zs.active and self.ps.active:
            self.zs.active = False
Ejemplo n.º 7
0
class SwitchContainer(GridLayout):
    def __init__(self, **kwargs):
        super(SwitchContainer, self).__init__(**kwargs)
        self.cols = 2
        self.add_widget(Label(text="Auto jump status:"))
        self.settings_sample = Switch(active=False)
        self.add_widget(self.settings_sample)
        self.settings_sample.bind(active=switch_callback)
Ejemplo n.º 8
0
    def sw_factory(self):
        def cb(ins, val):
            self.value = val
            print(self.value)

        ti = Switch(size_hint_y=None, height=30)
        ti.bind(active=cb)
        return ti
Ejemplo n.º 9
0
    def __init__(self, **kwargs):
        super(SettingsLiteScreen, self).__init__(**kwargs)

        # Set up the settings in a grid
        popup = GridLayout(cols=1, size_hint_y=None)
        # Make sure the height is such that there is something to scroll.
        popup.bind(minimum_height=popup.setter('height'))

        # Set up setting buttons
        with open(join(dirname(__file__), 'camera.json')) as json_file:
            json_data = json.load(json_file)
            for setting in json_data:
                if setting['settings_lite'] == '1':

                    # Check if the setting is boolean
                    if setting['type'] == 'bool':

                        # Check if the current setting is on or off
                        if main.App.get_running_app().config.getint('Camera', setting['key']) == 1:
                            cur_state = True
                        else:
                            cur_state = False

                        # Create the widgets
                        label = Label(text=setting['title'],
                                     size_hint_y=None,
                                     height=48)
                        switch = Switch(active=cur_state,
                                    size_hint_y=None,
                                    height=48)
                        switch.bind(active=partial(self.settings_lite_switch_toggle, setting['key']))
                        # Add to main settings_lite widget
                        popup.add_widget(label)
                        popup.add_widget(switch)

                    # Else just make the setting a button
                    else:
                        btn = Button(text=setting['title'],
                                     size_hint_y=None,
                                     height=96)
                        btn.bind(on_release=self.settings_lite_button_push)
                        popup.add_widget(btn)

        # Setup the scrollable section and add to floatlayout.
        scrolly = ScrollView(size_hint=(0.2, 0.83),
                             pos_hint={'x':0.8, 'y':0.17})
        scrolly.add_widget(popup)
        floaty = FloatLayout()
        floaty.add_widget(scrolly)

        # Add the close button to the bottom
        close_button = Button(text='Close',
                              size_hint=(0.2, 0.16),
                              pos_hint={'x':0.8, 'y':0})
        close_button.bind(on_release=self.close_settings_lite)
        floaty.add_widget(close_button)
        self.add_widget(floaty)
Ejemplo n.º 10
0
    def dashboard_speed_tab(self):
        canvas = BoxLayout(orientation='vertical')

        # 1st layer
        setup = BoxLayout(orientation='horizontal')
        #setup.height = 20
        setup.size_hint = (1, None)
        btnPlus = Button(text='-', id="minus")
        self.w_spd_targetspeed = Label(text='10', font_size="20sp")
        btnMinus = Button(text='+', id="plus")
        btnAspd = ToggleButton(text='AirSpeed',
                               id="aspd",
                               group='speed_source',
                               state='down')
        btnGspd = ToggleButton(text='GndSpeed',
                               id="gspd",
                               group='speed_source')
        btnAspd.bind(state=self.cb_set_speed_source)
        btnGspd.bind(state=self.cb_set_speed_source)
        btnPlus.bind(state=self.cb_set_speed_source)
        btnMinus.bind(state=self.cb_set_speed_source)
        swRead = Switch(active=False)
        swRead.bind(active=self.toggle_reading)
        setup.add_widget(btnPlus)
        setup.add_widget(self.w_spd_targetspeed)
        setup.add_widget(btnMinus)
        setup.add_widget(btnAspd)
        setup.add_widget(btnGspd)
        setup.add_widget(swRead)

        # zaskrtavatko - hlas, tón, pipani
        # Ukazatel

        data = BoxLayout(orientation='horizontal')

        data_actual = BoxLayout(orientation='vertical')
        self.w_spd_release_status = Label(text="--Release--", markup=True)
        self.w_spd_speed_info = Label(text="info",
                                      markup=True,
                                      halign="center")
        data_actual.add_widget(self.w_spd_release_status)
        data_actual.add_widget(self.w_spd_speed_info)

        data_offset = BoxLayout(orientation='vertical')
        self.w_spd_offset = Label(text="Err", font_size="50sp", markup=True)
        data_offset.add_widget(self.w_spd_offset)

        self.w_spd_range = Range()

        data.add_widget(data_actual)
        data.add_widget(data_offset)
        data.add_widget(self.w_spd_range)

        canvas.add_widget(setup)
        canvas.add_widget(data)
        return canvas
Ejemplo n.º 11
0
class FlashApp(App):
    def build(self):
        self.root = Switch()
        self.service = AndroidService('Kivy FlashLight', 'I haz a FlashLight!')
        self.root.bind(active=self.toggle_flash)
        return self.root

    def toggle_flash(self, *args):
        if self.root.active:
            self.service.start()
        else:
            self.service.stop()
Ejemplo n.º 12
0
class Tela(FloatLayout):
    def __init__(self, **kwargs):
        super(Tela, self).__init__(**kwargs)
        self.switch = Switch(active=False)
        self.switch.bind(active=self.esta_ativo)        
        self.add_widget(self.switch)   

    def esta_ativo(self, instance, value):
        if value == True:
            print('O switch Ativo')
        else:
            print('O switch Desativado')
Ejemplo n.º 13
0
def BrowserPop(self):
    layout = GridLayout(cols=1, size_hint=(None, 1.0), width=700)
    layout.bind(minimum_height=layout.setter("height"))
    panel = SettingsPanel(title="Browser Mods", settings=self)
    main = BoxLayout(orientation="vertical")
    root = ScrollView(
        size_hint=(None, None), bar_margin=-11, bar_color=(47 / 255.0, 167 / 255.0, 212 / 255.0, 1.0), do_scroll_x=False
    )
    root.size = (600, 400)
    root.add_widget(layout)
    main.add_widget(root)
    done = Button(text="Done Choosing Options")
    main.add_widget(done)
    if "const/4 v0, 0x4" in open("%s/BrowserSettings.smali" % (Browser)).read():
        fp = open("%s/BrowserSettings.smali" % (Browser), "r")
        lines = fp.readlines()
        fp.close()
        tabs = SettingItem(
            panel=panel,
            title="Unlimited Browser Tabs",
            disabled=False,
            desc="Allows Unlimited number of browser tabs to be open",
        )
        for i in range(len(lines)):
            if "const/4 v0, 0x4" in open("%s/BrowserSettings.smali" % (Browser)).read():
                tabs_switch = Switch(active=False)
                continue
            if "const/4 v0, 0x4" in open("%s/BrowserSettings.smali" % (Browser)).read():
                tabs_switch = Switch(active=True)
        tabs.add_widget(tabs_switch)
        layout.add_widget(tabs)

        def callback(instance, value):
            tabs_state(instance, value)

        tabs_switch.bind(active=callback)

    popup = Popup(
        background="atlas://images/eds/pop",
        title="Browser Mods",
        content=main,
        auto_dismiss=False,
        size_hint=(None, None),
        size=(630, 500),
    )
    popup.open()

    def finish(self):
        finish_browser(self)
        popup.dismiss()

    done.bind(on_release=finish)
Ejemplo n.º 14
0
class BoxLayoutItemBoolean(BoxLayoutItem):
    def __init__(self, section, item_name, item_value):
        super(BoxLayoutItemBoolean, self).__init__(section, item_name,
                                                   item_value)

        self.item_value = Switch(active=item_value)
        self.add_widget(self.item_value)
        self.item_value.bind(active=self.item_activated)

    def item_activated(self, *args):
        self.changed_value(args[1])

    def restore_item_value(self):
        self.item_value.active = self.server_value
Ejemplo n.º 15
0
    def __init__(self, **kwargs):
        super(WhiteNoise, self).__init__(**kwargs)
        pos_hint = {"x": .5, "y": .1}

        def callback(instance, value):
            if (value is True):
                noise1.play()
            elif (value is False):
                noise1.stop()

        self.text = "white noise"
        noise1 = SoundLoader.load('sounds/noise1.wav')
        noise1.loop = True
        switch = Switch()
        switch.bind(active=callback)
        self.add_widget(switch)
Ejemplo n.º 16
0
 def show_plugins(self, plugins_list):
     def on_active(sw, value):
         self.plugins.toggle_enabled(self.electrum_config, sw.name)
         run_hook('init_kivy', self)
     for item in self.plugins.descriptions:
         if 'kivy' not in item.get('available_for', []):
             continue
         name = item.get('__name__')
         label = Label(text=item.get('fullname'), height='48db', size_hint=(1, None))
         plugins_list.add_widget(label)
         sw = Switch()
         sw.name = name
         p = self.plugins.get(name)
         sw.active = (p is not None) and p.is_enabled()
         sw.bind(active=on_active)
         plugins_list.add_widget(sw)
Ejemplo n.º 17
0
class LabeledSwitch(BoxLayout):
    def __init__(self,
                 text,
                 color=[1] * 4,
                 pos_hint={
                     "x": 0,
                     "y": 0
                 },
                 size_hint=[1, 1],
                 *args,
                 **kwargs):

        super(LabeledSwitch, self).__init__(pos_hint=pos_hint,
                                            size_hint=size_hint,
                                            *args,
                                            **kwargs)

        #    self.Initialize(*args,**kwargs)

        #def Initialize(self,*args,**kwargs):
        self.Label = Label(text=text, color=color)
        self.add_widget(self.Label)
        self.Switch = Switch(*args, **kwargs)
        self.add_widget(self.Switch)
        #print self.size, self.Switch.size

    def bindSwitch(self, *args, **kwargs):
        return self.Switch.bind(*args, **kwargs)

    def IsActive(self):
        return self.Switch.active
Ejemplo n.º 18
0
class RamdomFacePage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        Window.size = (640, 700)
        self.cross_img = Image(source="", size=(640, 640), pos=(0, 120))

        self.add_widget(self.cross_img)

        self.noise_slider = Slider(min=-1, max=1, value=0, pos=(290, 40))
        self.add_widget(self.noise_slider)

        self.Generate_button = Button(text="Generate",
                                      size=(320, 60),
                                      pos=(0, 0),
                                      font_size=default_font_size)
        self.Generate_button.bind(on_press=self.Generate_image)
        self.add_widget(self.Generate_button)

        self.back_button = Button(text="Back",
                                  size=(320, 60),
                                  pos=(320, 0),
                                  font_size=default_font_size)
        self.back_button.bind(on_press=self.back)
        self.add_widget(self.back_button)

        self.switch = Switch(size=(50, 60), pos=(30, 50))
        self.switch.bind(active=self.switch_training)
        self.add_widget(self.switch)

    def Generate_image(self, instance):
        if cgan.test(is_training=is_training,
                     desc='',
                     noise=self.noise_slider.value,
                     alt_path=alt_path):
            # self.cross_img = Image(source=cgan.test_dir + cgan.version + '/test.jpg', size=(640, 640), pos=(0, 120))
            self.cross_img.source = cgan.test_dir + cgan.version + '/test.jpg'
            print(self.cross_img.source)
            self.cross_img.reload()

    def back(self, instance):
        chat_app.screen_manager.current = 'MainMenu'

    def switch_training(self, instance, value):
        global is_training
        is_training = value
Ejemplo n.º 19
0
    def create_save_image_buttons(self):
        time_lapse_layout = BoxLayout(orientation = 'vertical', size_hint_y = 0.6)
        save_image_button = Button(text = 'save image', size_hint_y = 0.2, background_color = [0, 0.3, 1, 1]) 
        time_lapse_interval_input = TextInput(text = str(self.time_lapse_interval), multiline = False, size_hint_y = 0.3)
        time_lapse_interval_label = Label(text = 'time_lapse\ninterval(sec)', size_hint_y = 0.15, color = [0, 1, 0, 1])
        time_lapse_button = Switch(size_hint_y = 0.2) # need to make a popup to choose time_interval etc.
        time_lapse_button_label = Label(text = 'on/off\ntime_lapse', size_hint_y = 0.15,  color = [0, 1, 0, 1])
        
        def save_image(instance):
            ''' Callback for save_image_button'''
            self.filepath_update = False # this prevents saving image mess up naming 
            self.filepath = self.format_filepath(update = False)
            if debug_mode is True:
                print('save image to {}'.format(self.filepath))
            if debug_mode is False:
                mc.camera_library('save_image', self.folder, self.filepath)
            self.image_number = self.image_number + 1

        def start_time_lapse(instance, value):
            ''' Callback for time_lapse_button'''
            update_time_lapse_interval(time_lapse_interval_input)
            if value is True:
                # start time lapse
                save_image('')
                self.event = Clock.schedule_interval(save_image, self.time_lapse_interval)
            if value is False:
                Clock.unschedule(self.event)
        def update_time_lapse_interval(instance):
            try: 
                self.time_lapse_interval = float(time_lapse_interval_input.text)
            except:
                # if the text_input is not a valid value, use 60 as default value
                time_lapse_interval_input.text = str(self.time_lapse_interval)
                self.time_lapse_interval = float(time_lapse_interval_input.text)
                print(self.time_lapse_interval)
            
        save_image_button.bind(on_release = save_image)
        time_lapse_button.bind(active = start_time_lapse)
        if debug_mode is False:
            # When click the time_lapse_interval_input, stop the preview
            time_lapse_interval_input.bind(focus = partial(mc.camera_library, 'stop_preview'))
        time_lapse_interval_input.bind(on_text_validate = update_time_lapse_interval)
        for i in [save_image_button, time_lapse_interval_label, time_lapse_interval_input, time_lapse_button_label, time_lapse_button]:
            time_lapse_layout.add_widget(i)

        return time_lapse_layout
Ejemplo n.º 20
0
def MmsPop(self):
    layout = GridLayout(cols=1, size_hint=(None, 1.0), width=700)
    layout.bind(minimum_height=layout.setter('height'))
    panel = SettingsPanel(title="Mms Mods", settings=self)   
    main = BoxLayout(orientation = 'vertical')
    root = ScrollView(size_hint=(None, None),bar_margin=-11, bar_color=(47 / 255., 167 / 255., 212 / 255., 1.), do_scroll_x=False)
    root.size = (600, 400)
    root.add_widget(layout)
    main.add_widget(root)
    done = Button(text ='Done Choosing Options')
    main.add_widget(done)
    if """    .line 77
    const/4 v0, 0x1

    sput-boolean v0, Lcom/android/mms/model/ImageModel;->mCheckResolution:Z""" in open("%s/ImageModel.smali" % (Mms)).read():
        fp = open("%s/ImageModel.smali" % (Mms), "r")
        lines = fp.readlines()
        fp.close()
        comp = SettingItem(panel = panel, title = "Remove Mms Compression",disabled=False, desc = "Disables Compression of Mms Messages")
        for i in range(len(lines)):
            if """    .line 77
    const/4 v0, 0x1

    sput-boolean v0, Lcom/android/mms/model/ImageModel;->mCheckResolution:Z""" in open("%s/ImageModel.smali" % (Mms)).read():
                comp_switch = Switch(active=False)
                continue
            if """    .line 77
    const/4 v0, 0x1

    sput-boolean v0, Lcom/android/mms/model/ImageModel;->mCheckResolution:Z""" in open("%s/ImageModel.smali" % (Mms)).read():
                comp_switch = Switch(active=True)
        comp.add_widget(comp_switch)
        layout.add_widget(comp)
    
        def callback(instance, value):
            comp_state(instance, value)
        comp_switch.bind(active=callback)

    popup = Popup(background='atlas://images/eds/pop', title='Mms Mods', content=main, auto_dismiss=False, size_hint=(None, None), size=(630, 500))
    popup.open()

    def finish(self):
        finish_comp(self)
        popup.dismiss()
    done.bind(on_release=finish)
class RVViewClass(BoxLayout):
    user_id = NumericProperty(None, allownone=True)
    estimator_id = NumericProperty(None, allownone=True)
    db = ObjectProperty(None, allownone=True)

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

        self.label_user_info = Label(text='', bold=True, italic=True)
        self.add_widget(self.label_user_info)
        self.label_estimator_info = Label(text='', bold=True, italic=True)
        self.add_widget(self.label_estimator_info)
        self.switch_is_accessible = Switch(active=True)
        self.add_widget(self.switch_is_accessible)

        self.bind(user_id=self.represent_info)
        self.bind(estimator_id=self.represent_info)
        self.bind(db=self.represent_info)
        self.switch_is_accessible.bind(active=self.switch_is_accessible_bind)

    def switch_is_accessible_bind(self, *args):
        user = self.db.get_user_by_id(self.user_id)
        estimator = self.db.get_estimator_by_id(self.estimator_id)

        if self.switch_is_accessible.active:
            if not (estimator in user.estimators):
                user.estimators.append(estimator)
        else:
            if estimator in user.estimators:
                user.estimators.remove(estimator)

    def represent_info(self, *args):
        if self.user_id and self.estimator_id and self.db:
            user = self.db.get_user_by_id(self.user_id)
            estimator = self.db.get_estimator_by_id(self.estimator_id)

            self.label_user_info.text = represent_user_in_rv(user)
            self.label_estimator_info.text = represent_estimator_in_rv(
                estimator)
            self.switch_is_accessible.active = estimator in user.estimators
Ejemplo n.º 22
0
    def on_enter(self):
        try:
            #Clear all labels
            self.ids.groupName.clear_widgets()
            self.ids.devicesConnected.clear_widgets()

            #Add back labels for the group and devices connectedf
            self.ids.groupName.add_widget(Label(text="Name:", font_size=35))
            #self.ids.groupName.add_widget(Label(text="Group " + str(self.currentGroupNo),font_size=35))
            #NEEDS TO BE CHANGED TO DISPLAY ACTUAL GROUP DATA
            self.ids.groupName.add_widget(
                Label(
                    text=self.manager.create_group_screen.ids.group_name.text,
                    font_size=20))

            self.ids.devicesConnected.add_widget(
                Label(text="Status:", font_size=35))
            self.ids.devicesConnected.add_widget(
                Label(text=str(' Inactive'), font_size=20))

            self.ids.devicelisting.clear_widgets()
            for i in xrange(0, len(ConnectDevicesScreen().applied_list)):
                addedGroup = BoxLayout(size_hint_y=None,
                                       height='75sp',
                                       orientation='horizontal')

                addedGroup.add_widget(
                    Label(text="Device " +
                          ConnectDevicesScreen().applied_list[i],
                          font_size=10,
                          color=(0, 0, 0, 1)))

                switch = Switch(active=False,
                                id=ConnectDevicesScreen().applied_list[i])
                switch.bind(active=self.switch_on)
                addedGroup.add_widget(switch)

                self.ids.devicelisting.add_widget(addedGroup)
        except Exception:
            print('Error in the on_enter function!')
Ejemplo n.º 23
0
Archivo: gui.py Proyecto: MNiko97/ECAM
 def settings(self):
     screen = Screen(name=ROOT + 'Settings')
     settings_background = Image(source='settings_background.jpg',
                                 allow_stretch=True,
                                 keep_ratio=False)
     layout = FloatLayout(size=(500, 500))
     layout.add_widget(settings_background)
     btn_singleplayer = Button(text='Single Player',
                               size_hint=(.15, .08),
                               pos_hint={
                                   'x': .65,
                                   'y': .45
                               })
     btn_singleplayer.bind(on_press=self.singleplayer)
     btn_multiplayer = Button(text='Multiplayer',
                              size_hint=(.15, .08),
                              pos_hint={
                                  'x': .825,
                                  'y': .45
                              })
     btn_multiplayer.bind(on_press=self.multiplayer)
     label_switch = Label(text='Random Map Generator',
                          size_hint=(.15, .08),
                          pos_hint={
                              'x': .5,
                              'y': .1
                          })
     switch = Switch(active=False,
                     size_hint=(.15, .08),
                     pos_hint={
                         'x': .7,
                         'y': .1
                     })
     switch.bind(active=self.map_setting)
     layout.add_widget(btn_multiplayer)
     layout.add_widget(btn_singleplayer)
     layout.add_widget(label_switch)
     layout.add_widget(switch)
     screen.add_widget(layout)
     return screen
Ejemplo n.º 24
0
    def set_settings_layout(self):
        looping_switch_layout = BoxLayout()
        looping_switch_layout.spacing = 2
        looping_switch_layout.size_hint = (.2, 1)
        looping_switch_layout.orientation = "horizontal"

        looping_switch_label = Label()
        looping_switch_label.color = [.6, .2, 1, .5]
        looping_switch_label.text = "Loop Sound"
        looping_switch_label.size_hint = (.3, 1)
        looping_switch_layout.add_widget(looping_switch_label)

        looping_switch = Switch(active=False)
        looping_switch.bind(active=self.toggle_looping_sound)
        looping_switch.size_hint = (.3, 1)
        looping_switch_layout.add_widget(looping_switch)

        empty_label = Label()
        empty_label.size_hint = (.4, 1)
        looping_switch_layout.add_widget(empty_label)

        self.title_layout.add_widget(looping_switch_layout)
Ejemplo n.º 25
0
class Switch_implementare(GridLayout):

    def __init__(self, **kwargs):
        super(Switch_implementare, self).__init__(**kwargs)
        global x
        self.cols = 1
        self.padding = 150
        self.switch1 = Switch(text="muzica")
        self.switch1.active =True
        self.add_widget(self.switch1)
        self.arata_volum = Label (text = "volum: 50")
        self.add_widget(self.arata_volum)
        self.slide_muzica = Slider(min=0, max=100, value=50)
        self.slide_muzica.step = 5
        self.slide_muzica.orientation="horizontal" # alte optiuni 'vertical'
        self.add_widget(self.slide_muzica)
        self.switch1.bind(active=self.dezactiveaza_volum)
        self.slide_muzica.bind(value=self.valoare_volum)
        
        self.sound = SoundLoader.load('JO_-_09_-_Fortitude.ogg')
        self.sound.play()
        self.sound.loop = True
        self.sound.volume=0.5
        x = self.sound

    def valoare_volum (self,x,y):
        '''utiliziat pentru seta volumul'''
        self.arata_volum.text = "volum: "+str(int(self.slide_muzica.value))
        self.sound.volume = self.slide_muzica.value/100
        
    def dezactiveaza_volum (self,x,y):
        '''utilziat pentru a acctiva sau a dezactiva slider-ul'''
        if (self.switch1.active == False) :
            self.slide_muzica.disabled =True
            self.sound.stop()
        else:
            self.slide_muzica.disabled =False
            self.slide_muzica.value = 0
            self.sound.play()
Ejemplo n.º 26
0
class Switch_implementare(GridLayout):
    def __init__(self, **kwargs):
        super(Switch_implementare, self).__init__(**kwargs)
        global x
        self.cols = 1
        self.padding = 150
        self.switch1 = Switch(text="muzica")
        self.switch1.active = True
        self.add_widget(self.switch1)
        self.arata_volum = Label(text="volum: 50")
        self.add_widget(self.arata_volum)
        self.slide_muzica = Slider(min=0, max=100, value=50)
        self.slide_muzica.step = 5
        self.slide_muzica.orientation = "horizontal"  # alte optiuni 'vertical'
        self.add_widget(self.slide_muzica)
        self.switch1.bind(active=self.dezactiveaza_volum)
        self.slide_muzica.bind(value=self.valoare_volum)

        self.sound = SoundLoader.load('JO_-_09_-_Fortitude.ogg')
        self.sound.play()
        self.sound.loop = True
        self.sound.volume = 0.5
        x = self.sound

    def valoare_volum(self, x, y):
        '''utiliziat pentru seta volumul'''
        self.arata_volum.text = "volum: " + str(int(self.slide_muzica.value))
        self.sound.volume = self.slide_muzica.value / 100

    def dezactiveaza_volum(self, x, y):
        '''utilziat pentru a acctiva sau a dezactiva slider-ul'''
        if (self.switch1.active == False):
            self.slide_muzica.disabled = True
            self.sound.stop()
        else:
            self.slide_muzica.disabled = False
            self.slide_muzica.value = 0
            self.sound.play()
Ejemplo n.º 27
0
def BrowserPop(self):
    layout = GridLayout(cols=1, size_hint=(None, 1.0), width=700)
    layout.bind(minimum_height=layout.setter('height'))
    panel = SettingsPanel(title="Browser Mods", settings=self)   
    main = BoxLayout(orientation = 'vertical')
    root = ScrollView(size_hint=(None, None),bar_margin=-11, bar_color=(47 / 255., 167 / 255., 212 / 255., 1.), do_scroll_x=False)
    root.size = (600, 400)
    root.add_widget(layout)
    main.add_widget(root)
    done = Button(text ='Done Choosing Options')
    main.add_widget(done)
    if 'const/4 v0, 0x4' in open("%s/BrowserSettings.smali" % (Browser)).read():
        fp = open("%s/BrowserSettings.smali" % (Browser), "r")
        lines = fp.readlines()
        fp.close()
        tabs = SettingItem(panel = panel, title = "Unlimited Browser Tabs",disabled=False, desc = "Allows Unlimited number of browser tabs to be open")
        for i in range(len(lines)):
            if 'const/4 v0, 0x4' in open("%s/BrowserSettings.smali" % (Browser)).read():
                tabs_switch = Switch(active=False)
                continue
            if 'const/4 v0, 0x4' in open("%s/BrowserSettings.smali" % (Browser)).read():
                tabs_switch = Switch(active=True)
        tabs.add_widget(tabs_switch)
        layout.add_widget(tabs)
    
        def callback(instance, value):
            tabs_state(instance, value)
        tabs_switch.bind(active=callback)
    
    popup = Popup(background='atlas://images/eds/pop', title='Browser Mods', content=main, auto_dismiss=False, size_hint=(None, None), size=(630, 500))
    popup.open()

    def finish(self):
        finish_browser(self)
        popup.dismiss()
    done.bind(on_release=finish)
Ejemplo n.º 28
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.cols = 2

        self.pref = Prefences()

        # App will speak pref
        ch = Switch(active=self.getSettingValue('speak'))
        ch.bind(active=self.callback)
        self.add_widget(Label(text='app will speak words'))
        self.add_widget(ch)

        chMakeCaps = Switch(active=self.getSettingValue('makeCaps'))
        chMakeCaps.bind(active=self.callbackMakeCaps)
        self.add_widget(Label(text='app will show all words in Caps'))
        self.add_widget(chMakeCaps)

        self.add_widget(
            Label(text="URL importing")
        )

        self.urlLayout = UrlLayout()
        self.add_widget(self.urlLayout)
Ejemplo n.º 29
0
    def on_enter(self):

        try:
            #Clear all widgets
            self.ids.devicetestlisting.clear_widgets()
            for i in xrange(0, len(ConnectDevicesScreen.applied_list)):
                addedGroup = BoxLayout(size_hintOK_y=None,
                                       height='75sp',
                                       orientation='horizontal')

                addedGroup.add_widget(
                    Label(text="" + ConnectDevicesScreen.applied_list[i],
                          font_size=10,
                          color=(0, 0, 0, 1)))

                switch = Switch(active=True,
                                id=ConnectDevicesScreen.applied_list[i])
                switch.bind(active=self.switch_on)
                addedGroup.add_widget(switch)

                self.ids.devicetestlisting.add_widget(addedGroup)
                self.deviceTestedValues.append(True)
        except Exception:
            print('Error in the on_enter function!')
Ejemplo n.º 30
0
class DeviceBox(BoxLayout):
	
	nexa_controllers = ['Nexa3ButtonRemote',
						'Nexa2ButtonSwitch']
	
	nexa_sensors = ['NexaOpeningSensor',
					'NexaMovementSensor']
	
	nexa_devices = ['NexaDevice']
	
	def __init__(self, json_device, *args, **kwargs):
		super(DeviceBox, self).__init__(*args, **kwargs)
		
		self.app = App.get_running_app()
		
		print 'building device box'
		print json_device
		print '\n'
		
		self.maj_id = json_device['id']
		self.model = json_device['device_key']
		self.name = json_device['name']
		
		self.orientation = 'vertical'
		self.add_widget(Label(text = self.name,
							  text_size = (self.width-dp(10), 35)))
		
		if self.model in self.nexa_controllers:
			self.switches = []
			for switch in json_device['switches']:
				if switch['state'] != None:	state = switch['state']
				else: state = False
				new_switch = Switch(id = switch['id'], active = state, disabled = True) 
				self.switches.append(new_switch)
				self.add_widget(new_switch)
		elif self.model in self.nexa_sensors:
			self.last_activated = Label(text = json_device['last_activated'],
									    size_hint = (None, 1),
									    text_size = (self.width-dp(10), 100),
									    pos_hint = {'center_x': 0.5})
			self.add_widget(self.last_activated)
		elif self.model in self.nexa_devices:
			self.switch = Switch(id = json_device['id'])
			self.switch.bind(active = self.user_action)
			self.add_widget(self.switch)
		
	def update(self, json_update):
		
		if self.model in self.nexa_controllers:
			for switch in json_update['switches']:
				for my_switch in self.switches:
					if switch['id'] == my_switch.id:
						if switch['state'] != None:
							my_switch.active = switch['state']
		elif self.model in self.nexa_sensors:
			self.last_activated.text = json_update['last_activated']
		elif self.model in self.nexa_devices:
			if json_update['state'] != None:
				self.switch.unbind(active = self.user_action)
				self.switch.active = json_update['state']
				self.switch.bind(active = self.user_action)

	def user_action(self, instance, value):
		
		print 'sending action request'
		print {'command': 'device_action',
			   'model': self.model,
			   'id': instance.id}
		
		self.app.send_request(None,
							  {'command': 'device_action',
							   'model': self.model,
							   'id': instance.id})
Ejemplo n.º 31
0
class InteractionScreen(
        Screen
):  #This is the main screen for drawing and user input. Next steps include nesting layouts and adding/binding buttons
    def __init__(self, **kwargs):
        super(InteractionScreen, self).__init__(**kwargs)

        ### CREATE LAYOUTS

        self.layout = FloatLayout(
        )  #creates a Float Layout called self.layout  (self. allows reference for entire class?)
        self.layout.width = Window.width
        self.layout.height = Window.height
        self.layout.x = 0
        self.layout.y = 0

        self.rightlayout = FloatLayout(
        )  #creates Float Layout for object selector, speed and angle labels, go button
        self.rightlayout.width = self.layout.width * (1. / 6.)
        self.rightlayout.height = self.layout.height
        self.rightlayout.x = Window.width - self.rightlayout.width
        self.rightlayout.y = Window.height / 2 - self.rightlayout.height / 2

        self.leftlayout = FloatLayout(
        )  # float layout for drawing area and background images
        self.leftlayout.width = self.layout.width * (5. / 6.)
        self.leftlayout.height = self.layout.height
        self.leftlayout.x = 0  #Window.width - self.centerlayout.width
        self.leftlayout.y = 0  #Window.width/2 - self.centerlayout.height/2

        with self.rightlayout.canvas:  #sets canvas instructions for the rightlayout and draws a blue rect. filling the entire layout
            Color(0, 0, .5, 1)  #BLUE
            Rectangle(pos=(self.rightlayout.x, self.rightlayout.y),
                      size=(self.rightlayout.width, self.rightlayout.height))

        ### LEFT LAYOUT CONTENT

        # DRAWING FUNCTIONALITY
        global drawUtility
        drawUtility = DrawingApp()
        drawUtility.size_hint = (5. / 6., 1)
        self.leftlayout.add_widget(drawUtility, 0)
        self.layout.add_widget(self.leftlayout, 2)
        self.layout.add_widget(self.rightlayout)
        self.add_widget(self.layout)

        # DEFAULT BACKGROUND IMAGE
        self.bg_image_default = Image(source=assetsdirectory +
                                      str('starfield.jpg'))
        self.bg_image_default.allow_stretch = True
        self.bg_image_default.keep_ratio = False
        self.bg_image_default.size_hint = ((5. / 6.), 1)
        self.bg_image_default.pos = (0, 0)
        self.bg_image_default.opacity = 1.0
        self.leftlayout.add_widget(self.bg_image_default,
                                   1)  #ADDS DEFAULT BACKGROUND IMAGE

        # BACKGROUND IMAGE UPDATE FUNCTION
        self.imageNumber = 1  #default image number
        self.event = Clock.schedule_interval(
            self.imageUpdate,
            1.0 / 5.0)  #SCHEDULES THE IMAGE UPDATING TO OCCUR

        # HOME BUTTON AND IMAGE
        homeBtn = Button(text='',
                         size_hint=((1. / 24.), (.06)),
                         pos_hint={
                             'x': 0,
                             'y': .94
                         },
                         opacity=.5)  #back button to the interaction screen
        homeBtn.bind(
            on_press=self.changer
        )  #binds this button to change the screen back to the welcome screen
        self.layout.add_widget(homeBtn,
                               0)  #adds the button to the float layout

        self.homeImage = Image(
            source=assetsdirectory + str('explosion1.png')
        )  # adds slightly transparent home icon over the back button
        self.homeImage.size_hint = ((1. / 24.), .06)
        self.homeImage.pos_hint = {'x': 0, 'y': .94}
        self.homeImage.opacity = .5
        self.layout.add_widget(self.homeImage)

        ### RIGHT LAYOUT CONTENT

        # OBJECT BUTTON (Must be in same order for correct layout)
        objButton = Spinner(text='PLEASE SELECT\nAN OBJECT',
                            halign='center',
                            font_size='18',
                            values=('Particle', 'Planet', 'Comet', 'Star',
                                    'Black Hole',
                                    'Elephant'))  # object spinner
        objButton.pos_hint = {'x': 0, 'y': .8}
        objButton.size_hint = ((1. / 6.), .2)
        objButton.background_color = [.4, .4, .4, 1]
        self.rightlayout.add_widget(objButton, 0)

        # TOPOGRAPHY TOGGLE SWITCH
        self.topoSwitch = Switch(
            active=True
        )  # switch to toggle between updating topography and static star field
        self.topoSwitch.pos_hint = {'x': 0, 'y': .6}
        self.topoSwitch.size_hint = ((1. / 6.), .15)
        self.topoSwitch.background_color = [.4, .4, .4, 1]
        self.rightlayout.add_widget(self.topoSwitch)

        self.topoSwitch.bind(
            active=self.topoChange)  # bind switch to topoChange function

        # SPEED LABEL
        self.spdLabel = Label(text='Speed:\n' + str(drawUtility.speed),
                              font_size='20',
                              halign='center')  # label showing current speed
        self.spdLabel.pos_hint = {'x': 0, 'y': .4}
        self.spdLabel.size_hint = ((1. / 6.), .2)
        self.spdLabel.background_color = [.4, .4, .4, 1]
        self.rightlayout.add_widget(self.spdLabel)

        def update_speed(
                value, instance):  # callback function to bind speed to vector
            self.spdLabel.text = 'Speed:\n' + str(drawUtility.speed)

        drawUtility.bind(speed=update_speed)  # bind speed to vector length

        # ANGLE LABEL
        self.angLabel = Label(text='Angle:\n' + str(drawUtility.angle),
                              font_size='20',
                              halign='center')  # label showing current angle
        self.angLabel.pos_hint = {'x': 0, 'y': .2}
        self.angLabel.size_hint = ((1. / 6.), .2)
        self.angLabel.background_color = [.4, .4, .4, 1]
        self.rightlayout.add_widget(self.angLabel)

        def update_angle(
                value, instance):  # callback function to bind angle to vector
            self.angLabel.text = 'Angle:\n' + str(drawUtility.angle)

        drawUtility.bind(angle=update_angle)  # bind angle to vector

        # GO BUTTON
        self.goButton = MyButton(
            text='Go!')  # go button to send user input to algorithm
        self.goButton.pos_hint = {'x': 0, 'y': 0}
        self.goButton.size_hint = ((1. / 6.), .2)
        self.goButton.background_color = [.4, .4, .4, 1]
        self.goButton.bind(
            on_release=self.userInput
        )  # when the button is released the USERINPUT function is called
        self.rightlayout.add_widget(self.goButton)

    ### FUNCTIONS

    def massSelect(self, *args):
        print('Mass Selector Function called')

    def userInput(
            self, *args
    ):  # function to save user input and take output from algorithm

        name_of_file = 'algorithm_input'  # USER INPUT FILENAME
        inputFileName = os.path.join(assetsdirectory,
                                     name_of_file + '.txt')  #TOTAL PATH NAME

        with open(
                inputFileName, 'w'
        ) as f:  # create file and write initial and final coordinate positions
            f.write('%f\t%f\t%f\t%f' %
                    (drawUtility.x_initial, drawUtility.y_initial,
                     drawUtility.x_final, drawUtility.y_final))

        drawUtility.canvas.clear()
        particle = Particle(
            pos=(drawUtility.x_initial, drawUtility.y_initial),
            size=(10, 10))  # draw a particle at chosen initial position
        drawUtility.add_widget(particle)

        while os.path.isfile(
                'algorithm_output.npy') == False:  # search for output file
            sleep(1)
            print("Still no file")
        else:
            x = np.load('mylistx.npy')
            xs = np.split(x,
                          len(x) / 200, 0)  # test data
            y = np.load('mylisty.npy')
            ys = np.split(y,
                          len(y) / 200, 0)
            print("File found!")

            #x,y = np.load('algorithm_output.npy') # load in algorithm output
            #xs = np.split(x, len(x)/200, 0); ys = np.split(y, len(y)/200, 0) # split x and y arrays into manageable chunks for animation

            self.animate(xs, ys, 0,
                         particle)  # call animation function with output data

    def animate(self, x_coords, y_coords, index,
                instance):  # function to animate particle through orbit

        if index < len(x_coords):  # check if reached last coordinate chunk

            animation = Animation(
                pos=(int(x_coords[index][0]), int(y_coords[index][0])),
                t='linear',
                duration=.02
            )  # create animation instance beginning at first coordinate of chunk

            for i in np.arange(
                    1, len(x_coords[index])
            ):  # add all points in chunk to animation instance in sequence
                animation += Animation(pos=(int(x_coords[index][i]),
                                            int(y_coords[index][i])),
                                       t='linear',
                                       duration=.02)

            animation.bind(
                on_complete=lambda x, y:
                (self.animate(x_coords, y_coords, index + 1, instance)
                 ))  # once one chunk is animated, animate next
            animation.start(instance)  # begin animation

    def changer(self, *args):  # function to go back to home screen
        self.manager.current = 'screen1'
        self.manager.transition.direction = 'right'

    def topoChange(
            self, instance,
            value):  # function for turning updating topography on and off

        if self.topoSwitch.active == True:  # if topography active, call image update function once every .2 seconds
            self.event = Clock.schedule_interval(self.imageUpdate, 1.0 / 5.0)
        elif self.topoSwitch.active == False:  # if topography not active,
            self.event.cancel()  # cancel clock event
            self.leftlayout.remove_widget(
                self.bg_image)  # remove the updating background image widget
            self.leftlayout.add_widget(self.bg_image_default,
                                       1)  # add default image widget

    def imageUpdate(self, dt):  # function for live topography updating

        #TESTING MULTIPLE IMAGE UPDATE
        try:
            self.leftlayout.remove_widget(
                self.bg_image_default
            )  # try to remove both image widgets, ensures proper layering of widgets
            self.leftlayout.remove_widget(self.bg_image)
        except:
            pass

        self.imageNumber ^= 1
        imageStr = assetsdirectory + str('color_field_') + str(
            self.imageNumber) + '.jpg'  # randomly choose sandstone image
        #print('imageNumber: %s' % self.imageNumber)

        self.bg_image = Image(source=imageStr)
        self.bg_image.allow_stretch = True
        self.bg_image.keep_ratio = False
        self.bg_image.size_hint = ((5. / 6.), 1)
        self.bg_image.pos = (0, 0)
        self.bg_image.opacity = 1.0
        #self.bg_image.reload()

        self.leftlayout.add_widget(self.bg_image,
                                   1)  # add topography image widget
Ejemplo n.º 32
0
class MainBox(BoxLayout):
    '''
    Mainbox class
    '''

    def __init__(self, **kwargs):
        '''
        Init main class ui
        '''
        super(MainBox, self).__init__(**kwargs)
        self.f_size = '15sp'

        # Shape Widget
        self.shape = Shape(size_hint=(0.7, 1))
        self.add_widget(self.shape)

        # Right Menu
        self.panel = TabbedPanel(size_hint=(0.3, 1), do_default_tab=False)
        self.tab_param = TabbedPanelItem(text='Parameters')
        self.tab_color = TabbedPanelItem(text='Shape')
        self.tab_color_bg = TabbedPanelItem(text='Background')
        self.tab_export = TabbedPanelItem(text='Export')
        self.panel.add_widget(self.tab_param)
        self.panel.add_widget(self.tab_color)
        self.panel.add_widget(self.tab_color_bg)
        self.panel.add_widget(self.tab_export)

        self.menu_right = RightMenu(
            padding=15,
            orientation="vertical")

        # Switch mode line
        self.box_switch = BoxLayout(orientation='horizontal')
        self.mode_label = Label(
            text="Line mode",
            font_size=self.f_size,
            markup=True)
        self.box_switch.add_widget(self.mode_label)
        self.switch_mode = Switch(active=False)
        self.switch_mode.bind(active=self.on_switch)
        self.box_switch.add_widget(self.switch_mode)
        self.menu_right.add_widget(self.box_switch)

        # Size value
        self.box_size = BoxLayout(orientation='horizontal')
        self.size_label = Label(
            text="Shape size",
            font_size=self.f_size,
            markup=True)
        self.size_label_value = Label(
            text=str(self.shape.shape_size),
            font_size=self.f_size,
            markup=True)
        self.box_size.add_widget(self.size_label)
        self.box_size.add_widget(self.size_label_value)
        self.slider_shape_size = Slider(
            min=self.shape.property('shape_size').get_min(self.shape),
            max=self.shape.property('shape_size').get_max(self.shape),
            value=self.shape.shape_size, step=1)
        self.slider_shape_size.bind(value=self.change_shape_size)
        self.menu_right.add_widget(self.box_size)
        self.menu_right.add_widget(self.slider_shape_size)

        # Width point or line
        self.box_stroke = BoxLayout(orientation='horizontal')
        self.wdth_label = Label(
            text="Stroke width",
            font_size=self.f_size,
            markup=True)
        self.wdth_label_value = Label(
            text=str(self.shape.wdth),
            font_size=self.f_size,
            markup=True)
        self.box_stroke.add_widget(self.wdth_label)
        self.box_stroke.add_widget(self.wdth_label_value)
        self.slider_wdth = Slider(
            min=self.shape.property('wdth').get_min(self.shape),
            max=self.shape.property('wdth').get_max(self.shape),
            value=self.shape.wdth, step=1)
        self.slider_wdth.bind(value=self.change_wdth)
        self.menu_right.add_widget(self.box_stroke)
        self.menu_right.add_widget(self.slider_wdth)

        # a value
        self.box_a = BoxLayout(orientation='horizontal')
        self.a_label = Label(
            text="Param a ",
            font_size=self.f_size,
            markup=True)
        self.a_label_value = Label(
            text=str(self.shape.a),
            font_size=self.f_size,
            markup=True)
        self.box_a.add_widget(self.a_label)
        self.box_a.add_widget(self.a_label_value)
        self.slider_a = Slider(
            min=self.shape.property('a').get_min(self.shape),
            max=self.shape.property('a').get_max(self.shape),
            value=self.shape.a)
        self.slider_a.bind(value=self.change_a)
        self.menu_right.add_widget(self.box_a)
        self.menu_right.add_widget(self.slider_a)

        # b value
        self.box_b = BoxLayout(orientation='horizontal')
        self.b_label = Label(
            text="Param b ",
            font_size=self.f_size,
            markup=True)
        self.b_label_value = Label(
            text=str(self.shape.b),
            font_size=self.f_size,
            markup=True)
        self.box_b.add_widget(self.b_label)
        self.box_b.add_widget(self.b_label_value)
        self.slider_b = Slider(
            min=self.shape.property('b').get_min(self.shape),
            max=self.shape.property('b').get_max(self.shape),
            value=self.shape.b)
        self.slider_b.bind(value=self.change_b)
        self.menu_right.add_widget(self.box_b)
        self.menu_right.add_widget(self.slider_b)

        # m value
        self.box_m = BoxLayout(orientation='horizontal')
        self.m_label = Label(
            text="Param m ",
            font_size=self.f_size,
            markup=True)
        self.m_label_value = Label(
            text=str(self.shape.m),
            font_size=self.f_size,
            markup=True)
        self.box_m.add_widget(self.m_label)
        self.box_m.add_widget(self.m_label_value)
        self.slider_m = Slider(
            min=self.shape.property('m').get_min(self.shape),
            max=self.shape.property('m').get_max(self.shape),
            value=self.shape.m)
        self.slider_m.bind(value=self.change_m)
        self.menu_right.add_widget(self.box_m)
        self.menu_right.add_widget(self.slider_m)

        # n1 value
        self.box_n1 = BoxLayout(orientation='horizontal')
        self.n1_label = Label(
            text="Param n1 ",
            font_size=self.f_size,
            markup=True)
        self.n1_label_value = Label(
            text=str(self.shape.n1),
            font_size=self.f_size,
            markup=True)
        self.box_n1.add_widget(self.n1_label)
        self.box_n1.add_widget(self.n1_label_value)
        self.slider_n1 = Slider(
            min=self.shape.property('n1').get_min(self.shape),
            max=self.shape.property('n1').get_max(self.shape),
            value=self.shape.n1)
        self.slider_n1.bind(value=self.change_n1)
        self.menu_right.add_widget(self.box_n1)
        self.menu_right.add_widget(self.slider_n1)

        # n2 value
        self.box_n2 = BoxLayout(orientation='horizontal')
        self.n2_label = Label(
            text="Param n2 ",
            font_size=self.f_size,
            markup=True)
        self.n2_label_value = Label(
            text=str(self.shape.n2),
            font_size=self.f_size,
            markup=True)
        self.box_n2.add_widget(self.n2_label)
        self.box_n2.add_widget(self.n2_label_value)
        self.slider_n2 = Slider(
            min=self.shape.property('n2').get_min(self.shape),
            max=self.shape.property('n2').get_max(self.shape),
            value=self.shape.n2)
        self.slider_n2.bind(value=self.change_n2)
        self.menu_right.add_widget(self.box_n2)
        self.menu_right.add_widget(self.slider_n2)

        # n3 value
        self.box_n3 = BoxLayout(orientation='horizontal')
        self.n3_label = Label(
            text="Param n3 ",
            font_size=self.f_size,
            markup=True)
        self.n3_label_value = Label(
            text=str(self.shape.n3),
            font_size=self.f_size,
            markup=True)
        self.box_n3.add_widget(self.n3_label)
        self.box_n3.add_widget(self.n3_label_value)
        self.slider_n3 = Slider(
            min=self.shape.property('n3').get_min(self.shape),
            max=self.shape.property('n3').get_max(self.shape),
            value=self.shape.n3)
        self.slider_n3.bind(value=self.change_n3)
        self.menu_right.add_widget(self.box_n3)
        self.menu_right.add_widget(self.slider_n3)

        # Nb points
        self.box_nbp = BoxLayout(orientation='horizontal')
        self.nbp_label = Label(
            text="Points number ",
            font_size=self.f_size,
            markup=True)
        self.nbp_label_value = Label(
            text=str(self.shape.nbp),
            font_size=self.f_size,
            markup=True)
        self.box_nbp.add_widget(self.nbp_label)
        self.box_nbp.add_widget(self.nbp_label_value)
        self.slider_nbp = Slider(
            min=self.shape.property('nbp').get_min(self.shape),
            max=self.shape.property('nbp').get_max(self.shape),
            value=self.shape.nbp, step=2)
        self.slider_nbp.bind(value=self.change_nbp)
        self.menu_right.add_widget(self.box_nbp)
        self.menu_right.add_widget(self.slider_nbp)

        # Percent
        self.box_percent = BoxLayout(orientation='horizontal')
        self.percent_label = Label(
            text="Percent ",
            font_size=self.f_size,
            markup=True)
        self.percent_label_value = Label(
            text=str(self.shape.percent),
            font_size=self.f_size,
            markup=True)
        self.box_percent.add_widget(self.percent_label)
        self.box_percent.add_widget(self.percent_label_value)
        self.slider_percent = Slider(
            min=self.shape.property('percent').get_min(self.shape),
            max=self.shape.property('percent').get_max(self.shape),
            value=self.shape.percent, step=1)
        self.slider_percent.bind(value=self.change_percent)
        self.menu_right.add_widget(self.box_percent)
        self.menu_right.add_widget(self.slider_percent)

        # Travel
        self.box_travel = BoxLayout(orientation='horizontal')
        self.travel_label = Label(
            text="Travel ",
            font_size=self.f_size,
            markup=True)
        self.travel_label_value = Label(
            text=str(self.shape.travel),
            font_size=self.f_size,
            markup=True)
        self.box_travel.add_widget(self.travel_label)
        self.box_travel.add_widget(self.travel_label_value)
        self.slider_travel = Slider(
            min=self.shape.property('travel').get_min(self.shape),
            max=self.shape.property('travel').get_max(self.shape),
            value=self.shape.travel, step=2)
        self.slider_travel.bind(value=self.change_travel)
        self.menu_right.add_widget(self.box_travel)
        self.menu_right.add_widget(self.slider_travel)

        # ColorPicker for Shape
        self.picker = ColorPicker()
        self.picker.bind(color=self.on_color)

        # ColorPicker for background
        self.picker_bg = ColorPicker()
        self.picker_bg.bind(color=self.on_color_bg)

        # Export svg button
        self.export_button = Button(text='Export', size_hint=(1, 0.15))
        self.export_button.bind(on_press=self.export)

        # Tab packs
        self.tab_param.add_widget(self.menu_right)
        self.tab_color.add_widget(self.picker)
        self.tab_color_bg.add_widget(self.picker_bg)
        self.tab_export.add_widget(self.export_button)
        self.add_widget(self.panel)

        # Popups
        self.pop_export = Popup(
            title="Export file",
            content=Label(text="File exported"),
            size_hint=(None, None),
            size=(640, 240))

    def change_wdth(self, *args):
        '''
        Change stroke width
        '''
        self.shape.wdth = self.slider_wdth.value
        self.wdth_label_value.text = str(self.slider_wdth.value)

    def on_switch(self, *args):
        '''
        Switch mode line or point
        '''
        self.shape.line = self.switch_mode.active

    def on_color(self, *args):
        '''
        Shape color
        '''
        self.shape.color = self.picker.hex_color

    def on_color_bg(self, *args):
        '''
        Shape background color
        '''
        self.shape.bg_color = self.picker_bg.hex_color

    def change_shape_size(self, *args):
        '''
        Shape size
        '''
        self.shape.shape_size = self.slider_shape_size.value
        self.size_label_value.text = str(self.slider_shape_size.value)

    def change_a(self, *args):
        '''
        a value
        '''
        self.shape.a = self.slider_a.value
        self.a_label_value.text = str(self.slider_a.value)

    def change_b(self, *args):
        '''
        b value
        '''
        self.shape.b = self.slider_b.value
        self.b_label_value.text = str(self.slider_b.value)

    def change_m(self, *args):
        '''
        m value
        '''
        self.shape.m = self.slider_m.value
        self.m_label_value.text = str(self.slider_m.value)

    def change_n1(self, *args):
        '''
        n1 value
        '''
        self.shape.n1 = self.slider_n1.value
        self.n1_label_value.text = str(self.slider_n1.value)

    def change_n2(self, *args):
        '''
        n2 value
        '''
        self.shape.n2 = self.slider_n2.value
        self.n2_label_value.text = str(self.slider_n2.value)

    def change_n3(self, *args):
        '''
        n3 value
        '''
        self.shape.n3 = self.slider_n3.value
        self.n3_label_value.text = str(self.slider_n3.value)

    def change_nbp(self, *args):
        '''
        point number
        '''
        self.shape.nbp = self.slider_nbp.value
        self.nbp_label_value.text = str(self.slider_nbp.value)

    def change_percent(self, *args):
        '''
        Percent value
        '''
        self.shape.percent = self.slider_percent.value
        self.percent_label_value.text = str(self.slider_percent.value)

    def change_travel(self, *args):
        '''
        Travel number
        '''
        self.shape.travel = self.slider_travel.value
        self.travel_label_value.text = str(self.slider_travel.value)

    def export(self, *args):
        '''
        Export to svg file
        '''
        document = svgwrite.Drawing(filename='export.svg', debug=True)
        tmp = [(float("%.4g" % e)) for e in self.shape.path]
        # Export polygon
        if self.shape.line:
            svg_path = coupled(tmp)
            document.add(document.polygon(points=svg_path))
        else:  # Export points
            svg_path = coupled(coupled(tmp))
            for elem in svg_path:
                document.add(document.line(
                    start=elem[0],
                    end=elem[1]
                ))
        document.save()
        self.shape.export_to_png('export.png')
        self.pop_export.open()
Ejemplo n.º 33
0
class InteractionScreen(
        Screen
):  #This is the main screen for drawing and user input. Next steps include nesting layouts and adding/binding buttons
    def __init__(self, **kwargs):
        super(InteractionScreen, self).__init__(**kwargs)
        self.INTERVAL = 2.6  #THIS INTERVAL IS USED FOR SYNCING IMAGE UPDATING W/ ALGORITHM

        ### CREATE LAYOUTS

        self.layout = FloatLayout(
        )  #creates a Float Layout called self.layout  (self. allows reference for entire class?)
        self.layout.width = Window.width
        self.layout.height = Window.height
        self.layout.x = 0
        self.layout.y = 0

        self.rightlayout = FloatLayout(
        )  #creates Float Layout for object selector, speed and angle labels, go button
        self.rightlayout.width = self.layout.width * (1. / 6.)
        self.rightlayout.height = self.layout.height
        self.rightlayout.x = Window.width - self.rightlayout.width
        self.rightlayout.y = Window.height / 2 - self.rightlayout.height / 2

        self.leftlayout = FloatLayout(
        )  # float layout for drawing area and background images
        self.leftlayout.width = self.layout.width * (5. / 6.)
        self.leftlayout.height = self.layout.height
        self.leftlayout.x = 0  #Window.width - self.centerlayout.width
        self.leftlayout.y = 0  #Window.width/2 - self.centerlayout.height/2

        with self.rightlayout.canvas:  #sets canvas instructions for the rightlayout and draws a blue rect. filling the entire layout
            Color(.125, .184, .31, 1)  #BLUE
            Rectangle(pos=(self.rightlayout.x, self.rightlayout.y),
                      size=(self.rightlayout.width, self.rightlayout.height))

        ### LEFT LAYOUT CONTENT

        # DRAWING FUNCTIONALITY
        global drawUtility
        drawUtility = DrawingApp()
        drawUtility.size_hint = (5. / 6., 1)
        self.leftlayout.add_widget(drawUtility, 0)
        self.layout.add_widget(self.leftlayout, 2)
        self.layout.add_widget(self.rightlayout)
        self.add_widget(self.layout)

        # DEFAULT BACKGROUND IMAGE
        self.bg_image_default = Image(source=assetsdirectory +
                                      str('starfield.jpg'))
        self.bg_image_default.allow_stretch = True
        self.bg_image_default.keep_ratio = False
        self.bg_image_default.size_hint = ((5. / 6.), 1)
        self.bg_image_default.pos = (0, 0)
        self.bg_image_default.opacity = 1.0
        self.leftlayout.add_widget(self.bg_image_default,
                                   1)  #ADDS DEFAULT BACKGROUND IMAGE

        #### BACKGROUND IMAGE UPDATE FUNCTION

        self.imageNumber = 1  #default image number, used in XOR function to alternate images in imageUpdate function
        self.event = Clock.schedule_interval(
            self.imageUpdate, self.INTERVAL
        )  #SCHEDULES THE IMAGE UPDATING TO OCCUR, INTERVAL DEFINED AT START OF CLASS

        ### RIGHT LAYOUT CONTENT

        # HOME BUTTON
        homeButton = Button(text='HOME', font_size='25sp')
        homeButton.pos_hint = {'x': 0, 'y': .8}
        homeButton.color = [.937, .804, .769, 1]
        homeButton.size_hint = ((1. / 6.), .2)
        homeButton.background_color = [.353, .396, .522, 1]
        homeButton.bind(on_press=self.changer)
        self.rightlayout.add_widget(homeButton, 0)

        # TOPOGRAPHY LABEL
        self.topoLabel = Label(text='TOPOGRAPHY', halign='center')
        self.topoLabel.pos_hint = {'x': 0, 'y': .65}
        self.topoLabel.color = [.937, .804, .769, 1]
        self.topoLabel.font_size = '17sp'
        self.topoLabel.size_hint = ((.1 / .6), .2)
        self.topoLabel.background_color = [.353, .396, .522, 1]
        self.rightlayout.add_widget(self.topoLabel)

        # TOPOGRAPHY TOGGLE SWITCH
        self.topoSwitch = Switch(
            active=True
        )  # switch to toggle between updating topography and static star field
        self.topoSwitch.pos_hint = {'x': 0, 'y': .6}
        self.topoSwitch.size_hint = ((1. / 6.), .15)
        self.topoSwitch.background_color = [.125, .184, .31, 1]
        self.rightlayout.add_widget(self.topoSwitch)

        self.topoSwitch.bind(
            active=self.topoChange)  # bind switch to topoChange function

        # SPEED LABEL
        self.spdLabel = Label(text='SPEED:\n' + str(drawUtility.speed),
                              halign='center')  # label showing current speed
        self.spdLabel.pos_hint = {'x': 0, 'y': .4}
        self.spdLabel.font_size = '17sp'
        self.spdLabel.color = [.937, .804, .769, 1]
        self.spdLabel.size_hint = ((1. / 6.), .2)
        self.spdLabel.background_color = [.4, .4, .4, 1]
        self.rightlayout.add_widget(self.spdLabel)

        def update_speed(
                value, instance):  # callback function to bind speed to vector
            self.spdLabel.text = 'SPEED:\n' + str(drawUtility.speed)

        drawUtility.bind(speed=update_speed)  # bind speed to vector length

        # ANGLE LABEL
        self.angLabel = Label(text='ANGLE:\n' + str(drawUtility.angle),
                              halign='center')  # label showing current angle
        self.angLabel.pos_hint = {'x': 0, 'y': .2}
        self.angLabel.font_size = '17sp'
        self.angLabel.size_hint = ((1. / 6.), .2)
        self.angLabel.color = [.937, .804, .769, 1]
        self.angLabel.background_color = [.4, .4, .4, 1]
        self.rightlayout.add_widget(self.angLabel)

        def update_angle(
                value, instance):  # callback function to bind angle to vector
            self.angLabel.text = 'ANGLE:\n' + str(drawUtility.angle)

        drawUtility.bind(angle=update_angle)  # bind angle to vector

        # GO! BUTTON
        self.goButton = MyButton(
            text='GO!')  # go button to send user input to algorithm
        self.goButton.pos_hint = {'x': 0, 'y': 0}
        self.goButton.font_size = '30sp'
        self.goButton.size_hint = ((1. / 6.), .2)
        self.goButton.color = [.937, .804, .769, 1]
        self.goButton.background_color = [.353, .396, .522, 1]
        self.goButton.bind(
            on_release=self.userInput
        )  # when the button is released the USERINPUT function is called
        self.rightlayout.add_widget(self.goButton)

    ### FUNCTIONS

    def userInput(
            self, *args
    ):  # function to save user input and take output from algorithm

        name_of_file = 'algorithm_input'  # USER INPUT FILENAME
        inputFileName = os.path.join(assetsdirectory,
                                     name_of_file + '.txt')  #TOTAL PATH NAME

        with open(
                inputFileName, 'w'
        ) as f:  # create file and write initial and final coordinate positions
            f.write('%f\t%f\t%f\t%f' %
                    (drawUtility.x_initial, drawUtility.y_initial,
                     drawUtility.x_final, drawUtility.y_final))

        drawUtility.canvas.clear()
        particle = Particle(
            pos=(drawUtility.x_initial, drawUtility.y_initial),
            size=(10, 10))  # draw a particle at chosen initial position
        drawUtility.add_widget(particle)

        while os.path.isfile(
                'algorithm_output.npy') == False:  # search for output file
            sleep(1)
            print("Still no file")
        else:
            #x = np.load('mylistx.npy'); xs = np.split(x, len(x)/200, 0) # test data
            #y = np.load('mylisty.npy'); ys = np.split(y, len(y)/200, 0)
            print("File found!")

            x, y = np.load('algorithm_output.npy')  # load in algorithm output
            xs = np.split(x,
                          len(x) / 200, 0)
            ys = np.split(
                y,
                len(y) / 200,
                0)  # split x and y arrays into manageable chunks for animation

            #self.animate(xs, ys, 0, particle) # call animation function with output data

    '''        
    def animate(self, x_coords, y_coords, index, instance): # function to animate particle through orbit
        
        if index < len(x_coords): # check if reached last coordinate chunk
            
            animation = Animation(pos=(int(x_coords[index][0]), int(y_coords[index][0])), t='linear', duration=.02) # create animation instance beginning at first coordinate of chunk
            
            for i in np.arange(1, len(x_coords[index])): # add all points in chunk to animation instance in sequence
                animation += Animation(pos=(int(x_coords[index][i]), int(y_coords[index][i])), t='linear', duration=.02)
                
            animation.bind(on_complete=lambda x, y: (self.animate(x_coords, y_coords, index+1, instance))) # once one chunk is animated, animate next
            animation.start(instance) # begin animation     
    '''

    def changer(self, *args):  # function to go back to home screen
        self.manager.current = 'screen1'
        self.manager.transition.direction = 'right'

    def topoChange(
            self, instance,
            value):  # function for turning updating topography on and off

        if self.topoSwitch.active == True:  # if topography active, call image update function once every .2 seconds
            self.event = Clock.schedule_interval(self.imageUpdate,
                                                 self.INTERVAL)
        elif self.topoSwitch.active == False:  # if topography not active,
            self.event.cancel()  # cancel clock event
            self.leftlayout.remove_widget(
                self.bg_image)  # remove the updating background image widget
            self.leftlayout.add_widget(self.bg_image_default,
                                       1)  # add default image widget

    def imageUpdate(self, dt):  # function for live topography updating

        #TESTING MULTIPLE IMAGE UPDATE
        try:
            self.leftlayout.remove_widget(
                self.bg_image_default
            )  # try to remove both image widgets, ensures proper layering of widgets
            self.leftlayout.remove_widget(self.bg_image)
        except:
            pass

        self.imageNumber ^= 1  # XOR function for switching background images between color_field_0 and color_field_1
        imageStr = assetsdirectory + str('color_field_') + str(
            self.imageNumber) + '.jpg'  #color_field_ + 1 or 0
        #print('imageNumber: %s' % self.imageNumber)

        self.bg_image = Image(source=imageStr)
        self.bg_image.allow_stretch = True
        self.bg_image.keep_ratio = False
        self.bg_image.size_hint = ((5. / 6.), 1)
        self.bg_image.pos = (0, 0)
        self.bg_image.opacity = 1.0
        self.bg_image.nocache = True
        #self.bg_image.reload()

        self.leftlayout.add_widget(self.bg_image,
                                   1)  # add topography image widget
Ejemplo n.º 34
0
class Anritsu(AbstractSource):
    def __init__(self, **kwargs):
        super(Anritsu, self).__init__(kwargs=kwargs)

        self.is_source_active = False

        on_off_label = Label(text="Use Source")
        self.on_off_switch = Switch(active=False)
        self.on_off_switch.bind(active=self.on_off)

        on_off_layout = BoxLayout(orientation="horizontal", size_hint=(1, None), size=(1, 40))
        on_off_layout.add_widget(on_off_label)
        on_off_layout.add_widget(self.on_off_switch)

        init_frec_label = Label(text="Frequency")
        self.init_frec_value = TextInput(multiline=False)
        self.init_frec_value.disabled = True
        self.init_frec_value.text = "0.0"
        self.init_frec_unit = UnitSpinner(UnitSpinner.hz)

        amplitud_frec_label = Label(text="Power")
        self.amplitud_frec_value = TextInput(multiline=False)
        self.amplitud_frec_value.disabled = True
        self.amplitud_frec_value.bind(text=self._check_input_number)
        self.amplitud_frec_unit = UnitSpinner(UnitSpinner.db)

        buttons_configuration = GridLayout(cols=3, row_force_default=True, row_default_height=40)

        buttons_configuration.add_widget(init_frec_label)
        buttons_configuration.add_widget(self.init_frec_value)
        buttons_configuration.add_widget(self.init_frec_unit)

        buttons_configuration.add_widget(amplitud_frec_label)
        buttons_configuration.add_widget(self.amplitud_frec_value)
        buttons_configuration.add_widget(self.amplitud_frec_unit)

        main_layout = BoxLayout(orientation="vertical")
        main_layout.add_widget(on_off_layout)
        main_layout.add_widget(buttons_configuration)

        self.add_widget(main_layout)

    def do_sweep(self):
        return False

    def is_active(self):
        return self.is_source_active

    def get_source_config(self):
        return_dic = {}

        return_dic["ip_direction"] = "TCPIP0::192.168.1.36::inst0::INSTR"
        return_dic["power"] = self.amplitud_frec_value.text
        return_dic["frequency"] = float(self.init_frec_value.text) * self.init_frec_unit.get_unit_norm()

        return_dic["instance"] = AnritsuTone

        return return_dic

    def save_config_dictionary(self):
        data_dic = {}

        data_dic["active"] = self.is_source_active
        data_dic["power"] = self.amplitud_frec_value.text
        data_dic["frequency"] = float(self.init_frec_value.text) * self.init_frec_unit.get_unit_norm()

        return {self.get_my_name(): data_dic}

    def get_my_name(self):
        return "Anritsu"

    def set_configuration(self, config_dictionary):

        if self.get_my_name() in config_dictionary:
            config_dictionary_ = config_dictionary[self.get_my_name()]
            self.is_source_active = config_dictionary_["active"]
            self.on_off_switch.active = self.is_source_active
            self.amplitud_frec_value.text = config_dictionary_["power"]
            self.init_frec_value.text = str(config_dictionary_["frequency"])
            self.init_frec_unit.text = "Hz"

    def on_off(self, spinner, text):
        self.is_source_active = text

        self.init_frec_value.disabled = not text
        self.amplitud_frec_value.disabled = not text

    def _check_input_number(self, instance, value):
        try:
            if len(value) > 0:
                float(value)

        except ValueError:
            if not value == "-":
                instance.text = value[0:-1]
                popup = Popup(
                    title="Error",
                    content=Label(text="Mal valor,\nsolo numeros"),
                    size_hint=(None, None),
                    size=(120, 100),
                )
                popup.open()
Ejemplo n.º 35
0
class VpnApp(App):

    def __init__(self, **kwargs):
        super(VpnApp, self).__init__(**kwargs)
        self.client = None
        self.server = None
        self.message_receiver = None
        self.debug = False
        self.continue_pressed = False

    def client_connected_callback(self, ip_addr, port):
        self.enable_disable_widgets(
            chat_input=True,
            send_button=True,
            debug_continue=False,
        )
        sender = "SERVER"
        conn = self.client
        chat_panel = self.chat_panel
        if self.servermode.state == "down":
            self.chat_panel.write_info("Client connected from (%s, %i)" % (ip_addr, port))
            sender = "CLIENT"
            conn = self.server
        self.message_receiver = MessageReceiver(sender, conn, chat_panel)
        self.message_receiver.start()

    # specify which widgets to enable. All unspecified widgets will get disabled
    def enable_disable_widgets(
            self, 
            clientmode=None, 
            servermode=None, 
            ip_address=None,
            port=None,
            shared_value=None,
            connect=None,
            disconnect=None,
            chat_panel=None,
            chat_input=None,
            send_button=None,
            debug_switch=None,
            debug_continue=None,
    ):

        def enable_widget(enable, widget):
            if enable is None:
                return
            if enable:
                widget.disabled = False
            else:
                widget.disabled = True

        enable_widget(clientmode, self.clientmode)
        enable_widget(servermode, self.servermode)
        enable_widget(ip_address, self.ip_address)
        enable_widget(port, self.port)
        enable_widget(shared_value, self.shared_value)
        enable_widget(connect, self.connect)
        enable_widget(disconnect, self.disconnect)
        enable_widget(chat_panel, self.chat_panel)
        enable_widget(chat_input, self.chat_input)
        enable_widget(send_button, self.send_button)
        enable_widget(debug_continue, self.debug_continue)
        enable_widget(debug_switch, self.debug_switch)


    # called when 'Client' toggle button is pressed
    def client_callback(self, *args):
        state = args[1]
        if state == "down":
            self.settings_panel.add_widget(self.ip_address, 7)
            self.settings_panel.remove_widget(self.debug_boxlayout)
            self.settings_panel.remove_widget(self.debug_continue)
            self.chat_panel.write_info("Switched to Client Mode")
    
    # called when 'Server' toggle button is pressed
    def server_callback(self, *args):
        state = args[1]
        if state == "down":
            self.settings_panel.remove_widget(self.ip_address)
            self.settings_panel.add_widget(self.debug_boxlayout, 3)
            self.settings_panel.add_widget(self.debug_continue, 3)
            self.chat_panel.write_info("Switched to Server Mode")

    def debug_continue_callback(self, instance):
       self.continue_pressed = True

    # called when 'debug' toggled
    def debug_callback(self, btn, value):
        if value:
            self.debug = True
        else:
            self.debug = False

    # called when 'Connect' button is pressed
    def connect_callback(self, btn):
        self.disconnect.disabled = True

        # get inserted port number
        port = 0
        for child in self.port.children:
            if isinstance(child, TextInput):
                try:
                    port = int(child.text)
                except ValueError:
                    self.chat_panel.write_info("Invalid port: " + child.text)
                    return
    
        # get the shared key value
        shared_key = ""
        for child in self.shared_value.children:
            if isinstance(child, TextInput):
                shared_key = str(child.text)
                if not shared_key:
                    self.chat_panel.write_info("Shared key must have some value")
                    return

        # get the inserted ip address
        if (self.clientmode.state == 'down'):
            ip_address = ""
            for child in self.ip_address.children:
                if isinstance(child, TextInput):
                    try:
                        ip_address = child.text
                        ipaddress.ip_address(unicode(child.text, 'utf-8'))
                    except ValueError:
                        #TODO: print error to chat panel
                        self.chat_panel.write_info("Invalid IP Address: " + child.text)
                        return

        if (self.servermode.state == 'down'):
            # vpn is in 'server' mode
            self.server = VpnServer(
                    port, 
                    shared_key,
                    self.client_connected_callback,
                    self.broken_conn_callback,
                    self.debug_continue,
                    self.debug,
                    self
            )
            error, message = self.server.setup()
            if (error != 0):
                # error while setting up socket
                self.chat_panel.write_info(message)
                return
            else:
                self.chat_panel.write_info(message)
                self.enable_disable_widgets(
                    clientmode=False,
                    servermode=False,
                    port=False,
                    shared_value=False,
                    connect=False,
                    disconnect=True,
                    chat_input=False,
                    send_button=False,
                    debug_switch=False, 
                    debug_continue=False,
                )
                self.server.start(callback=self.client_connected_callback)
        else:
            # vpn is in 'client' mode 
            self.client = VpnClient(
                    ip_address, 
                    port, 
                    shared_key,
                    self.broken_conn_callback,
                    self
            )
            error, message = self.client.connect()
            if (error != 0):
                self.chat_panel.write_info(message)
                return
            else:
                self.chat_panel.write_info(message)
                self.enable_disable_widgets(
                    clientmode=False,
                    servermode=False,
                    ip_address=False,
                    port=False,
                    shared_value=False,
                    connect=False,
                    disconnect=True,
                    chat_input=False,
                    send_button=False,
                    debug_switch=False,
                    debug_continue=True,
                )
                self.client_connected_callback(ip_address, port)
        
    def send_msg(self, btn):
        msg = self.chat_input.text
        if (len(msg) > 500):
            self.chat_panel.write_info("Input cannot be more than 500 characters")
        else:
            if self.servermode.state == 'down':
                self.chat_panel.write_server(msg)
                self.server.send(msg)
            else:
                self.chat_panel.write_client(msg)
                self.client.send(msg)
            self.chat_input.text = ""
    
    def SettingsEntry(self,text=None):
        boxlayout = BoxLayout(orientation="vertical", padding=30)
        self.label = Label(text=text, size=(300, 50),size_hint=(1, None))
        boxlayout.add_widget(self.label)
        self.textinput = TextInput(multiline=False, size=(300, 50), size_hint=(1, None))
        boxlayout.add_widget(self.textinput)
        return boxlayout

    def build(self):
        # create the root window for the app
        self.root = BoxLayout(
                orientation="horizontal",
                spacing=10,
                padding=10
        )

        # create settings panel
        self.settings_panel = ColoredBoxLayout(
                            orientation="vertical",
                            background_color=(0,169,184,0.5),
                            size_hint=(0.3, 1),
                            padding=10,
        )
        self.root.add_widget(self.settings_panel)

        # client and server toggle buttons
        self.clientmode = ClientServerToggle(
                text='Client', 
                group='mode', 
                state='down',
                allow_no_selection=False,
                size=(300,100),
                size_hint=(1, None)
        )
        self.servermode = ClientServerToggle(
                text='Server', 
                group='mode', 
                allow_no_selection=False,
                size=(300,100),
                size_hint=(1, None)
        )
        self.clientmode.bind(state=self.client_callback)
        self.servermode.bind(state=self.server_callback)
        self.settings_panel.add_widget(self.clientmode)
        self.settings_panel.add_widget(self.servermode)

        # add empty space
        empty_widget = Widget()
        self.settings_panel.add_widget(empty_widget)

        # add ip address input
        self.ip_address = self.SettingsEntry(text="VPN Server IP Address")
        self.settings_panel.add_widget(self.ip_address)

        # add port input
        self.port = self.SettingsEntry(text="VPN Server Port")
        self.settings_panel.add_widget(self.port)
        
        # add shared value 
        self.shared_value = self.SettingsEntry(text="Shared Secret Value")
        self.settings_panel.add_widget(self.shared_value)

        # add debug mode
        self.debug_boxlayout = BoxLayout(orientation="vertical", padding=30)
        self.debug_label = Label(text="Debug Mode", size=(300, 50), size_hint=(1, None))
        self.debug_boxlayout.add_widget(self.debug_label)
        self.debug_switch = Switch(active=False, size=(300, 50), size_hint=(1, None))
        self.debug_switch.bind(active=self.debug_callback)
        self.debug_boxlayout.add_widget(self.debug_switch)
        #self.settings_panel.add_widget(self.debug_boxlayout)

        # add debug continue button
        self.debug_continue = Button(
            text="Continue",
            background_color=(0,0,1,1),
            size=(300, 100),
            size_hint=(1, None),
            disabled=True,
        )
        self.debug_continue.bind(on_press=self.debug_continue_callback)
        #self.settings_panel.add_widget(self.debug_continue)

        # add empty space
        empty_widget = Widget()
        self.settings_panel.add_widget(empty_widget)

        # add connect and disconnect buttons
        self.connect = Button(
                text="Connect", 
                background_color=(0,1,0,1),
                size=(300, 150),
                size_hint=(1, None)
        )
        self.connect.bind(on_press=self.connect_callback)
        self.disconnect = Button(
                text="Disconnect", 
                background_color=(1,0,0,1),
                size=(300, 150),
                size_hint=(1, None),
                disabled=True,
        )
        self.disconnect.bind(on_press=self.disconnect_callback)
        self.settings_panel.add_widget(self.connect)
        self.settings_panel.add_widget(self.disconnect)

        # create chat panel
        self.chat_layout = BoxLayout(
                orientation="vertical",
                spacing=10,
                size_hint=(0.7, 1)
        )
        self.chat_panel = ChatPanel(
                markup=True,
                readonly=True,
                scroll_y=1,
                focused=True,
                cursor_color=(0,0,0,0),
                bar_color=(1,0,0,1),
        )
        self.input_layout = BoxLayout(
                orientation="horizontal",
                spacing=10,
                size=(0, 50),
                size_hint=(1, None)
        )
        self.chat_input = TextInput(size_hint=(0.8, 1))
        self.send_button = Button(size_hint=(0.2, 1), text="Send")
        self.send_button.bind(on_press=self.send_msg)
        self.input_layout.add_widget(self.chat_input)
        self.input_layout.add_widget(self.send_button)
        self.chat_layout.add_widget(self.chat_panel)
        self.chat_layout.add_widget(self.input_layout)
        self.root.add_widget(self.chat_layout)
        self.chat_input.disabled=True
        self.send_button.disabled=True
        return self.root

    def broken_conn_callback(self):
        if self.message_receiver:
            self.message_receiver.close()
        if self.server:
            self.server.broken_conn()
            self.server.start(callback=self.client_connected_callback)
            self.chat_panel.write_info("Client disconnected")
            self.chat_panel.write_info("Listening for connections...")
            self.enable_disable_widgets(
                chat_input=False,
                send_button=False,
                debug_continue=False,
            )
        else:
            self.client.close()
            self.enable_disable_widgets(
                clientmode=True,
                servermode=True,
                ip_address=True,
                port=True,
                shared_value=True,
                connect=True,
                disconnect=False,
                chat_input=False,
                send_button=False,
                debug_switch=True,
                debug_continue=False,
            )
            self.chat_panel.write_info("Lost connection to server")
        
    def disconnect_callback(self, instance):
        if self.servermode.state == 'down':
            self.server.close()
            self.chat_panel.write_info("Closing Server...")
        else:
            self.client.close()
            self.chat_panel.write_info("Disconnecting from server...")
        if self.message_receiver:
            self.message_receiver.close()
        self.clientmode.disabled=False
        self.servermode.disabled=False
        self.ip_address.disabled=False
        self.port.disabled=False
        self.shared_value.disabled=False
        self.connect.disabled=False
        self.disconnect.disabled=True
        self.chat_input.disabled=True
        self.send_button.disabled=True
        self.debug_switch.disabled=False
        self.debug_continue.disabled=True

    def close(self):
        if self.server:
            self.server.close()
        if self.client:
            self.client.close()
        if self.message_receiver:
            self.message_receiver.close()
Ejemplo n.º 36
0
class Screen(FloatLayout):

    def build(self):
        self.object1 = BoxLayout()
        return self.object1
       
    def __init__(self, **kwargs):
        super(Screen, self).__init__(**kwargs)
#Fundal image
        with self.canvas.before:
            self.fundal_image = Image(source = "E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/fundal.jpg")
            self.fundal_image.opacity = 0.7
            self.add_widget(self.fundal_image)
            self.rect = Rectangle(size = self.size, pos = self.pos)

        self.bind(size = self._update_rect, pos = self._update_rect)

        self.layout = FloatLayout()
        self.layout.size_hint = (None, None)
        self.layout.size = (600, 500)
        self.layout.padding = 20
        self.fundal_image.add_widget(self.layout)
        
        self.sound = SoundLoader.load("E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/JO_-_09_-_Fortitude.ogg")
        self.sound.play()
        self.sound.loop = True
        self.sound.volume = 0.5
               
        self.Menu(None)

    def Menu(self, buton):

        self.layout.clear_widgets()
        
        self.button1 = Button(text = 'Carousel', bold = True, background_color =(0, 0, 1, 1))
        self.button1.pos = (290, 380)
        self.button1.size_hint = (0.3, 0.1)
        self.layout.add_widget(self.button1)

        self.button2 = Button(text = 'Optiuni', bold = True, background_color =(0, 0, 1, 1))
        self.button2.pos = (290, 280)
        self.button2.size_hint = (0.3, 0.1)
        self.layout.add_widget(self.button2)

        self.button3 = Button(text = 'About', bold = True, background_color =(0, 0, 1, 1))
        self.button3.pos = (290, 180)
        self.button3.size_hint = (0.3, 0.1)
        self.layout.add_widget(self.button3)

        self.button4 = Button(text = 'Iesi', bold = True, background_color =(0, 0, 1, 1))
        self.button4.pos = (290, 80)
        self.button4.size_hint = (0.3, 0.1)
        self.layout.add_widget(self.button4)

        self.button1.bind(on_press = self.Carousel)
        self.button2.bind(on_press = self.Options)
        self.button3.bind(on_press = self.About)
        self.button4.bind(on_press = self.Exit)

    def Carousel(self, buton):

        self.layout.clear_widgets()
        
        self.carousel = Carousel(direction = 'right')
        self.carousel.anim_move_duration = 1
        self.carousel.loop = True
        self.carousel.size_hint = (0.7, 0.7)
        self.carousel.pos = (200, 120)
        self.layout.add_widget(self.carousel)

        self.image1 = Image(source = 'E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/nature1.jpg')
        self.carousel.add_widget(self.image1)
        self.image2 = Image(source= 'E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/nature2.jpg')
        self.carousel.add_widget(self.image2)
        self.image3 = Image(source = 'E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/nature3.jpg')
        self.carousel.add_widget(self.image3)
        self.image4 = Image(source = 'E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/nature4.jpg')
        self.carousel.add_widget(self.image4)

        self.label = Label(text = 'This is the end of the list!', font_size = 30)
        self.carousel.add_widget(self.label)

        self.backbutton = Button(text = 'Back', bold = True, background_color = (0, 0, 1, 1))
        self.backbutton.pos = (200, 100)
        self.backbutton.size_hint = (0.7, 0.1)
        self.layout.add_widget(self.backbutton)
        
        self.backbutton.bind(on_press = self.Menu)

    def Options(self, buton):
        
        self.layout.clear_widgets()

        self.switch = Switch(text = 'Music')
        self.switch.active = True
        self.switch.size_hint = (0.3, 0.2)
        self.switch.pos = (300, 360)
        self.layout.add_widget(self.switch)

        self.show_volume = Label(text = 'Volume = 50')
        self.layout.add_widget(self.show_volume)

        self.music_slide = Slider(min = 0, max = 100, value = 50)
        self.music_slide.step = 5
        self.music_slide.size_hint = (0.3, 0.1)
        self.music_slide.pos = (300, 180)
        self.music_slide.orientation = 'horizontal'
        self.layout.add_widget(self.music_slide)

        self.button = Button(text = 'Back', bold = True, background_color = (0, 0, 1, 1))
        self.button.pos = (300, 120)
        self.button.size_hint = (0.3, 0.1)
        self.button.opacity = 0.7
        self.layout.add_widget(self.button)
        
        self.switch.bind(active = self.mute)
        self.music_slide.bind(value = self.volume_value)
        self.button.bind(on_press = self.Menu)
       

    def volume_value(self,x,y):
        self.show_volume.text = 'Volume ' + str(int(self.music_slide.value))
        self.sound.volume = self.music_slide.value / 100

    def mute(self,x,y):
        if (self.switch.active == False):
            self.music_slide.disabled = True
            self.sound.stop()
        else:
            self.music_slide.disabled = False
            self.music_slide.value = 0
            self.sound.play()

    def About(self, buton):
        
        self.layout.clear_widgets()
        
        self.backbutton = Button(text = 'Back', background_color = (0, 0, 1, 1))
        self.backbutton.size_hint = (1, 0.1)
        
        self.label = Label(text = 'Thanks InfoAcademy!', bold = True, font_size = 24)
        self.blayout = BoxLayout()
        self.blayout.orientation = 'vertical'
        self.blayout.padding = 40
        
        self.blayout.add_widget(self.backbutton)
        self.blayout.add_widget(self.label)
        self.backbutton.bind(on_press = self.Menu)
        
        self.popup = Popup(background = 'E:/PROGRAMMIN/Curs/Pentru examen/fisiere proiect/fundal4_tema.jpg')
        self.popup.size_hint =(None, None)
        self.popup.size = (400, 400)
        self.popup.title = 'Who made this aplication?'
        self.popup.content = self.blayout
        self.popup.open()
        self.popup.bind(on_press = self.close_popup)
        self.backbutton.bind(on_press = self.close_popup)

    def close_popup(self, buton):
        self.popup.dismiss()

    def Exit(self, buton):
        sys.exit()
               
                                           
    def _update_rect(self, instance, value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size
Ejemplo n.º 37
0
class ProtectorApp(App):
 def build(self):
        
        #Creates a grid layout to hold the app interfaces like buttons,switches,labels etc,.                   
        rl = GridLayout(rows = 14)
         
        #creates a main label for app title
        l = Label(text = "The Protector Dashboard",
                      font_size = 30, 
                      size_hint =(.3, .3),  
                      pos_hint ={'right_x':.5, 'center_y':.5}, 
                      )
        
        #creates a label for displaying limit              
        n = Label(text = "Customer Limit", 
                      size_hint =(.2, .2),  
                      pos_hint ={'right_x':.5, 'center_y':.5}, 
                      )
                                   
        #creates a dyanamic label for updating limit
        self.limit = Label(text = '', size_hint =(.1, .1))
  
        #creates a label for switch1 title
        l2 = Label(text = "Socket", 
                      size_hint =(.2, .2),  
                      pos_hint ={'right_x':.5, 'center_y':.5}, 
                      )     
                    
        #creates a label for switch2 title              
        l3 = Label(text = "Light", 
                      size_hint =(.2, .2),  
                      pos_hint ={'right_x':.5, 'center_y':.5}, 
                      )
                    
        #creates a label for switch3 title            
        l4 = Label(text = "Fan", 
                      size_hint =(.2, .2),  
                      pos_hint ={'right_x':.5, 'center_y':.5}, 
                      )
                        
        #creates a label to display persons count                
        l5 = Label(text = "Number of Persons", 
                      size_hint =(.2, .2),  
                      pos_hint ={'right_x':.5, 'center_y':.5}, 
                      )
                                                 
        #creates a dynamic label to show the person count                                                         
        self.output_label = Label(text = '', size_hint =(.1, .1))
        
	#creates a label for High temperature warning
        self.warn_label = Label(text = '', size_hint =(.1, .1))
	
        #creates a button instance               
        b1 = Button(size_hint = (.2, .1),  
                    text ="+")  
        #binds a function to the instance            
        b1.bind(state=self.on_up)           
        
        #creates a button instance
        b2 = Button(size_hint = (.2, .1),  
                    text ="-")  
        #binds a function to the instance            
        b2.bind(state=self.on_down)
        
        #creates switch instance
        self.s = Switch(active = False, size_hint = (.1,.1))
        self.s2 = Switch(active = False, size_hint = (.1,.1))
        self.s3 = Switch(active = False, size_hint = (.1,.1))
       
        #adds all the widgets to the layout
        rl.add_widget(l)
        rl.add_widget(n)
        rl.add_widget(b1)
        rl.add_widget(self.limit)
        rl.add_widget(b2)
        rl.add_widget(l5)
        rl.add_widget(self.output_label)
        rl.add_widget(l2)
        rl.add_widget(self.s)
        rl.add_widget(l3)
        rl.add_widget(self.s2)
        rl.add_widget(l4)
        rl.add_widget(self.s3)
	rl.add_widget(self.warn_label)
                        
        #binds functions to the switch instances                
        self.s.bind(active_norm_pos = self.on_press_sw1)
        self.s2.bind(active_norm_pos = self.on_press_sw2)
        self.s3.bind(active_norm_pos = self.on_press_sw3)
        #create a scheduled clock to update label parameters       
        Clock.schedule_interval(self.person, 1)
        return rl

 #function called during switch actions
 def on_press_sw1(self,instance,value): 
  if (value == True):
   sendRequest(root_url+"/H")
   
  if (value == False):
   sendRequest(root_url+"/L")
   
 #function called during switch actions  
 def on_press_sw2(self,instance,value): 
  if (value == True):
   sendRequest(root_url+"/O")
   
  if (value == False):
   sendRequest(root_url+"/C")
   
 #function called during switch actions  
 def on_press_sw3(self,instance,value): 
  if (value == True):
   sendRequest(root_url+"/F")
     
  if (value == False):
   sendRequest(root_url+"/B")
   
 #function called during button action  
 def on_up(self,instance,value):
  if (value == "down"):
   sendRequest(root_url+"/U")  
    
 #function called during button action   
 def on_down(self,instance,value):
  if (value == "down"): 
   sendRequest(root_url+"/D")
    
 #function accessed by clock at an interval of 1 sec   
 def person(self,instance):
   #access the devices IP address and reads the data
   html_doc = urllib.request.urlopen(root_url)
   soup = BeautifulSoup(html_doc, 'html.parser')
   #extracts data from the particular tags
   x = soup.find('t1') 
   l = soup.find('t2')
   cc1 = soup.find('c1')
   cc2 = soup.find('c2')
   cc3 = soup.find('c3') 
   alt = soup.find('alt') 
   #removes spaces from the retrived data
   c1 = cc1.string.strip()
   c2 = cc2.string.strip()
   c3 = cc3.string.strip()
   al = alt.string.strip()	
   txt = str(x.string.lstrip())
   n = str(l.string.lstrip())
   #update the data to labels
   self.output_label.text = txt
   self.limit.text = n
   #checks the data with reference value
   if (al > "0"):
    #if true updates warning label
    self.warn_label.text = "Alert! " + al + " Person"	
   #checks the data with reference value
   if (c1 == "1"):
    #if true changes state of switch
    self.s.active = True
   #checks the data with reference value
   if (c1 == "0"):
    #if true changes state of switch
    self.s.active = False
   
   #checks the data with reference value
   if (c2 == "1"):
    #if true changes state of switch
    self.s2.active = True      
   #checks the data with reference value
   if (c2 == "0"):
    #if true changes state of switch
    self.s2.active = False     
   
   #checks the data with reference value
   if (c3 == "1"):    
    #if true changes state of switch     
    self.s3.active = True
   #checks the data with reference value
   if (c3 == "0"):
    #if true changes state of switch
    self.s3.active = False
Ejemplo n.º 38
0
class SettingsScreen(Screen):
    def __init__(self, theme, data, **kwargs):
        super(SettingsScreen, self).__init__(**kwargs)

        # the main container
        self.root = BoxLayout(orientation='vertical')

        # the top bar with the back button
        bar = BoxLayout(orientation='horizontal', size_hint=[1, None], size=[150, 50], padding=[20, -20])
        self.back_button = Button(
            size_hint=[None, None],
            size=[50, 50],
            on_release=lambda n: self.change_to_menu(theme),
            background_normal=f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/return_button_normal_{theme.current}.png',
            background_down=f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/return_button_pressed_{theme.current}.png'
        )
        bar.add_widget(self.back_button)
        self.root.add_widget(bar)

        # to display a nice heading
        self.heading = Label(
            text='Settings',
            font_size='50sp',
            font_name='gothic',
            color=theme.get_secondary(),
            halign='center',
            valign='bottom',
            padding_y=20,
            size_hint=[1, None],
            size=[150, 150]
        )
        self.heading.bind(size=self.heading.setter('text_size'))
        self.root.add_widget(self.heading)

        # to make the settings panel scrollable
        settings = ScrollView(
            size_hint=[1, 1]
        )
        # to place the settings groups beneath each other
        settings_gridlayout = GridLayout(cols=1, size_hint_y=None)
        settings_gridlayout.bind(minimum_height=settings_gridlayout.setter('height'))

        # setup the group for the general game settings
        self.game_group = SettingsGroup(name='Game settings', theme=theme, size_y=180)

        # the grid size settings
        grid_size_setting = BoxLayout(orientation='horizontal', size_hint=[1, None], size=[50, 50], padding=[20, 0])
        self.grid_size_setting_name = SettingName(name='Grid size', theme=theme, size_hint=[0.33, None], size=[150, 50])
        self.grid_size_setting_value = SettingLabel(text=str(data['grid_size']), theme=theme, size_hint=[0.1, None], size=[30, 50],
                                                    halign='right')
        self.grid_size_setting_slider = Slider(
            min=3,
            max=20,
            step=1,
            on_touch_up=lambda instance, touch: self.grid_size_setting_change(self.grid_size_setting_slider,
                                                                              self.grid_size_setting_value, instance,
                                                                              touch),
            on_touch_move=lambda instance, touch: self.grid_size_setting_update_value_label(
                self.grid_size_setting_slider,
                self.grid_size_setting_value,
                instance, touch),
            value=data['grid_size'])
        grid_size_setting.add_widget(self.grid_size_setting_name)
        grid_size_setting.add_widget(self.grid_size_setting_slider)
        grid_size_setting.add_widget(self.grid_size_setting_value)
        self.game_group.root.add_widget(grid_size_setting)

        # the mines percentage settings
        mines_percentage_setting = BoxLayout(orientation='horizontal', size_hint=[1, None], size=[50, 50],
                                             padding=[20, 0])
        self.mines_percentage_setting_name = SettingName(name='Mines percentage', theme=theme, size_hint=[0.8, None],
                                                         size=[150, 50])
        self.mines_percentage_setting_value = SettingLabel(text=str(data['mines_percentage']) + '%', theme=theme, size_hint=[0.2, None],
                                                           size=[30, 50], halign='right')
        self.mines_percentage_setting_slider = Slider(
            min=1,
            max=50,
            step=1,
            on_touch_up=lambda instance, touch: self.mines_percentage_setting_change(
                self.mines_percentage_setting_slider,
                self.mines_percentage_setting_value,
                instance, touch),
            on_touch_move=lambda instance, touch: self.mines_percentage_setting_update_value_label(
                self.mines_percentage_setting_slider,
                self.mines_percentage_setting_value, instance, touch),
            value=data['mines_percentage'])
        mines_percentage_setting.add_widget(self.mines_percentage_setting_name)
        mines_percentage_setting.add_widget(self.mines_percentage_setting_slider)
        mines_percentage_setting.add_widget(self.mines_percentage_setting_value)
        self.game_group.root.add_widget(mines_percentage_setting)

        # self.game_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.game_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.game_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.game_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.game_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        settings_gridlayout.add_widget(self.game_group)

        # setup the group for the leaderboard settings
        self.leaderboard_group = SettingsGroup(name='Leaderboard', theme=theme, size_y=130)

        # the button to clear the leaderboard
        leaderboard_clear_setting = AnchorLayout(anchor_x='center', anchor_y='center', size_hint=[1, None],
                                                 size=[50, 60], padding=[20, 5])

        self.leaderboard_clear_setting_button = Button(text='Clear leaderboard', font_name='gothic', font_size='16sp',
                                                       size_hint=[None, None], size=[250, 50],
                                                       on_release=self.clear_leaderboard, color=theme.get_secondary(),
                                                       background_normal=f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/button_normal_{theme.current}.png',
                                                       background_down=f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/button_pressed_{theme.current}.png', )

        leaderboard_clear_setting.add_widget(self.leaderboard_clear_setting_button)
        self.leaderboard_group.root.add_widget(leaderboard_clear_setting)

        # some placeholders
        # self.leaderboard_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.leaderboard_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.leaderboard_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.leaderboard_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.leaderboard_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        settings_gridlayout.add_widget(self.leaderboard_group)

        # setup the group for the dark mode settings
        self.dark_mode_group = SettingsGroup(name='Appearance', theme=theme, size_y=120)

        # the switch for the dark mode
        dark_mode_settings = BoxLayout(orientation='horizontal', size_hint=[1, None], size=[50, 50], padding=[20, 5])

        # get the state of the switch, according to the settings file
        if data['theme'] == 'light':
            dark_mode_state = False
        else:
            dark_mode_state = True

        self.dark_mode_settings_name = SettingName(name='Dark mode', theme=theme, size_hint=[1, None], size=[50, 50])
        self.dark_mode_setting_switch = Switch(active=dark_mode_state, size_hint=[0.3, None], size=[50, 50])
        self.dark_mode_setting_switch.bind(
            active=lambda instance, value: self.dark_mode_settings_change(theme, instance, value))

        dark_mode_settings.add_widget(self.dark_mode_settings_name)
        dark_mode_settings.add_widget(self.dark_mode_setting_switch)
        self.dark_mode_group.root.add_widget(dark_mode_settings)

        # some placeholders
        # self.dark_mode_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.dark_mode_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.dark_mode_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.dark_mode_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        # self.dark_mode_group.root.add_widget(Button(size_hint=[None, None], size=[450, 50]))
        settings_gridlayout.add_widget(self.dark_mode_group)

        settings.add_widget(settings_gridlayout)
        self.root.add_widget(settings)
        self.add_widget(self.root)

        # apply the given settings
        # self.apply_settings(data)
        

    def change_to_menu(self, theme):
        self.save_settings(theme)
        self.manager.current = 'menu_screen'

    # GRID SIZE SETTINGS
    # grid size settings, fired when the mouse leaves the slider
    def grid_size_setting_change(self, slider, label, instance, touch):
        if instance.collide_point(*touch.pos):
            print('current grid size', slider.value)
            self.manager.get_screen('game_screen').weeper.reset_game(grid_size=slider.value)
            label.text = str(slider.value)

            #  calculate the least possible value for the mines percentage slider (so that there is always 1 mine in the
            #  field)
            least_mine_percentage = math.ceil(
                (1 * 100) / (self.grid_size_setting_slider.value * self.grid_size_setting_slider.value))

            # apply the value to the slider
            self.mines_percentage_setting_slider.min = least_mine_percentage
            self.mines_percentage_setting_slider.step = least_mine_percentage

            # set the value to the value nearest to 15%
            self.mines_percentage_setting_slider.value = ((50 - (50 % least_mine_percentage)) * 0.3) - (
                    (50 - (50 % least_mine_percentage)) * 0.3) % least_mine_percentage

            # apply the new value to the minesweeper game and change the value displayed on the side
            self.manager.get_screen('game_screen').weeper.reset_game(
                mines_percent=self.mines_percentage_setting_slider.value / 100)
            self.mines_percentage_setting_value.text = str(int(self.mines_percentage_setting_slider.value)) + '%'

    # fired when the slider is moved
    def grid_size_setting_update_value_label(self, slider, label, instance, touch):
        if instance.collide_point(*touch.pos):
            label.text = str(slider.value)

    # MINES PERCENTAGE SETTINGS
    # fired when the slider is moved
    def mines_percentage_setting_change(self, slider, label, instance, touch):
        if instance.collide_point(*touch.pos):
            print('current mines percent', slider.value / 100)
            self.manager.get_screen('game_screen').weeper.reset_game(mines_percent=slider.value / 100)
            label.text = str(slider.value) + '%'

    # fired when the mouse leaves the slider
    def mines_percentage_setting_update_value_label(self, slider, label, instance, touch):
        print(instance)
        if instance.collide_point(*touch.pos):
            label.text = str(slider.value) + '%'

    # CLEAR LEADERBOARD SETTINGS
    # fires when the button is released, deletes the whole leaderboard
    def clear_leaderboard(self, *args):
        self.manager.get_screen('leaderboard_screen').entries.clear_all()
        self.manager.get_screen('leaderboard_screen').update_list()

    # DARK MODE SETTINGS
    # fired when the switch is activated
    def dark_mode_settings_change(self, theme, instance, value):
        print(value)
        if value:
            theme.current = 'dark'
        else:
            theme.current = 'light'

        Window.clearcolor = theme.get_primary()
        self.apply_theme(theme)

    # UNIVERSAL: to update the theme when switched
    def apply_theme(self, theme):
        self.heading.color = theme.get_secondary()

        self.game_group.apply_theme(theme)
        self.grid_size_setting_name.color = theme.get_secondary()
        self.grid_size_setting_value.color = theme.get_secondary()
        self.grid_size_setting_slider.color = theme.get_secondary()

        self.mines_percentage_setting_name.color = theme.get_secondary()
        self.mines_percentage_setting_value.color = theme.get_secondary()
        self.mines_percentage_setting_slider.color = theme.get_secondary()

        self.leaderboard_group.apply_theme(theme)
        self.leaderboard_clear_setting_button.color = theme.get_secondary()

        # recolor button
        self.leaderboard_clear_setting_button.background_normal = f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/button_normal_{theme.current}.png'
        self.leaderboard_clear_setting_button.background_down = f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/button_pressed_{theme.current}.png'

        self.back_button.background_normal = f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/return_button_normal_{theme.current}.png'
        self.back_button.background_down = f'C:/Users/Nutzer/PycharmProjects/Minesweeper/assets/img/buttons/return_button_pressed_{theme.current}.png'

        self.dark_mode_group.apply_theme(theme)
        self.dark_mode_settings_name.color = theme.get_secondary()

        self.manager.get_screen('menu_screen').apply_theme(theme)
        self.manager.get_screen('game_screen').apply_theme(theme)
        self.manager.get_screen('pause_screen').apply_theme(theme)
        self.manager.get_screen('game_over_screen').apply_theme(theme)
        self.manager.get_screen('leaderboard_screen').apply_theme(theme)

    # save the current settings
    def save_settings(self, theme):
        data = {}
        data['grid_size'] = self.grid_size_setting_slider.value
        data['mines_percentage'] = self.mines_percentage_setting_slider.value
        data['theme'] = theme.current

        with open('saves\settings.json', 'w') as settings_file:
            json.dump(data, settings_file)
Ejemplo n.º 39
0
class ZhonxGUIApp(App):
    
    def connect(self, instance, value):
        print('the switch', instance, 'is', value)
        if value == True:
            try:
                self.connection = serial.Serial(self.dlPort.text, self.dlBaudrate.text)
            except Exception as e:
#                 instance.active = False
                print(e)
        else:
            try:
                self.connection.close()
            except Exception as e:
#                 instance.active = True
                print(e)
    
    def build(self):
        self.availablePorts = listSerialPorts()
        if len(self.availablePorts) == 0:
            self.availablePorts.append("----")
        
        tabbedPannel = TabbedPanel(do_default_tab=False)
        
        # Connection Tab
        self.connectionTab = TabbedPanelItem(text="Connection")
        
        self.layout1 = BoxLayout(orientation='vertical', spacing=10, padding=(200, 200))
        self.connectionTab.add_widget(self.layout1)
        
        self.lblSerialSettings = Label(text="Connection settings")
        self.layout1.add_widget(self.lblSerialSettings)
        
        self.dlBaudrate = Spinner(values = ["57600", "115200", "230400", "460800", "921600"],
                                  text = "115200")
        self.layout1.add_widget(self.dlBaudrate)
        
        self.dlPort = Spinner(values = self.availablePorts,
                              text = self.availablePorts[0])
        self.layout1.add_widget(self.dlPort)
        
        self.btnConnect = Switch()
        self.btnConnect.bind(active = self.connect)
        
        self.layout1.add_widget(self.btnConnect)
        
        # Graph tab
        self.graphTab = TabbedPanelItem(text = "Graph")
#         self.layout2 = BoxLayout(orientation='vertical', spacing=10, padding=(200, 200))
#         self.graphTab.add_widget(self.layout2)
        
        graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
        x_ticks_major=25, y_ticks_major=1,
        y_grid_label=True, x_grid_label=True, padding=5,
        x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
        plot = MeshLinePlot(color=[1, 1, 0, 1])
        plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
        graph.add_plot(plot)
        self.graphTab.add_widget(graph)
        
        
        tabbedPannel.add_widget(self.connectionTab)
        tabbedPannel.add_widget(self.graphTab)
        return tabbedPannel
Ejemplo n.º 40
0
def MmsPop(self):
    layout = GridLayout(cols=1, size_hint=(None, 1.0), width=700)
    layout.bind(minimum_height=layout.setter('height'))
    panel = SettingsPanel(title="Mms Mods", settings=self)
    main = BoxLayout(orientation='vertical')
    root = ScrollView(size_hint=(None, None),
                      bar_margin=-11,
                      bar_color=(47 / 255., 167 / 255., 212 / 255., 1.),
                      do_scroll_x=False)
    root.size = (600, 400)
    root.add_widget(layout)
    main.add_widget(root)
    done = Button(text='Done Choosing Options')
    main.add_widget(done)
    if """    .line 77
    const/4 v0, 0x1

    sput-boolean v0, Lcom/android/mms/model/ImageModel;->mCheckResolution:Z""" in open(
            "%s/ImageModel.smali" % (Mms)).read():
        fp = open("%s/ImageModel.smali" % (Mms), "r")
        lines = fp.readlines()
        fp.close()
        comp = SettingItem(panel=panel,
                           title="Remove Mms Compression",
                           disabled=False,
                           desc="Disables Compression of Mms Messages")
        for i in range(len(lines)):
            if """    .line 77
    const/4 v0, 0x1

    sput-boolean v0, Lcom/android/mms/model/ImageModel;->mCheckResolution:Z""" in open(
                    "%s/ImageModel.smali" % (Mms)).read():
                comp_switch = Switch(active=False)
                continue
            if """    .line 77
    const/4 v0, 0x1

    sput-boolean v0, Lcom/android/mms/model/ImageModel;->mCheckResolution:Z""" in open(
                    "%s/ImageModel.smali" % (Mms)).read():
                comp_switch = Switch(active=True)
        comp.add_widget(comp_switch)
        layout.add_widget(comp)

        def callback(instance, value):
            comp_state(instance, value)

        comp_switch.bind(active=callback)

    popup = Popup(background='atlas://images/eds/pop',
                  title='Mms Mods',
                  content=main,
                  auto_dismiss=False,
                  size_hint=(None, None),
                  size=(630, 500))
    popup.open()

    def finish(self):
        finish_comp(self)
        popup.dismiss()

    done.bind(on_release=finish)
Ejemplo n.º 41
0
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.switch import Switch
from var import var

layout = BoxLayout()
switch = Switch(text="setting")

if var == 0:
    switch.active = False
elif var == 1:
    switch.active = True

layout.add_widget(switch)

def fun(x, y):
    if y == True:
        f = opne("var.py", "w")

switch.bind(active=fun)

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

if __name__ == "__main__":
    MyApp().run()
Ejemplo n.º 42
0
	def __init__(self, **kwargs):
		super(MainScreen, self).__init__(**kwargs)
	
		self.cols = 1
		self.rows = 1

		self._data_queue = queue.Queue()
		self.gps_location = None
		self.gps_status = None
		self.default_sensor = "Accelerometer"
		self.default_protocol = "terminal"
		self.default_server = "test.mosquitto.org"
		self.default_port = "1883"
		self.default_topic_url = "ie/dcu/ee513"

		#Layouts
		self._main_layout = BoxLayout(orientation='vertical', padding=0, size_hint=(1, 1))
		if (platform == 'android') or (platform == 'ios'):
			_terminal_layout = BoxLayout(orientation='vertical', padding=0, size_hint=(1, 0.7))
			_partition_layout = GridLayout(cols=2, rows=6, padding=0, size_hint=(1, 1), row_force_default=True, \
										rows_minimum={0: 150, 1: 150, 2: 150, 3: 150}, row_default_height=150, spacing=25)
		else:
			_terminal_layout = BoxLayout(orientation='vertical', padding=0, size_hint=(1, 0.4))
			_partition_layout = GridLayout(cols=2, rows=6, padding=0, size_hint=(1, 1), row_force_default=True, \
										rows_minimum={0: 50, 1: 50, 2: 50, 3: 50}, row_default_height=50, spacing=25)
  
		_action_previous = ActionPrevious(title='EE513 LABS', with_previous=False, app_icon='icons/sxmitter-logo-app-small.png', padding=0)
		_action_overflow = ActionOverflow()
		_action_view = ActionView(overflow_group=_action_overflow, use_separator=True)
		_action_button = ActionButton(text='debug')
		_action_overflow.add_widget(_action_button)
		_action_button_about = ActionButton(text='About')
		_action_button_about.bind(on_release=self._popup_about)
		_action_button_quit = ActionButton(text='Quit')
		_action_button_quit.bind(on_release=self.quitApp)
		_action_view.add_widget(_action_previous)
		_action_view.add_widget(_action_button_about)
		_action_view.add_widget(_action_button_quit)
		_action_view.add_widget(_action_overflow)
		_action_bar = ActionBar(pos_hint={'top': 1})
		_action_bar.add_widget(_action_view)

		_partition_layout.add_widget(Label(text='Server', size_hint_x=None, width=400))
		self._data_object["server"] = self.default_server
		self.server = TextInput(text='test.mosquitto.org', multiline=False, cursor_blink=True)
		self.server.bind(text=self.callback_server_text)
		_partition_layout.add_widget(self.server)
	
		_partition_layout.add_widget(Label(text='Port', size_hint_x=None, width=400))
		self._data_object["port"] = self.default_port
		self.port = TextInput(text='1883', multiline=False)
		self.port.bind(text=self.callback_port_text)
		_partition_layout.add_widget(self.port)

		_partition_layout.add_widget(Label(text='Sensor', size_hint_x=None, width=400))
		self._data_object["sensor"] = self.default_sensor
		sensor_spinner = Spinner(
					text=self.default_sensor,
					values=('Accelerometer', 'Compass', 'GPS', 'Barometer', 'Gravity', 'Gyroscope'),
					size_hint=(0.3, 0.5), sync_height=True)
		sensor_spinner.bind(text=self.callback_sensor_spinner_text)
		_partition_layout.add_widget(sensor_spinner)

		_partition_layout.add_widget(Label(text='Protocol', size_hint_x=None, width=400))
		self._data_object["protocol"] = self.default_protocol
		protocol_spinner = Spinner(
					text=self.default_protocol,
					values=('http', 'https', 'mqtt', 'udp', 'terminal'),
					size_hint=(0.3, 0.5), sync_height=True)
		protocol_spinner.bind(text=self.callback_protocol_spinner_text)
		_partition_layout.add_widget(protocol_spinner)

		_partition_layout.add_widget(Label(text='Topic/URL', size_hint_x=None, width=400))
		self._data_object["topic_url"] = self.default_topic_url
		self.topic_url = TextInput(text='ie/dcu/ee513', multiline=False)
		self.topic_url.bind(text=self.callback_topic_url_text)
		_partition_layout.add_widget(self.topic_url)
  
		_partition_layout.add_widget(Label(text='Connect', size_hint_x=None, width=400))
		switch = Switch()
		switch.bind(active=self.callback_switch)
		_partition_layout.add_widget(switch)

		self.terminal = TextInput(text='Terminal output...', multiline=True, readonly=False, size_hint=(1, 1))
		self.global_terminal = self.terminal
		_terminal_layout.add_widget(self.terminal)		
		
		self._main_layout.add_widget(_action_bar)
		self._main_layout.add_widget(_partition_layout)
		self._main_layout.add_widget(_terminal_layout)
		self.add_widget(self._main_layout)
Ejemplo n.º 43
0
from kivy.app import App
from kivy.uix.switch import Switch

sw = Switch(active=True)


# Let's define the callback functions.
def down_callback(instance, value):
    print('*****')


def active_callback(instance, value):
    if value:
        print('activated')
    else:
        print('deactivated')


# Let's bind the events to the callback functions.
sw.bind(on_touch_down=down_callback)
sw.bind(active=active_callback)


class TestApp(App):
    def build(self):
        return sw


if __name__ == '__main__':
    TestApp().run()
Ejemplo n.º 44
0
Archivo: Kivy.py Proyecto: caojc/kivy
class CustomLayout(FloatLayout):
    def __init__(self, **kwargs):
        # suprascrierea initului vechi din modul
        super(CustomLayout, self).__init__(**kwargs)
        # var muzica_activa este o definita in acest namespace pt a avea efect in dezactivarea_volumului
        self.muzica_activa = 0
        # obiectul layout0 este de tipul FloatLayout()
        self.layout0 = FloatLayout()
        # setam atributul source al obiect imag1
        self.imag1 = Image(source="fundal.jpg")
        # adaugam fundalul ca si widget
        self.add_widget(self.imag1)
        # setam atributele layout0
        self.layout0.size = (600, 500)
        self.layout0.size_hint = (None, None)
        self.layout0.padding = 200
        self.imag1.add_widget(self.layout0)
        # incarcam widgetul SoundLoader si atributele sale
        self.sound = SoundLoader.load('And_So_YouCode Rap_Tarzi.wav')
        self.sound.play()
        self.sound.loop = True
        self.sound.volume = 0.5
        # anulam functionalitatile cu care vine metoda
        self.Menu(None)

    def Menu(self, Buton):
        # am curatat layoutul
        self.layout0.clear_widgets()
        # creare but1 si atributelor sale
        self.but1 = Button(text="Carusel",
                           bold=True,
                           background_color=(0, 0, 1, 1))
        self.but1.pos = (300, 380)
        self.but1.size_hint = (0.3, 0.1)
        self.but1.opacity = 0.7
        #adaugarea ca si widget a but1 pe layout0
        self.layout0.add_widget(self.but1)

        # creare but2 si atributelor sale
        self.but2 = Button(text="Optiuni",
                           bold=True,
                           background_color=(0, 0, 1, 1))
        self.but2.pos = (300, 300)
        self.but2.size_hint = (0.3, 0.1)
        self.but2.opacity = 0.7
        self.layout0.add_widget(self.but2)

        # creare but3 si atributelor sale
        self.but3 = Button(text="About",
                           bold=True,
                           background_color=(0, 0, 1, 1))
        self.but3.pos = (300, 220)
        self.but3.size_hint = (0.3, 0.1)
        self.but3.opacity = 0.7
        self.layout0.add_widget(self.but3)

        # creare but4 si atributelor sale
        self.but4 = Button(text="Iesi",
                           bold=True,
                           background_color=(0, 0, 1, 1))
        self.but4.pos = (300, 140)
        self.but4.size_hint = (0.3, 0.1)
        self.but4.opacity = 0.7
        self.layout0.add_widget(self.but4)

        # se leaga evenimentele de apasare a butoanelor de metodele de mai jos
        self.but1.bind(on_press=self.CatreCarusel)
        self.but2.bind(on_press=self.Optiuni)
        self.but3.bind(on_press=self.About)
        self.but4.bind(on_press=self.Iesi)

    def CatreCarusel(self, Buton):
        # am curatat layoutul
        self.layout0.clear_widgets()

        # am adaptat programul din clasa folosind obiecte dar nu merge
        # setam directia in care vom misca cu mouse-ul imaginile
        self.carousel = Carousel(direction='right')
        # setam viteza de miscare
        self.carousel.anim_move_duration = 1
        self.carousel.loop = True
        self.carousel.size_hint = (0.7, 0.7)
        self.carousel.pos = (200, 120)
        self.carousel.add_widget(self.layout0)
        self.image1 = Image(source="nature1.jpg")
        self.carousel.add_widget(self.image1)
        self.image2 = Image(source="nature2.jpg")
        self.carousel.add_widget(self.image2)
        self.image3 = Image(source="nature3.jpg")
        self.carousel.add_widget(self.image3)
        self.image1 = Image(source="nature4.jpg")
        self.carousel.add_widget(self.image4)
        self.eticheta_final = Label(text="Am ajuns la finalul listei!",
                                    font_size=30)
        self.carousel.add_widget(self.eticheta_final)

        # cream widgetul inapoiButon
        self.inapoiButon = Button(text="Inapoi",
                                  bold=True,
                                  background_color=(0, 0, 1, 1))
        self.inapoiButon.pos = (200, 100)
        self.inapoiButon.size_hint = (0.7, 0.1)
        self.inapoiButon.opacity = 0.7
        self.layout0.add_widget(self.inapoiButon)
        #legam apasarea butonului de intoarcerea la meniul principal
        self.inapoiButon.bind(on_press=self.Menu)

    def Optiuni(self, Buton):
        self.layout0.clear_widgets()

        # Cream un widget Switch si atributele sale
        self.switch1 = Switch(text="muzica")
        self.switch1.active = True
        self.switch1.size_hint = (0.3, 0.2)
        self.switch1.pos = (300, 360)
        self.layout0.add_widget(self.switch1)
        # leaga Switch-ul de metoda dezactiveaza_volum
        self.switch1.bind(active=self.dezactiveaza_volum)

        # cream un widget Label si atributele sale
        # textul de pe acesta urmand sa se schimbe odata cu volumul
        self.arata_volum = Label(text="volum: 50")
        self.arata_volum.size_hint = (0.3, 0.1)
        self.arata_volum.pos = (300, 260)
        self.layout0.add_widget(self.arata_volum)

        # cream un widget Slider si atributele sale
        # nu am urmat exact indicatiile din cerinta pt. a crea atributele
        # am incercercat sa fac fereastra sa semene cu poza
        self.slide_muzica = Slider(min=0, max=100, value=50)
        self.slide_muzica.step = 5
        self.slide_muzica.pos = (300, 100)
        self.slide_muzica.size_hint = (0.3, 0.5)
        self.slide_muzica.orientation = "horizontal"
        self.layout0.add_widget(self.slide_muzica)
        # leaga Slider-ul de metoda valoare_volum
        self.slide_muzica.bind(value=self.valoare_volum)

        # crearea widgetu-lui inapoiButon si atributelor sale
        self.inapoiButon = Button(text="Inapoi",
                                  bold=True,
                                  background_color=(0, 0, 1, 1))
        self.inapoiButon.pos = (300, 120)
        self.inapoiButon.size_hint = (0.3, 0.1)
        self.inapoiButon.opacity = 0.7
        self.layout0.add_widget(self.inapoiButon)
        # legam apasarea butonului de intoarcerea la meniul principal
        self.inapoiButon.bind(on_press=self.Menu)

    def Iesi(self, Buton):
        # Apelam sys.exit()
        sys.exit()

    def valoare_volum(self, x, y):
        # modificam Labelul arata_volum aratand valoarea integer a slide-ului
        self.arata_volum.text = "volum: " + str(int(self.slide_muzica.value))
        self.sound.volume = self.slide_muzica.value / 100

    def dezactiveaza_volum(self, x, y):
        if (self.muzica_activa % 2 == 0):
            # slide-ul este dezactivat
            self.slide_muzica.disabled = True
            # stocam valoarea slidu-lui intr-o var temporara
            self.slide_muzica.value_temp = int(self.slide_muzica.value)
            # setam valorea volumului la 0
            self.slide_muzica.value = 0
        else:
            # facem slide-ul iar available
            self.slide_muzica.disabled = False
            # reluam volumul melodiei din variabila temporara
            self.slide_muzica.value = int(self.slide_muzica.value_temp)
            self.sound.play()
        # folosim aceasta variabila pt. a contoriza switch-ul
        self.muzica_activa += 1

    def About(self, Buton):
        # crearea widgetu-lui inchide si atributelor sale
        self.inchide = Button(text="Inapoi", background_color=(0, 0, 1, 1))
        self.inchide.pos = (300, 120)
        self.inchide.size_hint = (1, 0.1)
        # legam apasarea butonului de intoarcerea la meniul principal
        self.inchide.bind(on_press=self.inchide_popup)

        # cream Label
        self.eticheta = Label(text="Multumiri InfoAcademy",
                              bold=True,
                              font_size=24)

        self.layout1 = BoxLayout()
        self.layout1.orientation = "vertical"
        self.layout1.padding = 40
        self.layout1.add_widget(self.eticheta)
        self.layout1.add_widget(self.inchide)
        self.popup = Popup()
        self.popup.background = "fundal4_tema.jpg"
        self.popup.size_hint = (None, None)
        self.popup.size = (400, 400)
        self.popup.title = 'Cine a creat aplicatia?'
        self.popup.content = self.layout1
        self.popup.open()

    def inchide_popup(self, Buton):
        self.popup.dismiss()
Ejemplo n.º 45
0
class CommonSource(AbstractSource):

    def __init__(self, **kwargs):

        super(CommonSource, self).__init__(kwargs=kwargs)

        main_layout = BoxLayout(orientation='vertical')
        on_off_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,40))
        sweep_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,40))
        buttons_configuration = GridLayout(cols=3, row_force_default=True, row_default_height=40)

        self.is_source_active = False
        self.do_a_sweep = False

        on_off_label = Label(text='Use Source')
        self.on_off_switch = Switch(active=False)
        self.on_off_switch.bind(active=self.on_off)
        on_off_layout.add_widget(on_off_label)
        on_off_layout.add_widget(self.on_off_switch)

        sweep_label = Label(text='Do Sweep')
        self.sweep_switch = Switch(active=False)
        self.sweep_switch.bind(active=self.sweepe_or_not)
        sweep_layout.add_widget(sweep_label)
        sweep_layout.add_widget(self.sweep_switch)

        init_frec_label = Label(text='Initial\nFrequency',)
        self.init_frec_value = TextInput(multiline=False)
        self.init_frec_value.disabled = True
        self.init_frec_value.bind(text=self.update_values)
        self.init_frec_unit = UnitSpinner(UnitSpinner.hz)

        final_frec_label = Label(text='Final\nFrequency')
        self.final_frec_value = TextInput(multiline=False)
        self.final_frec_value.disabled = True
        self.final_frec_value.bind(text=self.update_values)
        self.final_frec_unit = UnitSpinner(UnitSpinner.hz)

        delta_frec_label = Label(text='Frequency\nStep')
        self.delta_frec_value = TextInput(multiline=False)
        self.delta_frec_value.disabled = True
        self.delta_frec_value.bind(text=self.change_delta_frec)
        self.delta_frec_unit = UnitSpinner(UnitSpinner.hz)

        puntos_frec_label = Label(text='Number\nof Points')
        self.puntos_frec_value = TextInput(multiline=False)
        self.puntos_frec_value.disabled = True
        self.puntos_frec_value.bind(text=self.change_points_number)
        self.puntos_frec_unit = UnitSpinner(UnitSpinner.simple)

        amplitud_frec_label = Label(text='Power')
        self.amplitud_frec_value = TextInput(multiline=False)
        self.amplitud_frec_value.disabled = True
        self.amplitud_frec_value.bind(text=self._check_input_number)
        self.amplitud_frec_unit = UnitSpinner(UnitSpinner.db)


        buttons_configuration.add_widget(init_frec_label)
        buttons_configuration.add_widget(self.init_frec_value)
        buttons_configuration.add_widget(self.init_frec_unit)

        buttons_configuration.add_widget(final_frec_label)
        buttons_configuration.add_widget(self.final_frec_value)
        buttons_configuration.add_widget(self.final_frec_unit)

        buttons_configuration.add_widget(delta_frec_label)
        buttons_configuration.add_widget(self.delta_frec_value)
        buttons_configuration.add_widget(self.delta_frec_unit)

        buttons_configuration.add_widget(puntos_frec_label)
        buttons_configuration.add_widget(self.puntos_frec_value)
        buttons_configuration.add_widget(self.puntos_frec_unit)

        buttons_configuration.add_widget(amplitud_frec_label)
        buttons_configuration.add_widget(self.amplitud_frec_value)
        buttons_configuration.add_widget(self.amplitud_frec_unit)

        main_layout.add_widget(on_off_layout)
        main_layout.add_widget(sweep_layout)
        main_layout.add_widget(buttons_configuration)

        self.add_widget(main_layout)

        self.manual_change_delta = False
        self.manual_change_puntos = False
        self.manual_change_init = False
        self.manual_change_final = False

    def get_my_name(self):
        pass

    def get_my_ip(self):
        pass

    def get_my_port(self):
        pass

    def sweepe_or_not(self, spinner, text):
        self.do_a_sweep = text
        self.final_frec_value.disabled = not (text and self.is_source_active)
        self.delta_frec_value.disabled = not (text and self.is_source_active)
        self.puntos_frec_value.disabled = not (text and self.is_source_active)

    def on_off(self, spinner, text):
        self.is_source_active = text

        self.final_frec_value.disabled = not (text and self.do_a_sweep)
        self.delta_frec_value.disabled = not (text and self.do_a_sweep)
        self.puntos_frec_value.disabled = not (text and self.do_a_sweep)
        self.init_frec_value.disabled = not text
        self.amplitud_frec_value.disabled = not text


    def _check_input_number(self,instance, value):
        try:
            if len(value) > 0:
                float(value)

        except ValueError:
            if not value == '-':
                instance.text = value[0:-1]
                popup = Popup(title='Error', content=Label(text='Mal valor,\nsolo numeros'),\
                          size_hint=(None, None), size=(120, 100))
                popup.open()

    def update_values(self, instance, value):
        self._check_input_number(instance, value)

    def change_delta_frec(self, instance, value):
        self._check_input_number(instance, value)
        print 'frec'

        if self.manual_change_delta:
            self.manual_change_delta = False
            return

        frec_init = self.init_frec_value._get_text()
        frec_final = self.final_frec_value._get_text()

        if len(frec_init) < 1 or len(frec_final) < 1:
            return

        frec_init = float(frec_init)*self.init_frec_unit.get_unit_norm()
        frec_final = float(frec_final)*self.final_frec_unit.get_unit_norm()

        delta = float(self.delta_frec_value.text)*self.delta_frec_unit.get_unit_norm()

        npoints = int((delta + frec_final - frec_init)/delta) + 1

        power10 = 1
        while npoints >= 1000 or npoints < 1:
            if npoints >= 1000:
                power10 *= 10**3
                npoints *= 10**-3
            elif npoints < 1:
                power10 *=10**-3
                npoints *= 10**3

        self.manual_change_puntos = True

        self.puntos_frec_value.text = str(npoints)
        self.puntos_frec_unit.set_unit(power10)

        print 'end'

    def change_points_number(self, instance, value):
        self._check_input_number(instance, value)

        if self.manual_change_puntos:
            self.manual_change_puntos = False
            return

        frec_init = self.init_frec_value._get_text()
        frec_final = self.final_frec_value._get_text()

        if len(frec_init) < 1 or len(frec_final) < 1:
            return


        frec_init = float(frec_init)*self.init_frec_unit.get_unit_norm()
        frec_final = float(frec_final)*self.final_frec_unit.get_unit_norm()

        if frec_init > frec_final:
            return

        npoint = float(self.puntos_frec_value.text)*self.puntos_frec_unit.get_unit_norm()
        if npoint < 2:
            return

        delta = (frec_final - frec_init)/(npoint - 1)

        power10 = 1
        while delta >= 1000 or delta < 1:
            if delta >= 1000:
                power10 *= 10**3
                delta *= 10**-3
            elif delta < 1:
                power10 *=10**-3
                delta *= 10**3

        self.manual_change_delta = True

        self.delta_frec_unit.set_unit(power10)
        self.delta_frec_value.text = str(delta)

        print 'end pp'

    def is_active(self):
        return self.is_source_active

    def do_sweep(self):
        return self.do_a_sweep

    def get_source_config(self):
        data_dic = {}
        data_dic['ip'] = self.get_my_ip()
        data_dic['port'] = self.get_my_port()
        data_dic['power'] = self.amplitud_frec_value._get_text()

        if self.do_a_sweep:
            data_dic['frec_init'] = float(self.init_frec_value._get_text())*self.init_frec_unit.get_unit_norm()
            data_dic['frec_end'] = float(self.final_frec_value._get_text())*self.final_frec_unit.get_unit_norm()
            data_dic['frec_number_point'] = int(self.puntos_frec_value._get_text())*self.puntos_frec_unit.get_unit_norm()
            data_dic['instance'] = SourceThread

        else:
            data_dic['frec'] = float(self.init_frec_value._get_text())*self.init_frec_unit.get_unit_norm()
            data_dic['instance'] = ToneDCSource

        data_dic['name'] = self.get_my_name()

        return data_dic

    def save_config_dictionary(self):
        data_dic = {}

        data_dic['use_source'] = self.is_source_active
        data_dic['sweep'] = self.do_a_sweep
        data_dic['ip'] = self.get_my_ip()
        data_dic['port'] = self.get_my_port()
        data_dic['power'] = self.amplitud_frec_value._get_text()

        data_dic['frec_init'] = self.init_frec_value._get_text()
        data_dic['frec_init_unit'] = self.init_frec_unit.get_unit()
        data_dic['frec_end'] = self.final_frec_value._get_text()
        data_dic['frec_end_unit'] = self.final_frec_unit.get_unit()
        data_dic['frec_number_point'] = self.puntos_frec_value._get_text()
        data_dic['frec_numer_points_unit'] = self.puntos_frec_unit.get_unit()

        return {self.get_my_name():data_dic}

    def set_configuration(self, config_dictionary):

        if self.get_my_name() in config_dictionary:
            config_dictionary_ = config_dictionary[self.get_my_name()]

            self.is_source_active = config_dictionary_['use_source']
            self.on_off_switch.active = self.is_source_active

            self.do_a_sweep = config_dictionary_['sweep']
            self.sweep_switch.active = self.do_a_sweep

            self.amplitud_frec_value.text = config_dictionary_['power']

            self.init_frec_value.text = config_dictionary_['frec_init']
            self.init_frec_unit.text = config_dictionary_['frec_init_unit']

            self.final_frec_value.text = config_dictionary_['frec_end']
            self.final_frec_unit.text = config_dictionary_['frec_end_unit']

            self.puntos_frec_value.text = config_dictionary_['frec_number_point']
            self.puntos_frec_unit.text = config_dictionary_['frec_numer_points_unit']
Ejemplo n.º 46
0
class BeamScanner(AbstractSource):
    def __init__(self, **kwargs):
        super(BeamScanner, self).__init__(kwargs=kwargs)

        # activate the beam scanner

        self.active_state = False
        self.sweep_state = False
        sweep_label = Label(text='Do Sweep')
        self.sweep_switch = Switch(active=False)
        self.sweep_switch.bind(active=self.sweepe_or_not)



        sweep_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,40))
        sweep_layout.add_widget(sweep_label)
        sweep_layout.add_widget(self.sweep_switch)

        # this is the controll to move the beam scanner
        self.set_center = Button(text='Set Center', size_hint=(1, None), size=(1, 30))
        self.set_center.bind(on_press=self.set_zero_xy)
        self.move_up = Button(text='/\\', size_hint=(0.33, None), size=(1, 30))
        self.move_up.bind(on_press=self.move_up_beam)
        move_up_padding_l = Label(size_hint=(0.33, None), size=(1, 30))
        move_up_padding_r = Label(size_hint=(0.33, None), size=(1, 30))

        self.move_left = Button(text='<', size_hint=(0.33, None), size=(1, 30))
        self.move_left.bind(on_press=self.move_left_beam)
        self.move_rigth = Button(text='>', size_hint=(0.33, None), size=(1, 30))
        self.move_rigth.bind(on_press=self.move_rigth_beam)
        self.step_size = TextInput(size_hint=(0.33, None), size=(1, 30), multiline=False)
        self.step_size.text = '0.0'

        self.move_down = Button(text='\\/', size_hint=(0.33, None), size=(1, 30))
        self.move_down.bind(on_press=self.move_down_beam)
        move_down_padding_l = Label(size_hint=(0.33, None), size=(1, 30))
        move_down_padding_r = Label(size_hint=(0.33, None), size=(1, 30))

        move_top = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        move_top.add_widget(move_up_padding_l)
        move_top.add_widget(self.move_up)
        move_top.add_widget(move_up_padding_r)

        move_middle = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        move_middle.add_widget(self.move_left)
        move_middle.add_widget(self.step_size)
        move_middle.add_widget(self.move_rigth)

        move_bottom = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        move_bottom.add_widget(move_down_padding_l)
        move_bottom.add_widget(self.move_down)
        move_bottom.add_widget(move_down_padding_r)

        move_xy_layes = BoxLayout(orientation='vertical', size_hint=(1, None), size=(1, 120))

        move_xy_layes.add_widget(self.set_center)
        move_xy_layes.add_widget(move_top)
        move_xy_layes.add_widget(move_middle)
        move_xy_layes.add_widget(move_bottom)

        # this is the controll to rotate the beam scanner

        self.set_origin = Button(text='Set Zero', size_hint=(0.33, None), size=(1, 30))
        self.set_origin.bind(on_press=self.set_zero_ang)
        self.do_rotation = Button(text='Rotate to:', size_hint=(0.33, None), size=(1, 30))
        self.do_rotation.bind(on_press=self.rotate)
        self.destination_angle = TextInput(size_hint=(0.33, None), size=(1, 30), multiline=False)
        self.destination_angle.text = '0.0'

        rotation_layou = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        rotation_layou.add_widget(self.set_origin)
        rotation_layou.add_widget(self.do_rotation)
        rotation_layou.add_widget(self.destination_angle)

        # rotation speed

        speed_rotation = Label(text='Angular Speed', size_hint=(1, None), size=(1, 30))
        self.speed_rotation_value = TextInput(size_hint=(1, None), size=(1, 30))
        self.speed_rotation_value.text = '10.0'

        rotation_speed = BoxLayout(orientaion='horizontal', size_hint=(1, None), size=(1, 30))
        rotation_speed.add_widget(speed_rotation)
        rotation_speed.add_widget(self.speed_rotation_value)

        #  check the plane movility

        size_of_plane_label = Label(text='Plane size [mm]', size=(1, 30))
        self.size_of_plane_val = TextInput(size=(1, 30), multiline=False)
        self.size_of_plane_val.text = '0.0'
        self.size_of_plane_val.bind(focus=self.set_number_of_points)

        plane_size = BoxLayout(orientaion='horizontal', size_hint=(1, None), size=(1, 30))
        plane_size.add_widget(size_of_plane_label)
        plane_size.add_widget(self.size_of_plane_val)

        # configuration

        # frecuency

        frec_label = Label(text='Set Lambda [mm]: ', size_hint=(1, None), size=(1, 30))
        self.frec_value = TextInput(size_hint=(1, None), size=(1, 30), multiline=False)
        self.frec_value.text = '0.0'
        self.frec_value.bind(focus=self.set_number_of_points)

        frec_step = Label(text='Step factor: ', size_hint=(1, None), size=(1, 30))
        self.frec_step_value = TextInput(size_hint=(1, None), size=(1, 30), multiline=False)
        self.frec_step_value.text = '0.45'
        self.frec_step_value.bind(focus=self.set_number_of_points)

        frec_layout_val = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        frec_layout_val.add_widget(frec_label)
        frec_layout_val.add_widget(self.frec_value)

        frec_layout_step = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        frec_layout_step.add_widget(frec_step)
        frec_layout_step.add_widget(self.frec_step_value)

        frec_layout = BoxLayout(orientation='vertical', size_hint=(1, None), size=(1, 60))
        frec_layout.add_widget(frec_layout_val)
        frec_layout.add_widget(frec_layout_step)

        # display step

        step_label = Label(text='Number of Points: ')
        self.step_val = Label(text='0')

        display_step = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        display_step.add_widget(step_label)
        display_step.add_widget(self.step_val)

        # fast sweep enable

        self.fast_sweepp = ToggleButton(text='fast sweep', size_hint=(1,None), size=(1,30))

        # goto configuration

        goto_label = Label(text='Go to Position')
        self.goto_switch = Switch(active=False)
        self.goto_switch.bind(active=self.goto_or_not)

        x_dest = Label(text = 'x position [mm]')
        y_dest = Label(text = 'y position [mm]')
        theta_dest = Label(text = 'angle [Degree]')

        self.x_dest_val = TextInput(size_hint=(0.33, None), size=(1, 30), multiline=False)
        self.x_dest_val.text = '0.0'
        self.y_dest_val = TextInput(size_hint=(0.33, None), size=(1, 30), multiline=False)
        self.y_dest_val.text = '0.0'
        self.theta_dest_val = TextInput(size_hint=(0.33, None), size=(1, 30), multiline=False)
        self.theta_dest_val.text = '0.0'


        goto_layout = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        goto_layout.add_widget(goto_label)
        goto_layout.add_widget(self.goto_switch)

        goto_layout_x = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        goto_layout_x.add_widget(x_dest)
        goto_layout_x.add_widget(self.x_dest_val)

        goto_layout_y = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        goto_layout_y.add_widget(y_dest)
        goto_layout_y.add_widget(self.y_dest_val)

        goto_layout_theta = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        goto_layout_theta.add_widget(theta_dest)
        goto_layout_theta.add_widget(self.theta_dest_val)

        goto_switch = BoxLayout(orientation='vertical', size_hint=(1, None), size=(1, 120))
        goto_switch.add_widget(goto_layout)
        goto_switch.add_widget(goto_layout_x)
        goto_switch.add_widget(goto_layout_y)
        goto_switch.add_widget(goto_layout_theta)



        # big container configuration

        paddind = BoxLayout(size_hint=(1, 1), size=(1, 1000))

        self.big_one = BoxLayout(orientation='vertical')

        self.big_one.add_widget(sweep_layout)
        self.big_one.add_widget(move_xy_layes)
        self.big_one.add_widget(rotation_layou)
        self.big_one.add_widget(rotation_speed)
        self.big_one.add_widget(plane_size)
        self.big_one.add_widget(frec_layout)
        self.big_one.add_widget(display_step)
        self.big_one.add_widget(self.fast_sweepp)
        self.big_one.add_widget(goto_switch)
        self.big_one.add_widget(paddind)

        self.add_widget(self.big_one)



        # attributes that lets you connect to beam scanner

        self.ip_beam = '192.168.1.62'
        self.ip_port = 9988
        self.move_xy = MoveXY(self.ip_beam, self.ip_port)
        self.move_ang = Rotate(self.ip_beam, self.ip_port)

        # disconnect thread configuration

        self.monitor = threading.Event()
        self.disconnect = True
        self.launch_thread = False

    def sweepe_or_not(self, instance, value):
        if value:
            self.sweep_state = value
            self.goto_switch.active = False
        self.active_state = value

    def goto_or_not(self, instance, value):
        if value:
            self.sweep_state = False
            self.sweep_switch.active = False
        self.active_state = value

    def is_active(self):
        return self.active_state

    def do_sweep(self):
        return self.sweep_state

    # connecto to configure and move around
    def start_connection(self):
        self.disconnect = False
        if not self.launch_thread:
            try:
                self.move_xy.start_connection()
                self.move_ang.start_connection()
                threading.Thread(target=self.close_connection_timer).start()
                self.launch_thread = True
                try:
                    self.move_ang.set_hspd(float(self.speed_rotation_value.text))
                except:
                    pass
                return True
            except socket.error as e:
                Popup(title='Error BeamScanner', content=Label(text=e.message),
                      size_hint=(None, None), size=(200, 200)).open()
                return False
        return True

    def stop_connection(self):
        self.move_xy.close_connection()
        self.move_ang.close_connection()

    # movement of the beam scanner


    def move_left_beam(self, instance):
        if self.start_connection():
            try:
                if not self.move_xy.move_relative(float(self.step_size.text), 0):
                    self.stop_connection()
                    self.disconnect = True
            except Exception as e:
                self.stop_connection()

    def move_rigth_beam(self, instance):
        if self.start_connection():
            try:
                if not self.move_xy.move_relative(-float(self.step_size.text), 0):
                    self.stop_connection()
                    self.disconnect = True
            except Exception:
                self.stop_connection()

    def move_up_beam(self, instance):
        if self.start_connection():
            try:
                if not self.move_xy.move_relative(0, -float(self.step_size.text)):
                    self.stop_connection()
                    self.disconnect = True
            except Exception as e:
                self.stop_connection()

    def move_down_beam(self, instance):
        if self.start_connection():
            try:
                if not self.move_xy.move_relative(0, float(self.step_size.text)):
                    self.stop_connection()
                    self.disconnect = True
            except Exception as e:
                self.stop_connection()

    def rotate(self, instance):
        if self.start_connection():
            try:
                if not self.move_ang.move_absolute(float(self.destination_angle.text)):
                    self.stop_connection()
                    self.disconnect = True
            except Exception:
                self.stop_connection()

    def set_zero_xy(self, instance):
        if self.start_connection():
            try:
                if not self.move_xy.set_origin():
                    self.stop_connection()
                    self.disconnect = True
            except Exception:
                self.stop_connection()

    def set_zero_ang(self, instance):
        if self.start_connection():
            try:
                if not self.move_ang.set_origin():
                    self.stop_connection()
                    self.disconnect = True
            except Exception:
                self.stop_connection()

    def set_number_of_points(self, instance, value):
        try:
            lambda_ = float(self.frec_value.text)
            factor = float(self.frec_step_value.text)

            if lambda_*factor > 0:
                size = float(self.size_of_plane_val.text)
                points = int(0.5 + size/(lambda_*factor)) + 1
                self.step_val.text = str(points*points)
        except:
            pass

    # thead de apagado
    def close_connection_timer(self):
        print 'close function initiated'
        while 1:
            if self.disconnect:
                print 'closing function'
                self.stop_connection()
                break

            self.disconnect = True

            self.monitor.wait(15)

        self.launch_thread = False

    def get_source_config(self):
        return_dic = {}

        try :
            if self.sweep_state:
                return_dic['size'] = float(self.size_of_plane_val.text)

                return_dic['frec_number_point'] = (int(self.step_val.text))
                return_dic['angle_to_measure'] = float(self.destination_angle.text)

                return_dic['instance'] = BeamScannerController
                return_dic['angle_speed'] = float(self.speed_rotation_value.text)
                return_dic['name'] = self.get_my_name()
                return_dic['fast'] = self.fast_sweepp.state != 'normal'

                if return_dic['fast']:
                    return_dic['total_points'] = sqrt(int(self.step_val.text))*2
                    return_dic['frec_number_point'] = sqrt(int(self.step_val.text))*2
                else:
                    return_dic['total_points'] = int(self.step_val.text)
                    return_dic['frec_number_point'] = int(self.step_val.text)

            else:
                return_dic['angle_speed'] = float(self.speed_rotation_value.text)
                return_dic['name'] = self.get_my_name()
                return_dic['instance'] = BeamScannerControllerTone
                return_dic['x'] = float(self.x_dest_val.text)
                return_dic['y'] = float(self.y_dest_val.text)
                return_dic['theta'] = float(self.theta_dest_val.text)
        except:
            raise Exception('Please Enter Numbers only')


        return return_dic

    def get_my_name(self):
        return 'BeamScanner'

    def save_config_dictionary(self):
        dic_return = {}

        dic_return['on_off'] = self.active_state
        dic_return['sweep'] = self.sweep_state
        dic_return['size'] = self.size_of_plane_val.text
        dic_return['total_points'] = self.step_val.text
        dic_return['angle_to_measure'] = self.destination_angle.text
        dic_return['angle_speed'] = self.speed_rotation_value.text
        dic_return['x'] = float(self.x_dest_val.text)
        dic_return['y'] = float(self.y_dest_val.text)
        dic_return['theta'] = float(self.theta_dest_val.text)
        dic_return['lambda'] = self.frec_value.text
        dic_return['step_factor'] = self.step_size.text

        return {self.get_my_name():dic_return}

    def set_configuration(self, config_dictionary):
        if self.get_my_name() in config_dictionary:
            config_dictionary_ = config_dictionary[self.get_my_name()]
            self.active_state = config_dictionary_['on_off']
            self.sweep_state = config_dictionary_['sweep']
            self.size_of_plane_val.text = config_dictionary_['size']
            self.step_val.text = config_dictionary_['total_points']
            self.destination_angle.text = config_dictionary_['angle_to_measure']
            self.speed_rotation_value.text = config_dictionary_['angle_speed']
            self.x_dest_val.text = str(config_dictionary_['x'])
            self.y_dest_val.text = str(config_dictionary_['y'])
            self.theta_dest_val.text = str(config_dictionary_['theta'])
            self.frec_value.text = config_dictionary_['lambda']
            self.step_size.text = config_dictionary_['step_factor']

            if self.active_state:
                if self.sweep_state:
                    self.sweep_switch.active = True
                else:
                    self.goto_switch.active = True
            else:
                self.sweep_switch.active = False
                self.goto_switch.active = False
        else:
            self.sweep_switch.active = False
            self.goto_switch.active = False