source: nagslang/resources.py@ 119:b75de48a618c

Last change on this file since 119:b75de48a618c was 54:2c1b85b6f457, checked in by Simon Cross <hodgestar@…>, 8 years ago

Add .get_file() to resources.

File size: 2.5 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_file(self, *path_fragments, **kw):
42 mode = kw.get('mode', "rU")
43 path = self.get_resource_path(*path_fragments)
44 return file(path, mode)
45
46 def get_image(self, *name_fragments, **kw):
47 transforms = kw.get('transforms', ())
48 basedir = kw.get('basedir', 'images')
49
50 path = (basedir,) + name_fragments
51
52 if path not in self._cache:
53 fn = self.get_resource_path(*path)
54 image = pygame.image.load(fn)
55 if self.CONVERT_ALPHA:
56 image = image.convert_alpha(pygame.display.get_surface())
57 self._cache[path] = image
58
59 key = (path, transforms)
60 if key not in self._cache:
61 image = self._cache[path]
62 for mutator in transforms:
63 image = mutator(image)
64 self._cache[key] = image
65
66 return self._cache[key]
67
68 def get_font(self, file_name, font_size):
69 basedir = 'fonts'
70 key = (basedir, file_name, font_size)
71
72 if key not in self._cache:
73 fn = self.get_resource_path(basedir, file_name)
74 self._cache[key] = pygame.font.Font(fn, font_size)
75
76 return self._cache[key]
77
78
79resources = Resources('data')
Note: See TracBrowser for help on using the repository browser.