コード例 #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()
コード例 #2
0
ファイル: TodayScreen.py プロジェクト: bix709/MobileApps
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()
コード例 #3
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()
コード例 #4
0
ファイル: main.py プロジェクト: oukiar/DevsHub
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()
コード例 #5
0
class bbEntryRightControlPanel(BoxLayout):

    bb = ObjectProperty(None)
    labels = ListProperty(None)

    assign_label = ObjectProperty(None)
    delete_bb = ObjectProperty(None)

    bbId = StringProperty(None)
    bbLabel = StringProperty(None)

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

    def set_label_button_text(self):
        if self.bb.label:
            self.bbLabel = str(self.bb.label)
        else:
            self.bbLabel = "Undefined Label"

    def on_bb(self, instance, value):
        self.set_label_button_text()

    def assign_label_clicked(self, inst):
        self.bbLabel = 'Choose label'
        self.dropdown = DropDown(on_dismiss=self.dropdown_dismissed)
        for label in self.labels:
            btn = Button(text=str(label),
                         size_hint_y=None,
                         height=40,
                         background_color =  (.8, .8, .3, 1),
                         background_normal= ''
                         )
            btn.bind(on_release=lambda btn: self.label_clicked(btn, self.bb))
            self.dropdown.add_widget(btn)
        self.dropdown.auto_dismiss = True
        self.dropdown.open(inst)

    def dropdown_dismissed(self, value):
        self.set_label_button_text()

    def label_clicked(self, inst, bb):
        if self.dropdown:
            self.dropdown.dismiss()
            self.set_label_button_text()

        self.assign_label(bb, inst.text)
        self.bbLabel = str(self.bb.label)
コード例 #6
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()
コード例 #7
0
class DatePicker(Button):
    def __init__(self, **kwargs):
        super(DatePicker, self).__init__(**kwargs)

        self.dropdown = DropDown(auto_width=False, width=300)
        self.dropdown.bind(on_select=self.on_select)
        self.dropdown.add_widget(
            DatePickerBase(size_hint_y=None,
                           height=200,
                           dropdown=self.dropdown))

        self.add_widget(self.dropdown)
        self.dropdown.dismiss()

    def on_release(self, *args):
        self.dropdown.open(self)

    def on_select(self, instance, data):
        self.text = data
コード例 #8
0
ファイル: main.py プロジェクト: tshirtman/CaeMobile
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()
コード例 #9
0
class OptionsLay(Screen):
    """ layout zawierający możliwość zmainy opcji, czyli ścieżki pobierania narazie """
    save_btn = ObjectProperty(None)
    dir_input = ObjectProperty(None)
    channel_input = ObjectProperty(None)
    change_file_type_dropdown_main_btn = ObjectProperty(None)

    def __init__(self, layout_manager, **kwargs):
        super(OptionsLay, self).__init__(**kwargs)
        self.maked_dropdown = False
        self.layout_manager = layout_manager

    def go_return(self):
        self.layout_manager.window_manager.transition.direction = 'down'
        self.layout_manager.window_manager.current = 'menu_lay'

    def save_options(self):
        """ zapisuje opcje, jeśli zmieniono kanał to czyści załadowne opcje i blokuje pobieranie, aby uniknąć błędów """
        options_dict = JsonOperations.load_json('../data/config.json')

        options_dict['save_path'] = self.dir_input.text
        options_dict[
            'file_type'] = self.change_file_type_dropdown_main_btn.text

        if self.parse_yt_channel_name():
            self.format_channel_input()
            self.check_channel_options(self.channel_input.text)
            if options_dict['channel'] != self.channel_input.text:
                self.block_on_change_channel()
                options_dict['channel'] = self.channel_input.text

            self.save_btn.text = 'Saved'
        else:
            self.save_btn.text = 'Bad channel'
        JsonOperations.save_json(options_dict, '../data/config.json')
        Clock.schedule_once(self.change_text_save_btn, 0.8)

    def change_text_save_btn(self, _):
        self.save_btn.text = 'Save'

    def parse_yt_channel_name(self):
        """ za pomocą zewnętrznej funkcji sprawdza czy podany adres jest poprwany, czyli czy jest po  nazwie lub id """
        if parse_yt_channel_name(self.channel_input.text):
            return True
        return False

    def format_channel_input(self):
        """ odcina niepotrzebną końcówkę w adresie """
        txt = self.channel_input.text
        if len(txt.split("/")) != 5:
            self.channel_input.text = "/".join(txt.split("/")[:5])

    @staticmethod
    def check_channel_options(new_channel):
        """ jeśli nowego kanału nie ma w bazie ostanich utworów to go dodaje """
        last_track_dict = JsonOperations.load_json('../data/last_track.json')
        if new_channel not in last_track_dict.keys():
            last_track_dict[new_channel] = ''
            JsonOperations.save_json(last_track_dict,
                                     '../data/last_track.json')

    def block_on_change_channel(self):
        """ czyści liste utworów w layoucie i blokuje pobieranie przy zmianie kanału w opcjach """
        self.layout_manager.inst_main_chill_layout.clear_scroll()
        self.layout_manager.inst_main_chill_layout.un_or_block_btn(
            list_btn_to_block=[
                self.layout_manager.inst_main_chill_layout.new_download_btn,
                self.layout_manager.inst_main_chill_layout.select_songs_btn
            ],
            block=True)

    def make_options(self):
        conf_dict = DownloaderOperations.get_all_config()
        self.dir_input.text = conf_dict['save_path']
        self.channel_input.text = conf_dict['channel']
        self.change_file_type_dropdown_main_btn.text = conf_dict['file_type']
        if not self.maked_dropdown:
            self.make_dropdown()

    def make_dropdown(self):
        self.dropdown = DropDown()
        self.dropdown.dismiss_on_select = False
        for ft_name in SUPPORTED_FORMAT_TYPES:
            dd_btn = Button(
                text=ft_name,
                size_hint_y=None,
                height=50,
                background_normal='',
                border=(16, 16, 16, 16),
                background_color=[0.81640625, 0.3125, 0.43359375, 1])
            dd_btn.bind(on_release=self.release_dropdown_button)
            self.dropdown.add_widget(dd_btn)
        self.change_file_type_dropdown_main_btn.bind(
            on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, dd_main_text: setattr(
            self.change_file_type_dropdown_main_btn, 'text', dd_main_text))
        self.maked_dropdown = True

    def release_dropdown_button(self, instance):
        self.dropdown.select(instance.text)
        self.dropdown.dismiss()
コード例 #10
0
ファイル: DropDown.py プロジェクト: thica/ORCA-Remote
class cWidgetDropDown(cWidgetButton):
    '''
    WikiDoc:Doc
    WikiDoc:Context:Widgets
    WikiDoc:Page:Widgets-DROPDOWN
    WikiDoc:TOCTitle:DropDown
    = DROPDOWN =

    The dropdown list widget is one of the core widgets. It is based on a button widget, whichs adds further option buttons linked to the button, when the button is clicked
    If you press a button from the options buttons, an action is triggered
    The button widget shares the common widget attributes and the button widget attributes.
    The following attributes are additional attributes to button widget attributes:
    <div style="overflow:auto; ">
    {| class="wikitable"
    ! align="left" | Attribute
    ! align="left" | Description
    |-
    |type
    |fixed: needs to be "DROPDOWN". Capital letters!
    |-
    |captions
    |List of captions for all option buttons. This is a comma separated list 
    |-
    |actions
    |List of actions for each option button. This is a comma separated list. This list must match the numer of captions. If you do not want to bind a caption, leave it as a comma seperated empty list (e.g. ",,,,"
    |-
    |framecolor
    |If you want a colored frame around the dropdown, this specifies the frame color.
    |-
    |framewidth
    |If you want a colored frame around the dropdown, this specifies the frame width in relative pixels
    |}</div>
     
    Below you see an example for a dropdown widget
    <div style="overflow-x: auto;"><syntaxhighlight  lang="xml">
    <element name="Dropdown" type="DROPDOWN" fontsize='%h50' caption='My Dropdown' captions='Option 1,Option 2,Option 3,Option 4' actions=',,,' htextalign='center' vtextalign='middle' picturenormal="button wide*" framecolor='$var(dimmed)' framewidth='500'/>
    </syntaxhighlight></div>
    WikiDoc:End
    '''

    def __init__(self,**kwargs):
        super(cWidgetDropDown, self).__init__(**kwargs)
        self.oDropDownButtons = []
        self.uCaptions        = []
        self.uActions         = []
        self.oObjectDropDown  = None
        self.oDimmer          = None
        self.iFrameWidth      = 0
        self.uActionNames     = u''
        self.tFrameColor      = []


    def InitWidgetFromXml(self,oXMLNode,oParentScreenPage, uAnchor):
        bRet=super(cWidgetDropDown, self).InitWidgetFromXml(oXMLNode,oParentScreenPage, uAnchor)
        if bRet:
            self.tFrameColor  = GetColorFromHex(GetXMLTextAttribut(oXMLNode,u'framecolor',False,u'$var(dimmed)'))
            self.iFrameWidth  = GetXMLIntAttribut(oXMLNode,u'framewidth',  False,self.oDef.iDefMaxX/self.fRationX)*0.02

            if u':::' in self.uCaption:
                uCaptions         = self.uCaption.split(u':::')
                self.uCaption     = uCaptions[0]
                #self.uOrgCaption  = self.uCaption
                self.uCaptions    = uCaptions[1:]
                self.uActionNames = ReplaceVars(self.uActionName).split(u':::')
                self.uActionName  = u''
            else:
                self.uCaptions    = GetXMLTextAttribut(oXMLNode,u'captions', True,u'unknown').split(u',')
                self.uActionNames = GetXMLTextAttribut(oXMLNode,u'actions',  True,u'').split(u',')

            if len(self.uActionNames)!=len(self.uCaptions):
                LogError(u'cWidgetDropDown: Captions do not match Actions:'+self.uActionName)
                bRet=False
            else:
                for num in range(len(self.uCaptions)):
                    oBtn                      = cWidgetButton()
                    # we cant use the touchbutton object, as Buttonbehaviour not work on buttons on scolllayout
                    #oBtn.ClassName            = Button
                    oBtn.bIsDropButton        = True
                    oBtn.InitWidgetFromXml(oXMLNode,oParentScreenPage, uAnchor)
                    oBtn.SetCaption(self.uCaptions[num])
                    oBtn.uActionName          = self.uActionNames[num]
                    oBtn.iAnchorPosX          = 0
                    oBtn.iAnchorPosY          = 0
                    oBtn.iPosX                = 0
                    oBtn.iPosY                = 0
                    oBtn.uActionNameDoubleTap = u''
                    oBtn.uActionNameDownOnly  = u''
                    oBtn.uActionNameUpOnly    = u''
                    oBtn.uActionNameLongTap   = u''
                    self.oDropDownButtons.append(oBtn)
        return bRet

    def Create(self,oParent,iWidgetIndex):

        try:
            if super(cWidgetDropDown, self).Create(oParent,iWidgetIndex):
                self.oObjectDropDown=DropDown()
                #self.dismiss_on_select=True
                for oWidget in self.oDropDownButtons:
                    oWidget.Create(oParent,-1)
                    oWidget.uName            = "*DROPDOWNBUTTON*"+oWidget.uName
                    oBtn                     = oWidget.oObject
                    oWidget.oParent.remove_widget(oBtn)
                    oBtn.size_hint_y         = None
                    oBtn.unbind(on_q_release = oWidget.On_Button_Up)
                    oBtn.bind(on_q_release   = self.DropDownSelect)
                    self.oObjectDropDown.add_widget(oBtn)
                self.oObject.bind(on_q_release = self.OpenDropDown)
                self.oObjectDropDown.bind(on_dismiss = self.CloseDropDown)
                return True
            return False
        except Exception as e:
            LogError("Can''t create Dropdown",e)
            return False

    def OpenDropDown(self,instance):
        ''' opens the dropdown '''
        Object=self.oObjectDropDown
        Object.open(self.oObject)
        self.oDimmer=cTouchRectangle(pos=(Object.pos[0]-self.iFrameWidth,Object.pos[1]-self.iFrameWidth),width=Object.width+self.iFrameWidth*2,height=Object.height+self.iFrameWidth*2,background_color=self.tFrameColor)
        self.oParent.add_widget(self.oDimmer)

    def CloseDropDown(self,instance):
        ''' closes the dropdown '''
        self.oParent.remove_widget(self.oDimmer)

    def DropDownSelect(self,instance):
        ''' selects on item of dropdown '''
        #self.SetCaption(instance.text)
        self.oObjectDropDown.dismiss()
        instance.oOrcaWidget.On_Button_Up(instance)
        return

    def UpdateWidget(self):

        uCaption=ReplaceVars(self.uOrgCaption)
        if u':::' in uCaption:
            aCaptions         = self.uCaption.split(u':::')
            self.SetCaption2(aCaptions[0])
            aCaptions    = aCaptions[1:]

            for i in range(len(self.oDropDownButtons)):
                if i<len(aCaptions):
                    self.oDropDownButtons[i].UpdateWidget(aCaptions[i])
            return True
        return self.SetCaption2(self.uOrgCaption)
コード例 #11
0
ファイル: DropDown.py プロジェクト: thica/ORCA-Remote
class cWidgetDropDown(cWidgetButton):
    """
    WikiDoc:Doc
    WikiDoc:Context:Widgets
    WikiDoc:Page:Widgets-DROPDOWN
    WikiDoc:TOCTitle:DropDown
    = DROPDOWN =

    The dropdown list widget is one of the core widgets. It is based on a button widget, which adds further option buttons linked to the button, when the button is clicked
    If you press a button from the options buttons, an action is triggered
    The "DROPDOWNVALUE" value is added to the action pars which refers to the button text
    The "DROPDOWNINDEX" index is added to the action pars which refers to the button order, eg: "0" is the first button in the list

    The button widget shares the common widget attributes and the button widget attributes.
    The following attributes are additional attributes to button widget attributes:
    <div style="overflow:auto; ">
    {| class="wikitable"
    ! align="left" | Attribute
    ! align="left" | Description
    |-
    |type
    |fixed: needs to be "DROPDOWN". Capital letters!
    |-
    |captions
    |List of captions for all option buttons. This is a comma separated list. You can pass $DIRLIST[mypath] as captions, which then expands to the list of folders within that path. You can pass an array of variables as well. In this case, you need to pass the variable name (without $var() (MyBottonText:::Myarray[]). Each of the elements will be seen as a variable, which will be expanded at runtime
    |-
    |actions
    |List of actions for each option button. This is a comma separated list. This list must match the numer of captions. If you do not want to bind a caption, leave it as a comma seperated empty list (e.g. ",,,,"). If you pass only one action, than this will be called for all events. In all cases, a function var will be passed with the value of the selected option. (eg. MYACTION_parameter_DROPDOWNVALUE)
    |-
    |framecolor
    |If you want a colored frame around the dropdown, this specifies the frame color.
    |-
    |framewidth
    |If you want a colored frame around the dropdown, this specifies the frame width, either in relative pixels or in percentage, If not given, a defult vaule will be used
    |-
    |sorted
    |(0/1) If set, the captions of the dropdown will be sorted, It will not sort the actions, so use it only if you use the same action for each item
    |-
    |setcaption
    |(0/1) If set, the caption of the main button will be set o the selected dropdown value

    |}</div>

    Below you see an example for a dropdown widget
    <div style="overflow-x: auto;"><syntaxhighlight  lang="xml">
    <element name="Dropdown" type="DROPDOWN" fontsize='%h50' caption='My Dropdown' captions='Option 1,Option 2,Option 3,Option 4' actions=',,,' htextalign='center' vtextalign='middle' picturenormal="button wide*" framecolor='$var(dimmed)' framewidth='500'/>
    </syntaxhighlight></div>
    WikiDoc:End
    """

    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.aDropDownButtons:List[cWidgetButton]   = []
        self.aCaptions:List[str]                    = []
        self.aSecondCaptions:List[str]              = []
        self.uOrgCaptions:str                       = u''
        self.aOrgActionNames:List[str]              = []
        self.aActionNames:List[str]                 = []
        self.oObjectDropDown:Union[DropDown,None]   = None
        self.oDimmer:Union[cTouchRectangle,None]    = None
        self.iFrameWidth:int                        = 0
        self.uActionNames:str                       = u''
        self.aFrameColor:List[float]                = aColorUndefined
        self.bSorted:bool                           = False
        self.oXMLNode:Union[Element,None]           = None
        self.iTmpAnchorWidth:int                    = 0
        self.iTmpAnchorHeight:int                   = 0
        self.bSetCaption:bool                       = False

    def InitWidgetFromXml(self,*,oXMLNode:Element,oParentScreenPage:cScreenPage, uAnchor:str) -> bool:

        uCaption:str = GetXMLTextAttribute(oXMLNode=oXMLNode,uTag="caption",bMandatory=False,vDefault="")
        bRet:bool    = super().InitWidgetFromXml(oXMLNode=oXMLNode,oParentScreenPage=oParentScreenPage, uAnchor=uAnchor)
        bDummy:bool

        oXMLNode.set("caption", uCaption)

        if bRet:
            self.aFrameColor        = GetColorFromHex(GetXMLTextAttribute(oXMLNode=oXMLNode,uTag=u'framecolor',bMandatory=False,vDefault=u'$var(dimmed)'))
            # uFramewidth:str         = GetXMLTextAttribute(oXMLNode=oXMLNode,uTag=u'framewidth',  bMandatory=False,vDefault=str(int((self.oDef.iDefMaxX/self.fRationX)*0.03)))
            uFramewidth:str         = GetXMLTextAttribute(oXMLNode=oXMLNode,uTag=u'framewidth',  bMandatory=False,vDefault=str(int((self.oDef.iDefMaxX/self.fRationX)*0.05)))
            self.iFrameWidth,bDummy = self.CalculateWidth(uWidth=uFramewidth,iAnchorWidth=self.iWidth)
            self.iFrameWidth        = self.iFrameWidth / self.fRationX
            self.aCaptions          = GetXMLTextAttribute(oXMLNode=oXMLNode,uTag=u'captions', bMandatory=False,vDefault=u'unknown').split(u',')
            self.aActionNames       = GetXMLTextAttribute(oXMLNode=oXMLNode,uTag=u'actions',  bMandatory=False,vDefault=u'').split(u',')
            self.aOrgActionNames    = copy(self.aActionNames)
            self.bSorted            = GetXMLBoolAttribute(oXMLNode=oXMLNode,uTag=u'sorted',   bMandatory=False,bDefault=False)
            self.bSetCaption        = GetXMLBoolAttribute(oXMLNode=oXMLNode,uTag=u'setcaption', bMandatory=False,bDefault=False)
            self.oXMLNode           = oXMLNode

            # this is a little bit tricky
            # we should parse all dropdown button here as well, but then,
            # updatewidget for the dropdown would not work
            # so we do it in create, but at that time, the dimensions of the anchor is lost
            # so, we need to save the anchor dimensions here
            self.iTmpAnchorWidth = self.oTmpAnchor.iWidth
            self.iTmpAnchorHeight = self.oTmpAnchor.iHeight
        return bRet

    def Create(self, oParent: Widget) -> bool:

        del self.aDropDownButtons[:]

        try:
            self.GetCaptions()
            if self.GetActions():
                for num in range(len(self.aCaptions)):
                    oBtn:cWidgetButton = cWidgetButton()
                    # we cant use the touchbutton object, as Buttonbehaviour not work on buttons on scolllayout
                    #oBtn.ClassName           = Button
                    oBtn.bIsDropButton        = True
                    self.oXMLNode.set("caption",self.aCaptions[num])
                    self.oXMLNode.set("type","BUTTON")
                    # self.oXMLNode.set("action", self.aActionNames[num])
                    self.oXMLNode.set("action", "NoAction")

                    if self.uAnchorName:
                        oTmpAnchor = self.oParentScreenPage.dWidgets[self.uAnchorName][0]
                        oTmpAnchor.iWidth  = self.iTmpAnchorWidth
                        oTmpAnchor.iHeight = self.iTmpAnchorHeight

                    oBtn.InitWidgetFromXml(oXMLNode=self.oXMLNode, oParentScreenPage=self.oParentScreenPage, uAnchor=self.uAnchorName)
                    # oBtn.SetCaption(self.aCaptions[num])
                    oBtn.iAnchorPosX          = 0
                    oBtn.iAnchorPosY          = 0
                    oBtn.iPosX                = 0
                    oBtn.iPosY                = 0
                    oBtn.uActionNameDoubleTap = u''
                    oBtn.uActionNameDownOnly  = u''
                    oBtn.uActionNameUpOnly    = u''
                    oBtn.uActionNameLongTap   = u''
                    oBtn.iButtonNum           = num

                    self.aDropDownButtons.append(oBtn)

            if self.oObjectDropDown is None:
                super(cWidgetDropDown, self).Create(oParent)

            if self.oObject is not None:
                self.oObjectDropDown=DropDown()
                #self.dismiss_on_select=True

                if self.bSorted:
                    self.aDropDownButtons = sorted(self.aDropDownButtons, key=lambda oDropDownButtons: ReplaceVars(oDropDownButtons.uCaption))

                for oWidget in self.aDropDownButtons:
                    oWidget.Create(oParent)
                    oWidget.oObject.size        = self.oObject.size
                    oWidget.oObject.text_size   = self.oObject.text_size

                    if oWidget.bIcon and self.bIcon:
                        oWidget.oObject.font_size = self.oObject.font_size

                    if (not oWidget.bIcon) and (not self.bIcon):
                        oWidget.oObject.font_size = self.oObject.font_size

                    oWidget.uName               = "*DROPDOWNBUTTON*"+oWidget.uName
                    oKivyBtn:Button             = oWidget.oObject
                    oWidget.oParent.remove_widget(oKivyBtn)
                    oKivyBtn.size_hint_y            = None
                    oKivyBtn.unbind(on_q_release    = oWidget.On_Button_Up)
                    oKivyBtn.bind(on_q_release      = self.DropDownSelect)
                    self.oObjectDropDown.add_widget(oKivyBtn)
                self.oObject.bind(on_q_release  = self.OpenDropDown)
                self.oObjectDropDown.bind(on_dismiss = self.CloseDropDown)
                return True
            return False
        except Exception as e:
            LogError(uMsg="Can''t create Dropdown",oException=e)
            return False

    def GetActions(self) -> bool:
        if len(self.aActionNames) == 1 and len(self.aCaptions) > 1:
            # noinspection PyUnusedLocal
            self.aActionNames = [self.aActionNames[0] for x in range(len(self.aCaptions))]

        if self.uActionNameLongTap == u"":
            self.uActionNameLongTap = "noaction"

        if len(self.aActionNames) != len(self.aCaptions) and len(self.aCaptions) > 0:
            LogError(uMsg=u'cWidgetDropDown: [%s] Captions do not match Actions: %s' % (self.uName, self.uActionName))
            return False
        else:
            return True

    def GetCaptions(self) -> None:
        aCaptions: List[str]
        uCaptions: str

        del self.aDropDownButtons[:]
        if self.uCaption.endswith("[]"):
            aCaptions           = self.uCaption.split(u':::')
            self.uCaption       = aCaptions[0]
            uCaptions           = aCaptions[1]
            self.aCaptions      = Var_GetArray(uCaptions , 1)
            self.aCaptions      = [u"$var("+item+")" for item in self.aCaptions]
        elif u':::' in self.uCaption:
            aCaptions           = self.uCaption.split(u':::')
            self.uCaption       = aCaptions[0]
            self.aCaptions      = aCaptions[1:]
            self.aActionNames   = ReplaceVars(self.uActionName).split(u':::')
            self.uActionName    = u''
            super(cWidgetButton, self).SetCaption(self.uCaption)
        else:
            if self.aCaptions[0].startswith("$DIRLIST["):
                oPath:cPath = cPath(self.aCaptions[0][9:-1])
                self.aCaptions = oPath.GetFolderList()

    # noinspection PyUnusedLocal
    def OpenDropDown(self,instance:DropDown) -> None:
        """ opens the dropdown """
        Object=self.oObjectDropDown
        Object.open(self.oObject)
        self.oDimmer=cTouchRectangle(pos=(Object.pos[0]-self.iFrameWidth,Object.pos[1]-self.iFrameWidth),width=Object.width+self.iFrameWidth*2,height=Object.height+self.iFrameWidth*2,background_color=self.aFrameColor)
        self.oParent.add_widget(self.oDimmer)

    # noinspection PyUnusedLocal
    def CloseDropDown(self,instance:DropDown) -> None:
        """ closes the dropdown """
        self.oParent.remove_widget(self.oDimmer)

    def DropDownSelect(self,instance:DropDown) -> None:
        """ selects on item of dropdown """
        #self.SetCaption(instance.text)
        self.oObjectDropDown.dismiss()
        instance.oOrcaWidget.dActionPars["DROPDOWNVALUE"] = instance.text
        instance.oOrcaWidget.dActionPars["DROPDOWNINDEX"] = str(instance.oOrcaWidget.iButtonNum)
        instance.oOrcaWidget.uActionName = self.aActionNames[instance.oOrcaWidget.iButtonNum]
        instance.uTapType="down"
        instance.oOrcaWidget.On_Button_Down(instance)
        if self.bSetCaption:
            self.SetCaption(instance.text)
        return

    def UpdateWidget(self) -> None:
        self.uCaption     = ReplaceVars(self.uOrgCaption)
        self.aActionNames = copy(self.aOrgActionNames)
        if self.oObject:
            self.Create(self.oParent)
            self.SetCaption(self.uCaption)
        return

    def UpdateWidgetSecondCaption(self) -> None:
        uCaption:str = ReplaceVars(self.uOrgSecondCaption)
        if uCaption == u'':
            return
        self.uCaption = uCaption
        if self.oObject:
            self.Create(self.oParent)
        cWidgetButton.SetCaption(self,self.uCaption)
        return

    def EnableWidget(self, *, bEnable:bool) -> bool:
        oButton:cWidgetButton
        super().EnableWidget(bEnable=bEnable)
        for oButton in self.aDropDownButtons:
            oButton.EnableWidget(bEnable=bEnable)
        return True
コード例 #12
0
def summon_popup_song(db: DBMuziek, dd: DropDown, g_id=None, g_name=None):
    dd.dismiss()
    data = {"group_id": g_id, "group_name": g_name}
    PopupSong(db, update_data=data).open()
コード例 #13
0
class TopBar(FloatLayout):

    ##
    # Class Constructor: __init__
    # ---------------------------
    # This method is called during creation of the TopBar object.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    # (Various) **kwargs                Arguments for construction of internal
    #                                                       FloatLayout object
    ##
    def __init__(self, **kwargs):
        super(TopBar, self).__init__(size_hint=(1,None),
                                     size=(1000, 60),
                                     **kwargs)
        with self.canvas.before:
            self.rect = Image(source=BKGD_LCHRC,
                        keep_ratio=False,
                        allow_stretch=True,
                        size_hint=(1,1))
        self.bind(pos=manager.update_rect, size=manager.update_rect)
        self.button_panel = None
        self.search_bar = None
        self.settings = None
        self.search_mode = None
        self.search_dropdown = None
        self.popups = Popups()
        self.mode = "Users"


    def add_logo(self):
        self.add_widget(Image(source='images/logo.jpg',
                              keep_ratio=True,
                              allow_stretch=True,
                              size_hint=(None,None),
                              size=(90,60),
                              pos_hint={'top':1,'left':1}))

    ##
    # Class Method: draw_top_bar
    # --------------------------
    # This method clears and redraws the top bar, ommiting the create new group
    # and user buttons if the logged-in user is not an admin.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def draw_top_bar(self):
        self.clear_widgets()
        self.create_button_panel()
        self.add_logo()
        if manager.ADMIN:
            self.create_add_user_button()
            self.create_add_group_button()
        self.create_search_bar()
        self.create_search_filter()
        self.create_settings_dropdown()

    ##
    # Class Method: get_search_term
    # -----------------------------
    # This method returns the text that is currently entered into the search bar.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    #
    # (str) return                      Text in searchbar
    ##
    def get_search_term(self):
        return self.search_bar.text


    ##
    # Class Method: create_button_panel
    # ---------------------------------
    # This method creates the layout for all TopBar buttons, sizing itself dependant
    # on whether the logged-in user is an admin.
    #
    # @params
    # (TopBar) self                     This instance of TopBar 
    ##
    def create_button_panel(self):
        x_size = 680
        if not manager.ADMIN:
            x_size = 410
        self.button_panel = BoxLayout(size=(x_size,60),size_hint=(None, None), pos_hint={"right":1, "top":1},
                                      orientation="horizontal", spacing=10)
        self.add_widget(self.button_panel)


    ##
    # Class Method: create_add_user_button
    # ---------------------------------
    # This method creates and adds to this instance of TopBar the "Add New User"
    # button.
    #
    # @params
    # (TopBar) self                     This instance of TopBar 
    ##
    def create_add_user_button(self):
        self.button_panel.add_widget(HoverButton(text="Add New User",
                        button_up=BTN_LCHRC[0],
                        button_down=BTN_LCHRC[1],
                        font_size=14,
                        size=(125,40),
                        size_hint=(None,None),
                        pos_hint={'center_x':.5, 'center_y':.5},
                        on_press=self.popups.open_add_user_popup))


    ##
    # Class Method: create_add_group_button
    # ---------------------------------
    # This method creates and adds to this instance of TopBar the "Add New Group"
    # button.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_add_group_button(self):
        self.button_panel.add_widget(HoverButton(text="Add New Group",
                        button_up=BTN_LCHRC[0],
                        button_down=BTN_LCHRC[1],
                        font_size=14,
                        size=(125,40),
                        size_hint=(None,None),
                        pos_hint={'center_x':.5, 'center_y':.5},
                        on_press=self.popups.open_new_group_popup))


    ##
    # Class Method: on_text
    # ---------------------
    # This method is called by the search bar any time the text within it is
    # modified. This method communicates with menu.py, instructing it to update the
    # list of displayed user/group names to ones that match the search term.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    # (TextInput) instance              The searchbar
    # (str) value                       Text in the searchbar
    ##
    def on_text(self, instance, value):
        manager.menu.show_users(value)
        manager.menu.show_groups(value)
        if 'attr' in self.search_mode.text.lower():
            manager.menu.recolor_info_panel()


    ##
    # Class Method: create_search_filter
    # ----------------------------------
    # This method creates the dropdown on the topbar which allows
    # selection of a search filter between 'name', 'attr name',
    # and 'attr value.'
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_search_filter(self):
        
        self.search_dropdown = DropDown(auto_width=False,
                                        max_height=180,
                                        on_dismiss=self.reactivate_buttons)
        filter_layout = FloatLayout(size=(80, 60))
        search_label = Label(text="Search Mode",
                             font_size=12,
                             pos_hint={'center_x':.5, 'top':1.35})
        self.search_mode = HoverButton(text="Username",
                                            font_size=12,
                                            size_hint=(None, None),
                                            size=(80,30),
                                            pos_hint={'right':1, 'center_y':.4},
                                            button_up=DD_LCHRC[0],
                                            button_down=DD_LCHRC[1],
                                            on_release=lambda instance: self.open_dropdown(instance,
                                                                                self.search_dropdown))
        self.search_mode.name_button = HoverButton(text="Username",
                                            font_size=12,
                                            button_up=DD_LCHRC[0],
                                            pos_hint={"right":1},
                                            button_down=DD_LCHRC[1],
                                            size_hint=(None,None),
                                            size=(100,30),
                                            on_release=self.switch_search_mode)
        self.search_mode.attr_button = HoverButton(text="Attr Name",
                                            font_size=12,
                                            button_up=DD_LCHRC[0],
                                            button_down=DD_LCHRC[1],
                                            size_hint=(None,None),
                                            size=(100,30),
                                            on_release=self.switch_search_mode)
        self.search_mode.val_button = HoverButton(text="Attr Value",
                                            font_size=12,
                                            button_up=DD_LCHRC[0],
                                            button_down=DD_LCHRC[1],
                                            size_hint=(None,None),
                                            size=(100,30),
                                            on_release=self.switch_search_mode)
        self.search_dropdown.add_widget(self.search_mode.name_button)
        self.search_dropdown.add_widget(self.search_mode.attr_button)
        self.search_dropdown.add_widget(self.search_mode.val_button)
        self.button_panel.add_widget(filter_layout)
        filter_layout.add_widget(self.search_mode)
        filter_layout.add_widget(search_label)

    ##
    # Class Method: get_search_mode
    # -----------------------------
    # This method returns the mode in which the searchbar is
    # filtering which users/groups are displayed.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def get_search_mode(self):
        if "attr" not in self.search_mode.text.lower():
            return "name"
        else:
            if "Name" in self.search_mode.text:
                return "attr name"
            else:
                return "attr val"

    ##
    # Class Method: switch_search_mode
    # --------------------------------
    # This method switches the search mode and displays the currently searched
    # users/groups on the tabbed menu.
    #
    # (TopBar) self                     This instance of TopBar
    # (HoverButton) instance            The button pressed to switch search modes
    ## 
    def switch_search_mode(self, instance):
        self.search_mode.text = instance.text
        self.search_dropdown.dismiss()
        if self.mode == 'Users':
            manager.menu.show_searched_users()
        else:
            manager.menu.show_searched_groups()
        manager.menu.recolor_info_panel()

    ##
    # Class Method: toggle_group_user
    # -------------------------------
    # This method toggles the topbar mode between 'Users' mode and 'Groups' mode.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    # (str) mode                        Mode to switch to. 'Users' or 'Groups'
    ##
    def toggle_group_user(self, mode):
        if not self.search_mode:
            return
        if mode == 'Users':
            self.mode = 'Users'
            self.search_mode.name_button.text = 'Username'
            if self.search_mode.text == 'Groupname':
                self.search_mode.text = 'Username'
        else:
            self.mode = 'Groups'
            self.search_mode.name_button.text = 'Groupname'
            if self.search_mode.text == 'Username':
                self.search_mode.text = 'Groupname'


    ##
    # Class Method: create_search_bar
    # -------------------------------
    # This method creates a searchbar and adds it to this instance of TopBar.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_search_bar(self):
        self.search_bar = TextInput(size_hint=(None, None),
                         size=(250, 30),
                         background_normal=SRCH_BKGD[0],
                         padding_x=[33,0],
                         background_active=SRCH_BKGD[1],
                         pos_hint={'right':.995, 'center_y':.5},
                         hint_text='Search',
                         multiline=False)

        self.search_bar.bind(text=self.on_text)
        self.button_panel.add_widget(self.search_bar)


    ##
    # Class Method: create_presets_menu_button
    # ----------------------------------------
    # This method creates a button that switches the page to the presets menu page
    # and adds the button to the settings dropdown.
    # 
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_presets_menu_button(self):

        #Used by presets menu button to transition screens
        def to_preset_manager(instance):
            manager.sm.current = "presetMenu"
            self.settings.dismiss()
            
        self.settings.add_widget(HoverButton(text="User Presets Manager",
                                                 button_up=DD_LCHRC[0],
                                                 button_down=DD_LCHRC[1],
                                                 font_size=12,
                                                 size=(180,40),
                                                 size_hint=(None,None),
                                                 pos_hint={'right':1, 'right':1},
                                                 on_press=to_preset_manager))


    ##
    # Class Method: create_upload_file_button
    # ---------------------------------------
    # This method creates a button that allows uploading a user .txt file to load
    # into the database and adds the button to the settings dropdown. 
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_upload_file_button(self):
        def to_file_chooser(instance):
            self.settings.dismiss()
            self.popups.open_file_chooser(instance)
        self.settings.add_widget(HoverButton(text="Upload User File",
                                                 button_up=DD_LCHRC[0],
                                                 button_down=DD_LCHRC[1],
                                                 font_size=12,
                                                 size=(180,40),
                                                 size_hint=(None,None),
                                                 pos_hint={'right':1, 'right':1},
                                                 on_press=to_file_chooser))

    ##
    # Class Method: create_logout_button
    # ----------------------------------
    # This method creates the logout button and adds it to the settings dropdown.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_logout_button(self):
        self.settings.add_widget(HoverButton(text="Logout",
                                                 button_up=DD_LCHRC[0],
                                                 button_down=DD_LCHRC[1],
                                                 font_size=12,
                                                 size=(180,40),
                                                 size_hint=(None,None),
                                                 pos_hint={'right':1, 'right':1},
                                                 on_press=lambda instance: manager.logout(self.settings)))

    ##
    # Class Method: create_admin_pw_button
    # ------------------------------------
    # This method creates the change admin password button and adds it to the settings dropdown.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_admin_pw_button(self):
        self.settings.add_widget(HoverButton(text="Change Admin Password",
                                                 button_up=DD_LCHRC[0],
                                                 button_down=DD_LCHRC[1],
                                                 font_size=12,
                                                 size=(180,40),
                                                 size_hint=(None,None),
                                                 pos_hint={'right':1, 'right':1},
                                                 on_press=self.popups.change_adminpw_popup))

    ##
    # Class Method: open_dropdown
    # ---------------------------
    # This method opens a dropdown and makes the group of buttons
    # underneath the dropdown (buttons on the options panel)
    # inactive.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    # (HoverButton) instance            Mainbutton of dropdown
    ##
    def open_dropdown(self, instance, dropdown):
        dropdown.open(instance)
        HoverButton.inactive_group = 'options'


    ##
    # Class Method: reactivate_buttons
    # --------------------------------
    # This method is called when the settings dropdown is dismissed, and
    # it simply reactivates the buttons below where the dropdown was.
    # (reactivates buttons on the options panel).
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    # (DropDown) instance               Dropdown which was dismissed
    ##
    def reactivate_buttons(self, instance):
        HoverButton.inactive_group = None

    ##
    # Class Method: create_settings_dropdown
    # --------------------------------------
    # This method creates the settings dropdown, and adds it to this
    # instance of topbar.
    #
    # @params
    # (TopBar) self                     This instance of TopBar
    ##
    def create_settings_dropdown(self):
        self.settings = DropDown(auto_width=False,
                                 width=180,
                                 pos_hint={"right":1},
                                 on_dismiss=self.reactivate_buttons)
        mainbutton = HoverButton(size=(60,60),size_hint=(None,None),
                             button_down=BTN_OPTS[1],
                             button_up=BTN_OPTS[0],
                             pos_hint={"center_y":.5},
                             on_release=lambda instance: self.open_dropdown(instance, self.settings))
        self.button_panel.add_widget(mainbutton)
        if manager.ADMIN:
            self.create_presets_menu_button()
            self.create_upload_file_button()
            self.create_admin_pw_button()
        self.create_logout_button()
コード例 #14
0
ファイル: tx_dialog.py プロジェクト: AXErunners/electrum-axe
class TxDialog(Factory.Popup):
    def __init__(self, app, tx):
        Factory.Popup.__init__(self)
        self.app = app
        self.wallet = self.app.wallet
        self.tx = tx
        self._action_button_fn = lambda btn: None
        self.dropdown = None

    def on_open(self):
        self.update()

    def update(self):
        raw_tx = str(self.tx)
        tx_type = tx_header_to_tx_type(bfh(raw_tx[:8]))
        if tx_type == 0:
            txid = self.tx.txid()
            tx_type, completed = self.wallet.db.get_ps_tx(txid)
        self.title = '%s %s' % (SPEC_TX_NAMES[tx_type], _('Transaction'))
        format_amount = self.app.format_amount_and_units
        tx_details = self.wallet.get_tx_info(self.tx)
        tx_mined_status = tx_details.tx_mined_status
        exp_n = tx_details.mempool_depth_bytes
        amount, fee = tx_details.amount, tx_details.fee
        self.status_str = tx_details.status
        self.description = tx_details.label
        self.can_broadcast = tx_details.can_broadcast
        self.tx_hash = tx_details.txid or ''
        islock = tx_details.islock
        timestamp = tx_mined_status.timestamp
        if not timestamp and islock:
            timestamp = islock
        if timestamp:
            self.date_label = _('Date')
            dttm = datetime.fromtimestamp(timestamp)
            self.date_str = dttm.isoformat(' ')[:-3]
        elif exp_n:
            self.date_label = _('Mempool depth')
            self.date_str = _('{} from tip').format('%.2f MB' %
                                                    (exp_n / 1000000))
        else:
            self.date_label = ''
            self.date_str = ''

        if amount is None:
            self.amount_str = _("Transaction unrelated to your wallet")
        elif amount > 0:
            self.is_mine = False
            self.amount_str = format_amount(amount)
        else:
            self.is_mine = True
            self.amount_str = format_amount(-amount)
        if fee is not None:
            self.fee_str = format_amount(fee)
            fee_per_kb = fee / self.tx.estimated_size() * 1000
            self.feerate_str = self.app.format_fee_rate(fee_per_kb)
        else:
            self.fee_str = _('unknown')
            self.feerate_str = _('unknown')
        self.can_sign = self.wallet.can_sign(self.tx)
        self.ids.output_list.update(self.tx.get_outputs_for_UI())
        self.is_local_tx = tx_mined_status.height == TX_HEIGHT_LOCAL
        self.update_action_button()

    def update_action_button(self):
        action_button = self.ids.action_button
        options = (
            ActionButtonOption(text=_('Sign'),
                               func=lambda btn: self.do_sign(),
                               enabled=self.can_sign),
            ActionButtonOption(text=_('Broadcast'),
                               func=lambda btn: self.do_broadcast(),
                               enabled=self.can_broadcast),
            ActionButtonOption(text=_('Remove'),
                               func=lambda btn: self.remove_local_tx(),
                               enabled=self.is_local_tx),
        )
        num_options = sum(map(lambda o: bool(o.enabled), options))
        # if no options available, hide button
        if num_options == 0:
            action_button.disabled = True
            action_button.opacity = 0
            return
        action_button.disabled = False
        action_button.opacity = 1

        if num_options == 1:
            # only one option, button will correspond to that
            for option in options:
                if option.enabled:
                    action_button.text = option.text
                    self._action_button_fn = option.func
        else:
            # multiple options. button opens dropdown which has one sub-button for each
            self.dropdown = DropDown()
            action_button.text = _('Options')
            self._action_button_fn = self.dropdown.open
            for option in options:
                if option.enabled:
                    btn = Button(text=option.text,
                                 size_hint_y=None,
                                 height='48dp')
                    btn.bind(on_release=option.func)
                    self.dropdown.add_widget(btn)

    def on_action_button_clicked(self):
        action_button = self.ids.action_button
        self._action_button_fn(action_button)

    def do_sign(self):
        if self.dropdown:
            self.dropdown.dismiss()
        self.app.protected(
            _("Enter your PIN code in order to sign this transaction"),
            self._do_sign, ())

    def _do_sign(self, password):
        self.status_str = _('Signing') + '...'
        Clock.schedule_once(lambda dt: self.__do_sign(password), 0.1)

    def __do_sign(self, password):
        try:
            self.app.wallet.sign_transaction(self.tx, password)
        except InvalidPassword:
            self.app.show_error(_("Invalid PIN"))
        self.update()

    def do_broadcast(self):
        if self.dropdown:
            self.dropdown.dismiss()
        self.app.broadcast(self.tx)

    def show_qr(self):
        from electrum_axe.bitcoin import base_encode, bfh
        raw_tx = str(self.tx)
        text = bfh(raw_tx)
        text = base_encode(text, base=43)
        self.app.qr_dialog(_("Raw Transaction"),
                           text,
                           text_for_clipboard=raw_tx)

    def remove_local_tx(self):
        if self.dropdown:
            self.dropdown.dismiss()
        txid = self.tx.txid()
        to_delete = {txid}
        to_delete |= self.wallet.get_depending_transactions(txid)
        question = _("Are you sure you want to remove this transaction?")
        if len(to_delete) > 1:
            question = (_(
                "Are you sure you want to remove this transaction and {} child transactions?"
            ).format(len(to_delete) - 1))

        def on_prompt(b):
            if b:
                for tx in to_delete:
                    self.wallet.remove_transaction(tx)
                self.wallet.storage.write()
                self.app._trigger_update_wallet()  # FIXME private...
                self.dismiss()

        d = Question(question, on_prompt)
        d.open()
コード例 #15
0
class MainLayout(Widget):
    btn_toggle_airports = ObjectProperty(
        None
    )  # Hold a reference to the "Show Airports" button after the graphics are rendered.
    btn_toggle_airplanes = ObjectProperty(
        None
    )  # Hold a reference to the "Show Airplanes" button after the graphics are rendered.
    locations_map = ObjectProperty(
        None)  # Hold a reference to the map after the graphics are rendered.
    airports_search_bar = ObjectProperty(
        None
    )  # Hold a reference to the airports search bar after the graphics are rendered.
    airplanes_search_bar = ObjectProperty(
        None
    )  # Hold a reference to the airplanes search bar after the graphics are rendered.
    settings_panel = ObjectProperty(
        None
    )  # Hold a reference to the settings panel after the graphics are rendered.

    def __init__(self):
        super(MainLayout, self).__init__()
        self.suggestions_dropdown = DropDown(
        )  # Declare and initialize the suggestions drop-down object for both search bars.
        self.app = MDApp.get_running_app(
        )  # Hold a reference to the main class which inherits from App to jump-start the app.

    def toggle_airports(self):
        """
        Allows to application to add the airports found within the field of view.
        :return: None
        """
        if self.locations_map.show_airports:
            self.locations_map.show_airports = False
        else:
            if self.locations_map.zoom > 5:
                self.locations_map.show_airports = True
                self.locations_map.start_getting_locations_in_fov()
            else:
                self.btn_toggle_airports.state = 'normal'
                show_message_popup("Zoom level must be greater than 5.")

    def toggle_airplanes(self):
        """
        Allows the application to add the airplanes found within the field of view.
        :return: None
        """
        if self.locations_map.show_airplanes:
            self.locations_map.show_airplanes = False
        else:
            if self.locations_map.zoom > 5:
                self.locations_map.show_airplanes = True
                self.locations_map.start_getting_locations_in_fov()
            else:
                self.btn_toggle_airplanes.state = 'normal'
                show_message_popup("Zoom level must be greater than 5.")

    def get_airport_suggestions(self):
        """
        Renders the airports suggestions as options within a drop-down menu
        based on the text given by the user within the airports search bar.
        :return: None
        """
        if not self.airports_search_bar.focus:  # If the function gets called after the user has chosen option,
            self.suggestions_dropdown.dismiss()  # hide drop-down.
            return
        else:  # else, if the function is called to select option,
            self.suggestions_dropdown.dismiss()  # hide previous drop-down.

        self.suggestions_dropdown = DropDown()

        airports_data = self.app.data_manager.airports_tree_manager.get_in_order_list(
            self.app.data_manager.airports_tree,
            self.airports_search_bar.text.upper())

        airport_id_index = self.app.data_manager.airports_tree_manager.index

        if airports_data is None:
            btn_suggestion = Button(text='NOT FOUND',
                                    size_hint_y=None,
                                    height=44)
            self.suggestions_dropdown.add_widget(btn_suggestion)
        else:
            for airport_data in airports_data:
                btn_suggestion = DataButton(
                    data=airport_data,
                    text=airport_data[airport_id_index],
                    size_hint_y=None,
                    height=44)
                btn_suggestion.bind(on_release=lambda btn_suggestion_ref: self.
                                    focus_on_airport(btn_suggestion_ref))
                self.suggestions_dropdown.add_widget(btn_suggestion)

        self.suggestions_dropdown.bind(
            on_select=lambda instance, btn_suggestion_ref: setattr(
                self.airports_search_bar, 'text', btn_suggestion_ref))
        self.suggestions_dropdown.open(self.airports_search_bar)
        self.airports_search_bar.bind(
            on_parent=self.suggestions_dropdown.dismiss)

    def focus_on_airport(self, btn_suggestion):
        """
        Focuses the map's current field of view on the chosen airport.
        :param btn_suggestion: The button carrying the airport's information.
        :return: None
        """
        self.locations_map.remove_airports()
        self.locations_map.remove_airplanes()
        self.suggestions_dropdown.select(btn_suggestion.text)
        self.locations_map.zoom = 10
        self.locations_map.center_on(btn_suggestion.data[15],
                                     btn_suggestion.data[16])
        self.airports_search_bar.focus = False
        self.locations_map.focus_on_airport = True
        self.locations_map.focus_on_airplane = True
        #self.locations_map.add_airport(btn_suggestion.data)
        Thread(target=self.app.data_manager.get_potential_collisions,
               args=(
                   self.app.data_manager.collision_forecaster.
                   get_potential_collisions_from_airport,
                   (btn_suggestion.data[15], btn_suggestion.data[16]),
               )).start()

        self.locations_map.get_locations_in_fov(airport_focus=True,
                                                airplane_focus=True)

    def get_airplane_suggestions(self):
        """
        Renders the airplanes suggestions as options within a drop-down menu
        based on the text given by the user within the airplanes search bar.
        :return: None
        """
        if not self.airplanes_search_bar.focus:  # If the function gets called after the user has chosen option,
            self.suggestions_dropdown.dismiss()  # hide drop-down.
            return
        else:  # else, if the function is called to select option,
            self.suggestions_dropdown.dismiss()  # hide previous drop-down.

        self.suggestions_dropdown = DropDown()

        airplanes_data = self.app.data_manager.airplanes_tree_manager.get_in_order_list(
            self.app.data_manager.airplanes_tree,
            self.airplanes_search_bar.text.upper())

        airplane_id_index = self.app.data_manager.airplanes_tree_manager.index

        if airplanes_data is None:
            btn_suggestion = Button(text='NOT FOUND',
                                    size_hint_y=None,
                                    height=44)
            self.suggestions_dropdown.add_widget(btn_suggestion)
        else:
            for airplane_data in airplanes_data:
                btn_suggestion = DataButton(
                    data=airplane_data,
                    text=airplane_data[airplane_id_index],
                    size_hint_y=None,
                    height=44)
                btn_suggestion.bind(on_release=lambda btn_suggestion_ref: self.
                                    focus_on_airplane(btn_suggestion_ref))
                self.suggestions_dropdown.add_widget(btn_suggestion)

        self.suggestions_dropdown.bind(
            on_select=lambda instance, btn_suggestion_ref: setattr(
                self.airplanes_search_bar, 'text', btn_suggestion_ref))
        self.suggestions_dropdown.open(self.airplanes_search_bar)
        self.airplanes_search_bar.bind(
            on_parent=self.suggestions_dropdown.dismiss)

    def focus_on_airplane(self, btn_suggestion):
        """
        Focuses the map's current field of view on the chosen airplane.
        :param btn_suggestion: The button carrying the airplane's information.
        :return: None
        """
        self.locations_map.remove_airports()
        self.locations_map.remove_airplanes()
        self.suggestions_dropdown.select(btn_suggestion.text)
        self.locations_map.zoom = 10
        self.locations_map.center_on(btn_suggestion.data[6],
                                     btn_suggestion.data[7])
        self.airports_search_bar.focus = False
        self.locations_map.focus_on_airplane = True
        self.locations_map.focus_on_airport = True
        #self.locations_map.add_airplane(btn_suggestion.data)
        Thread(target=self.app.data_manager.get_potential_collisions,
               args=(
                   self.app.data_manager.collision_forecaster.
                   get_potential_collisions_from_plane,
                   btn_suggestion.data[0],
               )).start()
        self.locations_map.get_locations_in_fov(airplane_focus=True,
                                                airport_focus=True)

    @staticmethod
    def open_settings_window():
        """
        Opens the settings window.
        :return: None
        """
        settings_window = ModalView(size_hint=(0.5, 0.5), auto_dismiss=False)
        settings_window.add_widget(SettingsView(settings_window))
        settings_window.open()

    def close_app(self):
        """
        Cleans the airplanes database information, deletes the rotated airplanes images and closes the application.
        :return: None
        """
        BASE_DIR = os.path.dirname(os.path.abspath(__file__))

        db_path = os.path.join(BASE_DIR, "..", "DATA",
                               "AIRCRAFT_COLLISION_FORECAST_SYSTEM.db")
        clean_table(db_path, 'AIRPLANES')

        BASE_DIR = os.path.dirname(os.path.abspath(__file__))

        img_path = os.path.join(BASE_DIR, "..", "GUI", "IMAGE")

        # img_path = 'GUI\\IMAGE\\'
        img_file_names = [
            file_name for file_name in listdir(img_path)
            if isfile(join(img_path, file_name))
        ]
        for file_name in img_file_names:
            if file_name not in ('map_marker.png', 'airplane_marker.png',
                                 'collision_marker.png'):
                os.remove(os.path.join(img_path, file_name))
        print('Closing app')
        self.app.root_window.close()
コード例 #16
0
class EventHandlerTextInput(TextInput):
    '''EventHandlerTextInput is used to display/change/remove EventHandler
       for an event
    '''

    eventwidget = ObjectProperty(None)
    '''Current selected widget
       :data:`eventwidget` is a :class:`~kivy.properties.ObjectProperty`
    '''

    eventname = StringProperty(None)
    '''Name of current event
       :data:`eventname` is a :class:`~kivy.properties.ObjectProperty`
    '''

    kv_code_input = ObjectProperty()
    '''Reference to KVLangArea
       :data:`kv_code_input` is a :class:`~kivy.properties.ObjectProperty`
    '''

    text_inserted = BooleanProperty(None)
    '''Specifies whether text has been inserted or not
       :data:`text_inserted` is a :class:`~kivy.properties.ObjectProperty`
    '''

    info_message = StringProperty(None)
    '''Message to be displayed by InfoBubble
       :data:`info_message` is a :class:`~kivy.properties.StringProperty`
    '''

    dropdown = ObjectProperty(None)
    '''DropDown which will be displayed to show possible
       functions for that event
       :data:`dropdown` is a :class:`~kivy.properties.ObjectProperty`
    '''

    def on_touch_down(self, touch):
        '''Default handler for 'on_touch_down' event
        '''
        if self.collide_point(*touch.pos):
            self.info_bubble = InfoBubble(message=self.info_message)
            bubble_pos = list(self.to_window(*self.pos))
            bubble_pos[1] += self.height
            self.info_bubble.show(bubble_pos, 1.5)

        return super(EventHandlerTextInput, self).on_touch_down(touch)

    def show_drop_down_for_widget(self, widget):
        '''Show all functions for a widget in a Dropdown.
        '''
        self.dropdown = DropDown()
        list_funcs = dir(widget)
        for func in list_funcs:
            if '__' not in func and hasattr(getattr(widget, func), '__call__'):
                btn = Button(text=func, size_hint=(None, None),
                             size=(100, 30), shorten=True)
                self.dropdown.add_widget(btn)
                btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
                btn.text_size = [btn.size[0] - 4, btn.size[1]]
                btn.valign = 'middle'

        self.dropdown.open(self)
        self.dropdown.pos = (self.x, self.y)
        self.dropdown.bind(on_select=self._dropdown_select)

    def _dropdown_select(self, instance, value):
        '''Event handler for 'on_select' event of self.dropdown
        '''
        self.text += value

    def on_text(self, instance, value):
        '''Default event handler for 'on_text'
        '''
        if not self.kv_code_input:
            return

        d = get_designer()
        playground = d.ui_creator.playground
        self.kv_code_input.set_event_handler(self.eventwidget,
                                             self.eventname,
                                             self.text)
        if self.text and self.text[-1] == '.':
            if self.text == 'self.':
                self.show_drop_down_for_widget(self.eventwidget)
            ## TODO recursively call eventwidget.parent to get the root widget
            elif self.text == 'root.':
                self.show_drop_down_for_widget(playground.root)

            else:
                _id = self.text.replace('.', '')
                root = playground.root
                widget = None

                if _id in root.ids:
                    widget = root.ids[_id]

                if widget:
                    self.show_drop_down_for_widget(widget)

        elif self.dropdown:
            self.dropdown.dismiss()
コード例 #17
0
class ClassSummary(CustomBoxLayout):
    def __init__(self, *args, **kwargs):
        super(ClassSummary, self).__init__(*args, **kwargs)

        # The first item in this panel should be a dropdown containing
        # all of the contours in the current image.
        self.contour_select_dropdown = DropDown()
        self.contour_select_dropdown.auto_dismiss = False

        self.editor_box = CustomBoxLayout(orientation='vertical',
                                          padding=[8, 8, 8, 8],
                                          spacing=5)

        self.class_select_dropdown = DropDown()
        self.class_select_dropdown.auto_dismiss = False

        self.class_select_button = Button(text='Select Class',
                                          size_hint_y=None,
                                          height=30)

        self.class_select_button.bind(on_press=self._class_select_pressed)

        self.name_input = TextInput(text='Item Name',
                                    multiline=False,
                                    size_hint_y=None,
                                    height=30)
        self.comment_input = TextInput(text='Comments',
                                       multiline=True,
                                       size_hint_y=None,
                                       height=120)

        self.name_input.bind(text=self._name_text_changed)
        self.comment_input.bind(text=self._comment_text_changed)

        self.editor_box.add_widget(self.class_select_button)
        self.editor_box.add_widget(self.name_input)
        self.editor_box.add_widget(self.comment_input)

        self.dropdown_activator = DropDownContourItem(
            class_color=hex_color('#000000'), index=-1, class_name='none')

        self.dropdown_activator.bind(on_press=self._activator_pressed)

        self.add_widget(self.dropdown_activator)
        self.add_widget(self.editor_box)

        self.dropdown_open = False
        self.current_entry = None
        self.dataset = None
        self.contours = []
        self.contour_dropdown_items = []
        self.current_contour = None
        self.class_names = []
        self.class_buttons = []

    def _name_text_changed(self, inst, val):
        self.current_contour['name'] = val

    def _comment_text_changed(self, inst, val):
        self.current_contour['comment'] = val

    def writeChangesToMemory(self):
        if self.current_entry is None:
            raise Exception("Nothing is currently being edited.")

        entry = self.dataset.meta_structure['entries'][self.current_key]
        for idx, contour in enumerate(self.contours):
            entry[idx]['class_idx'] = contour['class_idx']
            entry[idx]['name'] = contour['name']
            entry[idx]['comment'] = contour['comment']

    def clearCurrentEntry(self):
        if self.current_entry is not None:
            for item in self.contour_dropdown_items:
                self.contour_select_dropdown.remove_widget(item)

        self.contours = []
        self.contour_dropdown_items = []

    def addContour(self, contour):
        item_class_idx = contour['class_idx']
        item_class_color = self.dataset.meta_structure['classes'][
            item_class_idx]['color']
        item_class_name = self.dataset.meta_structure['classes'][
            item_class_idx]['name']

        proper_name = item_class_name
        if contour['name'] != '':
            if not contour['name'].isspace():
                proper_name = self.current_contour['name']

        dropdown_item = DropDownContourItem(class_color=item_class_color,
                                            index=item_class_idx,
                                            class_name=proper_name)
        self.contour_select_dropdown.add_widget(dropdown_item)
        dropdown_item.bind(on_press=self._item_selected)

        self.contours.append(contour)
        self.contour_dropdown_items.append(dropdown_item)

    def setCurrentContour(self, contour):
        self.current_contour = contour
        item_class_idx = contour['class_idx']
        item_class_color = self.dataset.meta_structure['classes'][
            item_class_idx]['color']
        item_class_name = self.dataset.meta_structure['classes'][
            item_class_idx]['name']

        proper_name = item_class_name
        if self.current_contour['name'] != '':
            if not self.current_contour['name'].isspace():
                proper_name = self.current_contour['name']

        self.dropdown_activator.setProperties(item_class_color, item_class_idx,
                                              proper_name)

        self.name_input.text = contour['name']
        self.comment_input.text = contour['comment']
        self.class_select_button.text = item_class_name

        self.contour_select_dropdown.dismiss()
        self.dropdown_open = False

    def populateClassDropdown(self):
        for button in self.class_buttons:
            self.class_select_dropdown.remove_widget(button)

        self.class_names = []
        self.class_buttons = []
        for _class in self.dataset.meta_structure['classes']:
            self.class_names.append(_class['name'])
            button = Button(text=_class['name'], size_hint_y=None, height=30)
            self.class_buttons.append(button)
            self.class_select_dropdown.add_widget(button)
            button.bind(on_press=self._class_selected)

    def setCurrentEntry(self, key, dataset):
        if self.current_entry is not None:
            self.clearCurrentEntry()

        self.dataset = dataset
        self.current_entry = self.dataset.meta_structure['entries'][key]
        self.current_key = key

        self.populateClassDropdown()

        # Add each of these to the internal structure, and therefore the
        # image display.
        for contour in self.current_entry:
            self.addContour(contour)

        if len(self.current_entry) > 0:
            self.setCurrentContour(self.current_entry[0])

    def _activator_pressed(self, inst):
        if not self.dropdown_open:
            self.contour_select_dropdown.open(inst)
            self.dropdown_open = True
        else:
            self.dropdown_open = False
            self.contour_select_dropdown.dismiss()

    def _class_select_pressed(self, inst):
        self.class_select_dropdown.open(inst)

    def _class_selected(self, inst):
        self.class_select_button.text = inst.text
        self.current_contour['class_idx'] = self.class_names.index(inst.text)
        self.class_select_dropdown.dismiss()

        # We need to change the item in the dropdown list of contours to match.
        class_idx = self.class_names.index(inst.text)
        contour_idx = self.contours.index(self.current_contour)
        item_class_color = self.dataset.meta_structure['classes'][class_idx][
            'color']
        item_class_name = self.dataset.meta_structure['classes'][class_idx][
            'name']

        proper_name = item_class_name
        if self.current_contour['name'] != '':
            if not self.current_contour['name'].isspace():
                proper_name = self.current_contour['name']

        self.contour_dropdown_items[contour_idx].setProperties(
            item_class_color, self.class_names.index(inst.text), proper_name)

        self.dropdown_activator.setProperties(
            item_class_color, self.class_names.index(inst.text), proper_name)

        self.parent.display.image_display.setContourColor(
            contour_idx, item_class_color)

    def _item_selected(self, inst):
        idx = self.contour_dropdown_items.index(inst)
        contour = self.contours[idx]

        self.setCurrentContour(contour)
コード例 #18
0
class Chooser(
        TextInput, ):
    """
    TextInput with DropDown for 'suggestions' feature
    https://stackoverflow.com/questions/59779143/is-there-a-way-to-have-a-textinput-box-that-searches-automatically-searches-a-li
    """

    suggestions = ListProperty([])

    def __init__(self, **kwargs):
        self.suggestions = kwargs.pop('suggestions', [])  # list of suggestions
        super(Chooser, self).__init__(**kwargs)
        self.text_validate_unfocus = False
        self.multiline = False
        self.halign = 'left'
        # self.bind(choicesfile=self.load_choices)
        self.bind(text=self.on_text)
        # self.load_choices()
        self.dropdown = None

    def on_touch_down(self, touch):
        super(Chooser, self).on_touch_down(touch)

    def open_dropdown(self, *args):
        if self.dropdown:
            self.dropdown.open(self)

    def load_choices(self, entry_name_part):
        self.suggestions.clear()
        for i in db.read_entries_by_name_part(
                int(main.EntriesScreen.current_list_id), entry_name_part):
            self.suggestions.append(i)
        self.suggestions.reverse(
        )  # the first entry hast to be under TextInput - its the last position in suggestions

    def on_text(self, chooser, text):
        if self.dropdown:
            self.dropdown.dismiss()
            self.dropdown = None
        if text == '':
            return
        self.load_choices(text)

        if len(self.suggestions) > 0:
            if len(self.text) < len(self.suggestions[0]):
                self.suggestion_text = self.suggestions[0][len(self.text):]
            else:
                self.suggestion_text = ' '  # setting suggestion_text to '' screws everything
            self.dropdown = DropDown()
            for val in self.suggestions:
                self.dropdown.add_widget(
                    Button(text=str(val[0]),
                           size_hint_y=None,
                           height="60dp",
                           on_release=self.do_choose))
            self.dropdown.open(self)

    def do_choose(self, btn_obj):
        self.text = ''
        self.parent.parent.parent.do_choose_text_input(btn_obj.text)
        self.focused = True
        # TODO press enter here

        if self.dropdown:
            self.dropdown.dismiss()
            self.dropdown = None
コード例 #19
0
class SecondaryWindow(Screen):
    def __init__(self, **kwargs):
        # GUI from top to bottom, left to right
        super(SecondaryWindow, self).__init__(**kwargs)

        self.scroll = ScrollView(size_hint=(1, None),
                                 size=(Window.width, Window.height))
        self.scroll_btn = None

        self.scroll_grid = GridLayout(cols=2, spacing=1, size_hint_y=None)
        self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height'))

        with self.canvas:
            Color(0.2, 0.2, 0.28)
            Rectangle(size=(Window.width**2, Window.height**2))

        self.btn_live_orders = Button(size_hint_y=None,
                                      height=40,
                                      text="< Current Orders",
                                      background_color=[0.45, 0.45, 0.45, 3],
                                      on_release=self.changeWindow)
        self.scroll_grid.add_widget(self.btn_live_orders)

        self.btn_menu = Button(size_hint_y=None,
                               height=40,
                               text="Menu >",
                               background_color=[0.45, 0.45, 0.45, 3],
                               on_release=self.changeWindow)
        self.scroll_grid.add_widget(self.btn_menu)

        self.drp_date = DropDown()
        self.drp_date_check = str(datetime.date.today())
        self.drp_date_btn = Button(size_hint_y=None,
                                   height=40,
                                   text=f"{self.drp_date_check}",
                                   background_color=[0.45, 0.45, 0.45, 3],
                                   on_release=self.drp_date.open)
        self.drp_date_btn_dates = None

        self.scroll_grid.add_widget(self.drp_date_btn)

        self.popup = Popup(title='Title',
                           title_align='center',
                           content=Label(text='Text',
                                         size=(400, 400),
                                         text_size=[380, 380],
                                         halign='center',
                                         valign='center'),
                           size_hint=(None, None),
                           size=(400, 400))
        self.popup_db_list = []
        self.dropDown()

    def dropDown(self):  # Always called with __init__
        for i in range(len(screen_main.order_database_dates)):
            self.drp_date_btn_dates = Button(
                text=f"{screen_main.order_database_dates[i]}",
                size_hint_y=None,
                height=44,
                background_color=[0.45, 0.45, 0.45, 3],
                on_release=self.checkDate)
            self.drp_date.add_widget(self.drp_date_btn_dates)

    def checkDate(self, instance):
        self.drp_date_check = instance.text
        self.generateOrders()
        self.drp_date.dismiss()

    def changeWindow(self, instance):
        if 'Menu' in instance.text:
            sm.current = 'main'
            sm.transition.direction = 'left'
            self.reset()
        elif 'Orders' in instance.text:
            sm.current = 'tertiary'
            sm.transition.direction = 'right'
            self.reset()

    def reset(self):
        self.scroll_grid.clear_widgets()
        self.scroll_grid.add_widget(self.btn_live_orders)
        self.scroll_grid.add_widget(self.btn_menu)
        self.scroll_grid.add_widget(self.drp_date_btn)
        self.popup_db_list.clear()

    def popupItem(self, instance):
        num = int(instance.text.split('Order #')[-1])

        self.popup.content.text = f"{self.popup_db_list[num - 1]}"
        self.popup.title = f"Order #{num}"

        self.popup.open()

    def generateOrders(self, instance=None, text=None):
        self.reset()
        self.drp_date_btn.text = f"{self.drp_date_check}"
        count = 0

        for i in range(len(screen_main.order_database)):
            if self.drp_date_check == screen_main.order_database[i][:10]:
                self.scroll_btn = Button(text=f"Order #{(i + 1) - count}",
                                         size_hint_y=None,
                                         height=40,
                                         background_color=[1.8, 0.8, 0, 3],
                                         on_release=self.popupItem)
                self.scroll_grid.add_widget(self.scroll_btn)
                self.popup_db_list.append(screen_main.order_database[i])
            else:
                count += 1

        if len(self.scroll.children) == 0:
            self.scroll.add_widget(self.scroll_grid)
            self.add_widget(self.scroll)
コード例 #20
0
ファイル: main.py プロジェクト: scattenlaeufer/pybaccm
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()
コード例 #21
0
class DropDownButton(Button):
    """
    Base class for dropdown containing buttons.

    Assumes dropdown container doesn't contain *boxes* with buttons,
    and that all buttons result in dropdown being closed.
    """
    def __init__(self, container_buttons_height_ratio=2., **kwargs):
        super(DropDownButton, self).__init__(**kwargs)
        self.container_buttons_height_ratio = container_buttons_height_ratio
        self.dropdown = DropDown()
        self.add_dropdown_contents()
        self.add_widget(self.dropdown)
        self.bind(on_release=self.dropdown.open)
        self.set_initial_dropdown_selection()
        self.dropdown.dismiss()

    def container_child_height(self):
        return self.container_buttons_height_ratio * self.height

    @property
    def container_children(self):
        return self.dropdown.container.children

    @property
    def first_button(self):
        return self.container_children[-1]

    def on_release(self, *args):
        super(DropDownButton, self).on_release(*args)
        for btn in self.container_children:
            btn.height = self.container_child_height()

    @staticmethod
    def content_button():
        """
        Returns instance of Button after applying specific params.

        :return: (Button instance)
        """
        return Button(size_hint_y=None,)

    def bind_to_on_release_and_add_container(self, btn):
        btn.bind(on_release=self.apply_on_release_effects)
        btn.bind(on_release=self.dropdown.dismiss)
        self.dropdown.add_widget(btn)

    # Abstract
    def add_dropdown_contents(self, *args):
        raise NotImplementedError

    # Abstract
    def apply_on_release_effects(self, btn):
        """
        Applies all `on_release` effects of a dropdown child
        excluding `dismiss`.

        :param btn: button instance
        :return: (None)
        """
        raise NotImplementedError

    # Abstract
    def set_initial_dropdown_selection(self):
        raise NotImplementedError
コード例 #22
0
ファイル: editablelabel.py プロジェクト: davisgomes/FRAG
class EditableLabel(Label):
    
    ##
    # Class Method: toggle_edit
    # ----------------------------
    # This method removes the edit button and adds the confirm button once
    # the edit button is pressed and sets self.edit to true thus trigerring
    # the text box to be created.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers the function call
    ## 
    def toggle_edit(self, instance):
        self.remove_widget(self.edit_button)
        self.edit = True
        self.add_widget(self.confirm_button)

    ##
    # Class Method: move_buttons
    # ----------------------------
    # This method moves the buttons in accordance to the widgets height
    # and width on a change in position of the whole label.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (EditableLabel) instance          This is the same instance of EditableLabel
    # (List) value                      This is the list of the x and y size of the EditableLabel
    ## 
    def move_buttons(self, instance, value):
        self.edit_button.pos = (self.x + self.width, self.y)
        self.confirm_button.pos = (self.x + self.width, self.y)
        self.delete_button.pos = (self.x + self.width + 30, self.y)
        self.clear_button.pos = (self.x + self.width - 30, self.y)
        self.drop_button.pos= (self.x - 60, self.y)
        self.category_display.pos = (self.x - 60, self.y)
        
    ##
    # Class Method: validate_button
    # ----------------------------
    # This method is a wrapper function for the on_text_vaidate function.
    # This is called when the confirm button is pressed.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button that cause this function to be called
    ## 
    def validate_button(self, instance):
        self.on_text_validate(self)

    ##
    # Class Method: determine_category
    # ----------------------------
    # This method adds group to the category section if the editable label
    # is being used for a group. i.e. radcheck ----> radgroupcheck
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (string) instance                 This is the original category string to be edited
    ## 
    def determine_category(self, category):
        index = 3
        if self.group:
            return category[:index] + "group" + category[index:]
        else:
            return category

    ##
    # Class Constructor: __init__ 
    # ---------------------------
    # This method is called during creation of the EditableLabel class.
    # This function initializes all of the buttons and labels used in the creation
    # of the editable label class. This function also sets all of the class variables
    # to their original status
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (bool) editable                   Whether the label should be treated as editable
    # (string) attr_category            The category in which the label should be placed
    # (bool) group                      This decides whether or noit the label is part of a group attribute
    # (Various) **kwargs                various arguments for the internal Label
    ##
    def __init__(self, editable = True, attr_category = "radreply", group = False, **kwargs):
        super(EditableLabel, self).__init__(**kwargs)
        self.editable = editable
        self.group = group
        self.error_present = False
        self.current_attr = None
        self.attr_category = attr_category
        if self.text:
            attr_values = database.split_attributes(self.text)
            self.current_attr = Attribute(attr_values[0], attr_values[1], attr_values[2], self.attr_category)
        self.edit_button = HoverButton(button_up=BTN_EDIT[0],
                                      button_down=BTN_EDIT[1],
                                      size_hint=(None,None),
                                      size=(30,30),
                                      pos_hint={"center_y":.5},
                                      pos=(self.x + self.width, self.y),
                                      on_release=self.toggle_edit)
        self.confirm_button = HoverButton(button_up=BTN_CONFIRM[0],
                                      button_down=BTN_CONFIRM[1],
                                      size_hint=(None,None),
                                      size=(30,30),
                                      pos_hint={"center_y":.5},
                                      pos=(self.x + self.width, self.y),
                                      on_release=self.validate_button)
        self.delete_button = HoverButton(button_up=BTN_DELET[0],
                                      button_down=BTN_DELET[1],
                                      size_hint=(None,None),
                                      size=(30,30),
                                      pos_hint={"center_y":.5},
                                      pos=(self.x + self.width + 30, self.y),
                                      on_release=self.prompt_delete)
        self.clear_button = Button(text="x", size=(30, 30),
                                      background_normal=BTN_TRANSP[0],
                                      background_down=BTN_TRANSP[0],
                                      color=(150.0/255, 150.0/255, 150.0/255, 1),
                                      font_size=20,
                                      pos=(self.x + self.width - 30, self.y),
                                      on_press=self.clear_label)
        self.text_input = TextInput(text=self.text,
                                      size=self.size,
                                      size_hint=(None, None),
                                      font_size=self.font_size,
                                      font_name=self.font_name,
                                      pos=self.pos,
                                      multiline=False)
        self.dropdown = DropDown(auto_width=False,
                                      width=60,
                                      pos=(self.x - 60, self.y))
        category = "R"
        if self.attr_category == "radcheck":
            category = "C"
        if self.group:
            self.attr_category = self.determine_category(self.attr_category)
            
        self.drop_button = HoverButton(text=category,
                                      size=(60,30),
                                      size_hint=(None,None),
                                      button_up=DD_LCHRC[0],
                                      button_down=DD_LCHRC[1],
                                      font_size=12,
                                      pos=(self.x - 60, self.y),
                                      on_release=self.dropdown.open)
        self.rr_button = HoverButton(text="Reply",
                                      button_up=DD_DCHRC[0],
                                      button_down=DD_DCHRC[1],
                                      font_size=12,
                                      size=(60,30),
                                      size_hint=(None,None),
                                      on_press=self.select_rr)
        self.rc_button = HoverButton(text="Check",
                                      button_up=DD_DCHRC[0],
                                      button_down=DD_DCHRC[1],
                                      font_size=12,
                                      size=(60,30),
                                      size_hint=(None,None),
                                      on_press=self.select_rc)
        self.category_display = HoverButton(text=category,
                                      button_up=BKGD_CHRC,
                                      button_down=BKGD_CHRC,
                                      font_size=12,
                                      size=(60,30),
                                      pos=(self.x - 60, self.y),
                                      size_hint=(None,None))
        
        self.dropdown.add_widget(self.rr_button)
        self.dropdown.add_widget(self.rc_button)
                      
        self.bind(pos=self.text_input.setter('pos'), size=self.text_input.setter('size'))
        self.bind(pos=self.move_buttons)
        self.text_input.bind(on_text_validate=self.on_text_validate)
        if self.editable:
            self.add_widget(self.edit_button)
            self.add_widget(self.delete_button)
        self.add_widget(self.category_display)

        
    edit = BooleanProperty(False)
    textinput = ObjectProperty(None, allownone=True)

    ##
    # Class Method: select_rr
    # ----------------------------
    # This method selects the rad reply option from the dropdown
    # and sets the main button label with an 'R'. The attr category
    # is updated as well.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers this function call
    ## 
    def select_rr(self, instance):
        self.drop_button.text="R"
        self.attr_category = self.determine_category("radreply")
        self.category_display.text = "R"
        self.dropdown.dismiss()

    ##
    # Class Method: select_rc
    # ----------------------------
    # This method selects the rad check option from the dropdown
    # and sets the main button label with an 'C'. The attr category
    # is updated as well.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers this function call
    ## 
    def select_rc(self, instance):
        self.drop_button.text = "C"
        self.attr_category = self.determine_category("radcheck")
        self.category_display.text = "C"
        self.dropdown.dismiss()

    ##
    # Class Method: on_edit
    # ----------------------------
    # This method is triggered by an internal call. if self.edit is True, the text
    # box will appear for the end user to edit the label. In the case that self.edit
    # becomes False, the text box will be removed.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers this function call
    # (bool) value                      This is the value of self.edit
    ##
    def on_edit(self, instance, value):
        if not value:
            if self.text_input:
                self.remove_widget(self.text_input)
            return
        self.remove_widget(self.category_display)
        self.add_widget(self.text_input)
        self.add_widget(self.clear_button)
        self.add_widget(self.drop_button)

    ##
    # Class Method: clear_label
    # ----------------------------
    # This method sets the text of all the labels to nothing.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers this function call
    ##
    def clear_label(self, instance):
        self.text = ''
        self.text_input.text = ''

    ##
    # Class Method: clear_label
    # ----------------------------
    # This method creates a popup confirming whether or not the user
    # wants to delete an attribute as a backup check.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers this function call
    ##
    def prompt_delete(self, instance):
        self.pop_layout = FloatLayout(size=(Window.width, 200))
        self.del_popup = Popup(title='Delete Attribute',
                      content=self.pop_layout,
                      size_hint=(None,None),
                      size=(400,200),
                      background=BKGD_DCHRC,
                      pos_hint={"center_x":.5, 'top':.7},
                      auto_dismiss=False)

        self.pop_layout.add_widget(Label(text=("Delete Attribute?"),
                                   color=(1,1,1,1),
                                   pos_hint={'top':1.2, "center_x":.5},
                                   font_size=14))
                                   
        self.pop_layout.add_widget(HoverButton(text="Delete",
                            button_up=BTN_DCHRC[0],
                            button_down=BTN_DCHRC[1],
                            font_size=14,
                            size_hint=(None,None),
                            size=(100,40),
                            pos_hint={"center_x":.7, 'top':.35},
                            on_press=self.delete_label))
        self.pop_layout.add_widget(HoverButton(text="Cancel",
                            button_up=BTN_DCHRC[0],
                            button_down=BTN_DCHRC[1],
                            font_size=14,
                            size_hint=(None,None),
                            size=(100,40),
                            pos_hint={"center_x":.3, 'top':.35},
                            on_press=self.del_popup.dismiss))
        self.del_popup.open()

    ##
    # Class Method: delete_label
    # ----------------------------
    # This method removes the visible label from the user or group and
    # also removes the instance from the database, completely getting rid
    # of any trace of the curtrent label.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            This is the button which triggers this function call
    ##       
    def delete_label(self, instance):
        try:
            self.del_popup.dismiss()
        except:
            pass
        self.clear_from_db()
        if self.error_present:
            self.parent.parent.remove_widget(self.err_label)
        self.parent.parent.remove_widget(self.parent)

    ##
    # Class Method: clear_from_db
    # ----------------------------
    # This method removes the labels contents from the database depending
    # on within what category they are placed. The method then attempts to
    # update the database or text file to match the GUI
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    ##       
    def clear_from_db(self):
        if self.current_attr:
            attr = self.current_attr
            if manager.sm.current == "menu":
                try:
                    if not self.group:
                        attr.value = ""
                        database.modify_user_attr(manager.CURRENT_USER, attr)
                        self.current_attr = None
                    else:
                        attr.value = ""
                        database.modify_group_attr(manager.CURRENT_GROUP, attr)
                        self.current_attr = None
                except SyntaxError:
                    pass
            else:
                for preset in manager.presets:
                    if preset.name == manager.CURRENT_PRESET:
                        try:
                            preset.delete_attribute(attr.name, attr.operator, attr.category)
                            presets.save_presets(manager.presets, "user_presets.txt")
                            return
                        except SyntaxError:
                            pass

    error_present = False


    ##
    # Class Method: on_text_validate
    # ----------------------------
    # This method deals with what to do when the label is validated. First it checks to
    # see if a valid attribute is presented. If not, an error label is displayed. Then, the
    # database is updated with the correct information that matches the GUI.
    #
    # @params
    # (EditableLabel) self              This instance of EditableLabel
    # (HoverButton) instance            The button that triggered this function call
    ##       
    def on_text_validate(self, instance):
        if self.error_present:
            self.parent.parent.remove_widget(self.err_label)
        self.text = self.text_input.text

        self.clear_from_db()
        if self.text_input.text == '':
            self.delete_label(self)
            return

        try:
            attr_values = database.split_attributes(self.text)
            if attr_values[2].strip() == '':
                self.delete_label(self)
                return
        except SyntaxError:
            self.err_label = Label(text="Please enter a valid attribute",
                                                     pos_hint={"x-center":.5,"bottom":.95},
                                                     color=(1,0,0,1),
                                                     font_size=14)
            self.parent.parent.add_widget(self.err_label)
            self.error_present = True
            return

        self.remove_widget(self.confirm_button)
        self.remove_widget(self.drop_button)
        self.add_widget(self.edit_button)
        self.add_widget(self.category_display)
        self.remove_widget(self.clear_button)
        
        self.current_attr = Attribute(attr_values[0].strip(), attr_values[1].strip(), attr_values[2].strip(), self.attr_category)
        
        if manager.sm.current == "menu":
            if not self.group:
                database.modify_user_attr(manager.CURRENT_USER, self.current_attr)
            else:
                database.modify_group_attr(manager.CURRENT_GROUP, self.current_attr)
            manager.menu.recolor_info_panel()
        else:
            for preset in manager.presets:
                if preset.name == manager.CURRENT_PRESET:
                    try:
                        preset.update_attribute(attr_values[0], attr_values[1], attr_values[2], self.attr_category)

                    except SyntaxError:
                        error_button = Button(text='Please enter a valid attribute, press to close')
                        error_popup = Popup(title='Error Popup', content=error_button, size_hint=(.5, .5), pos_hint={'center_x': .5, 'center_y': .5})
                        error_button.bind(on_press=error_popup.dismiss)
                        error_popup.open()
                        return
            presets.save_presets(manager.presets, "user_presets.txt")
        self.edit = False
コード例 #23
0
class EditorOperationBox():
    def __init__(self, **kwargs):

        # Definitions defaults - config implementation later!
        self.newBtnColor = (0, 0, 0, 1)
        self.newBtnBgColor = (1, 1, 1, 1)
        self.newBtnWidth = 200
        self.newBtnHeight = 80

        self.store = kwargs.get("store")
        self.currentLayoutId = kwargs.get("currentLayoutId")

        self.engineRoot = kwargs.get("engineRoot")
        print("Access currentLayoutId -> ", self.currentLayoutId)

        # Prepare content
        content = GridLayout(orientation="lr-tb",
                             padding=[150, 0, 150, 0],
                             cols=2)
        clrPickerTextColor = ColorPicker(size_hint=(1, 1))
        clrPickerBackgroundColor = ColorPicker(size_hint=(1, 1))

        content.add_widget(Label(text='Layout Name(Tag)'))
        self.buttonNameText = TextInput(text='MyBoxLayout')
        content.add_widget(self.buttonNameText)

        content.add_widget(Label(text='Layout Type(Visual type)'))
        # self.buttonNameText = AlignedTextInput(text='utton', halign="middle", valign="center")

        self.layoutTypeList = DropDown()
        self.selectBtn = Button(text='Box', on_press=self.layoutTypeList.open)
        content.add_widget(self.selectBtn)

        self.layoutTypeList.dismiss()

        #Anchor layout:
        #Box layout:
        #Float layout:
        #Grid layout:
        #Page Layout:
        #Relative layout:
        #Scatter layout:
        # Stack layout:

        self.btnBox = Button(text='Box', size_hint_y=None, height=44)
        self.btnBox.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnBox)

        self.btnAnchor = Button(text='Anchor', size_hint_y=None, height=44)
        self.btnAnchor.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnAnchor)

        self.btnFloat = Button(text='Float', size_hint_y=None, height=44)
        self.btnFloat.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnFloat)

        self.btnGrid = Button(text='Grid', size_hint_y=None, height=44)
        self.btnGrid.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnGrid)

        self.btnPage = Button(text='Page', size_hint_y=None, height=44)
        self.btnPage.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnPage)

        self.btnRelative = Button(text='Relative', size_hint_y=None, height=44)
        self.btnRelative.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnRelative)

        self.btnScatter = Button(text='Scatter', size_hint_y=None, height=44)
        self.btnScatter.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnScatter)

        self.btnStack = Button(text='Stack', size_hint_y=None, height=44)
        self.btnStack.bind(on_release=partial(self.__setLayoutType))
        self.layoutTypeList.add_widget(self.btnStack)

        content.add_widget(self.layoutTypeList)

        colorHolder = BoxLayout(size_hint=(1, None), height=160)
        content.add_widget(colorHolder)

        colorHolder.add_widget(Label(text='Button background color'))
        colorHolder.add_widget(clrPickerBackgroundColor)

        colorHolderT = BoxLayout(size_hint=(1, None), height=160)
        content.add_widget(colorHolderT)

        colorHolderT.add_widget(Label(text='Button text color'))
        colorHolderT.add_widget(clrPickerTextColor)

        content.add_widget(Label(text='Orientation'))
        self.orientation = TextInput(text='vertical')
        content.add_widget(self.orientation)

        content.add_widget(Label(text='cols'))
        self.colsInput = TextInput(text='6')
        content.add_widget(self.colsInput)

        content.add_widget(Label(text='rows'))
        self.rowsInput = TextInput(text='0')
        content.add_widget(self.rowsInput)

        content.add_widget(Label(text='Padding'))
        self.layoutPadding = TextInput(text='0')
        content.add_widget(self.layoutPadding)

        content.add_widget(Label(text='Spacing'))
        self.layoutSpacing = TextInput(text="0")
        content.add_widget(self.layoutSpacing)

        #myCheckDimSys = BoxLayout()
        content.add_widget(Label(text='Use Pixel Dimensions'))
        #content.add_widget(myCheckDimSys)
        self.checkboxDim = CheckBox()
        content.add_widget(self.checkboxDim)

        self.checkboxDim.bind(
            active=self.on_checkbox_active)  # pylint disable=no-member

        content.add_widget(Label(text='Use Pixel For Width'))
        self.buttonWidthText = TextInput(text='200')
        content.add_widget(self.buttonWidthText)
        content.add_widget(Label(text='Use Pixel For Height'))
        self.buttonHeightText = TextInput(text='100')
        content.add_widget(self.buttonHeightText)

        #myCheckPerSys = BoxLayout()
        content.add_widget(Label(text='Use Percent Dimensions'))
        #content.add_widget(myCheckPerSys)
        self.checkboxPer = CheckBox(active=True)
        content.add_widget(self.checkboxPer)
        self.checkboxPer.bind(
            active=self.on_checkbox_per_active)  # pylint disable=no-member

        content.add_widget(
            Label(text='Use percent dimensions range(0 - 1). Width'))
        self.buttonHintX = TextInput(text='1')
        content.add_widget(self.buttonHintX)
        content.add_widget(
            Label(text='Use percent dimensions range(0 - 1). Height'))
        self.buttonHintY = TextInput(text='1')
        content.add_widget(self.buttonHintY)

        content.add_widget(Label(text='Position X in pixels'))
        self.buttonPositionX = TextInput(text='0', halign="center")
        content.add_widget(self.buttonPositionX)
        content.add_widget(Label(text='Position Y in pixels'))
        self.buttonPositionY = TextInput(text='0', halign="center")
        content.add_widget(self.buttonPositionY)

        content.add_widget(Label(text='Position Hint X'))
        self.buttonPositionHintX = TextInput(text='0', halign="center")
        content.add_widget(self.buttonPositionHintX)
        content.add_widget(Label(text='Position Hint Y'))
        self.buttonPositionHintY = TextInput(text='0', halign="center")
        content.add_widget(self.buttonPositionHintY)

        # Popup
        self.popup = Popup(title='Add new Layout editor box',
                           content=content,
                           auto_dismiss=False)

        # Events attach
        clrPickerTextColor.bind(color=self.on_color)  # pylint: disable=no-member
        clrPickerBackgroundColor.bind(color=self.on_bgcolor)  # pylint: disable=no-member
        # Open popup
        self.popup.open()

        # Bind elements
        commitBtn = Button(
            text='Add new Layout',
            size_hint=(1, None),
            height=88,
            color=self.engineRoot.engineConfig.getThemeTextColor(),
            background_color=(self.engineRoot.engineConfig.getThemeCustomColor(
                'engineBtnsBackground')),
            on_press=lambda a: self.oAddBox(self))
        content.add_widget(commitBtn)

        cancelBtn = Button(
            text='Cancel',
            size_hint=(1, None),
            height=88,
            color=self.engineRoot.engineConfig.getThemeTextColor(),
            background_color=(self.engineRoot.engineConfig.getThemeCustomColor(
                'engineBtnsBackground')),
            on_press=lambda a: self.DissmisPopup(self))
        content.add_widget(cancelBtn)

    def __setLayoutType(self, instance):
        print("__setLayoutType", instance)
        self.selectBtn.text = instance.text
        self.layoutTypeList.select(self.btnBox.text)

    def _add(self, localStagedElements, calculatedButtonData, currentLayoutId):
        for index, item in enumerate(localStagedElements):
            if item['id'] == currentLayoutId:
                localStagedElements[index]['elements'].append(
                    calculatedButtonData)
                return localStagedElements
                break
            if item['type'] == 'LAYOUT':
                self._add(item['elements'], calculatedButtonData,
                          currentLayoutId)
        return False

    def oAddBox(self, instance):
        ####################################################
        # Operation `Add`
        ####################################################
        print("instance on local call -> ", self.newBtnColor)

        dimensionRole = "pixel"
        if self.checkboxDim.active == True:
            local_size_hintX = None
            local_size_hintY = None
            print(" SET HINT NONE ")
            # self.buttonHintX.text, self.buttonHintY.text
        elif self.checkboxPer.active == True:
            print(" SET HINT ")
            if self.buttonHintX.text == "None":
                local_size_hintX = None
            else:
                local_size_hintX = float(self.buttonHintX.text)

            if self.buttonHintY.text == "None":
                local_size_hintY = None
            else:
                local_size_hintY = self.buttonHintY.text

            dimensionRole = "hint"
        elif self.checkboxCombine.active == True:
            print(" SET COMBINE ")
            if self.buttonHintX.text == "None":
                local_size_hintX = None
            else:
                local_size_hintX = float(self.buttonHintX.text)
            if self.buttonHintY.text == "None":
                local_size_hintY = None
            else:
                local_size_hintY = self.buttonHintY.text
            dimensionRole = "combine"

        #if str(detailData['layoutType']) == "Anchor" or str(detailData['layoutType']) == "Float":
        #localAnchor_x = self.selectAnchor.text
        #localAnchor_y = self.selectAnchorY.text
        #else:

        localAnchor_x = 'center'
        localAnchor_y = 'center'

        calculatedButtonData = {
            "id": str(uuid.uuid4()),
            "name": self.buttonNameText.text,
            "type": "LAYOUT",
            "cols": self.colsInput.text,
            "rows": self.rowsInput.text,
            "pos_x": self.buttonPositionX.text,
            "pos_y": self.buttonPositionY.text,
            "pos_hint_x": self.buttonPositionHintX.text,
            "pos_hint_y": self.buttonPositionHintY.text,
            "layoutType": self.selectBtn.text,
            "elements": [],
            "orientation": self.orientation.text,
            "padding": self.layoutPadding.text,
            "spacing": self.layoutSpacing.text,
            "color": self.newBtnColor,
            "bgColor": self.newBtnBgColor,
            "width": self.buttonWidthText.text,
            "height": self.buttonHeightText.text,
            "size_hint_x": str(self.buttonHintX.text),
            "size_hint_y": str(self.buttonHintY.text),
            "dimensionRole": dimensionRole,
            "anchor_x": localAnchor_x,
            "anchor_y": localAnchor_y,
            "swipe_threshold": str(0.4)
        }

        # print('what is the type of layout', self.selectBtn.text)
        localStagedElements = []

        if self.store.exists('renderComponentArray'):
            # print('renderComponentArray exists:', self.store.get('renderComponentArray')['elements'])
            localStagedElements = self.store.get(
                'renderComponentArray')['elements']
            #######################
            # First just root
            if self.currentLayoutId == None:
                localStagedElements.append(calculatedButtonData)
            else:
                self._add(localStagedElements, calculatedButtonData,
                          self.currentLayoutId)

        # Final
        self.store.put('renderComponentArray', elements=localStagedElements)

        self.popup.dismiss()

        self.engineRoot.updateScene()
        self.engineRoot.sceneGUIContainer.selfUpdate()

    # To monitor changes, we can bind to color property changes
    def on_color(self, instance, value):

        self.newBtnColor = str(value)
        # print( "RGBA = ", (value[0], value[1], value[2], 1 )) #  or instance.color
        self.newBtnColor = (value[0], value[1], value[2], 1)
        # print( "HSV = ", str(instance.hsv))
        # print( "HEX = ", str(instance.hex_color))

    def on_bgcolor(self, instance, value):

        print(str(value), ' ,,,,, color')
        # print( "RGBA = ", (value[0], value[1], value[2], 1 )) #  or instance.color
        self.newBtnBgColor = (value[0], value[1], value[2], 1)
        # print( "HSV = ", str(instance.hsv))
        # print( "HEX = ", str(instance.hex_color))

    def DissmisPopup(self, instance):
        print("Operation add.")
        self.popup.dismiss()

    def on_checkbox_active(instance, value1, value):
        print(" 1 : ", instance)
        print(" 2 ", value1)
        print(" 3 ", value)
        if value:
            print('The dimensions checkbox', value1, 'is active')
            instance.checkboxPer.active = False

        else:
            print('The dimensions checkbox', value1, 'is inactive')

    def on_checkbox_per_active(instance, value1, value):
        print(" input percent ", value)
        print(" acess ", instance)
        if value:
            print('The dimensions checkbox', value1, 'is active')
            instance.checkboxDim.active = False
        else:
            print('The dimensions checkbox', value1, 'is inactive')
コード例 #24
0
ファイル: main.py プロジェクト: snckmykek/time_control
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
コード例 #25
0
def summon_popup_playlist(db: DBMuziek, dd: DropDown):
    dd.dismiss()
    PopupPlaylist(db).open()
コード例 #26
0
ファイル: main.py プロジェクト: oukiar/DevsHub
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)
コード例 #27
0
ファイル: scoretracker.py プロジェクト: Campus77/scoretracker
class LoungeScreen(BaseScreen):

    current_player_slot = NumericProperty(0)
    players = ListProperty([{}] * 4)
    dropdown_player = ObjectProperty()
    drag_start_id = NumericProperty(-1)
    drag_stop_id = NumericProperty(-1)
    dragging = BooleanProperty()

    def __init__(self, **kwargs):
        super(LoungeScreen, self).__init__(**kwargs)
        self.set_title('Aufstellung')
        self.ids.topbar.hasNext = True
        self.is_dropdown_open = False
        self.slot_touch = None

        self.__reset()

    def on_enter(self):
        Clock.schedule_once(lambda dt: self.__setup_player_dropdown(), 0.2)
        self.current_player_slot = 0

    def on_leave(self):
        self.close_dropdown()

    def on_next(self):
        self.manager.current = 'match'

    def __reset(self):
        self.players = [{}] * 4
        self.current_player_slot = 0

    def __setup_player_dropdown(self):
        # only create if not existing
        if not self.dropdown_player:
            self.dropdown_player = DropDown(auto_dismiss=False)
            self.dropdown_player.bind(on_select=self.on_player_select)
            self.dropdown_player.bind(on_dismiss=self.on_dropdown_dismiss)

            players = sorted(PlayerData.get_players(), key=lambda player: player['name'])
            for player in players:
                btn = PlayerButton(data=player)
                btn.bind(on_release=lambda btn: self.dropdown_player.select(btn.data))
                self.dropdown_player.add_widget(btn)

    def on_dropdown_dismiss(self, instance):
        self.is_dropdown_open = False

    def open_dropdown(self, slot_id):
        if not self.is_dropdown_open:
            obj = self.ids['p' + str(slot_id)]
            self.dropdown_player.open(obj)
            self.is_dropdown_open = True

    def close_dropdown(self):
        if self.is_dropdown_open:
            self.dropdown_player.dismiss()

    def on_player_select(self, instance, data):
        # player was selected from dropdown list
        self.dropdown_player.dismiss()
        self.set_player(data)

    def on_players(self, instance, value):
        GameData.set_players(value)
        count_players = 0
        for player in self.players:
            count_players = count_players + (1 if player else 0)
        self.ids.topbar.isNextEnabled = (count_players == 4)

    def click_player_slot(self, player_slot):
        pass

    def __handle_rfid(self, rfid):
        # RFID --> player ID
        player_id = PlayerData.get_player_by_rfid(rfid)
        # player ID --> player dict
        player = PlayerData.get_player_by_id(player_id)
        Logger.info('ScoreTracker: RFID: {0} - ID: {1} - Player: {2}'.format(rfid, player_id, player))
        # player does not exist
        if player == None:
            self.denied()
        # player does exist
        else:
            if self.dropdown_player:
                self.dropdown_player.dismiss()
            self.set_player(player)

    def highlight_player(self, slot_id):
        obj = self.ids['p' + str(slot_id)].ids.playerName
        HighlightOverlay(orig_obj=obj, parent=self, active=True, bold=True).animate(font_size=80, color=(1, 1, 1, 0))

    def switch_players(self, slot_id_1, slot_id_2):
        self.players[slot_id_1], self.players[slot_id_2] = self.players[slot_id_2], self.players[slot_id_1]
        for player_id in [slot_id_1, slot_id_2]:
            self.highlight_player(player_id)
        SoundManager.play(Trigger.PLAYERS_SWITCHED)

    def get_slot_collision(self, event):
        slot_id = None
        colliding = False
        for i in range(0, 4):
            obj = self.ids['p' + str(i)]
            collide = obj.collide_point(event.pos[0], event.pos[1])
            if collide:
                slot_id = i
        return slot_id
        
    def handle_slot_touch_down(self, event):
        # check if slot was pressed
        colliding_slot_id = self.get_slot_collision(event)
        if colliding_slot_id is not None:
            self.slot_touch = {'source_id': colliding_slot_id, 'source_pos': event.pos, 'target_id': colliding_slot_id, 'dist': 0.0}
            self.drag_start_id = colliding_slot_id
            self.dragging = False
            #print 'down', self.slot_touch

    def handle_slot_touch_move(self, event):
        # a slot was dragged
        if self.slot_touch:
            dx = abs(self.slot_touch['source_pos'][0] - event.pos[0])
            dy = abs(self.slot_touch['source_pos'][1] - event.pos[1])
            dist = math.sqrt(dx * dx + dy * dy)
            self.slot_touch['dist'] = dist
            self.dragging = (dist > 10.0)
            # check collision
            colliding_slot_id = self.get_slot_collision(event)
            if colliding_slot_id is not None:
                self.slot_touch['target_id'] = colliding_slot_id
                self.drag_stop_id = colliding_slot_id
            else:
                self.slot_touch['target_id'] = None
                self.drag_stop_id = -1

            #print 'move', self.slot_touch

    # a slot was released
    def handle_slot_touch_up(self, event):
        if self.slot_touch:
            #print 'up', self.slot_touch
            # release on same slot
            if self.slot_touch['source_id'] == self.slot_touch['target_id']:
                # started in this slot: toggle dropdown
                if self.slot_touch['source_id'] == self.current_player_slot:
                    if self.is_dropdown_open:
                        self.close_dropdown()
                    else:
                        self.open_dropdown(self.slot_touch['target_id'])
                # activate
                else:
                    self.current_player_slot = self.slot_touch['source_id']
                    self.close_dropdown()
                    # highlight icon
                    obj = self.ids['p' + str(self.current_player_slot)].ids.icon
                    HighlightOverlay(orig_obj=obj, parent=self, active=True).animate(font_size=160, color=(1, 1, 1, 0))
            # dragged to another slot
            else:
                if self.slot_touch['target_id'] is not None:
                    self.switch_players(self.slot_touch['source_id'], self.slot_touch['target_id'])

            self.slot_touch = None
            self.drag_start_id = -1
            self.drag_stop_id = -1

    def set_player(self, player):
        # check if player has already been set before
        try:
            idx_already_set = self.players.index(player)
        except ValueError, e:
            # player is not in any team yet
            self.players[self.current_player_slot] = player
            self.highlight_player(self.current_player_slot)
            SoundManager.play(Trigger.PLAYER_JOINED, player)
        else:
コード例 #28
0
ファイル: client.py プロジェクト: WallTack/Python-Practice
class SecondaryWindow(Screen):
    def __init__(self, **kwargs):
        # GUI from top to bottom, left to right
        super(SecondaryWindow, self).__init__(**kwargs)

        self.scroll = ScrollView(size_hint=(1, None),
                                 size=(Window.width, Window.height))
        self.scroll_btn = None

        self.scroll_grid = GridLayout(cols=2, spacing=1, size_hint_y=None)
        self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height'))

        with self.canvas:
            Color(0.2, 0.2, 0.28)
            Rectangle(size=(Window.width**2, Window.height**2))

        self.btn_live_orders = Button(size_hint_y=None,
                                      height=40,
                                      text="< Current Orders",
                                      background_color=[0.45, 0.45, 0.45, 3],
                                      on_release=self.changeWindow)
        self.scroll_grid.add_widget(self.btn_live_orders)

        self.btn_menu = Button(size_hint_y=None,
                               height=40,
                               text="Menu >",
                               background_color=[0.45, 0.45, 0.45, 3],
                               on_release=self.changeWindow)
        self.scroll_grid.add_widget(self.btn_menu)

        self.drp_date = DropDown()
        self.drp_date_check = str(datetime.date.today())
        self.drp_date_btn = Button(size_hint_y=None,
                                   height=40,
                                   text=f"{self.drp_date_check}",
                                   background_color=[0.45, 0.45, 0.45, 3],
                                   on_release=self.drp_date.open)
        self.drp_date_btn_dates = None

        self.scroll_grid.add_widget(self.drp_date_btn)

        self.popup = Popup(title='Title',
                           title_align='center',
                           content=Label(text='Text',
                                         size=(400, 400),
                                         text_size=[380, 380],
                                         halign='center',
                                         valign='center'),
                           size_hint=(None, None),
                           size=(400, 400))
        self.popup_db_list = []

    #     self.dropDown()
    #
    # def dropDown(self):  # Always called with __init__
    #     for i in range(len(screen_main.order_database_dates)):
    #         self.drp_date_btn_dates = Button(text=f"{screen_main.order_database_dates[i]}", size_hint_y=None,
    #                                          height=44, background_color=[0.45, 0.45, 0.45, 3],
    #                                          on_release=self.checkDate)
    #         self.drp_date.add_widget(self.drp_date_btn_dates)

    def connectSocket(self):

        host = '10.0.0.69'
        port = 8912
        address = (host, port)

        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(address)

        while True:
            msg = pickle.loads(client.recv(4096))
            print(msg)

    def checkDate(self, instance):
        self.drp_date_check = instance.text
        self.generateOrders()
        self.drp_date.dismiss()

    def changeWindow(self, instance):
        if 'Menu' in instance.text:
            sm.current = 'main'
            sm.transition.direction = 'left'
            self.reset()
        elif 'Orders' in instance.text:
            sm.current = 'tertiary'
            sm.transition.direction = 'right'
            self.reset()

    def reset(self):
        self.scroll_grid.clear_widgets()
        self.scroll_grid.add_widget(self.btn_live_orders)
        self.scroll_grid.add_widget(self.btn_menu)
        self.scroll_grid.add_widget(self.drp_date_btn)
        self.popup_db_list.clear()

    def popupItem(self, instance):
        num = int(instance.text.split('Order #')[-1])

        self.popup.content.text = f"{self.popup_db_list[num - 1]}"
        self.popup.title = f"Order #{num}"

        self.popup.open()
コード例 #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)
コード例 #30
0
def summon_popup_group(db: DBMuziek, dd: DropDown):
    dd.dismiss()
    PopupGroup(db).open()
コード例 #31
0
class EventHandlerTextInput(TextInput):
    '''EventHandlerTextInput is used to display/change/remove EventHandler
       for an event
    '''

    eventwidget = ObjectProperty(None)
    '''Current selected widget
       :data:`eventwidget` is a :class:`~kivy.properties.ObjectProperty`
    '''

    eventname = StringProperty(None)
    '''Name of current event
       :data:`eventname` is a :class:`~kivy.properties.ObjectProperty`
    '''

    kv_code_input = ObjectProperty()
    '''Reference to KVLangArea
       :data:`kv_code_input` is a :class:`~kivy.properties.ObjectProperty`
    '''

    text_inserted = BooleanProperty(None)
    '''Specifies whether text has been inserted or not
       :data:`text_inserted` is a :class:`~kivy.properties.ObjectProperty`
    '''

    project_loader = ObjectProperty(None)
    '''Reference to ProjectLoader
       :data:`project_loader` is a :class:`~kivy.properties.ObjectProperty`
    '''

    info_message = StringProperty(None)
    '''Message to be displayed by InfoBubble
       :data:`info_message` is a :class:`~kivy.properties.StringProperty`
    '''

    dropdown = ObjectProperty(None)
    '''DropDown which will be displayed to show possible
       functions for that event
       :data:`dropdown` is a :class:`~kivy.properties.ObjectProperty`
    '''

    def on_touch_down(self, touch):
        '''Default handler for 'on_touch_down' event
        '''
        if self.collide_point(*touch.pos):
            self.info_bubble = InfoBubble(message=self.info_message)
            bubble_pos = list(self.to_window(*self.pos))
            bubble_pos[1] += self.height
            self.info_bubble.show(bubble_pos, 1.5)

        return super(EventHandlerTextInput, self).on_touch_down(touch)

    def show_drop_down_for_widget(self, widget):
        '''Show all functions for a widget in a Dropdown.
        '''
        self.dropdown = DropDown()
        list_funcs = dir(widget)
        for func in list_funcs:
            if '__' not in func and hasattr(getattr(widget, func), '__call__'):
                btn = Button(text=func, size_hint=(None, None),
                             size=(100, 30), shorten=True)
                self.dropdown.add_widget(btn)
                btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
                btn.text_size = [btn.size[0] - 4, btn.size[1]]
                btn.valign = 'middle'

        self.dropdown.open(self)
        self.dropdown.pos = (self.x, self.y)
        self.dropdown.bind(on_select=self._dropdown_select)

    def _dropdown_select(self, instance, value):
        '''Event handler for 'on_select' event of self.dropdown
        '''
        self.text += value

    def on_text(self, instance, value):
        '''Default event handler for 'on_text'
        '''
        if not self.kv_code_input:
            return

        self.kv_code_input.set_event_handler(self.eventwidget,
                                             self.eventname,
                                             self.text)
        if self.text and self.text[-1] == '.':
            if self.text == 'self.':
                self.show_drop_down_for_widget(self.eventwidget)

            elif self.text == 'root.':
                self.show_drop_down_for_widget(
                    self.project_loader.root_rule.widget)

            else:
                _id = self.text.replace('.', '')
                root = self.project_loader.root_rule.widget
                widget = None

                if _id in root.ids:
                    widget = root.ids[_id]

                if widget:
                    self.show_drop_down_for_widget(widget)

        elif self.dropdown:
            self.dropdown.dismiss()
コード例 #32
0
class RemoveUser(Popup):

    ##
    # Class Constructor: __init__ 
    # ---------------------------
    # This method is called during creation of the RemoveUser class.
    # This function creates the layout for the popup as well as initializes all the 
    # popup attributes.
    #
    # @params
    # (RemoveUser) self                 This instance of RemoveUser
    # (Various) **kwargs                Arguments for constuction of internal Popup object
    ##
    def __init__(self, **kwargs):
        self.layout = FloatLayout(size=(Window.width, 200))
        super(RemoveUser, self).__init__(title='Remove User',
                                              content=self.layout,
                                              size_hint=(None,None),
                                              size=(400,200),
                                              background=BKGD_DCHRC,
                                              pos_hint={"center_x":.5, 'top':.7},
                                              auto_dismiss=False,
                                              **kwargs)
        
    ##
    # Class Method: draw_layout
    # -------------------------
    # This method creates the entire layout for the remove user popup including
    # the dropdown from which to select group users to remove
    #
    # @params
    # (RemoveUser) self                 This instance of RemoveUser
    ## 
    def draw_layout(self):
        self.button_x = .5
        if manager.CURRENT_GROUP != None:
            self.button_x = .3
            self.dropdown = DropDown(auto_width=False, width=180, max_height=180)
            self.dropdown.main_button = HoverButton(text="Select User",
                                      size=(180,40),
                                      size_hint=(None,None),
                                      pos_hint={"center_x":.5, 'top':.8},
                                      button_down=DD_DCHRC[1],
                                      button_up=DD_DCHRC[0],
                                      on_release=self.dropdown.open)
            self.layout.add_widget(self.dropdown.main_button)
            self.remove_user_dropdown()
            
            self.layout.add_widget(HoverButton(text="Remove",
                                button_down=BTN_DCHRC[1],
                                button_up=BTN_DCHRC[0],
                                font_size=14,
                                size_hint=(None,None),
                                size=(100,40),
                                pos_hint={"center_x":.7, 'top':.35},
                                on_press=self.remove_from_group))
        else:
            self.layout.add_widget(Label(text="No Group Selected",
                                font_size=14,
                                pos_hint={"center_x":.5, 'top':1.2}))
        self.layout.add_widget(HoverButton(text="Cancel",
                            button_down=BTN_DCHRC[1],
                            button_up=BTN_DCHRC[0],
                            font_size=14,
                            size_hint=(None,None),
                            size=(100,40),
                            pos_hint={"center_x":self.button_x, 'top':.35},
                            on_press=self.dismiss))

    ##
    # Class Method: select_user
    # -------------------------
    # This method sets the main button to the user selected and closes the dropdown
    #
    # @params
    # (RemoveUser) self                 This instance of RemoveUser
    # (HoverButton) instance            The button of the user that has been selected
    ## 
    def select_user(self, instance):
        self.dropdown.dismiss()
        self.dropdown.main_button.text = instance.text
        if len(self.group_members) == 1:
            for child in self.layout.children:
                if type(child) == Label and child.text == "Please Select a User to Remove" or\
                   child.text == "Deleting this user will delete the Group! Proceed with caution":
                    self.layout.remove_widget(child)
            self.layout.add_widget(Label(text="Deleting this user will delete the Group! Proceed with caution",
                                       color = (1, 0, 0, 1),
                                       font_size = 11,
                                       pos_hint={"center_x":.5, "top":1.95}))
            

    ##
    # Class Method: remove_user_dropdown
    # ----------------------------------
    # This method adds all of the current grop members to the dropdown to be selected
    # for removal
    #
    # @params
    # (RemoveUser) self                 This instance of RemoveUser
    ## 
    def remove_user_dropdown(self):
        self.group_members = database.get_group_members(manager.CURRENT_GROUP)
        for user in self.group_members:
            self.dropdown.add_widget(HoverButton(text=user[0],
                                             button_up=DD_DCHRC[0],
                                             button_down=DD_DCHRC[1],
                                             font_size=12,
                                             size=(180,30),
                                             size_hint=(None,None),
                                             on_release=self.select_user))
            
    ##
    # Class Method: remove_from_group
    # -------------------------------
    # This method removes the selected user from the group. In the case where no user is selected,
    # an error message is provided to inform the end user.
    #
    # @params
    # (RemoveUser) self                 This instance of RemoveUser
    # (HoverButton) instance            The button that triggers the call to remove_from_group
    ## 
    def remove_from_group(self, instance):
        user = self.dropdown.main_button.text
        if user == 'Select User':
            for child in self.layout.children:
                if type(child) == Label and child.text == "Please Select a User to Remove" or\
                   child.text == "Deleting this user will delete the Group! Proceed with caution":
                    self.layout.remove_widget(child)
            self.layout.add_widget(Label(text="Please Select a User to Remove",
                                       color = (1, 0, 0, 1),
                                       font_size = 11,
                                       pos_hint={"center_x":.5, "top":1.95}))
            return
        
        database.remove_group_member(user, manager.CURRENT_GROUP)
        if len(self.group_members) == 1:
            manager.menu.show_groups()
            manager.menu.info_panel.clear()
        else:
            manager.menu.display_group_info(manager.CURRENT_GROUP)
        self.dismiss()

    ##
    # Class Method: open_popup
    # ------------------------
    # This method is called to clear the widgets of the current popup layout and redraw the 
    # layout according to the current situation.
    #
    # @params
    # (RemoveUser) self                 This instance of RemoveUser
    ##  
    def open_popup(self):
        self.layout.clear_widgets()
        self.draw_layout()
        self.open()
コード例 #33
0
class UserInterface:
    def __init__(self, client):
        # TODO handle connection errors properly
        self.client = client
        self.layout = GridLayout(cols = 2, pos_hint={'x': 0, 'y': 0}, size_hint=(1, 0.1))
        self.client.layout.add_widget(self.layout, index = 1000)
        
        self.client.bind('connected', self.connected)
        self.client.bind('loaded', self.loaded)
        self.client.bind('registered', self.registered)
        
        if self.client.config.get('connection', 'autoconnect') == 'yes':
            self.auto = True
            self.client.connect(self.client.config.get('connection', 'server'))
        else:
            self.auto = False
        
            self.server_input = TextInput(text = self.client.config.get('connection', 'server'))
            self.server_button = Button(text = 'Connect', size_hint = (0.25, 1))
            self.server_button.bind(on_press = self.do_connect)
            
            self.layout.add_widget(self.server_input)
            self.layout.add_widget(self.server_button)
        
    def do_connect(self, button):
        self.client.connect(self.server_input.text)
        
        self.layout.remove_widget(self.server_input)
        self.layout.remove_widget(self.server_button)
        del self.server_input, self.server_button
        
        self.connecting_label = Label(text = 'connecting...')
        self.layout.add_widget(self.connecting_label)
        
    def connected(self, event):
        if not self.auto:
            self.client.config.set('connection', 'server', self.client.server)
            self.connecting_label.text = 'loading...'
        
    def loaded(self, event):
        if self.auto:
            self.client.register(self.client.config.get('connection', '_id'))
            return
        
        self.layout.remove_widget(self.connecting_label)
        del self.connecting_label
        
        self.dropdown = DropDown()
        
        for stage in sorted(self.client.meteor.find('stages'), key=lambda x: x['title']):
            self.dropdown.add_widget(Label(text = stage['title'], size_hint_y = None, height = 40))
            
            seen = []
            for minion in sorted(self.client.meteor.find('minions', 
                    selector = {'stage': stage['_id'], 'type': 'media'}), key=lambda x: x['title']):
                # workaround for python-meteor bug
                if not minion['stage'] == stage['_id']: continue
                
                if minion['_id'] in seen: continue
                else: seen.append(minion['_id'])

                button = Button(text = minion['title'], size_hint_y = None, height = 30)
                button.minion_id = minion['_id']
                button.bind(on_press = self.do_register)
                self.dropdown.add_widget(button)
        
        self.dropdown_button = Button(text = 'Select Minion')
        self.dropdown_button.bind(on_release = self.dropdown.open)
        self.layout.add_widget(self.dropdown_button)
            
        self.auto_checkbox = CheckBox()
        self.auto_label = Label(text = 'Connect automatically on start')
        self.layout.add_widget(self.auto_checkbox)
        self.layout.add_widget(self.auto_label)        
        
    def do_register(self, button):
        self.client.config.set('connection', '_id', button.minion_id)
        self.client.config.set('connection', 'autoconnect', 'yes' if self.auto_checkbox.active else 'no')
        self.client.config.write()
        self.client.register(button.minion_id)
        
        self.dropdown.dismiss()
        self.layout.remove_widget(self.dropdown_button)
        self.layout.remove_widget(self.auto_checkbox)
        self.layout.remove_widget(self.auto_label)
        del self.dropdown_button, self.dropdown, self.auto_checkbox, self.auto_label
        
        self.registering_label = Label(text = 'registering...')
        self.layout.add_widget(self.registering_label)
        
    def registered(self, event):
        if not self.auto:
            self.layout.remove_widget(self.registering_label)
            del self.registering_label
コード例 #34
0
class MainScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(MainScreen, self).__init__(*args, **kwargs)
        self.gen_env()
        #self.gen_map()
        self.edges = list()
        self.countries = list()
        self.player = None

    def gen_env(self):
        width, height = Window.size

        # Заголовок
        self.text1 = BlackLabel(size_hint=(None, None),
                                width=100,
                                height=30,
                                font_size=14,
                                pos=(50, height - 30))
        self.text1.text = 'Количество стран-вершин'
        self.add_widget(self.text1)

        # Окно поиска
        self.input1 = TextInput(multiline=False,
                                size_hint=(None, None),
                                width=100,
                                height=30,
                                font_size=14,
                                pos=(200, height - 30),
                                text='1')
                                # on_text_validate=print)
        self.add_widget(self.input1)

        # Генерация карты вершин
        self.generate_map = Button(
                                size_hint=(None, None),
                                width=100,
                                height=30,
                                font_size=14,
                                text='Генерировать',
                                pos=(310, height - 30)
        )
        self.generate_map.bind(on_release=self.gen_map)
        self.add_widget(self.generate_map)

        #gamma
        self.gamma_text = BlackLabel(size_hint=(None, None),
                                width=100,
                                height=30,
                                font_size=14,
                                pos=(450, height - 30))
        self.gamma_text.text = 'Введите гамма'
        self.add_widget(self.gamma_text)

        # Окно ввода гаммы
        self.input_gamma = TextInput(multiline=False,
                                size_hint=(None, None),
                                width=100,
                                height=30,
                                font_size=14,
                                pos=(550, height - 30),
                                text='2')
        # on_text_validate=print)
        self.add_widget(self.input_gamma)

        # ввод гаммы
        self.gamma_button = Button(size_hint=(None, None),
                                  width=130,
                                  height=30,
                                  font_size=14,
                                  text='Изменить гамма',
                                  pos=(550, height - 70))
        self.gamma_button.bind(on_release=self.change_gamma)
        self.add_widget(self.gamma_button)

        # Заголовок
        self.play_button= Button(size_hint=(None, None),
                                width=100,
                                height=30,
                                font_size=14,
                                text='Играть за',
                                pos=(50, height - 70))
        self.play_button.bind(on_release=self.add_player)
        self.add_widget(self.play_button)

        # Окно выбора игрока
        self.dropdown_1 = DropDown()
        self.country_change = Button(
            size_hint=(None, None),
            width=100,
            height=30,
            font_size=14,
            text='',
            pos=(150, height - 70)
        )
        self.country_change.bind(on_release=self.update_dropdown_1)
        # Действие в момент выбора
        # self.dropdown.bind(on_select=lambda instance, x: setattr(self.search, 'text', x))
        self.add_widget(self.country_change)

        self.model_game_btn = Button(
            size_hint=(None, None),
            width=100,
            height=30,
            font_size=14,
            text='Играть раунд',
            pos=(310, height - 70)
        )
        self.model_game_btn.bind(on_release=partial(self.model_game, 0))
        self.add_widget(self.model_game_btn)

        # Кнопка атаки
        self.attack = Button(size_hint=(None, None),
                             width=100,
                             height=30,
                             font_size=14,
                             text='Атаковать',
                             pos=(50, height - 110))
        self.attack.bind(on_release=self.country_conquest)
        self.add_widget(self.attack)

        # Окно выбора игрока
        self.dropdown_2 = DropDown()
        self.attack_country = Button(
            size_hint=(None, None),
            width=100,
            height=30,
            font_size=14,
            text='',
            pos=(150, height - 110)
        )
        self.attack_country.bind(on_release=self.update_dropdown_2)
        # Действие в момент выбора
        # self.dropdown.bind(on_select=lambda instance, x: setattr(self.search, 'text', x))
        self.add_widget(self.attack_country)

        # Кнопка паса
        self.passs = Button(size_hint=(None, None),
                             width=100,
                             height=30,
                             font_size=14,
                             text='Пасовать',
                             pos=(50, height - 150))
        self.passs.bind(on_release=self.pass_round)
        self.add_widget(self.passs)

    def change_gamma(self, *args):
        global my_w
        my_w.gamma = float(self.input_gamma.text)

    def update_dropdown_1(self, struct):
        if self.player:
            return -1
        global my_w
        self.dropdown_1.dismiss()
        self.dropdown_1=DropDown()
        self.dropdown_1.max_height = Window.size[1] * 0.7

        #Здесь будет возвращаться список стран
        for country in my_w.country_list:
            btn = Button(text=f'{country.get_number()}', size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: self.dropdown_1.select(btn.text))
            self.dropdown_1.add_widget(btn)

        self.dropdown_1.open(struct)
        self.dropdown_1.bind(on_select=lambda instance, x: setattr(self.country_change, 'text', x))

        self.attack_country.text=''

    def update_dropdown_2(self, struct):
        global my_w
        # Здесь будет возвращаться список соседей для выбранной страны
        if self.country_change.text!='':
            self.dropdown_2.dismiss()
            self.dropdown_2 = DropDown()
            self.dropdown_2.max_height = Window.size[1] * 0.7

            number = int(self.country_change.text)
            your_country = my_w.search_country_by_number(number)

            for neigh in your_country.get_neighbors():
                btn = Button(text=f'{neigh.get_number()}', size_hint_y=None, height=30)
                btn.bind(on_release=lambda btn: self.dropdown_2.select(btn.text))
                self.dropdown_2.add_widget(btn)

            self.dropdown_2.open(struct)
            self.dropdown_2.bind(on_select=lambda instance, x: setattr(self.attack_country, 'text', x))

    def country_conquest(self, *args):
        global my_w
        at_number = int(self.country_change.text)
        def_number = int(self.attack_country.text)
        if at_number!='' and def_number!='':
            att = my_w.search_country_by_number(at_number)
            deff = my_w.search_country_by_number(def_number)
            my_w.attack(att, deff)
            self.attack_country.text=''
            self.update_map()
        self.model_game(flag=1)

    def pass_round(self, *args):
        self.model_game(flag=1)

    def model_game(self, flag=0, *args):
        global my_w
        #создаём очередь
        if flag==0:
            self.queue = my_w.generate_queue()
            self.i = 0
        while self.i < len(self.queue):
            play_country = self.queue[self.i]
            if self.player == play_country:
                self.update_map()
                break

            loser = my_w.play(play_country)
            # создаём новую очередь, если что-то делаем
            if loser:
                new_queue = list()
                for country in self.queue:
                    if country != loser:
                        new_queue.append(country)
                self.queue = new_queue
            # проверяем сместилась ли она так, что элемент с текущим номером стал другим, если да, то ничего не делаем,
            # если нет, то i++
            if self.i < len(self.queue):
                if play_country == self.queue[self.i]:
                    self.i += 1

        self.update_map()

    def add_player(self, *args):
        if self.country_change.text !='':
            self.player = self.country_change.text

    def gen_map(self, *args):
        global my_w
        quantity = int(self.input1.text)

        my_w.zeroize()
        my_w.generate_vertexes(quantity=quantity)
        my_w.generate_countries()
        self.update_map()

    def update_map(self, *args):
        coordinate_vert_dict = dict()
        k = 0
        for vert in my_w.vertexes:
            coordinate_vert_dict[vert.get_number()] = (20 + k * 80, 200)
            k += 1
        defalt_size = 50
        # очистка ребёр с экрана
        for edge in self.edges:
            self.remove_widget(edge)
        self.edges = list()
        for edge in my_w.edges:
            x1, y1 = coordinate_vert_dict[edge[0]]
            x2, y2 = coordinate_vert_dict[edge[1]]
            kivy_edge = Edge([x1 + defalt_size // 2, y1 + defalt_size // 2,
                              x2 + defalt_size // 2, y2 + defalt_size // 2])
            self.edges.append(kivy_edge)
            self.add_widget(kivy_edge)

        for country in self.countries:
            # print(country)
            self.remove_widget(country)
        self.countries = list()
        for country in my_w.country_list:
            for vert in country.vertexes:
                cb = CircleButton(text=f'{vert.weight}',
                                  circle_color=country.color, font_size=25,
                                  pos=coordinate_vert_dict[vert.get_number()],
                                  size=(defalt_size, defalt_size))
                self.countries.append(cb)
                self.add_widget(cb)
コード例 #35
0
ファイル: main.py プロジェクト: Sergey-Shulnyaev/aviahacaton
class MapScreen(BaseScreen):
    def __init__(self, *args, **kwargs):
        super(MapScreen, self).__init__(*args, **kwargs)

        # Заголовок
        self.head = AviaLabel(size_hint=(.3, .1),
                              font_size=25,
                              pos_hint={
                                  'center_x': 0.15,
                                  'center_y': .95
                              })
        self.head.text = 'Карта'
        self.add_widget(self.head)

        # Окно поиска
        self.dropdown = DropDown()

        self.search = TextInput(
            multiline=False,
            size_hint=(1, 0.1),
            font_size=40,
            pos_hint={
                'center_x': .5,
                'center_y': .85
            },
            #on_text_validate=self.dropdown.open
        )
        self.search.bind(text=self.update_dropdown)
        #Действие в момент выбора
        #self.dropdown.bind(on_select=lambda instance, x: setattr(self.search, 'text', x))
        self.add_widget(self.search)

        # Карта
        self.airport = Image(source='airport.png',
                             size_hint=(1 * 4, 0.7 * 4),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .45
                             })
        self.add_widget(self.airport, 5)

        #Кнопка приближения
        self.plus_button = Button(text="+",
                                  size_hint=(None, None),
                                  size=(80, 80),
                                  pos=(Window.size[0] - 90,
                                       Window.size[1] * 0.2 + 90))
        self.plus_button.bind(on_release=self.big_map)
        self.add_widget(self.plus_button)
        #Кнопка отдаления
        self.minus_button = Button(text="-",
                                   size_hint=(None, None),
                                   size=(80, 80),
                                   pos=(Window.size[0] - 90,
                                        Window.size[1] * 0.2))
        self.minus_button.bind(on_release=self.small_map)
        self.add_widget(self.minus_button)

    def change(self, event):
        global mapp
        mapp.sm.current = 'flight'

    def update_dropdown(self, struct, mes):
        self.dropdown.dismiss()
        self.dropdown = DropDown()
        self.dropdown.max_height = Window.size[1] * 0.7

        #Здесь будет возвращаться список
        #Кнопки будут создавать маршрут уже до цели
        for index in range(40):
            btn = Button(text=f'{mes} %d' % index, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.dropdown.open(struct)

    def big_map(self, event):
        new_size = (self.airport.size_hint[0] * 1.1,
                    self.airport.size_hint[1] * 1.1)
        self.airport.size_hint = new_size
        print(self.airport.size_hint)

    def small_map(self, event):
        new_size = (self.airport.size_hint[0] * 0.9,
                    self.airport.size_hint[1] * 0.9)
        self.airport.size_hint = new_size
        print(self.airport.size_hint)
コード例 #36
0
class TxDialog(Factory.Popup):
    def __init__(self, app, tx):
        Factory.Popup.__init__(self)
        self.app = app  # type: ElectrumWindow
        self.wallet = self.app.wallet
        self.tx = tx  # type: Transaction
        self._action_button_fn = lambda btn: None
        self.dropdown = None

        # If the wallet can populate the inputs with more info, do it now.
        # As a result, e.g. we might learn an imported address tx is segwit,
        # or that a beyond-gap-limit address is is_mine.
        # note: this might fetch prev txs over the network.
        tx.add_info_from_wallet(self.wallet)

    def on_open(self):
        self.update()

    def update(self):
        raw_tx = str(self.tx)
        tx_type = tx_header_to_tx_type(bfh(raw_tx[:8]))
        if tx_type == 0:
            txid = self.tx.txid()
            tx_type, completed = self.wallet.db.get_ps_tx(txid)
        self.title = '%s %s' % (SPEC_TX_NAMES[tx_type], _('Transaction'))
        format_amount = self.app.format_amount_and_units
        tx_details = self.wallet.get_tx_info(self.tx)
        tx_mined_status = tx_details.tx_mined_status
        exp_n = tx_details.mempool_depth_bytes
        amount, fee = tx_details.amount, tx_details.fee
        self.status_str = tx_details.status
        self.description = tx_details.label
        self.can_broadcast = tx_details.can_broadcast
        self.tx_hash = tx_details.txid or ''
        islock = tx_details.islock
        timestamp = tx_mined_status.timestamp
        if not timestamp and islock:
            timestamp = islock
        if timestamp:
            self.date_label = _('Date')
            dttm = datetime.fromtimestamp(timestamp)
            self.date_str = dttm.isoformat(' ')[:-3]
        elif exp_n is not None:
            self.date_label = _('Mempool depth')
            self.date_str = _('{} from tip').format('%.2f MB' %
                                                    (exp_n / 1000000))
        else:
            self.date_label = ''
            self.date_str = ''

        self.can_sign = self.wallet.can_sign(self.tx)
        if amount is None:
            self.amount_str = _("Transaction unrelated to your wallet")
        elif amount > 0:
            self.is_mine = False
            self.amount_str = format_amount(amount)
        else:
            self.is_mine = True
            self.amount_str = format_amount(-amount)
        risk_of_burning_coins = (
            isinstance(self.tx, PartialTransaction) and self.can_sign
            and fee is not None and bool(
                self.wallet.get_warning_for_risk_of_burning_coins_as_fees(
                    self.tx)))
        if fee is not None and not risk_of_burning_coins:
            self.fee_str = format_amount(fee)
            fee_per_kb = fee / self.tx.estimated_size() * 1000
            self.feerate_str = self.app.format_fee_rate(fee_per_kb)
        else:
            self.fee_str = _('unknown')
            self.feerate_str = _('unknown')
        self.ids.output_list.update(self.tx.outputs())

        for dict_entry in self.ids.output_list.data:
            dict_entry['color'], dict_entry[
                'background_color'] = address_colors(self.wallet,
                                                     dict_entry['address'])

        self.can_remove_tx = tx_details.can_remove
        self.update_action_button()

    def update_action_button(self):
        action_button = self.ids.action_button
        options = (
            ActionButtonOption(text=_('Sign'),
                               func=lambda btn: self.do_sign(),
                               enabled=self.can_sign),
            ActionButtonOption(text=_('Broadcast'),
                               func=lambda btn: self.do_broadcast(),
                               enabled=self.can_broadcast),
            ActionButtonOption(text=_('Remove'),
                               func=lambda btn: self.remove_local_tx(),
                               enabled=self.can_remove_tx),
        )
        num_options = sum(map(lambda o: bool(o.enabled), options))
        # if no options available, hide button
        if num_options == 0:
            action_button.disabled = True
            action_button.opacity = 0
            return
        action_button.disabled = False
        action_button.opacity = 1

        if num_options == 1:
            # only one option, button will correspond to that
            for option in options:
                if option.enabled:
                    action_button.text = option.text
                    self._action_button_fn = option.func
        else:
            # multiple options. button opens dropdown which has one sub-button for each
            self.dropdown = DropDown()
            action_button.text = _('Options')
            self._action_button_fn = self.dropdown.open
            for option in options:
                if option.enabled:
                    btn = Button(text=option.text,
                                 size_hint_y=None,
                                 height='48dp')
                    btn.bind(on_release=option.func)
                    self.dropdown.add_widget(btn)

    def on_action_button_clicked(self):
        action_button = self.ids.action_button
        self._action_button_fn(action_button)

    def do_sign(self):
        if self.dropdown:
            self.dropdown.dismiss()
        self.app.protected(_("Sign this transaction?"), self._do_sign, ())

    def _do_sign(self, password):
        self.status_str = _('Signing') + '...'
        Clock.schedule_once(lambda dt: self.__do_sign(password), 0.1)

    def __do_sign(self, password):
        try:
            self.app.wallet.sign_transaction(self.tx, password)
        except InvalidPassword:
            self.app.show_error(_("Invalid PIN"))
        self.update()

    def do_broadcast(self):
        if self.dropdown:
            self.dropdown.dismiss()
        self.app.broadcast(self.tx)

    def show_qr(self):
        original_raw_tx = str(self.tx)
        qr_data = self.tx.to_qr_data()
        self.app.qr_dialog(_("Raw Transaction"),
                           qr_data,
                           text_for_clipboard=original_raw_tx)

    def remove_local_tx(self):
        if self.dropdown:
            self.dropdown.dismiss()
        txid = self.tx.txid()
        to_delete = {txid}
        to_delete |= self.wallet.get_depending_transactions(txid)
        question = _("Are you sure you want to remove this transaction?")
        if len(to_delete) > 1:
            question = (_(
                "Are you sure you want to remove this transaction and {} child transactions?"
            ).format(len(to_delete) - 1))

        def on_prompt(b):
            if b:
                for tx in to_delete:
                    self.wallet.remove_transaction(tx)
                self.wallet.save_db()
                self.app._trigger_update_wallet()  # FIXME private...
                self.dismiss()

        d = Question(question, on_prompt)
        d.open()

    def label_dialog(self):
        from .label_dialog import LabelDialog
        key = self.tx.txid()
        text = self.app.wallet.get_label_for_txid(key)

        def callback(text):
            self.app.wallet.set_label(key, text)
            self.update()
            self.app.history_screen.update()

        d = LabelDialog(_('Enter Transaction Label'), text, callback)
        d.open()
コード例 #37
0
class ItemViewer(Screen):
    todo = []  # Items that need action taken, taken from DepSelect.todo_deps
    thread_running = False
    todo_num = 0
    queue = []
    blank = (
        '',{
            'date': '',
            'desc': '',
            'ftype': '',
            'ghost': '',
            'img': 'none',
            'price': '',
            'upc': ''
        }
    )

    # Created a list with todo, last item is len-1
    # With a list it can be skipped through and returned into(object):
    def __init__(self, **kwargs):
        super(ItemViewer, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.build_layout()
        self.re_product(self.blank)

    def on_enter(self):
        info = DepSelect.todo_deps[self.app.selected_dep]
        self.todo = info['todo']
        self.hidden = info['hidden']
        self.todo_num = info['num']
        self.queue = info['queue']
        self.re_product(self.get_product())
        try:
            import admin
            importlib.reload(admin)
            admin.run(self)
            print('admin_user')
        except ModuleNotFoundError:
            pass

    def build_layout(self):
        #app.selected_dep
        lblbgc = (0.231, 0.647, 0.541, .8)  # blueish for text
        fgc = (0.752, 0.607, 0.349, 1)  # orangish for text
        bgc = (.90,.63,.47,.95)  # orangish on grey button
        #bgc2 = (.90,.63,.47,.2)
        # (.40,.23,.07,.95) # blueish back for label bg

        #fgc = (0.231, 0.647, 0.541, 1)
        
        #fgc=(1,1,1,1)

        
        self.dropdown = DropDown()

        self.hidebtn = Button(
            text='Hide This Item',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(None, None),
            width=Window.width,
            height=Window.height/8
        )
        self.hidebtn.bind(on_press=self.hide_item)
        self.dropdown.add_widget(self.hidebtn)

        self.change_depbtn = Button(
            text='Change Department',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(None, None),
            width=Window.width,
            height=Window.height/8
        )
        self.change_depbtn.bind(on_press=self.change_dep)
        self.dropdown.add_widget(self.change_depbtn)

        self.sign_outbtn = Button(
            text='Sign Out',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(None, None),
            width=Window.width,
            height=Window.height/8
        )
        self.sign_outbtn.bind(on_press=self.sign_out)
        self.dropdown.add_widget(self.sign_outbtn)

        self.menubtn = Button(
            text='Menu',
            font_size='30dp',
            size_hint=(.9, .05),
            color=fgc,
            background_color=bgc,
            pos_hint={'center_x':.5, 'center_y':.075}
        )
        self.menubtn.bind(on_release=self.dropdown.open)
        self.add_widget(self.menubtn)

        self.info=ColorLabel(
            color=fgc,
            font_size='25dp',
            size_hint=(.94, .05),
            pos_hint={'center_x':.5, 'center_y': .782}
        )
        self.info.set_bgcolor(.40,.23,.07,.95)
        self.add_widget(self.info)

        self.rightbtn = Button(
            text='>>',
            color=lblbgc,
            background_color=(.17,.34,.52,.3),
            font_size='55dp',
            size_hint=(.2, .48),
            pos_hint={'center_x': .9, 'center_y': .48}
        )
        self.rightbtn.bind(on_press=self.go_right)
        self.add_widget(self.rightbtn)

        self.leftbtn = Button(
            text='<<',
            color=lblbgc,
            background_color=(.17,.34,.52,.3),
            font_size='55dp',
            size_hint=(.2, .48),
            pos_hint={'center_x': .1, 'center_y': .48}
        )
        self.leftbtn.bind(on_press=self.go_left)
        self.add_widget(self.leftbtn)

        self.section_id = ColorLabel(
            color=lblbgc,
            pos_hint={'center_y': .832, 'center_x': .5},
            size_hint=(.96, .05),
            font_size='30dp'
        )
        self.section_id.set_bgcolor(.17,.34,.52,.3)
        self.add_widget(self.section_id)


        self.product_desc = ColorLabel(
            pos_hint={'center_x': .5, 'center_y': .96},
            font_size='23dp',  # used to be 30
            color=lblbgc,
            size_hint=(None, None),
            size=(Window.width, Window.height/9.5),
            halign='center'
        )
        self.product_desc.set_bgcolor(.17,.34,.52,.5)

        self.product_desc.text_size = self.product_desc.size
        self.add_widget(self.product_desc)


        self.img = AsyncImage(
            pos_hint={'center_x': .5, 'center_y': .5},
            size_hint=(.5, .5),
            allow_stretch=True
        )
        self.add_widget(self.img)
        self.product_upc = ColorLabel(
            size_hint=(.98, .05),
            color=lblbgc,
            pos_hint={'center_y': .882, 'center_x': .5},
            font_size='30dp',
            halign='left'
        )
        self.product_upc.set_bgcolor(.17,.34,.52,.4)
        self.add_widget(self.product_upc)
        self.mark_btn = Button(
            text='Marked',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(.35, .12),
            pos_hint={'center_x':.5, 'center_y':.17}
        )
        self.mark_btn.bind(on_press=self.marked)

        self.move_btn = Button(
            text='Moved',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(.35, .12),
            pos_hint={'center_x':.5, 'center_y':.17}
        )
        self.move_btn.bind(on_press=self.moved)

        self.marknmove_btn = Button(
            text='Marked &\nMoved',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(.35, .12),
            pos_hint={'center_x':.5, 'center_y':.17}
        )
        self.marknmove_btn.bind(on_press=self.marknmove)


        self.outstock_btn = Button(
            text='Out of\nStock',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(.33, .12),
            pos_hint={'center_x':.85, 'center_y':.17}
        )
        self.outstock_btn.bind(on_press=self.oos)
        self.add_widget(self.outstock_btn)

        self.date_btn = Button(
            text='New\nDate',
            color=fgc,
            background_color=bgc,
            font_size='30dp',
            size_hint=(.33, .12),
            pos_hint={'center_x':.15, 'center_y':.17}
        )
        self.date_btn.bind(on_press=self.open_keyboard)
        self.add_widget(self.date_btn)

    def pre_load_next_images(self, num):
        try:
            img = self.todo[num+1][1]['img']
            if img != 'none':
                AsyncImage(source=img)
        except IndexError:
            pass

    def re_product(self, product, *dt):
        self.pr = product
        self.pre_load_next_images(self.todo_num)
        self.product_desc.text=self.pr[1]['desc']  # desc
        ftype = self.pr[1]['ftype']  # ftype
        self.remove_widget(self.mark_btn)
        self.remove_widget(self.move_btn)
        self.remove_widget(self.marknmove_btn)
        if ftype == 'oos':
            fmsg = 'Enter a date for this item?'
        elif ftype == 'mark':
            self.add_widget(self.mark_btn)
            fmsg = 'Mark this item?'
        elif ftype == 'move':
            self.add_widget(self.move_btn)
            fmsg = 'Move this item?'
        elif ftype == 'ood':
            fmsg = 'Out of Date?'
        elif ftype == 'movenmark':
            self.add_widget(self.marknmove_btn)
            fmsg = 'Mark & Move?'
        else:
            fmsg = 'None'
          
        self.info.text=("Date: %s  %s"
            % (self.pr[1]['date'], fmsg))  # date / action
        
        word = self.pr[0] 
        new_word = (word[0:3]+' - '+word[3:6]+' - '+word[6::])
        self.section_id.text = new_word

        if self.pr[1]['img'] == 'none':
            self.img.color = [1, 1, 1, 0]
        else:
            self.img.color = [1, 1, 1, 1]
            self.img.source=self.pr[1]['img']  # img
        
        self.product_upc.text=self.pr[1]['upc']  # upc

    def change_dep(self, event):
        if self.thread_running:
            Clock.schedule_once(self.change_dep, .1)
        else:
            DepSelect.todo_deps[ self.app.selected_dep ]['queue'] = copy.deepcopy(self.queue)
            self.queue = []
            self.dropdown.dismiss()
            self.re_product(self.blank)
            DepSelect.todo_deps[ self.app.selected_dep ]['num'] = self.todo_num
            sm.current = 'dep_select'
    
    def sign_out(self, event):
        global sm
        self.dropdown.dismiss()
        for i in sm.screens:
            sm.remove_widget(i)
        sm.add_widget(Login(name='login'))
        sm.current = 'login'

    def marked(self, event):
        self.mfuncs()

    def moved(self, event):
        self.mfuncs()

    def marknmove(self, event):
        self.mfuncs()        

    def mfuncs(self):
        self.send_pr = self.pr
        t = Thread(target=self.post_item,
                         args=(self.send_pr, self.todo_num))
        t.daemon = True
        t.start()
        self.next_item()

    def oos(self, event):
        self.send_pr = self.pr
        if self.pr[1]['ftype'] == 'oos':
            self.next_item()
        else:
            self.send_pr[1]['ftype'] = 'oos'
            t = Thread(target=self.post_item,
                         args=(self.send_pr, self.todo_num))
            t.daemon = True
            t.start()
            self.next_item()

    def send_date(self, pr, date, *args):
        self.send_pr = pr
        self.send_pr[1]['date'] = date
        self.send_pr[1]['ftype'] = 'new_date'
        self.thread_running = True
        self.next_item()
        t = Thread(target=self.post_item,
                         args=(self.send_pr, self.todo_num))
        t.daemon = True
        t.start()

    def hide_item(self, event):
        self.send_pr = self.pr
        self.send_pr[1]['ftype'] = 'hide'
        t = Thread(target=self.post_item,
                        args=(self.send_pr, self.todo_num))
        t.daemon = True
        t.start()
        self.next_item()

    def post_item(self, *args):
        self.thread_running = True
        print("args", args)
        try:
            try:
                ftype = None
                pr = args[0]
                req = self.app.db.post_item(pr)
                if req.ok:
                    try:
                        ftype = req.json()['ftype']  # Possible breakpoint
                        pr[1]['ftype'] = ftype
                        if ftype == 'ok':
                            self.app.department_list[self.app.selected_dep]['todo_count'] -= 1
                        elif ftype == 'oos':
                            pr[1]['date'] = '0'
                        else:
                            self.queue.append(pr)
                    except KeyError as e:
                        print(e)
                        TroublePop("Trouble connecting", partial(self.post_item, args[0], args[1])).open()
                else:
                    TroublePop("Trouble connecting", partial(self.post_item, args[0], args[1])).open()
                
            except requests.exceptions.ConnectionError:
                TroublePop("Trouble connecting", partial(self.post_item, args[0], args[1])).open()
        except Exception:
            app = App.get_running_app()
            app.fb.capture_bug(format_exc(), app.id_token)
            print('ERROR IN THREAD\n\nERROR IN THREAD')
        self.thread_running = False

    def open_keyboard(self, event):
        self.app.date_keyboard.open(partial(self.send_date, self.pr))

    def go_left(self, *event):
        if self.todo_num >= 1:
            self.todo_num-=1
            self.re_product(self.get_product())
        else:
            return False

    def go_right(self, event):
        self.next_item()

    def next_item(self, *dt):
        print(self.app.local_id)
        # where to deal with queue
        print('length of todo', len(self.todo))
        if self.queue:
            print("There's a queue!")
            # Calling reproduct to build the screen
            self.re_product(self.todo[self.todo.index(self.queue.pop())])
        else:
            if (self.todo_num + 1) == len(self.todo):
                # Reached end
                # Wait for thread to finish
                if self.thread_running:
                    self.pr=('', {'desc': '', 'ftype': '', 'date': '', 'img': ''})
                    self.product_desc.text=''  # desc
                    self.info.text=''
                    self.section_id.text=''
                    self.product_upc.text=''
                    self.remove_widget(self.mark_btn)
                    self.remove_widget(self.move_btn)
                    self.remove_widget(self.marknmove_btn)
                    self.img.color = [1, 1, 1, 0]
                    Clock.schedule_once(self.next_item, 1)
                else:
                    self.todo_num = 0
                    Clock.schedule_once(partial(self.re_product, self.get_product()), .1)
                    
                    sm.current = 'dep_select'
            else:
                self.todo_num += 1
                self.re_product(self.get_product())

    def back_pressed(self):
        if self.go_left() == False:
            sm.current = 'dep_select'

    def get_product(self):
        try:
            return self.todo[self.todo_num]
        except IndexError:
            self.todo_num = 0
            return self.todo[0]