secondarycolour not used
[jalview.git] / src / jalview / util / Format.save
1 /*\r
2  * Cay S. Horstmann & Gary Cornell, Core Java\r
3  * Published By Sun Microsystems Press/Prentice-Hall\r
4  * Copyright (C) 1997 Sun Microsystems Inc.\r
5  * All Rights Reserved.\r
6  *\r
7  * Permission to use, copy, modify, and distribute this \r
8  * software and its documentation for NON-COMMERCIAL purposes\r
9  * and without fee is hereby granted provided that this \r
10  * copyright notice appears in all copies. \r
11  * \r
12  * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR \r
13  * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER \r
14  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE \r
15  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A \r
16  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS\r
17  * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED \r
18  * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING \r
19  * THIS SOFTWARE OR ITS DERIVATIVES.\r
20  */\r
21  \r
22 /**\r
23  * A class for formatting numbers that follows printf conventions.\r
24  * Also implements C-like atoi and atof functions\r
25  * @version 1.03 25 Oct 1997\r
26  * @author Cay Horstmann\r
27  */\r
28 \r
29 package jalview.util;\r
30 \r
31 import java.io.*;\r
32 \r
33 public class Format\r
34 \r
35 { /** \r
36   * Formats the number following printf conventions.\r
37   * Main limitation: Can only handle one format parameter at a time\r
38   * Use multiple Format objects to format more than one number\r
39   * @param s the format string following printf conventions\r
40   * The string has a prefix, a format code and a suffix. The prefix and suffix\r
41   * become part of the formatted output. The format code directs the\r
42   * formatting of the (single) parameter to be formatted. The code has the\r
43   * following structure\r
44   * <ul>\r
45   * <li> a % (required)\r
46   * <li> a modifier (optional)\r
47   * <dl>\r
48   * <dt> + <dd> forces display of + for positive numbers\r
49   * <dt> 0 <dd> show leading zeroes\r
50   * <dt> - <dd> align left in the field\r
51   * <dt> space <dd> prepend a space in front of positive numbers\r
52   * <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.\r
53   * </dl>\r
54   * <li> an integer denoting field width (optional)\r
55   * <li> a period followed by an integer denoting precision (optional)\r
56   * <li> a format descriptor (required)\r
57   * <dl>\r
58   * <dt>f <dd> floating point number in fixed format\r
59   * <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.\r
60   * <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.\r
61   * <dt>d, i <dd> integer in decimal\r
62   * <dt>x <dd> integer in hexadecimal\r
63   * <dt>o <dd> integer in octal\r
64   * <dt>s <dd> string\r
65   * <dt>c <dd> character\r
66   * </dl>\r
67   * </ul>\r
68   * @exception IllegalArgumentException if bad format\r
69   */\r
70 \r
71    public Format(String s)\r
72    {  width = 0;\r
73       precision = -1;\r
74       pre = "";\r
75       post = "";\r
76       leading_zeroes = false;\r
77       show_plus = false;\r
78       alternate = false;\r
79       show_space = false;\r
80       left_align = false;\r
81       fmt = ' '; \r
82       \r
83       int state = 0; \r
84       int length = s.length();\r
85       int parse_state = 0; \r
86       // 0 = prefix, 1 = flags, 2 = width, 3 = precision,\r
87       // 4 = format, 5 = end\r
88       int i = 0;\r
89       \r
90       while (parse_state == 0)\r
91       {  if (i >= length) parse_state = 5;\r
92          else if (s.charAt(i) == '%')\r
93          {  if (i < length - 1)\r
94             {  if (s.charAt(i + 1) == '%')\r
95                {  pre = pre + '%';\r
96                   i++;\r
97                }\r
98                else\r
99                   parse_state = 1;\r
100             }\r
101             else throw new java.lang.IllegalArgumentException();\r
102          }\r
103          else\r
104             pre = pre + s.charAt(i);\r
105          i++;\r
106       }\r
107       while (parse_state == 1)\r
108       {  if (i >= length) parse_state = 5;\r
109          else if (s.charAt(i) == ' ') show_space = true;\r
110          else if (s.charAt(i) == '-') left_align = true; \r
111          else if (s.charAt(i) == '+') show_plus = true;\r
112          else if (s.charAt(i) == '0') leading_zeroes = true;\r
113          else if (s.charAt(i) == '#') alternate = true;\r
114          else { parse_state = 2; i--; }\r
115          i++;\r
116       }      \r
117       while (parse_state == 2)\r
118       {  if (i >= length) parse_state = 5;\r
119          else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')\r
120          {  width = width * 10 + s.charAt(i) - '0';\r
121             i++;\r
122          }\r
123          else if (s.charAt(i) == '.')\r
124          {  parse_state = 3;\r
125             precision = 0;\r
126             i++;\r
127          }\r
128          else \r
129             parse_state = 4;            \r
130       }\r
131       while (parse_state == 3)\r
132       {  if (i >= length) parse_state = 5;\r
133          else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')\r
134          {  precision = precision * 10 + s.charAt(i) - '0';\r
135             i++;\r
136          }\r
137          else \r
138             parse_state = 4;                  \r
139       }\r
140       if (parse_state == 4) \r
141       {  if (i >= length) parse_state = 5;\r
142          else fmt = s.charAt(i);\r
143          i++;\r
144       }\r
145       if (i < length)\r
146          post = s.substring(i, length);\r
147    }      \r
148 \r
149   /** \r
150   * prints a formatted number following printf conventions\r
151   * @param s a PrintStream\r
152   * @param fmt the format string\r
153   * @param x the double to print\r
154   */\r
155   \r
156    public static void print(java.io.PrintStream s, String fmt, double x)\r
157    {  s.print(new Format(fmt).form(x));\r
158    }\r
159 \r
160   /** \r
161   * prints a formatted number following printf conventions\r
162   * @param s a PrintStream\r
163   * @param fmt the format string\r
164   * @param x the long to print\r
165   */\r
166   public static void print(java.io.PrintStream s, String fmt, long x)\r
167    {  s.print(new Format(fmt).form(x));\r
168    }\r
169 \r
170   /** \r
171   * prints a formatted number following printf conventions\r
172   * @param s a PrintStream\r
173   * @param fmt the format string\r
174   * @param x the character to \r
175   */\r
176   \r
177    public static void print(java.io.PrintStream s, String fmt, char x)\r
178    {  s.print(new Format(fmt).form(x));\r
179    }\r
180 \r
181   /** \r
182   * prints a formatted number following printf conventions\r
183   * @param s a PrintStream, fmt the format string\r
184   * @param x a string that represents the digits to print\r
185   */\r
186   \r
187    public static void print(java.io.PrintStream s, String fmt, String x)\r
188    {  s.print(new Format(fmt).form(x));\r
189    }\r
190    \r
191   /** \r
192   * Converts a string of digits (decimal, octal or hex) to an integer\r
193   * @param s a string\r
194   * @return the numeric value of the prefix of s representing a base 10 integer\r
195   */\r
196   \r
197    public static int atoi(String s)\r
198    {  return (int)atol(s);\r
199    } \r
200    \r
201   /** \r
202   * Converts a string of digits (decimal, octal or hex) to a long integer\r
203   * @param s a string\r
204   * @return the numeric value of the prefix of s representing a base 10 integer\r
205   */\r
206   \r
207    public static long atol(String s)\r
208    {  int i = 0;\r
209 \r
210       while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;\r
211       if (i < s.length() && s.charAt(i) == '0')\r
212       {  if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))\r
213             return parseLong(s.substring(i + 2), 16);\r
214          else return parseLong(s, 8);\r
215       }\r
216       else return parseLong(s, 10);\r
217    }\r
218 \r
219    private static long parseLong(String s, int base)\r
220    {  int i = 0;\r
221       int sign = 1;\r
222       long r = 0;\r
223       \r
224       while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;\r
225       if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }\r
226       else if (i < s.length() && s.charAt(i) == '+') { i++; }\r
227       while (i < s.length())\r
228       {  char ch = s.charAt(i);\r
229          if ('0' <= ch && ch < '0' + base)\r
230             r = r * base + ch - '0';\r
231          else if ('A' <= ch && ch < 'A' + base - 10)\r
232             r = r * base + ch - 'A' + 10 ;\r
233          else if ('a' <= ch && ch < 'a' + base - 10)\r
234             r = r * base + ch - 'a' + 10 ;\r
235          else \r
236             return r * sign;\r
237          i++;\r
238       }\r
239       return r * sign;      \r
240    }\r
241       \r
242    /** \r
243    * Converts a string of digits to an double\r
244    * @param s a string\r
245    */\r
246    \r
247    public static double atof(String s)\r
248    {  int i = 0;\r
249       int sign = 1;\r
250       double r = 0; // integer part\r
251       double f = 0; // fractional part\r
252       double p = 1; // exponent of fractional part\r
253       int state = 0; // 0 = int part, 1 = frac part\r
254       \r
255       while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;\r
256       if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }\r
257       else if (i < s.length() && s.charAt(i) == '+') { i++; }\r
258       while (i < s.length())\r
259       {  char ch = s.charAt(i);\r
260          if ('0' <= ch && ch <= '9')\r
261          {  if (state == 0)\r
262                r = r * 10 + ch - '0';\r
263             else if (state == 1)\r
264             {  p = p / 10;\r
265                r = r + p * (ch - '0');\r
266             }\r
267          }\r
268          else if (ch == '.') \r
269          {  if (state == 0) state = 1; \r
270             else return sign * r;\r
271          }\r
272          else if (ch == 'e' || ch == 'E')\r
273          {  long e = (int)parseLong(s.substring(i + 1), 10);\r
274             return sign * r * Math.pow(10, e);\r
275          }\r
276          else return sign * r;\r
277          i++;\r
278       }\r
279       return sign * r;\r
280    }\r
281             \r
282    /** \r
283    * Formats a double into a string (like sprintf in C)\r
284    * @param x the number to format\r
285    * @return the formatted string \r
286    * @exception IllegalArgumentException if bad argument\r
287    */\r
288    \r
289    public String form(double x)\r
290    {  String r;\r
291       if (precision < 0) precision = 6;\r
292       int s = 1;\r
293       if (x < 0) { x = -x; s = -1; }\r
294       if (fmt == 'f')\r
295          r = fixed_format(x);\r
296       else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')\r
297          r = exp_format(x);\r
298       else throw new java.lang.IllegalArgumentException();\r
299       \r
300       return pad(sign(s, r));\r
301    }\r
302    \r
303    /** \r
304    * Formats a long integer into a string (like sprintf in C)\r
305    * @param x the number to format\r
306    * @return the formatted string \r
307    */\r
308    \r
309    public String form(long x)\r
310    {  String r; \r
311       int s = 0;\r
312       if (fmt == 'd' || fmt == 'i')\r
313       {  if (x < 0) \r
314          {  r = ("" + x).substring(1);\r
315             s = -1; \r
316          }\r
317          else \r
318          {  r = "" + x; \r
319             s = 1;\r
320          }\r
321       }\r
322       else if (fmt == 'o')\r
323          r = convert(x, 3, 7, "01234567");\r
324       else if (fmt == 'x')\r
325          r = convert(x, 4, 15, "0123456789abcdef");\r
326       else if (fmt == 'X')\r
327          r = convert(x, 4, 15, "0123456789ABCDEF");\r
328       else throw new java.lang.IllegalArgumentException();\r
329          \r
330       return pad(sign(s, r));\r
331    }\r
332    \r
333    /** \r
334    * Formats a character into a string (like sprintf in C)\r
335    * @param x the value to format\r
336    * @return the formatted string \r
337    */\r
338    \r
339    public String form(char c)\r
340    {  if (fmt != 'c')\r
341          throw new java.lang.IllegalArgumentException();\r
342 \r
343       String r = "" + c;\r
344       return pad(r);\r
345    }\r
346    \r
347    /** \r
348    * Formats a string into a larger string (like sprintf in C)\r
349    * @param x the value to format\r
350    * @return the formatted string \r
351    */\r
352    \r
353    public String form(String s)\r
354    {  if (fmt != 's')\r
355          throw new java.lang.IllegalArgumentException();\r
356       if (precision >= 0) s = s.substring(0, precision);\r
357       return pad(s);\r
358    }\r
359    \r
360     \r
361    /**\r
362    * a test stub for the format class\r
363    */\r
364    \r
365    public static void main(String[] a)\r
366    {  double x = 1.23456789012;\r
367       double y = 123;\r
368       double z = 1.2345e30;\r
369       double w = 1.02;\r
370       double u = 1.234e-5;\r
371       int d = 0xCAFE;\r
372       Format.print(System.out, "x = |%f|\n", x);\r
373       Format.print(System.out, "u = |%20f|\n", u);\r
374       Format.print(System.out, "x = |% .5f|\n", x);\r
375       Format.print(System.out, "w = |%20.5f|\n", w);\r
376       Format.print(System.out, "x = |%020.5f|\n", x);\r
377       Format.print(System.out, "x = |%+20.5f|\n", x);\r
378       Format.print(System.out, "x = |%+020.5f|\n", x);\r
379       Format.print(System.out, "x = |% 020.5f|\n", x);\r
380       Format.print(System.out, "y = |%#+20.5f|\n", y);\r
381       Format.print(System.out, "y = |%-+20.5f|\n", y);\r
382       Format.print(System.out, "z = |%20.5f|\n", z);\r
383       \r
384       Format.print(System.out, "x = |%e|\n", x);\r
385       Format.print(System.out, "u = |%20e|\n", u);\r
386       Format.print(System.out, "x = |% .5e|\n", x);\r
387       Format.print(System.out, "w = |%20.5e|\n", w);\r
388       Format.print(System.out, "x = |%020.5e|\n", x);\r
389       Format.print(System.out, "x = |%+20.5e|\n", x);\r
390       Format.print(System.out, "x = |%+020.5e|\n", x);\r
391       Format.print(System.out, "x = |% 020.5e|\n", x);\r
392       Format.print(System.out, "y = |%#+20.5e|\n", y);\r
393       Format.print(System.out, "y = |%-+20.5e|\n", y);\r
394       \r
395       Format.print(System.out, "x = |%g|\n", x);\r
396       Format.print(System.out, "z = |%g|\n", z);\r
397       Format.print(System.out, "w = |%g|\n", w);\r
398       Format.print(System.out, "u = |%g|\n", u);\r
399       Format.print(System.out, "y = |%.2g|\n", y);\r
400       Format.print(System.out, "y = |%#.2g|\n", y);\r
401 \r
402       Format.print(System.out, "d = |%d|\n", d);\r
403       Format.print(System.out, "d = |%20d|\n", d);            \r
404       Format.print(System.out, "d = |%020d|\n", d);    \r
405       Format.print(System.out, "d = |%+20d|\n", d);\r
406       Format.print(System.out, "d = |% 020d|\n", d);\r
407       Format.print(System.out, "d = |%-20d|\n", d);\r
408       Format.print(System.out, "d = |%20.8d|\n", d);\r
409       Format.print(System.out, "d = |%x|\n", d);            \r
410       Format.print(System.out, "d = |%20X|\n", d);    \r
411       Format.print(System.out, "d = |%#20x|\n", d);\r
412       Format.print(System.out, "d = |%020X|\n", d);\r
413       Format.print(System.out, "d = |%20.8x|\n", d);\r
414       Format.print(System.out, "d = |%o|\n", d);            \r
415       Format.print(System.out, "d = |%020o|\n", d);    \r
416       Format.print(System.out, "d = |%#20o|\n", d);\r
417       Format.print(System.out, "d = |%#020o|\n", d);\r
418       Format.print(System.out, "d = |%20.12o|\n", d);\r
419       \r
420       Format.print(System.out, "s = |%-20s|\n", "Hello");      \r
421       Format.print(System.out, "s = |%-20c|\n", '!');      \r
422 \r
423       // regression test to confirm fix of reported bugs\r
424 \r
425       Format.print(System.out, "|%i|\n", Long.MIN_VALUE);\r
426 \r
427       Format.print(System.out, "|%6.2e|\n", 0.0);\r
428       Format.print(System.out, "|%6.2g|\n", 0.0);\r
429 \r
430       Format.print(System.out, "|%6.2f|\n", 9.99);\r
431       Format.print(System.out, "|%6.2f|\n", 9.999);\r
432 \r
433       Format.print(System.out, "|%6.0f|\n", 9.999);\r
434    }\r
435    \r
436    private static String repeat(char c, int n)\r
437    {  if (n <= 0) return "";\r
438       StringBuffer s = new StringBuffer(n);\r
439       for (int i = 0; i < n; i++) s.append(c);\r
440       return s.toString();\r
441    }\r
442 \r
443    private static String convert(long x, int n, int m, String d)\r
444    {  if (x == 0) return "0";\r
445       String r = "";\r
446       while (x != 0)\r
447       {  r = d.charAt((int)(x & m)) + r;\r
448          x = x >>> n;\r
449       }\r
450       return r;\r
451    }\r
452 \r
453    private String pad(String r)\r
454    {  String p = repeat(' ', width - r.length());\r
455       if (left_align) return pre + r + p + post;\r
456       else return pre + p + r + post;\r
457    }\r
458    \r
459    private String sign(int s, String r)\r
460    {  String p = "";\r
461       if (s < 0) p = "-"; \r
462       else if (s > 0)\r
463       {  if (show_plus) p = "+";\r
464          else if (show_space) p = " ";\r
465       }\r
466       else\r
467       {  if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";\r
468          else if (fmt == 'x' && alternate) p = "0x";\r
469          else if (fmt == 'X' && alternate) p = "0X";\r
470       }\r
471       int w = 0;\r
472       if (leading_zeroes) \r
473          w = width;\r
474       else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') \r
475          && precision > 0) w = precision;\r
476       \r
477       return p + repeat('0', w - p.length() - r.length()) + r;\r
478    }\r
479    \r
480    private String fixed_format(double d)\r
481    {  boolean removeTrailing\r
482          = (fmt == 'G' || fmt == 'g') && !alternate;\r
483          // remove trailing zeroes and decimal point\r
484 \r
485       if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d);\r
486       if (precision == 0) \r
487          return (long)(d + 0.5) + (removeTrailing ? "" : ".");\r
488 \r
489       long whole = (long)d;\r
490       double fr = d - whole; // fractional part\r
491       if (fr >= 1 || fr < 0) return exp_format(d);\r
492 \r
493       double factor = 1;\r
494       String leading_zeroes = "";\r
495       for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) \r
496       {  factor *= 10; \r
497          leading_zeroes = leading_zeroes + "0"; \r
498       }\r
499       long l = (long) (factor * fr + 0.5);\r
500       if (l >= factor) { l = 0; whole++; } // CSH 10-25-97\r
501       \r
502       String z = leading_zeroes + l;\r
503       z = "." + z.substring(z.length() - precision, z.length());\r
504 \r
505       if (removeTrailing)\r
506       {  int t = z.length() - 1;\r
507          while (t >= 0 && z.charAt(t) == '0') t--;\r
508          if (t >= 0 && z.charAt(t) == '.') t--;\r
509          z = z.substring(0, t + 1);\r
510       }\r
511 \r
512       return whole + z;\r
513    }\r
514 \r
515    private String exp_format(double d)\r
516    {  String f = "";\r
517       int e = 0;\r
518       double dd = d;\r
519       double factor = 1;\r
520       if (d != 0)\r
521       {  while (dd > 10) { e++; factor /= 10; dd = dd / 10; }\r
522          while (dd < 1) { e--; factor *= 10; dd = dd * 10; }\r
523       }\r
524       if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) \r
525          return fixed_format(d);\r
526       \r
527       d = d * factor;\r
528       f = f + fixed_format(d);\r
529       \r
530       if (fmt == 'e' || fmt == 'g')\r
531          f = f + "e";\r
532       else\r
533          f = f + "E";\r
534 \r
535       String p = "000";      \r
536       if (e >= 0) \r
537       {  f = f + "+";\r
538          p = p + e;\r
539       }\r
540       else\r
541       {  f = f + "-";\r
542          p = p + (-e);\r
543       }\r
544          \r
545       return f + p.substring(p.length() - 3, p.length());\r
546    }\r
547    \r
548    private int width;\r
549    private int precision;\r
550    private String pre;\r
551    private String post;\r
552    private boolean leading_zeroes;\r
553    private boolean show_plus;\r
554    private boolean alternate;\r
555    private boolean show_space;\r
556    private boolean left_align;\r
557    private char fmt; // one of cdeEfgGiosxXos\r
558 }\r
559 \r
560 \r
561 \r
562 \r
563 \r