diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 18e328d6..dfea7c3a 100755 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -42,7 +42,7 @@ if __debug__: signal.signal(signal.SIGTERM, lambda sig, frame: pdb.Pdb().set_trace(frame)) from l10n import Translations -Translations().install(config.get('language') or None) +Translations.install(config.get('language') or None) import companion import commodity diff --git a/PLUGINS.md b/PLUGINS.md index 5e10a76b..e07a7cdf 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -160,12 +160,36 @@ You can display an error in EDMC's status area by returning a string from your ` The status area is shared between EDMC itself and all other plugins, so your message won't be displayed for very long. Create a dedicated widget if you need to display routine status information. +## Localisation + +You can localise your plugin to one of the languages that EDMC itself supports. Add the following boilerplate near the top of each source file that contains strings that needs translating: + +```python +import l10n +import functools +_ = functools.partial(l10n.Translations.translate, context=__file__) +``` + +Wrap each string that needs translating with the `_()` function, e.g.: + +```python + this.status["text"] = _('Happy!') # Main window status +``` + +If you display localized strings in EDMC's main window you should refresh them in your `prefs_changed` function in case the user has changed their preferred language. + +Translation files should reside in folder named `L10n` inside your plugin's folder. Files must be in macOS/iOS ".strings" format, encoded as UTF-8. You can generate a starting template file for your translations by invoking `l10n.py` in your plugin's folder. This extracts all the translatable strings from Python files in your plugin's folder and places them in a file named `en.template` in the `L10n` folder. Rename this file as `.strings` and edit it. + +See EDMC's own [`L10n`](https://github.com/Marginal/EDMarketConnector/tree/master/L10n) folder for the list of supported language codes and for example translation files. + + # Python Package Plugins A _Package Plugin_ is both a standard Python package (i.e. contains an `__init__.py` file) and an EDMC plugin (i.e. contains a `load.py` file providing at minimum a `plugin_start()` function). These plugins are loaded before any non-Package plugins. Other plugins can access features in a Package Plugin by `import`ing the package by name in the usual way. + # Distributing a Plugin To package your plugin for distribution simply create a `.zip` archive of your plugin's folder: diff --git a/dashboard.py b/dashboard.py index 667ef618..e224b4ba 100644 --- a/dashboard.py +++ b/dashboard.py @@ -1,8 +1,8 @@ import json from calendar import timegm from operator import itemgetter -from os import listdir, stat -from os.path import isdir, isfile, join +from os import listdir +from os.path import isdir, isfile, join, getsize from sys import platform import time @@ -111,7 +111,7 @@ class Dashboard(FileSystemEventHandler): def on_modified(self, event): # watchdog callback - DirModifiedEvent on macOS, FileModifiedEvent on Windows - if event.is_directory or (isfile(event.src_path) and stat(event.src_path).st_size): # Can get on_modified events when the file is emptied + if event.is_directory or (isfile(event.src_path) and getsize(event.src_path)): # Can get on_modified events when the file is emptied self.process(event.src_path if not event.is_directory else None) # Can be called either in watchdog thread or, if polling, in main thread. diff --git a/l10n.py b/l10n.py index ee4d7177..d3bd1576 100755 --- a/l10n.py +++ b/l10n.py @@ -7,17 +7,21 @@ import codecs from collections import OrderedDict import numbers import os -from os.path import basename, dirname, isfile, join, normpath +from os.path import basename, dirname, exists, isfile, isdir, join, normpath import re import sys from sys import platform +from traceback import print_exc import __builtin__ import locale locale.setlocale(locale.LC_ALL, '') +from config import config + # Language name LANGUAGE_ID = '!Language' +LOCALISATION_DIR = 'L10n' if platform == 'darwin': @@ -40,10 +44,6 @@ elif platform == 'win32': GetNumberFormatEx.restype = ctypes.c_int -else: # POSIX - import locale - - class Translations: FALLBACK = 'en' # strings in this code are in English @@ -81,13 +81,20 @@ class Translations: if lang not in self.available(): self.install_dummy() else: - self.translations = self.contents(lang) + self.translations = { None: self.contents(lang) } + for plugin in os.listdir(config.plugin_dir): + plugin_path = join(config.plugin_dir, plugin, LOCALISATION_DIR) + if isdir(plugin_path): + self.translations[plugin] = self.contents(lang, plugin_path) __builtin__.__dict__['_'] = self.translate - def contents(self, lang): + def contents(self, lang, plugin_path=None): assert lang in self.available() translations = {} - with self.file(lang) as h: + h = self.file(lang, plugin_path) + if not h: + return {} + else: for line in h: if line.strip(): match = Translations.TRANS_RE.match(line) @@ -99,11 +106,18 @@ class Translations: translations[LANGUAGE_ID] = unicode(lang) # Replace language name with code if missing return translations - def translate(self, x): - if __debug__: - if x not in self.translations: - print 'Missing translation: "%s"' % x - return self.translations.get(x) or unicode(x).replace(ur'\"', u'"').replace(u'{CR}', u'\n') + def translate(self, x, context=None): + if context: + context = context[len(config.plugin_dir)+1:].split(os.sep)[0] + if __debug__: + if context not in self.translations: + print 'No translations for "%s"' % context + return self.translations.get(context, {}).get(x) or self.translate(x) + else: + if __debug__: + if x not in self.translations[None]: + print 'Missing translation: "%s"' % x + return self.translations[None].get(x) or unicode(x).replace(ur'\"', u'"').replace(u'{CR}', u'\n') # Returns list of available language codes def available(self): @@ -129,14 +143,22 @@ class Translations: if platform=='darwin': return normpath(join(dirname(sys.executable.decode(sys.getfilesystemencoding())), os.pardir, 'Resources')) else: - return join(dirname(sys.executable.decode(sys.getfilesystemencoding())), 'L10n') + return join(dirname(sys.executable.decode(sys.getfilesystemencoding())), LOCALISATION_DIR) elif __file__: - return join(dirname(__file__), 'L10n') + return join(dirname(__file__), LOCALISATION_DIR) else: - return 'L10n' + return LOCALISATION_DIR - def file(self, lang): - if getattr(sys, 'frozen', False) and platform=='darwin': + def file(self, lang, plugin_path=None): + if plugin_path: + f = join(plugin_path, '%s.strings' % lang) + if exists(f): + try: + return codecs.open(f, 'r', 'utf-8') + except: + print_exc() + return None + elif getattr(sys, 'frozen', False) and platform=='darwin': return codecs.open(join(self.respath(), '%s.lproj' % lang, 'Localizable.strings'), 'r', 'utf-16') else: return codecs.open(join(self.respath(), '%s.strings' % lang), 'r', 'utf-8') @@ -218,8 +240,9 @@ class Locale: lang = locale.getlocale()[0] return lang and [lang.replace('_','-')] -# singleton +# singletons Locale = Locale() +Translations = Translations() # generate template strings file - like xgettext @@ -229,7 +252,7 @@ if __name__ == "__main__": regexp = re.compile(r'''_\([ur]?(['"])(((?