2038
|
1 |
package com.nokia.cpp.internal.api.utils.ui;
|
|
2 |
|
|
3 |
import java.util.ArrayList;
|
|
4 |
import java.util.List;
|
|
5 |
import java.util.regex.Matcher;
|
|
6 |
import java.util.regex.Pattern;
|
|
7 |
|
|
8 |
import org.eclipse.jface.resource.JFaceColors;
|
|
9 |
import org.eclipse.jface.viewers.StyledString;
|
|
10 |
import org.eclipse.jface.viewers.StyledString.Styler;
|
|
11 |
import org.eclipse.swt.graphics.TextStyle;
|
|
12 |
import org.eclipse.swt.widgets.Display;
|
|
13 |
|
|
14 |
public class LinkParser {
|
|
15 |
|
|
16 |
public static class Element {
|
|
17 |
private String text;
|
|
18 |
|
|
19 |
public Element(String text) {
|
|
20 |
this.text = text;
|
|
21 |
}
|
|
22 |
|
|
23 |
public String getText() {
|
|
24 |
return text;
|
|
25 |
}
|
|
26 |
}
|
|
27 |
|
|
28 |
public static class LinkElement extends Element {
|
|
29 |
private String href;
|
|
30 |
|
|
31 |
public LinkElement(String href, String text) {
|
|
32 |
super(text);
|
|
33 |
this.href = href;
|
|
34 |
}
|
|
35 |
|
|
36 |
public String getHref() {
|
|
37 |
return href;
|
|
38 |
}
|
|
39 |
}
|
|
40 |
|
|
41 |
private static final Pattern HREF_PATTERN = Pattern.compile("<a href=\"([^\"]*)\">(.*?)</a>", Pattern.CASE_INSENSITIVE);
|
|
42 |
private static Styler hyperLinkStyler = new Styler() {
|
|
43 |
@Override
|
|
44 |
public void applyStyles(TextStyle textStyle) {
|
|
45 |
textStyle.foreground = JFaceColors.getHyperlinkText(Display.getDefault());
|
|
46 |
textStyle.underline = true;
|
|
47 |
}
|
|
48 |
};
|
|
49 |
|
|
50 |
public static List<Element> parseText(String text) {
|
|
51 |
List<Element> elements = new ArrayList<Element>();
|
|
52 |
if (text != null) {
|
|
53 |
Matcher m = HREF_PATTERN.matcher(text);
|
|
54 |
int start = 0;
|
|
55 |
int end;
|
|
56 |
while (m.find()) {
|
|
57 |
end = m.start();
|
|
58 |
if (start <= end)
|
|
59 |
elements.add(new Element(text.substring(start, end)));
|
|
60 |
elements.add(new LinkElement(m.group(1), m.group(2)));
|
|
61 |
start = m.end();
|
|
62 |
}
|
|
63 |
end = text.length();
|
|
64 |
if (start <= end)
|
|
65 |
elements.add(new Element(text.substring(start, end)));
|
|
66 |
}
|
|
67 |
return elements;
|
|
68 |
}
|
|
69 |
|
|
70 |
public static StyledString getStyledString(List<Element> elements) {
|
|
71 |
StyledString styledString = new StyledString();
|
|
72 |
for (Element element : elements) {
|
|
73 |
styledString.append(element.getText(), element instanceof LinkElement ? hyperLinkStyler : null);
|
|
74 |
}
|
|
75 |
return styledString;
|
|
76 |
}
|
|
77 |
|
|
78 |
} |