Example #1
0
    def test_render(self):
        """ 
        """

        f = pygame_font.Font(None, 20)
        s = f.render("foo", True, [0, 0, 0], [255, 255, 255])
        s = f.render("xxx", True, [0, 0, 0], [255, 255, 255])
        s = f.render("", True, [0, 0, 0], [255, 255, 255])
        s = f.render("foo", False, [0, 0, 0], [255, 255, 255])
        s = f.render("xxx", False, [0, 0, 0], [255, 255, 255])
        s = f.render("xxx", False, [0, 0, 0])
        s = f.render("   ", False, [0, 0, 0])
        s = f.render("   ", False, [0, 0, 0], [255, 255, 255])
        # null text should be 1 pixel wide.
        s = f.render("", False, [0, 0, 0], [255, 255, 255])
        self.assertEqual(s.get_size()[0], 1)
        # None text should be 1 pixel wide.
        s = f.render(None, False, [0, 0, 0], [255, 255, 255])
        self.assertEqual(s.get_size()[0], 1)
        # Non-text should raise a TypeError.
        self.assertRaises(TypeError, f.render,
                          [], False, [0, 0, 0], [255, 255, 255])
        self.assertRaises(TypeError, f.render,
                          1, False, [0, 0, 0], [255, 255, 255])
        # is background transparent for antialiasing?
        s = f.render(".", True, [255, 255, 255])
        self.failUnlessEqual(s.get_at((0, 0))[3], 0)
        # is Unicode and bytes encoding correct?
        # Cannot really test if the correct characters are rendered, but
        # at least can assert the encodings differ.
        su = f.render(as_unicode("."), False, [0, 0, 0], [255, 255, 255])
        sb = f.render(as_bytes("."), False, [0, 0, 0], [255, 255, 255])
        self.assert_(equal_images(su, sb))
        u = as_unicode(r"\u212A")
        b = u.encode("UTF-16")[2:] # Keep byte order consistent. [2:] skips BOM
        sb = f.render(b, False, [0, 0, 0], [255, 255, 255])
        try:
            su = f.render(u, False, [0, 0, 0], [255, 255, 255])
        except pygame.error:
            pass
        else:
            self.assert_(not equal_images(su, sb))

        # If the font module is SDL_ttf based, then it can only supports  UCS-2;
        # it will raise an exception for an out-of-range UCS-4 code point.
        if UCS_4 and not hasattr(f, 'ucs4'):
            ucs_2 = as_unicode(r"\uFFEE")
            s = f.render(ucs_2, False, [0, 0, 0], [255, 255, 255])
            ucs_4 = as_unicode(r"\U00010000")
            self.assertRaises(UnicodeError, f.render,
                              ucs_4, False, [0, 0, 0], [255, 255, 255])

        b = as_bytes("ab\x00cd")
        self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0])
        u = as_unicode("ab\x00cd")
        self.assertRaises(ValueError, f.render, b, 0, [0, 0, 0])
Example #2
0
 def test_as_unicode(self):
     r = r'Bo\u00F6tes'
     ords = [ord('B'), ord('o'), 0xF6, ord('t'), ord('e'), ord('s')]
     self.failUnlessEqual(len(r), 11)
     u = compat.as_unicode(r)
     self.failUnless(isinstance(u, compat.unicode_))
     self.failUnlessEqual([ord(c) for c in u], ords)
    def test_load(self):
        # __doc__ (as of 2008-07-13) for pygame.mixer_music.load:
        
          # pygame.mixer.music.load(filename): return None
          # Load a music file for playback

        data_fname = example_path('data')
        pygame.mixer.init()

        # The mp3 test file can crash smpeg on some systems.
        ## formats = ['mp3', 'ogg', 'wav']
        formats = ['ogg', 'wav']

        for f in formats:
            path = os.path.join(data_fname, 'house_lo.%s' % f)
            if os.sep == '\\':
                path = path.replace('\\', '\\\\')
            umusfn = as_unicode(path)
            bmusfn = filesystem_encode(umusfn) 
    
            pygame.mixer.music.load(umusfn)
            pygame.mixer.music.load(bmusfn)

            #NOTE: TODO: loading from filelikes are disabled...
            # because as of writing it only works in SDL_mixer svn.
            #pygame.mixer.music.load(open(musfn))
            #musf = open(musfn)
            #pygame.mixer.music.load(musf)
        pygame.mixer.quit()
Example #4
0
 def test_load_from_file_unicode(self):
     base_dir = os.path.dirname(pygame.__file__)
     font_path = os.path.join(base_dir, pygame_font.get_default_font())
     if os.path.sep == '\\':
         font_path = font_path.replace('\\', '\\\\')
     ufont_path = as_unicode(font_path)
     f = pygame_font.Font(ufont_path, 20)
Example #5
0
    def test_freetype_Font_get_size(self):

        font = self._TEST_FONTS['sans']

        def test_size(s):
            self.assertTrue(isinstance(s, tuple))
            self.assertEqual(len(s), 2)
            self.assertTrue(isinstance(s[0], int))
            self.assertTrue(isinstance(s[1], int))

        size_default = font.get_size("ABCDabcd", ptsize=24)
        test_size(size_default)
        self.assertTrue(size_default > (0, 0))
        self.assertTrue(size_default[0] > size_default[1])

        size_bigger = font.get_size("ABCDabcd", ptsize=32)
        test_size(size_bigger)
        self.assertTrue(size_bigger > size_default)

        size_bolden = font.get_size("ABCDabcd", ptsize=24, style=ft.STYLE_BOLD)
        test_size(size_bolden)
        self.assertTrue(size_bolden > size_default)

        font.vertical = True
        size_vert = font.get_size("ABCDabcd", ptsize=24)
        test_size(size_vert)
        self.assertTrue(size_vert[0] < size_vert[1])
        font.vertical = False

        size_italic = font.get_size("ABCDabcd", ptsize=24, style=ft.STYLE_ITALIC)
        test_size(size_italic)
        self.assertTrue(size_italic[0] > size_default[0])
        self.assertTrue(size_italic[1] == size_default[1])

        size_under = font.get_size("ABCDabcd", ptsize=24, style=ft.STYLE_UNDERLINE)
        test_size(size_under)
        self.assertTrue(size_under[0] == size_default[0])
        self.assertTrue(size_under[1] > size_default[1])

        size_utf32 = font.get_size(as_unicode(r'\U000130A7'), ptsize=24)
        size_utf16 = font.get_size(as_unicode(r'\uD80C\uDCA7'), ptsize=24)
        size_utf16 = font.get_size(as_unicode(r'\uD80C\uDCA7'), ptsize=24,
                                   surrogates=False)
        self.assertNotEqual(size_utf16[0], size_utf32[0]);
        
        self.assertRaises(RuntimeError,
                          nullfont().get_size, 'a', ptsize=24)
Example #6
0
 def test_as_str(self):
     # Bug reported on Pygame mailing list July 24, 2011:
     # For Python 3.x str(event) to raises an UnicodeEncodeError when
     # an event attribute is a string with a non-ascii character.
     try:
         str(pygame.event.Event(1, a=as_unicode(r"\xed")))
     except UnicodeEncodeError:
         self.fail("Event object raised exception for non-ascii character")
Example #7
0
 def test_load_from_file_unicode(self):
     base_dir = os.path.split(pygame.__file__)[0]
     sep = os.path.sep
     if sep == '\\':
         sep = '\\\\'
     font_path = base_dir + sep + pygame_font.get_default_font()
     ufont_path = as_unicode(font_path)
     f = pygame_font.Font(ufont_path, 20)
Example #8
0
    def test_metrics(self):
        # Ensure bytes decoding works correctly. Can only compare results
        # with unicode for now.
        f = pygame_font.Font(None, 20);
        um = f.metrics(as_unicode("."))
        bm = f.metrics(as_bytes("."))
        self.assert_(len(um) == 1)
        self.assert_(len(bm) == 1)
        self.assert_(um[0] is not None)
        self.assert_(um == bm)
        u = as_unicode(r"\u212A")
        b = u.encode("UTF-16")[2:] # Keep byte order consistent. [2:] skips BOM
        bm = f.metrics(b)
        self.assert_(len(bm) == 2)
        try:
            um = f.metrics(u)
        except pygame.error:
            pass
        else:
            self.assert_(len(um) == 1)
            self.assert_(bm[0] != um[0])
            self.assert_(bm[1] != um[0])

        if UCS_4:
            u = as_unicode(r"\U00013000")
            bm = f.metrics(u)
            self.assert_(len(bm) == 1 and bm[0] is None)
    
        return # unfinished
        # The documentation is useless here. How large a list?
        # How do list positions relate to character codes?
        # What about unicode characters?

        # __doc__ (as of 2008-08-02) for pygame_font.Font.metrics:

          # Font.metrics(text): return list
          # Gets the metrics for each character in the pased string.
          # 
          # The list contains tuples for each character, which contain the
          # minimum X offset, the maximum X offset, the minimum Y offset, the
          # maximum Y offset and the advance offset (bearing plus width) of the
          # character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny,
          # maxy, advance), ...]

        self.fail() 
Example #9
0
 def test_size(self):
     f = pygame_font.Font(None, 20)
     text = as_unicode("Xg")
     size = f.size(text)
     w, h = size
     self.assert_(isinstance(w, int) and isinstance(h, int))
     s = f.render(text, False, (255, 255, 255))
     self.assert_(size == s.get_size())
     btext = text.encode("ascii")
     self.assert_(f.size(btext) == size)
     text = as_unicode(r"\u212A")
     btext = text.encode("UTF-16")[2:] # Keep the byte order consistent.
     bsize = f.size(btext)
     try:
         size = f.size(text)
     except pygame.error:
         pass
     else:
         self.assert_(size != bsize)
    def test_freetype_Face_render(self):

        face = self._TEST_FONTS["sans"]

        surf = pygame.Surface((800, 600))
        color = pygame.Color(0, 0, 0)

        # make sure we always have a valid fg color
        self.assertRaises(TypeError, face.render, "FoobarBaz")
        self.assertRaises(TypeError, face.render, "FoobarBaz", None)

        rend = face.render("FoobarBaz", pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(isinstance(rend[0], pygame.Surface))
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(rend[0].get_rect().size, rend[1].size)
        s, r = face.render("", pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertEqual(r.width, 1)
        self.assertEqual(r.height, face.get_sized_height(24))
        self.assertEqual(s.get_size(), r.size)
        self.assertEqual(s.get_bitsize(), 32)

        # misc parameter test
        self.assertRaises(ValueError, face.render, "foobar", color)
        self.assertRaises(TypeError, face.render, "foobar", color, "", ptsize=24)
        self.assertRaises(ValueError, face.render, "foobar", color, None, style=42, ptsize=24)
        self.assertRaises(TypeError, face.render, "foobar", color, None, style=None, ptsize=24)
        self.assertRaises(ValueError, face.render, "foobar", color, None, style=97, ptsize=24)

        # valid surrogate pairs
        #        rend1 = face.render(None, as_unicode(r'\uD800\uDC00'), color, ptsize=24)
        #        rend1 = face.render(None, as_unicode(r'\uDBFF\uDFFF'), color, ptsize=24)
        #        rend1 = face.render(None, as_unicode(r'\uD80C\uDCA7'), color, ptsize=24)
        #        rend2 = face.render(None, as_unicode(r'\U000130A7'), color, ptsize=24)
        #        self.assertEqual(rend1[1], rend2[1])
        #        face.utf16_surrogates = False
        #        try:
        #            rend1 = face.render(None, as_unicode(r'\uD80C\uDCA7'),
        #                                color, ptsize=24)
        #        finally:
        #            face.utf16_surrogates = True
        #        self.assertNotEqual(rend1[1], rend2[1])

        # malformed surrogate pairs
        self.assertRaises(UnicodeEncodeError, face.render, as_unicode(r"\uD80C"), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render, as_unicode(r"\uDCA7"), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render, as_unicode(r"\uD7FF\uDCA7"), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render, as_unicode(r"\uDC00\uDCA7"), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render, as_unicode(r"\uD80C\uDBFF"), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render, as_unicode(r"\uD80C\uE000"), color, ptsize=24)

        # raises exception when uninitalized
        self.assertRaises(RuntimeError, nullface().render, "a", (0, 0, 0), ptsize=24)
Example #11
0
 def test_save_bad_filename(self):
     im = pygame.Surface((10, 10), 0, 32)
     u = as_unicode(r"a\x00b\x00c.png")
     self.assertRaises(pygame.error, save_extended, im, u)
 def test_smp(self):
     utf_8 = as_bytes("a\xF0\x93\x82\xA7b")
     u = as_unicode(r"a\U000130A7b")
     b = encode_string(u, 'utf-8', 'strict', AssertionError)
     self.assertEqual(b, utf_8)
Example #13
0
 def test_returns_bytes(self):
     u = as_unicode(r"Hello")
     self.assert_(isinstance(encode_string(u), bytes_))
Example #14
0
 def test_smp(self):
     utf_8 = as_bytes("a\xF0\x93\x82\xA7b")
     u = as_unicode(r"a\U000130A7b")
     b = encode_string(u, "utf-8", "strict", AssertionError)
     self.assertEqual(b, utf_8)
Example #15
0
    def test_freetype_Face_render(self):

        face = self._TEST_FONTS['sans']

        surf = pygame.Surface((800, 600))
        color = pygame.Color(0, 0, 0)

        # make sure we always have a valid fg color
        self.assertRaises(TypeError, face.render, None, 'FoobarBaz')
        self.assertRaises(TypeError, face.render, None, 'FoobarBaz', None)

        # render to new surface
        rend = face.render(None, 'FoobarBaz', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(isinstance(rend[0], pygame.Surface))
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(rend[0].get_rect().size, rend[1].size)
        s, r = face.render(None, '', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertEqual(r.width, 1)
        self.assertEqual(r.height, face.get_sized_height(24))
        self.assertEqual(s.get_size(), r.size)
        self.assertEqual(s.get_bitsize(), 32)

        # render to existing surface
        refcount = sys.getrefcount(surf);
        rend = face.render((surf, 32, 32), 'FoobarBaz', color, None, ptsize=24)
        self.assertEqual(sys.getrefcount(surf), refcount + 1)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        rsurf, rrect = rend
        self.assertTrue(rsurf is surf)
        self.assertTrue(isinstance(rrect, pygame.Rect))
        self.assertEqual(rrect.top, rrect.height)
##        self.assertEqual(rrect.left, something or other)
        rcopy = rrect.copy()
        rcopy.topleft = (32, 32)
        self.assertTrue(rsurf.get_rect().contains(rcopy))
        
        rect = pygame.Rect(20, 20, 2, 2)
        rend = face.render((surf, rect), 'FoobarBax', color, None, ptsize=24)
        self.assertEqual(rend[1].top, rend[1].height)
        self.assertNotEqual(rend[1].size, rect.size)
        rend = face.render((surf, 20.1, 18.9), 'FoobarBax',
                           color, None, ptsize=24)
##        self.assertEqual(tuple(rend[1].topleft), (20, 18))

        s, r = face.render((surf, rect), '', color, None, ptsize=24)
        self.assertFalse(r)
        self.assertEqual(r.height, face.get_sized_height(24))
        self.assertTrue(s is surf)

        # invalid dest test
        for dest in [0, (), (surf,), (surf, 'a'), (surf, ()),
                     (surf, (1,)), (surf, ('a', 2)), (surf, (1, 'a')),
                     (surf, (1+2j, 2)), (surf, (1, 1+2j)),
                     (surf, 'a', 2), (surf, 1, 'a'), (surf, 1+2j, 2),
                     (surf, 1, 1+2j), (surf, 1, 2, 3)]: 
            self.assertRaises(TypeError, face.render,
                              dest, 'foobar', color, ptsize=24)

        # misc parameter test
        self.assertRaises(ValueError, face.render, None, 'foobar', color)
        self.assertRaises(TypeError, face.render, None, 'foobar', color, "",
                ptsize=24)
        self.assertRaises(ValueError, face.render, None, 'foobar', color, None,
                style=42, ptsize=24)
        self.assertRaises(TypeError, face.render, None, 'foobar', color, None,
                style=None, ptsize=24)
        self.assertRaises(ValueError, face.render, None, 'foobar', color, None,
                style=97, ptsize=24)

        # valid surrogate pairs
#        rend1 = face.render(None, as_unicode(r'\uD800\uDC00'), color, ptsize=24)
#        rend1 = face.render(None, as_unicode(r'\uDBFF\uDFFF'), color, ptsize=24)
#        rend1 = face.render(None, as_unicode(r'\uD80C\uDCA7'), color, ptsize=24)
#        rend2 = face.render(None, as_unicode(r'\U000130A7'), color, ptsize=24)
#        self.assertEqual(rend1[1], rend2[1])
#        face.utf16_surrogates = False
#        try:
#            rend1 = face.render(None, as_unicode(r'\uD80C\uDCA7'),
#                                color, ptsize=24)
#        finally:
#            face.utf16_surrogates = True
#        self.assertNotEqual(rend1[1], rend2[1])
            
        # malformed surrogate pairs
        self.assertRaises(UnicodeEncodeError, face.render,
                          None, as_unicode(r'\uD80C'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render,
                          None, as_unicode(r'\uDCA7'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render,
                          None, as_unicode(r'\uD7FF\uDCA7'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render,
                          None, as_unicode(r'\uDC00\uDCA7'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render,
                          None, as_unicode(r'\uD80C\uDBFF'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, face.render,
                          None, as_unicode(r'\uD80C\uE000'), color, ptsize=24)

        # raises exception when uninitalized
        self.assertRaises(RuntimeError, nullface().render,
                          None, 'a', (0, 0, 0), ptsize=24)
 def test_load_bad_filename(self):
     u = as_unicode(r"a\x00b\x00c.png")
     self.assertRaises(pygame.error, imageext.load_extended, u)
 def test_save_bad_filename(self):
     im = pygame.Surface((10, 10), 0, 32)
     u = as_unicode(r"a\x00b\x00c.png")
     self.assertRaises(pygame.error, imageext.save_extended, im, u)
Example #18
0
 def test_encoding(self):
     u = as_unicode(r"Hello")
     self.assert_(isinstance(encode_file_path(u), bytes_))
Example #19
0
 def test_encoding_error(self):
     u = as_unicode(r"a\x80b")
     self.assert_(encode_string(u, 'ascii', 'strict') is None)
Example #20
0
    def test_freetype_Font_render(self):

        font = self._TEST_FONTS['sans']

        surf = pygame.Surface((800, 600))
        color = pygame.Color(0, 0, 0)

        # make sure we always have a valid fg color
        self.assertRaises(TypeError, font.render, 'FoobarBaz')
        self.assertRaises(TypeError, font.render, 'FoobarBaz', None)

        rend = font.render('FoobarBaz', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(isinstance(rend[0], pygame.Surface))
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(rend[0].get_rect().size, rend[1].size)
        s, r = font.render('', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertEqual(r.width, 1)
        self.assertEqual(r.height, font.get_sized_height(24))
        self.assertEqual(s.get_size(), r.size)
        self.assertEqual(s.get_bitsize(), 32)

        # misc parameter test
        self.assertRaises(ValueError, font.render, 'foobar', color)
        self.assertRaises(TypeError,
                          font.render,
                          'foobar',
                          color,
                          "",
                          ptsize=24)
        self.assertRaises(ValueError,
                          font.render,
                          'foobar',
                          color,
                          None,
                          style=42,
                          ptsize=24)
        self.assertRaises(TypeError,
                          font.render,
                          'foobar',
                          color,
                          None,
                          style=None,
                          ptsize=24)
        self.assertRaises(ValueError,
                          font.render,
                          'foobar',
                          color,
                          None,
                          style=97,
                          ptsize=24)

        # valid surrogate pairs
        #        rend1 = font.render(None, as_unicode(r'\uD800\uDC00'), color, ptsize=24)
        #        rend1 = font.render(None, as_unicode(r'\uDBFF\uDFFF'), color, ptsize=24)
        #        rend1 = font.render(None, as_unicode(r'\uD80C\uDCA7'), color, ptsize=24)
        #        rend2 = font.render(None, as_unicode(r'\U000130A7'), color, ptsize=24)
        #        self.assertEqual(rend1[1], rend2[1])
        #        font.utf16_surrogates = False
        #        try:
        #            rend1 = font.render(None, as_unicode(r'\uD80C\uDCA7'),
        #                                color, ptsize=24)
        #        finally:
        #            font.utf16_surrogates = True
        #        self.assertNotEqual(rend1[1], rend2[1])

        # malformed surrogate pairs
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          as_unicode(r'\uD80C'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          as_unicode(r'\uDCA7'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          as_unicode(r'\uD7FF\uDCA7'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          as_unicode(r'\uDC00\uDCA7'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          as_unicode(r'\uD80C\uDBFF'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          as_unicode(r'\uD80C\uE000'),
                          color,
                          ptsize=24)

        # raises exception when uninitalized
        self.assertRaises(RuntimeError,
                          nullfont().render,
                          'a', (0, 0, 0),
                          ptsize=24)
    def test_freetype_Font_render(self):

        font = self._TEST_FONTS['sans']

        surf = pygame.Surface((800, 600))
        color = pygame.Color(0, 0, 0)

        # make sure we always have a valid fg color
        self.assertRaises(TypeError, font.render, None, 'FoobarBaz')
        self.assertRaises(TypeError, font.render, None, 'FoobarBaz', None)

        # render to new surface
        rend = font.render(None,
                           'FoobarBaz',
                           pygame.Color(0, 0, 0),
                           None,
                           ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(isinstance(rend[0], pygame.Surface))
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(rend[0].get_rect(), rend[1])
        s, r = font.render(None, '', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertFalse(r, str(r))
        self.assertEqual(r.height, font.height)
        self.assertEqual(s.get_rect(), r)

        # render to existing surface
        refcount = sys.getrefcount(surf)
        rend = font.render((surf, 32, 32), 'FoobarBaz', color, None, ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(rend[0] is surf)
        self.assertEqual(sys.getrefcount(surf), refcount + 1)
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(tuple(rend[1].topleft), (32, 32))
        self.assertTrue(rend[0].get_rect().contains(rend[1]))

        rect = pygame.Rect(20, 20, 2, 2)
        rend = font.render((surf, rect), 'FoobarBax', color, None, ptsize=24)
        self.assertEqual(rend[1].topleft, rect.topleft)
        self.assertNotEqual(rend[1], rect)
        rend = font.render((surf, 20.1, 18.9),
                           'FoobarBax',
                           color,
                           None,
                           ptsize=24)
        self.assertEqual(tuple(rend[1].topleft), (20, 18))

        s, r = font.render((surf, rect), '', color, None, ptsize=24)
        self.assertFalse(r)
        self.assertEqual(r.height, font.height)
        self.assertTrue(s is surf)

        # invalid dest test
        for dest in [
                0, (), (surf, ), (surf, 'a'), (surf, ()), (surf, (1, )),
            (surf, ('a', 2)), (surf, (1, 'a')), (surf, (1 + 2j, 2)),
            (surf, (1, 1 + 2j)), (surf, 'a', 2), (surf, 1, 'a'),
            (surf, 1 + 2j, 2), (surf, 1, 1 + 2j), (surf, 1, 2, 3)
        ]:
            self.assertRaises(TypeError,
                              font.render,
                              dest,
                              'foobar',
                              color,
                              ptsize=24)

        # misc parameter test
        self.assertRaises(ValueError, font.render, None, 'foobar', color)
        self.assertRaises(TypeError,
                          font.render,
                          None,
                          'foobar',
                          color,
                          "",
                          ptsize=24)
        self.assertRaises(ValueError,
                          font.render,
                          None,
                          'foobar',
                          color,
                          None,
                          style=42,
                          ptsize=24)
        self.assertRaises(TypeError,
                          font.render,
                          None,
                          'foobar',
                          color,
                          None,
                          style=None,
                          ptsize=24)
        self.assertRaises(ValueError,
                          font.render,
                          None,
                          'foobar',
                          color,
                          None,
                          style=97,
                          ptsize=24)

        # valid surrogate pairs
        rend1 = font.render(None,
                            as_unicode(r'\uD800\uDC00'),
                            color,
                            ptsize=24)
        rend1 = font.render(None,
                            as_unicode(r'\uDBFF\uDFFF'),
                            color,
                            ptsize=24)
        rend1 = font.render(None,
                            as_unicode(r'\uD80C\uDCA7'),
                            color,
                            ptsize=24)
        rend2 = font.render(None, as_unicode(r'\U000130A7'), color, ptsize=24)
        self.assertEqual(rend1[1], rend2[1])
        rend1 = font.render(None,
                            as_unicode(r'\uD80C\uDCA7'),
                            color,
                            ptsize=24,
                            surrogates=False)
        self.assertNotEqual(rend1[1], rend2[1])

        # malformed surrogate pairs
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          None,
                          as_unicode(r'\uD80C'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          None,
                          as_unicode(r'\uDCA7'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          None,
                          as_unicode(r'\uD7FF\uDCA7'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          None,
                          as_unicode(r'\uDC00\uDCA7'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          None,
                          as_unicode(r'\uD80C\uDBFF'),
                          color,
                          ptsize=24)
        self.assertRaises(UnicodeEncodeError,
                          font.render,
                          None,
                          as_unicode(r'\uD80C\uE000'),
                          color,
                          ptsize=24)

        # raises exception when uninitalized
        self.assertRaises(RuntimeError,
                          nullfont().render,
                          None,
                          'a', (0, 0, 0),
                          ptsize=24)
Example #22
0
 def test_filesystem_encode(self):
     upath = compat.as_unicode(r"ab\u212Acd")
     self.assertEqual(compat.filesystem_encode(upath),
                      encode_file_path(upath))
 def test_returns_bytes(self):
     u = as_unicode(r"Hello")
     self.assert_(isinstance(encode_string(u), bytes_))
Example #24
0
 def test_check_defaults(self):
     u = as_unicode(r"a\u01F7b")
     b = u.encode("unicode_escape", "backslashreplace")
     self.assertTrue(encode_string(u) == b)
 def test_errors(self):
     s = r"abc\u0109defg\u011Dh\u0125ij\u0135klmnoprs\u015Dtu\u016Dvz"
     u = as_unicode(s)
     b = u.encode('ascii', 'ignore')
     self.assertEqual(encode_string(u, 'ascii', 'ignore'), b)
 def test_check_defaults(self):
     u = as_unicode(r"a\u01F7b")
     b = u.encode("unicode_escape", "backslashreplace") 
     self.assert_(encode_string(u) == b)
Example #27
0
 def test_filesystem_encode(self):
     upath = compat.as_unicode(r"ab\u212Acd")
     self.assertEqual(compat.filesystem_encode(upath),
                      encode_file_path(upath))
 def test_encode_unicode(self):
     u = as_unicode(r"\u00DEe Olde Komp\u00FCter Shoppe")
     b = u.encode('utf-8')
     self.assertEqual(encode_string(u, 'utf-8'), b)
Example #29
0
    def test_encoding(self):
        u = as_unicode(r"Hello")
        encoded_file_path = encode_file_path(u)

        self.assertIsInstance(encoded_file_path, bytes_)
 def test_encoding_error(self):
     u = as_unicode(r"a\x80b")
     self.assert_(encode_string(u, 'ascii', 'strict') is None)
Example #31
0
    def test_returns_bytes(self):
        u = as_unicode(r"Hello")
        encoded_string = encode_string(u)

        self.assertIsInstance(encoded_string, bytes_)
 def test_etype(self):
     u = as_unicode(r"a\x80b")
     self.assertRaises(SyntaxError, encode_string,
                       u, 'ascii', 'strict', SyntaxError)
Example #33
0
 def test_encode_unicode(self):
     u = as_unicode(r"\u00DEe Olde Komp\u00FCter Shoppe")
     b = u.encode("utf-8")
     self.assertEqual(encode_string(u, "utf-8"), b)
 def test_encoding(self):
     u = as_unicode(r"Hello")
     self.assert_(isinstance(encode_file_path(u), bytes_))
Example #35
0
 def test_errors(self):
     s = r"abc\u0109defg\u011Dh\u0125ij\u0135klmnoprs\u015Dtu\u016Dvz"
     u = as_unicode(s)
     b = u.encode("ascii", "ignore")
     self.assertEqual(encode_string(u, "ascii", "ignore"), b)
Example #36
0
 def test_load_bad_filename(self):
     u = as_unicode(r"a\x00b\x00c.png")
     self.assertRaises(pygame.error, load_extended, u)
Example #37
0
    def test_encoding_error(self):
        u = as_unicode(r"a\x80b")
        encoded_string = encode_string(u, "ascii", "strict")

        self.assertIsNone(encoded_string)
Example #38
0
class Font(_Font):
    """Font(filename, size) -> Font
       Font(object, size) -> Font
       create a new Font object from a file (freetype alternative)

       This Font type differs from font.Font in that it can render glyphs
       for Unicode code points in the supplementary planes (> 0xFFFF).
       """

    __encode_file_path = staticmethod(encode_file_path)
    __get_default_resolution = staticmethod(get_default_resolution)
    __default_font = encode_file_path(get_default_font())

    __unull = as_unicode(r"\x00")
    __bnull = as_bytes("\x00")

    def __init__(self, file, size=-1):
        if size <= 1:
            size = 1
        if isinstance(file, unicode_):
            try:
                file = self.__encode_file_path(file, ValueError)
            except ValueError:
                pass
        if isinstance(file, bytes_) and file == self.__default_font:
            file = None
        if file is None:
            resolution = int(self.__get_default_resolution() * 0.6875)
            if resolution == 0:
                kwds['resolution'] = 1
        else:
            resolution = 0
        super(Font, self).__init__(file, size=size, resolution=resolution)
        self.strength = 1.0 / 12.0
        self.kerning = False
        self.origin = True
        self.pad = True
        self.ucs4 = True
        self.underline_adjustment = 1.0

    def render(self, text, antialias, color, background=None):
        """render(text, antialias, color, background=None) -> Surface
           draw text on a new Surface"""

        if text is None:
            text = ""
        if (isinstance(text, unicode_) and  # conditional and
            self.__unull in text):
            raise ValueError("A null character was found in the text")
        if (isinstance(text, bytes_) and  # conditional and
            self.__bnull in text):
            raise ValueError("A null character was found in the text")
        save_antialiased = self.antialiased
        self.antialiased = bool(antialias)
        try:
            s, r = super(Font, self).render(text, color, background)
            return s
        finally:
            self.antialiased = save_antialiased

    def set_bold(self, value):
        """set_bold(bool) -> None
           enable fake rendering of bold text"""

        self.wide = bool(value)

    def get_bold(self):
        """get_bold() -> bool
           check if text will be rendered bold"""
 
        return self.wide

    def set_italic(self, value):
        """set_italic(bool) -> None
           enable fake rendering of italic text"""

        self.oblique = bool(value)

    def get_italic(self):
        """get_italic() -> bool
           check if the text will be rendered italic"""

        return self.oblique

    def set_underline(self, value):
        """set_underline(bool) -> None
           control if text is rendered with an underline"""

        self.underline = bool(value)

    def get_underline(self):
        """set_bold(bool) -> None
           enable fake rendering of bold text"""

        return self.underline

    def metrics(self, text):
        """metrics(text) -> list
           Gets the metrics for each character in the pased string."""

        return self.get_metrics(text)

    def get_ascent(self):
        """get_ascent() -> int
           get the ascent of the font"""

        return self.get_sized_ascender()

    def get_descent(self):
        """get_descent() -> int
           get the descent of the font"""

        return self.get_sized_descender()

    def get_height(self):
        """get_height() -> int
           get the height of the font"""

        return self.get_sized_ascender() - self.get_sized_descender() + 1

    def get_linesize(self):
        """get_linesize() -> int
           get the line space of the font text"""

        return self.get_sized_height();

    def size(self, text):
        """size(text) -> (width, height)
           determine the amount of space needed to render text"""

        return self.get_rect(text).size
Example #39
0
    def test_check_defaults(self):
        u = as_unicode(r"a\u01F7b")
        b = u.encode("unicode_escape", "backslashreplace")
        encoded_string = encode_string(u)

        self.assertEqual(encoded_string, b)
Example #40
0
    def test_freetype_Font_render(self):

        font = self._TEST_FONTS['sans']

        surf = pygame.Surface((800, 600))
        color = pygame.Color(0, 0, 0)

        # make sure we always have a valid fg color
        self.assertRaises(TypeError, font.render, None, 'FoobarBaz')
        self.assertRaises(TypeError, font.render, None, 'FoobarBaz', None)

        # render to new surface
        rend = font.render(None, 'FoobarBaz', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(isinstance(rend[0], pygame.Surface))
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(rend[0].get_rect(), rend[1])
        s, r = font.render(None, '', pygame.Color(0, 0, 0), None, ptsize=24)
        self.assertFalse(r, str(r))
        self.assertEqual(r.height, font.height)
        self.assertEqual(s.get_rect(), r)

        # render to existing surface
        refcount = sys.getrefcount(surf);
        rend = font.render((surf, 32, 32), 'FoobarBaz', color, None, ptsize=24)
        self.assertTrue(isinstance(rend, tuple))
        self.assertEqual(len(rend), 2)
        self.assertTrue(rend[0] is surf)
        self.assertEqual(sys.getrefcount(surf), refcount + 1)
        self.assertTrue(isinstance(rend[1], pygame.Rect))
        self.assertEqual(tuple(rend[1].topleft), (32, 32))
        self.assertTrue(rend[0].get_rect().contains(rend[1]))
        
        rect = pygame.Rect(20, 20, 2, 2)
        rend = font.render((surf, rect), 'FoobarBax', color, None, ptsize=24)
        self.assertEqual(rend[1].topleft, rect.topleft)
        self.assertNotEqual(rend[1], rect)
        rend = font.render((surf, 20.1, 18.9), 'FoobarBax',
                           color, None, ptsize=24)
        self.assertEqual(tuple(rend[1].topleft), (20, 18))

        s, r = font.render((surf, rect), '', color, None, ptsize=24)
        self.assertFalse(r)
        self.assertEqual(r.height, font.height)
        self.assertTrue(s is surf)

        # invalid dest test
        for dest in [0, (), (surf,), (surf, 'a'), (surf, ()),
                     (surf, (1,)), (surf, ('a', 2)), (surf, (1, 'a')),
                     (surf, (1+2j, 2)), (surf, (1, 1+2j)),
                     (surf, 'a', 2), (surf, 1, 'a'), (surf, 1+2j, 2),
                     (surf, 1, 1+2j), (surf, 1, 2, 3)]: 
            self.assertRaises(TypeError, font.render,
                              dest, 'foobar', color, ptsize=24)

        # misc parameter test
        self.assertRaises(ValueError, font.render, None, 'foobar', color)
        self.assertRaises(TypeError, font.render, None, 'foobar', color, "",
                ptsize=24)
        self.assertRaises(ValueError, font.render, None, 'foobar', color, None,
                style=42, ptsize=24)
        self.assertRaises(TypeError, font.render, None, 'foobar', color, None,
                style=None, ptsize=24)
        self.assertRaises(ValueError, font.render, None, 'foobar', color, None,
                style=97, ptsize=24)

        # valid surrogate pairs
        rend1 = font.render(None, as_unicode(r'\uD800\uDC00'), color, ptsize=24)
        rend1 = font.render(None, as_unicode(r'\uDBFF\uDFFF'), color, ptsize=24)
        rend1 = font.render(None, as_unicode(r'\uD80C\uDCA7'), color, ptsize=24)
        rend2 = font.render(None, as_unicode(r'\U000130A7'), color, ptsize=24)
        self.assertEqual(rend1[1], rend2[1])
        rend1 = font.render(None, as_unicode(r'\uD80C\uDCA7'),
                            color, ptsize=24, surrogates=False)
        self.assertNotEqual(rend1[1], rend2[1])
            
        # malformed surrogate pairs
        self.assertRaises(UnicodeEncodeError, font.render,
                          None, as_unicode(r'\uD80C'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, font.render,
                          None, as_unicode(r'\uDCA7'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, font.render,
                          None, as_unicode(r'\uD7FF\uDCA7'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, font.render,
                          None, as_unicode(r'\uDC00\uDCA7'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, font.render,
                          None, as_unicode(r'\uD80C\uDBFF'), color, ptsize=24)
        self.assertRaises(UnicodeEncodeError, font.render,
                          None, as_unicode(r'\uD80C\uE000'), color, ptsize=24)

        # raises exception when uninitalized
        self.assertRaises(RuntimeError, nullfont().render,
                          None, 'a', (0, 0, 0), ptsize=24)
Example #41
0
 def test_etype(self):
     u = as_unicode(r"a\x80b")
     self.assertRaises(SyntaxError, encode_string, u, "ascii", "strict",
                       SyntaxError)