0%

[Eclipse] RCP實戰

實務上遇到的專案有用到自訂的taglib和規則,為開發方便且好追code,希望按下Ctrl鍵後,便能快速顯示超連結,且能跳到指定的類別和方法,因此有自行寫Eclipse外掛的想法。

修改plugin.xml

建好Plug-in Project後,修改plugin.xml如下

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectors">
<hyperlinkDetector
class="com.usermark.plugin.detectors.HyperlinkDetector"
id="com.usermark.hyperlinkDetector"
name="Custom Link"
targetId="org.eclipse.ui.DefaultTextEditor">
</hyperlinkDetector>
</extension>
</plugin>

其中,第4行point屬性為org.eclipse.ui.workbench.texteditor.hyperlinkDetectors,表示針對超連結偵測做擴展。切記name屬性必須要有,否則執行時無法成功。

實作AbstractHyperlinkDetector

接著建立HyperlinkDetector類別來實作,其靈感來自於XMLJavaHyperlinkDetector,有興趣可以自行查看。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class HyperlinkDetector extends AbstractHyperlinkDetector {
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
if (region != null && textViewer != null) {
IDocument document = textViewer.getDocument();
ITextFileBuffer textFileBuffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
if (textFileBuffer != null) {
IPath basePath = textFileBuffer.getLocation();
if (basePath != null && !basePath.isEmpty()) {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(basePath.segment(0));
}
}
}

return null;
}
}

經過一系列操作,第10行便可取得專案類別IProject,這在後面會用到。

IRegion

那麼當游標停在某個code,未做圈選,如何得知哪個範圍的code要來判斷是否產生超連結呢?
答案是利用detectHyperlinks()第二個傳入參數region得知游標停在哪,搭配第5行的document前後移動游標,便能依自訂規則取出字串,實作selectQualifiedName()方法如下。

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
private NodeRegion selectQualifiedName(IDocument document, int anchor) {
try {
int offset = anchor;

while (offset >= 0) {
char c = document.getChar(offset);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
offset--;
}

int start = offset;

offset = anchor;
int length = document.getLength();

while (offset < length) {
char c = document.getChar(offset);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
offset++;
}

int end = offset;

if (start == end) {
return null;
}

// 往前找屬性名稱
offset = start;
int attrEnd = start;

while (offset >= 0) {
char c = document.getChar(offset);
if (c == '=')
attrEnd = offset;
else if (c == ' ')
break;
offset--;
}

int attrStart = offset;
String attrName = document.get(attrStart + 1, attrEnd - attrStart - 1);

// 往前找Tag名稱
while (offset >= 0) {
char c = document.getChar(offset);
if (c == '<')
break;
offset--;
}

int tagStart = offset;

while (offset < attrStart) {
char c = document.getChar(offset);
if (c == ' ')
break;
offset++;
}

int tagEnd = offset;
String tagName = document.get(tagStart + 1, tagEnd - tagStart - 1);

return new NodeRegion(start + 1, end - start - 1, tagName, attrName);

} catch (BadLocationException badLocationException) {
return null;
}
}

產生超連結

此處為方便說明,只呈現關鍵code,主要就是丟給createHyperlink()。

1
2
3
4
IPath basePath = textFileBuffer.getLocation();
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(basePath.segment(0));
NodeRegion hyperlinkRegion = selectQualifiedName(document, region.getOffset());
List<IHyperlink> links = createHyperlink(project, basePath, name, hyperlinkRegion);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private List<IHyperlink> createHyperlink(IProject project, IPath basePath, String elementName, NodeRegion region) {
IJavaProject javaProject = JavaCore.create(project);
if (javaProject != null && javaProject.exists()) {
try {
if (region.getTagName().equals("my:select") && region.getAttrName().equals("src")) {
IType element = javaProject.findType("your/full/class");
if (element != null && element.exists()) {
return Collections.singletonList(new JavaElementHyperlink(region, element));
}
} else if (region.getTagName().equals("my:button") && region.getAttrName().equals("action")) {
// 自行實作
}
} catch (Exception e) {
}
}

return null;
}

舉例有個html元素長這樣

1
<my:select src="com.usermark.tag.selectImp" />

當游標停在src的value時,便可呈現超連結。
那如果判斷過程中需要搭配xml配置的話也辦得到。

1
2
3
4
5
6
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(project.getFile("your/xml/path").getContents());
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "your/expression";
Node controller = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

或是使用IStructuredModel

1
2
3
4
5
6
7
8
9
IStructuredModel model = StructuredModelManager.getModelManager().getModelForRead(project.getFile(structsXml));
if (model instanceof IDOMModel) {
IDOMModel domModel = (IDOMModel) model;
Document xmlDocument = domModel.getDocument();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "your/expression";
Node page = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
}
model.releaseFromRead();

實作IHyperlink

透過JavaUI.openInEditor()開啟IJavaElement。

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
static class JavaElementHyperlink implements IHyperlink {
private final IJavaElement fElement;
private final IRegion fRegion;

JavaElementHyperlink(IRegion region, IJavaElement element) {
this.fRegion = region;
this.fElement = element;
}

@Override
public IRegion getHyperlinkRegion() {
return this.fRegion;
}

// 可以完整顯示method + class
@Override
public String getHyperlinkText() {
String elementLabel = JavaElementLabels.getElementLabel(this.fElement,
JavaElementLabels.M_POST_QUALIFIED
| JavaElementLabels.I_POST_QUALIFIED
| JavaElementLabels.F_POST_QUALIFIED
| JavaElementLabels.T_POST_QUALIFIED
| JavaElementLabels.TP_POST_QUALIFIED
| JavaElementLabels.D_POST_QUALIFIED
| JavaElementLabels.CF_POST_QUALIFIED
| JavaElementLabels.CU_POST_QUALIFIED
| JavaElementLabels.P_POST_QUALIFIED
| JavaElementLabels.ROOT_VARIABLE
| JavaElementLabels.ROOT_POST_QUALIFIED);
return NLS.bind(JSPUIMessages.Open, elementLabel);
}

@Override
public String getTypeLabel() {
return null;
}

@Override
public void open() {
try {
JavaUI.openInEditor(this.fElement);
} catch (PartInitException partInitException) {
} catch (JavaModelException javaModelException) {
}
}
}

完整code

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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package com.usermark.plugin.detectors;

import java.lang.reflect.Array;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.jst.jsp.core.internal.java.JSPTranslation;
import org.eclipse.jst.jsp.core.internal.java.JSPTranslationAdapter;
import org.eclipse.jst.jsp.core.internal.java.JSPTranslationExtension;
import org.eclipse.jst.jsp.ui.internal.JSPUIMessages;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.PartInitException;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class HyperlinkDetector extends AbstractHyperlinkDetector {

static class NodeRegion extends Region {
private String tagName;
private String attrName;

public NodeRegion(int offset, int length, String tagName, String attrName) {
super(offset, length);
this.tagName = tagName;
this.attrName = attrName;
}

public String getTagName() {
return tagName;
}

public String getAttrName() {
return attrName;
}
}

static class JavaElementHyperlink implements IHyperlink {
private final IJavaElement fElement;
private final IRegion fRegion;

JavaElementHyperlink(IRegion region, IJavaElement element) {
this.fRegion = region;
this.fElement = element;
}

@Override
public IRegion getHyperlinkRegion() {
return this.fRegion;
}

// 可以完整顯示method + class
@Override
public String getHyperlinkText() {
String elementLabel = JavaElementLabels.getElementLabel(this.fElement,
JavaElementLabels.M_POST_QUALIFIED
| JavaElementLabels.I_POST_QUALIFIED
| JavaElementLabels.F_POST_QUALIFIED
| JavaElementLabels.T_POST_QUALIFIED
| JavaElementLabels.TP_POST_QUALIFIED
| JavaElementLabels.D_POST_QUALIFIED
| JavaElementLabels.CF_POST_QUALIFIED
| JavaElementLabels.CU_POST_QUALIFIED
| JavaElementLabels.P_POST_QUALIFIED
| JavaElementLabels.ROOT_VARIABLE
| JavaElementLabels.ROOT_POST_QUALIFIED);
return NLS.bind(JSPUIMessages.Open, elementLabel);
}

@Override
public String getTypeLabel() {
return null;
}

@Override
public void open() {
try {
JavaUI.openInEditor(this.fElement);
} catch (PartInitException partInitException) {
} catch (JavaModelException javaModelException) {
}
}
}

private boolean isJspJavaContent(IDocument document, IRegion region) {
JSPTranslation translation = null;
IStructuredModel model = null;
try {
model = StructuredModelManager.getModelManager().getExistingModelForRead(document);
if (model instanceof IDOMModel) {
IDOMModel xmlModel = (IDOMModel) model;
if (xmlModel != null) {
IDOMDocument xmlDoc = xmlModel.getDocument();
JSPTranslationAdapter adapter = (JSPTranslationAdapter) xmlDoc
.getAdapterFor(org.eclipse.jst.jsp.core.internal.java.IJSPTranslation.class);
if (adapter != null) {
JSPTranslationExtension jSPTranslationExtension = adapter.getJSPTranslation();
if (jSPTranslationExtension != null) {
int javaOffset = jSPTranslationExtension.getJavaOffset(region.getOffset());
if (javaOffset > -1) {
return true;
}
}
}
}
}
} finally {
if (model != null) {
model.releaseFromRead();
}
}

return false;
}

private List<IHyperlink> createHyperlink(IProject project, IPath basePath, String elementName, NodeRegion region) {
IJavaProject javaProject = JavaCore.create(project);
if (javaProject != null && javaProject.exists()) {
try {
if (region.getTagName().equals("my:select") && region.getAttrName().equals("src")) {
IType element = javaProject.findType("your/full/class");
if (element != null && element.exists()) {
return Collections.singletonList(new JavaElementHyperlink(region, element));
}
} else if (region.getTagName().equals("my:button") && region.getAttrName().equals("action")) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(project.getFile("your/xml/path").getContents());
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "your/expression";
Node controller = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
// 自行實作
}
} catch (Exception e) {
}
}

return null;
}

@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
if (region != null && textViewer != null) {
IDocument document = textViewer.getDocument();
ITextFileBuffer textFileBuffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
if (textFileBuffer != null) {
IPath basePath = textFileBuffer.getLocation();
if (basePath != null && !basePath.isEmpty()) {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(basePath.segment(0));
try {
if (basePath.segmentCount() > 1 && project.isAccessible()
&& project.hasNature(JavaCore.NATURE_ID)) {

NodeRegion hyperlinkRegion = selectQualifiedName(document, region.getOffset());
if (hyperlinkRegion == null || isJspJavaContent(document, hyperlinkRegion)) {
return null;
}
String name = null;
try {
name = document.get(hyperlinkRegion.getOffset(), hyperlinkRegion.getLength()).trim();
} catch (BadLocationException badLocationException) {
}

if (name != null && !name.isEmpty()) {
List<IHyperlink> links = createHyperlink(project, basePath, name, hyperlinkRegion);
if (links != null) {
Object array = Array.newInstance(IHyperlink.class, links.size());
return (IHyperlink[]) links.toArray((Object[])array);
}
}
}
} catch (CoreException e) {
}
}
}
}

return null;
}

private NodeRegion selectQualifiedName(IDocument document, int anchor) {
try {
int offset = anchor;

while (offset >= 0) {
char c = document.getChar(offset);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
offset--;
}

int start = offset;

offset = anchor;
int length = document.getLength();

while (offset < length) {
char c = document.getChar(offset);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
offset++;
}

int end = offset;

if (start == end) {
return null;
}

// 往前找屬性名稱
offset = start;
int attrEnd = start;

while (offset >= 0) {
char c = document.getChar(offset);
if (c == '=')
attrEnd = offset;
else if (c == ' ')
break;
offset--;
}

int attrStart = offset;
String attrName = document.get(attrStart + 1, attrEnd - attrStart - 1);

// 往前找Tag名稱
while (offset >= 0) {
char c = document.getChar(offset);
if (c == '<')
break;
offset--;
}

int tagStart = offset;

while (offset < attrStart) {
char c = document.getChar(offset);
if (c == ' ')
break;
offset++;
}

int tagEnd = offset;
String tagName = document.get(tagStart + 1, tagEnd - tagStart - 1);

return new NodeRegion(start + 1, end - start - 1, tagName, attrName);

} catch (BadLocationException badLocationException) {
return null;
}
}
}