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.

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