TextLayoutHelper.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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" };
  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 setupPseudoCodeStage( String s )
  37. {
  38. return "<html><font color=#FDD017>"+s+"</font></html>";
  39. }
  40. public static String setupPseudoCode( String s, String[] vars )
  41. {
  42. System.out.print( s + " -> " );
  43. String delimiter = getDelimiterRegex();
  44. String ret = "<html>";
  45. String current = s.replaceAll( "&", "&amp" ).replaceAll( "<", "&lt").replaceAll( ">", "&gt");
  46. for( String k : keywords )
  47. {
  48. current = current.replaceAll( delimiter + "(" + k + ")" + delimiter, "$1<font color=orange>$2</font>$3" );
  49. }
  50. for( String v : vars )
  51. {
  52. current = current.replaceAll( delimiter + "(" + v + ")" + delimiter, "$1<font color=#3BB9FF>$2</font>$3" );
  53. }
  54. ret += current + "</html>";
  55. System.out.println( ret );
  56. return ret;
  57. }
  58. public static String[] getVariables( String s )
  59. {
  60. ArrayList<String> list = new ArrayList<>();
  61. Matcher m = Pattern.compile( "<font color=#3BB9FF>(.*?)</font>" ).matcher( s );
  62. while( m.find())
  63. {
  64. list.add( s.substring( m.start( 1 ), m.end( 1 ) ) );
  65. }
  66. return list.toArray( new String[ list.size() ] );
  67. }
  68. }