Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.framework / org.gvsig.andami / src / main / java / org / gvsig / andami / impl / DefaultLocaleManager.java @ 41693

History | View | Annotate | Download (14.6 KB)

1
package org.gvsig.andami.impl;
2

    
3
import java.io.File;
4
import java.net.URL;
5
import java.security.AccessController;
6
import java.security.PrivilegedAction;
7
import java.util.Collections;
8
import java.util.Comparator;
9
import java.util.HashSet;
10
import java.util.Iterator;
11
import java.util.List;
12
import java.util.Locale;
13
import java.util.Set;
14
import java.util.TreeSet;
15
import javax.swing.JComponent;
16
import javax.swing.SwingUtilities;
17
import org.apache.commons.configuration.PropertiesConfiguration;
18
import org.apache.commons.lang3.LocaleUtils;
19
import org.apache.commons.lang3.StringUtils;
20
import org.gvsig.andami.Launcher;
21
import org.gvsig.andami.LocaleManager;
22
import org.gvsig.andami.PluginServices;
23
import org.gvsig.andami.PluginsLocator;
24
import org.gvsig.andami.PluginsManager;
25
import org.gvsig.andami.config.generate.AndamiConfig;
26
import org.gvsig.andami.installer.translations.TranslationsInstallerFactory;
27
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
28
import org.gvsig.installer.lib.api.InstallerLocator;
29
import org.gvsig.installer.lib.api.InstallerManager;
30
import org.gvsig.utils.XMLEntity;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

    
34
public class DefaultLocaleManager implements LocaleManager {
35

    
36
    private static final Logger logger
37
            = LoggerFactory.getLogger(DefaultLocaleManager.class);
38

    
39
    private static final String LOCALE_CODE_VALENCIANO = "vl";
40

    
41
    private static final String I18N_EXTENSION = "org.gvsig.i18n.extension";
42
    private static final String INSTALLED_TRANSLATIONS_HOME_FOLDER = "i18n";
43
    private static final String VARIANT = "variant";
44
    private static final String COUNTRY = "country";
45
    private static final String LANGUAGE = "language";
46
    private static final String REGISTERED_LOCALES_PERSISTENCE = "RegisteredLocales";
47
    
48
    private static final String LOCALE_CONFIG_FILENAME = "locale.config";
49

    
50
    private final Locale[] hardcoredLocales = new Locale[]{
51
        // Default supported locales
52
        SPANISH, // Spanish
53
        ENGLISH, // English
54
        new Locale("en", "US"), // English US
55
        new Locale("ca"), // Catalan
56
        new Locale("gl"), // Galician
57
        new Locale("eu"), // Basque
58
        new Locale("de"), // German
59
        new Locale("cs"), // Czech
60
        new Locale("fr"), // French
61
        new Locale("it"), // Italian
62
        new Locale("pl"), // Polish
63
        new Locale("pt"), // Portuguese
64
        new Locale("pt", "BR"), // Portuguese Brazil
65
        new Locale("ro"), // Romanian
66
        new Locale("zh"), // Chinese
67
        new Locale("ru"), // Russian
68
        new Locale("el"), // Greek
69
        new Locale("ro"), // Romanian
70
        new Locale("pl"), // Polish
71
        new Locale("tr"), // Turkish
72
        new Locale("sr"), // Serbio
73
        new Locale("sw") // Swahili
74
    };
75

    
76
    private Set installedLocales = null;
77
    private Set defaultLocales = null;
78

    
79
    public DefaultLocaleManager() {
80
        Locale currentLocale = org.gvsig.i18n.Messages.getCurrentLocale();
81
        this.setCurrentLocale(currentLocale);
82
    }
83

    
84
    public Locale getCurrentLocale() {
85
        return org.gvsig.i18n.Messages.getCurrentLocale();
86
    }
87

    
88
    public void setCurrentLocale(final Locale locale) {
89
        org.gvsig.i18n.Messages.setCurrentLocale(locale, this.getLocaleAlternatives(locale));
90

    
91
        String localeStr = locale.getLanguage();
92
        if (localeStr.equalsIgnoreCase(LOCALE_CODE_VALENCIANO)) {
93
            Locale.setDefault(new Locale("ca"));
94
        } else {
95
            Locale.setDefault(locale);
96
        }
97

    
98
        AndamiConfig config = Launcher.getAndamiConfig();
99
        config.setLocaleLanguage(locale.getLanguage());
100
        config.setLocaleCountry(locale.getCountry());
101
        config.setLocaleVariant(locale.getVariant());
102

    
103
        setCurrentLocaleUI(locale);
104
    }
105

    
106
    public Locale getDefaultSystemLocale() {
107
        String language, region, country, variant;
108
        language = getSystemProperty("user.language", "en");
109
        // for compatibility, check for old user.region property
110
        region = getSystemProperty("user.region", null);
111

    
112
        if (region != null) {
113
            // region can be of form country, country_variant, or _variant
114
            int i = region.indexOf('_');
115
            if (i >= 0) {
116
                country = region.substring(0, i);
117
                variant = region.substring(i + 1);
118
            } else {
119
                country = region;
120
                variant = "";
121
            }
122
        } else {
123
            country = getSystemProperty("user.country", "");
124
            variant = getSystemProperty("user.variant", "");
125
        }
126
        return new Locale(language, country, variant);
127
    }
128

    
129
    public Set<Locale> loadLocalesFromConfing(File localesFile)  { 
130
        PropertiesConfiguration config = null;
131
        if (!localesFile.canRead()) {
132
            return null;
133
        }
134
        try {
135
            config = new PropertiesConfiguration(localesFile);
136
        } catch (Exception ex) {
137
            logger.warn("Can't open locale configuration '" + localesFile + "'.", ex);
138
            return null;
139
        }
140
        
141
        Set<Locale> locales = new HashSet<Locale>();
142
        List localeCodes = config.getList("locale");
143
        for (Object localeCode : localeCodes) {
144
            Locale locale = LocaleUtils.toLocale((String) localeCode);
145
            locales.add(locale);
146
        }
147
        return locales;
148
    }
149
    
150
    public Set<Locale> getDefaultLocales() {
151
        if (this.defaultLocales == null) {
152
            PluginsManager pluginsManager = PluginsLocator.getManager();
153
            File localesFile = new File(pluginsManager.getApplicationI18nFolder(), LOCALE_CONFIG_FILENAME);
154
            
155
            Set<Locale> locales = loadLocalesFromConfing(localesFile);
156
            defaultLocales = new HashSet<Locale>();
157
            if( locales == null ) {
158
                for (int i = 0; i < hardcoredLocales.length; i++) {
159
                    defaultLocales.add(hardcoredLocales[i]);
160
                }
161
            } else {
162
                defaultLocales.addAll(locales);
163
            }
164
        }
165
        return this.defaultLocales;
166
    }
167

    
168
    public boolean installLocales(URL localesFile) {
169
        PluginsManager pluginsManager = PluginsLocator.getManager();
170
        PropertiesConfiguration config = null;
171
        try {
172
            config = new PropertiesConfiguration(localesFile);
173
        } catch (Exception ex) {
174
            logger.warn("Can't open configuration '" + localesFile + "'.", ex);
175
        }
176
        if (config == null) {
177
            return false;
178
        }
179
        List localeCodes = config.getList("locale");
180
        for (Object localeCode : localeCodes) {
181
            Locale locale = LocaleUtils.toLocale((String) localeCode);
182
            if (!getInstalledLocales().contains(locale)) {
183
                this.installedLocales.add(locale);
184
            }
185
        }
186
        storeInstalledLocales();
187
        return true;
188
    }
189

    
190
    public Set<Locale> getInstalledLocales() {
191
        if (installedLocales == null) {
192
            installedLocales = new TreeSet<Locale>(new Comparator<Locale>() {
193
                public int compare(Locale t0, Locale t1) {
194
                    if (t1 == null || t0 == null) {
195
                        return 0;
196
                    }
197
                    return getLanguageDisplayName(t0).compareToIgnoreCase(getLanguageDisplayName(t1));
198
                }
199
            });
200

    
201
            XMLEntity child = getRegisteredLocalesPersistence();
202

    
203
            // If the list of registered locales is not already persisted,
204
            // this should be the first time gvSIG is run with the I18nPlugin
205
            // so we will take the list of default locales
206
            if (child == null) {
207
                installedLocales.addAll(getDefaultLocales());
208
                storeInstalledLocales();
209
            } else {
210
                XMLEntity localesEntity = getRegisteredLocalesPersistence();
211
                for (int i = 0; i < localesEntity.getChildrenCount(); i++) {
212
                    XMLEntity localeEntity = localesEntity.getChild(i);
213
                    String language = localeEntity.getStringProperty(LANGUAGE);
214
                    String country = localeEntity.getStringProperty(COUNTRY);
215
                    String variant = localeEntity.getStringProperty(VARIANT);
216
                    Locale locale = new Locale(language, country, variant);
217
                    installedLocales.add(locale);
218
                }
219
            }
220
            Set<Locale> lfp = getAllLocalesFromPackages();
221
            installedLocales.addAll(lfp);
222
        }
223
        return Collections.unmodifiableSet(installedLocales);
224
    }
225

    
226
    public boolean installLocale(Locale locale) {
227
        // Add the locale to the list of installed ones, if it
228
        // is new, otherwise, update the texts.
229
        if (!getInstalledLocales().contains(locale)) {
230
            getInstalledLocales().add(locale);
231
            storeInstalledLocales();
232
        }
233
        return true;
234
    }
235

    
236
    public boolean uninstallLocale(Locale locale) {
237
        if (!getInstalledLocales().remove(locale)) {
238
            return false;
239
        }
240
        storeInstalledLocales();
241
        return true;
242
    }
243

    
244
    public String getLanguageDisplayName(Locale locale) {
245

    
246
        String displayName;
247

    
248
        if ("eu".equals(locale.getLanguage())
249
                && "vascuence".equals(locale.getDisplayLanguage())) {
250
            // Correction for the Basque language display name,
251
            // show it in Basque, not in Spanish
252
            displayName = "Euskera";
253
        } else if (LOCALE_CODE_VALENCIANO.equals(locale.getLanguage())) {
254
            // Patch for Valencian/Catalan
255
            displayName = "Valenci?";
256
        } else {
257
            displayName = locale.getDisplayLanguage(locale);
258
        }
259

    
260
        return StringUtils.capitalize(displayName);
261
    }
262

    
263
    public Locale[] getLocaleAlternatives(Locale locale) {
264
        Locale alternatives[] = null;
265

    
266
        String localeStr = locale.getLanguage();
267
        if (localeStr.equals("es")
268
                || localeStr.equals("ca")
269
                || localeStr.equals("gl")
270
                || localeStr.equals("eu")
271
                || localeStr.equals(LOCALE_CODE_VALENCIANO)) {
272
            alternatives = new Locale[2];
273
            alternatives[0] = new Locale("es");
274
            alternatives[1] = new Locale("en");
275
        } else {
276
            // prefer English for the rest
277
            alternatives = new Locale[2];
278
            alternatives[0] = new Locale("en");
279
            alternatives[1] = new Locale("es");
280
        }
281
        return alternatives;
282
    }
283

    
284
    private void setCurrentLocaleUI(final Locale locale) {
285
        if (!SwingUtilities.isEventDispatchThread()) {
286
            try {
287
                SwingUtilities.invokeAndWait(new Runnable() {
288
                    public void run() {
289
                        setCurrentLocaleUI(locale);
290
                    }
291
                });
292
            } catch (Exception ex) {
293
                // Ignore
294
            }
295
        }
296
        try {
297
            JComponent.setDefaultLocale(locale);
298
        } catch (Exception ex) {
299
            logger.warn("Problems setting locale to JComponent.", ex);
300
        }
301
        if (MDIFrame.isInitialized()) {
302
            try {
303
                MDIFrame.getInstance().setLocale(locale);
304
            } catch (Exception ex) {
305
                logger.warn("Problems settings locale to MDIFrame.", ex);
306
            }
307
        }
308
    }
309

    
310
    public File getResourcesFolder() {
311
        File i18nFolder = new File(
312
                PluginsLocator.getManager().getApplicationHomeFolder(),
313
                INSTALLED_TRANSLATIONS_HOME_FOLDER
314
        );
315
        if (!i18nFolder.exists()) {
316
            i18nFolder.mkdirs();
317
        }
318
        return i18nFolder;
319
    }
320

    
321
    /**
322
     * Returns the child XMLEntity with the RegisteredLocales.
323
     */
324
    private XMLEntity getRegisteredLocalesPersistence() {
325
        XMLEntity entity = getI18nPersistence();
326
        XMLEntity child = null;
327
        for (int i = entity.getChildrenCount() - 1; i >= 0; i--) {
328
            XMLEntity tmpchild = entity.getChild(i);
329
            if (tmpchild.getName().equals(REGISTERED_LOCALES_PERSISTENCE)) {
330
                child = tmpchild;
331
                break;
332
            }
333
        }
334
        return child;
335
    }
336

    
337
    /**
338
     * Stores the list of installed locales into the plugin persistence.
339
     */
340
    private void storeInstalledLocales() {
341
        XMLEntity localesEntity = getRegisteredLocalesPersistence();
342

    
343
        // Remove the previous list of registered languages
344
        if (localesEntity != null) {
345
            XMLEntity i18nPersistence = getI18nPersistence();
346
            for (int i = i18nPersistence.getChildrenCount() - 1; i >= 0; i--) {
347
                XMLEntity child = i18nPersistence.getChild(i);
348
                if (child.getName().equals(REGISTERED_LOCALES_PERSISTENCE)) {
349
                    i18nPersistence.removeChild(i);
350
                    break;
351
                }
352
            }
353
        }
354

    
355
        // Create the new persistence for the registered languages
356
        localesEntity = new XMLEntity();
357

    
358
        localesEntity.setName(REGISTERED_LOCALES_PERSISTENCE);
359

    
360
        Set<Locale> locales = getInstalledLocales();
361
        for (Iterator iterator = locales.iterator(); iterator.hasNext();) {
362
            Locale locale = (Locale) iterator.next();
363
            XMLEntity localeEntity = new XMLEntity();
364
            localeEntity.setName(locale.getDisplayName());
365
            localeEntity.putProperty(LANGUAGE, locale.getLanguage());
366
            localeEntity.putProperty(COUNTRY, locale.getCountry());
367
            localeEntity.putProperty(VARIANT, locale.getVariant());
368

    
369
            localesEntity.addChild(localeEntity);
370
        }
371

    
372
        getI18nPersistence().addChild(localesEntity);
373
    }
374

    
375
    /**
376
     * Returns the I18n Plugin persistence.
377
     */
378
    private XMLEntity getI18nPersistence() {
379
        XMLEntity entity
380
                = PluginServices.getPluginServices(I18N_EXTENSION).getPersistentXML();
381
        return entity;
382
    }
383

    
384
    @SuppressWarnings("unchecked")
385
    private String getSystemProperty(final String property, String defaultValue) {
386
        String value
387
                = (String) AccessController.doPrivileged(new PrivilegedAction() {
388
                    public Object run() {
389
                        return System.getProperty(property);
390
                    }
391
                });
392
        return value == null ? defaultValue : value;
393
    }
394
    
395
    private Set<Locale> getAllLocalesFromPackages() {
396
        Set<Locale> locales = new HashSet<Locale>();
397
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
398
        List<File> folders = installerManager.getAddonFolders(TranslationsInstallerFactory.PROVIDER_NAME);
399
        for( File folder : folders ) {
400
            File file = new File(folder,LOCALE_CONFIG_FILENAME);
401
            Set<Locale> l = this.loadLocalesFromConfing(file);
402
            locales.addAll(l);
403
        }
404
        return locales;
405
    }
406
}