add language menu
[jSite2.git] / src / net / pterodactylus / jsite / i18n / I18n.java
1 /*
2  * jSite2 - I18n.java -
3  * Copyright © 2008 David Roden
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 package net.pterodactylus.jsite.i18n;
21
22 import java.awt.event.InputEvent;
23 import java.awt.event.KeyEvent;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.lang.reflect.Field;
27 import java.text.MessageFormat;
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.Locale;
31 import java.util.MissingResourceException;
32 import java.util.Properties;
33 import java.util.StringTokenizer;
34
35 import javax.swing.KeyStroke;
36
37 import net.pterodactylus.util.io.Closer;
38
39 /**
40  * Class that handles i18n.
41  * 
42  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
43  * @version $Id$
44  */
45 public class I18n {
46
47         /** List of I18nables that are notified when the language changes. */
48         private static final List<I18nable> i18nables = new ArrayList<I18nable>();
49
50         /** The current locale. */
51         private static Locale currentLocale;
52
53         /** The default language. */
54         private static Properties defaultLanguage;
55
56         /** The current language. */
57         private static Properties currentLanguage;
58
59         static {
60                 defaultLanguage = new Properties();
61                 InputStream inputStream = null;
62                 try {
63                         inputStream = I18n.class.getResourceAsStream("jSite.properties");
64                         if (inputStream != null) {
65                                 defaultLanguage.load(inputStream);
66                         }
67                 } catch (IOException e) {
68                         /* something is fucked. */
69                 }
70                 setLocale(Locale.getDefault(), false);
71         }
72
73         /**
74          * Returns the translated value for a key. The translated values may contain
75          * placeholders that are replaced with the given parameters.
76          * 
77          * @see MessageFormat
78          * @param key
79          *            The key to get
80          * @param parameters
81          *            The parameters in case the translated value contains
82          *            placeholders
83          * @return The translated message, or the key itself if no translation could
84          *         be found
85          */
86         public static String get(String key, Object... parameters) {
87                 String value = null;
88                 value = currentLanguage.getProperty(key);
89                 if (value == null) {
90                         return key;
91                 }
92                 if ((parameters != null) && (parameters.length > 0)) {
93                         return MessageFormat.format(value, parameters);
94                 }
95                 return value;
96         }
97
98         /**
99          * Returns the keycode from the value of the given key. You can specify the
100          * constants in {@link KeyEvent} in the properties file, e.g. VK_S for the
101          * keycode ‘s’ when used for mnemonics.
102          * 
103          * @param key
104          *            The key under which the keycode is stored
105          * @return The keycode
106          */
107         public static int getKey(String key) {
108                 String value = currentLanguage.getProperty(key);
109                 if (value == null) {
110                         return -1;
111                 }
112                 if (value.startsWith("VK_")) {
113                         try {
114                                 Field field = KeyEvent.class.getField(value);
115                                 return field.getInt(null);
116                         } catch (SecurityException e) {
117                                 /* ignore. */
118                         } catch (NoSuchFieldException e) {
119                                 /* ignore. */
120                         } catch (IllegalArgumentException e) {
121                                 /* ignore. */
122                         } catch (IllegalAccessException e) {
123                                 /* ignore. */
124                         }
125                 }
126                 return value.toUpperCase().charAt(0);
127         }
128
129         /**
130          * Returns a key stroke for use with swing accelerators.
131          * 
132          * @param key
133          *            The key of the key stroke
134          * @return The key stroke, or <code>null</code> if no key stroke could be
135          *         created from the translated value
136          */
137         public static KeyStroke getKeyStroke(String key) {
138                 String value = currentLanguage.getProperty(key);
139                 if (value == null) {
140                         return null;
141                 }
142                 StringTokenizer keyTokens = new StringTokenizer(value, "+- ");
143                 int modifierMask = 0;
144                 while (keyTokens.hasMoreTokens()) {
145                         String keyToken = keyTokens.nextToken();
146                         if ("ctrl".equalsIgnoreCase(keyToken)) {
147                                 modifierMask |= InputEvent.CTRL_DOWN_MASK;
148                         } else if ("alt".equalsIgnoreCase(keyToken)) {
149                                 modifierMask |= InputEvent.ALT_DOWN_MASK;
150                         } else if ("shift".equalsIgnoreCase(keyToken)) {
151                                 modifierMask |= InputEvent.SHIFT_DOWN_MASK;
152                         } else {
153                                 if (keyToken.startsWith("VK_")) {
154                                         try {
155                                                 Field field = KeyEvent.class.getField(keyToken);
156                                                 return KeyStroke.getKeyStroke(field.getInt(null), modifierMask);
157                                         } catch (SecurityException e) {
158                                                 /* ignore. */
159                                         } catch (NoSuchFieldException e) {
160                                                 /* ignore. */
161                                         } catch (IllegalArgumentException e) {
162                                                 /* ignore. */
163                                         } catch (IllegalAccessException e) {
164                                                 /* ignore. */
165                                         }
166                                 }
167                                 return KeyStroke.getKeyStroke(keyToken.charAt(0), modifierMask);
168                         }
169                 }
170                 return null;
171         }
172
173         /**
174          * Sets the current locale.
175          * 
176          * @param newLocale
177          *            The new locale to use
178          */
179         public static void setLocale(Locale newLocale) {
180                 setLocale(newLocale, true);
181         }
182
183         /**
184          * Sets the current locale.
185          * 
186          * @param newLocale
187          *            The new locale to use
188          * @param notify
189          *            <code>true</code> to notify registered {@link I18nable}s
190          *            after the language was changed
191          */
192         private static void setLocale(Locale newLocale, boolean notify) {
193                 currentLocale = newLocale;
194                 InputStream inputStream = null;
195                 try {
196                         currentLanguage = new Properties(defaultLanguage);
197                         if (newLocale == Locale.ENGLISH) {
198                                 if (notify) {
199                                         notifyI18nables();
200                                 }
201                                 return;
202                         }
203                         inputStream = I18n.class.getResourceAsStream("jSite_" + newLocale.getLanguage() + ".properties");
204                         if (inputStream != null) {
205                                 currentLanguage.load(inputStream);
206                                 if (notify) {
207                                         notifyI18nables();
208                                 }
209                         }
210                 } catch (MissingResourceException mre1) {
211                         currentLocale = Locale.ENGLISH;
212                 } catch (IOException ioe1) {
213                         currentLocale = Locale.ENGLISH;
214                 } finally {
215                         Closer.close(inputStream);
216                 }
217         }
218
219         /**
220          * Returns the current locale.
221          * 
222          * @return The current locale
223          */
224         public static Locale getLocale() {
225                 return currentLocale;
226         }
227
228         /**
229          * Finds all available locales.
230          * 
231          * @return All available locales
232          */
233         public static List<Locale> findAvailableLanguages() {
234                 List<Locale> availableLanguages = new ArrayList<Locale>();
235                 availableLanguages.add(Locale.ENGLISH);
236                 availableLanguages.add(Locale.GERMAN);
237                 return availableLanguages;
238         }
239
240         /**
241          * Registers the given I18nable to be updated when the language is changed.
242          * 
243          * @param i18nable
244          *            The i18nable to register
245          */
246         public static void registerI18nable(I18nable i18nable) {
247                 i18nables.add(i18nable);
248         }
249
250         /**
251          * Deregisters the given I18nable to be updated when the language is
252          * changed.
253          * 
254          * @param i18nable
255          *            The i18nable to register
256          */
257         public static void deregisterI18nable(I18nable i18nable) {
258                 i18nables.remove(i18nable);
259         }
260
261         //
262         // PRIVATE METHODS
263         //
264
265         /**
266          * Notifies all registered {@link I18nable}s that the language was changed.
267          */
268         private static void notifyI18nables() {
269                 for (I18nable i18nable: i18nables) {
270                         i18nable.updateI18n();
271                 }
272         }
273
274 }