-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathDartAnalysisServerService.java
2530 lines (2135 loc) · 97.1 KB
/
DartAnalysisServerService.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.lang.dart.analyzer;
import com.google.common.collect.EvictingQueue;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.dart.server.*;
import com.google.dart.server.generated.AnalysisServer;
import com.google.dart.server.internal.remote.DebugPrintStream;
import com.google.dart.server.internal.remote.RemoteAnalysisServerImpl;
import com.google.dart.server.internal.remote.StdioServerSocket;
import com.google.dart.server.utilities.logging.Logging;
import com.google.gson.JsonObject;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.fileEditor.impl.FileOffsetsManager;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.Consumer;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.lang.dart.DartBundle;
import com.jetbrains.lang.dart.DartFileType;
import com.jetbrains.lang.dart.assists.DartQuickAssistIntention;
import com.jetbrains.lang.dart.assists.DartQuickAssistIntentionListener;
import com.jetbrains.lang.dart.fixes.DartQuickFix;
import com.jetbrains.lang.dart.fixes.DartQuickFixListener;
import com.jetbrains.lang.dart.ide.actions.DartPubActionBase;
import com.jetbrains.lang.dart.ide.completion.DartCompletionTimerExtension;
import com.jetbrains.lang.dart.ide.errorTreeView.DartProblemsView;
import com.jetbrains.lang.dart.ide.template.postfix.DartPostfixTemplateProvider;
import com.jetbrains.lang.dart.sdk.DartSdk;
import com.jetbrains.lang.dart.sdk.DartSdkUpdateChecker;
import com.jetbrains.lang.dart.sdk.DartSdkUtil;
import com.jetbrains.lang.dart.util.PubspecYamlUtil;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.dartlang.analysis.server.protocol.*;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public final class DartAnalysisServerService implements Disposable {
public static final String MIN_SDK_VERSION = "1.12";
private static final String MIN_MOVE_FILE_SDK_VERSION = "2.3.2";
private static final String COMPLETION_2_SERVER_VERSION = "1.33";
// Webdev works going back to 2.6.0, future minimum version listed in the pubspec.yaml, link below, won't mean that 2.6.0 aren't
// supported.
// https://github.com/dart-lang/webdev/blob/master/webdev/pubspec.yaml#L11
public static final String MIN_WEBDEV_SDK_VERSION = "2.6.0";
// As of the Dart SDK version 2.8.0, the file .dart_tool/package_config.json is preferred over the .packages file.
// https://github.com/dart-lang/sdk/issues/48272
public static final String MIN_PACKAGE_CONFIG_JSON_SDK_VERSION = "2.8.0";
// The dart cli command provides a language server command, `dart language-server`, which
// should be used going forward instead of `dart .../analysis_server.dart.snapshot`.
public static final String MIN_DART_LANG_SERVER_SDK_VERSION = "2.16.0";
private static final long UPDATE_FILES_TIMEOUT = 300;
private static final long CHECK_CANCELLED_PERIOD = 10;
private static final long SEND_REQUEST_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
private static final long EDIT_FORMAT_TIMEOUT = TimeUnit.SECONDS.toMillis(3);
private static final long EDIT_ORGANIZE_DIRECTIVES_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(300);
private static final long EDIT_SORT_MEMBERS_TIMEOUT = TimeUnit.SECONDS.toMillis(3);
private static final long GET_HOVER_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
private static final long GET_NAVIGATION_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
private static final long GET_ASSISTS_TIMEOUT_EDT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long GET_ASSISTS_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1000);
private static final long GET_FIXES_TIMEOUT_EDT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long GET_FIXES_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(1000);
private static final long IMPORTED_ELEMENTS_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long POSTFIX_COMPLETION_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long POSTFIX_INITIALIZATION_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(5000);
private static final long STATEMENT_COMPLETION_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long GET_SUGGESTIONS_TIMEOUT = TimeUnit.SECONDS.toMillis(5);
private static final long GET_SUGGESTION_DETAILS_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long GET_SUGGESTION_DETAILS2_TIMEOUT = TimeUnit.MILLISECONDS.toMillis(100);
private static final long FIND_ELEMENT_REFERENCES_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
private static final long GET_TYPE_HIERARCHY_TIMEOUT = TimeUnit.SECONDS.toMillis(10);
private static final long EXECUTION_CREATE_CONTEXT_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
private static final long EXECUTION_MAP_URI_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
private static final long ANALYSIS_IN_TESTS_TIMEOUT = TimeUnit.SECONDS.toMillis(10);
private static final long TESTS_TIMEOUT_COEFF = 10;
private static final Logger LOG = Logger.getInstance(DartAnalysisServerService.class);
private static final int DEBUG_LOG_CAPACITY = 30;
private static final int MAX_DEBUG_LOG_LINE_LENGTH = 200; // Saw one line while testing that was > 50k
@NotNull private final Project myProject;
private boolean myInitializationOnServerStartupDone;
private boolean mySubscribeToServerLog;
// Do not wait for server response under lock. Do not take read/write action under lock.
private final Object myLock = new Object();
@Nullable private RemoteAnalysisServerImpl myServer;
@Nullable private StdioServerSocket myServerSocket;
@NotNull private String myServerVersion = "";
@NotNull private String mySdkVersion = "";
//private boolean myDoEnableMLBasedCodeCompletion = false;
@Nullable private String mySdkHome;
private final DartServerRootsHandler myRootsHandler;
private final Map<String, Long> myFilePathWithOverlaidContentToTimestamp = new HashMap<>();
private final List<String> myVisibleFiles = new ArrayList<>();
private final Set<Document> myChangedDocuments = new HashSet<>();
private final Alarm myUpdateFilesAlarm;
@NotNull private final Queue<CompletionInfo> myCompletionInfos = new LinkedList<>();
@NotNull private final Queue<SearchResultsSet> mySearchResultSets = new LinkedList<>();
@NotNull private final DartServerData myServerData;
private volatile boolean myAnalysisInProgress;
private volatile boolean myPubListInProgress;
@NotNull private final Alarm myShowServerProgressAlarm;
@NotNull private final DartAnalysisServerErrorHandler myServerErrorHandler;
@Nullable private ProgressIndicator myProgressIndicator;
private final Object myProgressLock = new Object();
private boolean myHaveShownInitialProgress;
private boolean mySentAnalysisBusy;
// files with red squiggles in Project View. This field is also used as a lock to access these 3 collections
@NotNull private final Set<String> myFilePathsWithErrors = new HashSet<>();
// how many files with errors are in this folder (recursively)
@NotNull private final Object2IntMap<String> myFolderPathsWithErrors = new Object2IntOpenHashMap<>();
// errors hash is tracked to optimize error notification listener: do not handle equal notifications more than once
@NotNull private final Object2IntMap<String> myFilePathToErrorsHash = new Object2IntOpenHashMap<>();
@NotNull private final EvictingQueue<String> myDebugLog = EvictingQueue.create(DEBUG_LOG_CAPACITY);
private boolean myDisposed;
private final @NotNull Condition<?> myDisposedCondition = o -> myDisposed;
public static String getClientId() {
return ApplicationNamesInfo.getInstance().getFullProductName().replace(' ', '-');
}
private static String getClientVersion() {
return ApplicationInfo.getInstance().getApiVersion();
}
@NotNull private final List<AnalysisServerListener> myAdditionalServerListeners = new SmartList<>();
@NotNull private final List<RequestListener> myRequestListeners = new SmartList<>();
@NotNull private final List<ResponseListener> myResponseListeners = new SmartList<>();
@NotNull private final List<DartQuickAssistIntentionListener> myQuickAssistIntentionListeners = new SmartList<>();
@NotNull private final List<DartQuickFixListener> myQuickFixListeners = new SmartList<>();
private final AnalysisServerListener myAnalysisServerListener = new AnalysisServerListenerAdapter() {
@Override
public void computedAvailableSuggestions(@NotNull List<AvailableSuggestionSet> changed, int @NotNull [] removed) {
myServerData.computedAvailableSuggestions(changed, removed);
}
@Override
public void computedExistingImports(@NotNull String filePathSD, @NotNull Map<String, Map<String, Set<String>>> existingImports) {
myServerData.computedExistingImports(filePathSD, existingImports);
}
@Override
public void computedErrors(@NotNull final String filePathSD, @NotNull final List<AnalysisError> errors) {
final String fileName = PathUtil.getFileName(filePathSD);
final ProgressIndicator indicator = myProgressIndicator;
if (indicator != null) {
indicator.setText(DartBundle.message("dart.analysis.progress.with.file", fileName));
}
final List<AnalysisError> errorsWithoutTodo = errors.isEmpty() ? Collections.emptyList() : new ArrayList<>(errors.size());
boolean hasSevereProblems = false;
for (AnalysisError error : errors) {
if (AnalysisErrorSeverity.ERROR.equals(error.getSeverity())) {
hasSevereProblems = true;
}
if (!AnalysisErrorType.TODO.equals(error.getType())) {
errorsWithoutTodo.add(error);
}
}
final String filePathSI = FileUtil.toSystemIndependentName(filePathSD);
final int oldHash;
synchronized (myFilePathsWithErrors) {
// TObjectIntHashMap returns 0 if there's no such entry, it's equivalent to empty error set for this file
oldHash = myFilePathToErrorsHash.getInt(filePathSI);
}
final int newHash = errorsWithoutTodo.isEmpty() ? 0 : ensureNotZero(errorsWithoutTodo.hashCode());
// do nothing if errors are the same as were already handled previously
if (oldHash == newHash && !myServerData.isErrorInfoInaccurate(filePathSI)) return;
final boolean visible = myVisibleFiles.contains(filePathSD);
if (myServerData.computedErrors(filePathSI, errorsWithoutTodo, visible)) {
onErrorsUpdated(filePathSI, errorsWithoutTodo, hasSevereProblems, newHash);
}
}
@Override
public void computedHighlights(@NotNull final String filePath, @NotNull final List<HighlightRegion> regions) {
myServerData.computedHighlights(FileUtil.toSystemIndependentName(filePath), regions);
}
@Override
public void computedClosingLabels(@NotNull final String filePath, List<ClosingLabel> labels) {
myServerData.computedClosingLabels(FileUtil.toSystemIndependentName(filePath), labels);
}
@Override
public void computedImplemented(String _filePath,
List<ImplementedClass> implementedClasses,
List<ImplementedMember> implementedMembers) {
myServerData.computedImplemented(FileUtil.toSystemIndependentName(_filePath), implementedClasses, implementedMembers);
}
@Override
public void computedNavigation(@NotNull final String _filePath, @NotNull final List<NavigationRegion> regions) {
myServerData.computedNavigation(FileUtil.toSystemIndependentName(_filePath), regions);
}
@Override
public void computedOverrides(@NotNull final String _filePath, @NotNull final List<OverrideMember> overrides) {
myServerData.computedOverrides(FileUtil.toSystemIndependentName(_filePath), overrides);
}
@Override
public void computedOutline(@NotNull final String _filePath, @NotNull final Outline outline) {
myServerData.computedOutline(FileUtil.toSystemIndependentName(_filePath), outline);
}
@Override
public void flushedResults(@NotNull final List<String> _filePaths) {
final List<String> filePaths = new ArrayList<>(_filePaths.size());
for (String path : _filePaths) {
filePaths.add(FileUtil.toSystemIndependentName(path));
}
myServerData.onFlushedResults(filePaths);
for (String filePath : filePaths) {
onErrorsUpdated(filePath, AnalysisError.EMPTY_LIST, false, 0);
}
}
@Override
public void computedCompletion(@NotNull final String completionId,
final int replacementOffset,
final int replacementLength,
@NotNull final List<CompletionSuggestion> completions,
@NotNull final List<IncludedSuggestionSet> includedSuggestionSets,
@NotNull final List<String> includedElementKinds,
@NotNull final List<IncludedSuggestionRelevanceTag> includedSuggestionRelevanceTags,
final boolean isLast,
@Nullable final String libraryFilePathSD) {
synchronized (myCompletionInfos) {
myCompletionInfos.add(new CompletionInfo(completionId, replacementOffset, replacementLength, completions, includedSuggestionSets,
includedElementKinds, includedSuggestionRelevanceTags, isLast, libraryFilePathSD));
myCompletionInfos.notifyAll();
}
}
@Override
public void computedSearchResults(String searchId, List<SearchResult> results, boolean last) {
synchronized (mySearchResultSets) {
mySearchResultSets.add(new SearchResultsSet(searchId, results, last));
mySearchResultSets.notifyAll();
}
}
@Override
public void serverConnected(@Nullable String version) {
myServerVersion = version != null ? version : "";
// completion_setSubscriptions() are handled here instead of in startServer() as the server version isn't known until this
// serverConnected() call.
if (myServer != null && !shouldUseCompletion2()) {
myServer.completion_setSubscriptions(List.of(CompletionService.AVAILABLE_SUGGESTION_SETS));
}
}
@Override
public void requestError(RequestError error) {
if (RequestErrorCode.SERVER_ERROR.equals(error.getCode())) {
serverError(false, error.getMessage(), error.getStackTrace());
}
else {
LOG.info(getShortErrorMessage("unknown", null, error));
}
}
@Override
public void serverError(boolean isFatal, @Nullable String message, @NonNls @Nullable String stackTrace) {
if (message == null) {
message = DartBundle.message("issue.occurred.with.analysis.server");
}
if (!isFatal &&
stackTrace != null &&
stackTrace.startsWith("#0 checkValidPackageUri (package:package_config/src/util.dart:72)")) {
return;
}
String sdkVersion = mySdkVersion.isEmpty() ? null : mySdkVersion;
StringBuilder debugLog = new StringBuilder();
synchronized (myDebugLog) {
for (String s : myDebugLog) {
debugLog.append(s).append('\n');
}
}
myServerErrorHandler.handleError(message, stackTrace, isFatal, sdkVersion, debugLog.length() == 0 ? null : debugLog.toString());
}
@Override
public void serverStatus(@Nullable final AnalysisStatus analysisStatus, @Nullable final PubStatus pubStatus) {
final boolean wasBusy = myAnalysisInProgress || myPubListInProgress;
if (analysisStatus != null) myAnalysisInProgress = analysisStatus.isAnalyzing();
if (pubStatus != null) myPubListInProgress = pubStatus.isListingPackageDirs();
if (!wasBusy && (myAnalysisInProgress || myPubListInProgress)) {
final Runnable delayedRunnable = () -> {
if (myAnalysisInProgress || myPubListInProgress) {
startShowingServerProgress();
}
};
// 50ms delay to minimize blinking in case of consequent start-stop-start-stop-... events that happen with pubStatus events
// 300ms delay to avoid showing progress for very fast analysis start-stop cycle that happens with analysisStatus events
final int delay = pubStatus != null && pubStatus.isListingPackageDirs() ? 50 : 300;
myShowServerProgressAlarm.addRequest(delayedRunnable, delay, ModalityState.any());
}
if (!myAnalysisInProgress && !myPubListInProgress) {
stopShowingServerProgress();
}
}
};
private static int ensureNotZero(int i) {
return i == 0 ? Integer.MAX_VALUE : i;
}
private void startShowingServerProgress() {
if (!myHaveShownInitialProgress) {
myHaveShownInitialProgress = true;
final Task.Backgroundable task = new Task.Backgroundable(myProject, DartBundle.message("dart.analysis.progress.title"), false) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
if (DartAnalysisServerService.this.myProject.isDisposed()) return;
if (!myAnalysisInProgress && !myPubListInProgress) return;
indicator.setText(DartBundle.message("dart.analysis.progress.title"));
if (ApplicationManager.getApplication().isDispatchThread()) {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
LOG.error("wait() in EDT");
}
}
else {
try {
myProgressIndicator = indicator;
waitWhileServerBusy();
}
finally {
myProgressIndicator = null;
}
}
}
};
ProgressManager.getInstance().run(task);
}
DartAnalysisServerMessages.sendAnalysisStarted(myProject, true);
mySentAnalysisBusy = true;
}
/**
* Must use it each time right after reading any offset or length from any class from org.dartlang.analysis.server.protocol package
*/
public int getConvertedOffset(@Nullable final VirtualFile file, final int originalOffset) {
if (originalOffset <= 0 || file == null) return originalOffset;
return myFilePathWithOverlaidContentToTimestamp.containsKey(file.getPath())
? originalOffset
: FileOffsetsManager.getInstance().getConvertedOffset(file, originalOffset);
}
/**
* Must use it right before sending any offsets and lengths to the AnalysisServer
*/
public int getOriginalOffset(@Nullable final VirtualFile file, final int convertedOffset) {
if (file == null) return convertedOffset;
return myFilePathWithOverlaidContentToTimestamp.containsKey(file.getPath())
? convertedOffset
: FileOffsetsManager.getInstance().getOriginalOffset(file, convertedOffset);
}
public int[] getConvertedOffsets(@NotNull final VirtualFile file, final int[] _offsets) {
final int[] offsets = new int[_offsets.length];
for (int i = 0; i < _offsets.length; i++) {
offsets[i] = getConvertedOffset(file, _offsets[i]);
}
return offsets;
}
public int[] getConvertedLengths(@NotNull final VirtualFile file, final int[] _offsets, final int[] _lengths) {
final int[] offsets = getConvertedOffsets(file, _offsets);
final int[] lengths = new int[_lengths.length];
for (int i = 0; i < _lengths.length; i++) {
lengths[i] = getConvertedOffset(file, _offsets[i] + _lengths[i]) - offsets[i];
}
return lengths;
}
public static boolean isDartSdkVersionSufficient(@NotNull final DartSdk sdk) {
return StringUtil.compareVersionNumbers(sdk.getVersion(), MIN_SDK_VERSION) >= 0;
}
public static boolean isDartSdkVersionSufficientForMoveFileRefactoring(@NotNull final DartSdk sdk) {
return StringUtil.compareVersionNumbers(sdk.getVersion(), MIN_MOVE_FILE_SDK_VERSION) >= 0;
}
public static boolean isDartSdkVersionSufficientForWebdev(@NotNull final DartSdk sdk) {
return StringUtil.compareVersionNumbers(sdk.getVersion(), MIN_WEBDEV_SDK_VERSION) >= 0;
}
public static boolean isDartSdkVersionSufficientForPackageConfigJson(@NotNull final DartSdk sdk) {
return StringUtil.compareVersionNumbers(sdk.getVersion(), MIN_PACKAGE_CONFIG_JSON_SDK_VERSION) >= 0;
}
public static boolean isDartSdkVersionSufficientForDartLangServer(@NotNull final DartSdk sdk) {
return StringUtil.compareVersionNumbers(sdk.getVersion(), MIN_DART_LANG_SERVER_SDK_VERSION) >= 0;
}
public boolean shouldUseCompletion2() {
return StringUtil.compareVersionNumbers(getServerVersion(), COMPLETION_2_SERVER_VERSION) >= 0;
}
public void addCompletions(@NotNull final VirtualFile file,
@NotNull final String completionId,
@NotNull final CompletionSuggestionConsumer consumer,
@NotNull final CompletionLibraryRefConsumer libraryRefConsumer) {
while (true) {
ProgressManager.checkCanceled();
synchronized (myCompletionInfos) {
CompletionInfo completionInfo;
while ((completionInfo = myCompletionInfos.poll()) != null) {
if (!completionInfo.myCompletionId.equals(completionId)) continue;
if (!completionInfo.isLast) continue;
for (final CompletionSuggestion completion : completionInfo.myCompletions) {
final int convertedReplacementOffset = getConvertedOffset(file, completionInfo.myOriginalReplacementOffset);
consumer.consumeCompletionSuggestion(convertedReplacementOffset, completionInfo.myReplacementLength, completion);
}
final Set<String> includedKinds = Sets.newHashSet(completionInfo.myIncludedElementKinds);
final Map<String, IncludedSuggestionRelevanceTag> includedRelevanceTags = new HashMap<>();
for (IncludedSuggestionRelevanceTag includedRelevanceTag : completionInfo.myIncludedSuggestionRelevanceTags) {
includedRelevanceTags.put(includedRelevanceTag.getTag(), includedRelevanceTag);
}
for (final IncludedSuggestionSet includedSet : completionInfo.myIncludedSuggestionSets) {
libraryRefConsumer.consumeLibraryRef(includedSet, includedKinds, includedRelevanceTags, completionInfo.myLibraryFilePathSD);
}
for (DartCompletionTimerExtension extension : DartCompletionTimerExtension.getExtensions()) {
extension.dartCompletionEnd();
}
return;
}
try {
myCompletionInfos.wait(CHECK_CANCELLED_PERIOD);
}
catch (InterruptedException e) {
return;
}
}
}
}
public static class FormatResult {
@Nullable private final List<SourceEdit> myEdits;
private final int myOffset;
private final int myLength;
public FormatResult(@Nullable final List<SourceEdit> edits, final int selectionOffset, final int selectionLength) {
myEdits = edits;
myOffset = selectionOffset;
myLength = selectionLength;
}
public int getLength() {
return myLength;
}
public int getOffset() {
return myOffset;
}
@Nullable
public List<SourceEdit> getEdits() {
return myEdits;
}
}
public DartAnalysisServerService(@NotNull final Project project) {
myProject = project;
myRootsHandler = new DartServerRootsHandler(project);
myServerData = new DartServerData(this);
myUpdateFilesAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this);
myShowServerProgressAlarm = new Alarm(this);
myServerErrorHandler = new DartAnalysisServerErrorHandler(project);
DartClosingLabelManager.getInstance().addListener(this::handleClosingLabelPreferenceChanged, this);
}
@SuppressWarnings("unused") // for Flutter plugin
public void addAnalysisServerListener(@NotNull final AnalysisServerListener serverListener) {
if (!myAdditionalServerListeners.contains(serverListener)) {
myAdditionalServerListeners.add(serverListener);
if (myServer != null && isServerProcessActive()) {
myServer.addAnalysisServerListener(serverListener);
}
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void removeAnalysisServerListener(@NotNull final AnalysisServerListener serverListener) {
myAdditionalServerListeners.remove(serverListener);
if (myServer != null) {
myServer.removeAnalysisServerListener(serverListener);
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void addRequestListener(@NotNull final RequestListener requestListener) {
if (!myRequestListeners.contains(requestListener)) {
myRequestListeners.add(requestListener);
if (myServer != null && isServerProcessActive()) {
myServer.addRequestListener(requestListener);
}
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void removeRequestListener(@NotNull final RequestListener requestListener) {
myRequestListeners.remove(requestListener);
if (myServer != null) {
myServer.removeRequestListener(requestListener);
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void addResponseListener(@NotNull final ResponseListener responseListener) {
if (!myResponseListeners.contains(responseListener)) {
myResponseListeners.add(responseListener);
if (myServer != null && isServerProcessActive()) {
myServer.addResponseListener(responseListener);
}
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void removeResponseListener(@NotNull final ResponseListener responseListener) {
myResponseListeners.remove(responseListener);
if (myServer != null) {
myServer.removeResponseListener(responseListener);
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void addQuickAssistIntentionListener(@NotNull DartQuickAssistIntentionListener listener) {
if (!myQuickAssistIntentionListeners.contains(listener)) {
myQuickAssistIntentionListeners.add(listener);
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void removeQuickAssistIntentionListener(@NotNull DartQuickAssistIntentionListener listener) {
myQuickAssistIntentionListeners.remove(listener);
}
public void fireBeforeQuickAssistIntentionInvoked(@NotNull DartQuickAssistIntention intention,
@NotNull Editor editor,
@NotNull PsiFile file) {
try {
myQuickAssistIntentionListeners.forEach(listener -> listener.beforeQuickAssistIntentionInvoked(intention, editor, file));
}
catch (Throwable t) {
LOG.error(t);
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void addQuickFixListener(@NotNull DartQuickFixListener listener) {
if (!myQuickFixListeners.contains(listener)) {
myQuickFixListeners.add(listener);
}
}
@SuppressWarnings("unused") // for Flutter plugin
public void removeQuickFixListener(@NotNull DartQuickFixListener listener) {
myQuickFixListeners.remove(listener);
}
public void fireBeforeQuickFixInvoked(@NotNull DartQuickFix fix, @NotNull Editor editor, @NotNull PsiFile file) {
try {
myQuickFixListeners.forEach(listener -> listener.beforeQuickFixInvoked(fix, editor, file));
}
catch (Throwable t) {
LOG.error(t);
}
}
private static void setDasLogger() {
if (Logging.getLogger() != com.google.dart.server.utilities.logging.Logger.NULL) {
return; // already registered
}
Logging.setLogger(new com.google.dart.server.utilities.logging.Logger() {
@Override
public void logError(String message) {
LOG.error(message);
}
@Override
public void logError(String message, Throwable exception) {
LOG.error(message, exception);
}
@Override
public void logInformation(String message) {
LOG.debug(message);
}
@Override
public void logInformation(String message, Throwable exception) {
LOG.debug(message, exception);
}
});
}
private void registerFileEditorManagerListener() {
myProject.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
@Override
public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) {
if (PubspecYamlUtil.PUBSPEC_YAML.equals(file.getName()) ||
FileTypeRegistry.getInstance().isFileOfType(file, DartFileType.INSTANCE)) {
DartSdkUpdateChecker.mayBeCheckForSdkUpdate(source.getProject());
}
updateCurrentFile();
if (isLocalAnalyzableFile(file)) {
updateVisibleFiles();
}
}
@Override
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
updateCurrentFile();
if (isLocalAnalyzableFile(event.getOldFile()) || isLocalAnalyzableFile(event.getNewFile())) {
updateVisibleFiles();
}
}
@Override
public void fileClosed(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) {
updateCurrentFile();
if (isLocalAnalyzableFile(file)) {
// file could be opened in more than one editor, so this check is needed
if (FileEditorManager.getInstance(myProject).getSelectedEditor(file) == null) {
myServerData.onFileClosed(file);
}
updateVisibleFiles();
}
}
});
}
private void registerDocumentListener() {
final DocumentListener documentListener = new DocumentListener() {
@Override
public void beforeDocumentChange(@NotNull DocumentEvent e) {
if (myServer == null) return;
myServerData.onDocumentChanged(e);
final VirtualFile file = FileDocumentManager.getInstance().getFile(e.getDocument());
if (isLocalAnalyzableFile(file)) {
for (VirtualFile fileInEditor : FileEditorManager.getInstance(myProject).getOpenFiles()) {
if (fileInEditor.equals(file)) {
synchronized (myLock) {
myChangedDocuments.add(e.getDocument());
}
break;
}
}
}
myUpdateFilesAlarm.cancelAllRequests();
myUpdateFilesAlarm.addRequest(DartAnalysisServerService.this::updateFilesContent, UPDATE_FILES_TIMEOUT);
}
};
EditorFactory.getInstance().getEventMulticaster().addDocumentListener(documentListener, this);
}
@NotNull
public static DartAnalysisServerService getInstance(@NotNull final Project project) {
return project.getService(DartAnalysisServerService.class);
}
@NotNull
public String getSdkVersion() {
return mySdkVersion;
}
@NotNull
public String getServerVersion() {
return myServerVersion;
}
@NotNull
public Project getProject() {
return myProject;
}
@Override
public void dispose() {
myDisposed = true;
stopServer();
}
public @NotNull Condition<?> getDisposedCondition() {
return myDisposedCondition;
}
private void handleClosingLabelPreferenceChanged() {
analysis_setSubscriptions();
}
@Nullable
public AvailableSuggestionSet getAvailableSuggestionSet(int id) {
return myServerData.getAvailableSuggestionSet(id);
}
@Nullable
public Map<String, Map<String, Set<String>>> getExistingImports(@Nullable String filePathSD) {
return myServerData.getExistingImports(filePathSD);
}
@NotNull
public List<DartServerData.DartError> getErrors(@NotNull final VirtualFile file) {
return myServerData.getErrors(file);
}
public List<DartServerData.DartError> getErrors(@NotNull final SearchScope scope) {
return myServerData.getErrors(scope);
}
@NotNull
public List<DartServerData.DartHighlightRegion> getHighlight(@NotNull final VirtualFile file) {
return myServerData.getHighlight(file);
}
@NotNull
public List<DartServerData.DartNavigationRegion> getNavigation(@NotNull final VirtualFile file) {
return myServerData.getNavigation(file);
}
@NotNull
public List<DartServerData.DartOverrideMember> getOverrideMembers(@NotNull final VirtualFile file) {
return myServerData.getOverrideMembers(file);
}
@NotNull
public List<DartServerData.DartRegion> getImplementedClasses(@NotNull final VirtualFile file) {
return myServerData.getImplementedClasses(file);
}
@NotNull
public List<DartServerData.DartRegion> getImplementedMembers(@NotNull final VirtualFile file) {
return myServerData.getImplementedMembers(file);
}
@Nullable
@Contract("null -> null")
public Outline getOutline(@Nullable final VirtualFile file) {
if (file == null) return null;
return myServerData.getOutline(file);
}
void updateCurrentFile() {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, myDisposedCondition,
() -> DartProblemsView.getInstance(myProject).setCurrentFile(getCurrentOpenFile())
);
}
public boolean isInIncludedRoots(@Nullable final VirtualFile vFile) {
return myRootsHandler.isInIncludedRoots(vFile);
}
@Nullable
private VirtualFile getCurrentOpenFile() {
final VirtualFile[] files = FileEditorManager.getInstance(myProject).getSelectedFiles();
if (files.length > 0) {
return files[0];
}
return null;
}
public void updateVisibleFiles() {
ApplicationManager.getApplication().assertReadAccessAllowed();
synchronized (myLock) {
final List<String> newVisibleFiles = new ArrayList<>();
for (VirtualFile file : FileEditorManager.getInstance(myProject).getSelectedFiles()) {
if (isLocalAnalyzableFile(file)) {
newVisibleFiles.add(FileUtil.toSystemDependentName(file.getPath()));
}
}
if (!Comparing.haveEqualElements(myVisibleFiles, newVisibleFiles)) {
myVisibleFiles.clear();
myVisibleFiles.addAll(newVisibleFiles);
analysis_setPriorityFiles();
analysis_setSubscriptions();
}
}
}
/**
* Return true if the given file can be analyzed by Dart Analysis Server.
*/
@Contract("null->false")
public static boolean isLocalAnalyzableFile(@Nullable final VirtualFile file) {
if (file != null && file.isInLocalFileSystem()) {
return isFileNameRespectedByAnalysisServer(file.getName());
}
return false;
}
public static boolean isFileNameRespectedByAnalysisServer(@NotNull String _fileName) {
// see https://github.com/dart-lang/sdk/blob/master/pkg/analyzer/lib/src/generated/engine.dart (class AnalysisEngine)
// and AbstractAnalysisServer.analyzableFilePatterns
@NonNls String fileName = _fileName.toLowerCase(Locale.US);
return fileName.endsWith(".dart") ||
fileName.endsWith(".htm") ||
fileName.endsWith(".html") ||
fileName.equals(".analysis_options") ||
fileName.equals("analysis_options.yaml") ||
fileName.equals("pubspec.yaml") ||
fileName.equals("fix_data.yaml") ||
fileName.equals("androidmanifest.xml");
}
public void updateFilesContent() {
if (myServer != null) {
ApplicationManager.getApplication().runReadAction(this::doUpdateFilesContent);
}
}
private void doUpdateFilesContent() {
// may be use DocumentListener to collect deltas instead of sending the whole Document.getText() each time?
AnalysisServer server = myServer;
if (server == null) {
return;
}
myUpdateFilesAlarm.cancelAllRequests();
final Map<String, Object> filesToUpdate = new HashMap<>();
ApplicationManager.getApplication().assertReadAccessAllowed();
synchronized (myLock) {
final Set<String> oldTrackedFiles = new HashSet<>(myFilePathWithOverlaidContentToTimestamp.keySet());
final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
// some documents in myChangedDocuments may be updated by external change, such as switch branch, that's why we track them,
// getUnsavedDocuments() is not enough, we must make sure that overlaid content is sent for myChangedDocuments as well (to trigger DAS notifications)
final Set<Document> documents = new HashSet<>(myChangedDocuments);
myChangedDocuments.clear();
ContainerUtil.addAll(documents, fileDocumentManager.getUnsavedDocuments());
for (Document document : documents) {
final VirtualFile file = fileDocumentManager.getFile(document);
if (isLocalAnalyzableFile(file)) {
oldTrackedFiles.remove(file.getPath());
final Long oldTimestamp = myFilePathWithOverlaidContentToTimestamp.get(file.getPath());
if (oldTimestamp == null || document.getModificationStamp() != oldTimestamp) {
filesToUpdate.put(FileUtil.toSystemDependentName(file.getPath()), new AddContentOverlay(document.getText()));
myFilePathWithOverlaidContentToTimestamp.put(file.getPath(), document.getModificationStamp());
}
}
}
// oldTrackedFiles at this point contains only those files that are not in FileDocumentManager.getUnsavedDocuments() anymore
for (String oldPath : oldTrackedFiles) {
final Long removed = myFilePathWithOverlaidContentToTimestamp.remove(oldPath);
LOG.assertTrue(removed != null, oldPath);
filesToUpdate.put(FileUtil.toSystemDependentName(oldPath), new RemoveContentOverlay());
}
if (LOG.isDebugEnabled()) {
final Set<String> overlaid = new HashSet<>(filesToUpdate.keySet());
for (String removeOverlaid : oldTrackedFiles) {
overlaid.remove(FileUtil.toSystemDependentName(removeOverlaid));
}
if (!overlaid.isEmpty()) {
LOG.debug("Sending overlaid content: " + StringUtil.join(overlaid, ",\n"));
}
if (!oldTrackedFiles.isEmpty()) {
LOG.debug("Removing overlaid content: " + StringUtil.join(oldTrackedFiles, ",\n"));
}
}
}
if (!filesToUpdate.isEmpty()) {
server.analysis_updateContent(filesToUpdate, myServerData::onFilesContentUpdated);
}
}
public void ensureAnalysisRootsUpToDate() {
myRootsHandler.updateRoots();
}
boolean setAnalysisRoots(@NotNull final List<String> includedRoots, @NotNull final List<String> excludedRoots) {
AnalysisServer server = myServer;
if (server == null) {
return false;
}
if (LOG.isDebugEnabled()) {
LOG.debug("analysis_setAnalysisRoots, included:\n" + StringUtil.join(includedRoots, ",\n") +
"\nexcluded:\n" + StringUtil.join(excludedRoots, ",\n"));
}
server.analysis_setAnalysisRoots(includedRoots, excludedRoots, null);
return true;
}
private void onErrorsUpdated(@NotNull final String filePath,
@NotNull List<? extends AnalysisError> errors,
boolean hasSevereProblems,
int errorsHash) {
updateFilesWithErrorsSet(filePath, hasSevereProblems, errorsHash);
DartProblemsView.getInstance(myProject).updateErrorsForFile(filePath, errors);
}
private void updateFilesWithErrorsSet(@NotNull final String filePath, final boolean hasSevereProblems, final int errorsHash) {
synchronized (myFilePathsWithErrors) {
if (errorsHash == 0) {