def build(self):
        b = BoxLayout(orientation='vertical')
        languages = Spinner(text='language',
                            values=sorted([
                                'KvLexer',
                            ] + lexers.LEXERS.keys()))

        languages.bind(text=self.change_lang)

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

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

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

        b.add_widget(self.codeinput)

        return b
Example #2
0
    def __init__(self):
        self._files = FileResolver()

        # Store keyboard keys and corresponded sounds
        self._key_sound = {}

        # Load keymap settings
        with open(self._files.keymap_path) as f:
            self._keymap = yaml.safe_load(f)

        # Lower buffer to lower sound delay
        mixer.init(44100, -16, 2, 256)
        # Set higher channels number, allows to play many sounds
        # at the same time without stopping previously started ones
        mixer.set_num_channels(20)

        # Get any mono font, if no mono fonts use system default
        fonts = tuple(filter(lambda txt: 'mono' in txt, font.get_fonts()))
        win_font = fonts[0] if fonts else None
        font.init()
        self._font = font.SysFont(win_font, self.FONT_SIZE)

        # Set up the window
        win_height = len(self._keymap) * self.FONT_SIZE + 2 * self.MARGIN
        self._screen = display.set_mode((self.WINDOW_WIDTH, win_height))
        display.set_caption(self.WINDOW_CAPTION)
Example #3
0
    def test_match_font_italic(self):
        fonts = pygame_font.get_fonts()

        # Look for an italic font.
        self.assertTrue(
            any(pygame_font.match_font(font, italic=True) for font in fonts)
        )
Example #4
0
 def test_match_font_name(self):
     """That match_font accepts names of various types"""
     font = pygame_font.get_fonts()[0]
     font_path = pygame_font.match_font(font)
     self.assertIsNotNone(font_path)
     font_b = font.encode()
     not_a_font = "thisisnotafont"
     not_a_font_b = b"thisisnotafont"
     good_font_names = [
         # Check single name bytes.
         font_b,
         # Check string of comma-separated names.
         ",".join([not_a_font, font, not_a_font]),
         # Check list of names.
         [not_a_font, font, not_a_font],
         # Check generator:
         (name for name in [not_a_font, font, not_a_font]),
         # Check comma-separated bytes.
         b",".join([not_a_font_b, font_b, not_a_font_b]),
         # Check list of bytes.
         [not_a_font_b, font_b, not_a_font_b],
         # Check mixed list of bytes and string.
         [font, not_a_font, font_b, not_a_font_b],
     ]
     for font_name in good_font_names:
         self.assertEqual(pygame_font.match_font(font_name), font_path,
                          font_name)
Example #5
0
    def test_match_font_all_exist(self):
        fonts = pygame_font.get_fonts()

        # Ensure all listed fonts are in fact available, and the returned file
        # name is a full path.
        for font in fonts:
            path = pygame_font.match_font(font)
            self.failIf(path is None)
            self.failUnless(os.path.isabs(path))
Example #6
0
    def test_match_font_all_exist(self):
        fonts = pygame_font.get_fonts()

        # Ensure all listed fonts are in fact available, and the returned file
        # name is a full path.
        for font in fonts:
            path = pygame_font.match_font(font)
            self.failIf(path is None)
            self.failUnless(os.path.isabs(path))
Example #7
0
    def test_match_font_italic(self):

        fonts = pygame_font.get_fonts()

        # Look for an italic font.
        for font in fonts:
            if pygame_font.match_font(font, italic=True) is not None:
                break
        else:
            self.fail()
Example #8
0
    def test_match_font_bold(self):

        fonts = pygame_font.get_fonts()

        # Look for a bold font.
        for font in fonts:
            if pygame_font.match_font(font, bold=True) is not None:
                break
        else:
            self.fail()
Example #9
0
    def test_match_font_bold(self):

        fonts = pygame_font.get_fonts()
 
        # Look for a bold font.
        for font in fonts:
            if pygame_font.match_font(font, bold=True) is not None:
                break
        else:
            self.fail()
Example #10
0
    def test_match_font_italic(self):

        fonts = pygame_font.get_fonts()

        # Look for an italic font.
        for font in fonts:
            if pygame_font.match_font(font, italic=True) is not None:
                break
        else:
            self.fail()
Example #11
0
    def test_match_font_comma_separated(self):
        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.assertTrue(pygame_font.match_font('thisisnotafont') is None)

        # Check comma separated list.
        names = ','.join(['thisisnotafont', fonts[-1], 'anothernonfont'])
        self.assertFalse(pygame_font.match_font(names) is None)
        names = ','.join(['thisisnotafont1', 'thisisnotafont2', 'thisisnotafont3'])
        self.assertTrue(pygame_font.match_font(names) is None)
Example #12
0
    def test_match_font_comma_separated(self):
        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.assertTrue(pygame_font.match_font("thisisnotafont") is None)

        # Check comma separated list.
        names = ",".join(["thisisnotafont", fonts[-1], "anothernonfont"])
        self.assertFalse(pygame_font.match_font(names) is None)
        names = ",".join(["thisisnotafont1", "thisisnotafont2", "thisisnotafont3"])
        self.assertTrue(pygame_font.match_font(names) is None)
Example #13
0
 def test_SysFont(self):
     # Can only check that a font object is returned.
     fonts = pygame_font.get_fonts()
     o = pygame_font.SysFont(fonts[0], 20)
     self.failUnless(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont(fonts[0], 20, italic=True)
     self.failUnless(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont(fonts[0], 20, bold=True)
     self.failUnless(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont('thisisnotafont', 20)
     self.failUnless(isinstance(o, pygame_font.FontType))
Example #14
0
 def test_SysFont(self):
     # Can only check that a font object is returned.
     fonts = pygame_font.get_fonts()
     o = pygame_font.SysFont(fonts[0], 20)
     self.failUnless(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont(fonts[0], 20, italic=True)
     self.failUnless(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont(fonts[0], 20, bold=True)
     self.failUnless(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont('thisisnotafont', 20)
     self.failUnless(isinstance(o, pygame_font.FontType))
Example #15
0
    def test_match_font_comma_separated(self):

        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.failUnless(pygame_font.match_font("thisisnotafont") is None)

        # Check comma separated list.
        names = ",".join(["thisisnotafont", fonts[-1], "anothernonfont"])
        self.failIf(pygame_font.match_font(names) is None)
        names = ",".join(["thisisnotafont1", "thisisnotafont2", "thisisnotafont3"])
        self.failUnless(pygame_font.match_font(names) is None)
Example #16
0
    def test_match_font_comma_separated(self):

        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.failUnless(pygame_font.match_font('thisisnotafont') is None)

        # Check comma separated list.
        names = ','.join(['thisisnotafont', fonts[-1], 'anothernonfont'])
        self.failIf(pygame_font.match_font(names) is None)
        names = ','.join(['thisisnotafont1', 'thisisnotafont2', 'thisisnotafont3'])
        self.failUnless(pygame_font.match_font(names) is None)
Example #17
0
    def test_get_fonts(self):
        fnts = pygame_font.get_fonts()

        self.assertTrue(fnts, msg=repr(fnts))

        for name in fnts:
            # note, on ubuntu 2.6 they are all unicode strings.

            self.assertTrue(isinstance(name, str), name)
            # Font names can be comprised of only numeric characters, so
            # just checking name.islower() will not work as expected here.
            self.assertFalse(any(c.isupper() for c in name))
            self.assertTrue(name.isalnum(), name)
Example #18
0
 def test_SysFont(self):
     # Can only check that a font object is returned.
     fonts = pygame_font.get_fonts()
     if "arial" in fonts:
         # Try to use arial font if it is there, rather than a random font
         #  which can be different depending on installed fonts on the system.
         font_name = "arial"
     else:
         font_name = sorted(fonts)[0]
     o = pygame_font.SysFont(font_name, 20)
     self.assertTrue(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont(font_name, 20, italic=True)
     self.assertTrue(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont(font_name, 20, bold=True)
     self.assertTrue(isinstance(o, pygame_font.FontType))
     o = pygame_font.SysFont("thisisnotafont", 20)
     self.assertTrue(isinstance(o, pygame_font.FontType))
Example #19
0
    def test_get_fonts(self):
        fnts = pygame_font.get_fonts()

        self.assertTrue(fnts, msg=repr(fnts))

        if (PY_MAJOR_VERSION >= 3):
            # For Python 3.x, names will always be unicode strings.
            name_types = (str, )
        else:
            # For Python 2.x, names may be either unicode or ascii strings.
            name_types = (str, unicode)

        for name in fnts:
            # note, on ubuntu 2.6 they are all unicode strings.

            self.assertTrue(isinstance(name, name_types), name)
            self.assertTrue(name.islower(), name)
            self.assertTrue(name.isalnum(), name)
Example #20
0
 def draw_button(self):
     button_x = self.grid_size[0] * 3
     button_y = self.grid_size[0] / 2
     button_size = [button_x, button_y]
     x = Constants.WINDOW_WIDTH / 2 - button_x / 2
     y = Constants.WINDOW_HEIGHT - 0.03125 * Constants.WINDOW_HEIGHT - button_y / 2
     if self.button_clicked:
         draw.rect(self.screen, (255, 0, 0), ((x, y), button_size), int(self.line_width / 3))
     else:
         draw.rect(self.screen, (0, 0, 0), ((x, y), button_size), int(self.line_width / 3))
     font1 = font.SysFont(font.get_fonts()[0], int(button_y * 0.7))
     if self.game.game_ended_bool:
         text = font1.render("NEW GAME", True, (0, 0, 0))
         self.screen.blit(text, (x + 0.15 * x, y))
         if self.button_clicked:
             self.new_game = True
     else:
         text = font1.render("MAKE DOUBLE MOVE", True, (0, 0, 0))
         self.screen.blit(text, (x + 0.005 * x, y))
Example #21
0
    def test_get_fonts(self):
        fnts = pygame_font.get_fonts()

        self.assertTrue(fnts, msg=repr(fnts))

        if (PY_MAJOR_VERSION >= 3):
            # For Python 3.x, names will always be unicode strings.
            name_types = (str, )
        else:
            # For Python 2.x, names may be either unicode or ascii strings.
            name_types = (str, unicode)

        for name in fnts:
            # note, on ubuntu 2.6 they are all unicode strings.

            self.assertTrue(isinstance(name, name_types), name)
            # Font names can be comprised of only numeric characters, so
            # just checking name.islower() will not work as expected here.
            self.assertFalse(any(c.isupper() for c in name))
            self.assertTrue(name.isalnum(), name)
Example #22
0
 def draw_ball_keeper_left(self):
     keeper_x = Constants.WINDOW_WIDTH * 0.2
     keeper_y = Constants.BOARD_SIZE * 1.1
     keeper_size = [keeper_x, keeper_y]
     x = Constants.WINDOW_WIDTH * 0.025
     y = Constants.WINDOW_HEIGHT * 0.5625 - keeper_y / 2
     if self.game.players[self.game.current_player].name == self.game.players[0].name:
         color = (255, 0, 0)
     else:
         color = (0, 0, 0)
     if self.game.game_ended_bool:
         color = (0, 0, 0)
     draw.rect(self.screen, color, ((x, y), keeper_size), int(self.line_width / 2))
     for i, ball in enumerate(self.game.players[0].bag.balls):
         x_ball = int(i % self.size_balls) * keeper_x / self.size_balls + x
         y_ball = int(i / self.size_balls) * keeper_x / self.size_balls + y
         self.draw_balls(x_ball, y_ball, keeper_x / self.size_balls, ball)
     font1 = font.SysFont(font.get_fonts()[0], int(keeper_x * 0.2))
     text = font1.render(self.game.players[0].name, True, (0, 0, 0))
     self.screen.blit(text, (x + 0.005 * x, y - y * 0.7))
Example #23
0
    def test_get_fonts(self):
        fnts = pygame_font.get_fonts()
        
        if not fnts:
            raise Exception(repr(fnts))

        self.failUnless(fnts)

        if (PY_MAJOR_VERSION >= 3):
            # For Python 3.x, names will always be unicode strings.
            name_types = (str,)
        else:
            # For Python 2.x, names may be either unicode or ascii strings.
            name_types = (str, unicode)

        for name in fnts:
            # note, on ubuntu 2.6 they are all unicode strings.

            self.failUnless(isinstance(name, name_types), name)
            self.failUnless(name.islower(), name)
            self.failUnless(name.isalnum(), name)
Example #24
0
    def test_get_fonts(self):
        fnts = pygame_font.get_fonts()

        if not fnts:
            raise Exception(repr(fnts))

        self.failUnless(fnts)

        # strange python 2.x bug... if you assign to unicode,
        #   all sorts of weirdness happens.
        if sys.version_info <= (3, 0, 0):
            unicod = unicode
        else:
            unicod = str

        for name in fnts:
            # note, on ubuntu 2.6 they are all unicode strings.

            self.failUnless(isinstance(name, (str, unicod)))
            self.failUnless(name.islower(), name)
            self.failUnless(name.isalnum(), name)
    def test_get_fonts(self):
        fnts = pygame_font.get_fonts()
        
        if not fnts:
            raise Exception(repr(fnts))

        self.failUnless(fnts)

        # strange python 2.x bug... if you assign to unicode, 
        #   all sorts of weirdness happens.
        if sys.version_info <= (3, 0, 0):
            unicod = unicode
        else:
            unicod = str

        for name in fnts:
            # note, on ubuntu 2.6 they are all unicode strings.

            self.failUnless(isinstance(name, (str, unicod)), name)
            self.failUnless(name.islower(), name)
            self.failUnless(name.isalnum(), name)
Example #26
0
        def test_get_fonts(self):
            fnts = pygame_font.get_fonts()

            if not fnts:
                raise Exception(repr(fnts))

            self.failUnless(fnts)

            if (PY_MAJOR_VERSION >= 3):
                # For Python 3.x, names will always be unicode strings.
                name_types = (str, )
            else:
                # For Python 2.x, names may be either unicode or ascii strings.
                name_types = (str, unicode)

            for name in fnts:
                # note, on ubuntu 2.6 they are all unicode strings.

                self.failUnless(isinstance(name, name_types), name)
                self.failUnless(name.islower(), name)
                self.failUnless(name.isalnum(), name)
Example #27
0
    def __init__(self, **kwargs):
        super(FontChooser, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.fonts = sorted(map(str, fonts.get_fonts()))

        data = [{'text': str(i), 'is_selected': i == self.font} for i in self.fonts]

        args_converter = lambda row_index, rec: {'text': rec['text'],
                                                 'size_hint_y': None,
                                                 'height': 25}

        self.list_adapter = ListAdapter(data=data, args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False)
        self.list_view = ListView(adapter=self.list_adapter)
        self.list_adapter.bind(selection=self.on_font_select)

        self.label = Label(text="The quick brown fox jumps over the brown lazy dog. 0123456789", font_size="30dp", halign="center", size_hint_y=None)
        self.label.font_name = fonts.match_font(self.list_adapter.selection[0].text)
        self.label.bind(size=self.label.setter("text_size"))
        self.font = self.list_adapter.selection[0].text

        self.add_widget(self.list_view)
        self.add_widget(self.label)          
Example #28
0
    def build(self):
        b = BoxLayout(orientation='vertical')
        languages = Spinner(
            text='language',
            values=sorted(['KvLexer', ] + list(lexers.LEXERS.keys())))

        languages.bind(text=self.change_lang)

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

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

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

        b.add_widget(self.codeinput)

        return b
Example #29
0
    def __init__(self, **kwargs):
        super(FontChooser, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.fonts = sorted(map(str, fonts.get_fonts()))

        data = [{
            'text': str(i),
            'is_selected': i == self.font
        } for i in self.fonts]

        args_converter = lambda row_index, rec: {
            'text': rec['text'],
            'size_hint_y': None,
            'height': 25
        }

        self.list_adapter = ListAdapter(data=data,
                                        args_converter=args_converter,
                                        cls=ListItemButton,
                                        selection_mode='single',
                                        allow_empty_selection=False)
        self.list_view = ListView(adapter=self.list_adapter)
        self.list_adapter.bind(selection=self.on_font_select)

        self.label = Label(
            text=
            "The quick brown fox jumps over the brown lazy dog. 0123456789",
            font_size="30dp",
            halign="center",
            size_hint_y=None)
        self.label.font_name = fonts.match_font(
            self.list_adapter.selection[0].text)
        self.label.bind(size=self.label.setter("text_size"))
        self.font = self.list_adapter.selection[0].text

        self.add_widget(self.list_view)
        self.add_widget(self.label)
Example #30
0
 def test_get_fonts_returns_something(self):
     fnts = pygame_font.get_fonts()
     self.failUnless(fnts)
Example #31
0
 def installed(cls):
     if not cls._sort: cls._sort = sorted(pf.get_fonts())
     return cls._sort
Example #32
0
def get_font(name: FontType, size: int) -> '__font.Font':
    """
    Return a :py:class:`pygame.font.Font` object from a name or file.

    :param name: Font name or path
    :param size: Font size in px
    :return: Font object
    """
    assert_font(name)
    assert isinstance(size, int)

    font: Optional['__font.Font']
    if isinstance(name, __font.Font):
        font = name
        return font

    else:
        name = str(name)

        if name == '':
            raise ValueError('font name cannot be empty')

        if size <= 0:
            raise ValueError('font size cannot be lower or equal than zero')

        # Font is not a file, then use a system font
        if not path.isfile(name):
            font_name = name
            name = __font.match_font(font_name)

            if name is None:  # Show system available fonts
                from difflib import SequenceMatcher
                from random import randrange
                system_fonts = __font.get_fonts()

                # Get the most similar example
                most_similar = 0
                most_similar_index = 0
                for i in range(len(system_fonts)):
                    # noinspection PyArgumentEqualDefault
                    sim = SequenceMatcher(None, system_fonts[i], font_name).ratio()
                    if sim > most_similar:
                        most_similar = sim
                        most_similar_index = i
                sys_font_sim = system_fonts[most_similar_index]
                sys_suggestion = f'system font "{font_name}" unknown, use "{sys_font_sim}" instead'
                sys_message = 'check system fonts with pygame.font.get_fonts() function'

                # Get examples
                examples_number = 3
                examples = []
                j = 0
                for i in range(len(system_fonts)):
                    font_random = system_fonts[randrange(0, len(system_fonts))]
                    if font_random not in examples:
                        examples.append(font_random)
                        j += 1
                    if j >= examples_number:
                        break
                examples.sort()
                fonts_random = ', '.join(examples)
                sys_message_2 = f'some examples: {fonts_random}'

                # Raise the exception
                raise ValueError(f'{sys_suggestion}\n{sys_message}\n{sys_message_2}')

        # Try to load the font
        font = None
        if (name, size) in _cache:
            return _cache[(name, size)]
        try:
            font = __font.Font(name, size)
        except IOError:
            pass

        # If font was not loaded throw an exception
        if font is None:
            raise IOError(f'font file "{font}" cannot be loaded')
        _cache[(name, size)] = font
        return font
Example #33
0
try:
    import numpy
    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False

try:
    import PIL
    HAS_PIL = True
except ImportError:
    HAS_PIL = False

CAN_SHADOWS = HAS_NUMPY and HAS_PIL

# fonts
AVAILABLE_FONTS = sorted(get_fonts())

# pygame events
EVENT_QUIT = pygame_event.Event(QUIT)

THORPY_EVENT = USEREVENT
# events types : these are the names of thorpy events.
# A ThorPy event has an attribute name, and the numbers below are these attributes, not pygame events!!!
# However, due to the working principle of Reactions, we follow the numbers after pygame.USEREVENT
EVENT_TIME =   1
EVENT_PRESS =   2  # posted when an element enter state pressed
# posted when sth has been inserted into an Inserter
EVENT_INSERT =   3
EVENT_SELECT =   4  # posted when sth has been selected into a DDL
# posted when mousewheel has been used on an element that handles it
EVENT_WHEEL =   5
Example #34
0
        maxWidth = 0
        for ch in chars:
            maxWidth = max(f.size(ch)[0], maxWidth)

        maxWidth *= COLS
        maxHeight *= COLS

        if textureWidth < max(maxHeight, maxWidth):
            retFont = f
            break

        retFont = f

    return retFont

for fontFileShort in font.get_fonts():
    print fontFileShort

    if not fontFileShort.startswith('free'): continue

    fontFile = font.match_font(fontFileShort)
    
    # find a size.....
    for sqTextSize in goals:
        f = font.Font(fontFile, sqTextSize/COLS)
        #f = findGoal(sqTextSize, fontFile)
        print 'h', f.get_height()


        #maxHeight = f.size(chars)[1]
        #maxWidth = 0
Example #35
0
def find_fonts():
    monospaced = ["bitstreamverasansmono", "consolas", "luximono", "lucidaconsole", "andalemono", "couriernew", 'inconsolata', 'courier', 'monaco']
    return sorted([f for f in font.get_fonts() if f in monospaced])
Example #36
0
import pygame

from pygame import font

print(font.get_fonts())
Example #37
0
    def build(self):
        self.robot = Robot(status_display=self, code_display=self)

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

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

        # file menu
        mnu_file = Spinner(
            text='File',
            values=('Connect', 'Open', 'SaveAs', 'Save', 'Close'))
        mnu_file.bind(text=self._file_menu_selected)

        # motors on/off
        btn_motors_on = Button(text='Motors On')
        btn_motors_on.bind(on_press=self._on_motors_on)

        btn_motors_off = Button(text='Motors Off')
        btn_motors_off.bind(on_press=self._on_motors_off)

        # run script
        btn_run_script = Button(text='Run Script')
        btn_run_script.bind(on_press=self._on_run_script)

        # add keyframe
        btn_add_keyframe = Button(text='Add Keyframe')
        btn_add_keyframe.bind(on_press=self._on_add_keyframe)

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

        # add to menu
        menu.add_widget(mnu_file)
        menu.add_widget(btn_add_keyframe)
        menu.add_widget(btn_motors_on)
        menu.add_widget(btn_motors_off)
        menu.add_widget(btn_run_script)
        menu.add_widget(robot_actions)
        b.add_widget(menu)

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

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

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


        m.add_widget(code_status)
        self.joints_ui = NaoJoints(size_hint=(0.4, 1))
        m.add_widget(self.joints_ui)

        b.add_widget(m)
        return b
Example #38
0
 def installed(cls):
     if not cls._sort: cls._sort = sorted(pf.get_fonts())
     return cls._sort
Example #39
0
 def test_get_fonts_returns_something(self):
     fnts = pygame_font.get_fonts()
     self.assertTrue(fnts)
Example #40
0
    def build(self):
        self.robot = Robot(status_display=self, code_display=self,
                           on_disconnect=self._on_disconnect,
                           on_stiffness=self._on_chain_stiffness_from_robot)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        b.add_widget(controls)

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

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

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


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

        b.add_widget(m)
        return b
Example #41
0
 def test_get_fonts_returns_something(self):
     fnts = pygame_font.get_fonts()
     self.failUnless(fnts)
Example #42
0
    def test_match_font_bold(self):
        fonts = pygame_font.get_fonts()

        # Look for a bold font.
        self.assertTrue(
            any(pygame_font.match_font(font, bold=True) for font in fonts))
Example #43
0
def get_font(name, size):
    """
    Return a pygame.Font object from a name or file.

    :param name: Font name or path
    :type name: basestring
    :param size: Font size
    :type size: int
    :return: Font object
    :rtype: pygame.font.FontType
    """
    assert isinstance(size, int)
    if isinstance(name, _font.Font):
        font = name  # type: (_font.FontType,None)
        return font
    else:

        if name == '':
            raise ValueError('Font name cannot be empty')

        if size <= 0:
            raise ValueError('Font size cannot be lower or equal than zero')

        # Font is not a file, then use a system font
        if not path.isfile(name):
            font_name = name
            name = _font.match_font(font_name)

            if name is None:  # Show system available fonts
                from difflib import SequenceMatcher
                from random import randrange
                system_fonts = _font.get_fonts()

                # Get the most similar example
                most_similar = 0
                most_similar_index = 0
                for i in range(len(system_fonts)):
                    # noinspection PyArgumentEqualDefault
                    sim = SequenceMatcher(None, system_fonts[i],
                                          font_name).ratio()  # Similarity
                    if sim > most_similar:
                        most_similar = sim
                        most_similar_index = i
                sys_font_sim = system_fonts[most_similar_index]
                sys_suggestion = 'System font "{0}" unknown, use "{1}" instead'.format(
                    font_name, sys_font_sim)
                sys_message = 'Check system fonts with pygame.font.get_fonts() function'

                # Get examples
                examples_number = 3
                examples = []
                j = 0
                for i in range(len(system_fonts)):
                    font_random = system_fonts[randrange(0, len(system_fonts))]
                    if font_random not in examples:
                        examples.append(font_random)
                        j += 1
                    if j >= examples_number:
                        break
                examples.sort()
                fonts_random = ', '.join(examples)
                sys_message_2 = 'Some examples: {0}'.format(fonts_random)

                # Raise the exception
                raise ValueError('{0}\n{1}\n{2}'.format(
                    sys_suggestion, sys_message, sys_message_2))

        # Try to load the font
        font = None  # type: (_font.FontType,None)
        try:
            font = _font.Font(name, size)
        except IOError:
            pass

        # If font was not loaded throw an exception
        if font is None:
            raise IOError('Font file "{0}" cannot be loaded'.format(font))
        return font
Example #44
0
    def test_match_font_name(self):
        """that match_font accepts names of various types"""
        font = pygame_font.get_fonts()[0]
        not_a_font = "thisisnotafont"

        # Check for not found.
        self.assertTrue(pygame_font.match_font(not_a_font) is None)

        # Check single name string:
        font_path = pygame_font.match_font(font)
        self.assertFalse(font_path is None)
        self.assertTrue(pygame_font.match_font(not_a_font) is None)

        # Check string of comma-separated names.
        names = ",".join([not_a_font, font, not_a_font])
        font_path_2 = pygame_font.match_font(names)
        self.assertEqual(font_path_2, font_path)
        names = ",".join([not_a_font, not_a_font, not_a_font])
        self.assertTrue(pygame_font.match_font(names) is None)

        # Check list of names.
        names = [not_a_font, font, not_a_font]
        font_path_2 = pygame_font.match_font(names)
        self.assertEqual(font_path_2, font_path)
        names = [not_a_font, not_a_font, not_a_font]
        self.assertTrue(pygame_font.match_font(names) is None)

        # Check generator:
        names = (name for name in [not_a_font, font, not_a_font])
        font_path_2 = pygame_font.match_font(names)
        self.assertEqual(font_path_2, font_path)
        names = (name for name in [not_a_font, not_a_font, not_a_font])
        self.assertTrue(pygame_font.match_font(names) is None)

        font_b = font.encode()
        not_a_font_b = b"thisisnotafont"

        # Check single name bytes.
        self.assertEqual(pygame_font.match_font(font_b), font_path)
        self.assertTrue(pygame_font.match_font(not_a_font_b) is None)

        # Check comma-separated bytes.
        names = b",".join([not_a_font_b, font_b, not_a_font_b])
        font_path_2 = pygame_font.match_font(names)
        self.assertEqual(font_path_2, font_path)
        names = b",".join([not_a_font_b, not_a_font_b, not_a_font_b])
        self.assertTrue(pygame_font.match_font(names) is None)

        # Check list of bytes.
        names = [not_a_font_b, font_b, not_a_font_b]
        font_path_2 = pygame_font.match_font(names)
        self.assertEqual(font_path_2, font_path)
        names = [not_a_font_b, not_a_font_b, not_a_font_b]
        self.assertTrue(pygame_font.match_font(names) is None)

        # Check mixed list of bytes and string.
        names = [font, not_a_font, font_b, not_a_font_b]
        font_path_2 = pygame_font.match_font(names)
        self.assertEqual(font_path_2, font_path)
        names = [not_a_font, not_a_font_b, not_a_font]
        self.assertTrue(pygame_font.match_font(names) is None)