3 * $Date: 2007-04-26 16:57:51 -0500 (Thu, 26 Apr 2007) $
6 * Copyright (C) 2005 The Jmol Development Team
8 * Contact: jmol-developers@lists.sf.net
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
27 import java.lang.reflect.Array;
29 import java.util.Map.Entry;
31 import javajs.J2SIgnoreImport;
32 import javajs.api.JSONEncodable;
35 * a combination of Parsing and Text-related utility classes
41 @J2SIgnoreImport(value = { java.lang.reflect.Array.class })
44 public static int parseInt(String str) {
45 return parseIntNext(str, new int[] {0});
48 public static int parseIntNext(String str, int[] next) {
49 int cch = str.length();
50 if (next[0] < 0 || next[0] >= cch)
51 return Integer.MIN_VALUE;
52 return parseIntChecked(str, cch, next);
55 public static int parseIntChecked(String str, int ichMax, int[] next) {
56 boolean digitSeen = false;
60 return Integer.MIN_VALUE;
62 while (ich < ichMax && isWhiteSpace(str, ich))
64 boolean negative = false;
65 if (ich < ichMax && str.charAt(ich) == 45) { //"-"
69 while (ich < ichMax && (ch = str.charAt(ich)) >= 48 && ch <= 57) {
70 value = value * 10 + (ch - 48);
74 if (!digitSeen)// || !checkTrailingText(str, ich, ichMax))
75 value = Integer.MIN_VALUE;
82 public static boolean isWhiteSpace(String str, int ich) {
84 return (ich >= 0 && ((ch = str.charAt(ich)) == ' ' || ch == '\t' || ch == '\n'));
88 * A float parser that is 30% faster than Float.parseFloat(x) and also accepts
94 * pointer; incremented
96 * @return value or Float.NaN
98 public static float parseFloatChecked(String str, int ichMax, int[] next,
100 boolean digitSeen = false;
102 if (isStrict && str.indexOf('\n') != str.lastIndexOf('\n'))
104 while (ich < ichMax && isWhiteSpace(str, ich))
106 boolean negative = false;
107 if (ich < ichMax && str.charAt(ich) == '-') {
111 // looks crazy, but if we don't do this, Google Closure Compiler will
112 // write code that Safari will misinterpret in a VERY nasty way --
113 // getting totally confused as to long integers and double values
115 // This is Safari figuring out the values of the numbers on the line (x, y, then z):
117 // ATOM 1241 CD1 LEU A 64 -2.206 36.532 31.576 1.00 60.60 C
120 // ATOM 1241 CD1 LEU A 64 -2.206 36.532 31.576 1.00 60.60 C
123 // ATOM 1241 CD1 LEU A 64 -2.206 36.532 31.576 1.00 60.60 C
127 // "e" values are just before and after the "value = -value" statement.
132 while (ich < ichMax && (ch = str.charAt(ich)) >= 48 && ch <= 57) {
133 ival = (ival * 10f) + (ch - 48)*1f;
137 boolean isDecimal = false;
139 int nzero = (ival == 0 ? -1 : 0);
142 while (++ich < ichMax && (ch = str.charAt(ich)) >= 48 && ch <= 57) {
151 if (iscale < decimalScale.length) {
152 ival2 = (ival2 * 10f) + (ch - 48)*1f;
159 // Safari breaks here intermittently converting integers to floats
163 } else if (ival2 > 0) {
164 value = ival2 * decimalScale[iscale - 1];
166 if (nzero - 2 < decimalScale.length) {
167 value *= decimalScale[nzero - 2];
169 value *= Math.pow(10, 1 - nzero);
177 boolean isExponent = false;
178 if (ich < ichMax && (ch == 69 || ch == 101 || ch == 68)) { // E e D
182 ch = str.charAt(ich);
183 if ((ch == '+') && (++ich >= ichMax))
186 int exponent = parseIntChecked(str, ichMax, next);
187 if (exponent == Integer.MIN_VALUE)
189 if (exponent > 0 && exponent <= tensScale.length)
190 value *= tensScale[exponent - 1];
191 else if (exponent < 0 && -exponent <= decimalScale.length)
192 value *= decimalScale[-exponent - 1];
193 else if (exponent != 0)
194 value *= Math.pow(10, exponent);
196 next[0] = ich; // the exponent code finds its own ichNextParse
198 // believe it or not, Safari reports the long-equivalent of the
199 // float value here, then later the float value, after no operation!
202 if (value == Float.POSITIVE_INFINITY)
203 value = Float.MAX_VALUE;
204 return (!isStrict || (!isExponent || isDecimal)
205 && checkTrailingText(str, next[0], ichMax) ? value : Float.NaN);
208 public final static float[] tensScale = { 10f, 100f, 1000f, 10000f, 100000f, 1000000f };
209 public final static float[] decimalScale = {
220 public static boolean checkTrailingText(String str, int ich, int ichMax) {
221 //number must be pure -- no additional characters other than white space or ;
223 while (ich < ichMax && (isWhitespace(ch = str.charAt(ich)) || ch == ';'))
225 return (ich == ichMax);
228 public static float[] parseFloatArray(String str) {
229 return parseFloatArrayNext(str, new int[1], null, null, null);
232 public static int parseFloatArrayInfested(String[] tokens, float[] data) {
233 int len = data.length;
234 int nTokens = tokens.length;
237 for (int i = 0; i >= 0 && i < len && n < nTokens; i++) {
239 while (Float.isNaN(f = parseFloat(tokens[n++]))
254 * @param strStart or null
255 * @param strEnd or null
256 * @return array of float values
259 public static float[] parseFloatArrayNext(String str, int[] next, float[] f,
260 String strStart, String strEnd) {
264 if (strStart != null) {
265 int p = str.indexOf(strStart, pt);
267 next[0] = p + strStart.length();
269 str = str.substring(next[0]);
270 pt = (strEnd == null ? -1 : str.indexOf(strEnd));
274 str = str.substring(0, pt);
276 String[] tokens = getTokens(str);
278 f = new float[tokens.length];
279 n = parseFloatArrayInfested(tokens, f);
283 for (int i = n; i < f.length; i++)
288 public static float parseFloatRange(String str, int ichMax, int[] next) {
289 int cch = str.length();
292 if (next[0] < 0 || next[0] >= ichMax)
294 return parseFloatChecked(str, ichMax, next, false);
297 public static float parseFloatNext(String str, int[] next) {
298 int cch = (str == null ? -1 : str.length());
299 return (next[0] < 0 || next[0] >= cch ? Float.NaN : parseFloatChecked(str, cch, next, false));
302 public static float parseFloatStrict(String str) {
303 // checks trailing characters and does not allow "1E35" to be float
304 int cch = str.length();
307 return parseFloatChecked(str, cch, new int[] {0}, true);
310 public static float parseFloat(String str) {
311 return parseFloatNext(str, new int[] {0});
314 public static int parseIntRadix(String s, int i) throws NumberFormatException {
317 * JavaScript uses parseIntRadix
321 * return Integer.parseIntRadix(s, i);
325 return Integer.parseInt(s, i);
329 public static String[] getTokens(String line) {
330 return getTokensAt(line, 0);
333 public static String parseToken(String str) {
334 return parseTokenNext(str, new int[] {0});
337 public static String parseTrimmed(String str) {
338 return parseTrimmedRange(str, 0, str.length());
341 public static String parseTrimmedAt(String str, int ichStart) {
342 return parseTrimmedRange(str, ichStart, str.length());
345 public static String parseTrimmedRange(String str, int ichStart, int ichMax) {
346 int cch = str.length();
351 return parseTrimmedChecked(str, ichStart, cch);
354 public static String[] getTokensAt(String line, int ich) {
357 int cchLine = line.length();
358 if (ich < 0 || ich > cchLine)
360 int tokenCount = countTokens(line, ich);
361 String[] tokens = new String[tokenCount];
362 int[] next = new int[1];
364 for (int i = 0; i < tokenCount; ++i)
365 tokens[i] = parseTokenChecked(line, cchLine, next);
369 public static int countChar(String line, char c) {
372 while ((pt = line.indexOf(c, pt + 1)) >= 0)
377 public static int countTokens(String line, int ich) {
380 int ichMax = line.length();
382 while (ich < ichMax && isWhiteSpace(line, ich))
389 } while (ich < ichMax && !isWhiteSpace(line, ich));
395 public static String parseTokenNext(String str, int[] next) {
396 int cch = str.length();
397 return (next[0] < 0 || next[0] >= cch ? null : parseTokenChecked(str, cch, next));
400 public static String parseTokenRange(String str, int ichMax, int[] next) {
401 int cch = str.length();
404 return (next[0] < 0 || next[0] >= ichMax ? null : parseTokenChecked(str, ichMax, next));
407 public static String parseTokenChecked(String str, int ichMax, int[] next) {
409 while (ich < ichMax && isWhiteSpace(str, ich))
411 int ichNonWhite = ich;
412 while (ich < ichMax && !isWhiteSpace(str, ich))
415 return (ichNonWhite == ich ? null : str.substring(ichNonWhite, ich));
418 public static String parseTrimmedChecked(String str, int ich, int ichMax) {
419 while (ich < ichMax && isWhiteSpace(str, ich))
421 int ichLast = ichMax - 1;
422 while (ichLast >= ich && isWhiteSpace(str, ichLast))
424 return (ichLast < ich ? "" : str.substring(ich, ichLast + 1));
427 public static double dVal(String s) throws NumberFormatException {
432 * throw new NumberFormatException("null");
433 * var d=parseFloat(s);
435 * throw new NumberFormatException("Not a Number : "+s);
440 return Double.valueOf(s).doubleValue();
444 public static float fVal(String s) throws NumberFormatException {
448 * return this.dVal(s);
451 return Float.parseFloat(s);
455 public static int parseIntRange(String str, int ichMax, int[] next) {
456 int cch = str.length();
459 return (next[0] < 0 || next[0] >= ichMax ? Integer.MIN_VALUE : parseIntChecked(str, ichMax, next));
463 * parses a string array for floats. Returns NaN for nonfloats.
465 * @param tokens the strings to parse
466 * @param data the array to fill
468 public static void parseFloatArrayData(String[] tokens, float[] data) {
469 parseFloatArrayDataN(tokens, data, data.length);
473 * parses a string array for floats. Returns NaN for nonfloats or missing data.
475 * @param tokens the strings to parse
476 * @param data the array to fill
477 * @param nData the number of elements
479 public static void parseFloatArrayDataN(String[] tokens, float[] data, int nData) {
480 for (int i = nData; --i >= 0;)
481 data[i] = (i >= tokens.length ? Float.NaN : parseFloat(tokens[i]));
486 * proper splitting, even for Java 1.3 -- if the text ends in the run,
487 * no new line is appended.
491 * @return String array
493 public static String[] split(String text, String run) {
494 if (text.length() == 0)
495 return new String[0];
497 int i = text.indexOf(run);
499 int runLen = run.length();
500 if (i < 0 || runLen == 0) {
501 lines = new String[1];
505 int len = text.length() - runLen;
506 for (; i >= 0 && i < len; n++)
507 i = text.indexOf(run, i + runLen);
508 lines = new String[n];
512 for (; (ipt = text.indexOf(run, i)) >= 0 && pt + 1 < n;) {
513 lines[pt++] = text.substring(i, ipt);
516 if (text.indexOf(run, len) != len)
518 lines[pt] = text.substring(i, len);
522 public final static float FLOAT_MIN_SAFE = 2E-45f;
523 // Float.MIN_VALUE (1.45E-45) is not reliable with JavaScript because of the float/double difference there
525 /// general static string-parsing class ///
527 // next[0] tracks the pointer within the string so these can all be static.
528 // but the methods parseFloat, parseInt, parseToken, parseTrimmed, and getTokens do not require this.
530 // public static String concatTokens(String[] tokens, int iFirst, int iEnd) {
533 // for (int i = iFirst; i < iEnd; i++) {
534 // if (i < tokens.length) {
535 // str += sep + tokens[i];
542 public static String getQuotedStringAt(String line, int ipt0) {
543 int[] next = new int[] { ipt0 };
544 return getQuotedStringNext(line, next);
550 * @param next passes [current pointer]
551 * @return quoted string -- does NOT unescape characters
553 public static String getQuotedStringNext(String line, int[] next) {
555 if (i < 0 || (i = line.indexOf("\"", i)) < 0)
558 int len = line.length();
559 while (++i < len && line.charAt(i) != '"')
560 if (line.charAt(i) == '\\')
563 return line.substring(pt, i);
567 * CSV format -- escaped quote is "" WITHIN "..."
571 * @param next int[2] filled with [ptrQuote1, ptrAfterQuote2]
572 * next[1] will be -1 if unmatched quotes are found (continuation on next line)
573 * @return unescaped string or null
575 public static String getCSVString(String line, int[] next) {
577 if (i < 0 || (i = line.indexOf("\"", i)) < 0)
579 int pt = next[0] = i;
580 int len = line.length();
581 boolean escaped = false;
582 boolean haveEscape = false;
584 && (line.charAt(i) != '"' || (escaped = (i + 1 < len && line.charAt(i + 1) == '"'))))
592 return null; // unmatched
595 String s = line.substring(pt + 1, i);
596 return (haveEscape ? rep(rep(s, "\"\"", "\0"), "\0","\"") : s);
599 public static boolean isOneOf(String key, String semiList) {
600 if (semiList.length() == 0)
602 if (semiList.charAt(0) != ';')
603 semiList = ";" + semiList + ";";
604 return key.indexOf(";") < 0 && semiList.indexOf(';' + key + ';') >= 0;
607 public static String getQuotedAttribute(String info, String name) {
608 int i = info.indexOf(name + "=");
609 return (i < 0 ? null : getQuotedStringAt(info, i));
612 public static float approx(float f, float n) {
613 return Math.round (f * n) / n;
617 * Does a clean ITERATIVE replace of strFrom in str with strTo.
618 * Thus, rep("Testttt", "tt","t") becomes "Test".
623 * @return replaced string
625 public static String rep(String str, String strFrom, String strTo) {
626 if (str == null || strFrom.length() == 0 || str.indexOf(strFrom) < 0)
628 boolean isOnce = (strTo.indexOf(strFrom) >= 0);
630 str = str.replace(strFrom, strTo);
631 } while (!isOnce && str.indexOf(strFrom) >= 0);
635 public static String formatF(float value, int width, int precision,
636 boolean alignLeft, boolean zeroPad) {
637 return formatS(DF.formatDecimal(value, precision), width, 0, alignLeft, zeroPad);
647 * @param allowOverflow IGNORED
648 * @return formatted string
650 public static String formatD(double value, int width, int precision,
651 boolean alignLeft, boolean zeroPad, boolean allowOverflow) {
652 return formatS(DF.formatDecimal((float)value, -1 - precision), width, 0, alignLeft, zeroPad);
658 * @param width number of columns
659 * @param precision precision > 0 ==> precision = number of characters max from left
660 * precision < 0 ==> -1 - precision = number of char. max from right
662 * @param zeroPad generally for numbers turned strings
663 * @return formatted string
665 public static String formatS(String value, int width, int precision,
666 boolean alignLeft, boolean zeroPad) {
669 int len = value.length();
670 if (precision != Integer.MAX_VALUE && precision > 0
672 value = value.substring(0, precision);
673 else if (precision < 0 && len + precision >= 0)
674 value = value.substring(len + precision + 1);
676 int padLength = width - value.length();
679 boolean isNeg = (zeroPad && !alignLeft && value.charAt(0) == '-');
680 char padChar = (zeroPad ? '0' : ' ');
681 char padChar0 = (isNeg ? '-' : padChar);
686 sb.appendC(padChar0);
687 for (int i = padLength; --i > 0;)
688 // this is correct, not >= 0
691 sb.append(isNeg ? padChar + value.substring(1) : value);
692 return sb.toString();
696 * Does a clean replace of any of the characters in str with chrTo
697 * If strTo contains strFrom, then only a single pass is done.
698 * Otherwise, multiple passes are made until no more replacements can be made.
703 * @return replaced string
705 public static String replaceWithCharacter(String str, String strFrom,
709 for (int i = strFrom.length(); --i >= 0;)
710 str = str.replace(strFrom.charAt(i), chTo);
715 * Does a clean replace of any of the characters in str with strTo
716 * If strTo contains strFrom, then only a single pass is done.
717 * Otherwise, multiple passes are made until no more replacements can be made.
722 * @return replaced string
724 public static String replaceAllCharacters(String str, String strFrom,
726 for (int i = strFrom.length(); --i >= 0;) {
727 String chFrom = strFrom.substring(i, i + 1);
728 str = rep(str, chFrom, strTo);
733 public static String trim(String str, String chars) {
734 if (str == null || str.length() == 0)
736 if (chars.length() == 0)
738 int len = str.length();
740 while (k < len && chars.indexOf(str.charAt(k)) >= 0)
742 int m = str.length() - 1;
743 while (m > k && chars.indexOf(str.charAt(m)) >= 0)
745 return str.substring(k, m + 1);
748 public static String trimQuotes(String value) {
749 return (value != null && value.length() > 1 && value.startsWith("\"")
750 && value.endsWith("\"") ? value.substring(1, value.length() - 1)
754 public static boolean isNonStringPrimitive(Object info) {
755 // note that we don't use Double, Float, or Integer here
756 // because in JavaScript those would be false for unwrapped primitives
757 // coming from equivalent of Array.get()
758 // Strings will need their own escaped processing
760 return info instanceof Number || info instanceof Boolean;
763 private static Object arrayGet(Object info, int i) {
766 * Note that info will be a primitive in JavaScript
767 * but a wrapped primitive in Java.
774 return Array.get(info, i);
778 @SuppressWarnings("unchecked")
779 public static String toJSON(String infoType, Object info) {
781 return packageJSON(infoType, null);
782 if (isNonStringPrimitive(info))
783 return packageJSON(infoType, info.toString());
787 if (info instanceof String) {
792 * if (typeof s == "undefined") s = "null"
796 if (s.indexOf("{\"") != 0) {
797 //don't doubly fix JSON strings when retrieving status
798 s = rep(s, "\"", "\\\"");
799 s = rep(s, "\n", "\\n");
804 if (info instanceof JSONEncodable) {
805 // includes javajs.util.BS, org.jmol.script.SV
806 if ((s = ((JSONEncodable) info).toJSON()) == null)
807 s = "null"; // perhaps a list has a null value (group3List, for example)
811 if (info instanceof Map) {
814 for (String key : ((Map<String, ?>) info).keySet()) {
815 sb.append(sep).append(
816 packageJSON(key, toJSON(null, ((Map<?, ?>) info).get(key))));
822 if (info instanceof Lst) {
824 int n = ((Lst<?>) info).size();
825 for (int i = 0; i < n; i++) {
828 sb.append(toJSON(null, ((Lst<?>) info).get(i)));
833 if (info instanceof M34) {
835 int len = (info instanceof M4 ? 4 : 3);
836 float[] x = new float[len];
839 for (int i = 0; i < len; i++) {
843 sb.append(toJSON(null, x));
848 s = nonArrayString(info);
851 int n = AU.getLength(info);
852 for (int i = 0; i < n; i++) {
855 sb.append(toJSON(null, arrayGet(info, i)));
860 info = info.toString();
862 return packageJSON(infoType, (s == null ? sb.toString() : s));
866 * Checks to see if an object is an array, and if it is, returns null;
867 * otherwise it returns the string equivalent of that object.
870 * @return String or null
872 public static String nonArrayString(Object x) {
876 * var s = x.toString(); return (s.startsWith("[object") &&
877 * s.endsWith("Array]") ? null : s);
884 } catch (Exception e) {
890 public static String byteArrayToJSON(byte[] data) {
894 for (int i = 0; i < n; i++) {
897 sb.appendI(data[i] & 0xFF);
900 return sb.toString();
903 public static String packageJSON(String infoType, String info) {
904 return (infoType == null ? info : "\"" + infoType + "\": " + info);
907 public static String escapeUrl(String url) {
908 url = rep(url, "\n", "");
909 url = rep(url, "%", "%25");
910 url = rep(url, "#", "%23");
911 url = rep(url, "[", "%5B");
912 url = rep(url, "]", "%5D");
913 url = rep(url, " ", "%20");
917 private final static String escapable = "\\\\\tt\rr\nn\"\"";
919 public static String esc(String str) {
920 if (str == null || str.length() == 0)
922 boolean haveEscape = false;
924 for (; i < escapable.length(); i += 2)
925 if (str.indexOf(escapable.charAt(i)) >= 0) {
930 while (i < escapable.length()) {
932 char ch = escapable.charAt(i++);
933 char ch2 = escapable.charAt(i++);
936 while ((pt = str.indexOf(ch, pt + 1)) >= 0) {
937 sb.append(str.substring(pt0, pt)).appendC('\\').appendC(ch2);
940 sb.append(str.substring(pt0, str.length()));
943 return "\"" + escUnicode(str) + "\"";
946 public static String escUnicode(String str) {
947 for (int i = str.length(); --i >= 0;)
948 if (str.charAt(i) > 0x7F) {
949 String s = "0000" + Integer.toHexString(str.charAt(i));
950 str = str.substring(0, i) + "\\u" + s.substring(s.length() - 4)
951 + str.substring(i + 1);
957 * ensures that a float turned to string has a decimal point
960 * @return string version of float
962 public static String escF(float f) {
967 * if (sf.indexOf(".") < 0 && sf.indexOf("e") < 0)
974 public static String join(String[] s, char c, int i0) {
979 for (int i = i0; i < s.length; i++)
980 sb.appendC(c).append(s[i]);
981 return sb.toString();
985 * a LIKE "x" a is a string and equals x
987 * a LIKE "*x" a is a string and ends with x
989 * a LIKE "x*" a is a string and starts with x
991 * a LIKE "*x*" a is a string and contains x
997 public static boolean isLike(String a, String b) {
998 boolean areEqual = a.equals(b);
1001 boolean isStart = b.startsWith("*");
1002 boolean isEnd = b.endsWith("*");
1003 return (!isStart && !isEnd) ? areEqual
1004 : isStart && isEnd ? b.length() == 1 || a.contains(b.substring(1, b.length() - 1))
1005 : isStart ? a.endsWith(b.substring(1))
1006 : a.startsWith(b.substring(0, b.length() - 1));
1009 public static Object getMapValueNoCase(Map<String, ?> h, String key) {
1010 if ("this".equals(key))
1012 Object val = h.get(key);
1014 for (Entry<String, ?> e : h.entrySet())
1015 if (e.getKey().equalsIgnoreCase(key))
1016 return e.getValue();
1020 public static String clean(String s) {
1021 return rep(replaceAllCharacters(s, " \t\n\r", " "), " ", " ").trim();
1026 * fdup duplicates p or q formats for formatCheck
1027 * and the format() function.
1032 * @return %3.5q%3.5q%3.5q%3.5q or %3.5p%3.5p%3.5p
1034 public static String fdup(String f, int pt, int n) {
1037 for (int i = pt; --i >= 1; ) {
1038 if (isDigit(ch = f.charAt(i)))
1046 if (i != 1 && f.charAt(i - 1) != '.')
1053 String s = f.substring(0, pt + 1);
1055 for (int i = 0; i < n; i++)
1057 sb.append(f.substring(pt + 1));
1058 return sb.toString();
1062 * generic string formatter based on formatLabel in Atom
1065 * @param strFormat .... %width.precisionKEY....
1066 * @param key any string to match
1067 * @param strT replacement string or null
1068 * @param floatT replacement float or Float.NaN
1069 * @param doubleT replacement double or Double.NaN -- for exponential
1070 * @param doOne mimic sprintf
1071 * @return formatted string
1074 public static String formatString(String strFormat, String key, String strT,
1075 float floatT, double doubleT, boolean doOne) {
1076 if (strFormat == null)
1078 if ("".equals(strFormat))
1080 int len = key.length();
1081 if (strFormat.indexOf("%") < 0 || len == 0 || strFormat.indexOf(key) < 0)
1084 String strLabel = "";
1085 int ich, ichPercent, ichKey;
1086 for (ich = 0; (ichPercent = strFormat.indexOf('%', ich)) >= 0
1087 && (ichKey = strFormat.indexOf(key, ichPercent + 1)) >= 0;) {
1088 if (ich != ichPercent)
1089 strLabel += strFormat.substring(ich, ichPercent);
1090 ich = ichPercent + 1;
1091 if (ichKey > ichPercent + 6) {
1096 boolean alignLeft = false;
1097 if (strFormat.charAt(ich) == '-') {
1101 boolean zeroPad = false;
1102 if (strFormat.charAt(ich) == '0') {
1108 while ((ch = strFormat.charAt(ich)) >= '0' && (ch <= '9')) {
1109 width = (10 * width) + (ch - '0');
1112 int precision = Integer.MAX_VALUE;
1113 boolean isExponential = false;
1114 if (strFormat.charAt(ich) == '.') {
1116 if ((ch = strFormat.charAt(ich)) == '-') {
1117 isExponential = true;
1120 if ((ch = strFormat.charAt(ich)) >= '0' && ch <= '9') {
1121 precision = ch - '0';
1125 precision = -precision - (strT == null ? 1 : 0);
1127 String st = strFormat.substring(ich, ich + len);
1128 if (!st.equals(key)) {
1129 ich = ichPercent + 1;
1134 if (!Float.isNaN(floatT))
1135 strLabel += formatF(floatT, width, precision, alignLeft,
1137 else if (strT != null)
1138 strLabel += formatS(strT, width, precision, alignLeft,
1140 else if (!Double.isNaN(doubleT))
1141 strLabel += formatD(doubleT, width, precision, alignLeft,
1145 } catch (IndexOutOfBoundsException ioobe) {
1150 strLabel += strFormat.substring(ich);
1151 //if (strLabel.length() == 0)
1156 public static String formatStringS(String strFormat, String key, String strT) {
1157 return formatString(strFormat, key, strT, Float.NaN, Double.NaN, false);
1160 public static String formatStringF(String strFormat, String key, float floatT) {
1161 return formatString(strFormat, key, null, floatT, Double.NaN, false);
1164 public static String formatStringI(String strFormat, String key, int intT) {
1165 return formatString(strFormat, key, "" + intT, Float.NaN, Double.NaN, false);
1169 * sprintf emulation uses (almost) c++ standard string formats
1171 * 's' string 'i' or 'd' integer, 'e' double, 'f' float, 'p' point3f 'q'
1172 * quaternion/plane/axisangle with added "i" (equal to the insipid "d" --
1177 * a listing of what sort of data will be found in Object[] values, in
1178 * order: s string, f float, i integer, d double, p point3f, q
1179 * quaternion/point4f, S String[], F float[], I int[], and D double[]
1181 * Object[] containing above types
1182 * @return formatted string
1184 public static String sprintf(String strFormat, String list, Object[] values) {
1187 int n = list.length();
1188 if (n == values.length)
1190 for (int o = 0; o < n; o++) {
1191 if (values[o] == null)
1193 switch (list.charAt(o)) {
1195 strFormat = formatString(strFormat, "s", (String) values[o],
1196 Float.NaN, Double.NaN, true);
1199 strFormat = formatString(strFormat, "f", null, ((Float) values[o])
1200 .floatValue(), Double.NaN, true);
1203 strFormat = formatString(strFormat, "d", "" + values[o], Float.NaN,
1205 strFormat = formatString(strFormat, "i", "" + values[o], Float.NaN,
1209 strFormat = formatString(strFormat, "e", null, Float.NaN,
1210 ((Double) values[o]).doubleValue(), true);
1213 T3 pVal = (T3) values[o];
1214 strFormat = formatString(strFormat, "p", null, pVal.x, Double.NaN,
1216 strFormat = formatString(strFormat, "p", null, pVal.y, Double.NaN,
1218 strFormat = formatString(strFormat, "p", null, pVal.z, Double.NaN,
1222 T4 qVal = (T4) values[o];
1223 strFormat = formatString(strFormat, "q", null, qVal.x, Double.NaN,
1225 strFormat = formatString(strFormat, "q", null, qVal.y, Double.NaN,
1227 strFormat = formatString(strFormat, "q", null, qVal.z, Double.NaN,
1229 strFormat = formatString(strFormat, "q", null, qVal.w, Double.NaN,
1233 String[] sVal = (String[]) values[o];
1234 for (int i = 0; i < sVal.length; i++)
1235 strFormat = formatString(strFormat, "s", sVal[i], Float.NaN,
1239 float[] fVal = (float[]) values[o];
1240 for (int i = 0; i < fVal.length; i++)
1241 strFormat = formatString(strFormat, "f", null, fVal[i],
1245 int[] iVal = (int[]) values[o];
1246 for (int i = 0; i < iVal.length; i++)
1247 strFormat = formatString(strFormat, "d", "" + iVal[i], Float.NaN,
1249 for (int i = 0; i < iVal.length; i++)
1250 strFormat = formatString(strFormat, "i", "" + iVal[i], Float.NaN,
1254 double[] dVal = (double[]) values[o];
1255 for (int i = 0; i < dVal.length; i++)
1256 strFormat = formatString(strFormat, "e", null, Float.NaN,
1261 return rep(strFormat, "%%", "%");
1262 } catch (Exception e) {
1265 System.out.println("TextFormat.sprintf error " + list + " " + strFormat);
1266 return rep(strFormat, "%", "?");
1271 * formatCheck checks p and q formats and duplicates if necessary
1272 * "%10.5p xxxx" ==> "%10.5p%10.5p%10.5p xxxx"
1275 * @return f or dupicated format
1277 public static String formatCheck(String strFormat) {
1278 if (strFormat == null || strFormat.indexOf('p') < 0 && strFormat.indexOf('q') < 0)
1280 strFormat = rep(strFormat, "%%", "\1");
1281 strFormat = rep(strFormat, "%p", "%6.2p");
1282 strFormat = rep(strFormat, "%q", "%6.2q");
1283 String[] format = split(strFormat, "%");
1285 sb.append(format[0]);
1286 for (int i = 1; i < format.length; i++) {
1287 String f = "%" + format[i];
1289 if (f.length() >= 3) {
1290 if ((pt = f.indexOf('p')) >= 0)
1292 if ((pt = f.indexOf('q')) >= 0)
1297 return sb.toString().replace('\1', '%');
1300 public static void leftJustify(SB s, String s1, String s2) {
1302 int n = s1.length() - s2.length();
1304 s.append(s1.substring(0, n));
1307 public static void rightJustify(SB s, String s1, String s2) {
1308 int n = s1.length() - s2.length();
1310 s.append(s1.substring(0, n));
1314 public static String safeTruncate(float f, int n) {
1315 if (f > -0.001 && f < 0.001)
1317 return (f + " ").substring(0,n);
1320 public static boolean isWild(String s) {
1321 return s != null && (s.indexOf("*") >= 0 || s.indexOf("?") >= 0);
1325 * A general non-regex (for performance) text matcher that utilizes ? and *.
1327 * ??? means "at most three" characters if at beginning or end;
1328 * "exactly three" otherwise
1329 * \1 in search is a stand-in for actual ?
1332 * the string to search
1336 * @param allowInitialStar
1337 * @return true if found
1339 public static boolean isMatch(String search, String match, boolean checkStar,
1340 boolean allowInitialStar) {
1341 // search == match --> true
1342 if (search.equals(match))
1344 int mLen = match.length();
1345 // match == "" --> false
1348 boolean isStar0 = (checkStar && allowInitialStar ? match.charAt(0) == '*'
1350 // match == "*" --> true
1351 if (mLen == 1 && isStar0)
1353 boolean isStar1 = (checkStar && match.endsWith("*"));
1354 boolean haveQ = (match.indexOf('?') >= 0);
1355 // match == "**" --> true
1356 // match == "*xxx*" --> search contains "xxx"
1357 // match == "*xxx" --> search ends with "xxx"
1358 // match == "xxx*" --> search starts with "xxx"
1361 return (isStar1 ? (mLen < 3 || search.indexOf(match.substring(1,
1362 mLen - 1)) >= 0) : search.endsWith(match.substring(1)));
1364 return search.startsWith(match.substring(0, mLen - 1));
1366 int sLen = search.length();
1367 // pad match with "?" -- same as *
1368 String qqqq = "????";
1376 match = qqqq + match.substring(1);
1380 match = match.substring(0, mLen - 1) + qqqq;
1384 // length of match < length of search --> false
1388 // -- each ? matches ONE character if not at end
1389 // -- extra ? at end ignored
1391 // (allowInitialStar == true)
1392 // -- extra ? at beginning reduced to match length
1395 while (mLen > sLen) {
1396 if (allowInitialStar && match.charAt(ich) == '?') {
1398 } else if (match.charAt(ich + mLen - 1) != '?') {
1404 // both are effectively same length now.
1405 // \1 is stand-in for "?"
1407 for (int i = sLen; --i >= 0;) {
1408 char chm = match.charAt(ich + i);
1411 char chs = search.charAt(i);
1412 if (chm != chs && (chm != '\1' || chs != '?'))
1418 public static String replaceQuotedStrings(String s, Lst<String> list,
1419 Lst<String> newList) {
1420 int n = list.size();
1421 for (int i = 0; i < n; i++) {
1422 String name = list.get(i);
1423 String newName = newList.get(i);
1424 if (!newName.equals(name))
1425 s = rep(s, "\"" + name + "\"", "\"" + newName
1431 public static String replaceStrings(String s, Lst<String> list,
1432 Lst<String> newList) {
1433 int n = list.size();
1434 for (int i = 0; i < n; i++) {
1435 String name = list.get(i);
1436 String newName = newList.get(i);
1437 if (!newName.equals(name))
1438 s = rep(s, name, newName);
1443 public static boolean isDigit(char ch) {
1444 // just way simpler code than Character.isDigit(ch);
1446 return (48 <= c && c <= 57);
1449 public static boolean isUpperCase(char ch) {
1451 return (65 <= c && c <= 90);
1454 public static boolean isLowerCase(char ch) {
1456 return (97 <= c && c <= 122);
1459 public static boolean isLetter(char ch) {
1460 // just way simpler code than Character.isLetter(ch);
1462 return (65 <= c && c <= 90 || 97 <= c && c <= 122);
1465 public static boolean isLetterOrDigit(char ch) {
1466 // just way simpler code than Character.isLetterOrDigit(ch);
1468 return (65 <= c && c <= 90 || 97 <= c && c <= 122 || 48 <= c && c <= 57);
1471 public static boolean isWhitespace(char ch) {
1473 return (c >= 0x1c && c <= 0x20 || c >= 0x9 && c <= 0xd);
1476 public static final float FRACTIONAL_PRECISION = 100000f;
1477 public static final float CARTESIAN_PRECISION = 10000f;
1479 public static void fixPtFloats(T3 pt, float f) {
1480 //this will equate float and double as long as -256 <= x <= 256
1481 pt.x = Math.round(pt.x * f) / f;
1482 pt.y = Math.round(pt.y * f) / f;
1483 pt.z = Math.round(pt.z * f) / f;
1486 public static double fixDouble(double d, double f) {
1487 return Math.round(d * f) / f;
1491 * parse a float or "float/float"
1495 public static float parseFloatFraction(String s) {
1496 int pt = s.indexOf("/");
1497 return (pt < 0 ? parseFloat(s) : parseFloat(s.substring(0, pt))
1498 / parseFloat(s.substring(pt + 1)));
1503 // double d = 790.8999998888;
1504 // float x = 790.8999998888f;
1505 // for (int i = 0; i < 50; i++) {
1506 // System.out.println(x + " " + d);
1507 // System.out.println(Math.round(x * 100000) / 100000f);
1508 // System.out.println(Math.round(d * 100000) / 100000.);
1509 // System.out.println(Math.round(x * 10000) / 10000f);
1510 // System.out.println(Math.round(d * 10000) / 10000.);
1514 // System.out.println(100.123456789f);
1520 // t = System.currentTimeMillis();
1521 // for (int i = 0; i < 10000000; i++) {
1522 // boolean b = PT.isUpperCase(c);
1524 // System.out.println(System.currentTimeMillis() - t);
1526 // t = System.currentTimeMillis();
1527 // for (int i = 0; i < 10000000; i++) {
1528 // boolean b = Character.isUpperCase(c);
1530 // System.out.println(System.currentTimeMillis() - t);
1532 // t = System.currentTimeMillis();
1533 // for (int i = 0; i < 10000000; i++) {
1534 // boolean b = PT.isUpperCase(c);
1536 // System.out.println(System.currentTimeMillis() - t);
1538 // System.out.println("PT test");