-
Notifications
You must be signed in to change notification settings - Fork 9
/
ProjectSpecificLanguageServerWrapper.java
360 lines (336 loc) · 12.5 KB
/
ProjectSpecificLanguageServerWrapper.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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*******************************************************************************
* Copyright (c) 2016 Red Hat Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mickael Istria (Red Hat Inc.) - initial implementation
*******************************************************************************/
package org.eclipse.languageserver;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.languageserver.operations.diagnostics.LSPDiagnosticsToMarkers;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.internal.progress.ProgressMonitorFocusJobDialog;
import io.typefox.lsapi.InitializeResult;
import io.typefox.lsapi.Message;
import io.typefox.lsapi.ServerCapabilities;
import io.typefox.lsapi.TextDocumentContentChangeEvent;
import io.typefox.lsapi.TextDocumentSyncKind;
import io.typefox.lsapi.impl.ClientCapabilitiesImpl;
import io.typefox.lsapi.impl.DidChangeTextDocumentParamsImpl;
import io.typefox.lsapi.impl.DidOpenTextDocumentParamsImpl;
import io.typefox.lsapi.impl.InitializeParamsImpl;
import io.typefox.lsapi.impl.RangeImpl;
import io.typefox.lsapi.impl.TextDocumentContentChangeEventImpl;
import io.typefox.lsapi.impl.TextDocumentItemImpl;
import io.typefox.lsapi.impl.VersionedTextDocumentIdentifierImpl;
import io.typefox.lsapi.services.json.InvalidMessageException;
import io.typefox.lsapi.services.json.MessageJsonHandler;
import io.typefox.lsapi.services.json.StreamMessageReader;
import io.typefox.lsapi.services.json.StreamMessageWriter;
import io.typefox.lsapi.services.transport.client.LanguageClientEndpoint;
import io.typefox.lsapi.services.transport.io.ConcurrentMessageReader;
import io.typefox.lsapi.services.transport.io.MessageWriter;
import io.typefox.lsapi.services.transport.trace.MessageTracer;
/**
* Wraps instantiation, initialization of project-specific instance of the
* language server
*/
public class ProjectSpecificLanguageServerWrapper {
private final class DocumentChangeListenenr implements IDocumentListener {
private URI fileURI;
private int version = 2;
private DidChangeTextDocumentParamsImpl change;
public DocumentChangeListenenr(URI fileURI) {
this.fileURI = fileURI;
}
@Override
public void documentChanged(DocumentEvent event) {
if (this.change == null) {
return;
}
this.change.getContentChanges().get(0).setText(event.getDocument().get());
languageClient.getTextDocumentService().didChange(this.change);
version++;
}
@Override
public void documentAboutToBeChanged(DocumentEvent event) {
// create change event according synch
TextDocumentContentChangeEventImpl changeEvent = toChangeEvent(event);
if (changeEvent == null) {
return;
}
this.change = new DidChangeTextDocumentParamsImpl();
VersionedTextDocumentIdentifierImpl doc = new VersionedTextDocumentIdentifierImpl();
doc.setUri(fileURI.toString());
doc.setVersion(version);
this.change.setTextDocument(doc);
this.change.setContentChanges(Arrays.asList(new TextDocumentContentChangeEventImpl[] { changeEvent }));
}
/**
* Convert Eclipse {@link DocumentEvent} to LS according
* {@link TextDocumentSyncKind}.
* {@link TextDocumentContentChangeEventImpl}.
*
* @param event
* Eclipse {@link DocumentEvent}
* @return the converted LS {@link TextDocumentContentChangeEventImpl}.
*/
private TextDocumentContentChangeEventImpl toChangeEvent(DocumentEvent event) {
IDocument document = event.getDocument();
TextDocumentContentChangeEventImpl changeEvent = null;
TextDocumentSyncKind syncKind = getTextDocumentSyncKind();
switch (syncKind) {
case None:
changeEvent = null;
break;
case Full:
changeEvent = new TextDocumentContentChangeEventImpl();
changeEvent.setText(document.get());
break;
case Incremental:
changeEvent = new TextDocumentContentChangeEventImpl();
String newText = event.getText();
int offset = event.getOffset();
int length = event.getLength();
try {
// try to convert the Eclipse start/end offset to LS range.
RangeImpl range = new RangeImpl(LSPEclipseUtils.toPosition(offset, document),
LSPEclipseUtils.toPosition(offset + length, document));
changeEvent.setRange(range);
changeEvent.setText(newText);
changeEvent.setRangeLength(length);
} catch (BadLocationException e) {
// error while conversion (should never occur)
// set the full document text as changes.
changeEvent.setText(document.get());
}
break;
}
return changeEvent;
}
/**
* Returns the text document sync kind capabilities of the server and
* {@link TextDocumentSyncKind#Full} otherwise.
*
* @return the text document sync kind capabilities of the server and
* {@link TextDocumentSyncKind#Full} otherwise.
*/
private TextDocumentSyncKind getTextDocumentSyncKind() {
TextDocumentSyncKind syncKind = initializeResult != null
? initializeResult.getCapabilities().getTextDocumentSync() : null;
return syncKind != null ? syncKind : TextDocumentSyncKind.Full;
}
}
final private StreamConnectionProvider lspStreamProvider;
private LanguageClientEndpoint languageClient;
private IProject project;
private Map<IPath, DocumentChangeListenenr> connectedFiles;
private Map<IPath, IDocument> documents;
private Job initializeJob;
private InitializeResult initializeResult;
public ProjectSpecificLanguageServerWrapper(IProject project, StreamConnectionProvider connection) {
this.project = project;
this.lspStreamProvider = connection;
this.connectedFiles = new HashMap<>();
this.documents = new HashMap<>();
}
private void start() throws IOException {
if (this.languageClient != null) {
if (stillActive()) {
return;
} else {
stop();
}
}
try {
ExecutorService executorService = Executors.newCachedThreadPool();
this.languageClient = new LanguageClientEndpoint(executorService);
this.languageClient.setMessageTracer(new MessageTracer() {
@Override
public void onWrite(Message message, String json) {
if (json.contains("telemetry/event")) {
return;
}
System.out.println("WRITE: ");
System.out.println(json);
System.out.println(message);
System.out.println("");
}
@Override
public void onRead(Message message, String json) {
if (json.contains("telemetry/event")) {
return;
}
System.out.println("READ: ");
System.out.println(json);
System.out.println(message);
System.out.println("");
}
@Override
public void onError(String message, Throwable throwable) {
System.err.println("ERR:");
System.err.println("message: " + message);
System.err.println("ex: " );
if (throwable != null) {
throwable.printStackTrace(System.err);
}
if (throwable instanceof InvalidMessageException) {
//System.err.println("json unavailable, see https://github.com/TypeFox/ls-api/issues/51");
System.err.println("json: " + ((InvalidMessageException)throwable).getJson());
}
}
});
this.lspStreamProvider.start();
MessageJsonHandler jsonHandler = new MessageJsonHandler();
jsonHandler.setMethodResolver(this.languageClient);
StreamMessageReader baseMessageReader = new StreamMessageReader(this.lspStreamProvider.getInputStream(), jsonHandler);
ConcurrentMessageReader multiThreadReader = new ConcurrentMessageReader(baseMessageReader, executorService);
MessageWriter writer = new StreamMessageWriter(this.lspStreamProvider.getOutputStream(), jsonHandler);
languageClient.connect(multiThreadReader, writer);
this.initializeJob = new Job("Initialize language server") {
protected IStatus run(IProgressMonitor monitor) {
InitializeParamsImpl initParams = new InitializeParamsImpl();
initParams.setRootPath(project.getLocation().toFile().getAbsolutePath());
String name = "Eclipse IDE";
if (Platform.getProduct() != null) {
name = Platform.getProduct().getName();
}
initParams.setClientName(name);
initParams.setCapabilities(new ClientCapabilitiesImpl());
connectDiagnostics();
CompletableFuture<InitializeResult> result = languageClient.initialize(initParams);
try {
initializeResult = result.get();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Status.OK_STATUS;
}
};
this.initializeJob.setUser(true);
this.initializeJob.setSystem(false);
this.initializeJob.schedule();
} catch (Exception ex) {
ex.printStackTrace();
stop();
}
}
private boolean stillActive() {
if (this.languageClient == null || this.languageClient.getReader() == null) {
return false;
}
return ((ConcurrentMessageReader)this.languageClient.getReader()).isRunning();
}
private void connectDiagnostics() {
this.languageClient.getTextDocumentService().onPublishDiagnostics(new LSPDiagnosticsToMarkers(this.project));
}
private void stop() {
if (this.initializeJob != null) {
this.initializeJob.cancel();
}
this.initializeJob = null;
this.initializeResult = null;
if (this.languageClient != null) {
this.languageClient.shutdown();
if (this.languageClient.getReader() != null) {
this.languageClient.getReader().close();
}
if (this.languageClient.getWriter() != null) {
this.languageClient.getWriter().close();
}
}
if (this.lspStreamProvider != null) {
this.lspStreamProvider.stop();
}
while (!this.documents.isEmpty()) {
disconnect(this.documents.keySet().iterator().next());
}
this.languageClient = null;
}
public void connect(IFile file, final IDocument document) throws IOException {
start();
if (this.connectedFiles.containsKey(file.getLocation())) {
return;
}
// add a document buffer
DidOpenTextDocumentParamsImpl open = new DidOpenTextDocumentParamsImpl();
TextDocumentItemImpl textDocument = new TextDocumentItemImpl();
textDocument.setUri(file.getLocationURI().toString());
textDocument.setText(document.get());
textDocument.setLanguageId(file.getFileExtension());
open.setTextDocument(textDocument);
try {
this.initializeJob.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.languageClient.getTextDocumentService().didOpen(open);
DocumentChangeListenenr listener = new DocumentChangeListenenr(file.getLocationURI());
document.addDocumentListener(listener);
this.connectedFiles.put(file.getLocation(), listener);
this.documents.put(file.getLocation(), document);
}
public void disconnect(IPath path) {
this.documents.get(path).removeDocumentListener(this.connectedFiles.get(path));
this.connectedFiles.remove(path);
this.documents.remove(path);
if (this.connectedFiles.isEmpty()) {
stop();
}
}
public LanguageClientEndpoint getServer() {
if (this.initializeJob.getState() != Job.NONE) {
if (Display.getCurrent() != null) { // UI Thread
ProgressMonitorFocusJobDialog dialog = new ProgressMonitorFocusJobDialog(null);
dialog.setBlockOnOpen(true);
dialog.show(this.initializeJob, null);
}
try {
this.initializeJob.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return languageClient;
}
public ServerCapabilities getServerCapabilities() {
try {
start();
this.initializeJob.join(1000, new NullProgressMonitor());
} catch (InterruptedException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (this.initializeResult != null) {
return this.initializeResult.getCapabilities();
} else {
return null;
}
}
}