/
MainPanel.java
221 lines (208 loc) · 8.28 KB
/
MainPanel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Element;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public final class MainPanel extends JPanel {
public static final HighlightPainter HIGHLIGHT = new DefaultHighlightPainter(Color.YELLOW);
public static final String SEPARATOR = "----%n%s%n";
public final JTextArea textArea = new JTextArea();
public final JEditorPane editorPane = new JEditorPane();
public final JTextField field = new JTextField("3");
public final Action elementIdAction = new AbstractAction("Element#getElement(id)") {
@Override public void actionPerformed(ActionEvent e) {
textArea.append(String.format(SEPARATOR, getValue(NAME)));
String id = field.getText().trim();
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
Element element = doc.getElement(id);
if (Objects.nonNull(element)) {
textArea.append(String.format("found: %s%n", element));
editorPane.requestFocusInWindow();
editorPane.select(element.getStartOffset(), element.getEndOffset());
}
}
};
public final Action highlightAction = new AbstractAction("Highlight Element[@id]") {
@Override public void actionPerformed(ActionEvent e) {
textArea.append(String.format(SEPARATOR, getValue(NAME)));
JToggleButton b = (JToggleButton) e.getSource();
if (b.isSelected()) {
for (Element root : editorPane.getDocument().getRootElements()) {
traverseElementById(root);
}
} else {
Highlighter highlighter = editorPane.getHighlighter();
highlighter.removeAllHighlights();
}
}
};
public final Action parserAction = new AbstractAction("ParserDelegator") {
@Override public void actionPerformed(ActionEvent e) {
textArea.append(String.format(SEPARATOR, getValue(NAME)));
String id = field.getText().trim();
String text = editorPane.getText();
ParserDelegator delegator = new ParserDelegator();
try {
delegator.parse(new StringReader(text), new HTMLEditorKit.ParserCallback() {
@Override public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos) {
Object attrId = a.getAttribute(HTML.Attribute.ID);
textArea.append(String.format("%s@id=%s%n", tag, attrId));
if (id.equals(attrId)) {
textArea.append(String.format("found: pos=%d%n", pos));
int endOffs = text.indexOf('>', pos);
textArea.append(String.format("%s%n", text.substring(pos, endOffs + 1)));
}
}
}, Boolean.TRUE);
} catch (IOException ex) {
ex.printStackTrace();
textArea.append(String.format("%s%n", ex.getMessage()));
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
}
}
};
private MainPanel() {
super(new BorderLayout());
editorPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
String span2 = "<span id='2'>345678</span>";
String span0 = "<span class='insert' id='0'>6</span>";
String span1 = "<span id='1'>8</span>";
String div3 = "<div class='fff' id='3'>123</div>";
String html = "<html>12%s90<p>1<a href='..'>23</a>45%s7%s90%s4567890</p>";
editorPane.setText(String.format(html, span2, span0, span1, div3));
DefaultHighlighter dh = (DefaultHighlighter) editorPane.getHighlighter();
dh.setDrawsLayeredHighlights(false);
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setTopComponent(new JScrollPane(editorPane));
sp.setBottomComponent(new JScrollPane(textArea));
JPanel p = new JPanel(new GridLayout(2, 2, 5, 5));
p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
p.add(field);
p.add(new JButton(elementIdAction));
p.add(new JToggleButton(highlightAction));
p.add(new JButton(parserAction));
add(sp);
add(p, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public void addHighlight(Element element, boolean isBlock) {
Highlighter highlighter = editorPane.getHighlighter();
int start = element.getStartOffset();
int lf = isBlock ? 1 : 0;
int end = element.getEndOffset() - lf; // lf???, setDrawsLayeredHighlights(false) bug???
try {
highlighter.addHighlight(start, end, HIGHLIGHT);
} catch (BadLocationException ex) {
// should never happen
RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
wrap.initCause(ex);
throw wrap;
}
}
public void traverseElementById(Element element) {
if (element.isLeaf()) {
checkId(element);
} else {
for (int i = 0; i < element.getElementCount(); i++) {
Element child = element.getElement(i);
checkId(child);
if (!child.isLeaf()) {
traverseElementById(child);
}
}
}
}
public void checkId(Element element) {
AttributeSet attrs = element.getAttributes();
Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
Object name = elementName == null ? attrs.getAttribute(StyleConstants.NameAttribute) : null;
HTML.Tag tag;
if (name instanceof HTML.Tag) {
tag = (HTML.Tag) name;
} else {
return;
}
textArea.append(String.format("%s%n", tag));
if (tag.isBlock()) { // block
blockHighlight(element, attrs);
} else { // inline
inlineHighlight(element, attrs);
}
}
private void blockHighlight(Element element, AttributeSet attrs) {
Optional.ofNullable(attrs.getAttribute(HTML.Attribute.ID))
.ifPresent(id -> {
textArea.append(String.format("block: id=%s%n", id));
addHighlight(element, true);
});
// Object bid = attrs.getAttribute(HTML.Attribute.ID);
// if (Objects.nonNull(bid)) {
// textArea.append(String.format("block: id=%s%n", bid));
// addHighlight(element, true);
// }
}
private void inlineHighlight(Element element, AttributeSet attrs) {
Collections.list(attrs.getAttributeNames()).stream()
.filter(AttributeSet.class::isInstance)
.map(AttributeSet.class::cast)
.map(a -> a.getAttribute(HTML.Attribute.ID))
.filter(Objects::nonNull)
.forEach(id -> {
textArea.append(String.format("inline: id=%s%n", id));
addHighlight(element, false);
});
// Enumeration<?> e = attrs.getAttributeNames();
// while (e.hasMoreElements()) {
// Object obj = attrs.getAttribute(e.nextElement());
// // System.out.println("AttributeNames: " + obj);
// if (obj instanceof AttributeSet) {
// AttributeSet a = (AttributeSet) obj;
// Object iid = a.getAttribute(HTML.Attribute.ID);
// if (Objects.nonNull(iid)) {
// textArea.append(String.format("inline: id=%s%n", iid));
// addHighlight(element, false);
// }
// }
// }
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException ignored) {
Toolkit.getDefaultToolkit().beep();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
ex.printStackTrace();
return;
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}