1 // MessageFormat.java - Localized message formatting.
3 /* Copyright (C) 1999 Red Hat, Inc.
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
13 import java.util.Date;
14 import java.util.Locale;
15 import java.util.Vector;
18 * @author Tom Tromey <tromey@cygnus.com>
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.
27 final class MessageFormatElement
31 // Formatter to be used. This is the format set by setFormat.
33 // Formatter to be used based on the type.
36 // Argument will be checked to make sure it is an instance of this
45 // Text to follow this element.
48 // FIXME: shouldn't need this.
49 Class forName (String name)
53 return Class.forName (name);
55 catch (ClassNotFoundException x)
61 // Recompute the locale-based formatter.
62 void setLocale (Locale loc)
66 else if (type.equals("number"))
68 // FIXME: named class literal.
69 // formatClass = Number.class;
70 formatClass = forName ("java.lang.Number");
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"))
80 NumberFormat nf = NumberFormat.getNumberInstance(loc);
81 nf.setMaximumFractionDigits(0);
82 nf.setGroupingUsed(false);
87 format = NumberFormat.getNumberInstance(loc);
88 DecimalFormat df = (DecimalFormat) format;
91 df.applyPattern(style);
93 catch (ParseException x)
95 throw new IllegalArgumentException (x.getMessage());
99 else if (type.equals("time") || type.equals("date"))
101 // FIXME: named class literal.
102 // formatClass = Date.class;
103 formatClass = forName ("java.util.Date");
105 int val = DateFormat.DEFAULT;
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;
117 if (type.equals("time"))
118 format = DateFormat.getTimeInstance(val, loc);
120 format = DateFormat.getDateInstance(val, loc);
122 if (style != null && val == DateFormat.DEFAULT)
124 SimpleDateFormat sdf = (SimpleDateFormat) format;
125 sdf.applyPattern(style);
128 else if (type.equals("choice"))
130 // FIXME: named class literal.
131 // formatClass = Number.class;
132 formatClass = forName ("java.lang.Number");
136 IllegalArgumentException ("style required for choice format");
137 format = new ChoiceFormat (style);
142 public class MessageFormat extends Format
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,
150 int max = pat.length();
152 for (; index < max; ++index)
154 char c = pat.charAt(index);
155 if (c == '\'' && index + 2 < max && pat.charAt(index + 2) == '\'')
157 buffer.append(pat.charAt(index + 1));
160 else if (c == '\'' && index + 1 < max
161 && pat.charAt(index + 1) == '\'')
169 throw new IllegalArgumentException ();
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,
182 int max = pat.length();
186 for (; index < max; ++index)
188 char c = pat.charAt(index);
189 if (c == '\'' && index + 2 < max && pat.charAt(index + 2) == '\'')
192 buffer.append(pat.charAt(index + 1));
196 else if (c == '\'' && index + 1 < max
197 && pat.charAt(index + 1) == '\'')
209 if (--brace_depth == 0)
213 // Check for TERM after braces, because TERM might be `}'.
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,
228 MessageFormatElement mfe = new MessageFormatElement ();
229 elts.addElement(mfe);
231 int max = pat.length();
233 // Skip the opening `{'.
236 // Fetch the argument number.
237 index = scanFormatElement (pat, index, buffer, ',');
240 mfe.argNumber = Integer.parseInt(buffer.toString());
242 catch (NumberFormatException nfx)
244 throw new IllegalArgumentException ();
247 // Extract the element format.
248 if (index < max && pat.charAt(index) == ',')
250 index = scanFormatElement (pat, index + 1, buffer, ',');
251 mfe.type = buffer.toString();
253 // Extract the style.
254 if (index < max && pat.charAt(index) == ',')
256 index = scanFormatElement (pat, index + 1, buffer, '}');
257 mfe.style = buffer.toString ();
261 // Advance past the last terminator.
262 if (index >= max || pat.charAt(index) != '}')
263 throw new IllegalArgumentException ();
266 // Now fetch trailing string.
267 index = scanString (pat, index, buffer);
268 mfe.trailer = buffer.toString ();
270 mfe.setLocale(locale);
275 public void applyPattern (String newPattern)
277 pattern = newPattern;
279 StringBuffer tempBuffer = new StringBuffer ();
281 int index = scanString (newPattern, 0, tempBuffer);
282 leader = tempBuffer.toString();
284 Vector elts = new Vector ();
285 while (index < newPattern.length())
286 index = scanFormat (newPattern, index, tempBuffer, elts, locale);
288 elements = new MessageFormatElement[elts.size()];
289 elts.copyInto(elements);
292 public Object clone ()
294 MessageFormat c = new MessageFormat ();
296 c.applyPattern(pattern);
300 public boolean equals (Object obj)
302 if (! (obj instanceof MessageFormat))
304 MessageFormat mf = (MessageFormat) obj;
305 return (pattern.equals(mf.pattern)
306 && locale.equals(mf.locale));
309 public static String format (String pattern, Object arguments[])
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();
317 public final StringBuffer format (Object arguments[], StringBuffer appendBuf,
318 FieldPosition ignore)
320 appendBuf.append(leader);
322 for (int i = 0; i < elements.length; ++i)
324 if (elements[i].argNumber >= arguments.length)
325 throw new IllegalArgumentException ();
326 Object thisArg = arguments[elements[i].argNumber];
328 Format formatter = null;
329 if (elements[i].setFormat != null)
330 formatter = elements[i].setFormat;
331 else if (elements[i].format != null)
333 if (elements[i].formatClass != null
334 && ! elements[i].formatClass.isInstance(thisArg))
335 throw new IllegalArgumentException ();
336 formatter = elements[i].format;
338 else if (thisArg instanceof Number)
339 formatter = NumberFormat.getInstance(locale);
340 else if (thisArg instanceof Date)
341 formatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
343 appendBuf.append(thisArg);
345 if (formatter != null)
347 // Special-case ChoiceFormat.
348 if (formatter instanceof ChoiceFormat)
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
355 formatter.format(thisArg, buf, ignore);
356 MessageFormat mf = new MessageFormat ();
357 mf.setLocale(locale);
358 mf.applyPattern(buf.toString());
361 formatter.format(thisArg, appendBuf, ignore);
364 appendBuf.append(elements[i].trailer);
370 public final StringBuffer format (Object singleArg, StringBuffer appendBuf,
371 FieldPosition ignore)
373 Object[] args = new Object[1];
375 return format (args, appendBuf, ignore);
378 public Format[] getFormats ()
380 Format[] f = new Format[elements.length];
381 for (int i = elements.length - 1; i >= 0; --i)
382 f[i] = elements[i].setFormat;
386 public Locale getLocale ()
391 public int hashCode ()
393 // FIXME: not a very good hash.
394 return pattern.hashCode() + locale.hashCode();
397 private MessageFormat ()
401 public MessageFormat (String pattern)
403 locale = Locale.getDefault();
404 applyPattern (pattern);
407 public Object[] parse (String sourceStr, ParsePosition pos)
409 // Check initial text.
410 int index = pos.getIndex();
411 if (! sourceStr.startsWith(leader, index))
413 pos.setErrorIndex(index);
416 index += leader.length();
418 Vector results = new Vector (elements.length, 1);
419 // Now check each format.
420 for (int i = 0; i < elements.length; ++i)
422 Format formatter = null;
423 if (elements[i].setFormat != null)
424 formatter = elements[i].setFormat;
425 else if (elements[i].format != null)
426 formatter = elements[i].format;
429 if (formatter instanceof ChoiceFormat)
431 // We must special-case a ChoiceFormat because it might
432 // have recursive formatting.
433 ChoiceFormat cf = (ChoiceFormat) formatter;
434 String[] formats = (String[]) cf.getFormats();
435 double[] limits = (double[]) cf.getLimits();
436 MessageFormat subfmt = new MessageFormat ();
437 subfmt.setLocale(locale);
438 ParsePosition subpos = new ParsePosition (index);
441 for (j = 0; value == null && j < limits.length; ++j)
443 subfmt.applyPattern(formats[j]);
444 subpos.setIndex(index);
445 value = subfmt.parse(sourceStr, subpos);
449 index = subpos.getIndex();
450 value = new Double (limits[j]);
453 else if (formatter != null)
456 value = formatter.parseObject(sourceStr, pos);
458 index = pos.getIndex();
462 // We have a String format. This can lose in a number
463 // of ways, but we give it a shot.
464 int next_index = sourceStr.indexOf(elements[i].trailer, index);
465 if (next_index == -1)
467 pos.setErrorIndex(index);
470 value = sourceStr.substring(index, next_index);
475 || ! sourceStr.startsWith(elements[i].trailer, index))
477 pos.setErrorIndex(index);
481 if (elements[i].argNumber >= results.size())
482 results.setSize(elements[i].argNumber + 1);
483 results.setElementAt(value, elements[i].argNumber);
485 index += elements[i].trailer.length();
488 Object[] r = new Object[results.size()];
493 public Object[] parse (String sourceStr) throws ParseException
495 ParsePosition pp = new ParsePosition (0);
496 Object[] r = parse (sourceStr, pp);
498 throw new ParseException ("couldn't parse string", pp.getErrorIndex());
502 public Object parseObject (String sourceStr, ParsePosition pos)
504 return parse (sourceStr, pos);
507 public void setFormat (int variableNum, Format newFormat)
509 elements[variableNum].setFormat = newFormat;
512 public void setFormats (Format[] newFormats)
514 if (newFormats.length < elements.length)
515 throw new IllegalArgumentException ();
516 int len = Math.min(newFormats.length, elements.length);
517 for (int i = 0; i < len; ++i)
518 elements[i].setFormat = newFormats[i];
521 public void setLocale (Locale loc)
524 if (elements != null)
526 for (int i = 0; i < elements.length; ++i)
527 elements[i].setLocale(loc);
531 public String toPattern ()
536 // The pattern string.
537 private String pattern;
539 private Locale locale;
541 private MessageFormatElement[] elements;
543 private String leader;