Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Styliser.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. position == 0);
  138. }
  139. }
  140. }
  141. }
  142. @Override
  143. public String doLinks(final String string) {
  144. String target = string;
  145. final String prefixes = connection == null ? null
  146. : connection.getGroupChatManager().getChannelPrefixes();
  147. String target2 = target;
  148. target = target.replaceAll(URL_REGEXP, CODE_HYPERLINK + "$0" + CODE_HYPERLINK);
  149. if (prefixes != null) {
  150. target = target.replaceAll(String.format(URL_CHANNEL, prefixes),
  151. CODE_CHANNEL + "$0" + CODE_CHANNEL);
  152. }
  153. for (int j = 0; j < 5 && !target.equals(target2); j++) {
  154. target2 = target;
  155. target = target
  156. .replaceAll(URL_INT1, "$1$3$2")
  157. .replaceAll(URL_INT2, "$1$2$3$5$4")
  158. .replaceAll(URL_INT3, "$1$2$4$3")
  159. .replaceAll(URL_INT4, "$1$3$2");
  160. }
  161. return target;
  162. }
  163. /**
  164. * Applies the smilie styles to the target.
  165. *
  166. * @param string The string to be smilified
  167. *
  168. * @return A copy of the string with smilies marked up
  169. *
  170. * @since 0.6.3m1
  171. */
  172. private String doSmilies(final String string) {
  173. // TODO: Check if they're enabled.
  174. // TODO: Store the list instead of building it every line
  175. final StringBuilder smilies = new StringBuilder();
  176. configManager.getOptions("icon").entrySet().stream()
  177. .filter(icon -> icon.getKey().startsWith("smilie-")).forEach(icon -> {
  178. if (smilies.length() > 0) {
  179. smilies.append('|');
  180. }
  181. smilies.append(Pattern.quote(icon.getKey().substring(7)));
  182. });
  183. return string.replaceAll("(\\s|^)(" + smilies + ")(?=\\s|$)",
  184. "$1" + CODE_SMILIE + "$2" + CODE_SMILIE);
  185. }
  186. /**
  187. * Returns a substring of the input string such that no control codes are present in the output.
  188. * If the returned value isn't the same as the input, then the character immediately after is a
  189. * control character.
  190. *
  191. * @param input The string to read from
  192. *
  193. * @return A substring of the input containing no control characters
  194. */
  195. @VisibleForTesting
  196. static String readUntilControl(final String input) {
  197. int pos = input.length();
  198. pos = checkChar(pos, input.indexOf(IRCControlCodes.BOLD));
  199. pos = checkChar(pos, input.indexOf(IRCControlCodes.UNDERLINE));
  200. pos = checkChar(pos, input.indexOf(IRCControlCodes.STOP));
  201. pos = checkChar(pos, input.indexOf(IRCControlCodes.COLOUR));
  202. pos = checkChar(pos, input.indexOf(IRCControlCodes.COLOUR_HEX));
  203. pos = checkChar(pos, input.indexOf(IRCControlCodes.ITALIC));
  204. pos = checkChar(pos, input.indexOf(IRCControlCodes.FIXED));
  205. pos = checkChar(pos, input.indexOf(CODE_HYPERLINK));
  206. pos = checkChar(pos, input.indexOf(CODE_NICKNAME));
  207. pos = checkChar(pos, input.indexOf(CODE_CHANNEL));
  208. pos = checkChar(pos, input.indexOf(CODE_SMILIE));
  209. pos = checkChar(pos, input.indexOf(IRCControlCodes.NEGATE));
  210. pos = checkChar(pos, input.indexOf(CODE_TOOLTIP));
  211. return input.substring(0, pos);
  212. }
  213. /**
  214. * Helper function used in readUntilControl. Checks if i is a valid index of the string (i.e.,
  215. * it's not -1), and then returns the minimum of pos and i.
  216. *
  217. * @param pos The current position in the string
  218. * @param i The index of the first occurrence of some character
  219. *
  220. * @return The new position (see implementation)
  221. */
  222. private static int checkChar(final int pos, final int i) {
  223. if (i < pos && i != -1) {
  224. return i;
  225. }
  226. return pos;
  227. }
  228. /**
  229. * Reads the first control character from the input string (and any arguments it takes), and
  230. * applies it to the specified attribute set.
  231. *
  232. * @return The number of characters read as control characters
  233. *@param string The string to read from
  234. * @param maker The attribute set that new attributes will be applied to
  235. * @param isStart Whether this is at the start of the string or not
  236. */
  237. private int readControlChars(final String string,
  238. final StyliserState state,
  239. final StyledMessageMaker<?> maker, final boolean isStart) {
  240. final boolean isNegated = state.isNegated;
  241. // Bold
  242. if (string.charAt(0) == IRCControlCodes.BOLD) {
  243. if (!isNegated) {
  244. maker.toggleBold();
  245. }
  246. return 1;
  247. }
  248. // Underline
  249. if (string.charAt(0) == IRCControlCodes.UNDERLINE) {
  250. if (!isNegated) {
  251. maker.toggleUnderline();
  252. }
  253. return 1;
  254. }
  255. // Italic
  256. if (string.charAt(0) == IRCControlCodes.ITALIC) {
  257. if (!isNegated) {
  258. maker.toggleItalic();
  259. }
  260. return 1;
  261. }
  262. // Hyperlinks
  263. if (string.charAt(0) == CODE_HYPERLINK) {
  264. if (!isNegated && styleURIs) {
  265. maker.toggleHyperlinkStyle(uriColour);
  266. }
  267. if (state.isInLink) {
  268. maker.endHyperlink();
  269. } else {
  270. maker.startHyperlink(readUntilControl(string.substring(1)));
  271. }
  272. state.isInLink = !state.isInLink;
  273. return 1;
  274. }
  275. // Channel links
  276. if (string.charAt(0) == CODE_CHANNEL) {
  277. if (!isNegated && styleChannels) {
  278. maker.toggleChannelLinkStyle(channelColour);
  279. }
  280. if (state.isInLink) {
  281. maker.endChannelLink();
  282. } else {
  283. maker.startChannelLink(readUntilControl(string.substring(1)));
  284. }
  285. state.isInLink = !state.isInLink;
  286. return 1;
  287. }
  288. // Nickname links
  289. if (string.charAt(0) == CODE_NICKNAME) {
  290. int count = 1;
  291. if (state.isInLink) {
  292. maker.endNicknameLink();
  293. } else {
  294. int next = string.indexOf(CODE_NICKNAME, 1);
  295. maker.startNicknameLink(string.substring(1, next));
  296. count += next;
  297. }
  298. state.isInLink = !state.isInLink;
  299. return count;
  300. }
  301. // Fixed pitch
  302. if (string.charAt(0) == IRCControlCodes.FIXED) {
  303. if (!isNegated) {
  304. maker.toggleFixedWidth();
  305. }
  306. return 1;
  307. }
  308. // Stop formatting
  309. if (string.charAt(0) == IRCControlCodes.STOP) {
  310. if (!isNegated) {
  311. maker.resetAllStyles();
  312. }
  313. return 1;
  314. }
  315. // Colours
  316. if (string.charAt(0) == IRCControlCodes.COLOUR) {
  317. int count = 1;
  318. // This isn't too nice!
  319. if (string.length() > count && isInt(string.charAt(count))) {
  320. int foreground = string.charAt(count) - '0';
  321. count++;
  322. if (string.length() > count && isInt(string.charAt(count))) {
  323. foreground = foreground * 10 + string.charAt(count) - '0';
  324. count++;
  325. }
  326. foreground %= 16;
  327. if (!isNegated) {
  328. maker.setForeground(colourManager.getColourFromString(
  329. String.valueOf(foreground), Colour.WHITE));
  330. if (isStart) {
  331. maker.setDefaultForeground(colourManager
  332. .getColourFromString(String.valueOf(foreground), Colour.WHITE));
  333. }
  334. }
  335. // Now background
  336. if (string.length() > count && string.charAt(count) == ','
  337. && string.length() > count + 1
  338. && isInt(string.charAt(count + 1))) {
  339. int background = string.charAt(count + 1) - '0';
  340. count += 2; // Comma and first digit
  341. if (string.length() > count && isInt(string.charAt(count))) {
  342. background = background * 10 + string.charAt(count) - '0';
  343. count++;
  344. }
  345. background %= 16;
  346. if (!isNegated) {
  347. maker.setBackground(colourManager
  348. .getColourFromString(String.valueOf(background), Colour.WHITE));
  349. if (isStart) {
  350. maker.setDefaultBackground(colourManager
  351. .getColourFromString(String.valueOf(background), Colour.WHITE));
  352. }
  353. }
  354. }
  355. } else if (!isNegated) {
  356. maker.resetColours();
  357. }
  358. return count;
  359. }
  360. // Hex colours
  361. if (string.charAt(0) == IRCControlCodes.COLOUR_HEX) {
  362. int count = 1;
  363. if (hasHexString(string, 1)) {
  364. if (!isNegated) {
  365. maker.setForeground(
  366. colourManager.getColourFromString(string.substring(1, 7).toUpperCase(),
  367. Colour.WHITE));
  368. if (isStart) {
  369. maker.setDefaultForeground(
  370. colourManager.getColourFromString(
  371. string.substring(1, 7).toUpperCase(), Colour.WHITE));
  372. }
  373. }
  374. count += 6;
  375. if (string.length() == count) {
  376. return count;
  377. }
  378. // Now for background
  379. if (string.charAt(count) == ',' && hasHexString(string, count + 1)) {
  380. count++;
  381. if (!isNegated) {
  382. maker.setBackground(colourManager.getColourFromString(
  383. string.substring(count, count + 6).toUpperCase(), Colour.WHITE));
  384. if (isStart) {
  385. maker.setDefaultBackground(colourManager.getColourFromString(
  386. string.substring(count, count + 6).toUpperCase(), Colour.WHITE));
  387. }
  388. }
  389. count += 6;
  390. }
  391. } else if (!isNegated) {
  392. maker.resetColours();
  393. }
  394. return count;
  395. }
  396. // Control code negation
  397. if (string.charAt(0) == IRCControlCodes.NEGATE) {
  398. state.isNegated = !state.isNegated;
  399. return 1;
  400. }
  401. // Smilies!!
  402. if (string.charAt(0) == CODE_SMILIE) {
  403. if (state.isInSmilie) {
  404. maker.endSmilie();
  405. } else {
  406. maker.startSmilie("smilie-" + readUntilControl(string.substring(1)));
  407. }
  408. state.isInSmilie = !state.isInSmilie;
  409. return 1;
  410. }
  411. // Tooltips
  412. if (string.charAt(0) == CODE_TOOLTIP) {
  413. if (state.isInToolTip) {
  414. maker.endToolTip();
  415. } else {
  416. final int index = string.indexOf(CODE_TOOLTIP, 1);
  417. if (index == -1) {
  418. // Doesn't make much sense, let's ignore it!
  419. return 1;
  420. }
  421. final String tooltip = string.substring(1, index);
  422. maker.startToolTip(tooltip);
  423. state.isInToolTip = !state.isInToolTip;
  424. return tooltip.length() + 2;
  425. }
  426. state.isInToolTip = !state.isInToolTip;
  427. return 1;
  428. }
  429. return 0;
  430. }
  431. /**
  432. * Determines if the specified character represents a single integer (i.e. 0-9).
  433. *
  434. * @param c The character to check
  435. *
  436. * @return True iff the character is in the range [0-9], false otherwise
  437. */
  438. private static boolean isInt(final char c) {
  439. return c >= '0' && c <= '9';
  440. }
  441. /**
  442. * Determines if the specified character represents a single hex digit (i.e., 0-F).
  443. *
  444. * @param c The character to check
  445. *
  446. * @return True iff the character is in the range [0-F], false otherwise
  447. */
  448. private static boolean isHex(final char c) {
  449. return isInt(c) || c >= 'A' && c <= 'F';
  450. }
  451. /**
  452. * Determines if the specified string has a 6-digit hex string starting at the specified offset.
  453. *
  454. * @param input The string to check
  455. * @param offset The offset to start at
  456. *
  457. * @return True iff there is a hex string preset at the offset
  458. */
  459. private static boolean hasHexString(final String input, final int offset) {
  460. // If the string's too short, it can't have a hex string
  461. if (input.length() < offset + 6) {
  462. return false;
  463. }
  464. boolean res = true;
  465. for (int i = offset; i < 6 + offset; i++) {
  466. res = res && isHex(input.toUpperCase(Locale.getDefault()).charAt(i));
  467. }
  468. return res;
  469. }
  470. @Override
  471. public void configChanged(final String domain, final String key) {
  472. switch (key) {
  473. case "stylelinks":
  474. styleURIs = configManager.getOptionBool("ui", "stylelinks");
  475. break;
  476. case "stylechannels":
  477. styleChannels = configManager.getOptionBool("ui", "stylechannels");
  478. break;
  479. case "linkcolour":
  480. uriColour = colourManager.getColourFromString(
  481. configManager.getOptionString("ui", "linkcolour"), null);
  482. break;
  483. case "channelcolour":
  484. channelColour = colourManager.getColourFromString(
  485. configManager.getOptionString("ui", "channelcolour"), null);
  486. break;
  487. }
  488. }
  489. private static class StyliserState {
  490. boolean isNegated;
  491. boolean isInLink;
  492. boolean isInSmilie;
  493. boolean isInToolTip;
  494. }
  495. }