forked from scalameta/metals
-
Notifications
You must be signed in to change notification settings - Fork 2
/
WorkspaceLspService.scala
1189 lines (1089 loc) Β· 42.3 KB
/
WorkspaceLspService.scala
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
package scala.meta.internal.metals
import java.nio.file.ProviderMismatchException
import java.util.concurrent.CompletableFuture
import java.{util => ju}
import scala.concurrent.Await
import scala.concurrent.ExecutionContextExecutorService
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.concurrent.duration.Duration
import scala.util.control.NonFatal
import scala.meta.internal.bsp.BuildChange
import scala.meta.internal.builds.NewProjectProvider
import scala.meta.internal.builds.ShellRunner
import scala.meta.internal.metals.DidFocusResult
import scala.meta.internal.metals.HoverExtParams
import scala.meta.internal.metals.MetalsEnrichments._
import scala.meta.internal.metals.MetalsLspService
import scala.meta.internal.metals.WindowStateDidChangeParams
import scala.meta.internal.metals.clients.language.ConfiguredLanguageClient
import scala.meta.internal.metals.clients.language.MetalsLanguageClient
import scala.meta.internal.metals.debug.BuildTargetNotFoundException
import scala.meta.internal.metals.debug.BuildTargetUndefinedException
import scala.meta.internal.metals.debug.DebugProvider
import scala.meta.internal.metals.doctor.DoctorVisibilityDidChangeParams
import scala.meta.internal.metals.findfiles.FindTextInDependencyJarsRequest
import scala.meta.internal.metals.logging.LanguageClientLogger
import scala.meta.internal.parsing.ClassFinderGranularity
import scala.meta.internal.pc
import scala.meta.internal.tvp.MetalsTreeViewChildrenResult
import scala.meta.internal.tvp.MetalsTreeViewProvider
import scala.meta.internal.tvp.NoopTreeViewProvider
import scala.meta.internal.tvp.TreeViewChildrenParams
import scala.meta.internal.tvp.TreeViewNodeCollapseDidChangeParams
import scala.meta.internal.tvp.TreeViewNodeRevealResult
import scala.meta.internal.tvp.TreeViewParentParams
import scala.meta.internal.tvp.TreeViewParentResult
import scala.meta.internal.tvp.TreeViewProvider
import scala.meta.internal.tvp.TreeViewVisibilityDidChangeParams
import scala.meta.io.AbsolutePath
import scala.meta.metals.lsp.ScalaLspService
import scala.meta.pc.DisplayableException
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import org.eclipse.lsp4j
import org.eclipse.lsp4j.CallHierarchyIncomingCall
import org.eclipse.lsp4j.CallHierarchyIncomingCallsParams
import org.eclipse.lsp4j.CallHierarchyItem
import org.eclipse.lsp4j.CallHierarchyOutgoingCall
import org.eclipse.lsp4j.CallHierarchyOutgoingCallsParams
import org.eclipse.lsp4j.CallHierarchyPrepareParams
import org.eclipse.lsp4j.CodeAction
import org.eclipse.lsp4j.CodeActionParams
import org.eclipse.lsp4j.CodeLens
import org.eclipse.lsp4j.CodeLensParams
import org.eclipse.lsp4j.CompletionItem
import org.eclipse.lsp4j.CompletionList
import org.eclipse.lsp4j.CompletionParams
import org.eclipse.lsp4j.DidChangeConfigurationParams
import org.eclipse.lsp4j.DidChangeTextDocumentParams
import org.eclipse.lsp4j.DidChangeWatchedFilesParams
import org.eclipse.lsp4j.DidCloseTextDocumentParams
import org.eclipse.lsp4j.DidOpenTextDocumentParams
import org.eclipse.lsp4j.DidSaveTextDocumentParams
import org.eclipse.lsp4j.DocumentFormattingParams
import org.eclipse.lsp4j.DocumentHighlight
import org.eclipse.lsp4j.DocumentOnTypeFormattingParams
import org.eclipse.lsp4j.DocumentRangeFormattingParams
import org.eclipse.lsp4j.DocumentSymbol
import org.eclipse.lsp4j.DocumentSymbolParams
import org.eclipse.lsp4j.ExecuteCommandParams
import org.eclipse.lsp4j.FoldingRange
import org.eclipse.lsp4j.FoldingRangeRequestParams
import org.eclipse.lsp4j.Hover
import org.eclipse.lsp4j.Location
import org.eclipse.lsp4j.ReferenceParams
import org.eclipse.lsp4j.RenameFilesParams
import org.eclipse.lsp4j.RenameParams
import org.eclipse.lsp4j.SelectionRange
import org.eclipse.lsp4j.SelectionRangeParams
import org.eclipse.lsp4j.SemanticTokens
import org.eclipse.lsp4j.SemanticTokensParams
import org.eclipse.lsp4j.SignatureHelp
import org.eclipse.lsp4j.SymbolInformation
import org.eclipse.lsp4j.TextDocumentPositionParams
import org.eclipse.lsp4j.TextEdit
import org.eclipse.lsp4j.WorkspaceEdit
import org.eclipse.lsp4j.WorkspaceSymbolParams
import org.eclipse.lsp4j.jsonrpc.messages
class WorkspaceLspService(
ec: ExecutionContextExecutorService,
sh: ju.concurrent.ScheduledExecutorService,
serverInputs: MetalsServerInputs,
client: MetalsLanguageClient,
initializeParams: lsp4j.InitializeParams,
val folders: List[Folder],
) extends ScalaLspService {
import serverInputs._
implicit val ex: ExecutionContextExecutorService = ec
implicit val rc: ReportContext = LoggerReportContext
private val cancelables = new MutableCancelable()
private val clientConfig =
ClientConfiguration(
serverInputs.initialServerConfig,
initializeParams,
)
private val languageClient = {
val languageClient =
new ConfiguredLanguageClient(client, clientConfig, () => userConfig)
// Set the language client so that we can forward log messages to the client
LanguageClientLogger.languageClient = Some(languageClient)
cancelables.add(() => languageClient.shutdown())
languageClient
}
@volatile
private var userConfig: UserConfiguration = initialUserConfig
val statusBar: StatusBar = new StatusBar(
languageClient,
time,
progressTicks,
clientConfig,
)
private val shellRunner = register {
new ShellRunner(languageClient, () => userConfig, time, statusBar)
}
var focusedDocument: Option[AbsolutePath] = None
private val recentlyFocusedFiles = new ActiveFiles(time)
private val timerProvider: TimerProvider = new TimerProvider(time)
def createService(folder: Folder): MetalsLspService =
folder match {
case Folder(uri, name) =>
new MetalsLspService(
ec,
sh,
serverInputs,
languageClient,
initializeParams,
clientConfig,
() => userConfig,
statusBar,
() => focusedDocument,
shellRunner,
timerProvider,
initTreeView,
uri,
name,
)
}
val workspaceFolders: WorkspaceFolders =
new WorkspaceFolders(
folders,
createService,
_.initialized(this),
() => shutdown().asScala,
redirectSystemOut,
)
def folderServices = workspaceFolders.getFolderServices
val treeView: TreeViewProvider =
if (clientConfig.isTreeViewProvider) {
new MetalsTreeViewProvider(
() => folderServices.map(_.treeView),
languageClient,
sh,
)
} else NoopTreeViewProvider
def initTreeView(): Unit = treeView.init()
private val newProjectProvider: NewProjectProvider = new NewProjectProvider(
languageClient,
statusBar,
clientConfig,
shellRunner,
clientConfig.icons,
folders.head.path,
)
private val githubNewIssueUrlCreator = new GithubNewIssueUrlCreator(
() => folderServices.map(_.gitHubIssueFolderInfo),
initializeParams.getClientInfo(),
)
private val workspaceChoicePopup: WorkspaceChoicePopup =
new WorkspaceChoicePopup(
() => folderServices,
languageClient,
)
def register[T <: Cancelable](cancelable: T): T = {
cancelables.add(cancelable)
cancelable
}
def getServiceForOpt(path: AbsolutePath): Option[MetalsLspService] =
try {
for {
workSpaceFolder <- folderServices
.filter(service => path.toNIO.startsWith(service.folder.toNIO))
.sortBy(_.folder.toNIO.getNameCount())
.lastOption
} yield workSpaceFolder
} catch {
case _: ProviderMismatchException => None
}
def getServiceFor(path: AbsolutePath): MetalsLspService =
if (folderServices.length == 1) folderServices.head
else getServiceForOpt(path).getOrElse(folderServices.head)
def getServiceFor(uri: String): MetalsLspService = {
val folder =
for {
// "metalsDecode" prefix is used for showing special files and is not an actual file system
path <- uri.stripPrefix("metalsDecode:").toAbsolutePathSafe()
} yield getServiceFor(path)
folder.getOrElse(folderServices.head) // fallback to the first one
}
def currentFolder: Option[MetalsLspService] =
focusedDocument.flatMap(getServiceForOpt)
/**
* Execute on current folder (for focused document).
* In no focused document create a popup for user to choose the folder.
* @param f -- action to be executed
* @param actionName -- action name to display for popup
*/
def onCurrentFolder[A](
f: MetalsLspService => Future[A],
actionName: String,
default: () => A,
): Future[A] = {
def currentService(): Future[Option[MetalsLspService]] =
folderServices match {
case head :: Nil => Future { Some(head) }
case _ =>
focusedDocument.flatMap(getServiceForOpt) match {
case Some(service) => Future { Some(service) }
case None =>
workspaceChoicePopup.interactiveChooseFolder(actionName)
}
}
currentService().flatMap {
case Some(service) => f(service)
case None =>
languageClient
.showMessage(
lsp4j.MessageType.Info,
s"No workspace folder chosen to execute $actionName.",
)
Future.successful(default())
}
}
def onCurrentFolder(
f: MetalsLspService => Future[Unit],
actionName: String,
): Future[Unit] =
onCurrentFolder(f, actionName, () => ())
def getServiceForExactUri(
folderUri: String
): Option[MetalsLspService] =
for {
workSpaceFolder <- folderServices
.find(service => service.folder.toString == folderUri)
} yield workSpaceFolder
def foreachSeq[A](
f: MetalsLspService => Future[A],
ignoreValue: Boolean = false,
): CompletableFuture[Object] = {
val res = Future.sequence(folderServices.map(f))
if (ignoreValue) res.ignoreValue.asJavaObject
else res.asJavaObject
}
def collectSeq[A, B](f: MetalsLspService => Future[A])(
compose: List[A] => B
): Future[B] =
Future.sequence(folderServices.map(f)).collect { case v => compose(v) }
override def didOpen(
params: DidOpenTextDocumentParams
): CompletableFuture[Unit] = {
focusedDocument.foreach(recentlyFocusedFiles.add)
focusedDocument = Some(params.getTextDocument.getUri.toAbsolutePath)
getServiceFor(params.getTextDocument().getUri()).didOpen(params)
}
override def didChange(
params: DidChangeTextDocumentParams
): CompletableFuture[Unit] =
getServiceFor(params.getTextDocument().getUri()).didChange(params)
override def didClose(params: DidCloseTextDocumentParams): Unit = {
val path = params.getTextDocument.getUri.toAbsolutePath
if (focusedDocument.contains(path)) {
focusedDocument = recentlyFocusedFiles.pollRecent()
}
getServiceFor(params.getTextDocument().getUri()).didClose(params)
}
override def didSave(
params: DidSaveTextDocumentParams
): CompletableFuture[Unit] =
getServiceFor(params.getTextDocument().getUri()).didSave(params)
override def definition(
position: TextDocumentPositionParams
): CompletableFuture[ju.List[Location]] =
getServiceFor(position.getTextDocument().getUri()).definition(position)
override def typeDefinition(
position: TextDocumentPositionParams
): CompletableFuture[ju.List[Location]] =
getServiceFor(position.getTextDocument().getUri()).typeDefinition(position)
override def implementation(
position: TextDocumentPositionParams
): CompletableFuture[ju.List[Location]] =
getServiceFor(position.getTextDocument().getUri()).implementation(position)
override def hover(params: HoverExtParams): CompletableFuture[Hover] =
getServiceFor(params.textDocument.getUri()).hover(params)
override def documentHighlights(
params: TextDocumentPositionParams
): CompletableFuture[ju.List[DocumentHighlight]] =
getServiceFor(params.getTextDocument.getUri()).documentHighlights(params)
override def documentSymbol(params: DocumentSymbolParams): CompletableFuture[
messages.Either[ju.List[DocumentSymbol], ju.List[SymbolInformation]]
] =
getServiceFor(params.getTextDocument.getUri()).documentSymbol(params)
override def formatting(
params: DocumentFormattingParams
): CompletableFuture[ju.List[TextEdit]] =
getServiceFor(params.getTextDocument.getUri()).formatting(params)
override def onTypeFormatting(
params: DocumentOnTypeFormattingParams
): CompletableFuture[ju.List[TextEdit]] =
getServiceFor(params.getTextDocument.getUri()).onTypeFormatting(params)
override def rangeFormatting(
params: DocumentRangeFormattingParams
): CompletableFuture[ju.List[TextEdit]] =
getServiceFor(params.getTextDocument.getUri()).rangeFormatting(params)
override def prepareRename(
params: TextDocumentPositionParams
): CompletableFuture[lsp4j.Range] =
getServiceFor(params.getTextDocument.getUri()).prepareRename(params)
override def rename(params: RenameParams): CompletableFuture[WorkspaceEdit] =
getServiceFor(params.getTextDocument.getUri()).rename(params)
override def references(
params: ReferenceParams
): CompletableFuture[ju.List[Location]] =
getServiceFor(params.getTextDocument.getUri()).references(params)
override def prepareCallHierarchy(
params: CallHierarchyPrepareParams
): CompletableFuture[ju.List[CallHierarchyItem]] =
getServiceFor(params.getTextDocument.getUri()).prepareCallHierarchy(params)
override def callHierarchyIncomingCalls(
params: CallHierarchyIncomingCallsParams
): CompletableFuture[ju.List[CallHierarchyIncomingCall]] =
getServiceFor(params.getItem.getUri).callHierarchyIncomingCalls(params)
override def callHierarchyOutgoingCalls(
params: CallHierarchyOutgoingCallsParams
): CompletableFuture[ju.List[CallHierarchyOutgoingCall]] =
getServiceFor(params.getItem.getUri).callHierarchyOutgoingCalls(params)
override def completion(
params: CompletionParams
): CompletableFuture[CompletionList] =
getServiceFor(params.getTextDocument.getUri).completion(params)
override def completionItemResolve(
item: CompletionItem
): CompletableFuture[CompletionItem] =
currentFolder
.map(_.completionItemResolve(item))
.getOrElse(Future.successful(item).asJava)
override def signatureHelp(
params: TextDocumentPositionParams
): CompletableFuture[SignatureHelp] =
getServiceFor(params.getTextDocument.getUri).signatureHelp(params)
override def codeAction(
params: CodeActionParams
): CompletableFuture[ju.List[CodeAction]] =
getServiceFor(params.getTextDocument.getUri).codeAction(params)
override def codeLens(
params: CodeLensParams
): CompletableFuture[ju.List[CodeLens]] =
getServiceFor(params.getTextDocument.getUri).codeLens(params)
override def foldingRange(
params: FoldingRangeRequestParams
): CompletableFuture[ju.List[FoldingRange]] =
getServiceFor(params.getTextDocument.getUri).foldingRange(params)
override def selectionRange(
params: SelectionRangeParams
): CompletableFuture[ju.List[SelectionRange]] =
getServiceFor(params.getTextDocument.getUri).selectionRange(params)
override def semanticTokensFull(
params: SemanticTokensParams
): CompletableFuture[SemanticTokens] =
getServiceFor(params.getTextDocument.getUri).semanticTokensFull(params)
override def workspaceSymbol(
params: WorkspaceSymbolParams
): CompletableFuture[ju.List[SymbolInformation]] =
CancelTokens.future { token =>
collectSeq(_.workspaceSymbol(params, token))(_.flatten.asJava)
}
override def willRenameFiles(
params: RenameFilesParams
): CompletableFuture[WorkspaceEdit] =
CancelTokens.future { _ =>
val moves = params.getFiles.asScala.toSeq.map { rename =>
val service = getServiceFor(rename.getOldUri())
val oldPath = rename.getOldUri().toAbsolutePath
val newPath = rename.getNewUri().toAbsolutePath
/* Changing package for files moved out of the workspace or between folders will cause unexpected issues
* This showed up with emacs automated backups.
*/
if (newPath.startWith(service.folder))
service.willRenameFile(oldPath, newPath)
else
Future.successful(
new WorkspaceEdit(Map.empty[String, ju.List[TextEdit]].asJava)
)
}
Future.sequence(moves).map(_.mergeChanges)
}
override def didChangeConfiguration(
params: DidChangeConfigurationParams
): CompletableFuture[Unit] = {
val fullJson = params.getSettings.asInstanceOf[JsonElement].getAsJsonObject
val metalsSection =
Option(fullJson.getAsJsonObject("metals")).getOrElse(new JsonObject)
updateConfiguration(metalsSection).asJava
}
private def updateConfiguration(json: JsonObject): Future[Unit] =
UserConfiguration.fromJson(json, clientConfig) match {
case Left(errors) =>
errors.foreach { error => scribe.error(s"config error: $error") }
Future.successful(())
case Right(newUserConfig) =>
val old = userConfig
userConfig = newUserConfig
collectSeq(_.onUserConfigUpdate(old))(_ => ())
}
override def didChangeWatchedFiles(
params: DidChangeWatchedFilesParams
): CompletableFuture[Unit] =
Future
.sequence(
params
.getChanges()
.asScala
.iterator
.toList
.map(event => {
val uri = event.getUri()
(uri.toAbsolutePath, getServiceFor(uri))
})
.groupBy(_._2)
.map { case (service, paths) =>
service.didChangeWatchedFiles(paths.map(_._1))
}
)
.ignoreValue
.asJava
override def didChangeWorkspaceFolders(
params: lsp4j.DidChangeWorkspaceFoldersParams
): CompletableFuture[Unit] =
workspaceFolders
.changeFolderServices(
params.getEvent().getRemoved().map(Folder.apply).asScala.toList,
params.getEvent().getAdded().map(Folder.apply).asScala.toList,
)
.asJava
override def treeViewChildren(
params: TreeViewChildrenParams
): CompletableFuture[MetalsTreeViewChildrenResult] = {
Future {
treeView.children(params)
}.asJava
}
override def treeViewParent(
params: TreeViewParentParams
): CompletableFuture[TreeViewParentResult] = {
Future {
treeView.parent(params)
}.asJava
}
override def treeViewVisibilityDidChange(
params: TreeViewVisibilityDidChangeParams
): CompletableFuture[Unit] =
Future {
treeView.onVisibilityDidChange(params)
}.asJava
override def treeViewNodeCollapseDidChange(
params: TreeViewNodeCollapseDidChangeParams
): CompletableFuture[Unit] =
Future {
treeView.onCollapseDidChange(params)
}.asJava
override def treeViewReveal(
params: TextDocumentPositionParams
): CompletableFuture[TreeViewNodeRevealResult] =
Future {
treeView
.reveal(
params.getTextDocument().getUri().toAbsolutePath,
params.getPosition(),
)
.orNull
}.asJava
override def findTextInDependencyJars(
params: FindTextInDependencyJarsRequest
): CompletableFuture[ju.List[Location]] =
collectSeq(_.findTextInDependencyJars(params))(_.flatten.asJava).asJava
override def doctorVisibilityDidChange(
params: DoctorVisibilityDidChangeParams
): CompletableFuture[Unit] = {
focusedDocument
.flatMap(getServiceForOpt)
.map(_.doctorVisibilityDidChange(params))
.getOrElse(
/* If we can't find the focused document, we still want to notify all the services.
* If a doctor is not visible this will have no effect.
*/
Future.sequence(folderServices.map(_.doctorVisibilityDidChange(params)))
)
.asJavaUnit
}
override def didFocus(
params: AnyRef
): CompletableFuture[DidFocusResult.Value] = {
val uriOpt: Option[String] = params match {
case string: String =>
Option(string)
case (h: String) :: Nil =>
Option(h)
case _ =>
scribe.warn(
s"Unexpected notification params received for didFocusTextDocument: $params"
)
None
}
uriOpt match {
case Some(uri) =>
focusedDocument = Some(uri.toAbsolutePath)
getServiceFor(uri).didFocus(uri)
case None =>
CompletableFuture.completedFuture(DidFocusResult.NoBuildTarget)
}
}
override def windowStateDidChange(params: WindowStateDidChangeParams): Unit =
if (params.focused) {
folderServices.foreach(_.unpause())
} else {
folderServices.foreach(_.pause())
}
private def displayNotFound(objectName: String, id: String) =
languageClient.showMessage(
Messages.errorMessageParams(s"$objectName not found: $id")
)
private def onFirstSatifying[T, R](mapTo: MetalsLspService => Future[T])(
satisfies: T => Boolean,
exec: (MetalsLspService, T) => Future[R],
onNotFound: () => Future[R],
): Future[R] =
Future
.sequence(folderServices.map(service => mapTo(service).map((service, _))))
.flatMap(
_.find { case (_, value) => satisfies(value) }
.map(exec.tupled)
.getOrElse(onNotFound())
)
override def executeCommand(
params: ExecuteCommandParams
): CompletableFuture[Object] =
params match {
case ServerCommands.ScanWorkspaceSources() =>
foreachSeq(_.indexSources(), ignoreValue = true)
case ServerCommands.RestartBuildServer() =>
folderServices.find(_.isBloop()).foreach(_.shutDownBloop())
foreachSeq(_.autoConnectToBuildServer())
case ServerCommands.GenerateBspConfig() =>
onCurrentFolder(
_.generateBspConfig(),
"generate BSP config",
).asJavaObject
case ServerCommands.ImportBuild() =>
onCurrentFolder(
_.slowConnectToBuildServer(forceImport = true),
"import build",
default = () => BuildChange.None,
).asJavaObject
case ServerCommands.ConnectBuildServer() =>
onCurrentFolder(
_.quickConnectToBuildServer(),
"connect build server",
default = () => BuildChange.None,
).asJavaObject
case ServerCommands.DisconnectBuildServer() =>
onCurrentFolder(
_.disconnectOldBuildServer(),
"disconnect old build server",
).asJavaObject
case ServerCommands.DecodeFile(uri) =>
getServiceFor(uri).decodeFile(uri).asJavaObject
case ServerCommands.DiscoverTestSuites(params) =>
Option(params.uri) match {
case None =>
Future
.sequence(folderServices.map(_.discoverTestSuites(uri = None)))
.map(_.flatten.asJava)
.asJavaObject
case Some(uri) =>
getServiceFor(params.uri)
.discoverTestSuites(uri = Some(uri))
.map(_.asJava)
.asJavaObject
}
case ServerCommands.DiscoverMainClasses(unresolvedParams) =>
getServiceFor(unresolvedParams.path)
.discoverMainClasses(unresolvedParams)
.asJavaObject
case ServerCommands.RunScalafix(params) =>
val uri = params.getTextDocument().getUri()
getServiceFor(uri).runScalafix(uri).asJavaObject
case ServerCommands.ChooseClass(params) =>
val uri = params.textDocument.getUri()
val searchGranularity =
if (params.kind == "class") ClassFinderGranularity.ClassFiles
else ClassFinderGranularity.Tasty
getServiceFor(uri).chooseClass(uri, searchGranularity).asJavaObject
case ServerCommands.RunDoctor() =>
onCurrentFolder(_.runDoctor(), "run doctor").asJavaObject
case ServerCommands.ZipReports() =>
Future {
val zip =
ZipReportsProvider.zip(folderServices.map(_.folderReportsZippper))
val pos = new lsp4j.Position(0, 0)
val location = new Location(
zip.toURI.toString(),
new lsp4j.Range(pos, pos),
)
languageClient.metalsExecuteClientCommand(
ClientCommands.GotoLocation.toExecuteCommandParams(
ClientCommands.WindowLocation(
location.getUri(),
location.getRange(),
)
)
)
}.asJavaObject
case ServerCommands.ListBuildTargets() =>
Future {
folderServices
.flatMap(
_.buildTargets.all.toList
.map(_.getDisplayName())
.sorted
)
.asJava
}.asJavaObject
case ServerCommands.BspSwitch() =>
onCurrentFolder(_.switchBspServer(), "switch BSP server").asJavaObject
case ServerCommands.OpenIssue() =>
Future
.successful(Urls.openBrowser(githubNewIssueUrlCreator.buildUrl()))
.asJavaObject
case OpenBrowserCommand(url) =>
Future.successful(Urls.openBrowser(url)).asJavaObject
case ServerCommands.CascadeCompile() =>
onCurrentFolder(_.cascadeCompile(), "cascade compile").asJavaObject
case ServerCommands.CleanCompile() =>
onCurrentFolder(_.cleanCompile(), "clean compile").asJavaObject
case ServerCommands.CancelCompile() =>
foreachSeq(_.cancelCompile(), ignoreValue = true)
case ServerCommands.PresentationCompilerRestart() =>
foreachSeq(_.restartCompiler(), ignoreValue = true)
case ServerCommands.GotoPosition(location) =>
Future {
languageClient.metalsExecuteClientCommand(
ClientCommands.GotoLocation.toExecuteCommandParams(
ClientCommands.WindowLocation(
location.getUri(),
location.getRange(),
)
)
)
}.asJavaObject
case ServerCommands.GotoSymbol(symbol) =>
Future {
for {
location <- folderServices.foldLeft(Option.empty[Location]) {
case (None, service) => service.getLocationForSymbol(symbol)
case (someLoc, _) => someLoc
}
} {
languageClient.metalsExecuteClientCommand(
ClientCommands.GotoLocation.toExecuteCommandParams(
ClientCommands.WindowLocation(
location.getUri(),
location.getRange(),
)
)
)
}
}.asJavaObject
case ServerCommands.GotoLog() =>
onCurrentFolder(
service =>
Future {
val log = service.folder.resolve(Directories.log)
val linesCount = log.readText.linesIterator.size
val pos = new lsp4j.Position(linesCount, 0)
val location = new Location(
log.toURI.toString(),
new lsp4j.Range(pos, pos),
)
languageClient.metalsExecuteClientCommand(
ClientCommands.GotoLocation.toExecuteCommandParams(
ClientCommands.WindowLocation(
location.getUri(),
location.getRange(),
)
)
)
},
"go to log",
).asJavaObject
case ServerCommands.StartDebugAdapter(params) if params.getData != null =>
val targets = params.getTargets().asScala
folderServices.find(s =>
targets.forall(s.supportsBuildTarget(_).isDefined)
) match {
case Some(service) => service.startDebugProvider(params).asJavaObject
case None =>
languageClient.showMessage(
Messages.errorMessageParams(
s"Could not find folder for build targets: ${targets.mkString(",")}"
)
)
Future.failed(DebugProvider.WorkspaceErrorsException).asJavaObject
}
case ServerCommands.StartMainClass(params) if params.mainClass != null =>
onFirstSatifying(_.findMainClassAndItsBuildTarget(params))(
_.nonEmpty,
(service, buildTargets) =>
service.startMainClass(buildTargets, params),
() => {
displayNotFound("Main class", params.mainClass)
Future.failed(new ju.NoSuchElementException(params.mainClass))
},
).asJavaObject
case ServerCommands.StartTestSuite(params)
if params.target != null && params.requestData != null =>
onFirstSatifying(service =>
Future.successful(service.supportsBuildTarget(params.target))
)(
_.isDefined,
(service, someTarget) =>
service.startTestSuite(someTarget.get, params),
() => {
displayNotFound("Build target", params.target.toString())
Future.failed(BuildTargetNotFoundException(params.target.getUri))
},
).asJavaObject
case ServerCommands.ResolveAndStartTestSuite(params)
if params.testClass != null =>
onFirstSatifying(_.findTestClassAndItsBuildTarget(params))(
_.nonEmpty,
(service, buildTargets) =>
service.startTestSuiteForResolved(buildTargets, params),
() => {
displayNotFound("Test class", params.testClass)
Future.failed(new ju.NoSuchElementException(params.testClass))
},
).asJavaObject
case ServerCommands.StartAttach(params) if params.hostName != null =>
onFirstSatifying(service =>
Future.successful(
service.findBuildTargetByDisplayName(params.buildTarget)
)
)(
_.isDefined,
(service, someTarget) =>
service.createDebugSession(someTarget.get.getId()),
() => {
displayNotFound("Build target", params.buildTarget)
Future.failed(BuildTargetUndefinedException())
},
).asJavaObject
case ServerCommands.DiscoverAndRun(params) =>
getServiceFor(params.path).debugDiscovery(params)
case ServerCommands.AnalyzeStacktrace(content) =>
Future {
// Getting the service for focused document and first one otherwise
val service =
focusedDocument.map(getServiceFor).getOrElse(folderServices.head)
val command = service.analyzeStackTrace(content)
command.foreach(languageClient.metalsExecuteClientCommand)
scribe.debug(s"Executing AnalyzeStacktrace ${command}")
}.asJavaObject
case ServerCommands.GotoSuperMethod(textDocumentPositionParams) =>
getServiceFor(textDocumentPositionParams.getTextDocument().getUri())
.gotoSupermethod(textDocumentPositionParams)
case ServerCommands.SuperMethodHierarchy(textDocumentPositionParams) =>
scribe.debug(s"Executing SuperMethodHierarchy ${params.getCommand()}")
getServiceFor(textDocumentPositionParams.getTextDocument().getUri())
.superMethodHierarchy(textDocumentPositionParams)
case ServerCommands.ResetChoicePopup() =>
val argsMaybe = Option(params.getArguments())
(argsMaybe.flatMap(_.asScala.headOption) match {
case Some(arg: JsonPrimitive) =>
val value = arg.getAsString().replace("+", " ")
scribe.debug(
s"Executing ResetChoicePopup ${params.getCommand()} for choice ${value}"
)
onCurrentFolder(_.resetPopupChoice(value), "reset choice")
case _ =>
scribe.debug(
s"Executing ResetChoicePopup ${params.getCommand()} in interactive mode."
)
onCurrentFolder(
_.interactivePopupChoiceReset(),
"interactive reset choice",
)
}).asJavaObject
case ServerCommands.ResetNotifications() =>
onCurrentFolder(
_.resetNotifications(),
"reset dismissed notifications",
).asJavaObject
case ServerCommands.NewScalaFile(args) =>
val directoryURI = args.lift(0).flatten
val name = args.lift(1).flatten
val fileType = args.lift(2).flatten
directoryURI
.map(getServiceFor)
.getOrElse(folderServices.head)
.createFile(directoryURI, name, fileType, isScala = true)
case ServerCommands.NewJavaFile(args) =>
val directoryURI = args.lift(0).flatten
val name = args.lift(1).flatten
val fileType = args.lift(2).flatten
directoryURI
.map(getServiceFor)
.getOrElse(folderServices.head)
.createFile(directoryURI, name, fileType, isScala = false)
case ServerCommands.StartAmmoniteBuildServer() =>
val res = focusedDocument match {
case None => Future.unit
case Some(path) =>
getServiceFor(path).ammoniteStart()
}
res.asJavaObject
case ServerCommands.StopAmmoniteBuildServer() =>
foreachSeq(_.ammoniteStop(), ignoreValue = false)
case ServerCommands.StartScalaCliServer() =>
val res = focusedDocument match {
case None => Future.unit
case Some(path) =>
getServiceFor(path).startScalaCli(path)
}
res.asJavaObject
case ServerCommands.StopScalaCliServer() =>
foreachSeq(_.stopScalaCli(), ignoreValue = true)
case ServerCommands.NewScalaProject() =>
newProjectProvider.createNewProjectFromTemplate().asJavaObject
case ServerCommands.CopyWorksheetOutput(path) =>
getServiceFor(path).copyWorksheetOutput(path.toAbsolutePath)
case actionCommand
if folderServices.head.allActionCommandsIds(
actionCommand.getCommand()
) =>
val getOptDisplayableMessage: PartialFunction[Throwable, String] = {
case e: DisplayableException => e.getMessage()
case e: Exception if (e.getCause() match {
case _: DisplayableException => true
case _ => false
}) =>
e.getCause().getMessage()
}
CancelTokens.future { token =>
currentFolder
.map(
_.executeCodeActionCommand(params, token)
.recover(
getOptDisplayableMessage andThen (languageClient
.showMessage(lsp4j.MessageType.Info, _))
)
)
.getOrElse(Future.successful(()))
.withObjectValue
}
case cmd =>
ServerCommands.all
.find(command => command.id == cmd.getCommand())
.fold {
scribe.error(s"Unknown command '$cmd'")
} { foundCommand =>
scribe.error(
s"Expected '${foundCommand.arguments}', but got '${cmd.getArguments()}'"
)
}
Future.successful(()).asJavaObject
}
def initialize(): CompletableFuture[lsp4j.InitializeResult] = {
timerProvider
.timed("initialize")(Future {
// load fingerprints from last execution
folderServices.foreach(_.loadFingerPrints())
val capabilities = new lsp4j.ServerCapabilities()
capabilities.setExecuteCommandProvider(
new lsp4j.ExecuteCommandOptions(
(ServerCommands.allIds ++ folderServices.head.allActionCommandsIds).toList.asJava
)
)
capabilities.setFoldingRangeProvider(true)
capabilities.setSelectionRangeProvider(true)
val semanticTokenOptions =
new lsp4j.SemanticTokensWithRegistrationOptions()
semanticTokenOptions.setFull(true)
semanticTokenOptions.setRange(false)
semanticTokenOptions.setLegend(
new lsp4j.SemanticTokensLegend(
pc.SemanticTokens.TokenTypes.asJava,
pc.SemanticTokens.TokenModifiers.asJava,
)
)
capabilities.setSemanticTokensProvider(semanticTokenOptions)
capabilities.setCodeLensProvider(new lsp4j.CodeLensOptions(false))
capabilities.setDefinitionProvider(true)
capabilities.setTypeDefinitionProvider(true)
capabilities.setImplementationProvider(true)