Example #1
0
class Color_Picker(Selection):
    colors = {"Sky Blue": (0.529, 0.808, 0.922)}

    browse_btn = Button(text="Browse")

    #browse_btn.bind(on_release=lambda x : x.root.browse(x))
    # bind button to static FileBrowser' browse() function
    #browse_btn.bind(on_release=lambda x : FileBrowser.open(FileBrowser.instance))

    def __init__(self, **kwargs):
        super(Color_Picker, self).__init__(**kwargs)
        # Layout for selecting items
        self.dropdown = DropDown()
        self.app = MDApp.get_running_app()
        self.picker_btn.text = "Choose Color"
        self.picker_btn.bind(on_release=self.dropdown.open)

        # Add colors to dropdown
        for color in self.colors:
            btn = Button(text=color, size_hint_y=None, height=40)
            # When a color is selected the name is passed to dropdown object
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self, 'selection', x))

    def dismiss(self):
        self.dropdown.dismiss()

    def on_leave(self):
        self.dropdown.clear_widgets()
Example #2
0
class GroupDropdown(Button):
    def __init__(self, db: DBMuziek, default=None, **kwargs):
        super(GroupDropdown, self).__init__(**kwargs)

        self.dropdown = DropDown()

        self.group_id = None
        self.text = "<Choice>"

        self.update_data(default)

        self._db = db
        self.groups = None
        self.update_groups()

        self.bind(on_release=self.open)
        self.dropdown.bind(on_select=lambda _, btn: self.on_select(btn))

    def update_data(self, data):
        if data:
            self.group_id = data["group_id"]
            self.text = data["group_name"]

    def reset_choice(self, dd=None):
        if dd:
            dd.dismiss()
        self.text = "<Choice>"
        self.group_id = None

    def update_groups(self):
        self.groups = self._db.get_groups()
        self.dropdown.clear_widgets()

        btn = Button(text="<Choice>", size_hint_y=None, height=44)
        btn.bind(on_release=lambda _: self.reset_select())
        self.dropdown.add_widget(btn)

        for group in self.groups:
            btn = GroupButton(text=group["group_name"], size_hint_y=None, height=44)
            btn.set_id(group["group_id"])
            btn.bind(on_release=self.dropdown.select)

            self.dropdown.add_widget(btn)

        btn = Button(text="+", size_hint_y=None, height=44)
        btn.bind(on_release=lambda _: summon_popup_group(self._db, self.dropdown))
        self.dropdown.add_widget(btn)

    def reset_select(self):
        self.reset_choice()
        self.dropdown.select(None)

    def open(self, btn):
        self.update_groups()
        self.dropdown.open(btn)

    def on_select(self, btn=None):
        if btn is not None:
            self.text = btn.text
            self.group_id = btn.group_id
Example #3
0
class PlaylistDropdown(Button):
    def __init__(self, db: DBMuziek, **kwargs):
        super(PlaylistDropdown, self).__init__(**kwargs)
        self._db = db

        self.dropdown = DropDown()

        self.playlist_id = None
        self.text = "<Choice>"

        self.playlists = None
        self.update_playlists()

        self.bind(on_release=self.open)
        self.dropdown.bind(on_select=lambda _, btn: self.on_select(btn))

    def reset_choice(self, dd=None):
        if dd:
            dd.dismiss()
        self.text = "<Choice>"
        self.playlist_id = None

    def update_playlists(self):
        self.playlists = self._db.get_playlists()
        self.dropdown.clear_widgets()

        btn = Button(text="<Choice>", size_hint_y=None, height=44)
        btn.bind(on_release=lambda _: self.reset_select())
        self.dropdown.add_widget(btn)

        for playlist in self.playlists:
            btn = PlaylistButton(text=playlist["playlist_name"],
                                 size_hint_y=None,
                                 height=44)
            btn.set_id(playlist["playlist_id"])
            btn.bind(on_release=self.dropdown.select)

            self.dropdown.add_widget(btn)

        btn = Button(text="+", size_hint_y=None, height=44)
        btn.bind(on_release=lambda _: summon_popup_playlist(
            self._db, self.dropdown))
        self.dropdown.add_widget(btn)

    def reset_select(self):
        self.reset_choice()
        self.dropdown.select(None)

    def open(self, btn):
        self.update_playlists()
        self.dropdown.open(btn)

    def on_select(self, btn=None):
        if btn is not None:
            self.text = btn.text
            self.playlist_id = btn.playlist_id
Example #4
0
class TodayScreen(ScrollableScreen):
    def __init__(self, **kwargs):
        self.unoccupied_users = DropDown()
        self.today = "{}/{}/{}".format(gmtime().tm_year,
                                       gmtime().tm_mon,
                                       gmtime().tm_mday)
        self.button_properties = kwargs.pop('buttons_properties', dict())
        self.busy_buttons_background = kwargs.pop('busy_buttons_background',
                                                  '')
        self.dropdown_buttons_properties = kwargs.pop(
            'dropdown_buttons_properties', dict())
        self.dropdown_height = Window.height / 7 if Window.height > Window.width else Window.width / 7
        super(TodayScreen, self).__init__(**kwargs)

    def setup_widgets(self):
        for hour in range(9, 21):
            if hour > time.gmtime().tm_hour:
                self.main_layout.add_widget(
                    FontFittingButton(
                        text="{}.00 - {}.50".format(hour, hour),
                        id="{}".format(hour),
                        size_hint_y=None,
                        height=self.dropdown_height,
                        on_press=lambda a: self.display_unoccupied(a),
                        **self.button_properties))

    def display_unoccupied(self, instance):
        db_kwargs = {'date': self.today, 'hour': instance.id}
        schedule_task(callback=GetUnoccupied(**db_kwargs),
                      instance=self,
                      button_instance=instance)

    def set_unoccupied(self, unoccupied_instructors, instance):
        self.unoccupied_users.clear_widgets()
        if unoccupied_instructors:
            instance.background_normal = self.button_properties[
                'background_normal']
            for instructor in unoccupied_instructors:
                self.unoccupied_users.add_widget(
                    UserButton(text="{}".format(instructor.name),
                               user=instructor,
                               size_hint_y=None,
                               height=self.dropdown_height / 1.5,
                               on_press=lambda a: self.add_lesson(a, instance),
                               **self.dropdown_buttons_properties))
            self.unoccupied_users.open(instance)
        else:
            instance.background_normal = self.busy_buttons_background

    def add_lesson(self, instance, button):
        self.unoccupied_users.dismiss()
        App.get_running_app().root.choosen_user = instance.user
        lesson_info = dict()
        lesson_info['lesson_id'] = "0"
        lesson_info['hour'] = button.text.split(".")[0]
        LessonPopup(date=self.today, lesson_info=lesson_info).open()
Example #5
0
class NoteItem(BoxLayout):
    def __init__(self, **kwargs):
        super(NoteItem, self).__init__(**kwargs)
        self.dropdown = DropDown()

    def addNoteItem(self, w):
        '''
        inventoryitem = Inventarios()
        inventoryitem.Clave = w.parent.txt_clave.text
        inventoryitem.Producto = w.parent.txt_producto.text
        inventoryitem.Existencias = w.parent.txt_existencias.text
        inventoryitem.Minimo = w.parent.txt_minimo.text
        inventoryitem.Maximo = w.parent.txt_maximo.text
        inventoryitem.Precio = w.parent.txt_precio.text
        inventoryitem.save()
        '''

        newitem = NoteItem()
        w.text = "X"

        table = app.root.ventas.lst_note

        table.add_widget(newitem, index=len(table.layout.children))

        app.root.ventas.txt_total.text = str(
            float(app.root.ventas.txt_total.text) +
            float(w.parent.txt_total.text))

    def on_completeproduct(self, w):
        print w.text
        if len(w.text) > 2:

            self.dropdown.clear_widgets()

            #for item in app.root.inventarios:
            for item in app.root.inventarios:
                if w.text.upper() in item.Producto.upper():
                    but = WhiteButton(text=item.Producto,
                                      size_hint_y=None,
                                      height=40)
                    but.bind(on_press=self.fillProduct)
                    but.Item = item
                    self.dropdown.add_widget(but)

            self.dropdown.open(w)

    def fillProduct(self, w):

        self.txt_producto.text = w.text
        self.txt_precio.text = w.Item.Precio
        if self.txt_cant.text != "":
            self.txt_total.text = str(
                float(self.txt_cant.text) * float(self.txt_precio.text))

        self.dropdown.dismiss()
Example #6
0
class MultiSelectSpinner(Button):
    """Widget allowing to select multiple text options."""

    dropdown = ObjectProperty(None, height=40)
    """(internal) DropDown used with MultiSelectSpinner."""

    values = ListProperty([])
    # """Values to choose from."""

    selected_values = ListProperty([])

    # """List of values selected by the user."""

    def __init__(self, **kwargs):
        self.bind(dropdown=self.update_dropdown)
        self.bind(values=self.update_dropdown)
        super(MultiSelectSpinner, self).__init__(**kwargs)
        self.bind(on_release=self.toggle_dropdown)

    def toggle_dropdown(self, *args):
        self.values = atributes
        if self.dropdown.parent:
            self.dropdown.dismiss()
        else:
            self.dropdown.open(self)

    def update_dropdown(self, *args):
        if not self.dropdown:
            self.dropdown = DropDown()
        values = self.values
        if values:
            if self.dropdown.children:
                self.dropdown.clear_widgets()
            for value in values:
                b = Factory.MultiSelectOption(text=value)
                b.bind(state=self.select_value)
                self.dropdown.add_widget(b)

    def select_value(self, instance, value):
        for v in self.selected_values:
            self.selected_values.remove(v)
        self.selected_values.append(instance.text)

    def on_selected_values(self, instance, value):
        if value:
            self.text = ', '.join(value)
        else:
            self.text = ''

    def on_selected_values(self, instance, value):
        if value:
            self.text = ', '.join(value)
        else:
            self.text = ''
class TransactionDetailsDropDownButton(Button):
    def __init__(self, **kwargs):
        super(TransactionDetailsDropDownButton, self).__init__(**kwargs)
        self.text = 'All'
        self.details_id = None
        self.dropdown = DropDown()
        self.dropdown.max_height = 150
        self.populate('earnings')
        self.bind(on_release=self.dropdown.open)
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self, 'text', x[1]))
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self, 'details_id', x[0]))

    def reset_button(self):
        self.text = 'All'
        self.details_id = None

    def populate(self, earnings_or_spendings):
        self.dropdown.clear_widgets()

        transaction_details = []
        if earnings_or_spendings == "earnings":
            transaction_details = database_manager.details_read_by_type(1)
        elif earnings_or_spendings == "spendings":
            transaction_details = database_manager.details_read_by_type(0)

        btn = Button(text='All', size_hint_y=None, height=44)
        btn.data = (None, 'All')
        btn.bind(on_release=lambda btn: self.dropdown.select(btn.data))

        # then add the button inside the dropdown
        self.dropdown.add_widget(btn)

        for transaction_detail in transaction_details:
            # When adding widgets, we need to specify the height manually
            # (disabling the size_hint_y) so the dropdown can calculate
            # the area it needs.

            btn = Button(text=transaction_detail[1],
                         size_hint_y=None,
                         height=44)
            btn.data = (str(transaction_detail[0]), transaction_detail[1])

            # for each button, attach a callback that will call the select() method
            # on the dropdown. We'll pass the text of the button as the data of the
            # selection.
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.data))

            # then add the button inside the dropdown
            self.dropdown.add_widget(btn)
Example #8
0
class AnalyseWindow(Screen):
    fichiers = ObjectProperty(list)
    confirmDate = ObjectProperty(None)
    dropdown = ObjectProperty(None)
    btnSession = ObjectProperty(None)
    selected_session = ObjectProperty(None)
    user = ObjectProperty(None)
    
    def on_enter(self,*args):
        self.get_possible_file()

    def get_possible_file(self):
        path = Path(os.path.abspath(__file__)).parent.joinpath("SAVED_DATA").joinpath(User.currentUser)
        self.fichiers = os.listdir(path)
    
    def available_session(self,day):
        path = Path(os.path.abspath(__file__)).parent.joinpath("SAVED_DATA").joinpath(User.currentUser).joinpath(day)
        self.sessions = os.listdir(path)

    def confirm_date_btn(self):
        if self.confirmDate.text in self.fichiers:
            self.available_session(self.confirmDate.text)
            self.create_dropdown()
            self.btnSession.background_color = 0,1,0,1
        
        else:
            invalidFile()

    def create_dropdown(self):
        self.dropdown = DropDown()
        for session in self.sessions:
            btn = Button(text= session, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)
        self.btnSession.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.btnSession, 'text', x))
    

    def lancer_analyse_btn(self):
        self.selected_session = (self.confirmDate.text,self.btnSession.text)
        data = Data(self.selected_session[1],self.selected_session[0])
        data.analyze_my_data()

    def on_leave(self):
        self.confirmDate.text = ""
        self.btnSession.text = "session \u039E"
        self.btnSession.background_color = 0.05,0.25,0.5,1
        try:
            self.dropdown.clear_widgets()
        except AttributeError:
            pass
Example #9
0
class ResultWindow(Screen):
    source1 = ObjectProperty(None)
    source2 = ObjectProperty(None)
    dropdown2 = ObjectProperty(None)
    analyse = ObjectProperty()
    btnResult = ObjectProperty(None)
    hourLabel = ObjectProperty(None)
    resultLabel= ObjectProperty(None)
    postureLabel = ObjectProperty(None)

    
    def on_enter(self):
        self.path = Path(os.path.abspath(__file__)).parent.joinpath("SAVED_DATA").joinpath(User.currentUser).joinpath(self.analyse.selected_session[0]).joinpath(self.analyse.selected_session[1])
        self.source1.source = str(self.path.joinpath('result1.png'))
        self.available_time()
        self.get_posture()
        self.create_dropdown()
        self.source2.source =  str(Path(os.path.abspath(__file__)).parent.joinpath("posture_img").joinpath(self.postures[self.times[0]]+".png"))
        setattr(self.hourLabel,'text',"[color=3333ff]"+self.times[0]+"[/color]")
        setattr(self.postureLabel,'text',"[color=3333ff]"+self.postures[self.times[0]]+"[/color]")
        msg = Message(self.postures,User.currentUser)
        self.resultLabel.text="[color=330000]"+msg.message+"[/color]"

    def available_time(self):
        with open(self.path.joinpath('times.json'), 'r') as f:
            self.times = json.load(f)

    def get_posture(self):
        with open(self.path.joinpath('postures.json'), 'r') as f:
            self.postures = json.load(f)

    def create_dropdown(self):
        self.dropdown2 = DropDown()
        for time in self.times:
            btn = Button(text= time, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: self.dropdown2.select(btn.text))
            self.dropdown2.add_widget(btn)
        self.btnResult.bind(on_release=self.dropdown2.open)
        self.dropdown2.bind(on_select=lambda instance, x: self.display_posture(x))

    def display_posture(self,x):
        self.source2.source = str(Path(os.path.abspath(__file__)).parent.joinpath("posture_img").joinpath(self.postures[x]+".png"))
        setattr(self.hourLabel,'text',"[color=3333ff]"+x+"[/color]")
        setattr(self.postureLabel,'text',"[color=3333ff]"+self.postures[x]+"[/color]")

    def on_leave(self):
        try:
            self.dropdown2.clear_widgets()
        except AttributeError:
            pass
Example #10
0
class ComboEdit(TextInput):
    options = ListProperty((Button(text=''), ))

    def __init__(self, **kwargs):
        self.email_db = []
        if EMAILS_LIST.exists():
            with EMAILS_LIST.open() as femails:
                self.email_db = set(
                    map(lambda e: e.strip(), femails.readlines()))

        self.drop_down = DropDown()
        self.drop_down.bind(on_select=self.on_select)
        super(ComboEdit, self).__init__(**kwargs)

    def _set_suggestions(self):
        self.options = (Button(text=''), )
        if len(self.text) >= 1:
            new_options = []
            for email in self.email_db:
                if email.startswith(self.text):
                    btn = Button(text=email,
                                 font_size="30sp",
                                 size_hint_y=None,
                                 height=40)
                    new_options.append(btn)
                if len(new_options) == 3:  # Show maximum 3 suggestions
                    break
            self.options = new_options

    def add_text_to_db(self):
        self.email_db.add(str(self.text))

    def keyboard_on_key_up(self, *args):
        self._set_suggestions()
        return super(ComboEdit, self).keyboard_on_key_up(*args)

    def on_options(self, instance, value):
        self.drop_down.clear_widgets()
        for widget in value:
            widget.bind(on_release=lambda btn: self.drop_down.select(btn.text))
            self.drop_down.add_widget(widget)

    def on_select(self, *args):
        self.text = args[1]

    def on_touch_up(self, touch):
        if touch.grab_current == self:
            self.drop_down.open(self)
            self._set_suggestions()
        return super(ComboEdit, self).on_touch_up(touch)
Example #11
0
class ChannelScreen(Screen):
    def __init__(self, **kwargs):
        self.connectionHandler = kwargs.get('connectionHandler', None)
        self.screenManager = kwargs.get('screenManager', None)
        self.name = kwargs.get('channel_info', 'ChannelScreen')
        super(ChannelScreen, self).__init__()
        self.channelbutton = self.ids.channels
        self.backbutton = self.ids.back
        self.backbutton.bind(on_press=self.goBack)
        self.channelbutton.bind(on_press=self.drop_down_ch)
        self.dropdown = DropDown()

    def on_enter(self):
        self.channelbutton.text = "Channels"
        self.dropdown.clear_widgets()
        for index in range(5):
            btn = Button(text='%d' % int(index + 1),
                         size_hint_y=None,
                         height=100)
            btn.id = str(index + 1)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            btn.bind(on_press=self.connect_device)
            self.dropdown.add_widget(btn)

    def drop_down_ch(self, channelbutton):
        self.channelbutton.bind(on_release=self.dropdown.open)
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(channelbutton, 'text', x))

    def connect_device(self, btn):
        self.connectionHandler.connectDevice(self.screenManager.device_id,
                                             int(btn.id))

    def goToChannelScreen(self):
        print("goToChannelScreen")
        self.screenManager.current = 'ChannelScreen'
        self.screenManager.transition.direction = 'left'

    def goBack(self, button):
        self.goToStartingScreen()

    def goToTeleopScreen(self):
        print("goToTeleopScreen")
        self.screenManager.current = 'TeleOpScreen'
        self.screenManager.transition.direction = 'left'

    def goToStartingScreen(self):
        print("goToStartingScreen")
        self.screenManager.current = 'StartingScreen'
        self.screenManager.transition.direction = 'left'
Example #12
0
class NoteItem(BoxLayout):
    def __init__(self, **kwargs):
        super(NoteItem, self).__init__(**kwargs)
        self.dropdown = DropDown()

    def addNoteItem(self, w):
        """
        inventoryitem = Inventarios()
        inventoryitem.Clave = w.parent.txt_clave.text
        inventoryitem.Producto = w.parent.txt_producto.text
        inventoryitem.Existencias = w.parent.txt_existencias.text
        inventoryitem.Minimo = w.parent.txt_minimo.text
        inventoryitem.Maximo = w.parent.txt_maximo.text
        inventoryitem.Precio = w.parent.txt_precio.text
        inventoryitem.save()
        """

        newitem = NoteItem()
        w.text = "X"

        table = app.root.ventas.lst_note

        table.add_widget(newitem, index=len(table.layout.children))

        app.root.ventas.txt_total.text = str(float(app.root.ventas.txt_total.text) + float(w.parent.txt_total.text))

    def on_completeproduct(self, w):
        print w.text
        if len(w.text) > 2:

            self.dropdown.clear_widgets()

            # for item in app.root.inventarios:
            for item in app.root.inventarios:
                if w.text.upper() in item.Producto.upper():
                    but = WhiteButton(text=item.Producto, size_hint_y=None, height=40)
                    but.bind(on_press=self.fillProduct)
                    but.Item = item
                    self.dropdown.add_widget(but)

            self.dropdown.open(w)

    def fillProduct(self, w):

        self.txt_producto.text = w.text
        self.txt_precio.text = w.Item.Precio
        if self.txt_cant.text != "":
            self.txt_total.text = str(float(self.txt_cant.text) * float(self.txt_precio.text))

        self.dropdown.dismiss()
Example #13
0
class CustomSpinner(TextButton):
    '''Custom Appearance and implementation of the Spinner class of Kivy'''
    values = ListProperty()
    is_open = BooleanProperty(False)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.dropdown = DropDown()
        self.dropdown.bind(on_select=self.on_dropdown_select)
        self.bind(on_release=lambda _: self.open_dropdown())

    def close_dropdown(self):
        '''Close the dropdown if it is opened'''
        if self.dropdown.attach_to:
            self.is_open = False
            self.dropdown.dismiss()

    def open_dropdown(self):
        '''If the dropdown is not opened then open it'''
        if not self.dropdown.attach_to:
            self.is_open = True
            self.dropdown.open(self)

    def build_dropdown(self):
        '''Build the dropdown from the values'''
        for i, value in enumerate(self.values):
            item = TextButton(size_hint_y=None, height=dp(48), text=value)
            if is_even(i):
                item.background_color = constants.TERNARY_COLOR
            else:
                item.background_color = constants.SECONDRY_COLOR

            item.bind(
                on_release=lambda option: self.dropdown.select(option.text))
            self.dropdown.add_widget(item)

    def on_values(self, instance, values):
        '''When values change then build dropdown from those values'''
        if self.dropdown.children:
            self.dropdown.clear_widgets()
        self.build_dropdown()

    def on_dropdown_select(self, instance, value):
        '''Select the value chosen from dropdown and close the dropdown'''
        self.text = value
        self.close_dropdown()
Example #14
0
class DropdownButtonList(Button):
    def __init__(self,
                 bar_width=20,
                 bar_color=(1, 1, 1, 1),
                 bar_inactive_color=(1, 1, 1, 1),
                 scroll_type=['content', 'bars'],
                 **kwargs):
        super(DropdownButtonList, self).__init__(**kwargs)
        self.drop_list = None
        self.drop_list = DropDown(bar_width=bar_width,
                                  bar_color=bar_color,
                                  bar_inactive_color=bar_inactive_color,
                                  scroll_type=scroll_type)
        self.update_dropdown([])
        self.callback = None

        self.bind(on_release=self.drop_list.open)
        #self.drop_list.bind(on_select=lambda instance, x: setattr(self, 'text', x))
        self.drop_list.bind(on_select=self.do_select)

    def do_select(self, instance, x):
        setattr(self, 'text', x)
        if self.callback is not None:
            self.callback(x)

    def update_dropdown(self, entries):
        self.drop_list.clear_widgets()
        for i in entries:
            btn = Button(text=i,
                         size_hint_y=None,
                         height=50,
                         valign="middle",
                         padding_x=5,
                         halign='left')
            #btn.text_size = btn.size
            btn.bind(on_release=lambda btn: self.drop_list.select(btn.text))

            self.drop_list.add_widget(btn)

    def register_callback(self, callback):
        self.callback = callback
Example #15
0
class ChoicePopup(Popup):
    """
    Popup form for view schedule for group, teacher or room
    """
    btn_text = StringProperty()
    choices = ListProperty()
    choice_input = ObjectProperty(None)
    on_release = ObjectProperty(None)
    dropdown = ObjectProperty(None)

    def __init__(self, on_release, **kwargs):
        self.on_release = on_release
        super(ChoicePopup, self).__init__(**kwargs)
        self.dropdown = DropDown()
        self.choice_input.bind(text=self.make_dropdown, focus=self.on_focus)
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self.choice_input, 'text', x)
        )

    def make_dropdown(self, *args):
        self.dropdown.clear_widgets()
        for choice in self.choices:
            if self.choice_input.text in choice or self.choice_input.text == '':
                button = Button(
                    text=choice,
                    size_hint_y=None,
                    height=35
                )
                button.bind(
                    on_release=lambda btn: self.dropdown.select(btn.text)
                )
                self.dropdown.add_widget(button)
            else:
                pass
        self.dropdown.open(self.choice_input)

    @staticmethod
    def on_focus(instance, value):
        if value:
            instance.text = ''
Example #16
0
class CompleteTextInput(TextInput):
    options = ListProperty([])
    dd = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(CompleteTextInput, self).__init__(**kwargs)
        self.dd = DropDown(auto_dismiss=False)
        self.dd.bind(on_select=self.setter('text'))
        self.bind(text=self.update_complete,
                  focus=self.update_complete)

    def update_complete(self, *args):
        if self.focus:
            self.dd.clear_widgets()
            for x in app.settings.get('settings', 'servers').split(','):
                url = x.split(';')[1].strip()
                if self.text in url:
                    b = Factory.DDButton(text=url)
                    b.bind(on_release=lambda btn: self.dd.select(btn.text))
                    self.dd.add_widget(b)
            self.dd.open(self)
        else:
            self.dd.dismiss()
Example #17
0
class CommitPage(Screen):
    commit_disable = BooleanProperty(True)
    sd = StringProperty("SD card")

    def __init__(self, **kwargs):
        super(CommitPage, self).__init__(**kwargs)
        self.dd = DropDown()
        Clock.schedule_interval(self.sd_dd_update, 0.05)
        self.types = []

    def sd_dd_update(self, dt):
        self.types = list_disks()
        if (not self.sd in self.types and not self.commit_disable):
            self.dd.clear_widgets()
            self.sd = "SD card"
            self.commit_disable = True
            data.setDiskSD('')

    def sd_dd(self):
        if not self.types:
            self.dd.clear_widgets()
            self.sd = "SD card"
            self.commit_disable = True
            data.setDiskSD('')
            return
        self.dd.clear_widgets()
        for i in self.types:
            btn = Button(text=i, size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: self.dd.select(btn.text))
            self.dd.add_widget(btn)
        self.ids['dd_btn'].bind(on_release=self.dd.open)
        self.dd.bind(on_select=lambda instance, x: self.pick_sd(x))

    def pick_sd(self, x):
        self.sd = x
        data.setDiskSD(x)
        self.commit_disable = False

    def commit(self):
        if data.validate():
            print("Writing files to img")
            img = img_mount(data.getIMGFile())
            img.write_config(data.build_config())
            img.close()
            print("Commiting to SD card")
            self.flash_progress = FlashProgress()
            self.flash_progress.validate = self.ids['validate'].active
            self.flash_progress.unmount = self.ids['unmount'].active
            self.flash_progress.flash_card()
            self.flash_progress.open()
        else:
            print("Failed to validate")
Example #18
0
class StartingScreen(Screen):
    def __init__(self, **kwargs):
        self.connectionHandler = kwargs.get('connectionHandler', None)
        self.screenManager = kwargs.get('screenManager', None)
        self.name = kwargs.get('label_info', 'StartingScreen')
        super(StartingScreen, self).__init__()
        self.devicebutton = self.ids.devices
        self.devicebutton.bind(on_press=self.drop_down)
        self.dropdown = DropDown()
        self.addBool = True

        if self.connectionHandler is None:
            print("Error - You need a Connection Handler")

        self.nearby_devices = self.connectionHandler.getNearbyDevices()
        print('enumerating devices....')

        self.ids.filter_list_checkbox.bind(active=self.on_click_checkbox)
        self.ids.add_list_checkbox.bind(active=self.on_check_add)

        isActive = self.ids.filter_list_checkbox.active
        self.addActive = self.ids.add_list_checkbox.active
        self.on_click_checkbox(self.ids.filter_list_checkbox, isActive)

    def on_check_add(self, instance, value):
        if value is True:
            print("on_add_filtered_list enabled")
            self.addBool = True
        else:
            print("on_add_filtered_list disabled")
            self.addBool = False

    def on_add_filtered_list(self, instance, device_name):
        print("[StartingScreen] on_add_filtered_list")
        store = JsonStore("devices_list.json")
        if store.exists(device_name) is not True:
            print("Adding new device to the .json file...")
            store.put(device_name, name=device_name)

    def on_click_checkbox(self, instance, value):
        self.dropdown.clear_widgets()
        if (len(self.nearby_devices) > 0):

            print(len(self.nearby_devices))
            k = 0
            list, ids_devices = self.connectionHandler.filter_list(
                self.nearby_devices, value)

            for bdname in list:
                btn = Button(text=bdname, size_hint_y=None, height=100)

                btn.id = str(ids_devices[k])
                btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
                btn.bind(on_press=self.connect_device)

                self.dropdown.add_widget(btn)
                k = k + 1
        else:
            print('no devices')
            self.ids.label_info.text = "There are no paired devices. Add them manually"

    def on_enter(self):
        self.connectionHandler.setCurrentScreen(self)
        self.connectionHandler.initConnection()
        self.devicebutton.text = " Devices list"

    def drop_down(self, devicebutton):
        self.devicebutton.bind(on_release=self.dropdown.open)
        self.dropdown.bind(
            on_select=lambda instance, x: setattr(devicebutton, 'text', x))

    def connect_device(self, btn):
        print("Button Pressed")
        if self.addBool is False:
            print("Device name won't be saved.")
        else:
            self.on_add_filtered_list(self.ids.add_list_checkbox, btn.text)
        self.screenManager.device_id = int(btn.id)
        self.goToChannelScreen()

    def goToChannelScreen(self):
        print("goToChannelScreen")
        self.screenManager.current = 'ChannelScreen'
        self.screenManager.transition.direction = 'left'

    def goToStartingScreen(self):
        print("goToStartingScreen")
        self.screenManager.current = 'StartingScreen'
        self.screenManager.transition.direction = 'left'

    def goToTeleopScreen(self):
        print("goToTeleopScreen")
        self.screenManager.current = 'TeleOpScreen'
        self.screenManager.transition.direction = 'left'
Example #19
0
class MainBox(BoxLayout):
    def __init__(self, **kwargs):
        super(MainBox, self).__init__(**kwargs)

        self.main_area = self.ids.main_area
        self.search = self.ids.search
        self.drop_down = DropDown()
        self.drop_down.auto_dismiss = False
        self.round_button = RoundButton()
        self.round_button.direction = '>'

        self.main_cols = 1

        self.refresh_main_area()

    def refresh_search_actions(self, search_text):

        self.drop_down.clear_widgets()

        btn = SearchButton(text='Create new action',
                           size_hint_y=None,
                           height=Window.height / 10)
        btn.bind(on_press=self.create_new_action)
        self.drop_down.add_widget(btn)

        for action in db.actions(search_text):
            line = SearchLine()
            line.ids.action.text = str(action[0])
            line.ids.action.bind(on_press=self.choose_search_action)
            self.drop_down.add_widget(line)

    def choose_search_action(self, instance):
        self.drop_down.dismiss()
        self.append_current_action(instance.text, False)
        self.refresh_main_area()
        self.search.text = ""

    def show_search_actions(self, focused):
        if focused:
            try:
                self.drop_down.open(self.search)
            except WidgetException:
                # Возникает в случае, когда несколько раз вызывается открытие виджета
                pass
        else:
            self.drop_down.dismiss()

    def create_new_action(self, instance):
        if self.search.text == "":
            self.drop_down.dismiss()
            return
        db.create_new_action(self.search.text)
        self.choose_search_action(self.search)

    @staticmethod
    def append_current_action(action, in_progress=True):
        db.append_current_action(datetime.now(), action, in_progress)

    def refresh_main_area(self):

        self.main_area.clear_widgets()
        actions = db.current_actions()
        self.set_cols(len(actions))

        for action in actions:
            act_butt = MyActionButton(
                text=str(action[1]),
                state='down' if action[2] == 'True' else 'normal')
            act_butt.date_start = action[0]
            act_butt.my_parent = self
            self.main_area.add_widget(act_butt)

    def set_cols(self, qty):
        if qty > 5:
            self.main_cols = 2
        else:
            self.main_cols = 1
Example #20
0
class CurrentPlayer(BoxLayout):
    players = ListProperty()
    playername = StringProperty()
    playerstatus = StringProperty()
    currenttrack = StringProperty()
    albumart = ObjectProperty()

    def __init__(self, player, **kwargs):
        BoxLayout.__init__(self, **kwargs)
        self.queue = Queue()
        self.activeslider = False
        self.dropdown = DropDown()
        self.stationdropdown = DropDown()
        self.currentplayer = player
        self.playerstatus = "Pending ...."
        self.playername = self.currentplayer.group.label
        self.rendering = self.currentplayer.renderingControl.subscribe(
            event_queue=self.queue)
        self.info = self.currentplayer.avTransport.subscribe(
            event_queue=self.queue)
        self.timer = Clock.schedule_interval(self.monitor, 0)

    def teardown(self):

        Clock.unschedule(self.timer)

        if self.rendering:
            try:
                self.rendering.unsubscribe()
            except:
                pass
        if self.info:
            try:
                self.info.unsubscribe()
            except:
                pass

    def volumechanged(self, instance, value):
        try:
            if self.activeslider:
                for p in self.currentplayer.group.members:
                    p.volume = int(value)
        except:
            pass

    def play(self):
        if (self.playerstatus == "PLAYING"):
            self.currentplayer.pause()
        else:
            try:
                self.currentplayer.play()
            except:
                pass

    def radiostations(self, widget):
        self.stationdropdown.clear_widgets()
        for station in self.currentplayer.get_favorite_radio_stations()['favorites']: # noqa
            btn = Button(text='%s' % (station['title'],),
                         size_hint_y=None, height=60,
                         halign="center", valign="middle")
            btn.bind(size=btn.setter("text_size"))
            btn.bind(on_release=partial(self.playradio, station))
            self.stationdropdown.add_widget(btn)
        self.stationdropdown.open(widget)

    def playradio(self, station, widget):
        self.currentplayer.play_uri(uri=station['uri'], #noqa
                                    title=station['title'])
        self.stationdropdown.select(station['title'])

    def parserenderingevent(self, event):
        if event.variables.get('output_fixed') == 1:
            self.ids.playervolume.disabled = True
            self.ids.playervolume.value = 100
            return
        else:
            self.ids.playervolume.disabled = False

        if not self.activeslider:
            try:
                self.ids.playervolume.value = int(event.volume['Master'])
            except:
                pass

    def parseavevent(self, event):
        playerstate = event.transport_state
        if playerstate == "TRANSITIONING":
            return

        self.playerstatus = playerstate
        try:
            metadata = event.current_track_meta_data
        except:
            print event.variables
            return

        # This can happen if the the player becomes part of a group
        if metadata == "" and event.enqueued_transport_uri_meta_data == "":
            return

        self.albumart = "http://%s:1400%s#.jpg" % (
            self.currentplayer.ip_address,
            metadata.album_art_uri)

        # Is this a radio track
        if type(event.current_track_meta_data) is soco.data_structures.DidlItem: #noqa
            currenttrack = event.enqueued_transport_uri_meta_data.title
        else:
            currenttrack = "%s - %s\n%s" % (metadata.creator,
                                            metadata.title,
                                            metadata.album if
                                            hasattr(metadata, 'album') else "")
        self.currenttrack = currenttrack

    def monitor(self, dt):
        try:
            event = self.queue.get_nowait()
        except Empty:
            return

        if event.service.service_type == "RenderingControl":
            self.parserenderingevent(event)
        else:
            self.parseavevent(event)

    def volumeslider_touch_down(self, instance, touch):
        if instance.collide_point(*touch.pos):
            self.activeslider = True
            return True

    def volumeslider_touch_up(self, instance, touch):
        if touch.grab_current is instance:
            self.activeslider = False
            return True

    def makegroup(self, player, widget):
        if player in self.currentplayer.group.members:
            player.unjoin()
        else:
            player.join(self.currentplayer)
        self.updatename()

    def editgroup(self, widget):
        self.dropdown.clear_widgets()
        for player in sorted(self.currentplayer.all_zones,
                             key=lambda x: x.player_name):
            btn = ToggleButton(text='%s' % (player.player_name,),
                               size_hint_y=None, height=60)
            btn.bind(on_release=partial(self.makegroup, player))
            if player in self.currentplayer.group.members:
                btn.state = "down"
            self.dropdown.add_widget(btn)
        self.dropdown.open(widget)

    def updatename(self):
        self.playername = self.currentplayer.group.label
Example #21
0
class OCTLasagneApp(App):
    """
    Main Kivy application window.
    """
    def __init__(self, config, **kwargs):
        super(OCTLasagneApp, self).__init__(**kwargs)
        self.title = 'oct-lasagne ' + __version__  # App window title
        self.icon = 'icon.ico'
        self.datadir = config['datadir']
        self.ratio = config['ratio']
        self.locked_scans = set(config['locked'])
        self.annopath = osp.join(self.datadir, ANNOFILE)
        self.backuppath = osp.join(self.datadir, BACKUPFILE)
        self.autosave = True  # save annotation on exit
        self.isvisible = True  # toggle visibility of layer annotation
        self.viewall = False  # toggle visibility of all layers
        self.df = None  # Pandas data frame
        self.oct = None  # OCT cube as numpy array of shape n,h,w
        self.oct_id = ''  # name of OCT cube
        self.octidx = -1  # index of OCT currently displayed
        self.scanidx = 0  # index of B scan in OCT currently displayed
        self.dfindex = None  # Pandas row indices currently selected
        self.layername = None  # Layer currently selected for editing

        self.annotimer = AnnotationTimer(self.update_time_display,
                                         self.update_time_anno)

    def build(self):
        """Build the window and its contents"""
        Window.size = WINDOWSIZE
        Window.bind(on_key_down=self.key_down)
        Window.bind(on_key_up=self.key_up)
        Window.bind(on_resize=self.resized)

        def on_dropdown_select(btn):
            return lambda _, x: setattr(btn, 'text', x)

        self.octpanel = OctPanel(self,
                                 size=(1000, 1000),
                                 do_rotation=False,
                                 auto_bring_to_front=False)

        self.layerdd = DropDown()
        self.layerbtn = Button(text=BTNLAYER,
                               size=BTNSIZE,
                               size_hint=BTNHINT,
                               font_size=FNTSIZE)
        self.layerbtn.bind(on_release=self.layerdd.open)
        self.layerdd.bind(on_select=on_dropdown_select(self.layerbtn))
        self.layerbtn.disabled = True

        self.annodd = DropDown()
        for btname in [
                BTNFILTER, BTNADDLAYER, BTNDELLAYER, BTNSAVE, BTNRECOVER
        ]:
            btn = Button(text=btname,
                         size_hint_y=None,
                         height=BTNHEIGHT,
                         font_size=FNTSMALLSIZE)
            btn.bind(on_release=self.on_annotation)
            self.annodd.add_widget(btn)
        self.viewallbtn = ToggleButton(text=BTNVIEWALL[self.viewall],
                                       size_hint_y=None,
                                       height=BTNHEIGHT,
                                       font_size=FNTSMALLSIZE)
        self.viewallbtn.bind(on_release=self.on_viewall)
        self.annodd.add_widget(self.viewallbtn)
        self.isvisblebtn = ToggleButton(text=BTNISVISIBLE[self.isvisible],
                                        size_hint_y=None,
                                        height=BTNHEIGHT,
                                        font_size=FNTSMALLSIZE)
        self.isvisblebtn.bind(on_release=self.on_visible)
        self.annodd.add_widget(self.isvisblebtn)
        self.autosavebtn = ToggleButton(text=BTNAUTOSAVE[self.autosave],
                                        size_hint_y=None,
                                        height=BTNHEIGHT,
                                        font_size=FNTSMALLSIZE)
        self.autosavebtn.bind(on_release=self.on_autosave)
        self.annodd.add_widget(self.autosavebtn)
        self.annobtn = Button(text=BTNANNO,
                              size=BTNSIZE,
                              size_hint=BTNHINT,
                              font_size=FNTSIZE)
        self.annobtn.bind(on_release=self.annodd.open)
        self.annodd.bind(on_select=on_dropdown_select(self.annobtn))

        self.nextoctbtn = Button(text='OCT >>',
                                 size=BTNSIZE,
                                 size_hint=BTNHINT,
                                 font_size=FNTSIZE)
        self.nextoctbtn.bind(on_release=self.on_next_oct)
        self.prevoctbtn = Button(text='<< OCT',
                                 size=BTNSIZE,
                                 size_hint=BTNHINT,
                                 font_size=FNTSIZE)
        self.prevoctbtn.bind(on_release=self.on_prev_oct)
        self.nextscanbtn = Button(text='Scan >>',
                                  size=BTNSIZE,
                                  size_hint=BTNHINT,
                                  font_size=FNTSIZE)
        self.nextscanbtn.bind(on_release=self.on_next_scan)
        self.prevscanbtn = Button(text='<< Scan',
                                  size=BTNSIZE,
                                  size_hint=BTNHINT,
                                  font_size=FNTSIZE)
        self.prevscanbtn.bind(on_release=self.on_prev_scan)
        helpbtn = Button(text='Help',
                         size=BTNSIZE,
                         size_hint=BTNHINT,
                         font_size=FNTSIZE)
        helpbtn.bind(on_release=self.on_show_help)

        buttonlyt = BoxLayout(orientation='horizontal')
        buttonlyt.add_widget(self.annobtn)
        buttonlyt.add_widget(self.layerbtn)
        buttonlyt.add_widget(self.prevoctbtn)
        buttonlyt.add_widget(self.nextoctbtn)
        buttonlyt.add_widget(self.prevscanbtn)
        buttonlyt.add_widget(self.nextscanbtn)
        buttonlyt.add_widget(helpbtn)

        self.octnamelbl = Label(font_size=FNTSIZE)
        self.lockedlbl = Label(font_size=FNTSIZE, color=[1, 0, 0, 1])
        self.timerlbl = Label(pos=(dp(0), dp(10)), font_size=FNTSIZE)

        root = Widget()
        root.add_widget(self.octpanel)
        root.add_widget(self.octnamelbl)
        root.add_widget(self.lockedlbl)
        root.add_widget(self.timerlbl)
        root.add_widget(buttonlyt)

        self.prepare_annotation()
        self.load_annotation()
        self.show_first_oct()
        return root

    def prepare_annotation(self):
        """Create annotation file if it does not exist"""
        if osp.exists(self.annopath):
            return
        octpaths = glob(osp.join(self.datadir, '*' + OCTEXT))
        octids = [osp.splitext(osp.basename(p))[0] for p in octpaths]
        df = pd.DataFrame(octids, columns=[OCTID])
        df[DURATION] = None  # add empty duration column
        for name in LAYERS:  # add empty layer columns
            df[name] = None
        save_as_pickle(df, self.annopath)

    def resized(self, root, *args):
        """Window has been resized. Adjust label and button positions"""
        w, h = args
        self.octnamelbl.pos = (w / 2, h - 3 * BTNHEIGHT)
        self.lockedlbl.pos = (w / 2, h - 5 * BTNHEIGHT)

    def show_first_oct(self):
        """Display first scan of first OCT"""
        self.on_next_oct(None)
        self.prevoctbtn.disabled = True
        self.center_oct()

    def add_layer_btn(self, name):
        """Add button for layer with given name to dropdown menu"""
        btn = Button(text=name,
                     size_hint_y=None,
                     height=BTNHEIGHT,
                     font_size=FNTSMALLSIZE)
        btn.bind(on_release=self.on_select_layer)
        self.layerdd.add_widget(btn)
        self.layerbtn.disabled = False
        self.on_select_layer(btn)

    def update_layer_btns(self):
        """Update dropdown menu that shows layers"""
        layernames = [n.replace(PREFIX, '') for n in self.get_layernames()]
        self.layerdd.clear_widgets()
        for layername in layernames:
            self.add_layer_btn(layername)
        if not layernames:  # no layers
            self.layerdd.select(BTNLAYER)
            self.layerbtn.disabled = True

    def on_select_layer(self, btn):
        """Select layer button pressed"""
        self.layername = PREFIX + btn.text
        self.layerdd.select(btn.text)
        self.octpanel.display_scan()

    def center_oct(self):
        """Center OCT panel in main window"""
        ww, wh = Window.size
        _, sh, sw = self.oct.shape
        self.octpanel.pos = (ww - sw) / 2, (wh - sh) / 2

    def on_show_help(self, obj):
        """Show help button pressed"""
        text = Label(text=HELPTEXT, font_size=FNTSMALLSIZE)
        popup = Popup(title='Help',
                      content=text,
                      size_hint=(None, None),
                      size=POPHELPSIZE)
        popup.open()

    def update_status(self):
        """Update status text: OCT name and timer"""
        is_locked = "LOCKED" if self.scanidx in self.locked_scans else ""
        self.octnamelbl.text = '{}:{}'.format(self.oct_id, self.scanidx)
        self.lockedlbl.text = 'LOCKED' if is_locked else ''
        self.update_timer_status()

    def update_timer_status(self):
        durations = self.get_durations()
        if durations is None or durations != durations:  # None or NaN
            self.timerlbl.text = ''
            self.annotimer.reset_timing(do_callback=False, seconds=0)
        else:
            seconds = durations[self.scanidx]
            self.annotimer.reset_timing(do_callback=True, seconds=seconds)

    def update_time_display(self, seconds):
        """Update timer display with current time delta"""
        # set label to time difference in format HH:MM:SS
        tdelta = timedelta(seconds=seconds)
        self.timerlbl.text = str(tdelta).split('.')[0]

    def update_time_anno(self, seconds):
        """Update time annotation with duration in float seconds"""
        durations = self.get_durations()
        if durations is None:
            durations = [0.0 for _ in range(self.oct.shape[0])]
        durations[self.scanidx] = seconds
        self.df.at[self.dfindex[self.octidx], DURATION] = durations

    def get_durations(self):
        """Return annotation durations for current oct"""
        return self.get_cellvalue(self.octidx, DURATION)

    def get_cellvalue(self, octidx, column):
        """Return cell value from pandas table"""
        return self.df.loc[self.dfindex[octidx]][column]

    def get_layernames(self):
        return [n for n in self.df.columns.values if n.startswith(PREFIX)]

    def get_layeranno(self):
        """Return annotation for current layer or None"""
        if self.oct is None or self.layername is None:
            return None
        annos = self.get_cellvalue(self.octidx, self.layername)
        return annos[self.scanidx][1][0] if annos else None

    def get_layerannos(self):
        """Return annotation for all layer or empty list"""
        layerannos = []
        for layername in self.get_layernames():
            annos = self.get_cellvalue(self.octidx, layername)
            if annos and self.oct is not None:
                layerannos.append(annos[self.scanidx][1][0])
        return layerannos

    def update_layeranno(self):
        """Update layer annotation in pandas table"""
        def scananno():
            pointlist = []  # empty list of points
            return 'polyline', [pointlist]

        annos = self.get_cellvalue(self.octidx, self.layername)
        if annos is None:
            n = self.oct.shape[0]
            annos = tuple(scananno() for _ in range(n))
        self.df.at[self.dfindex[self.octidx], self.layername] = annos
        return annos[self.scanidx][1][0]  # pointlist

    def load_oct(self):
        """Loads the current OCT"""
        self.oct_id = self.get_cellvalue(self.octidx, OCTID)
        self.scanidx = 0
        self.prevscanbtn.disabled = True
        octpath = osp.join(self.datadir, self.oct_id + OCTEXT)
        cube = np.load(octpath)
        dtype = cube.dtype
        dim = len(cube.shape)
        assert dtype == 'uint8', ('Expect OCT data type to be uint8 but got ' +
                                  str(dtype))
        assert dim == 3, ('Expect OCT data to have three dimensions but got ' +
                          str(cube.shape))
        return cube

    def display_oct_scan(self):
        """Displays the current OCT scan"""
        self.octpanel.display_scan()
        self.update_status()

    def on_annotation(self, btn):
        """Annotation button pressed"""
        self.annodd.select(btn.text)
        if btn.text == BTNSAVE:
            self.save_annotation()
        elif btn.text == BTNRECOVER:
            self.load_backup()
        elif btn.text == BTNFILTER:
            self.filter_data_dialog()
        elif btn.text == BTNADDLAYER:
            self.add_layer_dialog()
        elif btn.text == BTNDELLAYER:
            self.del_layer_dialog()

    def filter_data_dialog(self):
        """Dialog for filtering pandas rows = OCTs"""
        filterin = TextInput(text='', multiline=False, font_size=FNTSIZE)

        def dismissed(_):
            query = filterin.text
            self.filter_table(query)
            print('select rows:', filterin.text)
            print('#rows selected:', len(self.dfindex))
            if not len(self.dfindex):
                self.filter_table('')
            self.show_first_oct()
            return False

        selectpu = Popup(title='Filter data',
                         size_hint=(None, None),
                         size=POPSMALLSIZE)
        selectpu.add_widget(filterin)
        selectpu.bind(on_dismiss=dismissed)
        selectpu.open()

    def add_layer_dialog(self):
        """Dialog to add a new layer for annotation"""
        layerin = TextInput(text='', multiline=False, font_size=FNTSIZE)

        def dismissed(_):
            layername = layerin.text
            if layername:
                colname = PREFIX + layername
                self.df = self.df.assign(**{colname: lambda x: None})
                self.update_layer_btns()
            return False

        layerpu = Popup(title='Add layer annotation',
                        size_hint=(None, None),
                        size=POPSMALLSIZE)
        layerpu.add_widget(layerin)
        layerpu.bind(on_dismiss=dismissed)
        layerpu.open()

    def del_layer_dialog(self):
        """Dialog to delete an existing annotation layer"""
        layerin = TextInput(text='', multiline=False, font_size=FNTSIZE)

        def dismissed(_):
            layername = layerin.text
            if layername:
                colname = PREFIX + layername
                self.df = self.df.drop(colname, axis=1)
                self.update_layer_btns()
            return False

        layerpu = Popup(title='Delete layer annotation',
                        size_hint=(None, None),
                        size=POPSMALLSIZE)
        layerpu.add_widget(layerin)
        layerpu.bind(on_dismiss=dismissed)
        layerpu.open()

    def filter_table(self, query):
        """Filter pandas table with given query"""
        filtereddf = self.df.query(query,
                                   engine='python') if query else self.df
        self.dfindex = filtereddf.index.tolist()
        self.oct = None
        self.oct_id = ''
        self.octidx = -1
        self.scanidx = 0

    def load_backup(self):
        def cancel(_):
            popup.dismiss()

        def ok(_):
            print('loading backup... ', self.backuppath, end='...')
            self.df = load_dataframe(self.backuppath)
            print('done.')
            self.filter_table(query='')
            self.update_layer_btns()
            self.show_first_oct()
            popup.dismiss()

        btnok = Button(text='Yes',
                       size=BTNSIZE,
                       size_hint=BTNHINT,
                       font_size=FNTSIZE)
        btcancel = Button(text='Cancel',
                          size=BTNSIZE,
                          size_hint=BTNHINT,
                          font_size=FNTSIZE)
        btnok.bind(on_release=ok)
        btcancel.bind(on_release=cancel)
        buttonlyt = BoxLayout(orientation='horizontal')
        buttonlyt.add_widget(btnok)
        buttonlyt.add_widget(btcancel)
        popup = Popup(title='Load backup: are you sure?',
                      content=buttonlyt,
                      size_hint=(None, None),
                      size=(dp(230), dp(110)))
        popup.open()

    def load_annotation(self):
        """Load pandas table with annotation data"""
        print('loading annotation ...', self.annopath, end='...')
        self.df = load_dataframe(self.annopath)
        print('done.')
        # self.df.info()
        # print(self.df.head())
        self.filter_table(query='')
        self.update_layer_btns()

    def save_annotation(self):
        """Save annotation to pandas table"""
        if not self.df is None:
            print('saving annotation...', self.annopath, end='...')
            save_dataframe(self.df, self.annopath)
            print('done.')

    def save_backup(self):
        """Save annotation to backup pandas table"""
        if not self.df is None:
            print('saving backup... ', self.backuppath, end='...')
            save_dataframe(self.df, self.backuppath)
            print('done.')

    def on_next_oct(self, obj):
        """Next OCT button pressed"""
        n = len(self.dfindex) - 1
        self.annotimer.stop_timing()
        self.octidx += 0 if self.octidx >= n else 1
        self.nextoctbtn.disabled = self.octidx >= n
        self.prevoctbtn.disabled = False
        self.oct = self.load_oct()
        self.display_oct_scan()

    def on_prev_oct(self, obj):
        """Previous OCT button pressed"""
        self.annotimer.stop_timing()
        self.octidx -= 0 if self.octidx <= 0 else 1
        self.prevoctbtn.disabled = self.octidx <= 0
        self.nextoctbtn.disabled = False
        self.oct = self.load_oct()
        self.display_oct_scan()

    def on_prev_scan(self, obj):
        """Previous Scan button pressed"""
        self.annotimer.stop_timing()
        self.scanidx -= 0 if self.scanidx <= 0 else 1
        self.prevscanbtn.disabled = self.scanidx <= 0
        self.nextscanbtn.disabled = False
        self.display_oct_scan()

    def on_next_scan(self, obj):
        """Next Scan button pressed"""
        n = self.oct.shape[0] - 1
        self.annotimer.stop_timing()
        self.scanidx += 0 if self.scanidx >= n else 1
        self.nextscanbtn.disabled = self.scanidx >= n
        self.prevscanbtn.disabled = False
        self.display_oct_scan()

    def on_stop(self):
        """Stop application"""
        self.annotimer.event.set()  # stop timer
        if self.autosave:
            self.save_annotation()
        self.save_backup()
        return True

    def on_visible(self, btn):
        """Toggle visibility of layer annotation"""
        self.isvisible = not self.isvisible
        btn.text = BTNISVISIBLE[self.isvisible]
        self.octpanel.display_scan()

    def on_viewall(self, btn):
        """Toggle visibility of all layer annotations"""
        self.viewall = not self.viewall
        btn.text = BTNVIEWALL[self.viewall]
        self.octpanel.display_scan()

    def on_autosave(self, btn):
        """Toggle autosave"""
        self.autosave = not self.autosave
        btn.text = BTNAUTOSAVE[self.autosave]

    def key_down(self, key, scancode, codepoint, modifier, kwargs):
        """React on key press"""
        if scancode == KEYUP:
            self.prevoctbtn.trigger_action()
        elif scancode == KEYDOWN:
            self.nextoctbtn.trigger_action()
        elif scancode == KEYLEFT:
            self.prevscanbtn.trigger_action()
        elif scancode == KEYRIGHT:
            self.nextscanbtn.trigger_action()
        elif scancode == KEYLV:
            self.isvisblebtn.trigger_action()
        elif scancode == KEYLA:
            self.viewallbtn.trigger_action()
        elif scancode == KEYLS:
            self.annotimer.toggle_timing()
        elif scancode == KEYLR:
            self.annotimer.reset_timing()
        self.octpanel.editmode = EDITMODES.get(scancode, EDITOFF)

    def key_up(self, *wargs):
        """Keys released."""
        self.octpanel.editmode = EDITOFF
Example #22
0
class Pos(BoxLayout):
    def __init__(self, **kwargs):
        super(Pos, self).__init__(**kwargs)

        self.cliente = None

    def hacerNota(self):

        if self.txt_client.text == "":
            MessageBoxTime(title="Ops",
                           size_hint=(None, None),
                           size=(350, 120),
                           msg="Por favor especifica el cliente",
                           duration=2).open()
            return
        elif self.cliente == None:
            MessageBoxTime(title="Espere",
                           size_hint=(None, None),
                           size=(350, 120),
                           msg="Guardando cliente",
                           duration=2).open()

        print "Realizando nota"
        nota = Notas()
        nota.PUser = app.root.user
        nota.Total = self.txt_total.text
        nota.Cliente = self.cliente

        products = []

        for i in self.lst_note.layout.children:
            print i.txt_producto.text

            products.append({
                "Cantidad": i.txt_cant.text,
                "Product": i.txt_producto.text,
                "Precio": i.txt_precio.text,
                "Total": i.txt_total.text,
            })

        nota.Productos = products

        nota.save()

        #limpiar controles de nota
        self.lst_note.clear()
        self.lst_note.add_widget(NoteItem())
        self.txt_client.text = ""
        self.txt_total.text = "0"
        self.img_button.source = "plus.png"

        self.cliente = None

    def on_completeclient(self, w):

        if not hasattr(self, "dropdown"):
            self.dropdown = DropDown()

        if len(w.text) > 2:

            self.dropdown.clear_widgets()

            found = False

            for item in Clientes.Query.filter(
                    words__all=w.text.upper().split()):

                but = WhiteButton(text=item.Name, size_hint_y=None, height=40)
                but.bind(on_press=self.fillClient)
                but.Cliente = item
                self.dropdown.add_widget(but)
                found = True

            if found:
                self.dropdown.open(w)

    def fillClient(self, w):

        self.txt_client.text = w.text

        self.img_button.source = "ok.png"

        self.cliente = w.Cliente

        self.dropdown.dismiss()

    def addClient(self):
        print "Adding the client: " + self.txt_client.text

        self.cliente = Clientes()
        self.cliente.Name = self.txt_client.text
        self.cliente.PUser = app.root.user
        self.cliente.save()

        self.img_button.source = "ok.png"

    def fillNotas(self):
        print "Llenado lista de notas"

        for i in app.root.notas:
            print i
            notareg = NoteReg()
            notareg.txt_fecha.text = str(i.createdAt)
            if i.Cliente != None:
                notareg.txt_cliente.text = i.Cliente.Name
            notareg.txt_total.text = str(i.Total)

            self.lst_notas.add_widget(notareg)
Example #23
0
class RemoteCommand(App):
    commands = ListProperty([])
    container = ObjectProperty(None)
    status = ObjectProperty(None)
    log = StringProperty('')
    mouse_sensivity = NumericProperty(1)
    screen_texture = ObjectProperty(None)
    capture_fps = NumericProperty(0)
    image_size = NumericProperty(128)
    dropdown = ObjectProperty(None)
    mods = DictProperty({})
    mouse_pos = ListProperty([0, 0])
    protocol = ObjectProperty(None, allownone=True)
    interface = ObjectProperty(None)
    processes = DictProperty({})
    curtain = ObjectProperty(None)

    def connect(self, ip, port):
        Window.release_keyboard()

        if self.dropdown:
            self.dropdown.dismiss()

        self.protocol = None
        point = TCP4ClientEndpoint(reactor, ip, int(port))
        d = point.connect(CommandClientFactory())
        d.addCallback(self.got_protocol)
        self.log += u"trying to connect…\n"
        self.leftover = ''

        if ip not in self.config.items('connections'):
            self.config.set('connections', ip, str(port))

    def send(self, *args, **kwargs):
        self.protocol.sendMessage(json_encode(kwargs))

    def update_screen(self, *args):
        if self.interface.current_tab.text == 'image':
            self.send(command='capture',
                      size=(self.image_size, self.image_size))

    def propose_addresses(self, address_input):
        if address_input.focus:
            if not self.dropdown:
                self.dropdown = DropDown()
                #self.dropdown.bind(on_select=self.complete_address)
            else:
                self.dropdown.clear_widgets()

            connections = self.config.items('connections')

            for c in connections:
                if c[0].startswith(address_input.text):
                    lbl = Button(text=':'.join(c), size_hint_y=None,
                                 height=sp(30))
                    lbl.bind(on_press=lambda x:
                             self.connect(*x.text.split(':')))
                    self.dropdown.add_widget(lbl)

            self.dropdown.open(address_input.parent)

    def receive(self, stream):
        stream = self.leftover + stream
        while stream:
            try:
                datadict, index = json_decode(stream)
                self.leftover = ''
            except ValueError:
                # incomplete data, keep to analyse later
                self.leftover = stream
                return

            stream = stream[index:]

            #self.log += 'got data: %s\n' % datadict
            if not isinstance(datadict, dict):
                # something went wrong, gtfo for now, FIXME
                print "didn't get a dict for datadict"
                return

            if 'commands' in datadict:
                self.commands = datadict['commands']

            if 'process' in datadict:
                process = datadict['process']
                status = datadict.get('status', None)

                if status == 'started':
                    label = Label(text=datadict['name'],
                                  size_hint_y='None',
                                  height='30dp')

                    out = Button(text='output log')
                    err = Button(text='error log')
                    kill = Button(text='close')

                    kill.bind(on_release=lambda *args:
                              self.send(command='kill', uid=process))
                    out.bind(on_release=lambda *args:
                             self.display_out(process))
                    err.bind(on_release=lambda *args:
                             self.display_out(process, 'err'))

                    box = BoxLayout(size_hint_y=None, height=sp(20))
                    box.add_widget(label)
                    box.add_widget(out)
                    box.add_widget(err)
                    box.add_widget(kill)

                    self.processes[process] = {
                        'label': label,
                        'box': box,
                        'kill': kill,
                        'out': '', 'err': ''}

                    self.status.add_widget(box)

                elif status == 'ended':
                    box = self.processes[process]['box']
                    if datadict['autoclose']:
                        app.status.remove_widget(box)
                    else:
                        label = self.processes[process]['label']
                        label.text += ' - DONE'
                        kill = self.processes[process]['kill']
                        box.remove_widget(kill)
                        close = Button(text='close')
                        close.bind(on_release=lambda *args:
                                   app.status.remove_widget(box))
                        box.add_widget(close)

                elif 'stdout' in datadict:
                    self.processes[process]['out'] += datadict['stdout'].\
                        decode('base64')

                elif 'stderr' in datadict:
                    self.processes[process]['err'] += datadict['stderr'].\
                        decode('base64')

            if 'mouse_pos' in datadict:
                self.mouse_pos = datadict['mouse_pos']

            if 'image' in datadict:
                #print "receiving capture"
                uid = datadict['image']
                if uid not in self.images:
                    fn = 'tmp-%s.png' % uid
                    self.images[uid] = [
                        fn,  # filename
                        open(fn, 'w'),  # file descriptor
                        0,  # next expected chunk
                        {}  # chunks arrived too early
                    ]

                fn, f, c, chunks = self.images[uid]

                data = datadict['data']
                chunk = datadict['chunk']
                #print'receiving %s chunk %s data %s' % (uid, chunk, data[:10])

                if chunk == c:
                    if not data:
                        #print "empty chunk, closing"
                        f.close()
                        move(fn, 'tmp.png')
                        self.screen_texture.reload()
                        del self.images[uid]

                    else:
                        f.write(datadict['data'].decode('base64'))
                        #print "writting chunk", c
                        c += 1

                else:
                    chunks[chunk] = data.decode('base64')

                while c in chunks:
                    #print "applying chunk %s that we got before" % c
                    f.write(chunks[c])
                    c += 1

                if data:
                    self.images[uid] = fn, f, c, chunks

    def process_menu(self, process, *args):
        pass

    def display_out(self, uid, out='out'):
        process = self.processes[uid]
        p = Popup(size_hint=(.95, .95),
                  title='std%s %s' % (out, process['label'].text))
        sc = ScrollView()
        content = Label(text=process[out], size_hint=(None, None))
        sc.bind(width=content.setter('width'))
        content.bind(width=lambda c, w:
                     content.setter('text_size')(c, (w, None)))
        content.bind(texture_size=content.setter('size'))
        sc.add_widget(content)
        p.add_widget(sc)
        p.open()

    def got_protocol(self, p):
        self.log += "got protocol\n"
        self.protocol = p

    def on_protocol(self, *args):
        if not self.protocol:
            Animation(top=self.interface.top, d=.5, t='in_quad').start(
                self.curtain)
        else:
            Animation(top=0, d=.5, t='out_quad').start(self.curtain)

    def on_capture_fps(self, *args):
        Clock.unschedule(self.update_screen)
        if self.capture_fps:
            Clock.schedule_interval(self.update_screen, 1 / self.capture_fps)

    def on_commands(self, *args):
        self.container.clear_widgets()
        self.log += 'got a list of commands!\n'
        for command, arguments in self.commands:
            box = BoxLayout(height=sp(30))
            button = Button(text=command)

            args_inputs = []
            for arg in arguments.split(','):
                if arg == 'str':
                    txtinput = TextInput()
                    args_inputs.append(txtinput)
                    box.add_widget(txtinput)

            button.bind(on_press=partial(
                self.execute, command, arguments.split(','), args_inputs))
            box.add_widget(button)

            self.container.add_widget(box)

    def execute(self, command, arguments, args_inputs, *args):
        values = []
        for arg_type, arg_input in zip(arguments, args_inputs):
            if arg_type == 'str':
                values.append(arg_input.text)

        self.send(run=command, arguments=values)

    def mouse_move(self, dx, dy):
        self.send(command='mouse', action='move',
                  dx=int(round(dx * self.mouse_sensivity)),
                  dy=-int(round(dy * self.mouse_sensivity)))

    def mouse_click(self, b=1, n=2):
        self.send(command='mouse', action='click', b=b, n=n)

    def mouse_press(self, b=1):
        #self.log += 'mouse pressed\n'
        self.send(command='mouse', action='press', b=b)

    def mouse_release(self, b=1):
        #self.log += 'mouse released\n'
        self.send(command='mouse', action='release', b=b)

    def send_keys(self, string):
        self.send(command='type', string=string)

    def press_special_key(self, key):
        self.send(command='press_key', key=key.text)

    def release_special_key(self, key):
        self.send(command='release_key', key=key.text)

    def on_start(self, *args):
        self.config = ConfigParser()
        self.config.read(CONFIG)
        self.images = {}

        if not self.config.has_section('connections'):
            self.config.add_section('connections')

            with open(CONFIG, 'w') as f:
                self.config.write(f)

    def on_pause(self, *args):
        with open(CONFIG, 'w') as f:
            self.config.write(f)
        return True

    def on_resume(self, *args):
        return True

    def on_stop(self, *args):
        with open(CONFIG, 'w') as f:
            self.config.write(f)
        return True

    def populate_keyboard(self, grid):
        b = Button(text='escape')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)

        for f in range(12):
            b = Button(text='f%d' % (f + 1))
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        for i in range(13):
            grid.add_widget(Widget())

        grid.add_widget(Widget())

        b = Button(text='up')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)

        for i in range(2):
            grid.add_widget(Widget())

        for t in 'home', 'end':
            b = Button(text=t)
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        grid.add_widget(Widget())

        b = Button(text='shift')
        grid.add_widget(b)
        self.mods['shift'] = b

        b = Button(text='control')
        grid.add_widget(b)
        self.mods['control'] = b

        b = Button(text='alt')
        grid.add_widget(b)
        self.mods['alt'] = b

        b = Button(text='meta')
        grid.add_widget(b)
        self.mods['meta'] = b

        grid.add_widget(Widget())

        b = Button(text='backspace')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)

        #for i in range(5):
            #grid.add_widget(Widget())

        for t in 'left', 'down', 'right':
            b = Button(text=t)
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        grid.add_widget(Widget())

        for t in 'up', 'down':
            b = Button(text='page%s' % t)
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        for i in range(6):
            grid.add_widget(Widget())

        b = Button(text='return')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)
Example #24
0
class SelectionArea(GridLayout):
    def __init__(self, **kwargs):
        super(SelectionArea, self).__init__(**kwargs)
        self.datadir = './Data/'
        self.plotdir = './Plots/'
        self.delim = ','
        self.data = {}

        # Layout configuration
        self.cols = 1
        self.rows = 7
        self.spacing = 20

        self.CreateWidgets()
        self.CreateBindings()
        self.AddWidgets()

    # Helpers
    def CreateWidgets(self):
        # Layouts
        self.data_file_info_holder = GridLayout(cols=2, rows=1)
        self.x_value_holder = GridLayout(cols=2, rows=1)
        self.y_value_holder = GridLayout(cols=2, rows=1)
        self.title_holder = GridLayout(cols=2, rows=1)
        self.limit_holder = GridLayout(cols=4, rows=3)
        self.log_holder = GridLayout(cols=2, rows=1)
        self.plot_button_holder = GridLayout(cols=3, rows=1)

        # Labels
        self.data_fname_label = Label(text='Data file: ',
                                      halign='right',
                                      size_hint=(1, 0.5))
        self.x_val_label = Label(text='X Value: ',
                                 halign='right',
                                 size_hint=(1, 0.5))
        self.y_val_label = Label(text='Y Value: ',
                                 halign='right',
                                 size_hint=(1, 0.5))
        self.x_min_label = Label(text='Min x value: ',
                                 halign='right',
                                 size_hint=(1, 1))
        self.x_max_label = Label(text='Max x value: ',
                                 halign='right',
                                 size_hint=(1, 1))
        self.y_min_label = Label(text='Min y value: ',
                                 halign='right',
                                 size_hint=(1, 1))
        self.y_max_label = Label(text='Max y value: ',
                                 halign='right',
                                 size_hint=(1, 1))
        self.x_label_label = Label(text='X-axis label: ',
                                   halign='right',
                                   size_hint=(1, 1))
        self.y_label_label = Label(text='Y-axis label: ',
                                   halign='right',
                                   size_hint=(1, 1))
        self.title_label = Label(text='Graph title: ',
                                 halign='right',
                                 size_hint=(1, 0.5))

        # Text input
        self.x_min = TextInput(multiline=False, write_tab=False)
        self.x_max = TextInput(multiline=False, write_tab=False)
        self.y_min = TextInput(multiline=False, write_tab=False)
        self.y_max = TextInput(multiline=False, write_tab=False)
        self.x_label = TextInput(multiline=False, write_tab=False)
        self.y_label = TextInput(multiline=False, write_tab=False)
        self.title = TextInput(multiline=False,
                               write_tab=False,
                               size_hint=(1, 0.5))

        # Dropdowns
        self.x_val_dropdown = DropDown()
        self.y_val_dropdown = DropDown()
        self.data_fname_dropdown = self.CreateDataFilenameDropdown(
            self.datadir)

        # Buttons
        self.data_fname_btn = Button(text='Please select data file.',
                                     size_hint_y=0.5,
                                     height=40)
        self.x_val_btn = Button(text='Please select x value.',
                                size_hint_y=0.5,
                                height=40)
        self.y_val_btn = Button(text='Please select y value.',
                                size_hint_y=0.5,
                                height=40)
        self.plot_btn = Button(text='Plot values!',
                               size_hint_y=1,
                               height=40,
                               background_color=(0, 0, 255, 0.8))
        self.clear_btn = Button(text='Clear plot',
                                size_hint_y=1,
                                height=40,
                                background_color=(255, 0, 0, 0.8))
        self.save_btn = Button(text='Save plot',
                               size_hint_y=1,
                               height=40,
                               background_color=(0, 255, 0, 0.8))

        # Toggle buttons
        self.x_log_btn = ToggleButton(text='Logrithmic x-axis?')
        self.y_log_btn = ToggleButton(text='Logrithmic y-axis?')

    def AddWidgets(self):
        self.data_file_info_holder.add_widget(self.data_fname_label)
        self.data_file_info_holder.add_widget(self.data_fname_btn)

        self.x_value_holder.add_widget(self.x_val_label)
        self.x_value_holder.add_widget(self.x_val_btn)

        self.y_value_holder.add_widget(self.y_val_label)
        self.y_value_holder.add_widget(self.y_val_btn)

        self.title_holder.add_widget(self.title_label)
        self.title_holder.add_widget(self.title)

        self.limit_holder.add_widget(self.x_min_label)
        self.limit_holder.add_widget(self.x_min)

        self.limit_holder.add_widget(self.y_min_label)
        self.limit_holder.add_widget(self.y_min)

        self.limit_holder.add_widget(self.x_max_label)
        self.limit_holder.add_widget(self.x_max)

        self.limit_holder.add_widget(self.y_max_label)
        self.limit_holder.add_widget(self.y_max)

        self.limit_holder.add_widget(self.x_label_label)
        self.limit_holder.add_widget(self.x_label)

        self.limit_holder.add_widget(self.y_label_label)
        self.limit_holder.add_widget(self.y_label)

        self.log_holder.add_widget(self.x_log_btn)
        self.log_holder.add_widget(self.y_log_btn)

        self.plot_button_holder.add_widget(self.clear_btn)
        self.plot_button_holder.add_widget(self.save_btn)
        self.plot_button_holder.add_widget(self.plot_btn)

        self.add_widget(self.data_file_info_holder)
        self.add_widget(self.x_value_holder)
        self.add_widget(self.y_value_holder)
        self.add_widget(self.title_holder)
        self.add_widget(self.limit_holder)
        self.add_widget(self.log_holder)
        self.add_widget(self.plot_button_holder)

    def CreateBindings(self):
        # Button Bindings
        self.data_fname_btn.bind(on_release=self.data_fname_dropdown.open)
        self.x_val_btn.bind(on_release=self.x_val_dropdown.open)
        self.y_val_btn.bind(on_release=self.y_val_dropdown.open)
        self.plot_btn.bind(on_release=self.PlotSelectedValues)
        self.clear_btn.bind(on_release=self.ClearPlot)
        self.save_btn.bind(on_release=self.SavePlot)

        # ToggleButton Bindings
        self.x_log_btn.bind(state=self.LogrithmicX)
        self.y_log_btn.bind(state=self.LogrithmicY)

        # Dropdown bindings
        self.data_fname_dropdown.bind(on_select=self.ProcessDataFile)
        self.x_val_dropdown.bind(
            on_select=lambda inst, x: setattr(self.x_val_btn, 'text', x))
        self.y_val_dropdown.bind(
            on_select=lambda inst, x: setattr(self.y_val_btn, 'text', x))

        # TextInput bindings
        self.x_min.bind(focus=self.UpdateAxisLimits)
        self.x_max.bind(focus=self.UpdateAxisLimits)
        self.y_min.bind(focus=self.UpdateAxisLimits)
        self.y_max.bind(focus=self.UpdateAxisLimits)
        self.x_label.bind(focus=self.UpdateXLabel)
        self.y_label.bind(focus=self.UpdateYLabel)
        self.title.bind(focus=self.UpdateTitle)

    def RebindDropdowns(self):
        self.x_val_btn.bind(on_release=self.x_val_dropdown.open)
        self.y_val_btn.bind(on_release=self.y_val_dropdown.open)
        self.x_val_dropdown.bind(
            on_select=lambda inst, x: setattr(self.x_val_btn, 'text', x))
        self.y_val_dropdown.bind(
            on_select=lambda inst, x: setattr(self.y_val_btn, 'text', x))

    # Callbacks
    def CreateDataFilenameDropdown(self, datadir):
        dropdown = DropDown()
        for (dirpath, dirnames, filenames) in os.walk(datadir):
            for filename in sorted(filenames):
                if filename.endswith('.csv'):
                    btn = Button(text=filename, size_hint_y=None, height=44)
                    btn.bind(on_release=lambda btn: dropdown.select(btn.text))
                    dropdown.add_widget(btn)
        return dropdown

    def CreateDataLabelDropdown(self, dropdown):
        for label in self.data.keys():
            btn = Button(text=label, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)
        return dropdown

    def ProcessDataFile(self, instance, x):
        self.x_val_dropdown.clear_widgets()
        self.y_val_dropdown.clear_widgets()
        setattr(self.data_fname_btn, 'text', x)
        self.data = {}
        with open(self.datadir + x) as csvf:
            reader = csv.reader(csvf, delimiter=self.delim)
            for label in reader.__next__():
                self.data[label] = []
            n_label = len(self.data.keys())
            for row in reader:
                assert len(
                    row
                ) == n_label, '\n\tCSV Error: Number of data != Number of labels'
                i = 0
                for label in self.data.keys():
                    if row[i] != '':
                        print(row[i])
                        self.data[label].append(float(row[i]))
                    else:
                        self.data[label].append(0)
                    i += 1
        self.CreateDataLabelDropdown(self.x_val_dropdown)
        self.CreateDataLabelDropdown(self.y_val_dropdown)
        self.RebindDropdowns()

    # Plotting methods
    def PlotSelectedValues(self, instance):
        x_label = self.x_val_btn.text
        y_label = self.y_val_btn.text
        x_data = self.data[x_label]
        y_data = self.data[y_label]
        plt.plot(x_data, y_data, label=y_label)
        #plt.scatter(x_data,y_data,s=5,label=y_label)
        #plt.legend()
        canvas = plt.gcf().canvas
        canvas.draw()
        x_min, x_max = plt.gca().get_xlim()
        y_min, y_max = plt.gca().get_ylim()
        self.x_min.text = str(x_min)
        self.x_max.text = str(x_max)
        self.y_min.text = str(y_min)
        self.y_max.text = str(y_max)

    def ClearPlot(self, instance):
        plt.clf()
        canvas = plt.gcf().canvas
        canvas.draw()

    def SavePlot(self, instance):
        if self.title != '':
            fname = self.plotdir + self.title.text + '.png'
        else:
            fname = self.plotdir + 'default'
        fig = plt.figure()
        x_label = self.x_val_btn.text
        y_label = self.y_val_btn.text
        x_data = self.data[x_label]
        y_data = self.data[y_label]
        plt.scatter(x_data, y_data, s=5)
        plt.title(self.title.text)
        plt.xlabel(self.x_label.text)
        plt.ylabel(self.y_label.text)
        try:
            a = [
                float(self.x_min.text),
                float(self.x_max.text),
                float(self.y_min.text),
                float(self.y_max.text)
            ]
        except ValueError:
            a = None
        if a != None:
            plt.axis(a)
        fig.savefig(fname, bbox_inches='tight', format='png')
        plt.close(fig)

    def UpdateAxisLimits(self, inst, val):
        try:
            a = [
                float(self.x_min.text),
                float(self.x_max.text),
                float(self.y_min.text),
                float(self.y_max.text)
            ]
        except ValueError:
            return
        if not val:
            plt.axis(a)
            canvas = plt.gcf().canvas
            canvas.draw()

    def UpdateXLabel(self, inst, val):
        if not val:
            plt.xlabel(self.x_label.text)
            canvas = plt.gcf().canvas
            canvas.draw()

    def UpdateYLabel(self, inst, val):
        if not val:
            plt.ylabel(self.y_label.text)
            canvas = plt.gcf().canvas
            canvas.draw()

    def UpdateTitle(self, inst, val):
        if not val:
            plt.title(self.title.text)
            canvas = plt.gcf().canvas
            canvas.draw()

    def LogrithmicX(self, inst, val):
        ax = plt.gca()
        if val == 'down':
            ax.set_xscale('log')
        else:
            ax.set_xscale('linear')
        canvas = plt.gcf().canvas
        canvas.draw()

    def LogrithmicY(self, inst, val):
        ax = plt.gca()
        if val == 'down':
            ax.set_yscale('log')
        else:
            ax.set_yscale('linear')
        canvas = plt.gcf().canvas
        canvas.draw()
Example #25
0
class LSystemsView(Screen):

    def __init__(self,**kwargs): 
        #TODO KV!!!!!!
        self.register_event_type('on_edit')
        super(LSystemsView, self).__init__(**kwargs)
        self.name = "view"
        self.main_layout=BoxLayout(orientation='vertical')
        self.buttons_layout = BoxLayout(orientation='horizontal',size_hint= (1, .05))
        self.labels_layout = BoxLayout(orientation='horizontal',size_hint= (1, .05))       
        self.image = LSystemImage()
        self.image.bind(on_update=self.image_update)

        self.width_choice=DropDown()
        self.width_choice.bind(on_select=self.choose_width)
        self.width_choice_button=Button(text="Line width")
        self.width_choice_button.bind(on_release = self.width_choice.open)

        for i in range(1,10):
            btn = ToggleButton(text=str(i), group='width_values',size_hint_y=None,height=sp(30))
            if i == 1: btn.state = 'down'
            btn.bind(on_press = lambda btn: self.width_choice.select(btn.text))
            self.width_choice.add_widget(btn)
        self.fractal_choice = DropDown()
        self.fractal_choice.bind(on_select=self.choose_fractal)
        self.file_choice_button=Button(text = "File")        
        self.choice_button=Button(text = "L-System")
        self.file_choice_button.bind(on_release = self.on_file_choose) #self.file_choice.open)
        self.choice_button.bind(on_release = self.fractal_choice.open)
        self.next_button = Button(text="Next")
        self.ls_name = Label(text = "")
        self.cur_file = Label(text = "")
        self.plus_button = Button(text="+")
        self.minus_button = Button(text="-")
        self.background_button = Button(text="Background")
        self.background_button.bind(on_press=self.choose_background_color)
        self.plus_button.bind(on_press=self.plus)
        self.minus_button.bind(on_press=self.minus)
        self.next_button.bind(on_press=self.next)        
        self.edit_button = Button(text="Edit")
        self.edit_button.bind(on_press=self.edit)
        self.segments = Label(text="")
        self.iterations=Label()
        self.buttons_layout.add_widget(self.file_choice_button)
        self.buttons_layout.add_widget(self.choice_button)
        self.buttons_layout.add_widget(self.next_button)
        self.buttons_layout.add_widget(self.plus_button)
        self.buttons_layout.add_widget(self.minus_button)
        self.buttons_layout.add_widget(self.edit_button)
        self.buttons_layout.add_widget(self.background_button)
        self.buttons_layout.add_widget(self.width_choice_button)
        self.labels_layout.add_widget(Label(text="[b]File name:[/b]",markup=True))
        self.labels_layout.add_widget(self.cur_file)
        self.labels_layout.add_widget(Label(text="[b]L-system name:[/b]",markup=True))
        self.labels_layout.add_widget(self.ls_name)
        self.labels_layout.add_widget(Label(text="[b]Number of iterations:[/b]",markup=True))
        self.labels_layout.add_widget(self.iterations)
        self.labels_layout.add_widget(Label(text="[b]Number of segments:[/b]",markup=True))
        self.labels_layout.add_widget(self.segments)
        self.main_layout.add_widget(self.image)
        self.main_layout.add_widget(self.buttons_layout)
        self.main_layout.add_widget(self.labels_layout)

        self.file_chooser = LFileChooser()
        self.file_chooser.bind(on_choose=self.choose_file)
        self.popup = Popup(title='Load L-Systems', content=self.file_chooser,
                      size_hint=(None, None), size=(500, 500))


        
        self.color_picker=BackgroundColorPicker()
        self.color_picker.bind(on_choose=self.change_background_color)
        self.color_picker_popup = Popup(title = "Pick color",
                                        content = self.color_picker,
                                        size_hint = (None,None),
                                        size = (500,500))
        
        

        self.add_widget(self.main_layout)




    def choose_background_color(self,*args,**kwargs):
        self.color_picker_popup.open()

    def change_background_color(self,instance,color):
        r,g,b,a = color
        r=int(255*r)
        g=int(255*g)
        b=int(255*b)
        self.image.set_background_color((r,g,b))
        self.color_picker_popup.dismiss()

    def on_edit(self,*args,**kwargs):
        pass

    def on_file_choose(self,*args):
        self.popup.open()

    def edit(self,instance,*args):        
        name=self.ls_name.text
        if name: fractal = self.fractals[name][0]
        else: fractal = '',{},0
        self.dispatch("on_edit",(name,fractal))


    def set_fractals(self):
        self.fractal_choice.clear_widgets()
        for k in sorted(self.fractals.keys()):
            btn = Button(text = k,size_hint_y=None, height=44)
            btn.bind(on_release = lambda btn: self.fractal_choice.select(btn.text))
            self.fractal_choice.add_widget(btn)
       
    def choose_file(self,instance,text):
        self.cur_file.text = basename(text)
        self.popup.dismiss()
        self.fractals=l_parser(open(l_file_path(text)))
        self.set_fractals()
        self.choose_fractal(None,sorted(self.fractals.keys())[0])

    def choose_width(self,instance,text):
        self.image.set_width(int(text))


    def choose_fractal(self,instance,text):
        self.ls_name.text = text
        self.image.set_lsystem(self.fractals[text][0])
        self.image.set_iterations(1)
        self.iterations.text = str(self.image.get_iterations())


    def image_update(self,instance,num):
        self.segments.text = str(num)

    def next(self,*args):
        cur_name = self.ls_name.text
        if not cur_name: return
        lst = self.fractals.keys()
        i = lst.index(cur_name)
        i+=1
        if i==len(self.fractals): i=0
        self.choose_fractal(None,lst[i])
     

        
    def plus(self,*args):
        self.image.set_iterations(self.image.get_iterations()+1)
        self.iterations.text = str(self.image.get_iterations())

    def minus(self,*args):
        self.image.set_iterations(self.image.get_iterations()-1)
        if self.iterations.text!="0":
            self.iterations.text = str(self.image.get_iterations())
class GroupScreen(Screen):

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

        # Hold the widgets in a container
        screen_container = BoxLayout(orientation='vertical',
                                     padding=[1])

        # *Empowered Logo------------------------------------------------------
        self.logo = HomeButton()
        screen_container.add_widget(self.logo)

        # *Group Selection Title-----------------------------------------------
        screen_container.add_widget(Label(text='Group Selection',
                                          size_hint=(1, .1),
                                          color=(0, .1, .25, .75)))

        # *Dropdown Menu-------------------------------------------------------
        self.dropdown = DropDown()
        self.dropdown.bind(on_select=self.set_active_group)

        # On load, no group is active.
        global_data.active_group = ''
        # Store the drop down buttons for easy manipulation
        self.current_groups = {}

        #       Populate when top button hit
        self.mainbutton = CustomButton(text='Select a group',
                                       size_hint=(1, .2))

        # Populate drop down on select
        self.mainbutton.bind(on_release=self.load_groups)
        self.dropdown.bind(on_select=lambda instance, x:
                           setattr(self.mainbutton, 'text', x))
        # Place on screen
        screen_container.add_widget(self.mainbutton)

        # *Group Actions Title-------------------------------------------------
        # Declarations
        self.button_container = BoxLayout(orientation='horizontal')

        #       Edit Button
        self.edit_btn = CustomButton(text="Edit",
                                     size_hint=(.3, .3))
        self.edit_btn.bind(on_press=self.switch_screen)

        #       New Button
        self.new_btn = CustomButton(text="New",
                                    size_hint=(.3, .3))
        self.new_btn.bind(on_press=self.switch_screen)

        #       Delete Button
        self.delete_btn = CustomButton(text="Delete",
                                       size_hint=(.3, .3))
        self.delete_btn.bind(on_press=self.delete)

        # Put buttons in container
        self.button_container.add_widget(self.edit_btn)
        self.button_container.add_widget(self.new_btn)
        self.button_container.add_widget(self.delete_btn)

        # Add container to screen container
        screen_container.add_widget(self.button_container)
        # Package screen container
        self.add_widget(screen_container)
        # Make sure drop down menu gets reset
        self.bind(on_enter=self.reset_menu)

    def set_active_group(self, *args):
        # args = (<DropDown obj>, 'Methylation Pathway')
        # Storing which group is selected for use in gene screen and deletion
        global_data.active_group = args[1]

    def switch_screen(self, *args):
        # Switch screens
        if args[0].text == "Edit" and global_data.active_group != '':
            sm.current = 'gene'
        elif args[0].text == "New":
            sm.current = 'newgroup'

    def delete(self, *args):

        def delete_group(*args):

            # Get the selected group
            active_group = global_data.active_group

            # Delete it from the group dictionary
            del global_data.groups[active_group]

            log(f"Group {active_group} deleted.")

            # Overwrite the existing groups with the modified group dictionary
            group_mngr.save_groups(global_data.groups)

            # Clear the selected group
            global_data.active_group = ''
            # Remove it from the drop down menu
            self.dropdown.remove_widget(self.current_groups[active_group])
            # Set drop down menu to default
            self.dropdown.select('Select a group')

            popup.dismiss()

        # If a group is selected and delete button hit, confirm deletion
        if global_data.active_group != '':

            # *Confirmation Popup----------------------------------------------
            content = BoxLayout(orientation='vertical')
            content.add_widget(Label(text=
                                     f"Delete {global_data.active_group}?"))

            # *Popup buttons---------------------------------------------------
            options = BoxLayout(orientation='horizontal', spacing=2)

            confirm_btn = CustomButton(text="Delete",  # Confirm delete button
                                       size_hint=(.3, .3))

            cancel_btn = CustomButton(text="Cancel",  # Cancel delete button
                                      size_hint=(.3, .3))
            options.add_widget(confirm_btn)
            options.add_widget(cancel_btn)
            content.add_widget(options)

            # *Popup Attributes------------------------------------------------
            popup = Popup(title="Delete?", content=content,
                          size_hint=(None, None), size=(400, 400),
                          separator_color=[1., 1., 1., 1.])

            confirm_btn.bind(on_press=delete_group)
            cancel_btn.bind(on_press=popup.dismiss)

            popup.open()

    def load_groups(self, *args):

        self.dropdown.clear_widgets()  # Clear any packaged buttons
        self.current_groups = {}  # Clear drop down button list

        groups = global_data.groups

        for group in groups:  # Iterating through groups and adding a button
            btn = CustomButton(text=group,  # Create button
                               size_hint_y=None,
                               height=44)
            btn.bind(on_release=lambda button:
            self.dropdown.select(button.text))  # Bind drop down functionality
            self.current_groups[group] = btn
            self.dropdown.add_widget(btn)  # Put in drop down menu

        self.dropdown.open(args[0])  # Called on clicking the default button

    def reset_menu(self, *args):
        # Need to make sure the menu text is defaulted when screen is entered
        self.dropdown.select('Select a group')
        global_data.active_group = ''
        global_data.active_gene = ''
Example #27
0
class Shown_Mama(FloatLayout):
    def __init__(self,**kwargs):
        super(Shown_Mama, self).__init__(**kwargs)
        Window.bind(on_resize=self.window_size_changed)
        self.chveneba_klasi = Shown_Scroll()
        self.pirovneba_klasi = Pirovneba_box1()
        self.add_widget(self.chveneba_klasi)
        self.add_widget(self.pirovneba_klasi)



        self.dropdown = DropDown()  # Create the dropdown once and keep a reference to it
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.button, 'text', x))


        self.button = Button(text='იუნკერთა სია', font_size=20, size_hint=(.15,.10),font_name="bpg_arial_2009",
                             pos_hint= {'x':.0,'y':.80},background_color = get_color_from_hex("#ff680a"),on_release=self.refresh_dopdown)
        self.add_widget(self.button)

        self.items_klasi = Shown_Box()
        self.chveneba_klasi.add_widget(self.items_klasi)

        self.sataurebi_lay = sataurebi_layout()
        self.add_widget(self.sataurebi_lay)
        

        self.refres_btn = Button(text = "ძებნა",font_name="bpg_arial_2009", font_size=20)
        self.refres_btn.bind(on_release = self.refresh)
        self.pirovneba_klasi.add_widget(self.refres_btn)

        self.delete_btn = Button(text = "წაშლა",font_name="bpg_arial_2009", font_size=20)
        self.delete_btn.bind(on_release = self.delete_junker)
        self.pirovneba_klasi.add_widget(self.delete_btn)

    def window_size_changed(self,window, width,height):
        self.button.font_size = width/68.3
        self.dropdown.font_size = width/68.3


    def delete_junker(self,*args):
        Main.con.execute("delete from Junker_list where Name = N'%s'and Surname=N'%s'"%(self.pirovneba_klasi.kaci_teqst.text,
                                                                                        self.pirovneba_klasi.kaci_gvari_teqst.text))
        self.pirovneba_klasi.name_text.text = "უცნობია"
        self.pirovneba_klasi.surname_text.text = "უცნობია"
        self.pirovneba_klasi.laptop_serial_result.text = "უცნობია"
        self.button.text = "იუნკერთა სია"
        self.pirovneba_klasi.kaci_teqst.text = ""
        self.pirovneba_klasi.kaci_gvari_teqst.text = ""
        self.items_klasi.clear_widgets()

    def refresh_dopdown(self,*args):
        self.dropdown.open(self.button)
        self.dropdown.clear_widgets()
        for index in self.junker_list():
            btn = Button(text='Value %s %s' % (index[2],index[2]), size_hint_y=None, height=44,font_name="bpg_arial_2009",
                         on_release=lambda btn: self.command2(name=btn.text))  # bind every btn to a print statement
            btn.text = '%s %s' % (index[1],index[2])
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)




    def info_container(self):
        self.command= Main.con.execute("select Name,Surname,dasaxeleba,gacema,vada,Laptop_number from Junker_list, Item_list "
                                   "where Junker_list.Jun_ID = Item_list.junker_id and Name = N'%s'and Surname=N'%s' "
                                   "order by name"%(self.pirovneba_klasi.kaci_teqst.text,self.pirovneba_klasi.kaci_gvari_teqst.text))
        for items in self.command:
            yield items


    def junker_list(self):
        self.junker_fetch = Main.con.execute("select * from Junker_list")
        for junker in self.junker_fetch:
            yield junker


    def command2(self,name):
        self.dakofili = name.split(' ')
        self.pirovneba_klasi.kaci_teqst.text = self.dakofili[0]
        self.pirovneba_klasi.kaci_gvari_teqst.text = self.dakofili[1]
        self.refresh()




    def refresh(self,*args):
        self.items_klasi.clear_widgets()
        for self.number, self.item in enumerate(self.info_container()):
            self.pirovneba_klasi.name_text.text = self.item[0]
            self.pirovneba_klasi.surname_text.text = self.item[1]
            self.pirovneba_klasi.laptop_serial_result.text = self.item[5]
            self.a = self.item[4].split("-")
            self.vada_list = [int(g) for g in self.a]
            self.mimdinare_dro = datetime.datetime(int(self.vada_list[0]),int(self.vada_list[1]),int(self.vada_list[2])) - datetime.datetime.today()
            self.strig_converted = str(self.mimdinare_dro)

            if self.mimdinare_dro.days >= 60:
                self.items_klasi.add_widget(Shown_class.monacemebi(gamoidzaxe_row=str(self.item[2]),gamoidzaxe_nomeri=str(self.number+1),
                                              gamoidzaxe_gacema=str(self.item[3]),gamoidzaxe_vada=self.item[4],
                                              gamoidzaxe_statusi="[color=#55FB0E]%s დღე - %s სთ[/color]"%(self.strig_converted[:5],self.strig_converted[10:19])))
            elif self.mimdinare_dro.days < 60 and self.mimdinare_dro.days > 30:
                self.items_klasi.add_widget(Shown_class.monacemebi(gamoidzaxe_row=str(self.item[2]),gamoidzaxe_nomeri=str(self.number+1),
                                              gamoidzaxe_gacema=str(self.item[3]),gamoidzaxe_vada=self.item[4],
                                              gamoidzaxe_statusi="[color=#ffff14]%s დღე - %s სთ[/color]"%(self.strig_converted[:5],self.strig_converted[10:19])))
            elif self.mimdinare_dro.days <=30:
                self.items_klasi.add_widget(Shown_class.monacemebi(gamoidzaxe_row=str(self.item[2]),gamoidzaxe_nomeri=str(self.number+1),
                                              gamoidzaxe_gacema=str(self.item[3]),gamoidzaxe_vada=self.item[4],
                                              gamoidzaxe_statusi="[color=#ff2914]%s დღე - %s სთ[/color]"%(self.strig_converted[:5],self.strig_converted[10:19])))
Example #28
0
class RemoteCommand(App):
    commands = ListProperty([])
    container = ObjectProperty(None)
    status = ObjectProperty(None)
    log = StringProperty('')
    mouse_sensivity = NumericProperty(1)
    screen_texture = ObjectProperty(None)
    capture_fps = NumericProperty(0)
    image_size = NumericProperty(128)
    dropdown = ObjectProperty(None)
    mods = DictProperty({})
    mouse_pos = ListProperty([0, 0])
    protocol = ObjectProperty(None, allownone=True)
    interface = ObjectProperty(None)
    processes = DictProperty({})
    curtain = ObjectProperty(None)

    def connect(self, ip, port):
        Window.release_keyboard()

        if self.dropdown:
            self.dropdown.dismiss()

        self.protocol = None
        point = TCP4ClientEndpoint(reactor, ip, int(port))
        d = point.connect(CommandClientFactory())
        d.addCallback(self.got_protocol)
        self.log += u"trying to connect…\n"
        self.leftover = ''

        if ip not in self.config.items('connections'):
            self.config.set('connections', ip, str(port))

    def send(self, *args, **kwargs):
        self.protocol.sendMessage(json_encode(kwargs))

    def update_screen(self, *args):
        if self.interface.current_tab.text == 'image':
            self.send(command='capture',
                      size=(self.image_size, self.image_size))

    def propose_addresses(self, address_input):
        if address_input.focus:
            if not self.dropdown:
                self.dropdown = DropDown()
                #self.dropdown.bind(on_select=self.complete_address)
            else:
                self.dropdown.clear_widgets()

            connections = self.config.items('connections')

            for c in connections:
                if c[0].startswith(address_input.text):
                    lbl = Button(text=':'.join(c),
                                 size_hint_y=None,
                                 height=sp(30))
                    lbl.bind(
                        on_press=lambda x: self.connect(*x.text.split(':')))
                    self.dropdown.add_widget(lbl)

            self.dropdown.open(address_input.parent)

    def receive(self, stream):
        stream = self.leftover + stream
        while stream:
            try:
                datadict, index = json_decode(stream)
                self.leftover = ''
            except ValueError:
                # incomplete data, keep to analyse later
                self.leftover = stream
                return

            stream = stream[index:]

            #self.log += 'got data: %s\n' % datadict
            if not isinstance(datadict, dict):
                # something went wrong, gtfo for now, FIXME
                print "didn't get a dict for datadict"
                return

            if 'commands' in datadict:
                self.commands = datadict['commands']

            if 'process' in datadict:
                process = datadict['process']
                status = datadict.get('status', None)

                if status == 'started':
                    label = Label(text=datadict['name'],
                                  size_hint_y='None',
                                  height='30dp')

                    out = Button(text='output log')
                    err = Button(text='error log')
                    kill = Button(text='close')

                    kill.bind(on_release=lambda *args: self.send(
                        command='kill', uid=process))
                    out.bind(
                        on_release=lambda *args: self.display_out(process))
                    err.bind(on_release=lambda *args: self.display_out(
                        process, 'err'))

                    box = BoxLayout(size_hint_y=None, height=sp(20))
                    box.add_widget(label)
                    box.add_widget(out)
                    box.add_widget(err)
                    box.add_widget(kill)

                    self.processes[process] = {
                        'label': label,
                        'box': box,
                        'kill': kill,
                        'out': '',
                        'err': ''
                    }

                    self.status.add_widget(box)

                elif status == 'ended':
                    box = self.processes[process]['box']
                    if datadict['autoclose']:
                        app.status.remove_widget(box)
                    else:
                        label = self.processes[process]['label']
                        label.text += ' - DONE'
                        kill = self.processes[process]['kill']
                        box.remove_widget(kill)
                        close = Button(text='close')
                        close.bind(on_release=lambda *args: app.status.
                                   remove_widget(box))
                        box.add_widget(close)

                elif 'stdout' in datadict:
                    self.processes[process]['out'] += datadict['stdout'].\
                        decode('base64')

                elif 'stderr' in datadict:
                    self.processes[process]['err'] += datadict['stderr'].\
                        decode('base64')

            if 'mouse_pos' in datadict:
                self.mouse_pos = datadict['mouse_pos']

            if 'image' in datadict:
                #print "receiving capture"
                uid = datadict['image']
                if uid not in self.images:
                    fn = 'tmp-%s.png' % uid
                    self.images[uid] = [
                        fn,  # filename
                        open(fn, 'w'),  # file descriptor
                        0,  # next expected chunk
                        {}  # chunks arrived too early
                    ]

                fn, f, c, chunks = self.images[uid]

                data = datadict['data']
                chunk = datadict['chunk']
                #print'receiving %s chunk %s data %s' % (uid, chunk, data[:10])

                if chunk == c:
                    if not data:
                        #print "empty chunk, closing"
                        f.close()
                        move(fn, 'tmp.png')
                        self.screen_texture.reload()
                        del self.images[uid]

                    else:
                        f.write(datadict['data'].decode('base64'))
                        #print "writting chunk", c
                        c += 1

                else:
                    chunks[chunk] = data.decode('base64')

                while c in chunks:
                    #print "applying chunk %s that we got before" % c
                    f.write(chunks[c])
                    c += 1

                if data:
                    self.images[uid] = fn, f, c, chunks

    def process_menu(self, process, *args):
        pass

    def display_out(self, uid, out='out'):
        process = self.processes[uid]
        p = Popup(size_hint=(.95, .95),
                  title='std%s %s' % (out, process['label'].text))
        sc = ScrollView()
        content = Label(text=process[out], size_hint=(None, None))
        sc.bind(width=content.setter('width'))
        content.bind(
            width=lambda c, w: content.setter('text_size')(c, (w, None)))
        content.bind(texture_size=content.setter('size'))
        sc.add_widget(content)
        p.add_widget(sc)
        p.open()

    def got_protocol(self, p):
        self.log += "got protocol\n"
        self.protocol = p

    def on_protocol(self, *args):
        if not self.protocol:
            Animation(top=self.interface.top, d=.5,
                      t='in_quad').start(self.curtain)
        else:
            Animation(top=0, d=.5, t='out_quad').start(self.curtain)

    def on_capture_fps(self, *args):
        Clock.unschedule(self.update_screen)
        if self.capture_fps:
            Clock.schedule_interval(self.update_screen, 1 / self.capture_fps)

    def on_commands(self, *args):
        self.container.clear_widgets()
        self.log += 'got a list of commands!\n'
        for command, arguments in self.commands:
            box = BoxLayout(height=sp(30))
            button = Button(text=command)

            args_inputs = []
            for arg in arguments.split(','):
                if arg == 'str':
                    txtinput = TextInput()
                    args_inputs.append(txtinput)
                    box.add_widget(txtinput)

            button.bind(on_press=partial(self.execute, command,
                                         arguments.split(','), args_inputs))
            box.add_widget(button)

            self.container.add_widget(box)

    def execute(self, command, arguments, args_inputs, *args):
        values = []
        for arg_type, arg_input in zip(arguments, args_inputs):
            if arg_type == 'str':
                values.append(arg_input.text)

        self.send(run=command, arguments=values)

    def mouse_move(self, dx, dy):
        self.send(command='mouse',
                  action='move',
                  dx=int(round(dx * self.mouse_sensivity)),
                  dy=-int(round(dy * self.mouse_sensivity)))

    def mouse_click(self, b=1, n=2):
        self.send(command='mouse', action='click', b=b, n=n)

    def mouse_press(self, b=1):
        #self.log += 'mouse pressed\n'
        self.send(command='mouse', action='press', b=b)

    def mouse_release(self, b=1):
        #self.log += 'mouse released\n'
        self.send(command='mouse', action='release', b=b)

    def send_keys(self, string):
        self.send(command='type', string=string)

    def press_special_key(self, key):
        self.send(command='press_key', key=key.text)

    def release_special_key(self, key):
        self.send(command='release_key', key=key.text)

    def on_start(self, *args):
        self.config = ConfigParser()
        self.config.read(CONFIG)
        self.images = {}

        if not self.config.has_section('connections'):
            self.config.add_section('connections')

            with open(CONFIG, 'w') as f:
                self.config.write(f)

    def on_pause(self, *args):
        with open(CONFIG, 'w') as f:
            self.config.write(f)
        return True

    def on_resume(self, *args):
        return True

    def on_stop(self, *args):
        with open(CONFIG, 'w') as f:
            self.config.write(f)
        return True

    def populate_keyboard(self, grid):
        b = Button(text='escape')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)

        for f in range(12):
            b = Button(text='f%d' % (f + 1))
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        for i in range(13):
            grid.add_widget(Widget())

        grid.add_widget(Widget())

        b = Button(text='up')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)

        for i in range(2):
            grid.add_widget(Widget())

        for t in 'home', 'end':
            b = Button(text=t)
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        grid.add_widget(Widget())

        b = Button(text='shift')
        grid.add_widget(b)
        self.mods['shift'] = b

        b = Button(text='control')
        grid.add_widget(b)
        self.mods['control'] = b

        b = Button(text='alt')
        grid.add_widget(b)
        self.mods['alt'] = b

        b = Button(text='meta')
        grid.add_widget(b)
        self.mods['meta'] = b

        grid.add_widget(Widget())

        b = Button(text='backspace')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)

        #for i in range(5):
        #grid.add_widget(Widget())

        for t in 'left', 'down', 'right':
            b = Button(text=t)
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        grid.add_widget(Widget())

        for t in 'up', 'down':
            b = Button(text='page%s' % t)
            b.bind(on_press=self.press_special_key)
            b.bind(on_release=self.release_special_key)
            grid.add_widget(b)

        for i in range(6):
            grid.add_widget(Widget())

        b = Button(text='return')
        b.bind(on_press=self.press_special_key)
        b.bind(on_release=self.release_special_key)
        grid.add_widget(b)
Example #29
0
class Pos(BoxLayout):
    def __init__(self, **kwargs):
        super(Pos, self).__init__(**kwargs)

        self.cliente = None

    def hacerNota(self):

        if self.txt_client.text == "":
            MessageBoxTime(
                title="Ops", size_hint=(None, None), size=(350, 120), msg="Por favor especifica el cliente", duration=2
            ).open()
            return
        elif self.cliente == None:
            MessageBoxTime(
                title="Espere", size_hint=(None, None), size=(350, 120), msg="Guardando cliente", duration=2
            ).open()

        print "Realizando nota"
        nota = Notas()
        nota.PUser = app.root.user
        nota.Total = self.txt_total.text
        nota.Cliente = self.cliente

        products = []

        for i in self.lst_note.layout.children:
            print i.txt_producto.text

            products.append(
                {
                    "Cantidad": i.txt_cant.text,
                    "Product": i.txt_producto.text,
                    "Precio": i.txt_precio.text,
                    "Total": i.txt_total.text,
                }
            )

        nota.Productos = products

        nota.save()

        # limpiar controles de nota
        self.lst_note.clear()
        self.lst_note.add_widget(NoteItem())
        self.txt_client.text = ""
        self.txt_total.text = "0"
        self.img_button.source = "plus.png"

        self.cliente = None

    def on_completeclient(self, w):

        if not hasattr(self, "dropdown"):
            self.dropdown = DropDown()

        if len(w.text) > 2:

            self.dropdown.clear_widgets()

            found = False

            for item in Clientes.Query.filter(words__all=w.text.upper().split()):

                but = WhiteButton(text=item.Name, size_hint_y=None, height=40)
                but.bind(on_press=self.fillClient)
                but.Cliente = item
                self.dropdown.add_widget(but)
                found = True

            if found:
                self.dropdown.open(w)

    def fillClient(self, w):

        self.txt_client.text = w.text

        self.img_button.source = "ok.png"

        self.cliente = w.Cliente

        self.dropdown.dismiss()

    def addClient(self):
        print "Adding the client: " + self.txt_client.text

        self.cliente = Clientes()
        self.cliente.Name = self.txt_client.text
        self.cliente.PUser = app.root.user
        self.cliente.save()

        self.img_button.source = "ok.png"

    def fillNotas(self):
        print "Llenado lista de notas"

        for i in app.root.notas:
            print i
            notareg = NoteReg()
            notareg.txt_fecha.text = str(i.createdAt)
            if i.Cliente != None:
                notareg.txt_cliente.text = i.Cliente.Name
            notareg.txt_total.text = str(i.Total)

            self.lst_notas.add_widget(notareg)
Example #30
0
class MainScreen(ScrollView):
    
    nextReload = None
    showall = False

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        Window.bind(on_keyboard=self.Android_back_click)
        self.size_hint=(None, None)
        self.size=(Window.width, Window.height)
        self.pos_hint={'center_x':.5, 'center_y':.5}
        self.buildMainScreen()      

    def Android_back_click(self,window,key,*largs):
        if key == 27:
            self.buildMainScreen()   
            return True
        
    def buildMainScreen(self, _=None):
        self.clear_widgets()
        mainLayout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        mainLayout.bind(minimum_height=mainLayout.setter('height'))
        self.scroll_y = 1
        self.add_widget(mainLayout)
        cur.execute("SELECT DISTINCT taskId, endTime FROM Fights WHERE value = 0")
        runningTaskDeadlines = {}
        for r in cur.fetchall():
            runningTaskDeadlines[r[0]] = r[1]
        runningTasks = runningTaskDeadlines.keys()
        runningTasks.sort(key = lambda tid: runningTaskDeadlines[tid], reverse = False)
        cur.execute("SELECT DISTINCT taskId FROM Milestones WHERE deadline >= ?", [time.time()])
        tasks = [t[0] for t in cur.fetchall()]
        if tasks and not MainScreen.showall:
            tasks.sort(key = lambda tid: getCompletionExpirationDate(tid), reverse = False)
        else:
            MainScreen.showall = True
            cur.execute("SELECT id FROM Tasks")
            tasks = [x[0] for x in cur.fetchall()]
            tasks.sort(key = lambda tid: getScore(tid), reverse = True)
        tasks = [t for t in tasks if t not in runningTasks]
        tasks = runningTasks + tasks
        self.progressbars = []
        for tid in tasks:
            running = isRunning(tid, True)
            completed = isComplete(tid)
            taskLayout = GridLayout(cols=2, spacing=0, size_hint_y=None, height=100)
            mainLayout.add_widget(taskLayout)
            taskButton = Button(text=getTaskName(tid),  size_hint_y=None, height=100)
            taskLayout.add_widget(taskButton)   
            pledgeButton = Button(size_hint_y=None, size_hint_x=None, width=100, height=100)
            taskLayout.add_widget(pledgeButton)
            pledgeButton.background_color = (0,1,0,1)      
            taskButton.bind(on_press=self.taskMenu(tid))
            if running:
                taskButton.background_color = (0.8,1,0.8,1)
                pledgeButton.background_color = (1,0,0,1)
                cur.execute("SELECT startTime, endTime FROM Fights WHERE value = 0 AND taskId = ?",[tid])
                startTime, endTime = cur.fetchall()[0]
                pledgeButton.bind(on_press=self.taskPopup(tid,  startTime, endTime, True))
                taskProgress = ProgressBar(max=endTime-startTime)
                self.progressbars.append(taskProgress)
                mainLayout.add_widget(taskProgress)
                timeLeft = endTime - time.time()
                if timeLeft > 0: 
                    taskProgress.value = (min(time.time()-startTime, endTime-startTime+1))
                else: 
                    taskProgress.max = taskProgress.value = 1
            else:
                pledgeButton.bind(on_press=self.taskPopup(tid))
                if completed:
                    taskButton.background_color = (1,0.8,0.8,1)        
                    
        if not MainScreen.showall:
            moreButton = Button(text=localisation.get(language,"showmore"), bold=True, size_hint_y=None, height=100)
            mainLayout.add_widget(moreButton)
            moreButton.bind(on_press=self.toggleTasksShown)
        else:
            writeTaskInput = TextInput(text='')
            writeTaskPopup = Popup(title=localisation.get(language, "createnew"),
            content=writeTaskInput,
            size_hint=(None, None), size=(400, 200))
            writeTaskPopup.bind(on_dismiss=self.addEmptyTask(writeTaskInput))
            newTaskButton = Button(text=localisation.get(language,"createnew"), bold=True, size_hint_y=None, height=100)
            newTaskButton.bind(on_release=writeTaskPopup.open)
            mainLayout.add_widget(newTaskButton)
            langDropdown = DropDown()
            for lang in localisation.sections():
                btn = Button(text=lang,background_color = (0.6,0.6,0.6,1), valign = 'middle', halign='center', size_hint_y=None, height=100)
                btn.bind(on_release=self.changeLanguage(lang))
                btn.bind(on_release=langDropdown.dismiss)
                langDropdown.add_widget(btn)
            langButton = Button(text=localisation.get(language,"language"), bold=True, size_hint_y=None, height=100)
            langButton.bind(on_press=langDropdown.open)
            mainLayout.add_widget(langButton)
            lessButton = Button(text=localisation.get(language,"showless"), bold=True, size_hint_y=None, height=100)                        
            mainLayout.add_widget(lessButton)
            lessButton.bind(on_press=self.toggleTasksShown)
                                                
        Clock.unschedule(self.incrementProgressBars)
        Clock.schedule_interval(self.incrementProgressBars, 1)     
        
    def changeLanguage(self, newLanguage):
        def changeLanguage_inner(_=None):
            global language
            language = newLanguage
            self.buildMainScreen()
            commitConfig()   
        return changeLanguage_inner
        
    def addEmptyTask(self, taskInput):
        def addEmptyTask_inner(_):
            if taskInput.text:
                try:               
                    cur.execute("INSERT INTO Tasks(name) VALUES(?)", [taskInput.text.strip()])
                except:
                    cur.execute("INSERT INTO Tasks(name) VALUES(?)", [taskInput.text.strip().decode('utf-8')])
            con.commit()
            self.buildMainScreen()
        return addEmptyTask_inner        
        
    def toggleTasksShown(self, _):
        if MainScreen.showall: 
            MainScreen.showall = False
        else:
            MainScreen.showall = True
        self.buildMainScreen()
    
    def incrementProgressBars(self, dt): 
        for pb in self.progressbars:
            if pb.value == pb.max-1: playAudio(soundFiles[1]) 
            pb.value+=1
            
    def taskMenu(self, tid, oldScore=None):
        def taskMenu_inner(_=None):
            self.clear_widgets()
            taskMenuLayout = GridLayout(cols=1, spacing=10, size_hint_y=None)
            taskMenuLayout.bind(minimum_height=taskMenuLayout.setter('height'))
            self.scroll_y = 1
            self.add_widget(taskMenuLayout)
            backButton = Button(text=getTaskName(tid), size_hint_y=None, height=100)
            statusLabel = Label(font_size='12sp', valign = 'top', halign='left')
            if isRunning(tid, True):
                backButton.background_color = (0.8,1,0.8,1)
                statusLabel.text = localisation.get(language, "end") + " " + getDateString(getLastDeadline(tid)) 
            elif isComplete(tid):
                backButton.background_color = (1,0.8,0.8,1)
                statusLabel.text = localisation.get(language, "cooldown") + " " + getDateString(getCompletionExpirationDate(tid))
            else:
                statusLabel.text = localisation.get(language, "limbo") + " " + getDateString(getCompletionExpirationDate(tid))
            backButton.bind(on_press=self.buildMainScreen)
            taskMenuLayout.add_widget(backButton)
            taskMenuLayout.add_widget(statusLabel)
            for milestone in getMilestones(tid):  
                taskMenuLayout.add_widget(self.makeMilestoneLayout(tid, milestone, oldScore if milestone == getNextMilestone(tid) else None))
            newMilestoneButton = Button(text=localisation.get(language,"newdate"), bold=True, size_hint_y=None, height=100)
            taskMenuLayout.add_widget(newMilestoneButton)
            newMilestoneButton.bind(on_press=self.mileStonePopup(tid))
            delConfirmSwitch =  Switch()
            delConfirmPopup = Popup(title=localisation.get(language, "sure"),
            content=delConfirmSwitch,
            size_hint=(None, None), size=(200, 200))
            delConfirmPopup.bind(on_dismiss=self.deleteTask(tid, delConfirmSwitch))
            delButton = Button(text=localisation.get(language,"deltask"), bold=True, size_hint_y=None, height=100)
            delButton.bind(on_press=delConfirmPopup.open)            
            taskMenuLayout.add_widget(delButton)
        return taskMenu_inner
    
    def makeMilestoneLayout(self, tid, milestone = None, oldScore=None):
        milestone2 = getPreviousMilestone(tid, milestone)
        newScore = getScore(tid, milestone2, milestone)
        if oldScore is None:
            oldScore = newScore
        scoreLayout = GridLayout(cols=1, spacing=10, size_hint_y = None)
        milestoneButton = Button(text=getDateString(milestone, False), font_size='16sp', size_hint_y = None, height=50)
        milestoneButton.bind(on_press=self.milestoneMenu(tid, milestone))
        scoreLayout.add_widget(milestoneButton)
        progressLayout = BoxLayout(orientation='horizontal')
        prevScoreMilestone = Label(text=getScoreText(oldScore))
        prevScoreMilestone.color = (1,1-float(prevScoreMilestone.text[:-1])/100,1-float(prevScoreMilestone.text[:-1])/100,1)
        progressLayout.add_widget(prevScoreMilestone)
        scoreProgress = ProgressBar(max=0.1)
        scoreProgress.value = oldScore % 0.1
        progressLayout.add_widget(scoreProgress)
        nextScoreMilestone = Label(text=getScoreText(oldScore, True))
        nextScoreMilestone.color = (1,1-float(nextScoreMilestone.text[:-1])/100,1-float(nextScoreMilestone.text[:-1])/100,1)
        nextScoreMilestone.bold = nextScoreMilestone.text == '100%'
        progressLayout.add_widget(nextScoreMilestone)       
        Clock.schedule_interval(self.incrementScoreProgress(scoreProgress, prevScoreMilestone, nextScoreMilestone, oldScore, newScore), 0.1)
        scoreLayout.add_widget(progressLayout)
        scoreLabel = Label(text=str(int(100*newScore))+"%")
        if getNextMilestone(tid) == milestone:
            #expScore = newScore * (milestone-time.time()) / (time.time()-milestone2)
            idealScore = newScore + (milestone-time.time())/(milestone-milestone2)            
            scoreLabel.text += ' ('+ str(int(100*idealScore))+"%)"
        scoreLabel.color = (1,1-newScore,1-newScore,1)
        scoreLabel.bold = newScore>=0.99
        scoreLayout.add_widget(scoreLabel)
        return scoreLayout
            
    def incrementScoreProgress(self, scoreProgress, prevScoreMilestone, nextScoreMilestone, oldScore, newScore):              
        def incrementScoreProgress_inner(_=None):
            if getScoreText(newScore) == prevScoreMilestone.text and scoreProgress.value >= newScore % 0.1:
                Clock.unschedule(self.incrementScoreProgress)    
            else: 
                if getScoreText(newScore) == prevScoreMilestone.text and newScore % 0.1 - scoreProgress.value <= 0.02:
                    scoreProgress.value = newScore % 0.1
                else:
                    scoreProgress.value += 0.02
                if scoreProgress.value >= 0.99*scoreProgress.max and nextScoreMilestone.text == '100%':
                    playAudio(soundFiles[5])
                if scoreProgress.value >= scoreProgress.max and not nextScoreMilestone.text == '100%':
                    if nextScoreMilestone.text == '90%':
                        playAudio(soundFiles[4])
                    else:
                        playAudio(soundFiles[3])
                    scoreProgress.value = 0
                    prevScoreMilestone.text = str(10+int(prevScoreMilestone.text[:-1]))+'%'
                    prevScoreMilestone.color = (1,1-float(prevScoreMilestone.text[:-1])/100,1-float(prevScoreMilestone.text[:-1])/100,1)
                    nextScoreMilestone.text = str(10+int(nextScoreMilestone.text[:-1]))+'%'
                    nextScoreMilestone.color = (1,1-float(nextScoreMilestone.text[:-1])/100,1-float(nextScoreMilestone.text[:-1])/100,1)
                    nextScoreMilestone.bold = nextScoreMilestone.text == '100%'
        return incrementScoreProgress_inner       
    
    def milestoneMenu(self, tid, milestone):
        def milestoneMenu_inner(_=None):
            self.clear_widgets()
            milestoneMenuLayout = GridLayout(cols=1, spacing=10, size_hint_y=None)
            milestoneMenuLayout.bind(minimum_height=milestoneMenuLayout.setter('height'))
            self.scroll_y = 1
            self.add_widget(milestoneMenuLayout)
            milestone2 = getPreviousMilestone(tid, milestone)
            backButton = Button(size_hint_y=None, height=100, halign='center')
            backButton.text = getTaskName(tid)+ '\n' + getDateString(milestone2, False) + ' - ' + getDateString(milestone, False)
            backButton.bind(on_press=self.taskMenu(tid))
            milestoneMenuLayout.add_widget(backButton)
            cur.execute("SELECT startTime, endTime, value FROM Fights WHERE taskId = ? AND endTime + value > ? AND startTime < ? ORDER BY endTime + value DESC", [tid, milestone2, milestone])
            for startTime, endTime, value in cur.fetchall():
                if value > 1:
                    cooldownButton = Button(text=getDateString(endTime+value), background_color=(1,0,0,1), height=calculateHeight(value), size_hint_y=None, valign='top')
                    milestoneMenuLayout.add_widget(cooldownButton)
                pledgeButton = Button(text=getDateString(endTime), background_color=(0,1,0,1), height=calculateHeight(endTime-startTime), size_hint_y=None)
                if endTime-startTime >= 120:    
                    pledgeButton.text += '\n'+getDateString(startTime)
                milestoneMenuLayout.add_widget(pledgeButton)
            delButton = Button(text=localisation.get(language,"deltask"), bold=True, size_hint_y=None, height=100)
            delButton.bind(on_press=self.deleteMilestone(tid, milestone))      
            milestoneMenuLayout.add_widget(delButton)      
        return milestoneMenu_inner
    
    def deleteMilestone(self, task_id, milestone):
        def deleteMilestone_inner(_=None):
            cur.execute("DELETE FROM Milestones WHERE taskId = ? AND deadline = ?", [task_id, milestone])
            con.commit()
            self.taskMenu(task_id)()
        return deleteMilestone_inner
    
    def mileStonePopup(self, tid):
        def mileStonePopup_inner(_,__=None):
            popupLayout = BoxLayout(orientation='horizontal')
            popup = Popup(title=localisation.get(language,"newdate"),
            content=popupLayout,
            size_hint=(None, None), size=(400, 200))
            yearSelector = Button(text_size=(400, 100), valign = 'middle', halign='center')
            popupLayout.add_widget(yearSelector)
            monthSelector = Button(text_size=(400, 100), valign = 'middle', halign='center')
            popupLayout.add_widget(monthSelector)
            daySelector = Button(text_size=(400, 100), valign = 'middle', halign='center')
            popupLayout.add_widget(daySelector)
            yearDropdown = DropDown()
            yearSelector.bind(on_release=yearDropdown.open)
            yearDropdown.bind(on_select=lambda instance, x: setattr(yearSelector, 'text', x))
            firstYear = getFirstYear(tid)
            for year in range(firstYear,firstYear+101):
                if yearSelector.text == '': yearSelector.text = str(year)
                btn = Button(text=str(year),background_color = (0.6,0.6,0.6,1), text_size=(400, 100), valign = 'middle', halign='center', size_hint_y=None, width = 400, height=100)
                btn.bind(on_release=lambda btn: yearDropdown.select(btn.text))
                yearDropdown.add_widget(btn)
            monthDropdown = DropDown()
            monthSelector.bind(on_release=monthDropdown.open)
            monthDropdown.bind(on_select=lambda instance, x: setattr(monthSelector, 'text', x))
            for month in range(1,12+1):
                if monthSelector.text == '': monthSelector.text = str(month)
                btn = Button(text=str(month),background_color = (0.6,0.6,0.6,1), text_size=(400, 100), valign = 'middle', halign='center', size_hint_y=None, width = 400, height=100)
                btn.bind(on_release=lambda btn: monthDropdown.select(btn.text))
                monthDropdown.add_widget(btn)
            dayDropdown= DropDown()
            daySelector.bind(on_release=dayDropdown.open)
            dayDropdown.bind(on_select=lambda instance, x: setattr(daySelector, 'text', x))
            for day in range(1,31+1):
                if daySelector.text == '': daySelector.text = str(day)
                btn = Button(text=str(day),background_color = (0.6,0.6,0.6,1), text_size=(400, 100), valign = 'middle', halign='center', size_hint_y=None, width = 400, height=100)
                btn.bind(on_release=lambda btn: dayDropdown.select(btn.text))
                dayDropdown.add_widget(btn)
            popup.bind(on_dismiss=self.addMilestone(tid, yearSelector, monthSelector, daySelector))
            popup.open()
        return mileStonePopup_inner 
            
    def taskPopup(self, original_tid = None, original_timestamp = None, original_deadline = None, finished=False):
        def taskPopup_inner(_,__=None):
            popupLayout = BoxLayout(orientation='vertical')
            popup = Popup(title=localisation.get(language,"newtask"),
            content=popupLayout,
            size_hint=(None, None), size=(800, 800))
            # task selection menu
            tasksDropdown = DropDown()
            moreTaskDropdown =  DropDown()
            cur.execute("SELECT DISTINCT taskID FROM Fights WHERE value > 0")
            tasks = [x[0] for x in cur.fetchall()]
            firstTask = original_tid
            for tid in sorted(tasks, key=lambda x:getScore(x), reverse=True):
                #print getTaskName(tid), score
                btn = Button(text=getTaskName(tid), background_color = (0.6,0.6,0.6,1), text_size=(400, 100), valign = 'middle', halign='center', size_hint_y=None, width = 400, height=100)                
                if not isComplete(tid) and not isRunning(tid) and getNextMilestone(tid) > time.time():
                    if firstTask is None: firstTask = tid
                    tasksDropdown.add_widget(btn) 
                    btn.bind(on_release=lambda btn: tasksDropdown.select(btn.text)) 
                else:
                    btn.bind(on_release=lambda btn: moreTaskDropdown.select(btn.text))
                    moreTaskDropdown.add_widget(btn)                
            moreTasksButton = Button(text=localisation.get(language, "showmore"), bold=True, background_color = (0.6,0.6,0.6,1), text_size=(400, 100), valign = 'middle', halign='center', size_hint_y=None, width = 400, height=100)
            writeTaskButton = Button(text=localisation.get(language, "createnew"), bold=True, background_color = (0.6,0.6,0.6,1), text_size=(400, 100), valign = 'middle', halign='center', size_hint_y=None, width = 400, height=100)
            tasksDropdown.add_widget(moreTasksButton)
            moreTaskDropdown.add_widget(writeTaskButton)
            taskSelector = Button(text=getTaskName(firstTask), text_size=(400, 100), valign = 'middle', halign='center')
            if not finished: taskSelector.bind(on_release=tasksDropdown.open)
            tasksDropdown.bind(on_select=lambda instance, x: setattr(taskSelector, 'text', x))
            moreTaskDropdown.bind(on_select=lambda instance, x: setattr(taskSelector, 'text', x))
            moreTasksButton.bind(on_release=self.showMoreTasks(moreTaskDropdown, tasksDropdown, taskSelector))
            writeTaskInput = TextInput(text='')
            writeTaskPopup = Popup(title=localisation.get(language, "createnew"),
            content=writeTaskInput,
            size_hint=(None, None), size=(400, 200))
            writeTaskButton.bind(on_release=writeTaskPopup.open)
            writeTaskPopup.bind(on_dismiss=lambda _: setattr(taskSelector, 'text', writeTaskInput.text))
            writeTaskPopup.bind(on_dismiss=moreTaskDropdown.dismiss)
            popupLayout.add_widget(taskSelector)
            # duration menu
            self.endLabel = Label(text_size=(400, 50), font_size='12sp', valign = 'bottom', halign='left')
            popupLayout.add_widget(self.endLabel)
            self.writeDurationButton = Button(text=localisation.get(language, "createnew"), bold=True, background_color = (0.6,0.6,0.6,1), color=(0.2,0.7,1,1), text_size=(200, 100), valign = 'middle', halign='center', size_hint_y=None, width = 200, height=100)
            self.durationSelector = Button(text_size=(200, 100), valign = 'middle', halign='center')
            self.makeDurationDropdown(firstTask, original_timestamp)
            self.durationDropdown.add_widget(self.writeDurationButton)
            if finished:
                if original_deadline <= time.time(): 
                    self.durationSelector.text = durationToText(original_deadline-original_timestamp)
                    self.endLabel.text = localisation.get(language, "end") + " " + getDateString(original_deadline)
                else:
                    self.durationSelector.text = durationToText(time.time()-original_timestamp)
                    self.endLabel.text = localisation.get(language, "end") + " " + getDateString(time.time())
            self.durationSelector.bind(on_release=self.durationDropdown.open)
            self.durationDropdown.bind(on_select=lambda instance, x: setattr(self.durationSelector, 'text', x))
            writeDurationInput = TextInput(text=durationToText(60,True), input_filter=durationInputFilter)
            self.writeDurationPopup = Popup(title=localisation.get(language, "createnew"),
            content=writeDurationInput,
            size_hint=(None, None), size=(400, 200))
            self.writeDurationButton.bind(on_release=self.writeDurationPopup.open)
            self.writeDurationPopup.bind(on_dismiss=lambda _: setattr(self.durationSelector, 'text', writeDurationInput.text))
            self.writeDurationPopup.bind(on_dismiss=self.durationDropdown.dismiss)
            popupLayout.add_widget(self.durationSelector)
            # completion time menu
            self.cooldownLabel = Label(text_size=(400, 50), font_size='12sp', valign = 'bottom', halign='left')
            popupLayout.add_widget(self.cooldownLabel)
            self.writecompletionTimeButton = Button(text=localisation.get(language, "createnew"), bold=True, color=(0.2,0.7,1,1), background_color = (0.6,0.6,0.6,1), text_size=(200, 100), valign = 'middle', halign='center', size_hint_y=None, width = 200, height=100)
            self.completionTimeSelector = Button(text_size=(200, 100), valign = 'middle', halign='center')
            self.makeCompletionTimeDropdown(firstTask, original_timestamp)
            self.completionTimeDropdown.add_widget(self.writecompletionTimeButton)
            defaultCooldown = getDefaultCooldown(original_tid)
            if finished: 
                self.completionTimeSelector.text = durationToText(defaultCooldown)
                if original_deadline <= time.time(): 
                    self.cooldownLabel.text = localisation.get(language, "cooldown") + " " + getDateString(original_deadline+defaultCooldown)
                else:
                    self.cooldownLabel.text = localisation.get(language, "cooldown") + " " + getDateString(time.time()+defaultCooldown)
            self.completionTimeSelector.bind(on_release=self.completionTimeDropdown.open)
            self.completionTimeDropdown.bind(on_select=lambda instance, x: setattr(self.completionTimeSelector, 'text', x))
            writeCompletionTimeInput = TextInput(text=durationToText(defaultCompletionExpiration), input_filter=durationInputFilter)                         
            self.writeCompletionTimePopup = Popup(title=localisation.get(language, "createnew"),
            content=writeCompletionTimeInput,
            size_hint=(None, None), size=(400, 200))
            self.writecompletionTimeButton.bind(on_release=self.writeCompletionTimePopup.open)
            self.writeCompletionTimePopup.bind(on_dismiss=lambda _: setattr(self.completionTimeSelector, 'text', writeCompletionTimeInput.text))
            self.writeCompletionTimePopup.bind(on_dismiss=self.completionTimeDropdown.dismiss)
            popupLayout.add_widget(self.completionTimeSelector) 
            # button
            self.fightButton = None
            if not finished:
                addButton = Button(text=localisation.get(language, "go"), background_color=(0,1,0,1))                
                popupLayout.add_widget(addButton)
                addButton.bind(on_press=self.addNewPledge(taskSelector, self.durationSelector, self.completionTimeSelector, popup))
            else:
                self.fightButton = Button(text=localisation.get(language, "confirm"), background_color=(1,0,0,1))
                popupLayout.add_widget(self.fightButton)
                self.fightButton.bind(on_press=self.resolveFight(original_tid, original_timestamp, original_deadline, 1, self.durationSelector, self.completionTimeSelector, popup))
            # wrap it up          
            tasksDropdown.bind(on_select=lambda instance, changedTaskName:self.refreshTaskPopup(tname=changedTaskName, timestamp=original_timestamp))
            moreTaskDropdown.bind(on_select=lambda instance, changedTaskName:self.refreshTaskPopup(tname=changedTaskName, timestamp=original_timestamp))
            self.durationDropdown.bind(on_select=lambda instance, changedDuration:self.refreshTaskPopup(duration=changedDuration, timestamp=original_timestamp))
            self.completionTimeDropdown.bind(on_select=lambda instance, changedCooldown:self.refreshTaskPopup(cooldown=changedCooldown, timestamp=original_timestamp))
            self.writeDurationPopup.bind(on_dismiss=lambda _: self.refreshTaskPopup(duration=writeDurationInput.text, timestamp=original_timestamp))
            self.writeCompletionTimePopup.bind(on_dismiss=lambda _: self.refreshTaskPopup(cooldown=writeCompletionTimeInput.text, timestamp=original_timestamp))
            popup.open()  
        return taskPopup_inner
    
    
    def showMoreTasks(self, newDropdown, oldDropdown, parent):
        def showshowMoreTasks_inner(_=None):
            newDropdown.open(parent)
            oldDropdown.dismiss()
        return showshowMoreTasks_inner
    
    def makeDurationDropdown(self, tid, timestamp):
        if timestamp is None: timestamp = time.time()
        cur.execute("SELECT endTime, startTime FROM Fights WHERE taskID = ? AND value > 0 ORDER BY endTime DESC", [tid])
        res = cur.fetchall()
        durations = [durationToText(x[0]-x[1]) for x in res]
        seen = set()
        durations = [ x for x in durations if not (x in seen or seen.add(x))]
        self.durationDropdown = DropDown()
        firstDuration = None
        for d in durations[:10]:
            if firstDuration is None: firstDuration = d
            btn = Button(text=d, text_size=(200, 100), background_color = (0.6,0.6,0.6,1), valign = 'middle', halign='center', size_hint_y=None, width = 200, height=100)
            btn.bind(on_release=lambda btn: self.durationDropdown.select(btn.text))
            self.durationDropdown.add_widget(btn)
        if firstDuration is None: firstDuration = durationToText(1)
        self.durationSelector.text = firstDuration
        self.endLabel.text = localisation.get(language, "end") + " " + getDateString(timestamp+ durationToInt(firstDuration) )
        
    def makeCompletionTimeDropdown(self, tid, timestamp):
        if timestamp is None: timestamp = time.time()
        cur.execute("SELECT value FROM Fights WHERE taskID = ? AND value > 0 ORDER BY endTime DESC", [tid])
        res = cur.fetchall()
        values= [durationToText(x[0]) for x in res]
        seen = set()
        values = [ x for x in values if not (x in seen or seen.add(x))]
        self.completionTimeDropdown =  DropDown()
        firstValue = None
        for v in values[:10]:
            if firstValue is None: firstValue = v
            btn = Button(text=v, background_color = (0.6,0.6,0.6,1), text_size=(200, 100), valign = 'middle', halign='center', size_hint_y=None, width = 200, height=100)
            btn.bind(on_release=lambda btn: self.completionTimeDropdown.select(btn.text))
            self.completionTimeDropdown.add_widget(btn)
        if firstValue is None: firstValue = durationToText(defaultCompletionExpiration)
        self.completionTimeSelector.text = firstValue
        self.cooldownLabel.text = localisation.get(language, "cooldown") + " " + getDateString( timestamp+durationToInt(self.durationSelector.text)+durationToInt(firstValue) )
    
    def refreshTaskPopup(self, tname=None, duration=None, cooldown=None, timestamp=None):
        if timestamp is None: timestamp = time.time()
        if tname is not None:
            try:
                tid = getTaskId(tname)
            except:
                tid = None
            self.durationDropdown.clear_widgets()
            self.makeDurationDropdown(tid, timestamp)
            self.durationDropdown.add_widget(self.writeDurationButton)
            self.durationDropdown.bind(on_select=lambda instance, x: setattr(self.durationSelector, 'text', x))
            self.durationSelector.bind(on_release=self.durationDropdown.open)       
            self.completionTimeDropdown.clear_widgets()
            self.makeCompletionTimeDropdown(tid, timestamp)
            self.completionTimeDropdown.add_widget(self.writecompletionTimeButton)
            self.completionTimeDropdown.bind(on_select=lambda instance, x: setattr(self.completionTimeSelector, 'text', x))
            self.completionTimeSelector.bind(on_release=self.completionTimeDropdown.open)
            self.durationDropdown.bind(on_select=lambda instance, changedDuration:self.refreshTaskPopup(duration=changedDuration, timestamp=timestamp))
            self.completionTimeDropdown.bind(on_select=lambda instance, changedCooldown:self.refreshTaskPopup(cooldown=changedCooldown, timestamp=timestamp))
            self.writeDurationPopup.bind(on_dismiss=self.durationDropdown.dismiss)
            self.writeCompletionTimePopup.bind(on_dismiss=self.completionTimeDropdown.dismiss)
        if duration is not None:
            self.endLabel.text = localisation.get(language, "end") + " " + getDateString( timestamp + durationToInt(duration) )
            self.cooldownLabel.text = localisation.get(language, "cooldown") + " " + getDateString( timestamp + durationToInt(duration) + durationToInt(self.completionTimeSelector.text))
            if timestamp + durationToInt(duration) > time.time() and self.fightButton is not None:
                self.endLabel.color = (1,1,0,1)
                self.endLabel.text += " !"
            elif self.fightButton is not None:
                self.endLabel.color = (1,1,1,1)                
        if cooldown is not None:
            self.cooldownLabel.text = localisation.get(language, "cooldown") + " " + getDateString( timestamp + durationToInt(self.durationSelector.text) + durationToInt(cooldown))
             
        
    def addNewPledge(self, taskSelector, durationSelector, cooldownSelector=None, popup=None):
        def addNewPledge_inner(_=None):
            if not taskSelector.text == '' and not durationSelector.text == '':
                if popup is not None: 
                    popup.dismiss()
                try:
                    tid = getTaskId(taskSelector.text)
                except:     
                    try:               
                        cur.execute("INSERT INTO Tasks(name) VALUES(?)", [taskSelector.text.strip()])
                    except:
                        cur.execute("INSERT INTO Tasks(name) VALUES(?)", [taskSelector.text.strip().decode('utf-8')])
                    con.commit()
                    tid = getTaskId(taskSelector.text)
                duration = durationToInt(durationSelector.text) 
                cur.execute("UPDATE Fights SET value=-1 WHERE taskId=? AND value = 0 AND startTime <= ?;", [tid, time.time()])
                unComplete(tid)
                cur.execute("INSERT INTO Fights VALUES(?, ?, ?, ?)", [time.time(), time.time()+duration, 0, tid])
                con.commit() 
                setDefaultCooldown(tid, durationToInt(cooldownSelector.text))
                self.buildMainScreen()
        return addNewPledge_inner
               
    def resolveFight(self, task_id, timeStart, timeEnd, success, durationSelector=None, completionTimeSelector=None, popup=None):
        def resolveFight_inner(_=None):
            global waitingForResolution
            changedDeadline = timeStart + durationToInt(durationSelector.text)
            if changedDeadline <= time.time():
                if popup is not None: popup.dismiss()
                oldScore = getScore(task_id, getPreviousMilestone(task_id), getNextMilestone(task_id))
                if success >= 0:
                    if success == 0: 
                        completionTime = 1
                        deadline = time.time()
                        cur.execute("UPDATE Fights SET endTime=? WHERE taskId=? AND startTime=? AND endTime =?;", [deadline, task_id, timeStart, timeEnd])
                    else:
                        deadline = timeEnd
                    try:
                        completionTime = durationToInt(completionTimeSelector.text)+1
                    except:
                        completionTime = 1
                    cur.execute("UPDATE Fights SET value=? WHERE taskId=? AND startTime=? AND endTime =?;", [completionTime, task_id, timeStart, deadline])
                    if abs(changedDeadline-deadline) > 1:
                        cur.execute("UPDATE Fights SET endTime=? WHERE taskId=? AND startTime=? AND endTime =?;", [changedDeadline, task_id, timeStart, deadline])    
                    con.commit()  
                elif success == -1:
                    cur.execute("UPDATE Fights SET value=? WHERE taskId=? AND startTime=? AND endTime =?;", [-1, task_id, timeStart, timeEnd])  
                    playAudio(soundFiles[2])
                    #Clock.schedule_once(self.taskPopup(task_id, int((timeEnd-timeStart)/60)),0)
                con.commit()
                self.taskMenu(task_id, oldScore)()
        return resolveFight_inner       
    
    def addMilestone(self, task_id, yearSelector, monthSelector, daySelector):
        def addMilestone_inner(_=None):
            milestone = datetime.datetime(int(yearSelector.text), int(monthSelector.text), int(daySelector.text))
            timestamp = (milestone - datetime.datetime(1970, 1, 1)).total_seconds() 
            cur.execute("INSERT INTO Milestones VALUES(?, ?)", [task_id, timestamp])
            con.commit()
            self.taskMenu(task_id)()
        return addMilestone_inner
    
    def deleteTask(self, task_id, switch):
        def deleteTask_inner(_=None):
            if switch.active:
                cur.execute("DELETE FROM Fights WHERE taskId = ?", [task_id])
                cur.execute("DELETE FROM Cooldowns WHERE taskId = ?", [task_id])
                cur.execute("DELETE FROM Milestones WHERE taskId = ?", [task_id])
                cur.execute("DELETE FROM Tasks WHERE id = ?", [task_id])
                con.commit()
                self.buildMainScreen()
        return deleteTask_inner
Example #31
0
class NewArmyListPopup(Popup):

    army_list_name = None

    def __init__(self, army_list, **kwargs):
        super(NewArmyListPopup, self).__init__(**kwargs)
        self.army_list = army_list
        self.list_name = None
        self.nation_dropdown = DropDown()
        for nation in theater_selector_dict.keys():
            button = DropDownButton(text=nation)
            button.bind(
                on_release=lambda btn: self.nation_dropdown.select(btn.text))
            self.nation_dropdown.add_widget(button)
        self.ids["button_nation_selection"].bind(
            on_release=self.nation_dropdown.open)
        self.nation_dropdown.bind(on_select=self.set_nationality)
        self.theater_dropdown = DropDown()
        self.ids["button_theater_selector"].bind(
            on_release=self.theater_dropdown.open)
        self.theater_dropdown.bind(on_select=self.set_theater_selector)

    def set_nationality(self, instance, nationality):
        self.theater_dropdown.dismiss()
        if nationality != self.ids["button_nation_selection"].text:
            self.ids["button_nation_selection"].text = nationality
            self.ids["button_theater_selector"].text = "select"
            self.theater_dropdown.clear_widgets()
            for selector in theater_selector_dict[nationality]:
                button = DropDownButton(text=selector)
                button.bind(on_release=lambda btn: self.theater_dropdown.
                            select(btn.text))
                self.theater_dropdown.add_widget(button)

    def set_theater_selector(self, instance, theater_selector):
        self.ids["button_theater_selector"].text = theater_selector

    def cancel(self):
        self.dismiss()

    def ok(self):
        if self.ids["textinput_name"].text == "":
            MessagePopup("List With No Name",
                         "Please give your new list a name")
        elif self.ids["textinput_name"].text in self.army_list["lists"].keys():
            MessagePopup(
                "List already exist",
                "There already is a army list with the name {}".format(
                    self.ids["textinput_name"].text),
            )
        elif self.ids["button_nation_selection"].text == "select":
            MessagePopup("No nation selected", "Please select a nation.")
        elif self.ids["button_theater_selector"].text == "select":
            MessagePopup("No theater selector selected",
                         "Please select a theater selector")
        else:
            self.list_name = self.ids["textinput_name"].text
            lists_dict = self.army_list["lists"]
            lists_dict[self.list_name] = default_list_dict["lists"]["default"]
            lists_dict[self.list_name]["nationality"] = self.ids[
                "button_nation_selection"].text
            lists_dict[self.list_name]["theater_selector"] = self.ids[
                "button_theater_selector"].text
            self.army_list["lists"] = lists_dict
            self.dismiss()
Example #32
0
class SimpleActionBar(BoxLayout):
    time = StringProperty()
    emp_popup = None
    popup = None
    logger = logging.getLogger('JAM')

    def __init__(self, config, **kwargs):
        BoxLayout.__init__(self, **kwargs)
        Clock.schedule_interval(self.update_time, 1)
        self.machine_dropdown = DropDown()
        self.machine_dropdown.bind(on_select=lambda instance, x: setattr(self.machine_button, 'text', x))
        self.set_machine_dropdown(config)

    def update_time(self, _dt):
        self.time = time.strftime('%x %H:%M')

    def set_machine_dropdown(self, config):
        self.machine_button.text = App.get_running_app().get_current_machine().config['machine_name']
        self.machine_dropdown.clear_widgets()
        blayout = BoxLayout(orientation='vertical', padding=10, spacing=10, size_hint=(None, None), width='150sp')
        for idx in range(1, 4):
            if int(config.get('Machine', 'machine{}_enable'.format(idx))):
                name = config.get('General{}'.format(idx), 'machine_name')
                colour = config.get('General{}'.format(idx), 'bg_colour')
                button = Button(text=name, size_hint_y=None, height=100, background_normal='',
                                background_color=Colour[colour].value)
                button.idx = idx
                button.bind(on_release=self.machine_selected)

                blayout.add_widget(button)
        blayout.height = len(blayout.children) * 110
        with blayout.canvas.before:
            Color(rgba=(0, 0, 0, 1))
            Rectangle(pos=blayout.pos, size=blayout.size)
        self.machine_dropdown.add_widget(blayout)

    def select_machine(self):
        self.machine_dropdown.open(self.machine_button)

    def machine_selected(self, button):
        self.machine_dropdown.select(button.text)
        if button.idx is not App.get_running_app().current_index:
            App.get_running_app().change_machine(button.idx)
            self.logger.debug("Selected index {}".format(button.idx))

    def toggle_button_states(self):
        self.machine_button.disabled = not self.machine_button.disabled
        self.main_button.disabled = not self.main_button.disabled

    def select_employee(self):
        self.toggle_button_states()
        sm = App.get_running_app().screen_manager
        sm.transition = SlideTransition()
        if sm.current is not 'employee_page':
            sm.transition.direction = 'up'
            sm.current = 'employee_page'
        else:
            sm.transition.direction = 'down'
            sm.current = App.get_running_app().get_current_machine().get_page()

    def select_maintenance(self):
        sm = App.get_running_app().screen_manager
        if sm.current is not 'maintenance_page':
            self.emp_popup = EmployeeScanPage(caller=self, auto_dismiss=False)
            self.emp_popup.parent_method = self.start_maintenance
            self.emp_popup.open()

    def start_maintenance(self, emp_id, _alternate=False):
        machine = App.get_running_app().get_current_machine()
        self.logger.debug("Starting maintenance for machine {}".format(machine.index))
        machine.start_maintenance(emp_id)
        self.emp_popup.dismiss()
        sm = App.get_running_app().screen_manager
        if sm.current is not 'maintenance_page':
            sm.transition = SlideTransition()
            sm.transition.direction = 'up'
            sm.current = 'maintenance_page'

    def select_settings(self):
        popup_boxlayout = BoxLayout(orientation='vertical', spacing='10sp', padding='10sp')
        self.popup = Popup(title='Admin', content=popup_boxlayout, size_hint=(0.5, 0.5))
        popup_boxlayout.add_widget(Label(text='Password: '******'auto'
        pass_input.password = True
        popup_boxlayout.add_widget(pass_input)
        cancel_btn = Button(text='Cancel')
        cancel_btn.bind(on_press=self.popup.dismiss)
        confirm_btn = Button(text='Confirm')
        confirm_btn.bind(on_press=lambda btn: self.start_settings(pass_input.text))
        hbox_layout = BoxLayout(orientation='horizontal', spacing='10sp', padding='10sp')
        hbox_layout.add_widget(cancel_btn)
        hbox_layout.add_widget(confirm_btn)
        popup_boxlayout.add_widget(hbox_layout)
        # pass_input.focus = True
        self.popup.open()

    def start_settings(self, password):
        self.popup.dismiss()
        if password == App.get_running_app().config.get('Settings', 'password'):
            self.logger.debug("Password is correct, opening settings")
            App.get_running_app().open_settings()
Example #33
0
class QReader(FloatLayout):
    
    login = ObjectProperty()
    
    def signin(self):
        
        try:
            self.user = User.login(self.login.username.text, self.login.password.text)
        
            self.remove_widget(self.login)
            
            self.main = Main()
            self.add_widget(self.main)
        except:
            MessageBoxTime(msg="Bad login").open()
        
    
    def decoded(self, val):
        self.message.text = val
        
    def show_label(self):
        
        labeldata = LabelData()
        
        
        labelinfo = Warehouses.Query.get(objectId=self.message.text)
        
        print labelinfo, labelinfo.ReceiptDate

        for property, value in vars(labelinfo).iteritems():
            print property, ": ", value
            labeldata.content.add_widget(Label(text=str(property) ) )
            labeldata.content.add_widget(Label(text=str(value) ) )

        '''
        labeldata.receipt.text = str(labelinfo.Receipt)
        labeldata.status.text = labelinfo.Status
        labeldata.receiptDate.text = str(labelinfo.ReceiptDate)
        labeldata.agent.text = labelinfo.Agent
        labeldata.shipper.text = labelinfo.Shipper.Name
        labeldata.consignee.text = labelinfo.Consignee.Name
        '''
        
        labeldata.open()
        
    def on_repack(self):
        print "Repack !"
        
        self.repack = Repack()
        self.repack.open()
        
    def repack_done(self):
        self.repack.dismiss()
        
        #open the repack dialog information
        self.repackform = RepackForm()
        self.repackform.open()
        
    def repack_save(self):
        self.repackform.dismiss()
        
        wh = Warehouses()
        wh.Agent = self.repackform.agent.text
        #wh.Consignee.Name = self.repackform.consignee.text
        wh.Zone = self.repackform.zone.text
        wh.Transport = self.repackform.transport.text
        wh.Content = self.repackform.contentnotes.text
        wh.GeneralNotes = self.repackform.generalnotes.text
        wh.InternalNotes = self.repackform.internalnotes.text

        wh.save()
        
    def do_clientcomplete(self, w):
        print w.text
        
        clients = Clients.Query.all()

        #for the autocomplete
        if not hasattr(self, "down"):
            self.down = DropDown()

        self.down.clear_widgets()

        for client in clients:
            if w.text.lower() in client.Name.lower():
                print client.Name
                
                but = Button(text=client.Name, size_hint_y=None, height=44, on_press=self.select_clientresult)
                
                self.down.add_widget(but)
                
        self.down.open(self.repackform.consignee)

    def select_clientresult(self, w):
        print w.text
class GeneScreen(Screen):

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

        # Widget Container
        screen_container = BoxLayout(orientation='vertical',
                                     padding=[1])

        # *Logo----------------------------------------------------------------
        self.logo = HomeButton()
        screen_container.add_widget(self.logo)

        # *Gene Selection Title------------------------------------------------
        screen_container.add_widget(Label(text='Gene Selection',
                                          size_hint=(1, .1),
                                          color=(0, .1, .25, .75)))

        # *Drop Down Menu------------------------------------------------------
        self.dropdown = DropDown()
        self.dropdown.bind(on_select=self.set_gene)
        self.dd_btns = []  # A list of drop down buttons for easy deletion

        #       Populate when top button hit
        self.mainbutton = CustomButton(text='Select a gene',
                                       size_hint=(1, .2))
        self.mainbutton.bind(on_release=self.load_genes)  # Populate dropdown
        self.dropdown.bind(on_select=lambda instance, x:
                           setattr(self.mainbutton, 'text', x))
        #       Place on screen
        screen_container.add_widget(self.mainbutton)

        # *Gene Buttons--------------------------------------------------------
        #       Declarations
        self.button_holder = BoxLayout(orientation='horizontal')

        #       Edit Button
        self.edit_btn = CustomButton(text="Edit",
                                     size_hint=(.3, .3))
        self.edit_btn.bind(on_release=self.switch_screen)

        #       New Button
        self.new_btn = CustomButton(text="New",
                                    size_hint=(.3, .3))
        self.new_btn.bind(on_release=self.switch_screen)

        #       Delete Button
        self.delete_btn = CustomButton(text="Delete",
                                       size_hint=(.3, .3))
        self.delete_btn.bind(on_release=self.delete)

        #       Placement
        self.button_holder.add_widget(self.edit_btn)
        self.button_holder.add_widget(self.new_btn)
        self.button_holder.add_widget(self.delete_btn)
        screen_container.add_widget(self.button_holder)  # Place Container
        #       Pack all widgets
        self.add_widget(screen_container)

        # Reset drop down when screen is loaded
        self.bind(on_enter=self.reset_menu)

    def load_genes(self, *args):
        """Called when drop down is opened"""

        self.dropdown.clear_widgets()  # Clear any packaged buttons
        del self.dd_btns[:]  # Clear drop down button list

        # Grab relevant genes
        genes = global_data.groups[global_data.active_group]

        for gene in genes:
            btn = CustomButton(text=gene.name,
                               size_hint_y=None,
                               height=self.height/9)

            btn.bind(on_release=lambda button:
                     self.dropdown.select(button.text))
            self.dropdown.add_widget(btn)  # Add button to menu
            self.dd_btns.append(btn)  # Store button in delety-list

        self.dropdown.open(args[0])

    def set_gene(self, *args):
        # Storing which group is selected for use in gene screen
        global_data.active_gene = args[1]  # args[1] - Name of gene

    def delete(self, *args):

        def delete_gene():
            group = global_data.active_group  # Get active group
            gene = global_data.active_gene  # Get active gene

            # Iterate through genes because we need to check the name of each
            for index, _gene in enumerate(global_data.groups[group]):

                if _gene.name == gene:

                    # Delete the gene
                    del global_data.groups[group][index]
                    # Remove from drop down
                    self.dropdown.remove_widget(self.dd_btns[index])
                    log(f"Gene {gene} deleted.")
                    break

            group_mngr.save_groups(global_data.groups)  # Save the groups

            global_data.active_gene = ''  # No active gene
            self.dropdown.select('Select a gene')

            popup.dismiss()

        if global_data.active_gene != '':

            # *Deletion Confirmation-------------------------------------------
            content = BoxLayout(orientation='vertical')
            content.add_widget(Label(text=f"Delete "
                                     f"{global_data.active_gene}?"))

            # *Confirmation Buttons--------------------------------------------
            options = BoxLayout(orientation='horizontal',
                                spacing=2)

            confirm_btn = CustomButton(text="Delete",  # Confirm button
                                       size_hint=(.3, .3))

            cancel_btn = CustomButton(text="Cancel",  # Cancel button
                                      size_hint=(.3, .3))
            #       Add Widgets to container
            options.add_widget(confirm_btn)
            options.add_widget(cancel_btn)
            content.add_widget(options)

            # *Popup Settings--------------------------------------------------
            popup = Popup(title="Delete?",
                          content=content,
                          size_hint=(None, None),
                          size=(400, 400),
                          separator_color=[1., 1., 1., 1.])

            confirm_btn.bind(on_press=delete_gene)
            cancel_btn.bind(on_press=popup.dismiss)

            popup.open()

    def switch_screen(*args):

        if args[1].text == "New":
            sm.current = 'editgene'

        elif args[1].text == "Edit":
            if global_data.active_gene != '':
                sm.current = 'editgene'

    def reset_menu(self, *args):
        # Need to make sure the menu text is defaulted when screen is entered
        self.dropdown.select('Select a gene')
        global_data.active_gene = ''
Example #35
0
class SpriteSettings(BoxLayout):
    check_flip_h = ObjectProperty(None)
    pos_btn = ObjectProperty(None)
    subloc_btn = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(SpriteSettings, self).__init__(**kwargs)
        self.functions = {"flip_h": self.flip_sprite}
        self.activated = []
        self.flipped = []
        self.pos_drop = None
        self.subloc_drop = None
        self.create_pos_drop()
        self.create_subloc_drop()

    def apply_post_processing(self, sprite, setting):
        try:
            if setting == 0:
                if sprite not in self.flipped:
                    self.flip_sprite(sprite.texture)
                    self.flipped.append(sprite)
            else:
                if sprite in self.flipped:
                    self.flip_sprite(sprite.texture)
                    self.flipped.remove(sprite)
        except AttributeError:
            pass
        return sprite

    def flip_sprite(self, sprite_texture):
        sprite_texture.flip_horizontal()

    def on_checked_flip_h(self, value):
        user_handler = App.get_running_app().get_user_handler()
        if value:
            user_handler.set_chosen_sprite_option(0)
        else:
            user_handler.set_chosen_sprite_option(1)
        sprite = user_handler.get_chosen_sprite()
        sprite_option = user_handler.get_chosen_sprite_option()
        sprite = self.apply_post_processing(sprite, sprite_option)
        main_scr = App.get_running_app().get_main_screen()
        main_scr.sprite_preview.set_sprite(sprite)
        Clock.schedule_once(main_scr.refocus_text, 0.2)

    def on_pos_select_clicked(self):
        self.pos_drop.open(self.pos_btn)

    def on_subloc_select_clicked(self):
        subloc_drop_main_btn = Widget(size_hint=(None, None), size=(200, 30))
        self.add_widget(subloc_drop_main_btn)
        subloc_drop_main_btn.pos = (
            self.subloc_btn.x + self.subloc_btn.width, self.subloc_btn.y + self.subloc_btn.height)
        try:
            self.subloc_drop.open(subloc_drop_main_btn)
        except:
            pass
        self.remove_widget(subloc_drop_main_btn)

    def create_pos_drop(self):
        self.pos_drop = DropDown(size_hint=(None, None), size=(100, 30), scroll_type=["bars", "content"], effect_cls="ScrollEffect", bar_width=10)
        for pos in ('center', 'right', 'left'):
            btn = Button(text=pos, size_hint=(None, None), size=(100, 30))
            btn.bind(on_release=lambda btn_: self.pos_drop.select(btn_.text))
            self.pos_drop.add_widget(btn)
        self.pos_drop.bind(on_select=self.on_pos_select)

    def on_pos_select(self, inst, pos):
        self.pos_btn.text = pos
        main_scr = App.get_running_app().get_main_screen()
        user_handler = App.get_running_app().get_user_handler()
        user_handler.set_chosen_pos_name(pos)
        main_scr.refocus_text()

    def create_subloc_drop(self):
        self.subloc_drop = DropDown(size_hint=(None, None), size=(100, 30), scroll_type=["bars", "content"], effect_cls="ScrollEffect", bar_width=10)
        self.subloc_drop.bind(on_select=self.on_subloc_select)

    def on_subloc_select(self, inst, subloc_name):
        self.subloc_btn.text = subloc_name
        main_scr = App.get_running_app().get_main_screen()
        user_handler = App.get_running_app().get_user_handler()
        user_handler.set_chosen_subloc_name(subloc_name)
        sub = user_handler.get_chosen_subloc()
        main_scr.sprite_preview.set_subloc(sub)
        main_scr.refocus_text()

    def update_sub(self, loc):
        if self.subloc_btn is not None:
            self.subloc_drop.clear_widgets()
        fav_subloc = App.get_running_app().get_fav_subloc()
        config = ConfigParser()
        config.read('mysteryonline.ini')
        fav_list = str(config.get('other', 'fav_subloc').strip('[]'))
        fav_list = fav_list.replace("'", "")
        fav_list = fav_list.split(',')
        fav_list = [x.strip() for x in fav_list]
        for sub in loc.list_sub():
            if loc.name+'_'+sub in fav_list and loc.name+'_'+sub in fav_subloc.value:
                btn = Button(text=sub, size_hint=(None, None), size=(200, 30),
                             background_normal='atlas://data/images/defaulttheme/button_pressed',
                             background_down='atlas://data/images/defaulttheme/button')
                btn.bind(on_release=lambda btn_: self.subloc_drop.select(btn_.text))
                self.subloc_drop.add_widget(btn)
        for sub in loc.list_sub():
            if loc.name+'_'+sub not in fav_subloc.value or loc.name+'_'+sub not in fav_list:
                btn = Button(text=sub, size_hint=(None, None), size=(200, 30))
                btn.bind(on_release=lambda btn_: self.subloc_drop.select(btn_.text))
                self.subloc_drop.add_widget(btn)
        self.subloc_btn.text = loc.get_first_sub()
Example #36
0
class MainWin(BoxLayout):
    current_map = ObjectProperty('')
    current_location = StringProperty()
    containers = ObjectProperty(loc_dat['Havana']['container'], allownone=True)
    in_event = False

    def __init__(self, **kwargs):
        super(MainWin, self).__init__(**kwargs)
        self.current_map = 'maps/Havana.jpg'
        self.current_location = 'Havana'
        self.containers = loc_dat['Havana']['container']
        self.locale = loc_dat['Havana']['connections']
        self.first_run = True

        # Drop Down code
        self.dropdown = DropDown()  # Binds Class
        self.dd_updater()  # Calls method to determine location containers
        self.ids.mb.bind(on_release=self.dropdown.open)  # Connects generated locations to
        self.dropdown.bind(on_select=lambda instance, x: self.location(x))  # Binds button's location changing behavior

        # Widgets
        self.ew = EventWindow()

        # Handles the placement of buttons on the map
        self.place_locale()

    def place_locale(self):
        self.cleanup()
        if self.locale is None:
            pass
        else:
            for place in self.locale:
                place_button = Button(text=place,
                                      id='pb',
                                      size_hint=(.05, .05),
                                      pos_hint={'x': loc_dat[self.current_location]['connections'][place][0],
                                                'y': loc_dat[self.current_location]['connections'][place][1]},
                                      on_release=lambda destination: self.location(destination.text))
                self.ids.mapspace.add_widget(place_button)
        if self.first_run is False:
            MainWin.in_event = True
            self.ids.mapspace.add_widget(self.ew)

    def cleanup(self):
        for child in [child for child in self.ids.mapspace.children]:
            self.ids.mapspace.remove_widget(child)

    def dd_updater(self):
        self.dropdown.clear_widgets()
        if self.containers is None:
            pass
        else:
            for note in self.containers:  # Adds widgets to the existing dropdown
                btn = Button(text=note,
                             color=(0, 0, 0, 1),
                             background_normal='images/Button.png',
                             background_down='images/Button.png',
                             border=(0, 60, 0, 120),
                             size_hint_y=None,
                             height=30)
                btn.bind(on_release=lambda b: self.dropdown.select(b.text))
                self.dropdown.add_widget(btn)

    def location(self, new_loc):
        if MainWin.in_event is False or self.first_run is True:
            self.current_location = new_loc
            self.current_map = loc_dat[new_loc]['image']
            self.locale = loc_dat[new_loc]['connections']
            self.containers = loc_dat[new_loc]['container']
            event.event_name()
            event.parse()
            self.dd_updater()
            self.place_locale()
        else:
            pass
        self.first_run = False
class HomeScreen(Screen):
    addButton = ObjectProperty(None)
    removeButton = ObjectProperty(None)
    top_layout = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(HomeScreen, self).__init__(*args, **kwargs)

    def resetBoxes(self):
        self.ids.btn_release.text = "Release"
        self.ids.btn_version.text = "Version"
        self.ids.btn_device.text = "Device"
        return

    # def removeButtonPressed(self):
    # # self.dropdown.remove_widget(self)
    # self.dropdown.clear_widgets()
    # btn = Button(text="HAI",size_hint_y=None, height=20)
    # self.dropdown.add_widget(btn)
    # return
    # def addButtonPressed(self):
    # self.dropdown = DropDown()
    # notes = ['Features', 'Suggestions', 'Abreviations', 'Miscellaneous']
    # for note in notes:
    # btn = Button(text=note, size_hint_y=None, height=20)
    # btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
    # self.dropdown.add_widget(btn)
    # self.ids.btn_release.bind(on_release=self.dropdown.open)
    # self.dropdown.bind(on_select=lambda instance, x: setattr(self.ids.btn_release, 'text', x))
    # return

    # To debug this code I need to have a status textbox that informs me of
    # The state of each buttons .text state and what this corresponds to
    # I have a sneaking suspicion that I'm not probing them properly.
    def btn_releaseClicked(self):
        self.dropdown = DropDown()
        self.dropdown.clear_widgets()
        if ((self.ids.btn_release.text == "Variable 1"
             or self.ids.btn_version.text == "Variable 1"
             or self.ids.btn_device == "Variable 1")
                and self.ids.btn_release.text != "Variable 2"
                and self.ids.btn_version.text != "Variable 2"
                and self.ids.btn_device != "Variable 2"):
            notes = ['Disabled', 'Common', 'Constant', 'Variable 2']
        elif (self.ids.btn_release.text == "Variable 2"
              or self.ids.btn_version.text == "Variable 2"
              or self.ids.btn_device == "Variable 2"):
            notes = ['Disabled', 'Common', 'Constant']
        else:
            notes = ['Disabled', 'Common', 'Constant', 'Variable 1']
        for note in notes:
            btn = Button(text=note, size_hint_y=None, height=20)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)
            self.ids.btn_release.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, x: setattr(
            self.ids.btn_release, 'text', x))
        return

    def btn_versionClicked(self):
        self.dropdown = DropDown()
        self.dropdown.clear_widgets()
        if ((self.ids.btn_release.text == "Variable 1"
             or self.ids.btn_version.text == "Variable 1"
             or self.ids.btn_device == "Variable 1")
                and self.ids.btn_release.text != "Variable 2"
                and self.ids.btn_version.text != "Variable 2"
                and self.ids.btn_device != "Variable 2"):
            notes = ['Disabled', 'Common', 'Constant', 'Variable 2']
        elif (self.ids.btn_release.text == "Variable 2"
              or self.ids.btn_version.text == "Variable 2"
              or self.ids.btn_device == "Variable 2"):
            notes = ['Disabled', 'Common', 'Constant']
        else:
            notes = ['Disabled', 'Common', 'Constant', 'Variable 1']
        for note in notes:
            btn = Button(text=note, size_hint_y=None, height=20)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)
            self.ids.btn_version.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, x: setattr(
            self.ids.btn_version, 'text', x))
        return

    def btn_deviceClicked(self):
        self.dropdown = DropDown()
        self.dropdown.clear_widgets()
        if ((self.ids.btn_release.text == "Variable 1"
             or self.ids.btn_version.text == "Variable 1"
             or self.ids.btn_device == "Variable 1")
                and self.ids.btn_release.text != "Variable 2"
                and self.ids.btn_version.text != "Variable 2"
                and self.ids.btn_device != "Variable 2"):
            notes = ['Disabled', 'Common', 'Constant', 'Variable 2']
        elif (self.ids.btn_release.text == "Variable 2"
              or self.ids.btn_version.text == "Variable 2"
              or self.ids.btn_device == "Variable 2"):
            notes = ['Disabled', 'Common', 'Constant']
        else:
            notes = ['Disabled', 'Common', 'Constant', 'Variable 1']
        for note in notes:
            btn = Button(text=note, size_hint_y=None, height=20)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)
            self.ids.btn_device.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, x: setattr(
            self.ids.btn_device, 'text', x))
        return
Example #38
0
class SymbolSearch(TextInput):
    def __init__(self, trade_screen=None, **kwargs):
        super(SymbolSearch, self).__init__(**kwargs)
        self.font_size = 40
        self.multiline = False
        self.dropdown = DropDown()
        self.dropdown_items = []
        self.dropdown.max_height = Window.size[1] * .2
        self.dropdown.background_color = (1,1,1,1)
        self.trade_screen = trade_screen

    def update_dropdown_items(self):
        """
        Create the buttons for the dropdown menu
        """        
        try:
            self.dropdown.clear_widgets()
            if self.text != '':
                self.dropdown_items = tag_trie.items(prefix=self.text)
            else:
                raise ValueError()
        except:
            self.dropdown_items = []
        if len(self.dropdown_items) > 50:
            self.dropdown_items = self.dropdown_items[:50]
        for tag,_ in self.dropdown_items:
            button = Button(text=tag, bold=True, size_hint_y=None, height=Window.size[1] * .04,
                            background_color=DARK_GREEN, on_press=lambda btn: self.dropdown_selected(btn))
            self.dropdown.add_widget(button)

    def on_focus(self, text_input, focused):
        """
        Engage the drop down menu to search for a position
        """
        prior = self.text
        if prior == 'Search':
            self.text = ''
        if focused:
            self.update_dropdown_items()
            self.dropdown.open(self)
        else:
            if self.text == '':
                self.trade_screen.display_no_symbol()
            else:
                self.trade_screen.display_symbol(self.text)
        self.trade_screen.more_info_button.disabled = self.text == ''


    def on_text(self, text_input, text):
        """
        Update the dropdown list to reflect the new search text
        """
        self.update_dropdown_items()
        try:
            self.dropdown.open()
        except:
            pass
    
    def insert_text(self, substring, from_undo=False):
        new_text = substring.upper()
        return super(SymbolSearch, self).insert_text(new_text, from_undo=from_undo)
    
    def dropdown_selected(self, button):
        """
        Make the selection from the dropdown menu
        """
        if self.trade_screen:
            self.text = button.text
            self.trade_screen.display_symbol(button.text)
            self.trade_screen.update_estimated_value()
            self.trade_screen.check_confirm_button()
        self.text = button.text
        self.dropdown.select(button)        
Example #39
0
class GroupSongDropdown(Button):
    def __init__(self, db: DBMuziek, default=None, **kwargs):
        super(GroupSongDropdown, self).__init__(**kwargs)

        self.dropdown = DropDown()

        self.song_id = None
        self.text = "<Choice>"

        self._db = db
        self.songs = None
        self.g_id = None
        self.g_name = None
        self.disable()

        self.update_data(default)

        self.bind(on_release=self.open)
        self.dropdown.bind(on_select=lambda _, btn: self.on_select(btn))

    def disable(self):
        self.disabled = True

    def enable(self):
        self.disabled = False

    def update_data(self, data):
        if data and "group_id" in data:
            self.g_id = data["group_id"]
            self.g_name = data["group_name"]
            if "song_id" in data:
                self.song_id = data["song_id"]
                self.text = data["song_name"]
            if self.g_id is not None:
                self.update_songs()
                self.enable()

    def reset_choice(self, dd):
        if dd:
            dd.dismiss()
        self.text = "<Choice>"
        self.song_id = None

    def update_songs(self, g_id=-1, g_name=None):
        if g_id is None:
            self.reset_choice(None)
            self.g_id = None
            self.disable()
            return
        elif g_id != -1 and self.g_id != g_id:
            self.g_id = g_id
            self.enable()
            self.reset_choice(None)
        if g_name:
            self.g_name = g_name

        self.songs = self._db.get_songs({"group_id": self.g_id})

        self.dropdown.clear_widgets()

        btn = Button(text="<Choice>", size_hint_y=None, height=44)
        btn.bind(on_release=lambda _: self.reset_choice(self.dropdown))
        self.dropdown.add_widget(btn)

        for song in self.songs:
            btn = SongButton(text=song["song_name"],
                             size_hint_y=None,
                             height=44)
            btn.set_id(song["song_id"])
            btn.bind(on_release=self.dropdown.select)

            self.dropdown.add_widget(btn)

        btn = Button(text="+", size_hint_y=None, height=44)
        btn.bind(on_release=lambda _: summon_popup_song(
            self._db, self.dropdown, self.g_id, self.g_name))
        self.dropdown.add_widget(btn)

    def open(self, btn):
        self.update_songs()
        self.dropdown.open(btn)

    def on_select(self, btn):
        self.text = btn.text
        self.song_id = btn.song_id
Example #40
0
class ScreenMain(Screen):
    settings_popup = ObjectProperty(None, allownone=True)
    top_layout     = ObjectProperty(None)
    main_btn       = ObjectProperty(None)
    dd_btn         = ObjectProperty(None)
    
    def __init__ (self,**kwargs):
        super (ScreenMain, self).__init__(**kwargs)
        Clock.schedule_once(self.prepare, 0)
        self.dropdown = DropDown()
        self.user_name ='5 '
    def prepare(self, *args):
        global user_id
        # if first time or loged out
        user_id = 0
        # call the login screen
        self.manager.current = 'ScreenLogin'

    def new_user(self, sid, name):
        print sid, name
        global user_name
        self.user_name = name
            
        user_name_label=self.ids.user_name_label
        user_name_label.text=self.user_name
        first_id = self.add_classes()
            # need to get first list
        self.class_selected(first_id)

    def add_classes(self):
        # sql  get classes for user
        # is user a from teacher ?
        # change spinner text & values
        sql = 'SELECT sg.id, s.name \
                FROM studygroups sg \
                JOIN subjects s ON (sg.subject_id = s.id) \
                WHERE sg.staff_id=%d \
                AND sg.schYr = %d' % (user_id, 2016)

        alchemysql = alchemy_text(sql)
        result = engine.execute(alchemysql)

        classes = [r for r in result]
        self.create_dropdown(classes)

        if not classes: return

        print classes
        first_id   = classes[0][0]
        first_name = classes[0][1]
 
        ddbtn = self.ids.btn_ddID
        ddbtn.text = str(first_name)
        
        return first_id

    def create_dropdown(self, groups):
        self.dropdown.clear_widgets()
        for group in groups:
            # create button
            btn = self.create_button(group)
            # add it the dropdown
            self.dropdown.add_widget(btn)

    def create_button(self, group):
        gid, name = group
        
        # specify the height so the dropdown can calculate the area it needs.
        # store the class id in the buttons name
        btn = Button(text= name, size_hint_y=None, height=40, name=str(gid))
        
        # attach a callback that will call the select() method on the dropdown.
        # pass the button text as the data of the selection.
        btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
        
        # the call to update student list when button pressed
        btn.bind(on_release=partial(self.class_selected, gid))
        return btn

    def class_selected(self, *args ):
        class_id = args[0]

        student_list_widget = self.ids.student_list
        student_list_widget.clear_widgets()

        if not class_id: return
        
        sql = 'SELECT s.id, s.name \
                 FROM students_by_studygroup ss \
                 JOIN students s ON (ss.student_id = s.id) \
                 WHERE ss.studygroup_id=%d ' % (class_id,)
        alchemysql = alchemy_text(sql)
        result = engine.execute(alchemysql)
        # convert to a python list
        students = [r for r in result]
        self.add_students(students)

    def drop_down(self, x=''):
        # open the dropdown buttons
        self.dropdown.open(x)
        # set mainbutton text to select item
        self.dropdown.bind(on_select=lambda instance, y: setattr(x, 'text', y))

    def changer2(self, result, *args):
        global student_id
        student_id = args[0]
        self.manager.get_screen('ScreenStudentDetails').update(result)
        self.manager.current = 'ScreenStudentDetails'        
        
    def add_students(self, lst):
        student_list_widget = self.ids.student_list
        for item in lst:            
            btn = self.build_student_button(item)
            student_list_widget.add_widget(btn)
            sid = item[0]
            btn.bind(on_press=partial(self.changer2, sid))
        student_list_widget.bind(minimum_height=student_list_widget.setter('height'))
    
    def build_student_button(self, item):
        image_id = str(item[0]).zfill(5)
        image_file = "student_images/0000%d.jpg" % item[0]
        btn = StudentListItemButton(
                wid = str(item[0]), 
              image = image_file, 
              title = item[1], 
              label = item[1]
            )
        btn.size_hint=(1, None)
        btn.height = 42
        return btn
Example #41
0
class Toolbar(BoxLayout):
    def __init__(self, **kwargs):
        super(Toolbar, self).__init__(**kwargs)
        self.user = None
        self.color_drop = DropDown(size_hint=(None, None), size=(100, 30))
        for col in ('red', 'blue', 'golden', 'green', 'rainbow', 'purple', 'normal'):
            btn = Button(text=col, size_hint=(None, None), size=(100, 30))
            btn.bind(on_release=lambda btn_: self.color_drop.select(btn_.text))
            self.color_drop.add_widget(btn)
        self.text_col_btn = Button(text='color', size_hint=(None, None), size=(100, 30))
        self.text_col_btn.bind(on_release=self.color_drop.open)
        self.add_widget(self.text_col_btn)
        self.color_drop.bind(on_select=self.on_col_select)
        self.item_drop = DropDown(size_hint=(None, None), size=(200, 30))
        self.text_item_btn = Button(text='no item', size_hint=(None, None), size=(200, 30))
        self.text_item_btn.bind(on_release=self.build_item_drop)
        self.text_item_btn.bind(on_release=self.item_drop.open)
        self.add_widget(self.text_item_btn)
        self.item_drop.bind(on_select=self.on_item_select)

        self.sfx_main_btn = Button(text='SFX')
        self.sfx_dropdown = None    
        self.sfx_name = None        
        self.sfx_list = []          
        self.load_sfx()
        self.add_widget(self.sfx_main_btn)

    def build_item_drop(self, pos):
        self.item_drop.clear_widgets()
        item_list = self.user.inventory.get_item_string_list()
        default_btn = Button(text="no item", size_hint=(None, None), size=(200, 30))
        default_btn.bind(on_release=lambda btn_: self.item_drop.select(btn_.text))
        self.item_drop.add_widget(default_btn)
        for item in item_list:
            btn = Button(text=item, size_hint=(None, None), size=(200, 30))
            btn.bind(on_release=lambda btn_: self.item_drop.select(btn_.text))
            self.item_drop.add_widget(btn)

    def set_user(self, user):
        self.user = user

    def on_col_select(self, inst, col, user=None):
        main_scr = App.get_running_app().get_main_screen()
        if user is None:
            user = main_scr.user
        user.on_col_select(col, self.text_col_btn)
        main_scr.refocus_text()

    def on_item_select(self, inst, item):
        self.text_item_btn.text = item
        if item != "no item":
            item = self.user.inventory.get_item_by_name(item)
            self.user.inventory.send_item(item)
        self.text_item_btn.text = "no item"

    def get_sfx_name(self):     
        if self.sfx_name == "None":
            self.sfx_name = None
        current_sfx = self.sfx_name
        if self.sfx_name is not None:
            self.sfx_main_btn.text = "None"
            self.sfx_name = None
        return current_sfx

    def load_sfx(self):         
        for file in os.listdir('sounds/sfx'):
            if file.endswith('wav'):
                self.sfx_list.append(file)

    def create_sfx_dropdown(self):
        self.sfx_dropdown = DropDown()
        fav_sfx = App.get_running_app().get_fav_sfx()
        for sfx in fav_sfx.value:
            if sfx in self.sfx_list:
                btn = Button(text=sfx, size_hint_y=None, height=40,
                             background_normal='atlas://data/images/defaulttheme/button_pressed',
                             background_down='atlas://data/images/defaulttheme/button')
                btn.bind(on_release=lambda x: self.sfx_dropdown.select(x.text))
                self.sfx_dropdown.add_widget(btn)
        for sfx in self.sfx_list:
            if sfx not in fav_sfx.value:
                btn = Button(text=sfx, size_hint_y=None, height=40)
                btn.bind(on_release=lambda x: self.sfx_dropdown.select(x.text))
                self.sfx_dropdown.add_widget(btn)

        btn = Button(text="None", size_hint_y=None, height=40)
        btn.bind(on_release=lambda x: self.sfx_dropdown.select(x.text))
        self.sfx_main_btn.bind(on_release=self.sfx_dropdown.open)
        self.sfx_dropdown.add_widget(btn)
        self.sfx_dropdown.bind(on_select=lambda instance, x: setattr(self.sfx_main_btn, 'text', x))
        self.sfx_dropdown.bind(on_select=lambda instance, x: setattr(self, 'sfx_name', x))
Example #42
0
class ScreenMain(BoxLayout):
    top_layout   = ObjectProperty(None)
    dd_btn       = ObjectProperty(None)
    student_image_btn    = ObjectProperty('None')
    
    def __init__(self,**kwargs):
        super (ScreenMain,self).__init__(**kwargs)
        self.dropdown = DropDown()
        
        self.messages_grid = self.ids.messages_grid
        self.child_id = 0
        self.msg_id =10
        Clock.schedule_once(self.prepare, 0)
        
        
    def prepare(self, *args):
        global user_id
        print 'prepare'
        # if first time or loged out
        user_id = 0
        self.child_id = 0
        print ' call the login popup'
        p = LoginPopup()
        p.open()
        Clock.schedule_interval(self.get_new_messages, 1)
        Clock.schedule_interval(self.send_rnd_msg, 2)
        
    def send_rnd_msg(self, *args):

        cid = (random.choice([705,2,68]))

        sql ="INSERT INTO messages VALUES(%d, %d, 'rnd msg',  '01,01,2016', 0, 1)" % (self.msg_id, cid )

        print sql
        cur.execute(sql)

        self.msg_id +=1
                    
    def new_user(self):
        global user_name
        print 'new_user'
        user_name = ""        
        if user_id > 0:
            user_name = "Andrew Watts" # fetch name for user_id
            first_id = self.add_children()
            # need to get first list
            self.child_selected(first_id)

    def add_children(self):
        global user_id, children_dict
        children_dict = {}
        print 'add_children'
        # sql  get children for parent
        user_id = 180 # test
        sql = 'SELECT id, name \
                FROM students \
                WHERE father_id=180' 

        alchemysql = alchemy_text(sql)
        result = engine.execute(alchemysql)

        children = [r for r in result]
        count_children = len(children)
        
        for sid, name in children:
            children_dict[sid] = name
        print 'children_dict',children_dict
        self.create_dropdown(children)

        first_id   = children[0][0]
        first_name = children[0][1]
        
        ddbtn = self.ids.btn_ddID
        ddbtn.text = str(first_name)
        
        return first_id

    def drop_down(self, x=''):
        # open the dropdown buttons
        self.dropdown.open(x)
        # set mainbutton text to select item
        self.dropdown.bind(on_select=lambda instance, y: setattr(x, 'text', y))

    def create_dropdown(self, children):
        print 'create_dropdown'
        
        self.dropdown.clear_widgets()
        for child in children:
            # create button
            btn = self.create_button(child)
            # add it the dropdown
            self.dropdown.add_widget(btn)

    def create_button(self, child):
        print 'create_button'
        gid, name = child
        
        # specify the height so the dropdown can calculate the area it needs.
        # store the class id in the buttons name
        btn = Button(text= name, size_hint_y=None, height=40, name=str(gid))
        
        # attach a callback that will call the select() method on the dropdown.
        # pass the button text as the data of the selection.
        btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
        
        # the call to update student list when button pressed
        btn.bind(on_release=partial(self.child_selected, gid))
        return btn

    def create_mask(self):
        self.mask = Image.new('L', (200,200), 0)
        draw = ImageDraw.Draw(self.mask) 
        draw.ellipse((0, 0) + self.mask.size, fill=255)
    
    def child_selected(self, *args ):
        print 'child_selected'

        self.messages_grid.clear_widgets()
        
        self.child_id = args[0]
  
        image_id = str(self.child_id).zfill(5)
        self.imagefile =  'student_images/%s' % image_id
        print 'the imagefile', self.imagefile

        name = "Name:%s \n ID:%d" % (children_dict[self.child_id], self.child_id)
        studentname_label = self.ids.studentname_label
        studentname_label.text = name

        # would like to change img_btn to image
        # image would be a background fill with a 
        # round masked image of the student on top
        # or student behind and the fill has a hole in it

        img_btn = self.ids.student_image_btn
        img_btn.background_normal = 'student_images/00001.jpg'

        stored_messages = self.get_stored_messages()
  
        # get new messages
        self.get_new_messages()
        
        
    def get_new_messages(self, x=0):
        new_messages = self.select_column_and_value("SELECT id, message, date \
                                                       FROM messages \
                                                      WHERE child_id = %d \
                                                        AND user_id = 1 \
                                                        AND read <> 1" % self.child_id)
        txt = "there are %d new messages for child_id %d)" % (len(new_messages), self.child_id)
        print txt
        for msg in new_messages:
            msg_id, child_id, content, date = msg['id'], self.child_id, msg['message'], msg['date'] 

            sql = "INSERT INTO stored_messages VALUES (%d, %d, '%s', '%s')" % (msg_id, child_id, content, date)
            print sql
            cur.execute(sql)

            sql = "UPDATE messages SET read=1 WHERE id=%d"  % (msg_id, )
            print sql
            cur.execute(sql)
            

            self.display_msg(msg, 1)

    def notify_db(self, msg_id):
        pass
        

    def select_column_and_value(self, sql, parameters=()):
        execute = cur.execute(sql, parameters)
        fetch = execute.fetchall()

        if fetch is None:
            return {k[0]: None for k in execute.description}

        else:
            lis = []
            for row in fetch:
                lis.append( {k[0]: v for k, v in list(zip(execute.description, row))} )
            return lis


    def get_stored_messages(self):
        print 'get_stored_messages'
        
        stored_messages = self.select_column_and_value("SELECT id, message, date FROM stored_messages WHERE child_id = %d " % self.child_id)

        for msg in stored_messages:
            self.display_msg(msg)
        return stored_messages
   
        # save to file
        # if self.notify_db(key): is sucsessful
        #     pass
        # else:
        #     return # wait for clock 
            

    def display_msg(self, entry, new=0):
        print 'display_msg ', entry
        content = entry['message']
        print 'content = ', content
        if new:
           content = 'new %s' % content 
        lbl = Label( text = content)
        self.messages_grid.add_widget(lbl)

        widget = self.ids.messages_grid
        widget.bind(minimum_height= widget.setter('height'))