Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Styliser.java 22KB

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