source: nagslang/resources.py@ 53:39d346467052

Last change on this file since 53:39d346467052 was 39:0e7bb6eb7c0a, checked in by Stefano Rivera <stefano@…>, 8 years ago

Don't prefix the basedir twice

File size: 2.3 KB
Line 
1import os
2
3from pkg_resources import resource_filename
4import pygame
5
6
7class ResourceNotFound(Exception):
8 pass
9
10
11class Resources(object):
12 CONVERT_ALPHA = True
13
14 def __init__(self, resource_module, language=None):
15 self.resource_module = resource_module
16 self.lang_dialect = language
17 self.language = language.split('_', 1)[0] if language else None
18 self._cache = {}
19
20 def get_resource_path(self, *path_fragments):
21 for mod, full_path_fragments in self.lang_locations(path_fragments):
22 path = resource_filename(mod, os.path.join(*full_path_fragments))
23 if os.path.exists(path):
24 return path
25 raise ResourceNotFound(os.path.join(*path_fragments))
26
27 def lang_locations(self, path_fragments):
28 '''
29 For each resource module, yield:
30 * (<module>, (<lang>_<dialect>, <path>))
31 * (<module>, (<lang>, <path>))
32 * (<module>, (<path>, ))
33 '''
34 for module in (self.resource_module,):
35 if self.lang_dialect:
36 yield (module, (self.lang_dialect,) + path_fragments)
37 if self.language != self.lang_dialect:
38 yield (module, (self.language,) + path_fragments)
39 yield (module, path_fragments)
40
41 def get_image(self, *name_fragments, **kw):
42 transforms = kw.get('transforms', ())
43 basedir = kw.get('basedir', 'images')
44
45 path = (basedir,) + name_fragments
46
47 if path not in self._cache:
48 fn = self.get_resource_path(*path)
49 image = pygame.image.load(fn)
50 if self.CONVERT_ALPHA:
51 image = image.convert_alpha(pygame.display.get_surface())
52 self._cache[path] = image
53
54 key = (path, transforms)
55 if key not in self._cache:
56 image = self._cache[path]
57 for mutator in transforms:
58 image = mutator(image)
59 self._cache[key] = image
60
61 return self._cache[key]
62
63 def get_font(self, file_name, font_size):
64 basedir = 'fonts'
65 key = (basedir, file_name, font_size)
66
67 if key not in self._cache:
68 fn = self.get_resource_path(basedir, file_name)
69 self._cache[key] = pygame.font.Font(fn, font_size)
70
71 return self._cache[key]
72
73
74resources = Resources('data')
Note: See TracBrowser for help on using the repository browser.