|
16 | 16 | # You should have received a copy of the GNU Affero General Public License
|
17 | 17 | # along with this program. If not, see <http://www.gnu.org/licenses/>.
|
18 | 18 |
|
| 19 | +import functools |
19 | 20 | import os.path
|
20 | 21 |
|
21 | 22 | import xdg.BaseDirectory
|
22 | 23 | import xdg.Mime
|
| 24 | +import xdg.Locale |
23 | 25 |
|
24 | 26 |
|
25 | 27 | __all__ = [
|
@@ -59,17 +61,36 @@ def get_icon_for_type(typename: str) -> str:
|
59 | 61 | return _icons[typename]
|
60 | 62 | return mimetype.media + "-x-generic"
|
61 | 63 |
|
62 |
| - |
63 |
| -def get_name_for_type(typename: str) -> str: |
| 64 | +# xdg.Mime is by default memoized, but since we need to change the language, we |
| 65 | +# need to wipe the cache to load the correct language. So use our own caching |
| 66 | +# on top of it. |
| 67 | +@functools.cache |
| 68 | +def get_name_for_type(typename: str, language: str, alt_language: str) -> str: |
64 | 69 | """Get the natural language description of the MIME type.
|
65 | 70 |
|
66 | 71 | typename: a MIME type, e.g., "application/pdf".
|
| 72 | + language: the BCP47 code of the language for which to return the result. |
| 73 | + alt_language: underscore-separated form of the language code, to work |
| 74 | + around incorrect behavior in pyxdg. |
67 | 75 |
|
68 | 76 | return: the human-readable description (also called comment)
|
69 | 77 | of the given MIME type, e.g., "PDF document".
|
70 | 78 |
|
71 | 79 | """
|
| 80 | + # pyxdg expects the locale field to be provided as a posix-style locale |
| 81 | + # name, e.g. zh_CN. It assumes this in both the provided language name, and |
| 82 | + # in the xml:lang attribute of the mimetype xml files. Some distributions |
| 83 | + # instead use BCP47 language codes, e.g. zh-Hans-CN, in the mimetype xml |
| 84 | + # files (which is semantically more correct, as this is mandated by the xml |
| 85 | + # spec). |
| 86 | + # First parse the language from the posix format. |
| 87 | + xdg.Locale.update(alt_language) |
| 88 | + # Then, we make pyxdg think the BCP47 code is another variant of the |
| 89 | + # current language name. |
| 90 | + xdg.Locale.langs += [language] |
72 | 91 | mimetype = xdg.Mime.lookup(typename).canonical()
|
| 92 | + # Force reloading the comment, because the language might have changed. |
| 93 | + mimetype._comment = None |
73 | 94 | return mimetype.get_comment()
|
74 | 95 |
|
75 | 96 |
|
|
0 commit comments