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 @ 42184

History | View | Annotate | Download (17.2 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

    
16
import javax.swing.JComponent;
17
import javax.swing.SwingUtilities;
18

    
19
import org.apache.commons.configuration.PropertiesConfiguration;
20
import org.apache.commons.lang3.LocaleUtils;
21
import org.apache.commons.lang3.StringUtils;
22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24

    
25
import org.gvsig.andami.Launcher;
26
import org.gvsig.andami.LocaleManager;
27
import org.gvsig.andami.PluginServices;
28
import org.gvsig.andami.PluginsLocator;
29
import org.gvsig.andami.PluginsManager;
30
import org.gvsig.andami.config.generate.AndamiConfig;
31
import org.gvsig.andami.installer.translations.TranslationsInstallerFactory;
32
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
33
import org.gvsig.installer.lib.api.InstallerLocator;
34
import org.gvsig.installer.lib.api.InstallerManager;
35
import org.gvsig.utils.XMLEntity;
36

    
37
public class DefaultLocaleManager implements LocaleManager {
38

    
39
    private static final Logger logger
40
            = LoggerFactory.getLogger(DefaultLocaleManager.class);
41

    
42
    private static final String LOCALE_CODE_VALENCIANO = "vl";
43

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

    
51
    private static final String LOCALE_CONFIG_FILENAME = "locale.config";
52

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

    
79
    private Set installedLocales = null;
80
    private Set defaultLocales = null;
81

    
82
    private boolean storedInstalledLocales = false;
83

    
84
    public DefaultLocaleManager() {
85
        Locale currentLocale = org.gvsig.i18n.Messages.getCurrentLocale();
86
        this.setCurrentLocale(currentLocale);
87
    }
88

    
89
    public Locale getCurrentLocale() {
90
        return org.gvsig.i18n.Messages.getCurrentLocale();
91
    }
92

    
93
    public void setCurrentLocale(final Locale locale) {
94
        Locale nearestLocale = getNearestLocale(locale);
95
        if(nearestLocale == null){
96
            nearestLocale = this.getLocaleAlternatives(locale)[0];
97
        }
98
        org.gvsig.i18n.Messages.setCurrentLocale(nearestLocale, this.getLocaleAlternatives(nearestLocale));
99

    
100
        String localeStr = nearestLocale.getLanguage();
101
        if (localeStr.equalsIgnoreCase(LOCALE_CODE_VALENCIANO)) {
102
            Locale.setDefault(new Locale("ca"));
103
        } else {
104
            Locale.setDefault(nearestLocale);
105
        }
106

    
107
        AndamiConfig config = Launcher.getAndamiConfig();
108
        config.setLocaleLanguage(nearestLocale.getLanguage());
109
        config.setLocaleCountry(nearestLocale.getCountry());
110
        config.setLocaleVariant(nearestLocale.getVariant());
111

    
112
        setCurrentLocaleUI(nearestLocale);
113
    }
114

    
115
    public Locale getDefaultSystemLocale() {
116
        String language, region, country, variant;
117
        language = getSystemProperty("user.language", "en");
118
        // for compatibility, check for old user.region property
119
        region = getSystemProperty("user.region", null);
120

    
121
        if (region != null) {
122
            // region can be of form country, country_variant, or _variant
123
            int i = region.indexOf('_');
124
            if (i >= 0) {
125
                country = region.substring(0, i);
126
                variant = region.substring(i + 1);
127
            } else {
128
                country = region;
129
                variant = "";
130
            }
131
        } else {
132
            country = getSystemProperty("user.country", "");
133
            variant = getSystemProperty("user.variant", "");
134
        }
135
        return new Locale(language, country, variant);
136
    }
137

    
138
    private Set<Locale> loadLocalesFromConfing(File localesFile)  {
139
        PropertiesConfiguration config = null;
140
        if (!localesFile.canRead()) {
141
            return null;
142
        }
143
        try {
144
            config = new PropertiesConfiguration(localesFile);
145
        } catch (Exception ex) {
146
            logger.warn("Can't open locale configuration '" + localesFile + "'.", ex);
147
            return null;
148
        }
149

    
150
        Set<Locale> locales = new HashSet<Locale>();
151
        List localeCodes = config.getList("locale");
152
        for (Object localeCode : localeCodes) {
153
            try {
154
                Locale locale = LocaleUtils.toLocale((String) localeCode);
155
                locales.add(locale);
156
            } catch(IllegalArgumentException ex) {
157
                logger.warn("Can't load locale '"+localeCode+"' from config '"+localesFile.getAbsolutePath()+"'.",ex);
158
            }
159
        }
160
        return locales;
161
    }
162

    
163
    public Set<Locale> getDefaultLocales() {
164
        if (this.defaultLocales == null) {
165
            PluginsManager pluginsManager = PluginsLocator.getManager();
166
            File localesFile = new File(pluginsManager.getApplicationI18nFolder(), LOCALE_CONFIG_FILENAME);
167

    
168
            Set<Locale> locales = loadLocalesFromConfing(localesFile);
169
            defaultLocales = new HashSet<Locale>();
170
            if( locales == null ) {
171
                for (int i = 0; i < hardcoredLocales.length; i++) {
172
                    defaultLocales.add(hardcoredLocales[i]);
173
                }
174
            } else {
175
                defaultLocales.addAll(locales);
176
            }
177
        }
178
        return this.defaultLocales;
179
    }
180

    
181
    public boolean installLocales(URL localesFile) {
182
        PluginsManager pluginsManager = PluginsLocator.getManager();
183
        PropertiesConfiguration config = null;
184
        try {
185
            config = new PropertiesConfiguration(localesFile);
186
        } catch (Exception ex) {
187
            logger.warn("Can't open configuration '" + localesFile + "'.", ex);
188
        }
189
        if (config == null) {
190
            return false;
191
        }
192
        List localeCodes = config.getList("locale");
193
        for (Object localeCode : localeCodes) {
194
            Locale locale = LocaleUtils.toLocale((String) localeCode);
195
            if (!getInstalledLocales().contains(locale)) {
196
                this.installedLocales.add(locale);
197
            }
198
        }
199
        storeInstalledLocales();
200
        return true;
201
    }
202

    
203
    public Set<Locale> getInstalledLocales() {
204
        if (installedLocales == null) {
205
            installedLocales = new TreeSet<Locale>(new Comparator<Locale>() {
206
                public int compare(Locale t0, Locale t1) {
207
                    if (t1 == null || t0 == null) {
208
                        return 0;
209
                    }
210
                    // return getLanguageDisplayName(t0).compareToIgnoreCase(getLanguageDisplayName(t1));
211
                    return t0.toString().compareToIgnoreCase(t1.toString());
212
                }
213
            });
214

    
215
            XMLEntity child = getRegisteredLocalesPersistence();
216

    
217
            // If the list of registered locales is not already persisted,
218
            // this should be the first time gvSIG is run with the I18nPlugin
219
            // so we will take the list of default locales
220
            if (child == null) {
221
                installedLocales.addAll(getDefaultLocales());
222
            } else {
223
                XMLEntity localesEntity = child;
224
                for (int i = 0; i < localesEntity.getChildrenCount(); i++) {
225
                    Locale locale = null;
226
                    XMLEntity localeEntity = localesEntity.getChild(i);
227
                    String language = localeEntity.getStringProperty(LANGUAGE);
228
                    String country = localeEntity.getStringProperty(COUNTRY);
229
                    String variant = localeEntity.getStringProperty(VARIANT);
230
                    locale = new Locale(language, country, variant);
231
                    installedLocales.add(locale);
232
                }
233
            }
234
            Set<Locale> lfp = getAllLocalesFromPackages();
235
            installedLocales.addAll(lfp);
236
        }
237
        storeInstalledLocales();
238
        return Collections.unmodifiableSet(installedLocales);
239
    }
240

    
241
    public boolean installLocale(Locale locale) {
242
        // Add the locale to the list of installed ones, if it
243
        // is new, otherwise, update the texts.
244
        if (!getInstalledLocales().contains(locale)) {
245
            getInstalledLocales().add(locale);
246
            storeInstalledLocales();
247
        }
248
        return true;
249
    }
250

    
251
    public boolean uninstallLocale(Locale locale) {
252
        if (!getInstalledLocales().remove(locale)) {
253
            return false;
254
        }
255
        storeInstalledLocales();
256
        return true;
257
    }
258

    
259
    public String getLanguageDisplayName(Locale locale) {
260

    
261
        String displayName;
262

    
263
        if ("eu".equals(locale.getLanguage())
264
                && "vascuence".equals(locale.getDisplayLanguage())) {
265
            // Correction for the Basque language display name,
266
            // show it in Basque, not in Spanish
267
            displayName = "Euskera";
268
        } else if (LOCALE_CODE_VALENCIANO.equals(locale.getLanguage())) {
269
            // Patch for Valencian/Catalan
270
            displayName = "Valenci?";
271
        } else {
272
            displayName = locale.getDisplayLanguage(locale);
273
        }
274

    
275
        return StringUtils.capitalize(displayName);
276
    }
277

    
278
    public String getLocaleDisplayName(Locale locale) {
279
        String displayName = this.getLanguageDisplayName(locale);
280

    
281
        if( !StringUtils.isBlank(locale.getCountry()) ) {
282
            if( !StringUtils.isBlank(locale.getVariant()) ) {
283
                displayName = displayName + " (" +
284
                        StringUtils.capitalize(locale.getDisplayCountry(locale)) + "/" +
285
                        locale.getDisplayVariant(locale) + ")";
286
            } else {
287
                displayName = displayName + " ("+locale.getDisplayCountry(locale)+")";
288
            }
289
        }
290

    
291
        return displayName;
292
    }
293

    
294
    public Locale[] getLocaleAlternatives(Locale locale) {
295
        Locale alternatives[] = null;
296

    
297
        String localeStr = locale.getLanguage();
298
        if (localeStr.equals("es")
299
                || localeStr.equals("ca")
300
                || localeStr.equals("gl")
301
                || localeStr.equals("eu")
302
                || localeStr.equals(LOCALE_CODE_VALENCIANO)) {
303
            alternatives = new Locale[2];
304
            alternatives[0] = new Locale("es");
305
            alternatives[1] = new Locale("en");
306
        } else {
307
            // prefer English for the rest
308
            alternatives = new Locale[2];
309
            alternatives[0] = new Locale("en");
310
            alternatives[1] = new Locale("es");
311
        }
312
        return alternatives;
313
    }
314

    
315
    private void setCurrentLocaleUI(final Locale locale) {
316
        if (!SwingUtilities.isEventDispatchThread()) {
317
            try {
318
                SwingUtilities.invokeAndWait(new Runnable() {
319
                    public void run() {
320
                        setCurrentLocaleUI(locale);
321
                    }
322
                });
323
            } catch (Exception ex) {
324
                // Ignore
325
            }
326
        }
327
        try {
328
            JComponent.setDefaultLocale(locale);
329
        } catch (Exception ex) {
330
            logger.warn("Problems setting locale to JComponent.", ex);
331
        }
332
        if (MDIFrame.isInitialized()) {
333
            try {
334
                MDIFrame.getInstance().setLocale(locale);
335
            } catch (Exception ex) {
336
                logger.warn("Problems settings locale to MDIFrame.", ex);
337
            }
338
        }
339
    }
340

    
341
    public File getResourcesFolder() {
342
        File i18nFolder = new File(
343
                PluginsLocator.getManager().getApplicationHomeFolder(),
344
                INSTALLED_TRANSLATIONS_HOME_FOLDER
345
        );
346
        if (!i18nFolder.exists()) {
347
            i18nFolder.mkdirs();
348
        }
349
        return i18nFolder;
350
    }
351

    
352
    /**
353
     * Returns the child XMLEntity with the RegisteredLocales.
354
     */
355
    private XMLEntity getRegisteredLocalesPersistence() {
356
        XMLEntity entity = getI18nPersistence();
357
        if (entity == null) {
358
            return null;
359
        }
360
        XMLEntity child = null;
361
        for (int i = entity.getChildrenCount() - 1; i >= 0; i--) {
362
            XMLEntity tmpchild = entity.getChild(i);
363
            if (tmpchild.getName().equals(REGISTERED_LOCALES_PERSISTENCE)) {
364
                child = tmpchild;
365
                break;
366
            }
367
        }
368
        return child;
369
    }
370

    
371
    /**
372
     * Stores the list of installed locales into the plugin persistence.
373
     */
374
    private void storeInstalledLocales() {
375
        if(this.storedInstalledLocales ){
376
            return;
377
        }
378
        XMLEntity i18nPersistence = getI18nPersistence();
379
        if(i18nPersistence == null){
380
            return;
381
        }
382
        XMLEntity localesEntity = getRegisteredLocalesPersistence();
383

    
384
        // Remove the previous list of registered languages
385
        if (localesEntity != null) {
386
            for (int i = i18nPersistence.getChildrenCount() - 1; i >= 0; i--) {
387
                XMLEntity child = i18nPersistence.getChild(i);
388
                if (child.getName().equals(REGISTERED_LOCALES_PERSISTENCE)) {
389
                    i18nPersistence.removeChild(i);
390
                    break;
391
                }
392
            }
393
        }
394

    
395
        // Create the new persistence for the registered languages
396
        localesEntity = new XMLEntity();
397

    
398
        localesEntity.setName(REGISTERED_LOCALES_PERSISTENCE);
399

    
400
        Set<Locale> locales = this.installedLocales; //getInstalledLocales();
401
        for (Iterator iterator = locales.iterator(); iterator.hasNext();) {
402
            Locale locale = (Locale) iterator.next();
403
            XMLEntity localeEntity = new XMLEntity();
404
            localeEntity.setName(locale.getDisplayName());
405
            localeEntity.putProperty(LANGUAGE, locale.getLanguage());
406
            localeEntity.putProperty(COUNTRY, locale.getCountry());
407
            localeEntity.putProperty(VARIANT, locale.getVariant());
408

    
409
            localesEntity.addChild(localeEntity);
410
        }
411

    
412
        getI18nPersistence().addChild(localesEntity);
413
        this.storedInstalledLocales = true;
414
    }
415

    
416
    /**
417
     * Returns the I18n Plugin persistence.
418
     */
419
    private XMLEntity getI18nPersistence() {
420
        try {
421
            XMLEntity entity = PluginServices.getPluginServices(I18N_EXTENSION).getPersistentXML();
422
            return entity;
423
        } catch (Throwable t) {
424
            // logger.warn("Can't get I18nPersistence",t);
425
            return null;
426
        }
427
    }
428

    
429
    @SuppressWarnings("unchecked")
430
    private String getSystemProperty(final String property, String defaultValue) {
431
        String value
432
                = (String) AccessController.doPrivileged(new PrivilegedAction() {
433
                    public Object run() {
434
                        return System.getProperty(property);
435
                    }
436
                });
437
        return value == null ? defaultValue : value;
438
    }
439

    
440
    private Set<Locale> getAllLocalesFromPackages() {
441
        Set<Locale> locales = new HashSet<Locale>();
442
        InstallerManager installerManager = InstallerLocator.getInstallerManager();
443
        List<File> folders = installerManager.getAddonFolders(TranslationsInstallerFactory.PROVIDER_NAME);
444
        for( File folder : folders ) {
445
            File file = new File(folder,LOCALE_CONFIG_FILENAME);
446
            Set<Locale> l = this.loadLocalesFromConfing(file);
447
            locales.addAll(l);
448
        }
449
        return locales;
450
    }
451

    
452
    public Locale getNearestLocale(Locale locale) {
453
        String language = locale.getLanguage();
454
        String country = locale.getCountry();
455
        String variant = locale.getVariant();
456
        Locale nearestLocale;
457
        if (language != null && !language.isEmpty()) {
458
            if (country != null && !country.isEmpty()) {
459
                if(variant != null && !variant.isEmpty()){
460
                    nearestLocale = new Locale(language, country, variant);
461
                    if (getInstalledLocales().contains(nearestLocale)) {
462
                        return nearestLocale;
463
                    }
464
                }
465
                nearestLocale = new Locale(language, country);
466
                if (getInstalledLocales().contains(nearestLocale)) {
467
                    return nearestLocale;
468
                }
469
            }
470
            nearestLocale = new Locale(language);
471
            if (getInstalledLocales().contains(nearestLocale)) {
472
                return nearestLocale;
473
            }
474
        }
475
        return null;
476
    }
477
}