aboutsummaryrefslogtreecommitdiffstats
path: root/tools/java/org/unicode/cldr/util/CLDRLocale.java
blob: aae22e6138dc8d4a4dd83b8bb1aa362b484838bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// Copyright (C) 2008-2012 IBM Corporation and Others. All Rights Reserved.

package org.unicode.cldr.util;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.ibm.icu.text.LocaleDisplayNames;
import com.ibm.icu.text.Transform;
import com.ibm.icu.util.ULocale;

/**
 * This class implements a CLDR UTS#35 compliant locale.
 * It differs from ICU and Java locales in that it is singleton based, and that it is Comparable.
 * It uses LocaleIDParser to do the heavy lifting of parsing.
 *
 * @author srl
 * @see LocaleIDParser
 * @see ULocale
 */
public final class CLDRLocale implements Comparable<CLDRLocale> {
    private static final boolean DEBUG = false;

    public interface NameFormatter {
        String getDisplayName(CLDRLocale cldrLocale);

        String getDisplayName(CLDRLocale cldrLocale, boolean onlyConstructCompound, Transform<String, String> altPicker);

        String getDisplayLanguage(CLDRLocale cldrLocale);

        String getDisplayScript(CLDRLocale cldrLocale);

        String getDisplayVariant(CLDRLocale cldrLocale);

        String getDisplayCountry(CLDRLocale cldrLocale);
    }

    public static class SimpleFormatter implements NameFormatter {
        private LocaleDisplayNames ldn;

        public SimpleFormatter(ULocale displayLocale) {
            this.ldn = LocaleDisplayNames.getInstance(displayLocale);
        }

        public LocaleDisplayNames getDisplayNames() {
            return ldn;
        }

        public LocaleDisplayNames setDisplayNames(LocaleDisplayNames ldn) {
            return this.ldn = ldn;
        }

        @Override
        public String getDisplayVariant(CLDRLocale cldrLocale) {
            return ldn.variantDisplayName(cldrLocale.getVariant());
        }

        @Override
        public String getDisplayCountry(CLDRLocale cldrLocale) {
            return ldn.regionDisplayName(cldrLocale.getCountry());
        }

        @Override
        public String getDisplayName(CLDRLocale cldrLocale) {
            StringBuffer sb = new StringBuffer();
            String l = cldrLocale.getLanguage();
            String s = cldrLocale.getScript();
            String r = cldrLocale.getCountry();
            String v = cldrLocale.getVariant();

            if (l != null && !l.isEmpty()) {
                sb.append(getDisplayLanguage(cldrLocale));
            } else {
                sb.append("?");
            }
            if ((s != null && !s.isEmpty()) ||
                (r != null && !r.isEmpty()) ||
                (v != null && !v.isEmpty())) {
                sb.append(" (");
                if (s != null && !s.isEmpty()) {
                    sb.append(getDisplayScript(cldrLocale)).append(",");
                }
                if (r != null && !r.isEmpty()) {
                    sb.append(getDisplayCountry(cldrLocale)).append(",");
                }
                if (v != null && !v.isEmpty()) {
                    sb.append(getDisplayVariant(cldrLocale)).append(",");
                }
                sb.replace(sb.length() - 1, sb.length(), ")");
            }
            return sb.toString();
        }

        @Override
        public String getDisplayScript(CLDRLocale cldrLocale) {
            return ldn.scriptDisplayName(cldrLocale.getScript());
        }

        @Override
        public String getDisplayLanguage(CLDRLocale cldrLocale) {
            return ldn.languageDisplayName(cldrLocale.getLanguage());
        }

        @Override
        public String getDisplayName(CLDRLocale cldrLocale, boolean onlyConstructCompound, Transform<String, String> altPicker) {
            return getDisplayName(cldrLocale);
        }
    }

    /**
     * @author srl
     *
     * This formatter will delegate to CLDRFile.getName if a CLDRFile is given, otherwise StandardCodes
     */
    public static class CLDRFormatter extends SimpleFormatter {
        private FormatBehavior behavior = FormatBehavior.extend;

        private CLDRFile file = null;

        public CLDRFormatter(CLDRFile fromFile) {
            super(CLDRLocale.getInstance(fromFile.getLocaleID()).toULocale());
            file = fromFile;
        }

        public CLDRFormatter(CLDRFile fromFile, FormatBehavior behavior) {
            super(CLDRLocale.getInstance(fromFile.getLocaleID()).toULocale());
            this.behavior = behavior;
            file = fromFile;
        }

        public CLDRFormatter() {
            super(ULocale.ROOT);
        }

        public CLDRFormatter(FormatBehavior behavior) {
            super(ULocale.ROOT);
            this.behavior = behavior;
        }

        @Override
        public String getDisplayVariant(CLDRLocale cldrLocale) {
            if (file != null) return file.getName("variant", cldrLocale.getVariant());
            return tryForBetter(super.getDisplayVariant(cldrLocale),
                cldrLocale.getVariant(),
                "variant");
        }

        @Override
        public String getDisplayName(CLDRLocale cldrLocale) {
            if (file != null) return file.getName(cldrLocale.toDisplayLanguageTag(), true, null);
            return super.getDisplayName(cldrLocale);
        }

        @Override
        public String getDisplayName(CLDRLocale cldrLocale, boolean onlyConstructCompound, Transform<String, String> altPicker) {
            if (file != null) return file.getName(cldrLocale.toDisplayLanguageTag(), onlyConstructCompound, altPicker);
            return super.getDisplayName(cldrLocale);
        }

        @Override
        public String getDisplayScript(CLDRLocale cldrLocale) {
            if (file != null) return file.getName("script", cldrLocale.getScript());
            return tryForBetter(super.getDisplayScript(cldrLocale),
                cldrLocale.getScript(),
                "language");
        }

        @Override
        public String getDisplayLanguage(CLDRLocale cldrLocale) {
            if (file != null) return file.getName("language", cldrLocale.getLanguage());
            return tryForBetter(super.getDisplayLanguage(cldrLocale),
                cldrLocale.getLanguage(),
                "language");
        }

        @Override
        public String getDisplayCountry(CLDRLocale cldrLocale) {
            if (file != null) return file.getName("territory", cldrLocale.getCountry());
            return tryForBetter(super.getDisplayLanguage(cldrLocale),
                cldrLocale.getLanguage(),
                "territory");
        }

        private String tryForBetter(String superString, String code, String type) {
            if (superString.equals(code)) {
                String fromLst = StandardCodes.make().getData("language", code);
                if (fromLst != null && !fromLst.equals(code)) {
                    switch (behavior) {
                    case replace:
                        return fromLst;
                    case extend:
                        return superString + " [" + fromLst + "]";
                    case extendHtml:
                        return superString + " [<i>" + fromLst + "</i>]";
                    }
                }
            }
            return superString;
        }
    }

    public enum FormatBehavior {
        replace, extend, extendHtml
    };

    /**
     * Reference to the parent CLDRLocale
     */
    private CLDRLocale parent = null;
    /**
     * Cached ICU format locale
     */
    private ULocale ulocale;
    /**
     * base name, 'without parameters'. Currently same as fullname.
     */
    private String basename;
    /**
     * Full name
     */
    private String fullname;
    /**
     * The LocaleIDParser interprets the various parts (language, country, script, etc).
     */
    private LocaleIDParser parts = null;

    /**
     * Construct a CLDRLocale from an ICU ULocale.
     * Internal, called by the factory function.
     */
    private CLDRLocale(ULocale loc) {
        init(loc);
    }

    /**
     * Returns the BCP47 langauge tag for all except root. For root, returns "root".
     * @return
     */
    private String toDisplayLanguageTag() {
        if (getBaseName().equals("root")) {
            return "root";
        } else {
            return toLanguageTag();
        }
    }

    /**
     * Return BCP47 language tag
     * @return
     */
    public String toLanguageTag() {
        return ulocale.toLanguageTag();
    }

    /**
     * Construct a CLDRLocale from a string with the full locale ID.
     * Internal, called by the factory function.
     *
     * @param str
     */
    private CLDRLocale(String str) {
        init(str);
    }

    /**
     * Initialize a CLDRLocale from a ULocale
     *
     * @param loc
     */
    private void init(ULocale loc) {
        ulocale = loc;
        init(loc.getBaseName());
    }

    /**
     * Initialize a CLDRLocale from a string.
     *
     * @param str
     */
    private void init(String str) {
        // if(str.length()==0) {
        // str = "root";
        // }
        str = process(str);
        // System.err.println("bn: " + str);
        if (str.equals(ULocale.ROOT.getBaseName()) || str.equalsIgnoreCase("root")) {
            fullname = "root";
            parent = null;
        } else {
            parts = new LocaleIDParser();
            parts.set(str);
            fullname = parts.toString();
            String parentId = LocaleIDParser.getParent(str);
            if (DEBUG) System.out.println(str + " par = " + parentId);
            if (parentId != null) {
                parent = CLDRLocale.getInstance(parentId);
            } else {
                parent = null; // probably, we are root or we are supplemental
            }
        }
        basename = fullname;
        if (ulocale == null) {
            ulocale = new ULocale(fullname);
        }
    }

    /**
     * Return the full locale name, in CLDR format.
     */
    public String toString() {
        return fullname;
    }

    /**
     * Return the base locale name, in CLDR format, without any @keywords
     *
     * @return
     */
    public String getBaseName() {
        return basename;
    }

    /**
     * internal: process a string from ICU to CLDR form. For now, just collapse double underscores.
     *
     * @param baseName
     * @return
     * @internal
     */
    private String process(String baseName) {
        return baseName.replaceAll("__", "_");
    }

    /**
     * Compare to another CLDRLocale. Uses string order of toString().
     */
    public int compareTo(CLDRLocale o) {
        if (o == this) return 0;
        return fullname.compareTo(o.fullname);
    }

    /**
     * Hashcode - is the hashcode of the full string
     */
    public int hashCode() {
        return fullname.hashCode();
    }

    /**
     * Convert to an ICU compatible ULocale.
     *
     * @return
     */
    public ULocale toULocale() {
        return ulocale;
    }

    /**
     * Allocate a CLDRLocale (could be a singleton). If null is passed in, null will be returned.
     *
     * @param s
     * @return
     */
    public static CLDRLocale getInstance(String s) {
        if (s == null) return null;
        CLDRLocale loc = stringToLoc.get(s);
        if (loc == null) {
            loc = new CLDRLocale(s);
            loc.register();
        }
        return loc;
    }

    /**
     * Public factory function. Allocate a CLDRLocale (could be a singleton). If null is passed in, null will be
     * returned.
     *
     * @param u
     * @return
     */
    public static CLDRLocale getInstance(ULocale u) {
        if (u == null) return null;
        CLDRLocale loc = ulocToLoc.get(u);
        if (loc == null) {
            loc = new CLDRLocale(u);
            loc.register();
        }
        return loc;
    }

    /**
     * Register the singleton instance.
     */
    private void register() {
        stringToLoc.put(this.toString(), this);
        ulocToLoc.put(this.toULocale(), this);
    }

    private static Hashtable<String, CLDRLocale> stringToLoc = new Hashtable<String, CLDRLocale>();
    private static Hashtable<ULocale, CLDRLocale> ulocToLoc = new Hashtable<ULocale, CLDRLocale>();

    /**
     * Return the parent locale of this item. Null if no parent (root has no parent)
     *
     * @return
     */
    public CLDRLocale getParent() {
        return parent;
    }

    /**
     * Returns true if other is equal to or is an ancestor of this, false otherwise
     */
    public boolean childOf(CLDRLocale other) {
        if (other == null) return false;
        if (other == this) return true;
        if (parent == null) return false; // end
        return parent.childOf(other);
    }

    /**
     * Return an iterator that will iterate over locale, parent, parent etc, finally reaching root.
     *
     * @return
     */
    public Iterable<CLDRLocale> getParentIterator() {
        final CLDRLocale newThis = this;
        return new Iterable<CLDRLocale>() {
            public Iterator<CLDRLocale> iterator() {
                return new Iterator<CLDRLocale>() {
                    CLDRLocale what = newThis;

                    public boolean hasNext() {
                        // TODO Auto-generated method stub
                        return what.getParent() != null;
                    }

                    public CLDRLocale next() {
                        // TODO Auto-generated method stub
                        CLDRLocale curr = what;
                        if (what != null) {
                            what = what.getParent();
                        }
                        return curr;
                    }

                    public void remove() {
                        throw new InternalError("unmodifiable iterator");
                    }

                };
            }
        };
    }

    /**
     * Get the 'language' locale, as an object. Might be 'this'.
     * @return
     */
    public CLDRLocale getLanguageLocale() {
        return getInstance(getLanguage());
    }

    public String getLanguage() {
        return parts == null ? fullname : parts.getLanguage();
    }

    public String getScript() {
        return parts == null ? null : parts.getScript();
    }

    public boolean isLanguageLocale() {
        return this.equals(getLanguageLocale());
    }

    /**
     * Return the region
     *
     * @return
     */
    public String getCountry() {
        return parts == null ? null : parts.getRegion();
    }

    /**
     * Return "the" variant.
     *
     * @return
     */
    public String getVariant() {
        return toULocale().getVariant(); // TODO: replace with parts?
    }

    /**
     * Most objects should be singletons, and so equality/inequality comparison is done first.
     */
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof CLDRLocale)) return false;
        return (0 == compareTo((CLDRLocale) o));
    }

    /**
     * The root locale, a singleton.
     */
    public static final CLDRLocale ROOT = getInstance(ULocale.ROOT);

    public String getDisplayName() {
        return getDisplayName(getDefaultFormatter());
    }

    public String getDisplayRegion() {
        return getDisplayCountry(getDefaultFormatter());
    }

    public String getDisplayVariant() {
        return getDisplayVariant(getDefaultFormatter());
    }

    public String getDisplayName(boolean combined, Transform<String, String> picker) {
        return getDisplayName(getDefaultFormatter(), combined, picker);
    }

    /**
     * These functions wrap calls to the displayLocale, but are provided to supply an interface that looks similar to
     * ULocale.getDisplay___(displayLocale)
     *
     * @param displayLocale
     * @return
     */
    public String getDisplayName(NameFormatter displayLocale) {
        if (displayLocale == null) displayLocale = getDefaultFormatter();
        return displayLocale.getDisplayName(this);
    }

//    private static LruMap<ULocale, NameFormatter> defaultFormatters = new LruMap<ULocale, NameFormatter>(1);
    private static Cache<ULocale, NameFormatter> defaultFormatters = CacheBuilder.newBuilder().initialCapacity(1).build();
    private static NameFormatter gDefaultFormatter = getSimpleFormatterFor(ULocale.getDefault());

    public static NameFormatter getSimpleFormatterFor(ULocale loc) {
//        NameFormatter nf = defaultFormatters.get(loc);
//        if (nf == null) {
//            nf = new SimpleFormatter(loc);
//            defaultFormatters.put(loc, nf);
//        }
//        return nf;
//        return defaultFormatters.getIfPresent(loc);
        final ULocale uLocFinal = loc;
        try {
            return defaultFormatters.get(loc, new Callable<NameFormatter>() {

                @Override
                public NameFormatter call() throws Exception {
                    return new SimpleFormatter(uLocFinal);
                }
            });
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public String getDisplayName(ULocale displayLocale) {
        return getSimpleFormatterFor(displayLocale).getDisplayName(this);
    }

    public static NameFormatter getDefaultFormatter() {
        return gDefaultFormatter;
    }

    public static NameFormatter setDefaultFormatter(NameFormatter nf) {
        return gDefaultFormatter = nf;
    }

    /**
     * These functions wrap calls to the displayLocale, but are provided to supply an interface that looks similar to
     * ULocale.getDisplay___(displayLocale)
     *
     * @param displayLocale
     * @return
     */
    public String getDisplayCountry(NameFormatter displayLocale) {
        if (displayLocale == null) displayLocale = getDefaultFormatter();
        return displayLocale.getDisplayCountry(this);
    }

    /**
     * These functions wrap calls to the displayLocale, but are provided to supply an interface that looks similar to
     * ULocale.getDisplay___(displayLocale)
     *
     * @param displayLocale
     * @return
     */
    public String getDisplayVariant(NameFormatter displayLocale) {
        if (displayLocale == null) displayLocale = getDefaultFormatter();
        return displayLocale.getDisplayVariant(this);
    }

    /**
     * Construct an instance from an array
     *
     * @param available
     * @return
     */
    public static Set<CLDRLocale> getInstance(Iterable<String> available) {
        Set<CLDRLocale> s = new TreeSet<CLDRLocale>();
        for (String str : available) {
            s.add(CLDRLocale.getInstance(str));
        }
        return s;
    }

    public interface SublocaleProvider {
        public Set<CLDRLocale> subLocalesOf(CLDRLocale forLocale);
    }

    public String getDisplayName(NameFormatter engFormat, boolean combined, Transform<String, String> picker) {
        return engFormat.getDisplayName(this, combined, picker);
    }

    /**
     * Return the highest parent that is a child of root, or null.
     * @return highest parent, or null.  ROOT.getHighestNonrootParent() also returns null.
     */
    public CLDRLocale getHighestNonrootParent() {
        CLDRLocale res;
        if (this == ROOT) {
            res = null;
            ;
        } else if (this.parent == ROOT) {
            res = this;
        } else if (this.parent == null) {
            res = this;
        } else {
            res = parent.getHighestNonrootParent();
        }
        if (DEBUG) System.out.println(this + ".HNRP=" + res);
        return res;
    }
}