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.

Styliser.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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.interfaces.Connection;
  24. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  25. import com.dmdirc.interfaces.config.ConfigChangeListener;
  26. import com.dmdirc.util.colours.Colour;
  27. import com.google.common.annotations.VisibleForTesting;
  28. import java.util.Locale;
  29. import java.util.regex.Pattern;
  30. import javax.annotation.Nullable;
  31. /**
  32. * The styliser applies IRC styles to text. Styles are indicated by various control codes which are
  33. * a de-facto IRC standard.
  34. */
  35. public class Styliser implements ConfigChangeListener, StyleApplier {
  36. /** Internal chars. */
  37. private static final String INTERNAL_CHARS = String.valueOf(CODE_HYPERLINK)
  38. + CODE_NICKNAME + CODE_CHANNEL + CODE_SMILIE + CODE_TOOLTIP;
  39. /** Characters used for hyperlinks. */
  40. private static final String HYPERLINK_CHARS = Character.toString(CODE_HYPERLINK) + CODE_CHANNEL;
  41. /** Regexp to match characters which shouldn't be used in channel links. */
  42. private static final String RESERVED_CHARS = "[^\\s" + IRCControlCodes.BOLD + IRCControlCodes.COLOUR
  43. + IRCControlCodes.STOP + IRCControlCodes.COLOUR_HEX + IRCControlCodes.FIXED + IRCControlCodes.ITALIC
  44. + IRCControlCodes.UNDERLINE + CODE_CHANNEL + CODE_NICKNAME + IRCControlCodes.NEGATE
  45. + "\",]";
  46. /** Defines all characters treated as trailing punctuation that are illegal in URLs. */
  47. private static final String URL_PUNCT_ILLEGAL = "\"";
  48. /** Defines all characters treated as trailing punctuation that're legal in URLs. */
  49. private static final String URL_PUNCT_LEGAL = "';:!,\\.\\?";
  50. /** Defines all trailing punctuation. */
  51. private static final String URL_PUNCT = URL_PUNCT_ILLEGAL + URL_PUNCT_LEGAL;
  52. /** Defines all characters allowed in URLs that aren't treated as trailing punct. */
  53. private static final String URL_NOPUNCT = "a-z0-9$\\-_@&\\+\\*\\(\\)=/#%~\\|";
  54. /** Defines all characters allowed in URLs per W3C specs. */
  55. private static final String URL_CHARS = '[' + URL_PUNCT_LEGAL + URL_NOPUNCT
  56. + "]*[" + URL_NOPUNCT + "]+[" + URL_PUNCT_LEGAL + URL_NOPUNCT + "]*";
  57. /** The regular expression to use for marking up URLs. */
  58. private static final String URL_REGEXP = "(?i)((?>(?<!" + IRCControlCodes.COLOUR_HEX
  59. + "[a-f0-9]{5})[a-f]|[g-z+])+://" + URL_CHARS
  60. + "|(?<![a-z0-9:/])www\\." + URL_CHARS + ')';
  61. /** Regular expression for intelligent handling of closing brackets. */
  62. private static final String URL_INT1 = "(\\([^\\)" + HYPERLINK_CHARS
  63. + "]*(?:[" + HYPERLINK_CHARS + "][^" + HYPERLINK_CHARS + "]*["
  64. + HYPERLINK_CHARS + "])?[^\\)" + HYPERLINK_CHARS + "]*[" + HYPERLINK_CHARS
  65. + "][^" + HYPERLINK_CHARS + "]+)(\\)['\";:!,\\.\\)]*)([" + HYPERLINK_CHARS + "])";
  66. /** Regular expression for intelligent handling of trailing single and double quotes. */
  67. private static final String URL_INT2 = "(^(?:[^" + HYPERLINK_CHARS + "]+|["
  68. + HYPERLINK_CHARS + "][^" + HYPERLINK_CHARS + "][" + HYPERLINK_CHARS
  69. + "]))(['\"])([^" + HYPERLINK_CHARS + "]*?[" + HYPERLINK_CHARS + "][^"
  70. + HYPERLINK_CHARS + "]+)(\\1[" + URL_PUNCT + "]*)([" + HYPERLINK_CHARS + "])";
  71. /** Regular expression for intelligent handling of surrounding quotes. */
  72. private static final String URL_INT3 = "(['\"])([" + HYPERLINK_CHARS
  73. + "][^" + HYPERLINK_CHARS + "]+?)(\\1[^" + HYPERLINK_CHARS + "]*)(["
  74. + HYPERLINK_CHARS + "])";
  75. /** Regular expression for intelligent handling of trailing punctuation. */
  76. private static final String URL_INT4 = "([" + HYPERLINK_CHARS + "][^"
  77. + HYPERLINK_CHARS + "]+?)([" + URL_PUNCT + "]?)([" + HYPERLINK_CHARS + "])";
  78. /** The regular expression to use for marking up channels. */
  79. private static final String URL_CHANNEL = "(?i)(?<![^\\s\\+@\\-<>\\(\"',])([\\Q%s\\E]"
  80. + RESERVED_CHARS + "+)";
  81. /** Whether or not we should style links. */
  82. private boolean styleURIs;
  83. /** Whether or not we should style channel names. */
  84. private boolean styleChannels;
  85. /** Colour to use for URIs. */
  86. private Colour uriColour;
  87. /** Colour to use for channel names. */
  88. private Colour channelColour;
  89. /** Connection to get channel prefixes from, or null if not applicable. */
  90. @Nullable
  91. private final Connection connection;
  92. /** Config manager to retrieve settings from. */
  93. private final AggregateConfigProvider configManager;
  94. /** Colour manager to use to parse colours. */
  95. private final ColourManager colourManager;
  96. /**
  97. * Creates a new instance of Styliser.
  98. *
  99. * @param connection The {@link Connection} that this styliser is for. May be {@code null}.
  100. * @param configManager the {@link AggregateConfigProvider} to get settings from.
  101. * @param colourManager The {@link ColourManager} to get colours from.
  102. *
  103. * @since 0.6.3
  104. */
  105. public Styliser(@Nullable final Connection connection,
  106. final AggregateConfigProvider configManager,
  107. final ColourManager colourManager) {
  108. this.connection = connection;
  109. this.configManager = configManager;
  110. this.colourManager = colourManager;
  111. configManager.addChangeListener("ui", "linkcolour", this);
  112. configManager.addChangeListener("ui", "channelcolour", this);
  113. configManager.addChangeListener("ui", "stylelinks", this);
  114. configManager.addChangeListener("ui", "stylechannels", this);
  115. styleURIs = configManager.getOptionBool("ui", "stylelinks");
  116. styleChannels = configManager.getOptionBool("ui", "stylechannels");
  117. uriColour = colourManager.getColourFromString(
  118. configManager.getOptionString("ui", "linkcolour"), null);
  119. channelColour = colourManager.getColourFromString(
  120. configManager.getOptionString("ui", "channelcolour"), null);
  121. }
  122. @Override
  123. public void addStyledString(final StyledMessageMaker<?> maker, final String... strings) {
  124. maker.resetAllStyles();
  125. for (String string : strings) {
  126. final char[] chars = string.toCharArray();
  127. for (int j = 0; j < chars.length; j++) {
  128. if (chars[j] == 65533) {
  129. chars[j] = '?';
  130. }
  131. }
  132. int position = 0;
  133. final String target =
  134. doSmilies(doLinks(new String(chars).replaceAll(INTERNAL_CHARS, "")));
  135. final StyliserState state = new StyliserState();
  136. while (position < target.length()) {
  137. final String next = readUntilControl(target.substring(position));
  138. maker.appendString(next);
  139. position += next.length();
  140. if (position < target.length()) {
  141. position += readControlChars(target.substring(position), state, maker,
  142. position == 0);
  143. }
  144. }
  145. }
  146. }
  147. @Override
  148. public String doLinks(final String string) {
  149. String target = string;
  150. final String prefixes = connection == null ? null
  151. : connection.getGroupChatManager().getChannelPrefixes();
  152. String target2 = target;
  153. target = target.replaceAll(URL_REGEXP, CODE_HYPERLINK + "$0" + CODE_HYPERLINK);
  154. if (prefixes != null) {
  155. target = target.replaceAll(String.format(URL_CHANNEL, prefixes),
  156. CODE_CHANNEL + "$0" + CODE_CHANNEL);
  157. }
  158. for (int j = 0; j < 5 && !target.equals(target2); j++) {
  159. target2 = target;
  160. target = target
  161. .replaceAll(URL_INT1, "$1$3$2")
  162. .replaceAll(URL_INT2, "$1$2$3$5$4")
  163. .replaceAll(URL_INT3, "$1$2$4$3")
  164. .replaceAll(URL_INT4, "$1$3$2");
  165. }
  166. return target;
  167. }
  168. /**
  169. * Applies the smilie styles to the target.
  170. *
  171. * @param string The string to be smilified
  172. *
  173. * @return A copy of the string with smilies marked up
  174. *
  175. * @since 0.6.3m1
  176. */
  177. private String doSmilies(final String string) {
  178. // TODO: Check if they're enabled.
  179. // TODO: Store the list instead of building it every line
  180. final StringBuilder smilies = new StringBuilder();
  181. configManager.getOptions("icon").entrySet().stream()
  182. .filter(icon -> icon.getKey().startsWith("smilie-")).forEach(icon -> {
  183. if (smilies.length() > 0) {
  184. smilies.append('|');
  185. }
  186. smilies.append(Pattern.quote(icon.getKey().substring(7)));
  187. });
  188. return string.replaceAll("(\\s|^)(" + smilies + ")(?=\\s|$)",
  189. "$1" + CODE_SMILIE + "$2" + CODE_SMILIE);
  190. }
  191. /**
  192. * Returns a substring of the input string such that no control codes are present in the output.
  193. * If the returned value isn't the same as the input, then the character immediately after is a
  194. * control character.
  195. *
  196. * @param input The string to read from
  197. *
  198. * @return A substring of the input containing no control characters
  199. */
  200. @VisibleForTesting
  201. static String readUntilControl(final String input) {
  202. int pos = input.length();
  203. pos = checkChar(pos, input.indexOf(IRCControlCodes.BOLD));
  204. pos = checkChar(pos, input.indexOf(IRCControlCodes.UNDERLINE));
  205. pos = checkChar(pos, input.indexOf(IRCControlCodes.STOP));
  206. pos = checkChar(pos, input.indexOf(IRCControlCodes.COLOUR));
  207. pos = checkChar(pos, input.indexOf(IRCControlCodes.COLOUR_HEX));
  208. pos = checkChar(pos, input.indexOf(IRCControlCodes.ITALIC));
  209. pos = checkChar(pos, input.indexOf(IRCControlCodes.FIXED));
  210. pos = checkChar(pos, input.indexOf(CODE_HYPERLINK));
  211. pos = checkChar(pos, input.indexOf(CODE_NICKNAME));
  212. pos = checkChar(pos, input.indexOf(CODE_CHANNEL));
  213. pos = checkChar(pos, input.indexOf(CODE_SMILIE));
  214. pos = checkChar(pos, input.indexOf(IRCControlCodes.NEGATE));
  215. pos = checkChar(pos, input.indexOf(CODE_TOOLTIP));
  216. return input.substring(0, pos);
  217. }
  218. /**
  219. * Helper function used in readUntilControl. Checks if i is a valid index of the string (i.e.,
  220. * it's not -1), and then returns the minimum of pos and i.
  221. *
  222. * @param pos The current position in the string
  223. * @param i The index of the first occurrence of some character
  224. *
  225. * @return The new position (see implementation)
  226. */
  227. private static int checkChar(final int pos, final int i) {
  228. if (i < pos && i != -1) {
  229. return i;
  230. }
  231. return pos;
  232. }
  233. /**
  234. * Reads the first control character from the input string (and any arguments it takes), and
  235. * applies it to the specified attribute set.
  236. *
  237. * @return The number of characters read as control characters
  238. *@param string The string to read from
  239. * @param maker The attribute set that new attributes will be applied to
  240. * @param isStart Whether this is at the start of the string or not
  241. */
  242. private int readControlChars(final String string,
  243. final StyliserState state,
  244. final StyledMessageMaker<?> maker, final boolean isStart) {
  245. final boolean isNegated = state.isNegated;
  246. // Bold
  247. if (string.charAt(0) == IRCControlCodes.BOLD) {
  248. if (!isNegated) {
  249. maker.toggleBold();
  250. }
  251. return 1;
  252. }
  253. // Underline
  254. if (string.charAt(0) == IRCControlCodes.UNDERLINE) {
  255. if (!isNegated) {
  256. maker.toggleUnderline();
  257. }
  258. return 1;
  259. }
  260. // Italic
  261. if (string.charAt(0) == IRCControlCodes.ITALIC) {
  262. if (!isNegated) {
  263. maker.toggleItalic();
  264. }
  265. return 1;
  266. }
  267. // Hyperlinks
  268. if (string.charAt(0) == CODE_HYPERLINK) {
  269. if (!isNegated && styleURIs) {
  270. maker.toggleHyperlinkStyle(uriColour);
  271. }
  272. if (state.isInLink) {
  273. maker.endHyperlink();
  274. } else {
  275. maker.startHyperlink(readUntilControl(string.substring(1)));
  276. }
  277. state.isInLink = !state.isInLink;
  278. return 1;
  279. }
  280. // Channel links
  281. if (string.charAt(0) == CODE_CHANNEL) {
  282. if (!isNegated && styleChannels) {
  283. maker.toggleChannelLinkStyle(channelColour);
  284. }
  285. if (state.isInLink) {
  286. maker.endChannelLink();
  287. } else {
  288. maker.startChannelLink(readUntilControl(string.substring(1)));
  289. }
  290. state.isInLink = !state.isInLink;
  291. return 1;
  292. }
  293. // Nickname links
  294. if (string.charAt(0) == CODE_NICKNAME) {
  295. if (state.isInLink) {
  296. maker.endNicknameLink();
  297. } else {
  298. maker.startNicknameLink(readUntilControl(string.substring(1)));
  299. }
  300. state.isInLink = !state.isInLink;
  301. return 1;
  302. }
  303. // Fixed pitch
  304. if (string.charAt(0) == IRCControlCodes.FIXED) {
  305. if (!isNegated) {
  306. maker.toggleFixedWidth();
  307. }
  308. return 1;
  309. }
  310. // Stop formatting
  311. if (string.charAt(0) == IRCControlCodes.STOP) {
  312. if (!isNegated) {
  313. maker.resetAllStyles();
  314. }
  315. return 1;
  316. }
  317. // Colours
  318. if (string.charAt(0) == IRCControlCodes.COLOUR) {
  319. int count = 1;
  320. // This isn't too nice!
  321. if (string.length() > count && isInt(string.charAt(count))) {
  322. int foreground = string.charAt(count) - '0';
  323. count++;
  324. if (string.length() > count && isInt(string.charAt(count))) {
  325. foreground = foreground * 10 + string.charAt(count) - '0';
  326. count++;
  327. }
  328. foreground %= 16;
  329. if (!isNegated) {
  330. maker.setForeground(colourManager.getColourFromString(
  331. String.valueOf(foreground), Colour.WHITE));
  332. if (isStart) {
  333. maker.setDefaultForeground(colourManager
  334. .getColourFromString(String.valueOf(foreground), Colour.WHITE));
  335. }
  336. }
  337. // Now background
  338. if (string.length() > count && string.charAt(count) == ','
  339. && string.length() > count + 1
  340. && isInt(string.charAt(count + 1))) {
  341. int background = string.charAt(count + 1) - '0';
  342. count += 2; // Comma and first digit
  343. if (string.length() > count && isInt(string.charAt(count))) {
  344. background = background * 10 + string.charAt(count) - '0';
  345. count++;
  346. }
  347. background %= 16;
  348. if (!isNegated) {
  349. maker.setBackground(colourManager
  350. .getColourFromString(String.valueOf(background), Colour.WHITE));
  351. if (isStart) {
  352. maker.setDefaultBackground(colourManager
  353. .getColourFromString(String.valueOf(background), Colour.WHITE));
  354. }
  355. }
  356. }
  357. } else if (!isNegated) {
  358. maker.resetColours();
  359. }
  360. return count;
  361. }
  362. // Hex colours
  363. if (string.charAt(0) == IRCControlCodes.COLOUR_HEX) {
  364. int count = 1;
  365. if (hasHexString(string, 1)) {
  366. if (!isNegated) {
  367. maker.setForeground(
  368. colourManager.getColourFromString(string.substring(1, 7).toUpperCase(),
  369. Colour.WHITE));
  370. if (isStart) {
  371. maker.setDefaultForeground(
  372. colourManager.getColourFromString(
  373. string.substring(1, 7).toUpperCase(), Colour.WHITE));
  374. }
  375. }
  376. count += 6;
  377. if (string.length() == count) {
  378. return count;
  379. }
  380. // Now for background
  381. if (string.charAt(count) == ',' && hasHexString(string, count + 1)) {
  382. count++;
  383. if (!isNegated) {
  384. maker.setBackground(colourManager.getColourFromString(
  385. string.substring(count, count + 6).toUpperCase(), Colour.WHITE));
  386. if (isStart) {
  387. maker.setDefaultBackground(colourManager.getColourFromString(
  388. string.substring(count, count + 6).toUpperCase(), Colour.WHITE));
  389. }
  390. }
  391. count += 6;
  392. }
  393. } else if (!isNegated) {
  394. maker.resetColours();
  395. }
  396. return count;
  397. }
  398. // Control code negation
  399. if (string.charAt(0) == IRCControlCodes.NEGATE) {
  400. state.isNegated = !state.isNegated;
  401. return 1;
  402. }
  403. // Smilies!!
  404. if (string.charAt(0) == CODE_SMILIE) {
  405. if (state.isInSmilie) {
  406. maker.endSmilie();
  407. } else {
  408. maker.startSmilie("smilie-" + readUntilControl(string.substring(1)));
  409. }
  410. state.isInSmilie = !state.isInSmilie;
  411. return 1;
  412. }
  413. // Tooltips
  414. if (string.charAt(0) == CODE_TOOLTIP) {
  415. if (state.isInToolTip) {
  416. maker.endToolTip();
  417. } else {
  418. final int index = string.indexOf(CODE_TOOLTIP, 1);
  419. if (index == -1) {
  420. // Doesn't make much sense, let's ignore it!
  421. return 1;
  422. }
  423. final String tooltip = string.substring(1, index);
  424. maker.startToolTip(tooltip);
  425. state.isInToolTip = !state.isInToolTip;
  426. return tooltip.length() + 2;
  427. }
  428. state.isInToolTip = !state.isInToolTip;
  429. return 1;
  430. }
  431. return 0;
  432. }
  433. /**
  434. * Determines if the specified character represents a single integer (i.e. 0-9).
  435. *
  436. * @param c The character to check
  437. *
  438. * @return True iff the character is in the range [0-9], false otherwise
  439. */
  440. private static boolean isInt(final char c) {
  441. return c >= '0' && c <= '9';
  442. }
  443. /**
  444. * Determines if the specified character represents a single hex digit (i.e., 0-F).
  445. *
  446. * @param c The character to check
  447. *
  448. * @return True iff the character is in the range [0-F], false otherwise
  449. */
  450. private static boolean isHex(final char c) {
  451. return isInt(c) || c >= 'A' && c <= 'F';
  452. }
  453. /**
  454. * Determines if the specified string has a 6-digit hex string starting at the specified offset.
  455. *
  456. * @param input The string to check
  457. * @param offset The offset to start at
  458. *
  459. * @return True iff there is a hex string preset at the offset
  460. */
  461. private static boolean hasHexString(final String input, final int offset) {
  462. // If the string's too short, it can't have a hex string
  463. if (input.length() < offset + 6) {
  464. return false;
  465. }
  466. boolean res = true;
  467. for (int i = offset; i < 6 + offset; i++) {
  468. res = res && isHex(input.toUpperCase(Locale.getDefault()).charAt(i));
  469. }
  470. return res;
  471. }
  472. @Override
  473. public void configChanged(final String domain, final String key) {
  474. switch (key) {
  475. case "stylelinks":
  476. styleURIs = configManager.getOptionBool("ui", "stylelinks");
  477. break;
  478. case "stylechannels":
  479. styleChannels = configManager.getOptionBool("ui", "stylechannels");
  480. break;
  481. case "linkcolour":
  482. uriColour = colourManager.getColourFromString(
  483. configManager.getOptionString("ui", "linkcolour"), null);
  484. break;
  485. case "channelcolour":
  486. channelColour = colourManager.getColourFromString(
  487. configManager.getOptionString("ui", "channelcolour"), null);
  488. break;
  489. }
  490. }
  491. private static class StyliserState {
  492. boolean isNegated;
  493. boolean isInLink;
  494. boolean isInSmilie;
  495. boolean isInToolTip;
  496. }
  497. }