• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  **********************************************************************
3  *   Copyright (C) 1999-2007, International Business Machines
4  *   Corporation and others.  All Rights Reserved.
5  **********************************************************************
6  *   Date        Name        Description
7  *   11/17/99    aliu        Creation.
8  **********************************************************************
9  */
10 
11 #include "unicode/utypes.h"
12 
13 #if !UCONFIG_NO_TRANSLITERATION
14 
15 #include "unicode/putil.h"
16 #include "unicode/translit.h"
17 #include "unicode/locid.h"
18 #include "unicode/msgfmt.h"
19 #include "unicode/rep.h"
20 #include "unicode/resbund.h"
21 #include "unicode/unifilt.h"
22 #include "unicode/uniset.h"
23 #include "unicode/uscript.h"
24 #include "unicode/strenum.h"
25 #include "cpdtrans.h"
26 #include "nultrans.h"
27 #include "rbt_data.h"
28 #include "rbt_pars.h"
29 #include "rbt.h"
30 #include "transreg.h"
31 #include "name2uni.h"
32 #include "nortrans.h"
33 #include "remtrans.h"
34 #include "titletrn.h"
35 #include "tolowtrn.h"
36 #include "toupptrn.h"
37 #include "uni2name.h"
38 #include "esctrn.h"
39 #include "unesctrn.h"
40 #include "tridpars.h"
41 #include "anytrans.h"
42 #include "util.h"
43 #include "hash.h"
44 #include "mutex.h"
45 #include "ucln_in.h"
46 #include "uassert.h"
47 #include "cmemory.h"
48 #include "cstring.h"
49 #include "uinvchar.h"
50 
51 static const UChar TARGET_SEP  = 0x002D; /*-*/
52 static const UChar ID_DELIM    = 0x003B; /*;*/
53 static const UChar VARIANT_SEP = 0x002F; // '/'
54 
55 /**
56  * Prefix for resource bundle key for the display name for a
57  * transliterator.  The ID is appended to this to form the key.
58  * The resource bundle value should be a String.
59  */
60 static const char RB_DISPLAY_NAME_PREFIX[] = "%Translit%%";
61 
62 /**
63  * Prefix for resource bundle key for the display name for a
64  * transliterator SCRIPT.  The ID is appended to this to form the key.
65  * The resource bundle value should be a String.
66  */
67 static const char RB_SCRIPT_DISPLAY_NAME_PREFIX[] = "%Translit%";
68 
69 /**
70  * Resource bundle key for display name pattern.
71  * The resource bundle value should be a String forming a
72  * MessageFormat pattern, e.g.:
73  * "{0,choice,0#|1#{1} Transliterator|2#{1} to {2} Transliterator}".
74  */
75 static const char RB_DISPLAY_NAME_PATTERN[] = "TransliteratorNamePattern";
76 
77 /**
78  * Resource bundle key for the list of RuleBasedTransliterator IDs.
79  * The resource bundle value should be a String[] with each element
80  * being a valid ID.  The ID will be appended to RB_RULE_BASED_PREFIX
81  * to obtain the class name in which the RB_RULE key will be sought.
82  */
83 static const char RB_RULE_BASED_IDS[] = "RuleBasedTransliteratorIDs";
84 
85 /**
86  * The mutex controlling access to registry object.
87  */
88 static UMTX registryMutex = 0;
89 
90 /**
91  * System transliterator registry; non-null when initialized.
92  */
93 static U_NAMESPACE_QUALIFIER TransliteratorRegistry* registry = 0;
94 
95 // Macro to check/initialize the registry. ONLY USE WITHIN
96 // MUTEX. Avoids function call when registry is initialized.
97 #define HAVE_REGISTRY (registry!=0 || initializeRegistry())
98 
99 // Empty string
100 static const UChar EMPTY[] = {0}; //""
101 
102 U_NAMESPACE_BEGIN
103 
UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(Transliterator)104 UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(Transliterator)
105 
106 /**
107  * Return TRUE if the given UTransPosition is valid for text of
108  * the given length.
109  */
110 static inline UBool positionIsValid(UTransPosition& index, int32_t len) {
111     return !(index.contextStart < 0 ||
112              index.start < index.contextStart ||
113              index.limit < index.start ||
114              index.contextLimit < index.limit ||
115              len < index.contextLimit);
116 }
117 
118 /**
119  * Default constructor.
120  * @param theID the string identifier for this transliterator
121  * @param theFilter the filter.  Any character for which
122  * <tt>filter.contains()</tt> returns <tt>FALSE</tt> will not be
123  * altered by this transliterator.  If <tt>filter</tt> is
124  * <tt>null</tt> then no filtering is applied.
125  */
Transliterator(const UnicodeString & theID,UnicodeFilter * adoptedFilter)126 Transliterator::Transliterator(const UnicodeString& theID,
127                                UnicodeFilter* adoptedFilter) :
128     UObject(), ID(theID), filter(adoptedFilter),
129     maximumContextLength(0)
130 {
131     // NUL-terminate the ID string, which is a non-aliased copy.
132     ID.append((UChar)0);
133     ID.truncate(ID.length()-1);
134 }
135 
136 /**
137  * Destructor.
138  */
~Transliterator()139 Transliterator::~Transliterator() {
140     if (filter) {
141         delete filter;
142     }
143 }
144 
145 /**
146  * Copy constructor.
147  */
Transliterator(const Transliterator & other)148 Transliterator::Transliterator(const Transliterator& other) :
149     UObject(other), ID(other.ID), filter(0),
150     maximumContextLength(other.maximumContextLength)
151 {
152     // NUL-terminate the ID string, which is a non-aliased copy.
153     ID.append((UChar)0);
154     ID.truncate(ID.length()-1);
155 
156     if (other.filter != 0) {
157         // We own the filter, so we must have our own copy
158         filter = (UnicodeFilter*) other.filter->clone();
159     }
160 }
161 
clone() const162 Transliterator* Transliterator::clone() const {
163     return NULL;
164 }
165 
166 /**
167  * Assignment operator.
168  */
operator =(const Transliterator & other)169 Transliterator& Transliterator::operator=(const Transliterator& other) {
170     ID = other.ID;
171     // NUL-terminate the ID string
172     ID.getTerminatedBuffer();
173 
174     maximumContextLength = other.maximumContextLength;
175     adoptFilter((other.filter == 0) ? 0 : (UnicodeFilter*) other.filter->clone());
176     return *this;
177 }
178 
179 /**
180  * Transliterates a segment of a string.  <code>Transliterator</code> API.
181  * @param text the string to be transliterated
182  * @param start the beginning index, inclusive; <code>0 <= start
183  * <= limit</code>.
184  * @param limit the ending index, exclusive; <code>start <= limit
185  * <= text.length()</code>.
186  * @return the new limit index, or -1
187  */
transliterate(Replaceable & text,int32_t start,int32_t limit) const188 int32_t Transliterator::transliterate(Replaceable& text,
189                                       int32_t start, int32_t limit) const {
190     if (start < 0 ||
191         limit < start ||
192         text.length() < limit) {
193         return -1;
194     }
195 
196     UTransPosition offsets;
197     offsets.contextStart= start;
198     offsets.contextLimit = limit;
199     offsets.start = start;
200     offsets.limit = limit;
201     filteredTransliterate(text, offsets, FALSE, TRUE);
202     return offsets.limit;
203 }
204 
205 /**
206  * Transliterates an entire string in place. Convenience method.
207  * @param text the string to be transliterated
208  */
transliterate(Replaceable & text) const209 void Transliterator::transliterate(Replaceable& text) const {
210     transliterate(text, 0, text.length());
211 }
212 
213 /**
214  * Transliterates the portion of the text buffer that can be
215  * transliterated unambiguosly after new text has been inserted,
216  * typically as a result of a keyboard event.  The new text in
217  * <code>insertion</code> will be inserted into <code>text</code>
218  * at <code>index.contextLimit</code>, advancing
219  * <code>index.contextLimit</code> by <code>insertion.length()</code>.
220  * Then the transliterator will try to transliterate characters of
221  * <code>text</code> between <code>index.start</code> and
222  * <code>index.contextLimit</code>.  Characters before
223  * <code>index.start</code> will not be changed.
224  *
225  * <p>Upon return, values in <code>index</code> will be updated.
226  * <code>index.contextStart</code> will be advanced to the first
227  * character that future calls to this method will read.
228  * <code>index.start</code> and <code>index.contextLimit</code> will
229  * be adjusted to delimit the range of text that future calls to
230  * this method may change.
231  *
232  * <p>Typical usage of this method begins with an initial call
233  * with <code>index.contextStart</code> and <code>index.contextLimit</code>
234  * set to indicate the portion of <code>text</code> to be
235  * transliterated, and <code>index.start == index.contextStart</code>.
236  * Thereafter, <code>index</code> can be used without
237  * modification in future calls, provided that all changes to
238  * <code>text</code> are made via this method.
239  *
240  * <p>This method assumes that future calls may be made that will
241  * insert new text into the buffer.  As a result, it only performs
242  * unambiguous transliterations.  After the last call to this
243  * method, there may be untransliterated text that is waiting for
244  * more input to resolve an ambiguity.  In order to perform these
245  * pending transliterations, clients should call {@link
246  * #finishKeyboardTransliteration} after the last call to this
247  * method has been made.
248  *
249  * @param text the buffer holding transliterated and untransliterated text
250  * @param index an array of three integers.
251  *
252  * <ul><li><code>index.contextStart</code>: the beginning index,
253  * inclusive; <code>0 <= index.contextStart <= index.contextLimit</code>.
254  *
255  * <li><code>index.contextLimit</code>: the ending index, exclusive;
256  * <code>index.contextStart <= index.contextLimit <= text.length()</code>.
257  * <code>insertion</code> is inserted at
258  * <code>index.contextLimit</code>.
259  *
260  * <li><code>index.start</code>: the next character to be
261  * considered for transliteration; <code>index.contextStart <=
262  * index.start <= index.contextLimit</code>.  Characters before
263  * <code>index.start</code> will not be changed by future calls
264  * to this method.</ul>
265  *
266  * @param insertion text to be inserted and possibly
267  * transliterated into the translation buffer at
268  * <code>index.contextLimit</code>.  If <code>null</code> then no text
269  * is inserted.
270  * @see #START
271  * @see #LIMIT
272  * @see #CURSOR
273  * @see #handleTransliterate
274  * @exception IllegalArgumentException if <code>index</code>
275  * is invalid
276  */
transliterate(Replaceable & text,UTransPosition & index,const UnicodeString & insertion,UErrorCode & status) const277 void Transliterator::transliterate(Replaceable& text,
278                                    UTransPosition& index,
279                                    const UnicodeString& insertion,
280                                    UErrorCode &status) const {
281     _transliterate(text, index, &insertion, status);
282 }
283 
284 /**
285  * Transliterates the portion of the text buffer that can be
286  * transliterated unambiguosly after a new character has been
287  * inserted, typically as a result of a keyboard event.  This is a
288  * convenience method; see {@link
289  * #transliterate(Replaceable, int[], String)} for details.
290  * @param text the buffer holding transliterated and
291  * untransliterated text
292  * @param index an array of three integers.  See {@link
293  * #transliterate(Replaceable, int[], String)}.
294  * @param insertion text to be inserted and possibly
295  * transliterated into the translation buffer at
296  * <code>index.contextLimit</code>.
297  * @see #transliterate(Replaceable, int[], String)
298  */
transliterate(Replaceable & text,UTransPosition & index,UChar32 insertion,UErrorCode & status) const299 void Transliterator::transliterate(Replaceable& text,
300                                    UTransPosition& index,
301                                    UChar32 insertion,
302                                    UErrorCode& status) const {
303     UnicodeString str(insertion);
304     _transliterate(text, index, &str, status);
305 }
306 
307 /**
308  * Transliterates the portion of the text buffer that can be
309  * transliterated unambiguosly.  This is a convenience method; see
310  * {@link #transliterate(Replaceable, int[], String)} for
311  * details.
312  * @param text the buffer holding transliterated and
313  * untransliterated text
314  * @param index an array of three integers.  See {@link
315  * #transliterate(Replaceable, int[], String)}.
316  * @see #transliterate(Replaceable, int[], String)
317  */
transliterate(Replaceable & text,UTransPosition & index,UErrorCode & status) const318 void Transliterator::transliterate(Replaceable& text,
319                                    UTransPosition& index,
320                                    UErrorCode& status) const {
321     _transliterate(text, index, 0, status);
322 }
323 
324 /**
325  * Finishes any pending transliterations that were waiting for
326  * more characters.  Clients should call this method as the last
327  * call after a sequence of one or more calls to
328  * <code>transliterate()</code>.
329  * @param text the buffer holding transliterated and
330  * untransliterated text.
331  * @param index the array of indices previously passed to {@link
332  * #transliterate}
333  */
finishTransliteration(Replaceable & text,UTransPosition & index) const334 void Transliterator::finishTransliteration(Replaceable& text,
335                                            UTransPosition& index) const {
336     if (!positionIsValid(index, text.length())) {
337         return;
338     }
339 
340     filteredTransliterate(text, index, FALSE, TRUE);
341 }
342 
343 /**
344  * This internal method does keyboard transliteration.  If the
345  * 'insertion' is non-null then we append it to 'text' before
346  * proceeding.  This method calls through to the pure virtual
347  * framework method handleTransliterate() to do the actual
348  * work.
349  */
_transliterate(Replaceable & text,UTransPosition & index,const UnicodeString * insertion,UErrorCode & status) const350 void Transliterator::_transliterate(Replaceable& text,
351                                     UTransPosition& index,
352                                     const UnicodeString* insertion,
353                                     UErrorCode &status) const {
354     if (U_FAILURE(status)) {
355         return;
356     }
357 
358     if (!positionIsValid(index, text.length())) {
359         status = U_ILLEGAL_ARGUMENT_ERROR;
360         return;
361     }
362 
363 //    int32_t originalStart = index.contextStart;
364     if (insertion != 0) {
365         text.handleReplaceBetween(index.limit, index.limit, *insertion);
366         index.limit += insertion->length();
367         index.contextLimit += insertion->length();
368     }
369 
370     if (index.limit > 0 &&
371         UTF_IS_LEAD(text.charAt(index.limit - 1))) {
372         // Oops, there is a dangling lead surrogate in the buffer.
373         // This will break most transliterators, since they will
374         // assume it is part of a pair.  Don't transliterate until
375         // more text comes in.
376         return;
377     }
378 
379     filteredTransliterate(text, index, TRUE, TRUE);
380 
381 #if 0
382     // TODO
383     // I CAN'T DO what I'm attempting below now that the Kleene star
384     // operator is supported.  For example, in the rule
385 
386     //   ([:Lu:]+) { x } > $1;
387 
388     // what is the maximum context length?  getMaximumContextLength()
389     // will return 1, but this is just the length of the ante context
390     // part of the pattern string -- 1 character, which is a standin
391     // for a Quantifier, which contains a StringMatcher, which
392     // contains a UnicodeSet.
393 
394     // There is a complicated way to make this work again, and that's
395     // to add a "maximum left context" protocol into the
396     // UnicodeMatcher hierarchy.  At present I'm not convinced this is
397     // worth it.
398 
399     // ---
400 
401     // The purpose of the code below is to keep the context small
402     // while doing incremental transliteration.  When part of the left
403     // context (between contextStart and start) is no longer needed,
404     // we try to advance contextStart past that portion.  We use the
405     // maximum context length to do so.
406     int32_t newCS = index.start;
407     int32_t n = getMaximumContextLength();
408     while (newCS > originalStart && n-- > 0) {
409         --newCS;
410         newCS -= UTF_CHAR_LENGTH(text.char32At(newCS)) - 1;
411     }
412     index.contextStart = uprv_max(newCS, originalStart);
413 #endif
414 }
415 
416 /**
417  * This method breaks up the input text into runs of unfiltered
418  * characters.  It passes each such run to
419  * <subclass>.handleTransliterate().  Subclasses that can handle the
420  * filter logic more efficiently themselves may override this method.
421  *
422  * All transliteration calls in this class go through this method.
423  */
filteredTransliterate(Replaceable & text,UTransPosition & index,UBool incremental,UBool rollback) const424 void Transliterator::filteredTransliterate(Replaceable& text,
425                                            UTransPosition& index,
426                                            UBool incremental,
427                                            UBool rollback) const {
428     // Short circuit path for transliterators with no filter in
429     // non-incremental mode.
430     if (filter == 0 && !rollback) {
431         handleTransliterate(text, index, incremental);
432         return;
433     }
434 
435     //----------------------------------------------------------------------
436     // This method processes text in two groupings:
437     //
438     // RUNS -- A run is a contiguous group of characters which are contained
439     // in the filter for this transliterator (filter.contains(ch) == TRUE).
440     // Text outside of runs may appear as context but it is not modified.
441     // The start and limit Position values are narrowed to each run.
442     //
443     // PASSES (incremental only) -- To make incremental mode work correctly,
444     // each run is broken up into n passes, where n is the length (in code
445     // points) of the run.  Each pass contains the first n characters.  If a
446     // pass is completely transliterated, it is committed, and further passes
447     // include characters after the committed text.  If a pass is blocked,
448     // and does not transliterate completely, then this method rolls back
449     // the changes made during the pass, extends the pass by one code point,
450     // and tries again.
451     //----------------------------------------------------------------------
452 
453     // globalLimit is the limit value for the entire operation.  We
454     // set index.limit to the end of each unfiltered run before
455     // calling handleTransliterate(), so we need to maintain the real
456     // value of index.limit here.  After each transliteration, we
457     // update globalLimit for insertions or deletions that have
458     // happened.
459     int32_t globalLimit = index.limit;
460 
461     // If there is a non-null filter, then break the input text up.  Say the
462     // input text has the form:
463     //   xxxabcxxdefxx
464     // where 'x' represents a filtered character (filter.contains('x') ==
465     // false).  Then we break this up into:
466     //   xxxabc xxdef xx
467     // Each pass through the loop consumes a run of filtered
468     // characters (which are ignored) and a subsequent run of
469     // unfiltered characters (which are transliterated).
470 
471     for (;;) {
472 
473         if (filter != NULL) {
474             // Narrow the range to be transliterated to the first segment
475             // of unfiltered characters at or after index.start.
476 
477             // Advance past filtered chars
478             UChar32 c;
479             while (index.start < globalLimit &&
480                    !filter->contains(c=text.char32At(index.start))) {
481                 index.start += UTF_CHAR_LENGTH(c);
482             }
483 
484             // Find the end of this run of unfiltered chars
485             index.limit = index.start;
486             while (index.limit < globalLimit &&
487                    filter->contains(c=text.char32At(index.limit))) {
488                 index.limit += UTF_CHAR_LENGTH(c);
489             }
490         }
491 
492         // Check to see if the unfiltered run is empty.  This only
493         // happens at the end of the string when all the remaining
494         // characters are filtered.
495         if (index.limit == index.start) {
496             // assert(index.start == globalLimit);
497             break;
498         }
499 
500         // Is this run incremental?  If there is additional
501         // filtered text (if limit < globalLimit) then we pass in
502         // an incremental value of FALSE to force the subclass to
503         // complete the transliteration for this run.
504         UBool isIncrementalRun =
505             (index.limit < globalLimit ? FALSE : incremental);
506 
507         int32_t delta;
508 
509         // Implement rollback.  To understand the need for rollback,
510         // consider the following transliterator:
511         //
512         //  "t" is "a > A;"
513         //  "u" is "A > b;"
514         //  "v" is a compound of "t; NFD; u" with a filter [:Ll:]
515         //
516         // Now apply "c" to the input text "a".  The result is "b".  But if
517         // the transliteration is done incrementally, then the NFD holds
518         // things up after "t" has already transformed "a" to "A".  When
519         // finishTransliterate() is called, "A" is _not_ processed because
520         // it gets excluded by the [:Ll:] filter, and the end result is "A"
521         // -- incorrect.  The problem is that the filter is applied to a
522         // partially-transliterated result, when we only want it to apply to
523         // input text.  Although this example hinges on a compound
524         // transliterator containing NFD and a specific filter, it can
525         // actually happen with any transliterator which may do a partial
526         // transformation in incremental mode into characters outside its
527         // filter.
528         //
529         // To handle this, when in incremental mode we supply characters to
530         // handleTransliterate() in several passes.  Each pass adds one more
531         // input character to the input text.  That is, for input "ABCD", we
532         // first try "A", then "AB", then "ABC", and finally "ABCD".  If at
533         // any point we block (upon return, start < limit) then we roll
534         // back.  If at any point we complete the run (upon return start ==
535         // limit) then we commit that run.
536 
537         if (rollback && isIncrementalRun) {
538 
539             int32_t runStart = index.start;
540             int32_t runLimit = index.limit;
541             int32_t runLength =  runLimit - runStart;
542 
543             // Make a rollback copy at the end of the string
544             int32_t rollbackOrigin = text.length();
545             text.copy(runStart, runLimit, rollbackOrigin);
546 
547             // Variables reflecting the commitment of completely
548             // transliterated text.  passStart is the runStart, advanced
549             // past committed text.  rollbackStart is the rollbackOrigin,
550             // advanced past rollback text that corresponds to committed
551             // text.
552             int32_t passStart = runStart;
553             int32_t rollbackStart = rollbackOrigin;
554 
555             // The limit for each pass; we advance by one code point with
556             // each iteration.
557             int32_t passLimit = index.start;
558 
559             // Total length, in 16-bit code units, of uncommitted text.
560             // This is the length to be rolled back.
561             int32_t uncommittedLength = 0;
562 
563             // Total delta (change in length) for all passes
564             int32_t totalDelta = 0;
565 
566             // PASS MAIN LOOP -- Start with a single character, and extend
567             // the text by one character at a time.  Roll back partial
568             // transliterations and commit complete transliterations.
569             for (;;) {
570                 // Length of additional code point, either one or two
571                 int32_t charLength =
572                     UTF_CHAR_LENGTH(text.char32At(passLimit));
573                 passLimit += charLength;
574                 if (passLimit > runLimit) {
575                     break;
576                 }
577                 uncommittedLength += charLength;
578 
579                 index.limit = passLimit;
580 
581                 // Delegate to subclass for actual transliteration.  Upon
582                 // return, start will be updated to point after the
583                 // transliterated text, and limit and contextLimit will be
584                 // adjusted for length changes.
585                 handleTransliterate(text, index, TRUE);
586 
587                 delta = index.limit - passLimit; // change in length
588 
589                 // We failed to completely transliterate this pass.
590                 // Roll back the text.  Indices remain unchanged; reset
591                 // them where necessary.
592                 if (index.start != index.limit) {
593                     // Find the rollbackStart, adjusted for length changes
594                     // and the deletion of partially transliterated text.
595                     int32_t rs = rollbackStart + delta - (index.limit - passStart);
596 
597                     // Delete the partially transliterated text
598                     text.handleReplaceBetween(passStart, index.limit, EMPTY);
599 
600                     // Copy the rollback text back
601                     text.copy(rs, rs + uncommittedLength, passStart);
602 
603                     // Restore indices to their original values
604                     index.start = passStart;
605                     index.limit = passLimit;
606                     index.contextLimit -= delta;
607                 }
608 
609                 // We did completely transliterate this pass.  Update the
610                 // commit indices to record how far we got.  Adjust indices
611                 // for length change.
612                 else {
613                     // Move the pass indices past the committed text.
614                     passStart = passLimit = index.start;
615 
616                     // Adjust the rollbackStart for length changes and move
617                     // it past the committed text.  All characters we've
618                     // processed to this point are committed now, so zero
619                     // out the uncommittedLength.
620                     rollbackStart += delta + uncommittedLength;
621                     uncommittedLength = 0;
622 
623                     // Adjust indices for length changes.
624                     runLimit += delta;
625                     totalDelta += delta;
626                 }
627             }
628 
629             // Adjust overall limit and rollbackOrigin for insertions and
630             // deletions.  Don't need to worry about contextLimit because
631             // handleTransliterate() maintains that.
632             rollbackOrigin += totalDelta;
633             globalLimit += totalDelta;
634 
635             // Delete the rollback copy
636             text.handleReplaceBetween(rollbackOrigin, rollbackOrigin + runLength, EMPTY);
637 
638             // Move start past committed text
639             index.start = passStart;
640         }
641 
642         else {
643             // Delegate to subclass for actual transliteration.
644             int32_t limit = index.limit;
645             handleTransliterate(text, index, isIncrementalRun);
646             delta = index.limit - limit; // change in length
647 
648             // In a properly written transliterator, start == limit after
649             // handleTransliterate() returns when incremental is false.
650             // Catch cases where the subclass doesn't do this, and throw
651             // an exception.  (Just pinning start to limit is a bad idea,
652             // because what's probably happening is that the subclass
653             // isn't transliterating all the way to the end, and it should
654             // in non-incremental mode.)
655             if (!incremental && index.start != index.limit) {
656                 // We can't throw an exception, so just fudge things
657                 index.start = index.limit;
658             }
659 
660             // Adjust overall limit for insertions/deletions.  Don't need
661             // to worry about contextLimit because handleTransliterate()
662             // maintains that.
663             globalLimit += delta;
664         }
665 
666         if (filter == NULL || isIncrementalRun) {
667             break;
668         }
669 
670         // If we did completely transliterate this
671         // run, then repeat with the next unfiltered run.
672     }
673 
674     // Start is valid where it is.  Limit needs to be put back where
675     // it was, modulo adjustments for deletions/insertions.
676     index.limit = globalLimit;
677 }
678 
filteredTransliterate(Replaceable & text,UTransPosition & index,UBool incremental) const679 void Transliterator::filteredTransliterate(Replaceable& text,
680                                            UTransPosition& index,
681                                            UBool incremental) const {
682     filteredTransliterate(text, index, incremental, FALSE);
683 }
684 
685 /**
686  * Method for subclasses to use to set the maximum context length.
687  * @see #getMaximumContextLength
688  */
setMaximumContextLength(int32_t maxContextLength)689 void Transliterator::setMaximumContextLength(int32_t maxContextLength) {
690     maximumContextLength = maxContextLength;
691 }
692 
693 /**
694  * Returns a programmatic identifier for this transliterator.
695  * If this identifier is passed to <code>getInstance()</code>, it
696  * will return this object, if it has been registered.
697  * @see #registerInstance
698  * @see #getAvailableIDs
699  */
getID(void) const700 const UnicodeString& Transliterator::getID(void) const {
701     return ID;
702 }
703 
704 /**
705  * Returns a name for this transliterator that is appropriate for
706  * display to the user in the default locale.  See {@link
707  * #getDisplayName(Locale)} for details.
708  */
getDisplayName(const UnicodeString & ID,UnicodeString & result)709 UnicodeString& U_EXPORT2 Transliterator::getDisplayName(const UnicodeString& ID,
710                                               UnicodeString& result) {
711     return getDisplayName(ID, Locale::getDefault(), result);
712 }
713 
714 /**
715  * Returns a name for this transliterator that is appropriate for
716  * display to the user in the given locale.  This name is taken
717  * from the locale resource data in the standard manner of the
718  * <code>java.text</code> package.
719  *
720  * <p>If no localized names exist in the system resource bundles,
721  * a name is synthesized using a localized
722  * <code>MessageFormat</code> pattern from the resource data.  The
723  * arguments to this pattern are an integer followed by one or two
724  * strings.  The integer is the number of strings, either 1 or 2.
725  * The strings are formed by splitting the ID for this
726  * transliterator at the first TARGET_SEP.  If there is no TARGET_SEP, then the
727  * entire ID forms the only string.
728  * @param inLocale the Locale in which the display name should be
729  * localized.
730  * @see java.text.MessageFormat
731  */
getDisplayName(const UnicodeString & id,const Locale & inLocale,UnicodeString & result)732 UnicodeString& U_EXPORT2 Transliterator::getDisplayName(const UnicodeString& id,
733                                               const Locale& inLocale,
734                                               UnicodeString& result) {
735     UErrorCode status = U_ZERO_ERROR;
736 
737     ResourceBundle bundle(U_ICUDATA_TRANSLIT, inLocale, status);
738 
739     // Suspend checking status until later...
740 
741     result.truncate(0);
742 
743     // Normalize the ID
744     UnicodeString source, target, variant;
745     UBool sawSource;
746     TransliteratorIDParser::IDtoSTV(id, source, target, variant, sawSource);
747     if (target.length() < 1) {
748         // No target; malformed id
749         return result;
750     }
751     if (variant.length() > 0) { // Change "Foo" to "/Foo"
752         variant.insert(0, VARIANT_SEP);
753     }
754     UnicodeString ID(source);
755     ID.append(TARGET_SEP).append(target).append(variant);
756 
757     // build the char* key
758     if (uprv_isInvariantUString(ID.getBuffer(), ID.length())) {
759         char key[200];
760         uprv_strcpy(key, RB_DISPLAY_NAME_PREFIX);
761         int32_t length=(int32_t)uprv_strlen(RB_DISPLAY_NAME_PREFIX);
762         ID.extract(0, (int32_t)(sizeof(key)-length), key+length, (int32_t)(sizeof(key)-length), US_INV);
763 
764         // Try to retrieve a UnicodeString from the bundle.
765         UnicodeString resString = bundle.getStringEx(key, status);
766 
767         if (U_SUCCESS(status) && resString.length() != 0) {
768             return result = resString; // [sic] assign & return
769         }
770 
771 #if !UCONFIG_NO_FORMATTING
772         // We have failed to get a name from the locale data.  This is
773         // typical, since most transliterators will not have localized
774         // name data.  The next step is to retrieve the MessageFormat
775         // pattern from the locale data and to use it to synthesize the
776         // name from the ID.
777 
778         status = U_ZERO_ERROR;
779         resString = bundle.getStringEx(RB_DISPLAY_NAME_PATTERN, status);
780 
781         if (U_SUCCESS(status) && resString.length() != 0) {
782             MessageFormat msg(resString, inLocale, status);
783             // Suspend checking status until later...
784 
785             // We pass either 2 or 3 Formattable objects to msg.
786             Formattable args[3];
787             int32_t nargs;
788             args[0].setLong(2); // # of args to follow
789             args[1].setString(source);
790             args[2].setString(target);
791             nargs = 3;
792 
793             // Use display names for the scripts, if they exist
794             UnicodeString s;
795             length=(int32_t)uprv_strlen(RB_SCRIPT_DISPLAY_NAME_PREFIX);
796             for (int j=1; j<=2; ++j) {
797                 status = U_ZERO_ERROR;
798                 uprv_strcpy(key, RB_SCRIPT_DISPLAY_NAME_PREFIX);
799                 args[j].getString(s);
800                 if (uprv_isInvariantUString(s.getBuffer(), s.length())) {
801                     s.extract(0, sizeof(key)-length-1, key+length, (int32_t)sizeof(key)-length-1, US_INV);
802 
803                     resString = bundle.getStringEx(key, status);
804 
805                     if (U_SUCCESS(status)) {
806                         args[j] = resString;
807                     }
808                 }
809             }
810 
811             status = U_ZERO_ERROR;
812             FieldPosition pos; // ignored by msg
813             msg.format(args, nargs, result, pos, status);
814             if (U_SUCCESS(status)) {
815                 result.append(variant);
816                 return result;
817             }
818         }
819 #endif
820     }
821 
822     // We should not reach this point unless there is something
823     // wrong with the build or the RB_DISPLAY_NAME_PATTERN has
824     // been deleted from the root RB_LOCALE_ELEMENTS resource.
825     result = ID;
826     return result;
827 }
828 
829 /**
830  * Returns the filter used by this transliterator, or <tt>null</tt>
831  * if this transliterator uses no filter.  Caller musn't delete
832  * the result!
833  */
getFilter(void) const834 const UnicodeFilter* Transliterator::getFilter(void) const {
835     return filter;
836 }
837 
838 /**
839  * Returns the filter used by this transliterator, or
840  * <tt>NULL</tt> if this transliterator uses no filter.  The
841  * caller must eventually delete the result.  After this call,
842  * this transliterator's filter is set to <tt>NULL</tt>.
843  */
orphanFilter(void)844 UnicodeFilter* Transliterator::orphanFilter(void) {
845     UnicodeFilter *result = filter;
846     filter = NULL;
847     return result;
848 }
849 
850 /**
851  * Changes the filter used by this transliterator.  If the filter
852  * is set to <tt>null</tt> then no filtering will occur.
853  *
854  * <p>Callers must take care if a transliterator is in use by
855  * multiple threads.  The filter should not be changed by one
856  * thread while another thread may be transliterating.
857  */
adoptFilter(UnicodeFilter * filterToAdopt)858 void Transliterator::adoptFilter(UnicodeFilter* filterToAdopt) {
859     delete filter;
860     filter = filterToAdopt;
861 }
862 
863 /**
864  * Returns this transliterator's inverse.  See the class
865  * documentation for details.  This implementation simply inverts
866  * the two entities in the ID and attempts to retrieve the
867  * resulting transliterator.  That is, if <code>getID()</code>
868  * returns "A-B", then this method will return the result of
869  * <code>getInstance("B-A")</code>, or <code>null</code> if that
870  * call fails.
871  *
872  * <p>This method does not take filtering into account.  The
873  * returned transliterator will have no filter.
874  *
875  * <p>Subclasses with knowledge of their inverse may wish to
876  * override this method.
877  *
878  * @return a transliterator that is an inverse, not necessarily
879  * exact, of this transliterator, or <code>null</code> if no such
880  * transliterator is registered.
881  * @see #registerInstance
882  */
createInverse(UErrorCode & status) const883 Transliterator* Transliterator::createInverse(UErrorCode& status) const {
884     UParseError parseError;
885     return Transliterator::createInstance(ID, UTRANS_REVERSE,parseError,status);
886 }
887 
888 Transliterator* U_EXPORT2
createInstance(const UnicodeString & ID,UTransDirection dir,UErrorCode & status)889 Transliterator::createInstance(const UnicodeString& ID,
890                                 UTransDirection dir,
891                                 UErrorCode& status)
892 {
893     UParseError parseError;
894     return createInstance(ID, dir, parseError, status);
895 }
896 
897 /**
898  * Returns a <code>Transliterator</code> object given its ID.
899  * The ID must be either a system transliterator ID or a ID registered
900  * using <code>registerInstance()</code>.
901  *
902  * @param ID a valid ID, as enumerated by <code>getAvailableIDs()</code>
903  * @return A <code>Transliterator</code> object with the given ID
904  * @see #registerInstance
905  * @see #getAvailableIDs
906  * @see #getID
907  */
908 Transliterator* U_EXPORT2
createInstance(const UnicodeString & ID,UTransDirection dir,UParseError & parseError,UErrorCode & status)909 Transliterator::createInstance(const UnicodeString& ID,
910                                 UTransDirection dir,
911                                 UParseError& parseError,
912                                 UErrorCode& status)
913 {
914     if (U_FAILURE(status)) {
915         return 0;
916     }
917 
918     UnicodeString canonID;
919     UVector list(status);
920     if (U_FAILURE(status)) {
921         return NULL;
922     }
923 
924     UnicodeSet* globalFilter;
925     // TODO add code for parseError...currently unused, but
926     // later may be used by parsing code...
927     if (!TransliteratorIDParser::parseCompoundID(ID, dir, canonID, list, globalFilter)) {
928         status = U_INVALID_ID;
929         return NULL;
930     }
931 
932     TransliteratorIDParser::instantiateList(list, status);
933     if (U_FAILURE(status)) {
934         return NULL;
935     }
936 
937     U_ASSERT(list.size() > 0);
938     Transliterator* t = NULL;
939 
940     if (list.size() > 1 || canonID.indexOf(ID_DELIM) >= 0) {
941         // [NOTE: If it's a compoundID, we instantiate a CompoundTransliterator even if it only
942         // has one child transliterator.  This is so that toRules() will return the right thing
943         // (without any inactive ID), but our main ID still comes out correct.  That is, if we
944         // instantiate "(Lower);Latin-Greek;", we want the rules to come out as "::Latin-Greek;"
945         // even though the ID is "(Lower);Latin-Greek;".
946         t = new CompoundTransliterator(list, parseError, status);
947     }
948     else {
949         t = (Transliterator*)list.elementAt(0);
950     }
951 
952     t->setID(canonID);
953     if (globalFilter != NULL) {
954         t->adoptFilter(globalFilter);
955     }
956     return t;
957 }
958 
959 /**
960  * Create a transliterator from a basic ID.  This is an ID
961  * containing only the forward direction source, target, and
962  * variant.
963  * @param id a basic ID of the form S-T or S-T/V.
964  * @return a newly created Transliterator or null if the ID is
965  * invalid.
966  */
createBasicInstance(const UnicodeString & id,const UnicodeString * canon)967 Transliterator* Transliterator::createBasicInstance(const UnicodeString& id,
968                                                     const UnicodeString* canon) {
969     UParseError pe;
970     UErrorCode ec = U_ZERO_ERROR;
971     TransliteratorAlias* alias = 0;
972     Transliterator* t = 0;
973 
974     umtx_init(&registryMutex);
975     umtx_lock(&registryMutex);
976     if (HAVE_REGISTRY) {
977         t = registry->get(id, alias, ec);
978     }
979     umtx_unlock(&registryMutex);
980 
981     if (U_FAILURE(ec)) {
982         delete t;
983         delete alias;
984         return 0;
985     }
986 
987     // We may have not gotten a transliterator:  Because we can't
988     // instantiate a transliterator from inside TransliteratorRegistry::
989     // get() (that would deadlock), we sometimes pass back an alias.  This
990     // contains the data we need to finish the instantiation outside the
991     // registry mutex.  The alias may, in turn, generate another alias, so
992     // we handle aliases in a loop.  The max times through the loop is two.
993     // [alan]
994     while (alias != 0) {
995         U_ASSERT(t==0);
996         // Rule-based aliases are handled with TransliteratorAlias::
997         // parse(), followed by TransliteratorRegistry::reget().
998         // Other aliases are handled with TransliteratorAlias::create().
999         if (alias->isRuleBased()) {
1000             // Step 1. parse
1001             TransliteratorParser parser(ec);
1002             alias->parse(parser, pe, ec);
1003             delete alias;
1004             alias = 0;
1005 
1006             // Step 2. reget
1007             umtx_lock(&registryMutex);
1008             if (HAVE_REGISTRY) {
1009                 t = registry->reget(id, parser, alias, ec);
1010             }
1011             umtx_unlock(&registryMutex);
1012 
1013             // Step 3. Loop back around!
1014         } else {
1015             t = alias->create(pe, ec);
1016             delete alias;
1017             alias = 0;
1018             break;
1019         }
1020         if (U_FAILURE(ec)) {
1021             delete t;
1022             delete alias;
1023             t = NULL;
1024             break;
1025         }
1026     }
1027 
1028     if (t != NULL && canon != NULL) {
1029         t->setID(*canon);
1030     }
1031 
1032     return t;
1033 }
1034 
1035 /**
1036  * Returns a <code>Transliterator</code> object constructed from
1037  * the given rule string.  This will be a RuleBasedTransliterator,
1038  * if the rule string contains only rules, or a
1039  * CompoundTransliterator, if it contains ID blocks, or a
1040  * NullTransliterator, if it contains ID blocks which parse as
1041  * empty for the given direction.
1042  */
1043 Transliterator* U_EXPORT2
createFromRules(const UnicodeString & ID,const UnicodeString & rules,UTransDirection dir,UParseError & parseError,UErrorCode & status)1044 Transliterator::createFromRules(const UnicodeString& ID,
1045                                 const UnicodeString& rules,
1046                                 UTransDirection dir,
1047                                 UParseError& parseError,
1048                                 UErrorCode& status)
1049 {
1050     Transliterator* t = NULL;
1051 
1052     TransliteratorParser parser(status);
1053     parser.parse(rules, dir, parseError, status);
1054 
1055     if (U_FAILURE(status)) {
1056         return 0;
1057     }
1058 
1059     // NOTE: The logic here matches that in TransliteratorRegistry.
1060     if (parser.idBlockVector.size() == 0 && parser.dataVector.size() == 0) {
1061         t = new NullTransliterator();
1062     }
1063     else if (parser.idBlockVector.size() == 0 && parser.dataVector.size() == 1) {
1064         t = new RuleBasedTransliterator(ID, (TransliterationRuleData*)parser.dataVector.orphanElementAt(0), TRUE);
1065     }
1066     else if (parser.idBlockVector.size() == 1 && parser.dataVector.size() == 0) {
1067         // idBlock, no data -- this is an alias.  The ID has
1068         // been munged from reverse into forward mode, if
1069         // necessary, so instantiate the ID in the forward
1070         // direction.
1071         if (parser.compoundFilter != NULL) {
1072             UnicodeString filterPattern;
1073             parser.compoundFilter->toPattern(filterPattern, FALSE);
1074             t = createInstance(filterPattern + UnicodeString(ID_DELIM)
1075                     + *((UnicodeString*)parser.idBlockVector.elementAt(0)), UTRANS_FORWARD, parseError, status);
1076         }
1077         else
1078             t = createInstance(*((UnicodeString*)parser.idBlockVector.elementAt(0)), UTRANS_FORWARD, parseError, status);
1079 
1080 
1081         if (t != NULL) {
1082             t->setID(ID);
1083         }
1084     }
1085     else {
1086         UVector transliterators(status);
1087         int32_t passNumber = 1;
1088 
1089         int32_t limit = parser.idBlockVector.size();
1090         if (parser.dataVector.size() > limit)
1091             limit = parser.dataVector.size();
1092 
1093         for (int32_t i = 0; i < limit; i++) {
1094             if (i < parser.idBlockVector.size()) {
1095                 UnicodeString* idBlock = (UnicodeString*)parser.idBlockVector.elementAt(i);
1096                 if (!idBlock->isEmpty()) {
1097                     Transliterator* temp = createInstance(*idBlock, UTRANS_FORWARD, parseError, status);
1098                     if (temp != NULL && temp->getDynamicClassID() != NullTransliterator::getStaticClassID())
1099                         transliterators.addElement(temp, status);
1100                     else
1101                         delete temp;
1102                 }
1103             }
1104             if (!parser.dataVector.isEmpty()) {
1105                 TransliterationRuleData* data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0);
1106                 transliterators.addElement(
1107                     new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING) + (passNumber++),
1108                     data, TRUE), status);
1109             }
1110         }
1111 
1112         t = new CompoundTransliterator(transliterators, passNumber - 1, parseError, status);
1113         t->setID(ID);
1114         t->adoptFilter(parser.orphanCompoundFilter());
1115     }
1116     return t;
1117 }
1118 
toRules(UnicodeString & rulesSource,UBool escapeUnprintable) const1119 UnicodeString& Transliterator::toRules(UnicodeString& rulesSource,
1120                                        UBool escapeUnprintable) const {
1121     // The base class implementation of toRules munges the ID into
1122     // the correct format.  That is: foo => ::foo
1123     if (escapeUnprintable) {
1124         rulesSource.truncate(0);
1125         UnicodeString id = getID();
1126         for (int32_t i=0; i<id.length();) {
1127             UChar32 c = id.char32At(i);
1128             if (!ICU_Utility::escapeUnprintable(rulesSource, c)) {
1129                 rulesSource.append(c);
1130             }
1131             i += UTF_CHAR_LENGTH(c);
1132         }
1133     } else {
1134         rulesSource = getID();
1135     }
1136     // KEEP in sync with rbt_pars
1137     rulesSource.insert(0, UNICODE_STRING_SIMPLE("::"));
1138     rulesSource.append(ID_DELIM);
1139     return rulesSource;
1140 }
1141 
countElements() const1142 int32_t Transliterator::countElements() const {
1143     return (this->getDynamicClassID() ==
1144             CompoundTransliterator::getStaticClassID()) ?
1145         ((const CompoundTransliterator*) this)->getCount() : 0;
1146 }
1147 
getElement(int32_t index,UErrorCode & ec) const1148 const Transliterator& Transliterator::getElement(int32_t index, UErrorCode& ec) const {
1149     if (U_FAILURE(ec)) {
1150         return *this;
1151     }
1152     const CompoundTransliterator* cpd =
1153         (this->getDynamicClassID() == CompoundTransliterator::getStaticClassID()) ?
1154         (const CompoundTransliterator*) this : 0;
1155     int32_t n = (cpd == NULL) ? 1 : cpd->getCount();
1156     if (index < 0 || index >= n) {
1157         ec = U_INDEX_OUTOFBOUNDS_ERROR;
1158         return *this;
1159     } else {
1160         return (n == 1) ? *this : cpd->getTransliterator(index);
1161     }
1162 }
1163 
getSourceSet(UnicodeSet & result) const1164 UnicodeSet& Transliterator::getSourceSet(UnicodeSet& result) const {
1165     handleGetSourceSet(result);
1166     if (filter != NULL) {
1167     UnicodeSet* filterSet;
1168     UBool deleteFilterSet = FALSE;
1169     // Most, but not all filters will be UnicodeSets.  Optimize for
1170     // the high-runner case.
1171     if (filter->getDynamicClassID() == UnicodeSet::getStaticClassID()) {
1172         filterSet = (UnicodeSet*) filter;
1173     } else {
1174         filterSet = new UnicodeSet();
1175         deleteFilterSet = TRUE;
1176         filter->addMatchSetTo(*filterSet);
1177     }
1178     result.retainAll(*filterSet);
1179     if (deleteFilterSet) {
1180         delete filterSet;
1181     }
1182     }
1183     return result;
1184 }
1185 
handleGetSourceSet(UnicodeSet & result) const1186 void Transliterator::handleGetSourceSet(UnicodeSet& result) const {
1187     result.clear();
1188 }
1189 
getTargetSet(UnicodeSet & result) const1190 UnicodeSet& Transliterator::getTargetSet(UnicodeSet& result) const {
1191     return result.clear();
1192 }
1193 
1194 // For public consumption
registerFactory(const UnicodeString & id,Transliterator::Factory factory,Transliterator::Token context)1195 void U_EXPORT2 Transliterator::registerFactory(const UnicodeString& id,
1196                                      Transliterator::Factory factory,
1197                                      Transliterator::Token context) {
1198     umtx_init(&registryMutex);
1199     Mutex lock(&registryMutex);
1200     if (HAVE_REGISTRY) {
1201         _registerFactory(id, factory, context);
1202     }
1203 }
1204 
1205 // To be called only by Transliterator subclasses that are called
1206 // to register themselves by initializeRegistry().
_registerFactory(const UnicodeString & id,Transliterator::Factory factory,Transliterator::Token context)1207 void Transliterator::_registerFactory(const UnicodeString& id,
1208                                       Transliterator::Factory factory,
1209                                       Transliterator::Token context) {
1210     registry->put(id, factory, context, TRUE);
1211 }
1212 
1213 // To be called only by Transliterator subclasses that are called
1214 // to register themselves by initializeRegistry().
_registerSpecialInverse(const UnicodeString & target,const UnicodeString & inverseTarget,UBool bidirectional)1215 void Transliterator::_registerSpecialInverse(const UnicodeString& target,
1216                                              const UnicodeString& inverseTarget,
1217                                              UBool bidirectional) {
1218     UErrorCode status = U_ZERO_ERROR;
1219     TransliteratorIDParser::registerSpecialInverse(target, inverseTarget, bidirectional, status);
1220 }
1221 
1222 /**
1223  * Registers a instance <tt>obj</tt> of a subclass of
1224  * <code>Transliterator</code> with the system.  This object must
1225  * implement the <tt>clone()</tt> method.  When
1226  * <tt>getInstance()</tt> is called with an ID string that is
1227  * equal to <tt>obj.getID()</tt>, then <tt>obj.clone()</tt> is
1228  * returned.
1229  *
1230  * @param obj an instance of subclass of
1231  * <code>Transliterator</code> that defines <tt>clone()</tt>
1232  * @see #getInstance
1233  * @see #unregister
1234  */
registerInstance(Transliterator * adoptedPrototype)1235 void U_EXPORT2 Transliterator::registerInstance(Transliterator* adoptedPrototype) {
1236     umtx_init(&registryMutex);
1237     Mutex lock(&registryMutex);
1238     if (HAVE_REGISTRY) {
1239         _registerInstance(adoptedPrototype);
1240     }
1241 }
1242 
_registerInstance(Transliterator * adoptedPrototype)1243 void Transliterator::_registerInstance(Transliterator* adoptedPrototype) {
1244     registry->put(adoptedPrototype, TRUE);
1245 }
1246 
registerAlias(const UnicodeString & aliasID,const UnicodeString & realID)1247 void U_EXPORT2 Transliterator::registerAlias(const UnicodeString& aliasID,
1248                                              const UnicodeString& realID) {
1249     umtx_init(&registryMutex);
1250     Mutex lock(&registryMutex);
1251     if (HAVE_REGISTRY) {
1252         _registerAlias(aliasID, realID);
1253     }
1254 }
1255 
_registerAlias(const UnicodeString & aliasID,const UnicodeString & realID)1256 void Transliterator::_registerAlias(const UnicodeString& aliasID,
1257                                     const UnicodeString& realID) {
1258     registry->put(aliasID, realID, FALSE, TRUE);
1259 }
1260 
1261 /**
1262  * Unregisters a transliterator or class.  This may be either
1263  * a system transliterator or a user transliterator or class.
1264  *
1265  * @param ID the ID of the transliterator or class
1266  * @see #registerInstance
1267 
1268  */
unregister(const UnicodeString & ID)1269 void U_EXPORT2 Transliterator::unregister(const UnicodeString& ID) {
1270     umtx_init(&registryMutex);
1271     Mutex lock(&registryMutex);
1272     if (HAVE_REGISTRY) {
1273         registry->remove(ID);
1274     }
1275 }
1276 
1277 /**
1278  * == OBSOLETE - remove in ICU 3.4 ==
1279  * Return the number of IDs currently registered with the system.
1280  * To retrieve the actual IDs, call getAvailableID(i) with
1281  * i from 0 to countAvailableIDs() - 1.
1282  */
countAvailableIDs(void)1283 int32_t U_EXPORT2 Transliterator::countAvailableIDs(void) {
1284     umtx_init(&registryMutex);
1285     Mutex lock(&registryMutex);
1286     return HAVE_REGISTRY ? registry->countAvailableIDs() : 0;
1287 }
1288 
1289 /**
1290  * == OBSOLETE - remove in ICU 3.4 ==
1291  * Return the index-th available ID.  index must be between 0
1292  * and countAvailableIDs() - 1, inclusive.  If index is out of
1293  * range, the result of getAvailableID(0) is returned.
1294  */
getAvailableID(int32_t index)1295 const UnicodeString& U_EXPORT2 Transliterator::getAvailableID(int32_t index) {
1296     const UnicodeString* result = NULL;
1297     umtx_init(&registryMutex);
1298     umtx_lock(&registryMutex);
1299     if (HAVE_REGISTRY) {
1300         result = &registry->getAvailableID(index);
1301     }
1302     umtx_unlock(&registryMutex);
1303     U_ASSERT(result != NULL); // fail if no registry
1304     return *result;
1305 }
1306 
getAvailableIDs(UErrorCode & ec)1307 StringEnumeration* U_EXPORT2 Transliterator::getAvailableIDs(UErrorCode& ec) {
1308     if (U_FAILURE(ec)) return NULL;
1309     StringEnumeration* result = NULL;
1310     umtx_init(&registryMutex);
1311     umtx_lock(&registryMutex);
1312     if (HAVE_REGISTRY) {
1313         result = registry->getAvailableIDs();
1314     }
1315     umtx_unlock(&registryMutex);
1316     if (result == NULL) {
1317         ec = U_INTERNAL_TRANSLITERATOR_ERROR;
1318     }
1319     return result;
1320 }
1321 
countAvailableSources(void)1322 int32_t U_EXPORT2 Transliterator::countAvailableSources(void) {
1323     umtx_init(&registryMutex);
1324     Mutex lock(&registryMutex);
1325     return HAVE_REGISTRY ? _countAvailableSources() : 0;
1326 }
1327 
getAvailableSource(int32_t index,UnicodeString & result)1328 UnicodeString& U_EXPORT2 Transliterator::getAvailableSource(int32_t index,
1329                                                   UnicodeString& result) {
1330     umtx_init(&registryMutex);
1331     Mutex lock(&registryMutex);
1332     if (HAVE_REGISTRY) {
1333         _getAvailableSource(index, result);
1334     }
1335     return result;
1336 }
1337 
countAvailableTargets(const UnicodeString & source)1338 int32_t U_EXPORT2 Transliterator::countAvailableTargets(const UnicodeString& source) {
1339     umtx_init(&registryMutex);
1340     Mutex lock(&registryMutex);
1341     return HAVE_REGISTRY ? _countAvailableTargets(source) : 0;
1342 }
1343 
getAvailableTarget(int32_t index,const UnicodeString & source,UnicodeString & result)1344 UnicodeString& U_EXPORT2 Transliterator::getAvailableTarget(int32_t index,
1345                                                   const UnicodeString& source,
1346                                                   UnicodeString& result) {
1347     umtx_init(&registryMutex);
1348     Mutex lock(&registryMutex);
1349     if (HAVE_REGISTRY) {
1350         _getAvailableTarget(index, source, result);
1351     }
1352     return result;
1353 }
1354 
countAvailableVariants(const UnicodeString & source,const UnicodeString & target)1355 int32_t U_EXPORT2 Transliterator::countAvailableVariants(const UnicodeString& source,
1356                                                const UnicodeString& target) {
1357     umtx_init(&registryMutex);
1358     Mutex lock(&registryMutex);
1359     return HAVE_REGISTRY ? _countAvailableVariants(source, target) : 0;
1360 }
1361 
getAvailableVariant(int32_t index,const UnicodeString & source,const UnicodeString & target,UnicodeString & result)1362 UnicodeString& U_EXPORT2 Transliterator::getAvailableVariant(int32_t index,
1363                                                    const UnicodeString& source,
1364                                                    const UnicodeString& target,
1365                                                    UnicodeString& result) {
1366     umtx_init(&registryMutex);
1367     Mutex lock(&registryMutex);
1368     if (HAVE_REGISTRY) {
1369         _getAvailableVariant(index, source, target, result);
1370     }
1371     return result;
1372 }
1373 
_countAvailableSources(void)1374 int32_t Transliterator::_countAvailableSources(void) {
1375     return registry->countAvailableSources();
1376 }
1377 
_getAvailableSource(int32_t index,UnicodeString & result)1378 UnicodeString& Transliterator::_getAvailableSource(int32_t index,
1379                                                   UnicodeString& result) {
1380     return registry->getAvailableSource(index, result);
1381 }
1382 
_countAvailableTargets(const UnicodeString & source)1383 int32_t Transliterator::_countAvailableTargets(const UnicodeString& source) {
1384     return registry->countAvailableTargets(source);
1385 }
1386 
_getAvailableTarget(int32_t index,const UnicodeString & source,UnicodeString & result)1387 UnicodeString& Transliterator::_getAvailableTarget(int32_t index,
1388                                                   const UnicodeString& source,
1389                                                   UnicodeString& result) {
1390     return registry->getAvailableTarget(index, source, result);
1391 }
1392 
_countAvailableVariants(const UnicodeString & source,const UnicodeString & target)1393 int32_t Transliterator::_countAvailableVariants(const UnicodeString& source,
1394                                                const UnicodeString& target) {
1395     return registry->countAvailableVariants(source, target);
1396 }
1397 
_getAvailableVariant(int32_t index,const UnicodeString & source,const UnicodeString & target,UnicodeString & result)1398 UnicodeString& Transliterator::_getAvailableVariant(int32_t index,
1399                                                    const UnicodeString& source,
1400                                                    const UnicodeString& target,
1401                                                    UnicodeString& result) {
1402     return registry->getAvailableVariant(index, source, target, result);
1403 }
1404 
1405 #ifdef U_USE_DEPRECATED_TRANSLITERATOR_API
1406 
1407 /**
1408  * Method for subclasses to use to obtain a character in the given
1409  * string, with filtering.
1410  * @deprecated the new architecture provides filtering at the top
1411  * level.  This method will be removed Dec 31 2001.
1412  */
filteredCharAt(const Replaceable & text,int32_t i) const1413 UChar Transliterator::filteredCharAt(const Replaceable& text, int32_t i) const {
1414     UChar c;
1415     const UnicodeFilter* localFilter = getFilter();
1416     return (localFilter == 0) ? text.charAt(i) :
1417         (localFilter->contains(c = text.charAt(i)) ? c : (UChar)0xFFFE);
1418 }
1419 
1420 #endif
1421 
1422 /**
1423  * If the registry is initialized, return TRUE.  If not, initialize it
1424  * and return TRUE.  If the registry cannot be initialized, return
1425  * FALSE (rare).
1426  *
1427  * IMPORTANT: Upon entry, registryMutex must be LOCKED.  The entirely
1428  * initialization is done with the lock held.  There is NO REASON to
1429  * unlock, since no other thread that is waiting on the registryMutex
1430  * cannot itself proceed until the registry is initialized.
1431  */
initializeRegistry()1432 UBool Transliterator::initializeRegistry() {
1433     if (registry != 0) {
1434         return TRUE;
1435     }
1436 
1437     UErrorCode status = U_ZERO_ERROR;
1438 
1439     registry = new TransliteratorRegistry(status);
1440     if (registry == 0 || U_FAILURE(status)) {
1441         delete registry;
1442         registry = 0;
1443         return FALSE; // can't create registry, no recovery
1444     }
1445 
1446     /* The following code parses the index table located in
1447      * icu/data/translit/root.txt.  The index is an n x 4 table
1448      * that follows this format:
1449      *  <id>{
1450      *      file{
1451      *          resource{"<resource>"}
1452      *          direction{"<direction>"}
1453      *      }
1454      *  }
1455      *  <id>{
1456      *      internal{
1457      *          resource{"<resource>"}
1458      *          direction{"<direction"}
1459      *       }
1460      *  }
1461      *  <id>{
1462      *      alias{"<getInstanceArg"}
1463      *  }
1464      * <id> is the ID of the system transliterator being defined.  These
1465      * are public IDs enumerated by Transliterator.getAvailableIDs(),
1466      * unless the second field is "internal".
1467      *
1468      * <resource> is a ResourceReader resource name.  Currently these refer
1469      * to file names under com/ibm/text/resources.  This string is passed
1470      * directly to ResourceReader, together with <encoding>.
1471      *
1472      * <direction> is either "FORWARD" or "REVERSE".
1473      *
1474      * <getInstanceArg> is a string to be passed directly to
1475      * Transliterator.getInstance().  The returned Transliterator object
1476      * then has its ID changed to <id> and is returned.
1477      *
1478      * The extra blank field on "alias" lines is to make the array square.
1479      */
1480     //static const char translit_index[] = "translit_index";
1481 
1482     UResourceBundle *bundle, *transIDs, *colBund;
1483     bundle = ures_open(U_ICUDATA_TRANSLIT, NULL/*open default locale*/, &status);
1484     transIDs = ures_getByKey(bundle, RB_RULE_BASED_IDS, 0, &status);
1485 
1486     int32_t row, maxRows;
1487     if (U_SUCCESS(status)) {
1488         maxRows = ures_getSize(transIDs);
1489         for (row = 0; row < maxRows; row++) {
1490             colBund = ures_getByIndex(transIDs, row, 0, &status);
1491             if (U_SUCCESS(status)) {
1492                 UnicodeString id(ures_getKey(colBund), -1, US_INV);
1493                 UResourceBundle* res = ures_getNextResource(colBund, NULL, &status);
1494                 const char* typeStr = ures_getKey(res);
1495                 UChar type;
1496                 u_charsToUChars(typeStr, &type, 1);
1497 
1498                 if (U_SUCCESS(status)) {
1499                     int32_t len = 0;
1500                     const UChar *resString;
1501                     switch (type) {
1502                     case 0x66: // 'f'
1503                     case 0x69: // 'i'
1504                         // 'file' or 'internal';
1505                         // row[2]=resource, row[3]=direction
1506                         {
1507 
1508                             resString = ures_getStringByKey(res, "resource", &len, &status);
1509                             UBool visible = (type == 0x0066 /*f*/);
1510                             UTransDirection dir =
1511                                 (ures_getUnicodeStringByKey(res, "direction", &status).charAt(0) ==
1512                                  0x0046 /*F*/) ?
1513                                 UTRANS_FORWARD : UTRANS_REVERSE;
1514                             registry->put(id, UnicodeString(TRUE, resString, len), dir, TRUE, visible);
1515                         }
1516                         break;
1517                     case 0x61: // 'a'
1518                         // 'alias'; row[2]=createInstance argument
1519                         resString = ures_getString(res, &len, &status);
1520                         registry->put(id, UnicodeString(TRUE, resString, len), TRUE, TRUE);
1521                         break;
1522                     }
1523                 }
1524                 ures_close(res);
1525             }
1526             ures_close(colBund);
1527         }
1528     }
1529 
1530     ures_close(transIDs);
1531     ures_close(bundle);
1532 
1533     // Manually add prototypes that the system knows about to the
1534     // cache.  This is how new non-rule-based transliterators are
1535     // added to the system.
1536 
1537     registry->put(new NullTransliterator(), TRUE);
1538     registry->put(new LowercaseTransliterator(), TRUE);
1539     registry->put(new UppercaseTransliterator(), TRUE);
1540     registry->put(new TitlecaseTransliterator(), TRUE);
1541     registry->put(new UnicodeNameTransliterator(), TRUE);
1542     registry->put(new NameUnicodeTransliterator(), TRUE);
1543 
1544     RemoveTransliterator::registerIDs(); // Must be within mutex
1545     EscapeTransliterator::registerIDs();
1546     UnescapeTransliterator::registerIDs();
1547     NormalizationTransliterator::registerIDs();
1548     AnyTransliterator::registerIDs();
1549 
1550     _registerSpecialInverse(UNICODE_STRING_SIMPLE("Null"),
1551                             UNICODE_STRING_SIMPLE("Null"), FALSE);
1552     _registerSpecialInverse(UNICODE_STRING_SIMPLE("Upper"),
1553                             UNICODE_STRING_SIMPLE("Lower"), TRUE);
1554     _registerSpecialInverse(UNICODE_STRING_SIMPLE("Title"),
1555                             UNICODE_STRING_SIMPLE("Lower"), FALSE);
1556 
1557     ucln_i18n_registerCleanup(UCLN_I18N_TRANSLITERATOR, transliterator_cleanup);
1558 
1559     return TRUE;
1560 }
1561 
1562 U_NAMESPACE_END
1563 
1564 // Defined in ucln_in.h:
1565 
1566 /**
1567  * Release all static memory held by transliterator.  This will
1568  * necessarily invalidate any rule-based transliterators held by the
1569  * user, because RBTs hold pointers to common data objects.
1570  */
transliterator_cleanup(void)1571 U_CFUNC UBool transliterator_cleanup(void) {
1572     U_NAMESPACE_USE
1573     TransliteratorIDParser::cleanup();
1574     if (registry) {
1575         delete registry;
1576         registry = NULL;
1577     }
1578     umtx_destroy(&registryMutex);
1579     return TRUE;
1580 }
1581 
1582 #endif /* #if !UCONFIG_NO_TRANSLITERATION */
1583 
1584 //eof
1585