TextLayoutHelper.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package lib;
  2. import java.util.ArrayList;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5. public class TextLayoutHelper {
  6. /**
  7. * Modifies the given string such that its lenght matches the given length.
  8. * If the string is too small, whitespace is appended on both sides equally.
  9. * Then, if the string is too large, it is cut off on the right.
  10. * @param s the string
  11. * @param lenght the target length
  12. * @return the modified string
  13. */
  14. public static String strToLen( String s, int lenght )
  15. {
  16. while( s.length() < lenght )
  17. {
  18. s = " " + s + " ";
  19. }
  20. if( s.length() > lenght )
  21. return s.substring( 0, lenght );
  22. return s;
  23. }
  24. private static String[] keywords = { "for", "do", "to", "then", "else", "if", "foreach", "while", "or", "and", "call", "function", "false", "true", "undefined", "with" };
  25. private static String[] delimiter = { "\\+", "\\-", "\\[", "\\]", "\\|", " ", "^", "$", "\\=", "\\,", "\\(", "\\;", "\\.", "\\)" };
  26. private static String getDelimiterRegex()
  27. {
  28. String reg = "(";
  29. for( String d : delimiter )
  30. {
  31. reg += d + "|";
  32. }
  33. reg = reg.substring( 0, reg.length() - 1 ) + ")";
  34. return reg;
  35. }
  36. public static String setupPseudoCodeComment( String s )
  37. {
  38. return "<html><font color=#FDD017>"+s+"</font></html>";
  39. }
  40. public static String setupPseudoCode( String s, String[] vars )
  41. {
  42. if( s.startsWith( "--" ) )
  43. return setupPseudoCodeComment( s );
  44. String delimiter = getDelimiterRegex();
  45. String ret = "<html>";
  46. String current = s.replaceAll( "&", "&amp" ).replaceAll( "<", " &lt ").replaceAll( ">", " &gt ");
  47. for( String k : keywords )
  48. {
  49. current = current.replaceAll( delimiter + "(" + k + ")" + delimiter, "$1<font color=orange>$2</font>$3" );
  50. }
  51. for( String v : vars )
  52. {
  53. current = current.replaceAll( delimiter + "(" + v + ")" + delimiter, "$1<font color=#3BB9FF>$2</font>$3" );
  54. }
  55. current = current.replaceAll( "\\'(.*?)\\'", "'<font color=#3cb371>$1</font>'" );
  56. ret += current + "</html>";
  57. return ret;
  58. }
  59. public static String[] getVariables( String s )
  60. {
  61. ArrayList<String> list = new ArrayList<>();
  62. Matcher m = Pattern.compile( "<font color=#3BB9FF>(.*?)</font>" ).matcher( s );
  63. while( m.find())
  64. {
  65. if( !list.contains( s.substring( m.start( 1 ), m.end( 1 ) ) ) )
  66. list.add( s.substring( m.start( 1 ), m.end( 1 ) ) );
  67. }
  68. return list.toArray( new String[ list.size() ] );
  69. }
  70. }