2 * XdccDownloader - MessageCleaner.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.irc.util;
20 import java.io.IOException;
21 import java.io.StringReader;
22 import java.util.EnumSet;
26 * Removes formatting codes from IRC messages.
28 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
30 public class MessageCleaner {
32 /** The kind of attributes to clear. */
33 public enum Attributes {
41 /** A default instance. */
42 private static final MessageCleaner DEFAULT_INSTANCE = new MessageCleaner();
45 * Cleans all formatting from the given line.
48 * The line to remove all formatting from
49 * @return The given line with all formatting removed
51 public String clean(String line) {
52 return clean(line, EnumSet.allOf(Attributes.class));
56 * Cleans the given formattings from the given line.
59 * The line to remove all formatting from
61 * The attributes to remove
62 * @return The given line with all given formatting removed
64 public String clean(String line, Set<Attributes> attributes) {
65 StringBuilder clean = new StringBuilder(line.length());
67 StringReader reader = new StringReader(line);
72 int r = reader.read();
77 if ((c == 2) && (attributes.contains(Attributes.bold))) {
80 if ((c == 3) && (attributes.contains(Attributes.color))) {
84 if ((c == 15) && (attributes.contains(Attributes.clear))) {
87 if (inColorCode > 0) {
88 if (inColorCode == 1) {
89 if ((c < '0') || (c > '9')) {
99 } else if (inColorCode == 2) {
104 if ((c < '0') || (c > '5')) {
110 } else if (inColorCode == 3) {
117 } else if (inColorCode == 4) {
121 } else if ((c < '0') || (c > '9')) {
127 } else if (inColorCode == 5) {
129 if ((c >= '0') && (c <= '5')) {
132 } else if (inColorCode == 8) {
136 } else if (c == ',') {
142 } else if (inColorCode == 9) {
151 } catch (IOException ioe1) {
152 /* StringReader will never throw. */
155 return clean.toString();
163 * Returns the default instance.
165 * @return The default instance
167 public static MessageCleaner getDefaultInstance() {
168 return DEFAULT_INSTANCE;