summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/execution/services/ServiceViewManagerImpl.java
blob: 6769b7a4fff1847b5236315e457ff7ea715bc236 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.services;

import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.services.ServiceEventListener.ServiceEvent;
import com.intellij.execution.services.ServiceModel.ServiceViewItem;
import com.intellij.execution.services.ServiceModelFilter.ServiceViewFilter;
import com.intellij.execution.services.ServiceViewDragHelper.ServiceViewDragBean;
import com.intellij.execution.services.ServiceViewModel.*;
import com.intellij.icons.AllIcons;
import com.intellij.ide.lightEdit.LightEditUtil;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.util.treeView.TreeState;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.AppUIExecutor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.ui.AppUIUtil;
import com.intellij.ui.AutoScrollToSourceHandler;
import com.intellij.ui.content.*;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.FactoryMap;
import com.intellij.util.containers.SmartHashSet;
import kotlin.Unit;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.AsyncPromise;
import org.jetbrains.concurrency.Promise;

import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;

import static com.intellij.execution.services.ServiceViewContributor.CONTRIBUTOR_EP_NAME;

@State(name = "ServiceViewManager", storages = @Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE))
public final class ServiceViewManagerImpl implements ServiceViewManager, PersistentStateComponent<ServiceViewManagerImpl.State> {
  private static final @NonNls String HELP_ID = "services.tool.window";

  private final Project myProject;
  private State myState = new State();

  private final ServiceModel myModel;
  private final ServiceModelFilter myModelFilter;
  private final Map<String, Collection<ServiceViewContributor<?>>> myGroups = new ConcurrentHashMap<>();
  private final List<ServiceViewContentHolder> myContentHolders = new SmartList<>();
  private boolean myActivationActionsRegistered;
  private AutoScrollToSourceHandler myAutoScrollToSourceHandler;

  private final Set<String> myActiveToolWindowIds = new SmartHashSet<>();
  private boolean myRegisteringToolWindowAvailable;

  public ServiceViewManagerImpl(@NotNull Project project) {
    myProject = project;
    LightEditUtil.forbidServiceInLightEditMode(project, getClass());
    myModel = new ServiceModel(myProject);
    Disposer.register(myProject, myModel);
    myModelFilter = new ServiceModelFilter();
    loadGroups(CONTRIBUTOR_EP_NAME.getExtensionList());
    myProject.getMessageBus().connect(myModel).subscribe(ServiceEventListener.TOPIC, e -> {
      myModel.handle(e).onSuccess(o -> eventHandled(e));
    });
    initRoots();
    CONTRIBUTOR_EP_NAME.addExtensionPointListener(new ServiceViewExtensionPointListener(), myProject);
  }

  private void eventHandled(@NotNull ServiceEvent e) {
    String toolWindowId = getToolWindowId(e.contributorClass);
    if (toolWindowId == null) {
      return;
    }

    ServiceViewItem eventRoot = ContainerUtil.find(myModel.getRoots(), root -> e.contributorClass.isInstance(root.getRootContributor()));
    if (eventRoot != null) {
      boolean show = !(eventRoot.getViewDescriptor() instanceof ServiceViewNonActivatingDescriptor);
      updateToolWindow(toolWindowId, true, show);
    }
    else {
      Set<? extends ServiceViewContributor<?>> activeContributors = getActiveContributors();
      Collection<ServiceViewContributor<?>> toolWindowContributors = myGroups.get(toolWindowId);
      updateToolWindow(toolWindowId, ContainerUtil.intersects(activeContributors, toolWindowContributors), false);
    }
  }

  private void initRoots() {
    myModel.getInvoker().invokeLater(() -> {
      myModel.initRoots().onSuccess(o -> {
        Set<? extends ServiceViewContributor<?>> activeContributors = getActiveContributors();
        Map<String, Boolean> toolWindowIds = new HashMap<>();
        for (ServiceViewContributor<?> contributor : CONTRIBUTOR_EP_NAME.getExtensionList()) {
          String toolWindowId = getToolWindowId(contributor.getClass());
          if (toolWindowId != null) {
            Boolean active = toolWindowIds.putIfAbsent(toolWindowId, activeContributors.contains(contributor));
            if (active == Boolean.FALSE && activeContributors.contains(contributor)) {
              toolWindowIds.put(toolWindowId, Boolean.TRUE);
            }
          }
        }
        for (Map.Entry<String, Boolean> entry : toolWindowIds.entrySet()) {
          registerToolWindow(entry.getKey(), entry.getValue());
        }
      });
    });
  }

  private Set<? extends ServiceViewContributor<?>> getActiveContributors() {
    return ContainerUtil.map2Set(myModel.getRoots(), ServiceViewItem::getRootContributor);
  }

  private @Nullable ServiceViewContentHolder getContentHolder(@NotNull Class<?> contributorClass) {
    for (ServiceViewContentHolder holder : myContentHolders) {
      for (ServiceViewContributor<?> rootContributor : holder.rootContributors) {
        if (contributorClass.isInstance(rootContributor)) {
          return holder;
        }
      }
    }
    return null;
  }

  private void registerToolWindow(@NotNull String toolWindowId, boolean active) {
    if (myProject.isDefault()) {
      return;
    }

    ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject);
    toolWindowManager.invokeLater(() -> {
      if (!myActivationActionsRegistered) {
        myActivationActionsRegistered = true;
        Collection<ServiceViewContributor<?>> contributors = myGroups.get(ToolWindowId.SERVICES);
        if (contributors != null) {
          registerActivateByContributorActions(myProject, contributors);
        }
      }

      myRegisteringToolWindowAvailable = active;
      try {
        ToolWindow toolWindow = toolWindowManager.registerToolWindow(toolWindowId, builder -> {
          builder.contentFactory = new ServiceViewToolWindowFactory();
          builder.icon = AllIcons.Toolwindows.ToolWindowServices;
          builder.hideOnEmptyContent = false;
          if (toolWindowId.equals(ToolWindowId.SERVICES)) {
            builder.stripeTitle = () -> {
              @NlsSafe String title = toolWindowId;
              return title;
            };
          }
          return Unit.INSTANCE;
        });
        if (active) {
          myActiveToolWindowIds.add(toolWindowId);
        }
        toolWindow.setShowStripeButton(true);
      }
      finally {
        myRegisteringToolWindowAvailable = false;
      }
    });
  }

  private void updateToolWindow(@NotNull String toolWindowId, boolean active, boolean show) {
    if (myProject.isDisposed() || myProject.isDefault()) {
      return;
    }

    ApplicationManager.getApplication().invokeLater(() -> {
      ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(toolWindowId);
      if (toolWindow == null) {
        return;
      }

      if (active) {
        boolean doShow = show && !myActiveToolWindowIds.contains(toolWindowId);
        myActiveToolWindowIds.add(toolWindowId);
        if (doShow) {
          toolWindow.show();
        }
      }
      else if (myActiveToolWindowIds.remove(toolWindowId)) {
        // Hide tool window only if model roots became empty and there were some services shown before update.
        toolWindow.hide();
      }
    }, ModalityState.NON_MODAL, myProject.getDisposed());
  }

  boolean shouldBeAvailable() {
    return myRegisteringToolWindowAvailable;
  }

  void createToolWindowContent(@NotNull ToolWindow toolWindow) {
    String toolWindowId = toolWindow.getId();
    Collection<ServiceViewContributor<?>> contributors = myGroups.get(toolWindowId);
    if (contributors == null) return;

    if (myAutoScrollToSourceHandler == null) {
      myAutoScrollToSourceHandler = ServiceViewSourceScrollHelper.createAutoScrollToSourceHandler(myProject);
    }
    ToolWindowEx toolWindowEx = (ToolWindowEx)toolWindow;
    ServiceViewSourceScrollHelper.installAutoScrollSupport(myProject, toolWindowEx, myAutoScrollToSourceHandler);

    Pair<ServiceViewState, List<ServiceViewState>> states = getServiceViewStates(toolWindowId);
    AllServicesModel mainModel = new AllServicesModel(myModel, myModelFilter, contributors);
    ServiceView mainView = ServiceView.createView(myProject, mainModel, prepareViewState(states.first));
    mainView.setAutoScrollToSourceHandler(myAutoScrollToSourceHandler);

    ContentManager contentManager = toolWindow.getContentManager();
    ServiceViewContentHolder holder = new ServiceViewContentHolder(mainView, contentManager, contributors, toolWindowId);
    myContentHolders.add(holder);
    contentManager.addContentManagerListener(new ServiceViewContentMangerListener(myModelFilter, myAutoScrollToSourceHandler, holder));

    addMainContent(toolWindow.getContentManager(), mainView);
    loadViews(contentManager, mainView, contributors, states.second);
    ServiceViewDragHelper.installDnDSupport(myProject, toolWindowEx.getDecorator(), contentManager);
  }

  private void addMainContent(ContentManager contentManager, ServiceView mainView) {
    Content mainContent = ContentFactory.SERVICE.getInstance().createContent(mainView, null, false);
    mainContent.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE);
    mainContent.setHelpId(getToolWindowContextHelpId());
    mainContent.setCloseable(false);

    Disposer.register(mainContent, mainView);
    Disposer.register(mainContent, mainView.getModel());

    contentManager.addContent(mainContent);
    mainView.getModel().addModelListener(() -> {
      boolean isEmpty = mainView.getModel().getRoots().isEmpty();
      AppUIExecutor.onUiThread().expireWith(myProject).submit(() -> {
        if (contentManager.isDisposed()) return;

        if (isEmpty) {
          if (contentManager.getIndexOfContent(mainContent) < 0) {
            if (contentManager.getContentCount() == 0) {
              contentManager.addContent(mainContent, 0);
            }
          }
          else if (contentManager.getContentCount() > 1) {
              contentManager.removeContent(mainContent, false);
          }
        }
        else {
          if (contentManager.getIndexOfContent(mainContent) < 0) {
            contentManager.addContent(mainContent, 0);
          }
        }
      });
    });
  }

  private void loadViews(ContentManager contentManager,
                         ServiceView mainView,
                         Collection<? extends ServiceViewContributor<?>> contributors,
                         List<ServiceViewState> viewStates) {
    myModel.getInvoker().invokeLater(() -> {
      Map<String, ServiceViewContributor<?>> contributorsMap = FactoryMap.create(className -> {
        for (ServiceViewContributor<?> contributor : contributors) {
          if (className.equals(contributor.getClass().getName())) {
            return contributor;
          }
        }
        return null;
      });
      List<ServiceViewFilter> filters = new ArrayList<>();

      List<Pair<ServiceViewModel, ServiceViewState>> loadedModels = new ArrayList<>();
      ServiceViewModel toSelect = null;

      for (ServiceViewState viewState : viewStates) {
        ServiceViewFilter parentFilter = mainView.getModel().getFilter();
        if (viewState.parentView >= 0 && viewState.parentView < filters.size()) {
          parentFilter = filters.get(viewState.parentView);
        }
        ServiceViewFilter filter = parentFilter;
        ServiceViewModel viewModel = ServiceViewModel.loadModel(viewState, myModel, myModelFilter, parentFilter, contributorsMap);
        if (viewModel != null) {
          loadedModels.add(Pair.create(viewModel, viewState));
          if (viewState.isSelected) {
            toSelect = viewModel;
          }
          filter = viewModel.getFilter();
        }
        filters.add(filter);
      }

      if (!loadedModels.isEmpty()) {
        ServiceViewModel modelToSelect = toSelect;
        AppUIExecutor.onUiThread().expireWith(myProject).submit(() -> {
          for (Pair<ServiceViewModel, ServiceViewState> pair : loadedModels) {
            extract(contentManager, pair.first, pair.second, false);
          }
          selectContentByModel(contentManager, modelToSelect);
        });
      }
    });
  }

  @Override
  public @NotNull Promise<Void> select(@NotNull Object service, @NotNull Class<?> contributorClass, boolean activate, boolean focus) {
    AsyncPromise<Void> result = new AsyncPromise<>();
    // Ensure model is updated, then iterate over service views on EDT in order to find view with service and select it.
    myModel.getInvoker().invoke(() -> AppUIUtil.invokeLaterIfProjectAlive(myProject, () -> {
      String toolWindowId = getToolWindowId(contributorClass);
      if (toolWindowId == null) {
        result.setError("Contributor group not found");
        return;
      }
      Runnable runnable = () -> promiseFindView(contributorClass, result,
                                                serviceView -> serviceView.select(service, contributorClass),
                                                content -> selectContent(content, focus, myProject));
      ToolWindow toolWindow = activate ? ToolWindowManager.getInstance(myProject).getToolWindow(toolWindowId) : null;
      if (toolWindow != null) {
        toolWindow.activate(runnable, focus, focus);
      }
      else {
        runnable.run();
      }
    }));
    return result;
  }

  private void promiseFindView(Class<?> contributorClass, AsyncPromise<Void> result,
                               Function<? super ServiceView, ? extends Promise<?>> action, Consumer<? super Content> onSuccess) {
    ServiceViewContentHolder holder = getContentHolder(contributorClass);
    if (holder == null) {
      result.setError("Content manager not initialized");
      return;
    }
    List<Content> contents = new SmartList<>(holder.contentManager.getContents());
    if (contents.isEmpty()) {
      result.setError("Content not initialized");
      return;
    }
    Collections.reverse(contents);

    promiseFindView(contents.iterator(), result, action, onSuccess);
  }

  private static void promiseFindView(Iterator<? extends Content> iterator, AsyncPromise<Void> result,
                                      Function<? super ServiceView, ? extends Promise<?>> action, Consumer<? super Content> onSuccess) {
    Content content = iterator.next();
    ServiceView serviceView = getServiceView(content);
    if (serviceView == null) {
      if (iterator.hasNext()) {
        promiseFindView(iterator, result, action, onSuccess);
      }
      else {
        result.setError("Not services content");
      }
      return;
    }
    action.apply(serviceView)
      .onSuccess(v -> {
        if (onSuccess != null) {
          onSuccess.accept(content);
        }
        result.setResult(null);
      })
      .onError(e -> {
        if (iterator.hasNext()) {
          promiseFindView(iterator, result, action, onSuccess);
        }
        else {
          result.setError(e);
        }
      });
  }

  private static void selectContent(Content content, boolean focus, Project project) {
    AppUIExecutor.onUiThread().expireWith(project).submit(() -> {
      ContentManager contentManager = content.getManager();
      if (contentManager == null) return;

      if (contentManager.getSelectedContent() != content && contentManager.getIndexOfContent(content) >= 0) {
        contentManager.setSelectedContent(content, focus);
      }
    });
  }

  @Override
  public @NotNull Promise<Void> expand(@NotNull Object service, @NotNull Class<?> contributorClass) {
    AsyncPromise<Void> result = new AsyncPromise<>();
    // Ensure model is updated, then iterate over service views on EDT in order to find view with service and select it.
    myModel.getInvoker().invoke(() -> AppUIUtil.invokeLaterIfProjectAlive(myProject, () ->
      promiseFindView(contributorClass, result,
                    serviceView -> serviceView.expand(service, contributorClass),
                      null)));
    return result;
  }

  @Override
  public @NotNull Promise<Void> extract(@NotNull Object service, @NotNull Class<?> contributorClass) {
    AsyncPromise<Void> result = new AsyncPromise<>();
    myModel.getInvoker().invoke(() -> AppUIUtil.invokeLaterIfProjectAlive(myProject, () ->
      promiseFindView(contributorClass, result,
                      serviceView -> serviceView.extract(service, contributorClass),
                      null)));
    return result;
  }

  @NotNull
  Promise<Void> select(@NotNull VirtualFile virtualFile) {
    List<ServiceViewItem> selectedItems = new SmartList<>();
    for (ServiceViewContentHolder contentHolder : myContentHolders) {
      Content content = contentHolder.contentManager.getSelectedContent();
      if (content == null) continue;

      ServiceView serviceView = getServiceView(content);
      if (serviceView == null) continue;

      List<ServiceViewItem> items = serviceView.getSelectedItems();
      ContainerUtil.addIfNotNull(selectedItems, ContainerUtil.getOnlyItem(items));
    }

    AsyncPromise<Void> result = new AsyncPromise<>();
    myModel.getInvoker().invoke(() -> {
      Condition<? super ServiceViewItem> fileCondition = item -> {
        ServiceViewDescriptor descriptor = item.getViewDescriptor();
        return descriptor instanceof ServiceViewLocatableDescriptor &&
               virtualFile.equals(((ServiceViewLocatableDescriptor)descriptor).getVirtualFile());
      };

      // Multiple services may target to one virtual file.
      // Do nothing if service, targeting to the given virtual file, is selected,
      // otherwise it may lead to jumping selection,
      // if editor have just been selected due to some service selection.
      if (ContainerUtil.find(selectedItems, fileCondition) != null) {
        result.setResult(null);
        return;
      }

      ServiceViewItem fileItem = myModel.findItem(
        fileCondition,
        item -> !(item instanceof ServiceModel.ServiceNode) ||
                item.getViewDescriptor() instanceof ServiceViewLocatableDescriptor
      );
      if (fileItem != null) {
        Promise<Void> promise = select(fileItem.getValue(), fileItem.getRootContributor().getClass(), false, false);
        promise.processed(result);
      }
    });
    return result;
  }

  void extract(@NotNull ServiceViewDragBean dragBean) {
    List<ServiceViewItem> items = dragBean.getItems();
    if (items.isEmpty()) return;

    ServiceView serviceView = dragBean.getServiceView();
    ServiceViewContentHolder holder = getContentHolder(serviceView);
    if (holder == null) return;

    ServiceViewFilter parentFilter = serviceView.getModel().getFilter();
    ServiceViewModel viewModel = ServiceViewModel.createModel(items, dragBean.getContributor(), myModel, myModelFilter, parentFilter);
    ServiceViewState state = new ServiceViewState();
    serviceView.saveState(state);
    extract(holder.contentManager, viewModel, state, true);
  }

  private void extract(ContentManager contentManager, ServiceViewModel viewModel, ServiceViewState viewState, boolean select) {
    ServiceView serviceView = ServiceView.createView(myProject, viewModel, prepareViewState(viewState));
    ItemPresentation presentation = getContentPresentation(myProject, viewModel, viewState);
    if (presentation == null) return;

    Content content = addServiceContent(contentManager, serviceView, presentation, select);
    if (viewModel instanceof GroupModel) {
      extractGroup((GroupModel)viewModel, content);
    }
    else if (viewModel instanceof SingeServiceModel) {
      extractService((SingeServiceModel)viewModel, content);
    }
    else if (viewModel instanceof ServiceListModel) {
      extractList((ServiceListModel)viewModel, content);
    }
  }

  private static void extractGroup(GroupModel viewModel, Content content) {
    viewModel.addModelListener(() -> updateContentTab(viewModel.getGroup(), content));
    updateContentTab(viewModel.getGroup(), content);
  }

  private void extractService(SingeServiceModel viewModel, Content content) {
    ContentManager contentManager = content.getManager();
    viewModel.addModelListener(() -> {
      ServiceViewItem item = viewModel.getService();
      if (item != null && !viewModel.getChildren(item).isEmpty() && contentManager != null) {
        AppUIExecutor.onUiThread().expireWith(myProject).submit(() -> {
          ServiceViewItem viewItem = viewModel.getService();
          if (viewItem == null) return;

          int index = contentManager.getIndexOfContent(content);
          if (index < 0) return;

          contentManager.removeContent(content, true);
          ServiceListModel listModel = new ServiceListModel(myModel, myModelFilter, new SmartList<>(viewItem),
                                                            viewModel.getFilter().getParent());
          ServiceView listView = ServiceView.createView(myProject, listModel, prepareViewState(new ServiceViewState()));
          Content listContent =
            addServiceContent(contentManager, listView, viewItem.getViewDescriptor().getContentPresentation(), true, index);
          extractList(listModel, listContent);
        });
      }
      else {
        updateContentTab(item, content);
      }
    });
    updateContentTab(viewModel.getService(), content);
  }

  private static void extractList(ServiceListModel viewModel, Content content) {
    viewModel.addModelListener(() -> updateContentTab(ContainerUtil.getOnlyItem(viewModel.getRoots()), content));
    updateContentTab(ContainerUtil.getOnlyItem(viewModel.getRoots()), content);
  }

  private static ItemPresentation getContentPresentation(Project project, ServiceViewModel viewModel, ServiceViewState viewState) {
    if (viewModel instanceof ContributorModel) {
      return ((ContributorModel)viewModel).getContributor().getViewDescriptor(project).getContentPresentation();
    }
    else if (viewModel instanceof GroupModel) {
      return ((GroupModel)viewModel).getGroup().getViewDescriptor().getContentPresentation();
    }
    else if (viewModel instanceof SingeServiceModel) {
      return ((SingeServiceModel)viewModel).getService().getViewDescriptor().getContentPresentation();
    }
    else if (viewModel instanceof ServiceListModel) {
      List<ServiceViewItem> items = ((ServiceListModel)viewModel).getItems();
      if (items.size() == 1) {
        return items.get(0).getViewDescriptor().getContentPresentation();
      }
      String name = viewState.id;
      if (StringUtil.isEmpty(name)) {
        name = Messages.showInputDialog(project,
                                        ExecutionBundle.message("service.view.group.label"),
                                        ExecutionBundle.message("service.view.group.title"),
                                        null, null, null);
        if (StringUtil.isEmpty(name)) return null;
      }
      return new PresentationData(name, null, AllIcons.Nodes.Folder, null);
    }
    return null;
  }

  private static Content addServiceContent(ContentManager contentManager, ServiceView serviceView, ItemPresentation presentation,
                                           boolean select) {
    return addServiceContent(contentManager, serviceView, presentation, select, -1);
  }

  private static Content addServiceContent(ContentManager contentManager, ServiceView serviceView, ItemPresentation presentation,
                                           boolean select, int index) {
    Content content =
      ContentFactory.SERVICE.getInstance().createContent(serviceView, ServiceViewDragHelper.getDisplayName(presentation), false);
    content.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE);
    content.setHelpId(getToolWindowContextHelpId());
    content.setCloseable(true);
    content.setIcon(presentation.getIcon(false));

    Disposer.register(content, serviceView);
    Disposer.register(content, serviceView.getModel());

    contentManager.addContent(content, index);
    if (select) {
      contentManager.setSelectedContent(content);
    }
    return content;
  }

  private static void updateContentTab(ServiceViewItem item, Content content) {
    if (item != null) {
      WeakReference<ServiceViewItem> itemRef = new WeakReference<>(item);
      AppUIExecutor.onUiThread().expireWith(content).submit(() -> {
        ServiceViewItem viewItem = itemRef.get();
        if (viewItem == null) return;

        ItemPresentation itemPresentation = viewItem.getViewDescriptor().getContentPresentation();
        content.setDisplayName(ServiceViewDragHelper.getDisplayName(itemPresentation));
        content.setIcon(itemPresentation.getIcon(false));
        content.setTabColor(viewItem.getColor());
      });
    }
  }

  private void loadGroups(Collection<? extends ServiceViewContributor<?>> contributors) {
    if (Registry.is("ide.service.view.split")) {
      for (ServiceViewContributor<?> contributor : contributors) {
        myGroups.put(contributor.getViewDescriptor(myProject).getId(), new SmartList<>(contributor));
      }
    }
    else if (!contributors.isEmpty()) {
      String servicesToolWindowId = ToolWindowId.SERVICES;
      Collection<ServiceViewContributor<?>> servicesContributors =
        myGroups.computeIfAbsent(servicesToolWindowId, __ -> ContainerUtil.newConcurrentSet());
      servicesContributors.addAll(contributors);
    }
  }

  private @NotNull Pair<ServiceViewState, List<ServiceViewState>> getServiceViewStates(@NotNull String groupId) {
    List<ServiceViewState> states = ContainerUtil.filter(myState.viewStates, state -> groupId.equals(state.groupId));
    ServiceViewState mainState = ContainerUtil.find(states, state -> StringUtil.isEmpty(state.viewType));
    if (mainState == null) {
      mainState = new ServiceViewState();
    }
    else {
      states.remove(mainState);
    }
    return Pair.create(mainState, states);
  }

  @Override
  public @NotNull State getState() {
    ContainerUtil.retainAll(myState.viewStates, state -> myGroups.containsKey(state.groupId));
    for (ServiceViewContentHolder holder : myContentHolders) {
      ContainerUtil.retainAll(myState.viewStates, state -> !holder.toolWindowId.equals(state.groupId));

      ServiceViewFilter mainFilter = holder.mainView.getModel().getFilter();
      ServiceViewState mainState = new ServiceViewState();
      myState.viewStates.add(mainState);
      holder.mainView.saveState(mainState);
      mainState.groupId = holder.toolWindowId;
      mainState.treeStateElement = new Element("root");
      mainState.treeState.writeExternal(mainState.treeStateElement);
      mainState.clearTreeState();

      List<ServiceView> processedViews = new SmartList<>();
      for (Content content : holder.contentManager.getContents()) {
        ServiceView serviceView = getServiceView(content);
        if (serviceView == null || isMainView(serviceView)) continue;

        ServiceViewState viewState = new ServiceViewState();
        processedViews.add(serviceView);
        myState.viewStates.add(viewState);
        serviceView.saveState(viewState);
        viewState.groupId = holder.toolWindowId;
        viewState.isSelected = holder.contentManager.isSelected(content);
        ServiceViewModel viewModel = serviceView.getModel();
        if (viewModel instanceof ServiceListModel) {
          viewState.id = content.getDisplayName();
        }
        ServiceViewFilter parentFilter = viewModel.getFilter().getParent();
        if (parentFilter != null && !parentFilter.equals(mainFilter)) {
          for (int i = 0; i < processedViews.size(); i++) {
            ServiceView parentView = processedViews.get(i);
            if (parentView.getModel().getFilter().equals(parentFilter)) {
              viewState.parentView = i;
              break;
            }
          }
        }

        viewState.treeStateElement = new Element("root");
        viewState.treeState.writeExternal(viewState.treeStateElement);
        viewState.clearTreeState();
      }
    }

    return myState;
  }

  @Override
  public void loadState(@NotNull State state) {
    myState = state;
    for (ServiceViewState viewState : myState.viewStates) {
      viewState.treeState = TreeState.createFrom(viewState.treeStateElement);
    }
  }

  static final class State {
    public List<ServiceViewState> viewStates = new ArrayList<>();
    public boolean showServicesTree = true;
  }

  static String getToolWindowContextHelpId() {
    return HELP_ID;
  }

  private ServiceViewState prepareViewState(ServiceViewState state) {
    state.showServicesTree = myState.showServicesTree;
    return state;
  }

  boolean isShowServicesTree() {
    return myState.showServicesTree;
  }

  void setShowServicesTree(boolean value) {
    myState.showServicesTree = value;
    for (ServiceViewContentHolder holder : myContentHolders) {
      for (ServiceView serviceView : holder.getServiceViews()) {
        serviceView.getUi().setMasterComponentVisible(value);
      }
    }
  }

  boolean isSplitByTypeEnabled(@NotNull ServiceView selectedView) {
    if (!isMainView(selectedView) ||
        selectedView.getModel().getVisibleRoots().isEmpty()) {
      return false;
    }

    ServiceViewContentHolder holder = getContentHolder(selectedView);
    if (holder == null) return false;

    for (Content content : holder.contentManager.getContents()) {
      ServiceView serviceView = getServiceView(content);
      if (serviceView != null && serviceView != selectedView && !(serviceView.getModel() instanceof ContributorModel)) return false;
    }
    return true;
  }

  void splitByType(@NotNull ServiceView selectedView) {
    ServiceViewContentHolder holder = getContentHolder(selectedView);
    if (holder == null) return;

    myModel.getInvoker().invokeLater(() -> {
      List<ServiceViewContributor<?>> contributors = ContainerUtil.map(myModel.getRoots(), ServiceViewItem::getRootContributor);
      AppUIUtil.invokeOnEdt(() -> {
        for (ServiceViewContributor<?> contributor : contributors) {
          splitByType(holder.contentManager, contributor);
        }
      });
    });
  }

  private ServiceViewContentHolder getContentHolder(ServiceView serviceView) {
    for (ServiceViewContentHolder holder : myContentHolders) {
      if (holder.getServiceViews().contains(serviceView)) {
        return holder;
      }
    }
    return null;
  }

  private void splitByType(ContentManager contentManager, ServiceViewContributor<?> contributor) {
    for (Content content : contentManager.getContents()) {
      ServiceView serviceView = getServiceView(content);
      if (serviceView != null) {
        ServiceViewModel viewModel = serviceView.getModel();
        if (viewModel instanceof ContributorModel && contributor.equals(((ContributorModel)viewModel).getContributor())) {
          return;
        }
      }
    }

    ContributorModel contributorModel = new ContributorModel(myModel, myModelFilter, contributor, null);
    extract(contentManager, contributorModel, prepareViewState(new ServiceViewState()), true);
  }

  public @NotNull List<Object> getChildrenSafe(@NotNull AnActionEvent e, @NotNull List<Object> valueSubPath, @NotNull Class<?> contributorClass) {
    ServiceView serviceView = ServiceViewActionProvider.getSelectedView(e);
    return serviceView != null ? serviceView.getChildrenSafe(valueSubPath, contributorClass) : Collections.emptyList();
  }

  public @Nullable String getToolWindowId(@NotNull Class<?> contributorClass) {
    for (Map.Entry<String, Collection<ServiceViewContributor<?>>> entry : myGroups.entrySet()) {
      if (entry.getValue().stream().anyMatch(contributorClass::isInstance)) {
        return entry.getKey();
      }
    }
    return null;
  }

  private static boolean isMainView(@NotNull ServiceView serviceView) {
    return serviceView.getModel() instanceof AllServicesModel;
  }

  private static @Nullable Content getMainContent(@NotNull ContentManager contentManager) {
    for (Content content : contentManager.getContents()) {
      ServiceView serviceView = getServiceView(content);
      if (serviceView != null && isMainView(serviceView)) {
        return content;
      }
    }
    return null;
  }

  private static @Nullable ServiceView getServiceView(Content content) {
    Object component = content.getComponent();
    return component instanceof ServiceView ? (ServiceView)component : null;
  }

  private static void selectContentByModel(@NotNull ContentManager contentManager, @Nullable ServiceViewModel modelToSelect) {
    if (modelToSelect != null) {
      for (Content content : contentManager.getContents()) {
        ServiceView serviceView = getServiceView(content);
        if (serviceView != null && serviceView.getModel() == modelToSelect) {
          contentManager.setSelectedContent(content);
          break;
        }
      }
    }
    else {
      Content content = getMainContent(contentManager);
      if (content != null) {
        contentManager.setSelectedContent(content);
      }
    }
  }

  private static void selectContentByContributor(@NotNull ContentManager contentManager, @NotNull ServiceViewContributor<?> contributor) {
    Content mainContent = null;
    for (Content content : contentManager.getContents()) {
      ServiceView serviceView = getServiceView(content);
      if (serviceView != null) {
        if (serviceView.getModel() instanceof ContributorModel &&
            contributor.equals(((ContributorModel)serviceView.getModel()).getContributor())) {
          contentManager.setSelectedContent(content, true);
          return;
        }
        if (isMainView(serviceView)) {
          mainContent = content;
        }
      }
    }
    if (mainContent != null) {
      contentManager.setSelectedContent(mainContent, true);
    }
  }

  private static final class ServiceViewContentMangerListener implements ContentManagerListener {
    private final ServiceModelFilter myModelFilter;
    private final AutoScrollToSourceHandler myAutoScrollToSourceHandler;
    private final ServiceViewContentHolder myContentHolder;
    private final ContentManager myContentManager;

    ServiceViewContentMangerListener(@NotNull ServiceModelFilter modelFilter,
                                     @NotNull AutoScrollToSourceHandler toSourceHandler,
                                     @NotNull ServiceViewContentHolder contentHolder) {
      myModelFilter = modelFilter;
      myAutoScrollToSourceHandler = toSourceHandler;
      myContentHolder = contentHolder;
      myContentManager = contentHolder.contentManager;
    }

    @Override
    public void contentAdded(@NotNull ContentManagerEvent event) {
      Content content = event.getContent();
      ServiceView serviceView = getServiceView(content);
      if (serviceView != null && !isMainView(serviceView)) {
        serviceView.setAutoScrollToSourceHandler(myAutoScrollToSourceHandler);
        myModelFilter.addFilter(serviceView.getModel().getFilter());
        myContentHolder.processAllModels(ServiceViewModel::filtersChanged);

        serviceView.getModel().addModelListener(() -> {
          if (serviceView.getModel().getRoots().isEmpty()) {
            AppUIExecutor.onUiThread().expireWith(myContentManager).submit(() -> myContentManager.removeContent(content, true));
          }
        });
      }

      if (myContentManager.getContentCount() > 1) {
        Content mainContent = getMainContent(myContentManager);
        if (mainContent != null) {
          mainContent.setDisplayName(ExecutionBundle.message("service.view.all.services"));
        }
      }
    }

    @Override
    public void contentRemoved(@NotNull ContentManagerEvent event) {
      ServiceView serviceView = getServiceView(event.getContent());
      if (serviceView != null && !isMainView(serviceView)) {
        myModelFilter.removeFilter(serviceView.getModel().getFilter());
        myContentHolder.processAllModels(ServiceViewModel::filtersChanged);
      }
      if (myContentManager.getContentCount() == 1) {
        Content mainContent = getMainContent(myContentManager);
        if (mainContent != null) {
          mainContent.setDisplayName(null);
        }
      }
    }

    @Override
    public void selectionChanged(@NotNull ContentManagerEvent event) {
      ServiceView serviceView = getServiceView(event.getContent());
      if (serviceView == null) return;

      if (event.getOperation() == ContentManagerEvent.ContentOperation.add) {
        serviceView.onViewSelected();
      }
      else {
        serviceView.onViewUnselected();
      }
    }
  }

  private static void registerActivateByContributorActions(Project project, Collection<? extends ServiceViewContributor<?>> contributors) {
    for (ServiceViewContributor<?> contributor : contributors) {
      ActionManager actionManager = ActionManager.getInstance();
      String actionId = getActivateContributorActionId(contributor);
      if (actionId == null) continue;

      AnAction action = actionManager.getAction(actionId);
      if (action == null) {
        action = new ActivateToolWindowByContributorAction(contributor, contributor.getViewDescriptor(project).getPresentation());
        actionManager.registerAction(actionId, action);
      }
    }
  }

  private static String getActivateContributorActionId(ServiceViewContributor<?> contributor) {
    String name = contributor.getClass().getSimpleName();
    return name.isEmpty() ? null : "ServiceView.Activate" + name;
  }

  private final class ServiceViewExtensionPointListener implements ExtensionPointListener<ServiceViewContributor<?>> {
    @Override
    public void extensionAdded(@NotNull ServiceViewContributor<?> extension, @NotNull PluginDescriptor pluginDescriptor) {
      List<ServiceViewContributor<?>> contributors = new SmartList<>(extension);
      loadGroups(contributors);
      String toolWindowId = getToolWindowId(extension.getClass());
      boolean register = myGroups.get(toolWindowId).size() == 1;
      ServiceEvent e = ServiceEvent.createResetEvent(extension.getClass());
      myModel.handle(e).onSuccess(o -> {
        if (register) {
          ServiceViewItem eventRoot = ContainerUtil.find(myModel.getRoots(), root -> {
            return extension.getClass().isInstance(root.getRootContributor());
          });
          assert toolWindowId != null;
          registerToolWindow(toolWindowId, eventRoot != null);
        }
        else {
          eventHandled(e);
        }
        if (ToolWindowId.SERVICES.equals(toolWindowId)) {
          AppUIExecutor.onUiThread().expireWith(myProject).submit(() -> registerActivateByContributorActions(myProject, contributors));
        }
      });
    }

    @Override
    public void extensionRemoved(@NotNull ServiceViewContributor<?> extension, @NotNull PluginDescriptor pluginDescriptor) {
      ServiceEvent e = ServiceEvent.createSyncResetEvent(extension.getClass());
      myModel.handle(e).onProcessed(o -> {
        eventHandled(e);

        for (Map.Entry<String, Collection<ServiceViewContributor<?>>> entry : myGroups.entrySet()) {
          if (entry.getValue().remove(extension)) {
            if (entry.getValue().isEmpty()) {
              unregisterToolWindow(entry.getKey());
            }
            break;
          }
        }

        unregisterActivateByContributorActions(extension);
      });
    }

    private void unregisterToolWindow(String toolWindowId) {
      myActiveToolWindowIds.remove(toolWindowId);
      myGroups.remove(toolWindowId);
      for (ServiceViewContentHolder holder : myContentHolders) {
        if (holder.toolWindowId.equals(toolWindowId)) {
          myContentHolders.remove(holder);
          break;
        }
      }
      ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject);
      toolWindowManager.invokeLater(() -> {
        if (myProject.isDisposed() || myProject.isDefault()) return;

        ToolWindow toolWindow = toolWindowManager.getToolWindow(toolWindowId);
        if (toolWindow != null) {
          toolWindow.remove();
        }
      });
    }

    private void unregisterActivateByContributorActions(ServiceViewContributor<?> extension) {
      String actionId = getActivateContributorActionId(extension);
      if (actionId != null) {
        ActionManager actionManager = ActionManager.getInstance();
        AnAction action = actionManager.getAction(actionId);
        if (action != null) {
          actionManager.unregisterAction(actionId);
        }
      }
    }
  }

  private static class ActivateToolWindowByContributorAction extends DumbAwareAction {
    private final ServiceViewContributor<?> myContributor;

    ActivateToolWindowByContributorAction(ServiceViewContributor<?> contributor, ItemPresentation contributorPresentation) {
      myContributor = contributor;
      Presentation templatePresentation = getTemplatePresentation();
      templatePresentation.setText(ExecutionBundle.messagePointer("service.view.activate.tool.window.action.name",
                                                               ServiceViewDragHelper.getDisplayName(contributorPresentation)));
      templatePresentation.setIcon(contributorPresentation.getIcon(false));
      templatePresentation.setDescription(ExecutionBundle.messagePointer("service.view.activate.tool.window.action.description"));
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      Project project = e.getProject();
      if (project == null) return;

      String toolWindowId =
        ((ServiceViewManagerImpl)ServiceViewManager.getInstance(project)).getToolWindowId(myContributor.getClass());
      if (toolWindowId == null) return;

      ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(toolWindowId);
      if (toolWindow != null) {
        toolWindow.activate(() -> {
          ServiceViewContentHolder holder =
            ((ServiceViewManagerImpl)ServiceViewManager.getInstance(project)).getContentHolder(myContributor.getClass());
          if (holder != null) {
            selectContentByContributor(holder.contentManager, myContributor);
          }
        });
      }
    }
  }

  private static class ServiceViewContentHolder {
    final ServiceView mainView;
    final ContentManager contentManager;
    final Collection<ServiceViewContributor<?>> rootContributors;
    final String toolWindowId;

    ServiceViewContentHolder(ServiceView mainView,
                             ContentManager contentManager,
                             Collection<ServiceViewContributor<?>> rootContributors,
                             String toolWindowId) {
      this.mainView = mainView;
      this.contentManager = contentManager;
      this.rootContributors = rootContributors;
      this.toolWindowId = toolWindowId;
    }

    List<ServiceView> getServiceViews() {
      List<ServiceView> views = ContainerUtil.mapNotNull(contentManager.getContents(), ServiceViewManagerImpl::getServiceView);
      if (views.isEmpty()) return new SmartList<>(mainView);

      if (!views.contains(mainView)) {
        views.add(0, mainView);
      }
      return views;
    }

    private void processAllModels(Consumer<? super ServiceViewModel> consumer) {
      List<ServiceViewModel> models = ContainerUtil.map(getServiceViews(), ServiceView::getModel);
      ServiceViewModel model = ContainerUtil.getFirstItem(models);
      if (model != null) {
        model.getInvoker().invokeLater(() -> {
          for (ServiceViewModel viewModel : models) {
            consumer.accept(viewModel);
          }
        });
      }
    }
  }
}