forked from flutter/flutter-intellij
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlutterDartAnalysisServer.java
324 lines (282 loc) · 11.7 KB
/
FlutterDartAnalysisServer.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
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.dart;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.dart.server.AnalysisServerListenerAdapter;
import com.google.dart.server.ResponseListener;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import io.flutter.utils.JsonUtils;
import org.dartlang.analysis.server.protocol.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class FlutterDartAnalysisServer implements Disposable {
private static final String FLUTTER_NOTIFICATION_OUTLINE = "flutter.outline";
private static final String FLUTTER_NOTIFICATION_OUTLINE_KEY = "\"flutter.outline\"";
@NotNull final Project project;
/**
* Each key is a notification identifier.
* Each value is the set of files subscribed to the notification.
*/
private final Map<String, List<String>> subscriptions = new HashMap<>();
@VisibleForTesting
protected final Map<String, List<FlutterOutlineListener>> fileOutlineListeners = new HashMap<>();
/**
* Each key is a request identifier.
* Each value is the {@link Consumer} for the response.
*/
private final Map<String, Consumer<JsonObject>> responseConsumers = new HashMap<>();
private boolean isDisposed = false;
@NotNull
public static FlutterDartAnalysisServer getInstance(@NotNull final Project project) {
return Objects.requireNonNull(project.getService(FlutterDartAnalysisServer.class));
}
@NotNull
public DartAnalysisServerService getAnalysisService() {
return Objects.requireNonNull(DartPlugin.getInstance().getAnalysisService(project));
}
@NotNull
public String getSdkVersion() {
return getAnalysisService().getSdkVersion();
}
/** @noinspection BooleanMethodIsAlwaysInverted*/
public boolean isServerConnected() {
return !getSdkVersion().isEmpty();
}
@VisibleForTesting
public FlutterDartAnalysisServer(@NotNull Project project) {
this.project = project;
DartAnalysisServerService analysisService = getAnalysisService();
analysisService.addResponseListener(new CompatibleResponseListener());
analysisService.addAnalysisServerListener(new AnalysisServerListenerAdapter() {
private boolean hasComputedErrors = false;
@Override
public void serverConnected(String s) {
// If the server reconnected we need to let it know that we still care
// about our subscriptions.
if (!subscriptions.isEmpty()) {
sendSubscriptions();
}
// TODO(jwren) at this point the Dart Analysis Server Service is connected and isServerConnected() will return true, however
// the Flutter Plugin may have already called addOutlineListener (or other methods). If addOutlineListener is called before the
// server is connected, this method should follow up with those calls to undo the race condition.
}
@Override
public void computedErrors(String file, List<AnalysisError> errors) {
if (!hasComputedErrors && project.isOpen()) {
hasComputedErrors = true;
}
super.computedErrors(file, errors);
}
});
Disposer.register(project, this);
}
public void addOutlineListener(@NotNull final String filePath, @NotNull final FlutterOutlineListener listener) {
if(!isServerConnected()) {
return;
}
synchronized (fileOutlineListeners) {
final List<FlutterOutlineListener> listeners = fileOutlineListeners.computeIfAbsent(getAnalysisService().getLocalFileUri(filePath), k -> new ArrayList<>());
listeners.add(listener);
}
addSubscription(FlutterService.OUTLINE, filePath);
}
public void removeOutlineListener(@NotNull final String filePath, @NotNull final FlutterOutlineListener listener) {
if(!isServerConnected()) {
return;
}
final boolean removeSubscription;
synchronized (fileOutlineListeners) {
final List<FlutterOutlineListener> listeners = fileOutlineListeners.get(filePath);
removeSubscription = listeners != null && listeners.remove(listener);
}
if (removeSubscription) {
removeSubscription(FlutterService.OUTLINE, filePath);
}
}
/**
* Adds a flutter event subscription to the analysis server.
* <p>
* Note that <code>filePath</code> must be an absolute path.
*/
private void addSubscription(@NotNull final String service, @NotNull final String filePath) {
if(!isServerConnected()) {
return;
}
final List<String> files = subscriptions.computeIfAbsent(service, k -> new ArrayList<>());
final String filePathOrUri = getAnalysisService().getLocalFileUri(filePath);
if (!files.contains(filePathOrUri)) {
files.add(filePathOrUri);
sendSubscriptions();
}
}
/**
* Removes a flutter event subscription from the analysis server.
* <p>
* Note that <code>filePath</code> must be an absolute path.
*/
private void removeSubscription(@NotNull final String service, @NotNull final String filePath) {
if(!isServerConnected()) {
return;
}
final String filePathOrUri = getAnalysisService().getLocalFileUri(filePath);
final List<String> files = subscriptions.get(service);
if (files != null && files.remove(filePathOrUri)) {
sendSubscriptions();
}
}
private void sendSubscriptions() {
if(!isServerConnected()) {
return;
}
DartAnalysisServerService analysisService = getAnalysisService();
final String id = analysisService.generateUniqueId();
analysisService.sendRequest(id, FlutterRequestUtilities.generateAnalysisSetSubscriptions(id, subscriptions));
}
@NotNull
public List<SourceChange> edit_getAssists(@NotNull VirtualFile file, int offset, int length) {
DartAnalysisServerService analysisService = getAnalysisService();
return analysisService.edit_getAssists(file, offset, length);
}
@Nullable
public CompletableFuture<List<FlutterWidgetProperty>> getWidgetDescription(@NotNull VirtualFile file, int _offset) {
final CompletableFuture<List<FlutterWidgetProperty>> result = new CompletableFuture<>();
final String filePath = FileUtil.toSystemDependentName(file.getPath());
DartAnalysisServerService analysisService = getAnalysisService();
final int offset = analysisService.getOriginalOffset(file, _offset);
final String id = analysisService.generateUniqueId();
synchronized (responseConsumers) {
responseConsumers.put(id, (resultObject) -> {
try {
final JsonArray propertiesObject = resultObject.getAsJsonArray("properties");
final ArrayList<FlutterWidgetProperty> properties = new ArrayList<>();
for (JsonElement propertyObject : propertiesObject) {
properties.add(FlutterWidgetProperty.fromJson(propertyObject.getAsJsonObject()));
}
result.complete(properties);
}
catch (Throwable ignored) {
}
});
}
final JsonObject request = FlutterRequestUtilities.generateFlutterGetWidgetDescription(id, filePath, offset);
analysisService.sendRequest(id, request);
return result;
}
@Nullable
public SourceChange setWidgetPropertyValue(int propertyId, FlutterWidgetPropertyValue value) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<SourceChange> result = new AtomicReference<>();
DartAnalysisServerService analysisService = getAnalysisService();
final String id = analysisService.generateUniqueId();
synchronized (responseConsumers) {
responseConsumers.put(id, (resultObject) -> {
try {
final JsonObject propertiesObject = resultObject.getAsJsonObject("change");
result.set(SourceChange.fromJson(propertiesObject));
}
catch (Throwable ignored) {
}
latch.countDown();
});
}
final JsonObject request = FlutterRequestUtilities.generateFlutterSetWidgetPropertyValue(id, propertyId, value);
analysisService.sendRequest(id, request);
Uninterruptibles.awaitUninterruptibly(latch, 100, TimeUnit.MILLISECONDS);
return result.get();
}
private void processString(String jsonString) {
if (isDisposed) return;
ApplicationManager.getApplication().executeOnPooledThread(() -> {
// Short circuit just in case we have been disposed in the time it took
// for us to get around to listening for the response.
if (isDisposed) return;
processResponse(JsonUtils.parseString(jsonString).getAsJsonObject());
});
}
/**
* Handle the given {@link JsonObject} response.
*/
private void processResponse(JsonObject response) {
final JsonElement eventName = response.get("event");
if (eventName != null && eventName.isJsonPrimitive()) {
processNotification(response, eventName);
return;
}
if (response.has("error")) {
return;
}
final JsonObject resultObject = response.getAsJsonObject("result");
if (resultObject == null) {
return;
}
final JsonPrimitive idJsonPrimitive = (JsonPrimitive)response.get("id");
if (idJsonPrimitive == null) {
return;
}
final String idString = idJsonPrimitive.getAsString();
final Consumer<JsonObject> consumer;
synchronized (responseConsumers) {
consumer = responseConsumers.remove(idString);
}
if (consumer == null) {
return;
}
consumer.consume(resultObject);
}
/**
* Attempts to handle the given {@link JsonObject} as a notification.
*/
private void processNotification(JsonObject response, @NotNull JsonElement eventName) {
// If we add code to handle more event types below, update the filter in processString().
final String event = eventName.getAsString();
if (Objects.equals(event, FLUTTER_NOTIFICATION_OUTLINE)) {
final JsonObject paramsObject = response.get("params").getAsJsonObject();
final String file = paramsObject.get("file").getAsString();
final JsonElement instrumentedCodeElement = paramsObject.get("instrumentedCode");
final String instrumentedCode = instrumentedCodeElement != null ? instrumentedCodeElement.getAsString() : null;
final JsonObject outlineObject = paramsObject.get("outline").getAsJsonObject();
final FlutterOutline outline = FlutterOutline.fromJson(outlineObject);
final List<FlutterOutlineListener> listenersUpdated;
synchronized (fileOutlineListeners) {
final List<FlutterOutlineListener> listeners = fileOutlineListeners.get(file);
listenersUpdated = listeners != null ? Lists.newArrayList(listeners) : null;
}
if (listenersUpdated != null) {
for (FlutterOutlineListener listener : listenersUpdated) {
listener.outlineUpdated(file, outline, instrumentedCode);
}
}
}
}
class CompatibleResponseListener implements ResponseListener {
@SuppressWarnings({"override", "RedundantSuppression"})
public void onResponse(String jsonString) {
processString(jsonString);
}
}
@Override
public void dispose() {
isDisposed = true;
}
}