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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*
  2. * Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.FrameContainer;
  24. import com.dmdirc.actions.ActionManager;
  25. import com.dmdirc.actions.CoreActionType;
  26. import com.dmdirc.interfaces.ConfigChangeListener;
  27. import com.dmdirc.logger.ErrorLevel;
  28. import com.dmdirc.logger.Logger;
  29. import java.awt.Color;
  30. import java.util.Locale;
  31. import java.util.Map;
  32. import java.util.regex.Pattern;
  33. import javax.swing.UIManager;
  34. import javax.swing.text.BadLocationException;
  35. import javax.swing.text.DefaultStyledDocument;
  36. import javax.swing.text.SimpleAttributeSet;
  37. import javax.swing.text.StyleConstants;
  38. import javax.swing.text.StyledDocument;
  39. /**
  40. * The styliser applies IRC styles to text. Styles are indicated by various
  41. * control codes which are a de-facto IRC standard.
  42. * @author chris
  43. */
  44. public class Styliser implements ConfigChangeListener {
  45. /** The character used for marking up bold text. */
  46. public static final char CODE_BOLD = 2;
  47. /** The character used for marking up coloured text. */
  48. public static final char CODE_COLOUR = 3;
  49. /** The character used for marking up coloured text (using hex). */
  50. public static final char CODE_HEXCOLOUR = 4;
  51. /** Character used to indicate hyperlinks. */
  52. public static final char CODE_HYPERLINK = 5;
  53. /** Character used to indicate channel links. */
  54. public static final char CODE_CHANNEL = 6;
  55. /** Character used to indicate smilies. */
  56. public static final char CODE_SMILIE = 7;
  57. /** The character used for stopping all formatting. */
  58. public static final char CODE_STOP = 15;
  59. /** Character used to indicate nickname links. */
  60. public static final char CODE_NICKNAME = 16;
  61. /** The character used for marking up fixed pitch text. */
  62. public static final char CODE_FIXED = 17;
  63. /** The character used for negating control codes. */
  64. public static final char CODE_NEGATE = 18;
  65. /** The character used for tooltips. */
  66. public static final char CODE_TOOLTIP = 19;
  67. /** The character used for marking up italic text. */
  68. public static final char CODE_ITALIC = 29;
  69. /** The character used for marking up underlined text. */
  70. public static final char CODE_UNDERLINE = 31;
  71. /** Internal chars. */
  72. private static final String INTERNAL_CHARS = String.valueOf(CODE_HYPERLINK)
  73. + CODE_NICKNAME + CODE_CHANNEL + CODE_SMILIE + CODE_TOOLTIP;
  74. /** Characters used for hyperlinks. */
  75. private static final String HYPERLINK_CHARS = CODE_HYPERLINK + "" + CODE_CHANNEL;
  76. /** Regexp to match characters which shouldn't be used in channel links. */
  77. private static final String RESERVED_CHARS = "[^\\s" + CODE_BOLD + CODE_COLOUR
  78. + CODE_STOP + CODE_HEXCOLOUR + CODE_FIXED + CODE_ITALIC
  79. + CODE_UNDERLINE + CODE_CHANNEL + CODE_NICKNAME + CODE_NEGATE + "\",]";
  80. /** Defines all characters treated as trailing punctuation that are illegal in URLs. */
  81. private static final String URL_PUNCT_ILLEGAL = "\"";
  82. /** Defines all characters treated as trailing punctuation that're legal in URLs. */
  83. private static final String URL_PUNCT_LEGAL = "';:!,\\.\\?";
  84. /** Defines all trailing punctuation. */
  85. private static final String URL_PUNCT = URL_PUNCT_ILLEGAL + URL_PUNCT_LEGAL;
  86. /** Defines all characters allowed in URLs that aren't treated as trailing punct. */
  87. private static final String URL_NOPUNCT = "a-z0-9$\\-_@&\\+\\*\\(\\)=/#%~\\|";
  88. /** Defines all characters allowed in URLs per W3C specs. */
  89. private static final String URL_CHARS = "[" + URL_PUNCT_LEGAL + URL_NOPUNCT
  90. + "]*[" + URL_NOPUNCT + "]+[" + URL_PUNCT_LEGAL + URL_NOPUNCT + "]*";
  91. /** The regular expression to use for marking up URLs. */
  92. private static final String URL_REGEXP = "(?i)([a-z+]+://" + URL_CHARS
  93. + "|(?<![a-z0-9:/])www\\." + URL_CHARS + ")";
  94. /** Regular expression for intelligent handling of closing brackets. */
  95. private static final String URL_INT1 = "(\\([^\\)" + HYPERLINK_CHARS
  96. + "]*(?:[" + HYPERLINK_CHARS + "][^" + HYPERLINK_CHARS + "]*["
  97. + HYPERLINK_CHARS + "])?[^\\)" + HYPERLINK_CHARS + "]*[" + HYPERLINK_CHARS
  98. + "][^" + HYPERLINK_CHARS + "]+)(\\)['\";:!,\\.\\)]*)([" + HYPERLINK_CHARS + "])";
  99. /** Regular expression for intelligent handling of trailing single and double quotes. */
  100. private static final String URL_INT2 = "(^(?:[^" + HYPERLINK_CHARS + "]+|["
  101. + HYPERLINK_CHARS + "][^" + HYPERLINK_CHARS + "][" + HYPERLINK_CHARS
  102. + "]))(['\"])([^" + HYPERLINK_CHARS + "]*?[" + HYPERLINK_CHARS + "][^"
  103. + HYPERLINK_CHARS + "]+)(\\1[" + URL_PUNCT + "]*)([" + HYPERLINK_CHARS + "])";
  104. /** Regular expression for intelligent handling of surrounding quotes. */
  105. private static final String URL_INT3 = "(['\"])([" + HYPERLINK_CHARS
  106. + "][^" + HYPERLINK_CHARS + "]+?)(\\1[^" + HYPERLINK_CHARS + "]*)(["
  107. + HYPERLINK_CHARS + "])";
  108. /** Regular expression for intelligent handling of trailing punctuation. */
  109. private static final String URL_INT4 = "([" + HYPERLINK_CHARS + "][^"
  110. + HYPERLINK_CHARS + "]+?)([" + URL_PUNCT + "]?)([" + HYPERLINK_CHARS + "])";
  111. /** The regular expression to use for marking up channels. */
  112. private static final String URL_CHANNEL = "(?i)(?<![^\\s\\+@\\-<>\\(\"',])([\\Q%s\\E]"
  113. + RESERVED_CHARS + "+)";
  114. /** Whether or not we should style links. */
  115. private boolean styleURIs, styleChannels;
  116. /** Colours to use for URI and channel links. */
  117. private Color uriColour, channelColour;
  118. /** The container that owns this styliser. */
  119. private final FrameContainer<?> owner;
  120. /**
  121. * Creates a new instance of Styliser.
  122. *
  123. * @param owner The {@link FrameContainer} that owns this styliser.
  124. * @since 0.6.3
  125. */
  126. public Styliser(final FrameContainer<?> owner) {
  127. this.owner = owner;
  128. owner.getConfigManager().addChangeListener("ui", "linkcolour", this);
  129. owner.getConfigManager().addChangeListener("ui", "channelcolour", this);
  130. owner.getConfigManager().addChangeListener("ui", "stylelinks", this);
  131. owner.getConfigManager().addChangeListener("ui", "stylechannels", this);
  132. styleURIs = owner.getConfigManager().getOptionBool("ui", "stylelinks");
  133. styleChannels = owner.getConfigManager().getOptionBool("ui", "stylechannels");
  134. uriColour = owner.getConfigManager().getOptionColour("ui", "linkcolour");
  135. channelColour = owner.getConfigManager().getOptionColour("ui", "channelcolour");
  136. }
  137. /**
  138. * Stylises the specified strings and adds them to the specified document.
  139. *
  140. * @param styledDoc Document to add the styled strings to
  141. * @param strings The lines to be stylised
  142. */
  143. public void addStyledString(final StyledDocument styledDoc, final String[] strings) {
  144. addStyledString(styledDoc, strings, new SimpleAttributeSet());
  145. }
  146. /**
  147. * Stylises the specified strings and adds them to the specified document.
  148. *
  149. * @param styledDoc Document to add the styled strings to
  150. * @param strings The lines to be stylised
  151. * @param attribs Base attribute set
  152. */
  153. public void addStyledString(final StyledDocument styledDoc,
  154. final String[] strings, final SimpleAttributeSet attribs) {
  155. resetAttributes(attribs);
  156. for (int i = 0; i < strings.length; i++) {
  157. final char[] chars = strings[i].toCharArray();
  158. for (int j = 0; j < chars.length; j++) {
  159. if (chars[j] == 65533) {
  160. chars[j] = '?';
  161. }
  162. }
  163. try {
  164. final int ooffset = styledDoc.getLength();
  165. int offset = ooffset;
  166. int position = 0;
  167. final String target = doSmilies(doLinks(new String(chars)
  168. .replaceAll(INTERNAL_CHARS, "")));
  169. attribs.addAttribute("DefaultFontFamily", UIManager.getFont("TextPane.font"));
  170. while (position < target.length()) {
  171. final String next = readUntilControl(target.substring(position));
  172. styledDoc.insertString(offset, next, attribs);
  173. position += next.length();
  174. offset += next.length();
  175. if (position < target.length()) {
  176. position += readControlChars(target.substring(position),
  177. attribs, position == 0);
  178. }
  179. }
  180. ActionManager.processEvent(CoreActionType.CLIENT_STRING_STYLED,
  181. null, styledDoc, ooffset, styledDoc.getLength() - ooffset);
  182. } catch (BadLocationException ex) {
  183. Logger.userError(ErrorLevel.MEDIUM,
  184. "Unable to insert styled string: " + ex.getMessage());
  185. }
  186. }
  187. }
  188. /**
  189. * Stylises the specified string.
  190. *
  191. * @param strings The line to be stylised
  192. *
  193. * @return StyledDocument for the inputted strings
  194. */
  195. public StyledDocument getStyledString(final String[] strings) {
  196. final StyledDocument styledDoc = new DefaultStyledDocument();
  197. addStyledString(styledDoc, strings);
  198. return styledDoc;
  199. }
  200. /**
  201. * Retrieves the styled String contained within the unstyled offsets
  202. * specified. That is, the <code>from</code> and <code>to</code> arguments
  203. * correspond to indexes in an unstyled version of the <code>styled</code>
  204. * string. The unstyled indices are translated to offsets within the
  205. * styled String, and the return value includes all text and control codes
  206. * between those indices.
  207. * <p>
  208. * The index translation is left-biased; that is, the indices are translated
  209. * to be as far left as they possibly can be. This means that the start of
  210. * the string will include any control codes immediately preceeding the
  211. * desired text, and the end will not include any trailing codes.
  212. *
  213. * @param styled The styled String to be operated on
  214. * @param from The starting index in the unstyled string
  215. * @param to The ending index in the unstyled string
  216. * @return The corresponding text between the two indices
  217. * @since 0.6.3
  218. */
  219. public static String getStyledText(final String styled, final int from, final int to) {
  220. final String unstyled = stipControlCodes(styled);
  221. final String startBit = unstyled.substring(0, from);
  222. final String middleBit = unstyled.substring(from, to);
  223. int start = from;
  224. while (!stipControlCodes(styled.substring(0, start)).equals(startBit)) {
  225. start++;
  226. }
  227. int end = to + start - from;
  228. while (!stipControlCodes(styled.substring(start, end)).equals(middleBit)) {
  229. end++;
  230. }
  231. return styled.substring(start, end);
  232. }
  233. /**
  234. * Applies the hyperlink styles and intelligent linking regexps to the
  235. * target.
  236. *
  237. * @param string The string to be linked
  238. * @return A copy of the string with hyperlinks marked up
  239. */
  240. public String doLinks(final String string) {
  241. String target = string;
  242. final String prefixes = owner.getServer() == null ? null
  243. : owner.getServer().getChannelPrefixes();
  244. String target2 = target;
  245. target = target.replaceAll(URL_REGEXP, CODE_HYPERLINK + "$0" + CODE_HYPERLINK);
  246. if (prefixes != null) {
  247. target = target.replaceAll(String.format(URL_CHANNEL, prefixes),
  248. CODE_CHANNEL + "$0" + CODE_CHANNEL);
  249. }
  250. for (int j = 0; j < 5 && !target.equals(target2); j++) {
  251. target2 = target;
  252. target = target
  253. .replaceAll(URL_INT1, "$1$3$2")
  254. .replaceAll(URL_INT2, "$1$2$3$5$4")
  255. .replaceAll(URL_INT3, "$1$2$4$3")
  256. .replaceAll(URL_INT4, "$1$3$2");
  257. }
  258. return target;
  259. }
  260. /**
  261. * Applies the smilie styles to the target.
  262. *
  263. * @param string The string to be smilified
  264. * @return A copy of the string with smilies marked up
  265. * @since 0.6.3m1
  266. */
  267. public String doSmilies(final String string) {
  268. // TODO: Check if they're enabled.
  269. // TODO: Store the list instead of building it every line
  270. final StringBuilder smilies = new StringBuilder();
  271. for (Map.Entry<String, String> icon
  272. : owner.getConfigManager().getOptions("icon").entrySet()) {
  273. if (icon.getKey().startsWith("smilie-")) {
  274. if (smilies.length() > 0) {
  275. smilies.append('|');
  276. }
  277. smilies.append(Pattern.quote(icon.getKey().substring(7)));
  278. }
  279. }
  280. return string.replaceAll("(\\s|^)(" + smilies + ")(?=\\s|$)",
  281. "$1" + CODE_SMILIE + "$2" + CODE_SMILIE);
  282. }
  283. /**
  284. * Strips all recognised control codes from the input string.
  285. * @param input the String to be stripped
  286. * @return a copy of the input with control codes removed
  287. */
  288. public static String stipControlCodes(final String input) {
  289. return input.replaceAll("[" + CODE_BOLD + CODE_CHANNEL + CODE_FIXED
  290. + CODE_HYPERLINK + CODE_ITALIC + CODE_NEGATE + CODE_NICKNAME
  291. + CODE_SMILIE + CODE_STOP + CODE_UNDERLINE + "]|"
  292. + CODE_HEXCOLOUR + "([A-Za-z0-9]{6}(,[A-Za-z0-9]{6})?)?|"
  293. + CODE_COLOUR + "([0-9]{1,2}(,[0-9]{1,2})?)?", "")
  294. .replaceAll(CODE_TOOLTIP + ".*?" + CODE_TOOLTIP + "(.*?)"
  295. + CODE_TOOLTIP, "$1");
  296. }
  297. /**
  298. * Returns a substring of the input string such that no control codes are present
  299. * in the output. If the returned value isn't the same as the input, then the
  300. * character immediately after is a control character.
  301. * @param input The string to read from
  302. * @return A substring of the input containing no control characters
  303. */
  304. public static String readUntilControl(final String input) {
  305. int pos = input.length();
  306. pos = checkChar(pos, input.indexOf(CODE_BOLD));
  307. pos = checkChar(pos, input.indexOf(CODE_UNDERLINE));
  308. pos = checkChar(pos, input.indexOf(CODE_STOP));
  309. pos = checkChar(pos, input.indexOf(CODE_COLOUR));
  310. pos = checkChar(pos, input.indexOf(CODE_HEXCOLOUR));
  311. pos = checkChar(pos, input.indexOf(CODE_ITALIC));
  312. pos = checkChar(pos, input.indexOf(CODE_FIXED));
  313. pos = checkChar(pos, input.indexOf(CODE_HYPERLINK));
  314. pos = checkChar(pos, input.indexOf(CODE_NICKNAME));
  315. pos = checkChar(pos, input.indexOf(CODE_CHANNEL));
  316. pos = checkChar(pos, input.indexOf(CODE_SMILIE));
  317. pos = checkChar(pos, input.indexOf(CODE_NEGATE));
  318. pos = checkChar(pos, input.indexOf(CODE_TOOLTIP));
  319. return input.substring(0, pos);
  320. }
  321. /**
  322. * Helper function used in readUntilControl. Checks if i is a valid index of
  323. * the string (i.e., it's not -1), and then returns the minimum of pos and i.
  324. * @param pos The current position in the string
  325. * @param i The index of the first occurance of some character
  326. * @return The new position (see implementation)
  327. */
  328. private static int checkChar(final int pos, final int i) {
  329. if (i < pos && i != -1) { return i; }
  330. return pos;
  331. }
  332. /**
  333. * Reads the first control character from the input string (and any arguments
  334. * it takes), and applies it to the specified attribute set.
  335. * @return The number of characters read as control characters
  336. * @param string The string to read from
  337. * @param attribs The attribute set that new attributes will be applied to
  338. * @param isStart Whether this is at the start of the string or not
  339. */
  340. private int readControlChars(final String string,
  341. final SimpleAttributeSet attribs, final boolean isStart) {
  342. final boolean isNegated = attribs.containsAttribute("NegateControl", Boolean.TRUE);
  343. // Bold
  344. if (string.charAt(0) == CODE_BOLD) {
  345. if (!isNegated) {
  346. toggleAttribute(attribs, StyleConstants.FontConstants.Bold);
  347. }
  348. return 1;
  349. }
  350. // Underline
  351. if (string.charAt(0) == CODE_UNDERLINE) {
  352. if (!isNegated) {
  353. toggleAttribute(attribs, StyleConstants.FontConstants.Underline);
  354. }
  355. return 1;
  356. }
  357. // Italic
  358. if (string.charAt(0) == CODE_ITALIC) {
  359. if (!isNegated) {
  360. toggleAttribute(attribs, StyleConstants.FontConstants.Italic);
  361. }
  362. return 1;
  363. }
  364. // Hyperlinks
  365. if (string.charAt(0) == CODE_HYPERLINK) {
  366. if (!isNegated) {
  367. toggleURI(attribs);
  368. }
  369. if (attribs.getAttribute(IRCTextAttribute.HYPERLINK) == null) {
  370. attribs.addAttribute(IRCTextAttribute.HYPERLINK,
  371. readUntilControl(string.substring(1)));
  372. } else {
  373. attribs.removeAttribute(IRCTextAttribute.HYPERLINK);
  374. }
  375. return 1;
  376. }
  377. // Channel links
  378. if (string.charAt(0) == CODE_CHANNEL) {
  379. if (!isNegated) {
  380. toggleChannel(attribs);
  381. }
  382. if (attribs.getAttribute(IRCTextAttribute.CHANNEL) == null) {
  383. attribs.addAttribute(IRCTextAttribute.CHANNEL,
  384. readUntilControl(string.substring(1)));
  385. } else {
  386. attribs.removeAttribute(IRCTextAttribute.CHANNEL);
  387. }
  388. return 1;
  389. }
  390. // Nickname links
  391. if (string.charAt(0) == CODE_NICKNAME) {
  392. if (attribs.getAttribute(IRCTextAttribute.NICKNAME) == null) {
  393. attribs.addAttribute(IRCTextAttribute.NICKNAME,
  394. readUntilControl(string.substring(1)));
  395. } else {
  396. attribs.removeAttribute(IRCTextAttribute.NICKNAME);
  397. }
  398. return 1;
  399. }
  400. // Fixed pitch
  401. if (string.charAt(0) == CODE_FIXED) {
  402. if (!isNegated) {
  403. if (attribs.containsAttribute(StyleConstants.FontConstants.FontFamily, "monospaced")) {
  404. attribs.removeAttribute(StyleConstants.FontConstants.FontFamily);
  405. } else {
  406. attribs.removeAttribute(StyleConstants.FontConstants.FontFamily);
  407. attribs.addAttribute(StyleConstants.FontConstants.FontFamily, "monospaced");
  408. }
  409. }
  410. return 1;
  411. }
  412. // Stop formatting
  413. if (string.charAt(0) == CODE_STOP) {
  414. if (!isNegated) {
  415. resetAttributes(attribs);
  416. }
  417. return 1;
  418. }
  419. // Colours
  420. if (string.charAt(0) == CODE_COLOUR) {
  421. int count = 1;
  422. // This isn't too nice!
  423. if (string.length() > count && isInt(string.charAt(count))) {
  424. int foreground = string.charAt(count) - '0';
  425. count++;
  426. if (string.length() > count && isInt(string.charAt(count))) {
  427. foreground = foreground * 10 + (string.charAt(count) - '0');
  428. count++;
  429. }
  430. foreground = foreground % 16;
  431. if (!isNegated) {
  432. setForeground(attribs, String.valueOf(foreground));
  433. if (isStart) {
  434. setDefaultForeground(attribs, String.valueOf(foreground));
  435. }
  436. }
  437. // Now background
  438. if (string.length() > count && string.charAt(count) == ','
  439. && string.length() > count + 1
  440. && isInt(string.charAt(count + 1))) {
  441. int background = string.charAt(count + 1) - '0';
  442. count += 2; // Comma and first digit
  443. if (string.length() > count && isInt(string.charAt(count))) {
  444. background = background * 10 + (string.charAt(count) - '0');
  445. count++;
  446. }
  447. background = background % 16;
  448. if (!isNegated) {
  449. setBackground(attribs, String.valueOf(background));
  450. if (isStart) {
  451. setDefaultBackground(attribs, String.valueOf(background));
  452. }
  453. }
  454. }
  455. } else if (!isNegated) {
  456. resetColour(attribs);
  457. }
  458. return count;
  459. }
  460. // Hex colours
  461. if (string.charAt(0) == CODE_HEXCOLOUR) {
  462. int count = 1;
  463. if (hasHexString(string, 1)) {
  464. if (!isNegated) {
  465. setForeground(attribs, string.substring(1, 7).toUpperCase());
  466. if (isStart) {
  467. setDefaultForeground(attribs, string.substring(1, 7).toUpperCase());
  468. }
  469. }
  470. count = count + 6;
  471. if (string.length() == count) {
  472. return count;
  473. }
  474. // Now for background
  475. if (string.charAt(count) == ',' && hasHexString(string, count + 1)) {
  476. count++;
  477. if (!isNegated) {
  478. setBackground(attribs, string.substring(count, count + 6).toUpperCase());
  479. if (isStart) {
  480. setDefaultBackground(attribs,
  481. string.substring(count, count + 6).toUpperCase());
  482. }
  483. }
  484. count += 6;
  485. }
  486. } else if (!isNegated) {
  487. resetColour(attribs);
  488. }
  489. return count;
  490. }
  491. // Control code negation
  492. if (string.charAt(0) == CODE_NEGATE) {
  493. toggleAttribute(attribs, "NegateControl");
  494. return 1;
  495. }
  496. // Smilies!!
  497. if (string.charAt(0) == CODE_SMILIE) {
  498. if (attribs.getAttribute(IRCTextAttribute.SMILEY) == null) {
  499. final String smilie = readUntilControl(string.substring(1));
  500. attribs.addAttribute(IRCTextAttribute.SMILEY, "smilie-" + smilie);
  501. } else {
  502. attribs.removeAttribute(IRCTextAttribute.SMILEY);
  503. }
  504. return 1;
  505. }
  506. // Tooltips
  507. if (string.charAt(0) == CODE_TOOLTIP) {
  508. if (attribs.getAttribute(IRCTextAttribute.TOOLTIP) == null) {
  509. final int index = string.indexOf(CODE_TOOLTIP, 1);
  510. if (index == -1) {
  511. // Doesn't make much sense, let's ignore it!
  512. return 1;
  513. }
  514. final String tooltip = string.substring(1, index);
  515. attribs.addAttribute(IRCTextAttribute.TOOLTIP, tooltip);
  516. return tooltip.length() + 2;
  517. } else {
  518. attribs.removeAttribute(IRCTextAttribute.TOOLTIP);
  519. }
  520. return 1;
  521. }
  522. return 0;
  523. }
  524. /**
  525. * Determines if the specified character represents a single integer (i.e. 0-9).
  526. * @param c The character to check
  527. * @return True iff the character is in the range [0-9], false otherwise
  528. */
  529. private static boolean isInt(final char c) {
  530. return c >= '0' && c <= '9';
  531. }
  532. /**
  533. * Determines if the specified character represents a single hex digit
  534. * (i.e., 0-F).
  535. * @param c The character to check
  536. * @return True iff the character is in the range [0-F], false otherwise
  537. */
  538. private static boolean isHex(final char c) {
  539. return isInt(c) || (c >= 'A' && c <= 'F');
  540. }
  541. /**
  542. * Determines if the specified string has a 6-digit hex string starting at
  543. * the specified offset.
  544. * @param input The string to check
  545. * @param offset The offset to start at
  546. * @return True iff there is a hex string preset at the offset
  547. */
  548. private static boolean hasHexString(final String input, final int offset) {
  549. // If the string's too short, it can't have a hex string
  550. if (input.length() < offset + 6) {
  551. return false;
  552. }
  553. boolean res = true;
  554. for (int i = offset; i < 6 + offset; i++) {
  555. res = res && isHex(input.toUpperCase(Locale.getDefault()).charAt(i));
  556. }
  557. return res;
  558. }
  559. /**
  560. * Toggles the various channel link-related attributes.
  561. *
  562. * @param attribs The attributes to be modified.
  563. */
  564. private void toggleChannel(final SimpleAttributeSet attribs) {
  565. if (styleChannels) {
  566. toggleLink(attribs, IRCTextAttribute.CHANNEL, channelColour);
  567. }
  568. }
  569. /**
  570. * Toggles the various hyperlink-related attributes.
  571. *
  572. * @param attribs The attributes to be modified.
  573. */
  574. private void toggleURI(final SimpleAttributeSet attribs) {
  575. if (styleURIs) {
  576. toggleLink(attribs, IRCTextAttribute.HYPERLINK, uriColour);
  577. }
  578. }
  579. /**
  580. * Toggles the attributes for a link.
  581. *
  582. * @since 0.6.4
  583. * @param attribs The attributes to modify
  584. * @param attribute The attribute indicating whether the link is open or closed
  585. * @param colour The colour to colour the link
  586. */
  587. private void toggleLink(final SimpleAttributeSet attribs,
  588. final IRCTextAttribute attribute, final Color colour) {
  589. if (attribs.getAttribute(attribute) == null) {
  590. // Add the hyperlink style
  591. if (attribs.containsAttribute(StyleConstants.FontConstants.Underline, Boolean.TRUE)) {
  592. attribs.addAttribute("restoreUnderline", Boolean.TRUE);
  593. } else {
  594. attribs.addAttribute(StyleConstants.FontConstants.Underline, Boolean.TRUE);
  595. }
  596. if (colour != null) {
  597. final Object foreground = attribs.getAttribute(
  598. StyleConstants.FontConstants.Foreground);
  599. if (foreground != null) {
  600. attribs.addAttribute("restoreColour", foreground);
  601. attribs.removeAttribute(StyleConstants.FontConstants.Foreground);
  602. }
  603. attribs.addAttribute(StyleConstants.FontConstants.Foreground, colour);
  604. }
  605. } else {
  606. // Remove the hyperlink style
  607. if (attribs.containsAttribute("restoreUnderline", Boolean.TRUE)) {
  608. attribs.removeAttribute("restoreUnderline");
  609. } else {
  610. attribs.removeAttribute(StyleConstants.FontConstants.Underline);
  611. }
  612. if (colour != null) {
  613. attribs.removeAttribute(StyleConstants.FontConstants.Foreground);
  614. final Object foreground = attribs.getAttribute("restoreColour");
  615. if (foreground != null) {
  616. attribs.addAttribute(StyleConstants.FontConstants.Foreground, foreground);
  617. attribs.removeAttribute("restoreColour");
  618. }
  619. }
  620. }
  621. }
  622. /**
  623. * Toggles the specified attribute. If the attribute exists in the attribute
  624. * set, it is removed. Otherwise, it is added with a value of Boolean.True.
  625. * @param attribs The attribute set to check
  626. * @param attrib The attribute to toggle
  627. */
  628. private static void toggleAttribute(final SimpleAttributeSet attribs,
  629. final Object attrib) {
  630. if (attribs.containsAttribute(attrib, Boolean.TRUE)) {
  631. attribs.removeAttribute(attrib);
  632. } else {
  633. attribs.addAttribute(attrib, Boolean.TRUE);
  634. }
  635. }
  636. /**
  637. * Resets all attributes in the specified attribute list.
  638. * @param attribs The attribute list whose attributes should be reset
  639. */
  640. private static void resetAttributes(final SimpleAttributeSet attribs) {
  641. if (attribs.containsAttribute(StyleConstants.FontConstants.Bold, Boolean.TRUE)) {
  642. attribs.removeAttribute(StyleConstants.FontConstants.Bold);
  643. }
  644. if (attribs.containsAttribute(StyleConstants.FontConstants.Underline, Boolean.TRUE)) {
  645. attribs.removeAttribute(StyleConstants.FontConstants.Underline);
  646. }
  647. if (attribs.containsAttribute(StyleConstants.FontConstants.Italic, Boolean.TRUE)) {
  648. attribs.removeAttribute(StyleConstants.FontConstants.Italic);
  649. }
  650. if (attribs.containsAttribute(StyleConstants.FontConstants.FontFamily, "monospaced")) {
  651. final Object defaultFont = attribs.getAttribute("DefaultFontFamily");
  652. attribs.removeAttribute(StyleConstants.FontConstants.FontFamily);
  653. attribs.addAttribute(StyleConstants.FontConstants.FontFamily, defaultFont);
  654. }
  655. resetColour(attribs);
  656. }
  657. /**
  658. * Resets the colour attributes in the specified attribute set.
  659. * @param attribs The attribute set whose colour attributes should be reset
  660. */
  661. private static void resetColour(final SimpleAttributeSet attribs) {
  662. if (attribs.isDefined(StyleConstants.Foreground)) {
  663. attribs.removeAttribute(StyleConstants.Foreground);
  664. }
  665. if (attribs.isDefined("DefaultForeground")) {
  666. attribs.addAttribute(StyleConstants.Foreground,
  667. attribs.getAttribute("DefaultForeground"));
  668. }
  669. if (attribs.isDefined(StyleConstants.Background)) {
  670. attribs.removeAttribute(StyleConstants.Background);
  671. }
  672. if (attribs.isDefined("DefaultBackground")) {
  673. attribs.addAttribute(StyleConstants.Background,
  674. attribs.getAttribute("DefaultBackground"));
  675. }
  676. }
  677. /**
  678. * Sets the foreground colour in the specified attribute set to the colour
  679. * corresponding to the specified colour code or hex.
  680. * @param attribs The attribute set to modify
  681. * @param foreground The colour code/hex of the new foreground colour
  682. */
  683. private static void setForeground(final SimpleAttributeSet attribs,
  684. final String foreground) {
  685. if (attribs.isDefined(StyleConstants.Foreground)) {
  686. attribs.removeAttribute(StyleConstants.Foreground);
  687. }
  688. attribs.addAttribute(StyleConstants.Foreground, ColourManager.parseColour(foreground));
  689. }
  690. /**
  691. * Sets the background colour in the specified attribute set to the colour
  692. * corresponding to the specified colour code or hex.
  693. * @param attribs The attribute set to modify
  694. * @param background The colour code/hex of the new background colour
  695. */
  696. private static void setBackground(final SimpleAttributeSet attribs,
  697. final String background) {
  698. if (attribs.isDefined(StyleConstants.Background)) {
  699. attribs.removeAttribute(StyleConstants.Background);
  700. }
  701. attribs.addAttribute(StyleConstants.Background, ColourManager.parseColour(background));
  702. }
  703. /**
  704. * Sets the default foreground colour (used after an empty ctrl+k or a ctrl+o).
  705. * @param attribs The attribute set to apply this default on
  706. * @param foreground The default foreground colour
  707. */
  708. private static void setDefaultForeground(final SimpleAttributeSet attribs,
  709. final String foreground) {
  710. attribs.addAttribute("DefaultForeground", ColourManager.parseColour(foreground));
  711. }
  712. /**
  713. * Sets the default background colour (used after an empty ctrl+k or a ctrl+o).
  714. * @param attribs The attribute set to apply this default on
  715. * @param background The default background colour
  716. */
  717. private static void setDefaultBackground(final SimpleAttributeSet attribs,
  718. final String background) {
  719. attribs.addAttribute("DefaultBackground", ColourManager.parseColour(background));
  720. }
  721. /** {@inheritDoc} */
  722. @Override
  723. public void configChanged(final String domain, final String key) {
  724. if ("stylelinks".equals(key)) {
  725. styleURIs = owner.getConfigManager().getOptionBool("ui", "stylelinks");
  726. } else if ("stylechannels".equals(key)) {
  727. styleChannels = owner.getConfigManager().getOptionBool("ui", "stylechannels");
  728. } else if ("linkcolour".equals(key)) {
  729. uriColour = owner.getConfigManager().getOptionColour("ui", "linkcolour");
  730. } else if ("channelcolour".equals(key)) {
  731. channelColour = owner.getConfigManager().getOptionColour("ui", "channelcolour");
  732. }
  733. }
  734. }