OSDN Git Service

Initial revision
[pf3gnuchains/gcc-fork.git] / libjava / java / text / MessageFormat.java
1 // MessageFormat.java - Localized message formatting.
2
3 /* Copyright (C) 1999  Cygnus Solutions
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 package java.text;
12
13 import java.util.Date;
14 import java.util.Locale;
15 import java.util.Vector;
16
17 /**
18  * @author Tom Tromey <tromey@cygnus.com>
19  * @date March 3, 1999
20  */
21 /* Written using "Java Class Libraries", 2nd edition, plus online
22  * API docs for JDK 1.2 from http://www.javasoft.com.
23  * Status:  Believed complete and correct to 1.2, except serialization.
24  *          and parsing.
25  */
26
27 final class MessageFormatElement
28 {
29   // Argument number.
30   int argNumber;
31   // Formatter to be used.  This is the format set by setFormat.
32   Format setFormat;
33   // Formatter to be used based on the type.
34   Format format;
35
36   // Argument will be checked to make sure it is an instance of this
37   // class.
38   Class formatClass;
39
40   // Formatter type.
41   String type;
42   // Formatter style.
43   String style;
44
45   // Text to follow this element.
46   String trailer;
47
48   // FIXME: shouldn't need this.
49   Class forName (String name)
50     {
51       try
52         {
53           return Class.forName (name);
54         }
55       catch (ClassNotFoundException x)
56         {
57         }
58       return null;
59     }
60
61   // Recompute the locale-based formatter.
62   void setLocale (Locale loc)
63     {
64       if (type == null)
65         ;
66       else if (type.equals("number"))
67         {
68           // FIXME: named class literal.
69           // formatClass = Number.class;
70           formatClass = forName ("java.lang.Number");
71
72           if (style == null)
73             format = NumberFormat.getInstance(loc);
74           else if (style.equals("currency"))
75             format = NumberFormat.getCurrencyInstance(loc);
76           else if (style.equals("percent"))
77             format = NumberFormat.getPercentInstance(loc);
78           else if (style.equals("integer"))
79             {
80               NumberFormat nf = NumberFormat.getNumberInstance(loc);
81               nf.setMaximumFractionDigits(0);
82               nf.setGroupingUsed(false);
83               format = nf;
84             }
85           else
86             {
87               format = NumberFormat.getNumberInstance(loc);
88               DecimalFormat df = (DecimalFormat) format;
89               try
90                 {
91                   df.applyPattern(style);
92                 }
93               catch (ParseException x)
94                 {
95                   throw new IllegalArgumentException (x.getMessage());
96                 }
97             }
98         }
99       else if (type.equals("time") || type.equals("date"))
100         {
101           // FIXME: named class literal.
102           // formatClass = Date.class;
103           formatClass = forName ("java.util.Date");
104
105           int val = DateFormat.DEFAULT;
106           if (style == null)
107             ;
108           if (style.equals("short"))
109             val = DateFormat.SHORT;
110           else if (style.equals("medium"))
111             val = DateFormat.MEDIUM;
112           else if (style.equals("long"))
113             val = DateFormat.LONG;
114           else if (style.equals("full"))
115             val = DateFormat.FULL;
116
117           if (type.equals("time"))
118             format = DateFormat.getTimeInstance(val, loc);
119           else
120             format = DateFormat.getDateInstance(val, loc);
121
122           if (style != null && val == DateFormat.DEFAULT)
123             {
124               SimpleDateFormat sdf = (SimpleDateFormat) format;
125               sdf.applyPattern(style);
126             }
127         }
128       else if (type.equals("choice"))
129         {
130           // FIXME: named class literal.
131           // formatClass = Number.class;
132           formatClass = forName ("java.lang.Number");
133
134           if (style == null)
135             throw new
136               IllegalArgumentException ("style required for choice format");
137           format = new ChoiceFormat (style);
138         }
139     }
140 }
141
142 public class MessageFormat extends Format
143 {
144   // Helper that returns the text up to the next format opener.  The
145   // text is put into BUFFER.  Returns index of character after end of
146   // string.  Throws IllegalArgumentException on error.
147   private static final int scanString (String pat, int index,
148                                        StringBuffer buffer)
149     {
150       int max = pat.length();
151       buffer.setLength(0);
152       for (; index < max; ++index)
153         {
154           char c = pat.charAt(index);
155           if (c == '\'' && index + 2 < max && pat.charAt(index + 2) == '\'')
156             {
157               buffer.append(pat.charAt(index + 1));
158               index += 2;
159             }
160           else if (c == '\'' && index + 1 < max
161                    && pat.charAt(index + 1) == '\'')
162             {
163               buffer.append(c);
164               ++index;
165             }
166           else if (c == '{')
167             break;
168           else if (c == '}')
169             throw new IllegalArgumentException ();
170           else
171             buffer.append(c);
172         }
173       return index;
174     }
175
176   // This helper retrieves a single part of a format element.  Returns
177   // the index of the terminating character.
178   private static final int scanFormatElement (String pat, int index,
179                                               StringBuffer buffer,
180                                               char term)
181     {
182       int max = pat.length();
183       buffer.setLength(0);
184       int brace_depth = 1;
185
186       for (; index < max; ++index)
187         {
188           char c = pat.charAt(index);
189           if (c == '\'' && index + 2 < max && pat.charAt(index + 2) == '\'')
190             {
191               buffer.append(c);
192               buffer.append(pat.charAt(index + 1));
193               buffer.append(c);
194               index += 2;
195             }
196           else if (c == '\'' && index + 1 < max
197                    && pat.charAt(index + 1) == '\'')
198             {
199               buffer.append(c);
200               ++index;
201             }
202           else if (c == '{')
203             {
204               buffer.append(c);
205               ++brace_depth;
206             }
207           else if (c == '}')
208             {
209               if (--brace_depth == 0)
210                 break;
211               buffer.append(c);
212             }
213           // Check for TERM after braces, because TERM might be `}'.
214           else if (c == term)
215             break;
216           else
217             buffer.append(c);
218         }
219       return index;
220     }
221
222   // This is used to parse a format element and whatever non-format
223   // text might trail it.
224   private static final int scanFormat (String pat, int index,
225                                        StringBuffer buffer, Vector elts,
226                                        Locale locale)
227     {
228       MessageFormatElement mfe = new MessageFormatElement ();
229       elts.addElement(mfe);
230
231       int max = pat.length();
232
233       // Skip the opening `{'.
234       ++index;
235
236       // Fetch the argument number.
237       index = scanFormatElement (pat, index, buffer, ',');
238       try
239         {
240           mfe.argNumber = Integer.parseInt(buffer.toString());
241         }
242       catch (NumberFormatException nfx)
243         {
244           throw new IllegalArgumentException ();
245         }
246
247       // Extract the element format.
248       if (index < max && pat.charAt(index) == ',')
249         {
250           index = scanFormatElement (pat, index + 1, buffer, ',');
251           mfe.type = buffer.toString();
252
253           // Extract the style.
254           if (index < max && pat.charAt(index) == ',')
255             {
256               index = scanFormatElement (pat, index + 1, buffer, '}');
257               mfe.style = buffer.toString ();
258             }
259         }
260
261       // Advance past the last terminator.
262       if (index >= max || pat.charAt(index) != '}')
263         throw new IllegalArgumentException ();
264       ++index;
265
266       // Now fetch trailing string.
267       index = scanString (pat, index, buffer);
268       mfe.trailer = buffer.toString ();
269
270       mfe.setLocale(locale);
271
272       return index;
273     }
274
275   public void applyPattern (String newPattern)
276     {
277       pattern = newPattern;
278
279       StringBuffer tempBuffer = new StringBuffer ();
280
281       int index = scanString (newPattern, 0, tempBuffer);
282       leader = tempBuffer.toString();
283
284       Vector elts = new Vector ();
285       while (index < newPattern.length())
286         index = scanFormat (newPattern, index, tempBuffer, elts, locale);
287
288       elements = new MessageFormatElement[elts.size()];
289       elts.copyInto(elements);
290     }
291
292   public Object clone ()
293     {
294       MessageFormat c = new MessageFormat ();
295       c.setLocale(locale);
296       c.applyPattern(pattern);
297       return (Object) c;
298     }
299
300   public boolean equals (Object obj)
301     {
302       if (! (obj instanceof MessageFormat))
303         return false;
304       MessageFormat mf = (MessageFormat) obj;
305       return (pattern.equals(mf.pattern)
306               && locale.equals(mf.locale));
307     }
308
309   public static String format (String pattern, Object arguments[])
310     {
311       MessageFormat mf = new MessageFormat (pattern);
312       StringBuffer sb = new StringBuffer ();
313       FieldPosition fp = new FieldPosition (NumberFormat.INTEGER_FIELD);
314       return mf.format(arguments, sb, fp).toString();
315     }
316
317   public final StringBuffer format (Object arguments[], StringBuffer appendBuf,
318                                     FieldPosition ignore)
319     {
320       appendBuf.append(leader);
321
322       for (int i = 0; i < elements.length; ++i)
323         {
324           if (elements[i].argNumber >= arguments.length)
325             throw new IllegalArgumentException ();
326           Object thisArg = arguments[elements[i].argNumber];
327
328           Format formatter = null;
329           if (elements[i].setFormat != null)
330             formatter = elements[i].setFormat;
331           else if (elements[i].format != null)
332             {
333               if (elements[i].formatClass != null
334                   && ! elements[i].formatClass.isInstance(thisArg))
335                 throw new IllegalArgumentException ();
336               formatter = elements[i].format;
337             }
338           else if (thisArg instanceof Number)
339             formatter = NumberFormat.getInstance(locale);
340           else if (thisArg instanceof Date)
341             formatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
342           else
343             appendBuf.append(thisArg);
344
345           if (formatter != null)
346             {
347               // Special-case ChoiceFormat.
348               if (formatter instanceof ChoiceFormat)
349                 {
350                   StringBuffer buf = new StringBuffer ();
351                   // FIXME: don't actually know what is correct here.
352                   // Can a sub-format refer to any argument, or just
353                   // the single argument passed to it?  Must test
354                   // against JDK.
355                   formatter.format(thisArg, buf, ignore);
356                   MessageFormat mf = new MessageFormat ();
357                   mf.setLocale(locale);
358                   mf.applyPattern(buf.toString());
359                   formatter = mf;
360                 }
361               formatter.format(thisArg, appendBuf, ignore);
362             }
363
364           appendBuf.append(elements[i].trailer);
365         }
366
367       return appendBuf;
368     }
369
370   public final StringBuffer format (Object singleArg, StringBuffer appendBuf,
371                                     FieldPosition ignore)
372     {
373       Object[] args = new Object[1];
374       args[0] = singleArg;
375       return format (args, appendBuf, ignore);
376     }
377
378   public Format[] getFormats ()
379     {
380       Format[] f = new Format[elements.length];
381       for (int i = elements.length - 1; i >= 0; --i)
382         f[i] = elements[i].setFormat;
383       return f;
384     }
385
386   public Locale getLocale ()
387     {
388       return locale;
389     }
390
391   public int hashCode ()
392     {
393       // FIXME: not a very good hash.
394       return pattern.hashCode() + locale.hashCode();
395     }
396
397   private MessageFormat ()
398     {
399     }
400
401   public MessageFormat (String pattern)
402     {
403       applyPattern (pattern);
404     }
405
406   public Object[] parse (String sourceStr, ParsePosition pos)
407     {
408       // Check initial text.
409       int index = pos.getIndex();
410       if (! sourceStr.startsWith(leader, index))
411         {
412           pos.setErrorIndex(index);
413           return null;
414         }
415       index += leader.length();
416
417       Vector results = new Vector (elements.length, 1);
418       // Now check each format.
419       for (int i = 0; i < elements.length; ++i)
420         {
421           Format formatter = null;
422           if (elements[i].setFormat != null)
423             formatter = elements[i].setFormat;
424           else if (elements[i].format != null)
425             formatter = elements[i].format;
426
427           Object value = null;
428           if (formatter instanceof ChoiceFormat)
429             {
430               // We must special-case a ChoiceFormat because it might
431               // have recursive formatting.
432               ChoiceFormat cf = (ChoiceFormat) formatter;
433               String[] formats = (String[]) cf.getFormats();
434               double[] limits = (double[]) cf.getLimits();
435               MessageFormat subfmt = new MessageFormat ();
436               subfmt.setLocale(locale);
437               ParsePosition subpos = new ParsePosition (index);
438
439               int j;
440               for (j = 0; value == null && j < limits.length; ++j)
441                 {
442                   subfmt.applyPattern(formats[j]);
443                   subpos.setIndex(index);
444                   value = subfmt.parse(sourceStr, subpos);
445                 }
446               if (value != null)
447                 {
448                   index = subpos.getIndex();
449                   value = new Double (limits[j]);
450                 }
451             }
452           else if (formatter != null)
453             {
454               pos.setIndex(index);
455               value = formatter.parseObject(sourceStr, pos);
456               if (value != null)
457                 index = pos.getIndex();
458             }
459           else
460             {
461               // We have a String format.  This can lose in a number
462               // of ways, but we give it a shot.
463               int next_index = sourceStr.indexOf(elements[i].trailer, index);
464               if (next_index == -1)
465                 {
466                   pos.setErrorIndex(index);
467                   return null;
468                 }
469               value = sourceStr.substring(index, next_index);
470               index = next_index;
471             }
472
473           if (value == null
474               || ! sourceStr.startsWith(elements[i].trailer, index))
475             {
476               pos.setErrorIndex(index);
477               return null;
478             }
479
480           if (elements[i].argNumber >= results.size())
481             results.setSize(elements[i].argNumber + 1);
482           results.setElementAt(value, elements[i].argNumber);
483
484           index += elements[i].trailer.length();
485         }
486
487       Object[] r = new Object[results.size()];
488       results.copyInto(r);
489       return r;
490     }
491
492   public Object[] parse (String sourceStr) throws ParseException
493     {
494       ParsePosition pp = new ParsePosition (0);
495       Object[] r = parse (sourceStr, pp);
496       if (r == null)
497         throw new ParseException ("couldn't parse string", pp.getErrorIndex());
498       return r;
499     }
500
501   public Object parseObject (String sourceStr, ParsePosition pos)
502     {
503       return parse (sourceStr, pos);
504     }
505
506   public void setFormat (int variableNum, Format newFormat)
507     {
508       elements[variableNum].setFormat = newFormat;
509     }
510
511   public void setFormats (Format[] newFormats)
512     {
513       if (newFormats.length < elements.length)
514         throw new IllegalArgumentException ();
515       int len = Math.min(newFormats.length, elements.length);
516       for (int i = 0; i < len; ++i)
517         elements[i].setFormat = newFormats[i];
518     }
519
520   public void setLocale (Locale loc)
521     {
522       locale = loc;
523       if (elements != null)
524         {
525           for (int i = 0; i < elements.length; ++i)
526             elements[i].setLocale(loc);
527         }
528     }
529
530   public String toPattern ()
531     {
532       return pattern;
533     }
534
535   // The pattern string.
536   private String pattern;
537   // The locale.
538   private Locale locale;
539   // Variables.
540   private MessageFormatElement[] elements;
541   // Leader text.
542   private String leader;
543 }