Exemplo n.º 1
0
    def _get(params: Dict[str, Any],
             key: str,
             allowed_types: Optional[Union[Type, str, List[Type],
                                           Tuple[Type, ...]]] = None,
             default: Any = None) -> Any:
        """
        Return a value from a dictionary.

        Custom types (str)
            -   alignment           – pygame-menu alignment (locals)
            -   callable            – Is callable type, same as ``"function"``
            -   color               – Check color
            -   color_image         – Color or :py:class:`pygame_menu.baseimage.BaseImage`
            -   color_image_none    – Color, :py:class:`pygame_menu.baseimage.BaseImage`, or None
            -   color_none          – Color or None
            -   cursor              – Cursor object (pygame)
            -   font                – Font type
            -   image               – Value must be ``BaseImage``
            -   none                – None only
            -   position            – pygame-menu position (locals)
            -   position_vector     – pygame-menu position (str or vector)
            -   tuple2              – Only valid numeric tuples ``(x, y)`` or ``[x, y]``
            -   tuple2int           – Only valid integer tuples ``(x, y)`` or ``[x, y]``
            -   tuple3              – Only valid numeric tuples ``(x, y, z)`` or ``[x, y, z]``
            -   tuple3int           – Only valid integer tuples ``(x, y, z)`` or ``[x, y, z]``
            -   type                – Type-class (bool, str, etc...)

        :param params: Parameters dictionary
        :param key: Key to look for
        :param allowed_types: List of allowed types
        :param default: Default value to return
        :return: The value associated to the key
        """
        value = params.pop(key, default)
        if allowed_types is not None:
            other_types = []  # Contain other types to check from
            if not isinstance(allowed_types, VectorInstance):
                allowed_types = (allowed_types, )
            for val_type in allowed_types:

                if val_type == 'alignment':
                    assert_alignment(value)

                elif val_type == callable or val_type == 'function' or val_type == 'callable':
                    assert is_callable(value), \
                        'value must be callable type'

                elif val_type == 'color':
                    value = assert_color(value)

                elif val_type == 'color_image':
                    if not isinstance(value, BaseImage):
                        value = assert_color(value)

                elif val_type == 'color_image_none':
                    if not (value is None or isinstance(value, BaseImage)):
                        value = assert_color(value)

                elif val_type == 'color_none':
                    if value is not None:
                        value = assert_color(value)

                elif val_type == 'cursor':
                    assert_cursor(value)

                elif val_type == 'font':
                    assert_font(value)

                elif val_type == 'image':
                    assert isinstance(value, BaseImage), \
                        'value must be BaseImage type'

                elif val_type == 'none':
                    assert value is None

                elif val_type == 'position':
                    assert_position(value)

                elif val_type == 'position_vector':
                    assert_position_vector(value)

                elif val_type == 'type':
                    assert isinstance(value, type), \
                        'value is not type-class'

                elif val_type == 'tuple2':
                    assert_vector(value, 2)

                elif val_type == 'tuple2int':
                    assert_vector(value, 2, int)

                elif val_type == 'tuple3':
                    assert_vector(value, 3)

                elif val_type == 'tuple3int':
                    assert_vector(value, 3, int)

                else:  # Unknown type
                    assert isinstance(val_type, type), \
                        'allowed type "{0}" is not a type-class'.format(val_type)
                    other_types.append(val_type)

            # Check other types
            if len(other_types) > 0:
                others = tuple(other_types)
                assert isinstance(value, others), \
                    'Theme.{} type shall be in {} types (got {})'.format(key, others, type(value))

        return value
Exemplo n.º 2
0
    def validate(self) -> 'Theme':
        """
        Validate the values of the theme. If there's a invalid parameter throws an
        ``AssertionError``.

        This function also converts all lists to tuples. This is done because lists
        are mutable.

        :return: Self reference
        """
        if self._disable_validation:
            return self

        # Boolean asserts
        assert isinstance(self.scrollbar_shadow, bool)
        assert isinstance(self.title_bar_modify_scrollarea, bool)
        assert isinstance(self.title_close_button, bool)
        assert isinstance(self.title_font_antialias, bool)
        assert isinstance(self.title_font_shadow, bool)
        assert isinstance(self.widget_font_antialias, bool)
        assert isinstance(self.widget_font_background_color_from_menu, bool)
        assert isinstance(self.widget_font_shadow, bool)

        # Value type checks
        assert_alignment(self.widget_alignment)
        assert_cursor(self.scrollbar_cursor)
        assert_cursor(self.title_close_button_cursor)
        assert_cursor(self.widget_cursor)
        assert_font(self.title_font)
        assert_font(self.widget_font)
        assert_position(self.scrollbar_shadow_position)
        assert_position(self.title_font_shadow_position)
        assert_position(self.widget_font_shadow_position)
        assert_position_vector(self.widget_border_position)

        assert _check_menubar_style(self.title_bar_style)
        assert get_scrollbars_from_position(
            self.scrollarea_position) is not None

        # Check selection effect if None
        if self.widget_selection_effect is None:
            self.widget_selection_effect = NoneSelection()

        assert isinstance(self.cursor_switch_ms, NumberInstance)
        assert isinstance(self.fps, NumberInstance)
        assert isinstance(self.scrollbar_shadow_offset, int)
        assert isinstance(self.scrollbar_slider_pad, NumberInstance)
        assert isinstance(self.scrollbar_thick, int)
        assert isinstance(self.title, bool)
        assert isinstance(self.title_fixed, bool)
        assert isinstance(self.title_floating, bool)
        assert isinstance(self.title_font_shadow_offset, int)
        assert isinstance(self.title_font_size, int)
        assert isinstance(self.title_updates_pygame_display, bool)
        assert isinstance(self.widget_background_inflate_to_selection, bool)
        assert isinstance(self.widget_border_width, int)
        assert isinstance(self.widget_box_border_width, int)
        assert isinstance(self.widget_font_shadow_offset, int)
        assert isinstance(self.widget_font_size, int)
        assert isinstance(self.widget_padding, PaddingInstance)
        assert isinstance(self.widget_selection_effect, Selection)
        assert isinstance(self.widget_tab_size, int)

        # Format colors, this converts all color lists to tuples automatically,
        # if image, return the same object
        self.background_color = self._format_color_opacity(
            self.background_color)
        self.cursor_color = self._format_color_opacity(self.cursor_color)
        self.cursor_selection_color = self._format_color_opacity(
            self.cursor_selection_color)
        self.focus_background_color = self._format_color_opacity(
            self.focus_background_color)
        self.readonly_color = self._format_color_opacity(self.readonly_color)
        self.readonly_selected_color = self._format_color_opacity(
            self.readonly_selected_color)
        self.scrollbar_color = self._format_color_opacity(self.scrollbar_color)
        self.scrollbar_shadow_color = self._format_color_opacity(
            self.scrollbar_shadow_color)
        self.scrollbar_slider_color = self._format_color_opacity(
            self.scrollbar_slider_color)
        self.scrollbar_slider_hover_color = self._format_color_opacity(
            self.scrollbar_slider_hover_color)
        self.selection_color = self._format_color_opacity(self.selection_color)
        self.surface_clear_color = self._format_color_opacity(
            self.surface_clear_color)
        self.title_background_color = self._format_color_opacity(
            self.title_background_color)
        self.title_close_button_background_color = self._format_color_opacity(
            self.title_close_button_background_color)
        self.title_font_color = self._format_color_opacity(
            self.title_font_color)
        self.title_font_shadow_color = self._format_color_opacity(
            self.title_font_shadow_color)
        self.widget_background_color = self._format_color_opacity(
            self.widget_background_color, none=True)
        self.widget_border_color = self._format_color_opacity(
            self.widget_border_color)
        self.widget_box_arrow_color = self._format_color_opacity(
            self.widget_box_arrow_color)
        self.widget_box_background_color = self._format_color_opacity(
            self.widget_box_background_color)
        self.widget_box_border_color = self._format_color_opacity(
            self.widget_box_border_color)
        self.widget_font_background_color = self._format_color_opacity(
            self.widget_font_background_color, none=True)
        self.widget_font_color = self._format_color_opacity(
            self.widget_font_color)
        self.widget_font_shadow_color = self._format_color_opacity(
            self.widget_font_shadow_color)
        self.widget_url_color = self._format_color_opacity(
            self.widget_url_color)

        # List to tuple
        self.scrollarea_outer_margin = self._vec_to_tuple(
            self.scrollarea_outer_margin, 2, NumberInstance)
        self.title_offset = self._vec_to_tuple(self.title_offset, 2,
                                               NumberInstance)
        self.widget_background_inflate = self._vec_to_tuple(
            self.widget_background_inflate, 2, int)
        self.widget_border_inflate = self._vec_to_tuple(
            self.widget_border_inflate, 2, int)
        self.widget_box_arrow_margin = self._vec_to_tuple(
            self.widget_box_arrow_margin, 3, int)
        self.widget_box_inflate = self._vec_to_tuple(self.widget_box_inflate,
                                                     2, int)
        self.widget_box_margin = self._vec_to_tuple(self.widget_box_margin, 2,
                                                    NumberInstance)
        self.widget_margin = self._vec_to_tuple(self.widget_margin, 2,
                                                NumberInstance)
        if isinstance(self.widget_padding, VectorInstance):
            self.widget_padding = self._vec_to_tuple(self.widget_padding)
            assert 2 <= len(self.widget_padding) <= 4, \
                'widget padding tuple length must be 2, 3 or 4'
            for p in self.widget_padding:
                assert isinstance(p, NumberInstance), \
                    'each padding element must be numeric (integer or float)'
                assert p >= 0, \
                    'all padding elements must be equal or greater than zero'
        else:
            assert self.widget_padding >= 0, 'padding cannot be a negative number'
        self.widget_offset = self._vec_to_tuple(self.widget_offset, 2,
                                                NumberInstance)

        # Check sizes
        assert self.scrollarea_outer_margin[0] >= 0 and self.scrollarea_outer_margin[1] >= 0, \
            'scroll area outer margin must be equal or greater than zero on both axis'
        assert self.widget_offset[0] >= 0 and self.widget_offset[1] >= 0, \
            'widget offset must be equal or greater than zero'
        assert self.widget_background_inflate[0] >= 0 and self.widget_background_inflate[1] >= 0, \
            'widget background inflate must be equal or greater than zero on both axis'
        assert self.widget_border_inflate[0] >= 0 and self.widget_border_inflate[1] >= 0, \
            'widget border inflate must be equal or greater than zero on both axis'
        assert self.widget_box_inflate[0] >= 0 and self.widget_box_inflate[1] >= 0, \
            'widget box inflate inflate must be equal or greater than zero on both axis'

        assert self.cursor_switch_ms > 0, 'cursor switch ms must be greater than zero'
        assert self.fps >= 0, 'fps must be equal or greater than zero'
        assert self.scrollbar_shadow_offset > 0, 'scrollbar shadow offset must be greater than zero'
        assert self.scrollbar_slider_pad >= 0, 'slider pad must be equal or greater than zero'
        assert self.scrollbar_thick > 0, 'scrollbar thickness must be greater than zero'
        assert self.title_font_size > 0, 'title font size must be greater than zero'
        assert self.widget_border_width >= 0, 'widget border width must be equal or greater than zero'
        assert self.widget_box_border_width >= 0, 'widget border box width must be equal or greater than zero'
        assert self.widget_font_shadow_offset > 0, 'widget font shadow offset must be greater than zero'
        assert self.widget_font_size > 0, 'widget font size must be greater than zero'
        assert self.widget_tab_size >= 0, 'widget tab size must be equal or greater than zero'

        # Color asserts
        assert self.focus_background_color[3] != 0, \
            'focus background color cannot be fully transparent, suggested opacity between 1 and 255'

        return self
Exemplo n.º 3
0
    def update_cell_style(
        self,
        column: Union[int, Vector2IntType],
        row: Union[int, Vector2IntType],
        align: Optional[str] = None,
        background_color: Optional[ColorInputType] = None,
        border_color: Optional[ColorInputType] = None,
        border_position: Optional[WidgetBorderPositionType] = None,
        border_width: Optional[int] = None,
        font: Optional[FontType] = None,
        font_color: Optional[ColorInputType] = None,
        font_size: Optional[int] = None,
        padding: Optional[PaddingType] = None,
        vertical_position: Optional[str] = None
    ) -> Union['Widget', List['Widget']]:
        """
        Update cell style. If a parameter is ``None`` the default cell property
        will be used.

        :param column: Cell column position (counting from 1). If -1 update all column from the given row. Also, a 2-item list/tuple is accepted (from, to), ``to=-1`` is also accepted (last)
        :param row: Cell row position (counting from 1). If ``-1`` update all rows from the given column. Also, a 2-item list/tuple is accepted (from, to), ``to=-1`` is also accepted (last)
        :param align: Horizontal align of each cell. See :py:mod:`pygame_menu.locals`
        :param background_color: Background color
        :param border_color: Border color of each cell
        :param border_position: Border position of each cell. Valid only: north, south, east, and west. See :py:mod:`pygame_menu.locals`
        :param border_width: Border width in px of each cell
        :param font: Font name or path
        :param font_color: Font color
        :param font_size: Font size
        :param padding: Cell padding according to CSS rules. General shape: (top, right, bottom, left)
        :param vertical_position: Vertical position of each cell. Only valid: north, center, and south. See :py:mod:`pygame_menu.locals`
        :return: Cell widget
        """
        if row == -1 or isinstance(row, VectorInstance):
            max_rows = len(self._rows)
            if row == -1:
                row = []
                for i in range(max_rows):
                    row.append(i + 1)
            else:
                assert_vector(row, 2, int)
                row_k = list(row)
                if row_k[1] == -1:
                    row_k[1] = len(self._rows)
                assert 1 <= row_k[0] <= row_k[1] <= max_rows, \
                    f'(from, to) of rows vector must be increasing and between 1-{max_rows}'
                row = [row_k[0]]
                for i in range(row_k[1] - row_k[0]):
                    row.append(row_k[0] + (i + 1))
            if isinstance(column, VectorInstance) and column != [1, -1]:
                assert self.is_rectangular(), \
                    f'only rectangular tables (same number of columns for each row) ' \
                    f'accept a variable column different than -1 or [1, -1], but ' \
                    f'received "{column}"'
            updated_wid = []
            for i in row:
                w = self.update_cell_style(column=column,
                                           row=i,
                                           align=align,
                                           background_color=background_color,
                                           border_color=border_color,
                                           border_position=border_position,
                                           border_width=border_width,
                                           font=font,
                                           font_color=font_color,
                                           font_size=font_size,
                                           padding=padding,
                                           vertical_position=vertical_position)
                if not isinstance(w, list):
                    w = [w]
                for k in w:
                    updated_wid.append(k)
            return updated_wid
        if column == -1 or isinstance(column, VectorInstance):
            assert isinstance(row, int) and 1 <= row <= len(self._rows), \
                f'row index ({row}) cannot exceed the number of rows ({len(self._rows)})'
            max_columns = self._rows[row - 1].get_total_packed()
            if column == -1:
                column = []
                for i in range(max_columns):
                    column.append(i + 1)
            else:
                assert_vector(column, 2, int)
                column_k = list(column)
                if column_k[1] == -1:
                    column_k[1] = max_columns
                assert 1 <= column_k[0] <= column_k[1] <= max_columns, \
                    f'(from, to) of column vector must be increasing and between 1-{max_columns} for row {row}'
                column = [column_k[0]]
                for i in range(column_k[1] - column_k[0]):
                    column.append(column_k[0] + (i + 1))
            updated_wid = []
            for i in column:
                w = self.update_cell_style(column=i,
                                           row=row,
                                           align=align,
                                           background_color=background_color,
                                           border_color=border_color,
                                           border_position=border_position,
                                           border_width=border_width,
                                           font=font,
                                           font_color=font_color,
                                           font_size=font_size,
                                           padding=padding,
                                           vertical_position=vertical_position)
                if not isinstance(w, list):
                    w = [w]
                for k in w:
                    updated_wid.append(k)
            return updated_wid
        cell = self.get_cell(column, row)
        r = self._rows[row - 1]

        if align is None:
            align = cell.get_attribute('align')
        if background_color is None:
            background_color = cell.get_attribute('background_color')
        if border_color is None:
            border_color = cell.get_attribute('border_color')
        if border_position is None:
            border_position = cell.get_attribute('border_position')
        if border_width is None:
            border_width = cell.get_attribute('border_width')
        if padding is None:
            padding = cell.get_attribute('padding')
        if vertical_position is None:
            vertical_position = cell.get_attribute('vertical_position')

        self._check_cell_style(align=align,
                               background_color=background_color,
                               border_color=border_color,
                               border_position=border_position,
                               border_width=border_width,
                               padding=padding,
                               vertical_position=vertical_position)
        if background_color is not None:
            background_color = assert_color(background_color)
        if border_color is not None:
            border_color = assert_color(border_color)
        padding = parse_padding(padding)

        # Update background color
        if background_color != r._background_color:
            cell.set_background_color(background_color)
        else:
            cell.set_background_color(None)

        # Update font
        if font_color is None:
            font_color = cell._font_color
        assert_color(font_color)
        if font is None:
            font = cell._font_name
        assert_font(font)
        if font_size is None:
            font_size = cell._font_size

        try:
            cell.update_font({'color': font_color, 'name': font})
        except AssertionError:
            pass

        try:
            if isinstance(font_size, int) and font_size > 0:
                cell.update_font({'size': font_size})
        except AssertionError:
            pass

        if isinstance(border_position, str):
            border_position = [border_position]

        # Update cell
        cell.set_attribute('align', align)
        cell.set_attribute('background_color', background_color)
        cell.set_attribute('border_color', border_color)
        cell.set_attribute('border_position', border_position)
        cell.set_attribute('border_width', border_width)
        cell.set_attribute('padding', padding)
        cell.set_attribute('vertical_position', vertical_position)

        self._update_row_sizing()
        self._render()
        self.force_menu_surface_update()
        return cell
Exemplo n.º 4
0
    def _filter_widget_attributes(self, kwargs: Dict) -> Dict[str, Any]:
        attributes = {}

        # align
        align = kwargs.pop('align', self._theme.widget_alignment)
        assert isinstance(align, str)
        attributes['align'] = align

        # background_color
        background_is_color = False
        background_color = kwargs.pop('background_color',
                                      self._theme.widget_background_color)
        if background_color is not None:
            if isinstance(background_color, pygame_menu.BaseImage):
                pass
            else:
                background_color = assert_color(background_color)
                background_is_color = True
        attributes['background_color'] = background_color

        # background_inflate
        background_inflate = kwargs.pop('background_inflate',
                                        self._theme.widget_background_inflate)
        if background_inflate == 0:
            background_inflate = (0, 0)
        assert_vector(background_inflate, 2, int)
        assert background_inflate[0] >= 0 and background_inflate[1] >= 0, \
            'both background inflate components must be equal or greater than zero'
        attributes['background_inflate'] = background_inflate

        # border_color
        border_color = kwargs.pop('border_color',
                                  self._theme.widget_border_color)
        if border_color is not None:
            border_color = assert_color(border_color)
        attributes['border_color'] = border_color

        # border_inflate
        border_inflate = kwargs.pop('border_inflate',
                                    self._theme.widget_border_inflate)
        if border_inflate == 0:
            border_inflate = (0, 0)
        assert_vector(border_inflate, 2, int)
        assert isinstance(border_inflate[0], int) and border_inflate[0] >= 0
        assert isinstance(border_inflate[1], int) and border_inflate[1] >= 0
        attributes['border_inflate'] = border_inflate

        # border_position
        border_position = kwargs.pop('border_position',
                                     self._theme.widget_border_position)
        assert_position_vector(border_position)
        attributes['border_position'] = border_position

        # border_width
        border_width = kwargs.pop('border_width',
                                  self._theme.widget_border_width)
        assert isinstance(border_width, int) and border_width >= 0
        attributes['border_width'] = border_width

        # cursor
        cursor = kwargs.pop('cursor', self._theme.widget_cursor)
        assert_cursor(cursor)
        attributes['cursor'] = cursor

        # floating status
        float_ = kwargs.pop('float', False)
        assert isinstance(float_, bool)
        attributes['float'] = float_
        float_origin_position = kwargs.pop('float_origin_position', False)
        assert isinstance(float_origin_position, bool)
        attributes['float_origin_position'] = float_origin_position

        # font_antialias
        attributes['font_antialias'] = self._theme.widget_font_antialias

        # font_background_color
        font_background_color = kwargs.pop(
            'font_background_color', self._theme.widget_font_background_color)
        if font_background_color is None and \
                self._theme.widget_font_background_color_from_menu and \
                not background_is_color:
            if not isinstance(self._theme.background_color,
                              pygame_menu.BaseImage):
                font_background_color = assert_color(
                    self._theme.background_color)
        attributes['font_background_color'] = font_background_color

        # font_color
        font_color = kwargs.pop('font_color', self._theme.widget_font_color)
        attributes['font_color'] = assert_color(font_color)

        # font_name
        font_name = kwargs.pop('font_name', self._theme.widget_font)
        assert_font(font_name)
        attributes['font_name'] = font_name

        # font_shadow
        font_shadow = kwargs.pop('font_shadow', self._theme.widget_font_shadow)
        assert isinstance(font_shadow, bool)
        attributes['font_shadow'] = font_shadow

        # font_shadow_color
        font_shadow_color = kwargs.pop('font_shadow_color',
                                       self._theme.widget_font_shadow_color)
        attributes['font_shadow_color'] = assert_color(font_shadow_color)

        # font_shadow_offset
        font_shadow_offset = kwargs.pop('font_shadow_offset',
                                        self._theme.widget_font_shadow_offset)
        assert isinstance(font_shadow_offset, int)
        attributes['font_shadow_offset'] = font_shadow_offset

        # font_shadow_position
        font_shadow_position = kwargs.pop(
            'font_shadow_position', self._theme.widget_font_shadow_position)
        assert isinstance(font_shadow_position, str)
        attributes['font_shadow_position'] = font_shadow_position

        # font_size
        font_size = kwargs.pop('font_size', self._theme.widget_font_size)
        assert isinstance(font_size, int)
        assert font_size > 0, 'font size must be greater than zero'
        attributes['font_size'] = font_size

        # margin
        margin = kwargs.pop('margin', self._theme.widget_margin)
        if margin == 0:
            margin = (0, 0)
        assert_vector(margin, 2)
        attributes['margin'] = margin

        # padding
        padding = kwargs.pop('padding', self._theme.widget_padding)
        assert isinstance(padding, PaddingInstance)
        attributes['padding'] = padding

        # readonly_color
        readonly_color = kwargs.pop('readonly_color',
                                    self._theme.readonly_color)
        attributes['readonly_color'] = assert_color(readonly_color)

        # readonly_selected_color
        readonly_selected_color = kwargs.pop(
            'readonly_selected_color', self._theme.readonly_selected_color)
        attributes['readonly_selected_color'] = assert_color(
            readonly_selected_color)

        # selection_color
        selection_color = kwargs.pop('selection_color',
                                     self._theme.selection_color)
        attributes['selection_color'] = assert_color(selection_color)

        # selection_effect
        selection_effect = kwargs.pop('selection_effect',
                                      self._theme.widget_selection_effect)
        if selection_effect is None:
            selection_effect = pygame_menu.widgets.NoneSelection()
        else:
            selection_effect = selection_effect.copy()
        assert isinstance(selection_effect, pygame_menu.widgets.core.Selection)

        selection_effect.set_color(attributes['selection_color'])
        attributes['selection_effect'] = selection_effect

        # shadow
        attributes['shadow_aa'] = kwargs.pop('shadow_aa',
                                             self._theme.widget_shadow_aa)
        attributes['shadow_color'] = kwargs.pop(
            'shadow_color', self._theme.widget_shadow_color)
        attributes['shadow_radius'] = kwargs.pop(
            'shadow_radius', self._theme.widget_shadow_radius)
        attributes['shadow_type'] = kwargs.pop('shadow_type',
                                               self._theme.widget_shadow_type)
        attributes['shadow_width'] = kwargs.pop(
            'shadow_width', self._theme.widget_shadow_width)

        # tab_size
        attributes['tab_size'] = kwargs.pop('tab_size',
                                            self._theme.widget_tab_size)

        return attributes
Exemplo n.º 5
0
    def __init__(self,
                 title: Any,
                 toggleswitch_id: str = '',
                 default_state: int = 0,
                 infinite: bool = False,
                 onchange: CallbackType = None,
                 onselect: CallbackType = None,
                 slider_color: ColorInputType = (255, 255, 255),
                 slider_height_factor: NumberType = 1,
                 slider_thickness: int = 25,
                 slider_vmargin: NumberType = 0,
                 state_color: Tuple[ColorInputType,
                                    ...] = ((178, 178, 178), (117, 185, 54)),
                 state_text: Tuple[str, ...] = ('Off', 'On'),
                 state_text_font: Optional[FontType] = None,
                 state_text_font_color: Tuple[ColorInputType,
                                              ...] = ((255, 255, 255),
                                                      (255, 255, 255)),
                 state_text_font_size: Optional[int] = None,
                 state_text_position: Tuple2NumberType = (0.5, 0.5),
                 state_values: Tuple[Any, ...] = (False, True),
                 state_width: Union[Tuple[int, ...], int] = 150,
                 switch_border_color: ColorInputType = (40, 40, 40),
                 switch_border_width: int = 1,
                 switch_height: NumberType = 1.25,
                 switch_margin: Tuple2NumberType = (25, 0),
                 *args,
                 **kwargs) -> None:
        super(ToggleSwitch, self).__init__(args=args,
                                           kwargs=kwargs,
                                           onchange=onchange,
                                           onselect=onselect,
                                           title=title,
                                           widget_id=toggleswitch_id)

        # Asserts
        assert isinstance(default_state, int)
        assert isinstance(state_values, tuple)
        assert isinstance(infinite, bool)

        self._total_states = len(state_values)
        assert 2 <= self._total_states, 'the minimum number of states is 2'
        assert 0 <= default_state < self._total_states, 'invalid default state value'

        if state_text_font is not None:
            assert_font(state_text_font)
        assert isinstance(state_text_font_size, (int, type(None)))
        if state_text_font_size is not None:
            assert state_text_font_size > 0, 'state text font size must be equal or greater than zero'

        assert_vector(state_text_position, 2)
        switch_border_color = assert_color(switch_border_color)
        assert isinstance(switch_border_width, int) and switch_border_width >= 0, \
            'border width must be equal or greater than zero'
        slider_color = assert_color(slider_color)

        assert slider_height_factor > 0, 'slider height factor cannot be negative'
        assert slider_thickness >= 0, 'slider thickness cannot be negative'
        assert isinstance(slider_vmargin, NumberInstance)
        assert_vector(switch_margin, 2)
        assert isinstance(switch_height, NumberInstance) and switch_height > 0, \
            'switch height factor cannot be zero or negative'
        assert isinstance(state_color,
                          tuple) and len(state_color) == self._total_states

        new_state_color = []
        for c in state_color:
            new_state_color.append(assert_color(c))
        state_color = tuple(new_state_color)

        assert isinstance(state_text,
                          tuple) and len(state_text) == self._total_states
        for c in state_text:
            assert isinstance(c, str), 'all states text must be string-type'
        assert isinstance(
            state_text_font_color,
            tuple) and len(state_text_font_color) == self._total_states

        new_state_text_font_color = []
        for c in state_text_font_color:
            new_state_text_font_color.append(assert_color(c))
        state_text_font_color = tuple(new_state_text_font_color)

        self._switch_width = 0
        if isinstance(state_width, NumberInstance):
            state_width = [state_width]
        assert_vector(state_width, self._total_states - 1, int)

        for i in range(len(state_width)):
            assert isinstance(state_width[i],
                              int), 'each state width must be an integer'
            assert state_width[
                i] > 0, 'each state width must be greater than zero'
            self._switch_width += state_width[i]

        # Store properties
        self._switch_border_color = switch_border_color
        self._switch_border_width = switch_border_width
        self._infinite = infinite
        self._slider_color = slider_color
        self._slider_height_factor = slider_height_factor
        self._slider_thickness = slider_thickness
        self._slider_vmargin = slider_vmargin
        self._state = default_state
        self._state_color = state_color
        self._state_text = state_text
        self._state_text_font = state_text_font
        self._state_text_font_color = state_text_font_color
        self._state_text_font_size = state_text_font_size
        self._state_text_position = state_text_position
        self._state_values = state_values
        self._state_width = state_width
        self._switch_height_factor = float(switch_height)
        self._switch_margin = switch_margin

        # Compute state width accum
        self._state_width_accum = [0]
        accum = 0
        for w in self._state_width:
            accum += w
            self._state_width_accum.append(accum - self._slider_thickness -
                                           2 * self._switch_border_width)

        # Inner properties
        self._slider_height = 0
        self._slider_pos = (0, 0)  # to add to (rect.x, rect.y)
        self._state_font = None
        self._switch_font_rendered = []  # Stores font render for each state
        self._switch_height = 0
        self._switch_pos = (0, 0)  # horizontal pos, and delta to title
Exemplo n.º 6
0
    def __init__(
            self,
            title: Any,
            progressbar_id: str = '',
            default: NumberType = 0,
            width: int = 150,
            onselect: CallbackType = None,
            box_background_color: ColorInputType = (255, 255, 255),
            box_border_color: ColorInputType = (0, 0, 0),
            box_border_width: int = 1,
            box_margin: Tuple2IntType = (25, 0),
            box_progress_color: ColorInputType = (0, 255, 0),
            box_progress_padding: PaddingType = (1, 1),
            progress_text_align: str = ALIGN_CENTER,
            progress_text_enabled: bool = True,
            progress_text_font: Optional[FontType] = None,
            progress_text_font_color: ColorInputType = (0, 0, 0),
            progress_text_font_hfactor: float = 0.8,
            progress_text_format: ProgressBarTextFormatType = lambda x: str(round(x, 1)),
            progress_text_margin: Tuple2IntType = (0, 0),
            progress_text_placeholder: str = '{0} %',
            *args,
            **kwargs
    ) -> None:
        super(ProgressBar, self).__init__(
            args=args,
            kwargs=kwargs,
            onselect=onselect,
            title=title,
            widget_id=progressbar_id
        )

        # Check the value
        assert isinstance(default, NumberInstance)
        assert 0 <= default <= 100, 'default value must range from 0 to 100'

        # Check fonts
        if progress_text_font is not None:
            assert_font(progress_text_font)
        assert isinstance(progress_text_font_hfactor, NumberInstance)
        assert progress_text_font_hfactor > 0, \
            'progress text font height factor must be greater than zero'

        # Check colors
        box_background_color = assert_color(box_background_color)
        box_border_color = assert_color(box_border_color)
        box_progress_color = assert_color(box_progress_color)
        progress_text_font_color = assert_color(progress_text_font_color)

        # Check dimensions and sizes
        assert isinstance(box_border_width, int)
        assert box_border_width >= 0, \
            'box border width must be equal or greater than zero'
        assert_vector(box_margin, 2, int)
        assert_vector(progress_text_margin, 2, int)
        assert isinstance(width, int)
        assert width > 0, 'width must be greater than zero'
        box_progress_padding = parse_padding(box_progress_padding)
        self._box_progress_padding = box_progress_padding

        # Check progress text
        assert isinstance(progress_text_enabled, bool)
        assert is_callable(progress_text_format)
        assert isinstance(progress_text_format(0), str)
        assert isinstance(progress_text_placeholder, str)
        assert_alignment(progress_text_align)

        # Store properties
        self._default_value = default
        self._box_background_color = box_background_color
        self._box_border_color = box_border_color
        self._box_border_width = box_border_width
        self._box_margin = box_margin
        self._box_progress_color = box_progress_color
        self._progress = default
        self._progress_text_align = progress_text_align
        self._progress_text_enabled = progress_text_enabled
        self._progress_text_font = progress_text_font
        self._progress_text_font_color = progress_text_font_color
        self._progress_text_font_height = 0
        self._progress_text_font_height_factor = progress_text_font_hfactor
        self._progress_text_format = progress_text_format
        self._progress_text_margin = progress_text_margin
        self._progress_text_placeholder = progress_text_placeholder
        self._width = width