You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EventFormatter.java 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.ui.messages;
  23. import com.dmdirc.events.DisplayProperty;
  24. import com.dmdirc.events.DisplayPropertyMap;
  25. import com.dmdirc.events.DisplayableEvent;
  26. import com.dmdirc.interfaces.Displayable;
  27. import com.dmdirc.util.colours.ColourUtils;
  28. import java.util.Optional;
  29. import javax.inject.Inject;
  30. import javax.inject.Singleton;
  31. /**
  32. * Formats an event into a text string, based on a user-defined template.
  33. *
  34. * <p>Template tags start with <code>{{</code> and end with <code>}}</code>. The start of the
  35. * tag should be the property of the event that will be displayed. Properties can be chained using
  36. * a <code>.</code> character, e.g. <code>{{user.hostname}}</code>. One or more functions can
  37. * be applied to the result of this, to change the appearance of the output. Functions are
  38. * separated from their argument with a <code>|</code> character,
  39. * e.g. <code>{{user.hostname|uppercase}}</code>.
  40. *
  41. * <p>Properties and functions are case-insensitive.
  42. */
  43. @Singleton
  44. public class EventFormatter {
  45. private static final String ERROR_STRING = "<FormatError>";
  46. private final EventPropertyManager propertyManager;
  47. private final EventFormatProvider formatProvider;
  48. @Inject
  49. public EventFormatter(final EventPropertyManager propertyManager,
  50. final EventFormatProvider formatProvider) {
  51. this.propertyManager = propertyManager;
  52. this.formatProvider = formatProvider;
  53. }
  54. public Optional<String> format(final DisplayableEvent event) {
  55. final Optional<EventFormat> format = formatProvider.getFormat(event.getClass());
  56. format.map(EventFormat::getDisplayProperties)
  57. .ifPresent(event.getDisplayProperties()::putAll);
  58. return format.map(f -> format(f, event));
  59. }
  60. private String format(final EventFormat format, final DisplayableEvent event) {
  61. final StringBuilder builder = new StringBuilder();
  62. format.getBeforeTemplate().ifPresent(
  63. before -> builder.append(doSubstitutions(event, before)).append('\n'));
  64. builder.append(
  65. format.getIterateProperty()
  66. .map(iterate -> formatIterable(event, iterate, format.getTemplate()))
  67. .orElseGet(() -> doSubstitutions(event, format.getTemplate())));
  68. format.getAfterTemplate().ifPresent(
  69. after -> builder.append('\n').append(doSubstitutions(event, after)));
  70. return builder.toString();
  71. }
  72. private String doSubstitutions(final Object dataSource, final String line) {
  73. final StringBuilder builder = new StringBuilder(line);
  74. int tagStart = builder.indexOf("{{");
  75. while (tagStart > -1) {
  76. final int tagEnd = builder.indexOf("}}", tagStart);
  77. final String tag = builder.substring(tagStart + 2, tagEnd);
  78. final String replacement = getReplacement(dataSource, tag);
  79. builder.replace(tagStart, tagEnd + 2, replacement);
  80. tagStart = builder.indexOf("{{", tagStart + replacement.length());
  81. }
  82. return builder.toString();
  83. }
  84. private String formatIterable(final DisplayableEvent event, final String property,
  85. final String template) {
  86. final Optional<Object> value
  87. = propertyManager.getProperty(event, event.getClass(), property);
  88. if (!value.isPresent() || !(value.get() instanceof Iterable<?>)) {
  89. return ERROR_STRING;
  90. }
  91. @SuppressWarnings("unchecked")
  92. final Iterable<Object> collection = (Iterable<Object>) value.get();
  93. final StringBuilder res = new StringBuilder();
  94. for (Object line : collection) {
  95. if (res.length() > 0) {
  96. res.append('\n');
  97. }
  98. res.append(doSubstitutions(line, template));
  99. }
  100. return res.toString();
  101. }
  102. private String getReplacement(final Object dataSource, final String tag) {
  103. final String[] functionParts = tag.split("\\|");
  104. final String[] dataParts = functionParts[0].split("\\.");
  105. final DisplayPropertyMap displayProperties = new DisplayPropertyMap();
  106. Object target = dataSource;
  107. for (String part : dataParts) {
  108. final Optional<Object> result = propertyManager.getProperty(target, target.getClass(), part);
  109. if (result.isPresent()) {
  110. target = result.get();
  111. // Collate all the display properties for objects as we traverse. More specific ones will
  112. // override earlier ones.
  113. if (target instanceof Displayable) {
  114. displayProperties.putAll(((Displayable) target).getDisplayProperties());
  115. }
  116. } else {
  117. return ERROR_STRING;
  118. }
  119. }
  120. String value = target.toString();
  121. for (int i = 1; i < functionParts.length; i++) {
  122. value = propertyManager.applyFunction(value, functionParts[i]);
  123. }
  124. return applyDisplayProperties(displayProperties, value);
  125. }
  126. // TODO: It should be possible for plugins etc to add new ways of applying properties.
  127. private String applyDisplayProperties(final DisplayPropertyMap displayProperties, final String value) {
  128. final StringBuilder res = new StringBuilder(value);
  129. displayProperties.get(DisplayProperty.LINK_USER).ifPresent(user -> res
  130. .insert(0, StyleApplier.CODE_NICKNAME)
  131. .insert(0, user.getNickname())
  132. .insert(0, StyleApplier.CODE_NICKNAME)
  133. .append(StyleApplier.CODE_NICKNAME));
  134. displayProperties.get(DisplayProperty.FOREGROUND_COLOUR).ifPresent(colour -> res
  135. .insert(0, ColourUtils.getHex(colour))
  136. .insert(0, IRCControlCodes.COLOUR_HEX)
  137. .append(IRCControlCodes.COLOUR_HEX));
  138. return res.toString();
  139. }
  140. }