@Override
    public void navigate(MouseEvent mouseEvent, PsiElement element) {
      PsiElement parent = element.getParent();
      if (!(parent instanceof DotNetVirtualImplementOwner)
          || !OverrideUtil.isAllowForOverride(parent)) {
        return;
      }

      Collection<DotNetVirtualImplementOwner> members =
          OverrideUtil.collectOverridenMembers(((DotNetVirtualImplementOwner) parent));

      if (members.isEmpty()) {
        return;
      }

      if (members.size() == 1) {
        DotNetVirtualImplementOwner firstItem = ContainerUtil.getFirstItem(members);
        if (firstItem instanceof Navigatable) {
          ((Navigatable) firstItem).navigate(true);
        }
      } else {
        PsiElement[] elements = members.toArray(new PsiElement[members.size()]);

        JBPopup popup =
            NavigationUtil.getPsiElementPopup(
                elements,
                new ElementGutterRender(),
                "Open elements (" + elements.length + " " + "items)" + "");
        popup.show(new RelativePoint(mouseEvent));
      }
    }
  private void doUpdateRanges(
      int beforeChangedLine1, int beforeChangedLine2, int linesShift, int beforeTotalLines) {
    List<Range> rangesBeforeChange = new ArrayList<Range>();
    List<Range> rangesAfterChange = new ArrayList<Range>();
    List<Range> changedRanges = new ArrayList<Range>();

    sortRanges(
        beforeChangedLine1,
        beforeChangedLine2,
        linesShift,
        rangesBeforeChange,
        changedRanges,
        rangesAfterChange);

    Range firstChangedRange = ContainerUtil.getFirstItem(changedRanges);
    Range lastChangedRange = ContainerUtil.getLastItem(changedRanges);

    if (firstChangedRange != null && firstChangedRange.getLine1() < beforeChangedLine1) {
      beforeChangedLine1 = firstChangedRange.getLine1();
    }
    if (lastChangedRange != null && lastChangedRange.getLine2() > beforeChangedLine2) {
      beforeChangedLine2 = lastChangedRange.getLine2();
    }

    doUpdateRanges(
        beforeChangedLine1,
        beforeChangedLine2,
        linesShift,
        beforeTotalLines,
        rangesBeforeChange,
        changedRanges,
        rangesAfterChange);
  }
  @Override
  public void customizePainter(
      @NotNull JComponent component,
      @NotNull Collection<VcsRef> references,
      @Nullable VcsLogRefManager manager,
      @NotNull Color background,
      @NotNull Color foreground) {
    FontMetrics metrics = component.getFontMetrics(getReferenceFont());
    myHeight =
        metrics.getHeight()
            + RectanglePainter.TOP_TEXT_PADDING
            + RectanglePainter.BOTTOM_TEXT_PADDING;
    myWidth = 2 * PaintParameters.LABEL_PADDING;

    myLabels = ContainerUtil.newArrayList();
    if (manager == null) return;

    List<VcsRef> sorted = ContainerUtil.sorted(references, manager.getLabelsOrderComparator());

    for (Map.Entry<VcsRefType, Collection<VcsRef>> entry :
        ContainerUtil.groupBy(sorted, VcsRef::getType).entrySet()) {
      VcsRef ref = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(entry.getValue()));
      String text = ref.getName() + (entry.getValue().size() > 1 ? " +" : "");
      myLabels.add(Pair.create(text, entry.getKey().getBackgroundColor()));

      myWidth +=
          myLabelPainter.calculateSize(text, metrics).getWidth() + PaintParameters.LABEL_PADDING;
    }
  }
 private UnionScope(@NotNull GlobalSearchScope[] scopes) {
   super(
       ContainerUtil.getFirstItem(
           ContainerUtil.mapNotNull(
               scopes,
               new Function<GlobalSearchScope, Project>() {
                 @Override
                 public Project fun(GlobalSearchScope scope) {
                   return scope.getProject();
                 }
               }),
           null));
   if (scopes.length <= 1)
     throw new IllegalArgumentException("Too few scopes: " + Arrays.asList(scopes));
   myScopes = scopes;
   final int[] nested = {0};
   ContainerUtil.process(
       scopes,
       new Processor<GlobalSearchScope>() {
         @Override
         public boolean process(GlobalSearchScope scope) {
           nested[0] =
               Math.max(
                   nested[0],
                   scope instanceof UnionScope ? ((UnionScope) scope).myNestingLevel : 0);
           return true;
         }
       });
   myNestingLevel = 1 + nested[0];
   if (myNestingLevel > 1000) {
     throw new IllegalStateException(
         "Too many scopes combined: " + myNestingLevel + StringUtil.last(toString(), 500, true));
   }
 }
  private static Groups prepareGroups(
      @NotNull VcsLogDataPack dataPack,
      @Nullable Collection<VirtualFile> visibleRoots,
      @Nullable List<List<String>> recentItems) {
    Groups filteredGroups = new Groups();
    Collection<VcsRef> allRefs = dataPack.getRefs().getBranches();
    for (Map.Entry<VirtualFile, Set<VcsRef>> entry :
        VcsLogUtil.groupRefsByRoot(allRefs).entrySet()) {
      VirtualFile root = entry.getKey();
      if (visibleRoots != null && !visibleRoots.contains(root)) continue;
      Collection<VcsRef> refs = entry.getValue();
      VcsLogProvider provider = dataPack.getLogProviders().get(root);
      VcsLogRefManager refManager = provider.getReferenceManager();
      List<RefGroup> refGroups = refManager.group(refs);

      putActionsForReferences(refGroups, filteredGroups);
    }

    if (recentItems != null) {
      for (List<String> recentItem : recentItems) {
        if (recentItem.size() == 1) {
          final String item = ContainerUtil.getFirstItem(recentItem);
          if (filteredGroups.singletonGroups.contains(item)
              || ContainerUtil.find(
                      filteredGroups.expandedGroups.values(), strings -> strings.contains(item))
                  != null) {
            continue;
          }
        }
        filteredGroups.recentGroups.add(recentItem);
      }
    }

    return filteredGroups;
  }
  private void updateActiveTarget(
      @Nullable RunnerAndConfigurationSettings settings, @Nullable ExecutionTarget toSelect) {
    List<ExecutionTarget> suitable =
        settings == null
            ? Collections.singletonList(DefaultExecutionTarget.INSTANCE)
            : getTargetsFor(settings);
    ExecutionTarget toNotify;
    synchronized (myActiveTargetLock) {
      if (toSelect == null) toSelect = myActiveTarget;

      int index = -1;
      if (toSelect != null) {
        index = suitable.indexOf(toSelect);
      } else if (mySavedActiveTargetId != null) {
        for (int i = 0, size = suitable.size(); i < size; i++) {
          if (suitable.get(i).getId().equals(mySavedActiveTargetId)) {
            index = i;
            break;
          }
        }
      }
      toNotify =
          doSetActiveTarget(
              index >= 0
                  ? suitable.get(index)
                  : ContainerUtil.getFirstItem(suitable, DefaultExecutionTarget.INSTANCE));
    }

    if (toNotify != null) {
      myProject.getMessageBus().syncPublisher(TOPIC).activeTargetChanged(toNotify);
    }
  }
 @Nullable
 private String getLatestPackageVersionFromPyPI(@NotNull String packageName) throws IOException {
   LOG.debug("Requesting the latest PyPI version for the package " + packageName);
   final List<String> versions = getPackageVersionsFromPyPI(packageName, true);
   final String latest = ContainerUtil.getFirstItem(versions);
   getPyPIPackages().put(packageName, StringUtil.notNullize(latest));
   return latest;
 }
 @Override
 public PsiElement resolveInner() {
   GlobalSearchScope scope = getSearchScope();
   List<ErlangModule> modules =
       ErlangModuleIndex.getModulesByName(myElement.getProject(), myReferenceName, scope);
   if (modules.size() > 1) {
     ContainerUtil.sort(modules, new ModuleResolutionComparator());
   }
   return ContainerUtil.getFirstItem(modules);
 }
 @NotNull
 private String findPresetHttpUrl() {
   return ObjectUtils.chooseNotNull(
       ContainerUtil.find(
           myUrlsFromCommand,
           url -> {
             String scheme = UriUtil.splitScheme(url).getFirst();
             return scheme.startsWith("http");
           }),
       ContainerUtil.getFirstItem(myUrlsFromCommand));
 }
 @Nullable
 private IProperty getSelectedProperty() {
   final Collection<DefaultMutableTreeNode> selectedNode = getSelectedNodes();
   if (selectedNode.isEmpty()) {
     return null;
   }
   final ResourceBundleEditorViewElement element =
       getSelectedElement(ContainerUtil.getFirstItem(selectedNode));
   return element instanceof ResourceBundlePropertyStructureViewElement
       ? ((ResourceBundlePropertyStructureViewElement) element).getProperty()
       : null;
 }
  @NotNull
  public static <T> Promise<T> chooseDebuggee(
      @NotNull final Collection<T> targets,
      final int selectedIndex,
      @NotNull final Function<T, String> itemToString) {
    if (targets.size() == 1) {
      return Promise.resolve(ContainerUtil.getFirstItem(targets));
    } else if (targets.isEmpty()) {
      return Promise.reject("No tabs to inspect");
    }

    final AsyncPromise<T> result = new AsyncPromise<T>();
    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              @Override
              public void run() {
                final JBList list = new JBList(targets);
                list.setCellRenderer(
                    new ColoredListCellRenderer() {
                      @Override
                      protected void customizeCellRenderer(
                          JList list, Object value, int index, boolean selected, boolean hasFocus) {
                        //noinspection unchecked
                        append(itemToString.fun((T) value));
                      }
                    });
                if (selectedIndex != -1) {
                  list.setSelectedIndex(selectedIndex);
                }

                JBPopupFactory.getInstance()
                    .createListPopupBuilder(list)
                    .setTitle("Choose Page to Debug")
                    .setItemChoosenCallback(
                        new Runnable() {
                          @Override
                          public void run() {
                            @SuppressWarnings("unchecked")
                            T value = (T) list.getSelectedValue();
                            if (value == null) {
                              result.setError(Promise.createError("No target to inspect"));
                            } else {
                              result.setResult(value);
                            }
                          }
                        })
                    .createPopup()
                    .showInFocusCenter();
              }
            });
    return result;
  }
  private void doUpdateRanges(
      int beforeChangedLine1,
      int beforeChangedLine2,
      int linesShift, // before -> after
      int beforeTotalLines,
      @NotNull List<Range> rangesBefore,
      @NotNull List<Range> changedRanges,
      @NotNull List<Range> rangesAfter) {
    try {
      int vcsTotalLines = getLineCount(myVcsDocument);

      Range lastRangeBefore = ContainerUtil.getLastItem(rangesBefore);
      Range firstRangeAfter = ContainerUtil.getFirstItem(rangesAfter);

      //noinspection UnnecessaryLocalVariable
      int afterChangedLine1 = beforeChangedLine1;
      int afterChangedLine2 = beforeChangedLine2 + linesShift;

      int vcsLine1 = getVcsLine1(lastRangeBefore, beforeChangedLine1);
      int vcsLine2 =
          getVcsLine2(firstRangeAfter, beforeChangedLine2, beforeTotalLines, vcsTotalLines);

      List<Range> newChangedRanges =
          getNewChangedRanges(afterChangedLine1, afterChangedLine2, vcsLine1, vcsLine2);

      shiftRanges(rangesAfter, linesShift);

      if (!changedRanges.equals(newChangedRanges)) {
        replaceRanges(changedRanges, newChangedRanges);

        myRanges =
            new ArrayList<Range>(
                rangesBefore.size() + newChangedRanges.size() + rangesAfter.size());

        myRanges.addAll(rangesBefore);
        myRanges.addAll(newChangedRanges);
        myRanges.addAll(rangesAfter);

        for (Range range : myRanges) {
          if (!range.hasHighlighter()) range.setHighlighter(createHighlighter(range));
        }

        if (myRanges.isEmpty()) {
          markFileUnchanged();
        }
      }
    } catch (ProcessCanceledException ignore) {
    } catch (FilesTooBigForDiffException e1) {
      installAnathema();
      removeHighlightersFromMarkupModel();
    }
  }
  public void testNoParenthesisSurrounderForLambdaParameter() {
    configureByFile(BASE_PATH + getTestName(false) + ".java");

    SurroundDescriptor item =
        ContainerUtil.getFirstItem(
            LanguageSurrounders.INSTANCE.allForLanguage(JavaLanguage.INSTANCE));
    assertNotNull(item);
    SelectionModel selectionModel = getEditor().getSelectionModel();
    PsiElement[] elements =
        item.getElementsToSurround(
            getFile(), selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
    assertEmpty(elements);
  }
  @Override
  public void actionPerformed(AnActionEvent e) {
    final Project project = getProject(e);
    final ProjectSystemId projectSystemId = getSystemId(e);

    final List<ExternalSystemNode> selectedNodes =
        ExternalSystemDataKeys.SELECTED_NODES.getData(e.getDataContext());

    final ExternalProjectInfo projectInfo;
    final ExternalSystemNode<?> externalSystemNode = ContainerUtil.getFirstItem(selectedNodes);
    if (externalSystemNode == null) {
      projectInfo =
          ContainerUtil.getFirstItem(
              ProjectDataManager.getInstance().getExternalProjectsData(project, projectSystemId));
    } else {
      final ProjectNode projectNode =
          externalSystemNode instanceof ProjectNode
              ? (ProjectNode) externalSystemNode
              : externalSystemNode.findParent(ProjectNode.class);
      assert projectNode != null;

      final ProjectData projectData = projectNode.getData();
      assert projectData != null;
      projectInfo =
          ProjectDataManager.getInstance()
              .getExternalProjectData(
                  project, projectSystemId, projectData.getLinkedExternalProjectPath());
    }

    final ExternalProjectDataSelectorDialog dialog;
    if (projectInfo != null) {
      dialog =
          new ExternalProjectDataSelectorDialog(
              project,
              projectInfo,
              externalSystemNode != null ? externalSystemNode.getData() : null);
      dialog.showAndGet();
    }
  }
  public static void addTypeAndClassifierAndVersion(
      @NotNull InsertionContext context,
      @NotNull MavenDomDependency dependency,
      @NotNull String groupId,
      @NotNull String artifactId) {
    if (!StringUtil.isEmpty(dependency.getVersion().getStringValue())) return;

    Project project = context.getProject();

    if (!isInsideManagedDependency(dependency)) {
      MavenDomProjectModel model =
          DomUtil.<MavenDomProjectModel>getFileElement(dependency).getRootElement();
      MavenDomDependency managedDependency =
          findManagedDependency(model, project, groupId, artifactId);
      if (managedDependency != null) {
        if (dependency.getClassifier().getXmlTag() == null
            && dependency.getType().getXmlTag() == null) {
          String classifier = managedDependency.getClassifier().getRawText();
          if (StringUtil.isNotEmpty(classifier)) {
            dependency.getClassifier().setStringValue(classifier);
          }
          String type = managedDependency.getType().getRawText();
          if (StringUtil.isNotEmpty(type)) {
            dependency.getType().setStringValue(type);
          }
        }
        return;
      }
    }

    MavenProjectIndicesManager manager = MavenProjectIndicesManager.getInstance(project);

    Set<String> versions = manager.getVersions(groupId, artifactId);
    if (versions.size() == 1) {
      dependency.getVersion().setStringValue(ContainerUtil.getFirstItem(versions));
      return;
    }

    dependency.getVersion().setStringValue("");

    int versionPosition =
        dependency.getVersion().getXmlTag().getValue().getTextRange().getStartOffset();

    context.getEditor().getCaretModel().moveToOffset(versionPosition);

    if (versions.size() > 0) {
      invokeCompletion(context, CompletionType.BASIC);
    }
  }
 public void testEunitFullErrorPath() {
   FileReferenceFilter compilationErrorFilter =
       new FileReferenceFilter(getProject(), EUNIT_ERROR_PATH);
   File base = new File(getProject().getBaseDir().getPath());
   File file =
       ContainerUtil.getFirstItem(FileUtil.findFilesByMask(Pattern.compile(".*\\.erl"), base));
   VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
   assertNotNull(vFile);
   String canonicalPath = vFile.getCanonicalPath();
   final String consoleOutput =
       "in function bisect_server_test:'-false_test/0-fun-0-'/0 (" + canonicalPath + ", line 14)";
   final Filter.Result result =
       compilationErrorFilter.applyFilter(consoleOutput, consoleOutput.length());
   assertNotNull(result.hyperlinkInfo);
 }
 @NotNull
 @Override
 public Condition<CommitId> getContainedInBranchCondition(
     @NotNull final Collection<CommitId> heads) {
   List<Integer> headIds =
       ContainerUtil.map(
           heads,
           new Function<CommitId, Integer>() {
             @Override
             public Integer fun(CommitId head) {
               return myPermanentCommitsInfo.getNodeId(head);
             }
           });
   if (!heads.isEmpty() && ContainerUtil.getFirstItem(heads) instanceof Integer) {
     final TIntHashSet branchNodes = new TIntHashSet();
     myReachableNodes.walk(
         headIds,
         new Consumer<Integer>() {
           @Override
           public void consume(Integer node) {
             branchNodes.add((Integer) myPermanentCommitsInfo.getCommitId(node));
           }
         });
     return new Condition<CommitId>() {
       @Override
       public boolean value(CommitId commitId) {
         return branchNodes.contains((Integer) commitId);
       }
     };
   } else {
     final Set<CommitId> branchNodes = ContainerUtil.newHashSet();
     myReachableNodes.walk(
         headIds,
         new Consumer<Integer>() {
           @Override
           public void consume(Integer node) {
             branchNodes.add(myPermanentCommitsInfo.getCommitId(node));
           }
         });
     return new Condition<CommitId>() {
       @Override
       public boolean value(CommitId commitId) {
         return branchNodes.contains(commitId);
       }
     };
   }
 }
  private void doTest(@NotNull String fileName, Surrounder surrounder) {
    configureByFile(BASE_PATH + fileName + ".java");

    SurroundDescriptor item =
        ContainerUtil.getFirstItem(
            LanguageSurrounders.INSTANCE.allForLanguage(JavaLanguage.INSTANCE));
    assertNotNull(item);
    SelectionModel selectionModel = getEditor().getSelectionModel();
    PsiElement[] elements =
        item.getElementsToSurround(
            getFile(), selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
    assertTrue(surrounder.isApplicable(elements));

    SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder);

    checkResultByFile(BASE_PATH + fileName + "_after.java");
  }
  public boolean checkCanModify(final Collection<PackagingNodeSource> nodeSources) {
    if (nodeSources.isEmpty()) {
      return true;
    }

    if (nodeSources.size() > 1) {
      Messages.showErrorDialog(
          myArtifactsEditor.getMainComponent(),
          "The selected node consist of several elements so it cannot be edited.\nSwitch off 'Show content of elements' checkbox to edit the output layout.");
    } else {
      final PackagingNodeSource source = ContainerUtil.getFirstItem(nodeSources, null);
      if (source != null) {
        Messages.showErrorDialog(
            myArtifactsEditor.getMainComponent(),
            "The selected node belongs to '"
                + source.getPresentableName()
                + "' element so it cannot be edited.\nSwitch off 'Show content of elements' checkbox to edit the output layout.");
      }
    }
    return false;
  }
 @Nullable
 public ResourceBundleEditorViewElement getSelectedElementIfOnlyOne() {
   final Collection<ResourceBundleEditorViewElement> selectedElements = getSelectedElements();
   return selectedElements.size() == 1 ? ContainerUtil.getFirstItem(selectedElements) : null;
 }
 @Nullable
 private String getLatestPackageVersionFromAdditionalRepositories(@NotNull String packageName)
     throws IOException {
   final List<String> versions = getPackageVersionsFromAdditionalRepositories(packageName);
   return ContainerUtil.getFirstItem(versions);
 }
 @NotNull
 @Override
 public PropertiesFile getDefaultPropertiesFile() {
   return ContainerUtil.getFirstItem(myFiles);
 }
  QuickEditHandler(
      Project project,
      @NotNull PsiFile injectedFile,
      final PsiFile origFile,
      Editor editor,
      QuickEditAction action) {
    myProject = project;
    myEditor = editor;
    myAction = action;
    myOrigDocument = editor.getDocument();
    Place shreds = InjectedLanguageUtil.getShreds(injectedFile);
    FileType fileType = injectedFile.getFileType();
    Language language = injectedFile.getLanguage();
    PsiLanguageInjectionHost.Shred firstShred = ContainerUtil.getFirstItem(shreds);

    PsiFileFactory factory = PsiFileFactory.getInstance(project);
    String text = InjectedLanguageManager.getInstance(project).getUnescapedText(injectedFile);
    String newFileName =
        StringUtil.notNullize(language.getDisplayName(), "Injected")
            + " Fragment "
            + "("
            + origFile.getName()
            + ":"
            + firstShred.getHost().getTextRange().getStartOffset()
            + ")"
            + "."
            + fileType.getDefaultExtension();

    // preserve \r\n as it is done in MultiHostRegistrarImpl
    myNewFile = factory.createFileFromText(newFileName, language, text, true, false);
    myNewVirtualFile = ObjectUtils.assertNotNull((LightVirtualFile) myNewFile.getVirtualFile());
    myNewVirtualFile.setOriginalFile(origFile.getVirtualFile());

    assert myNewFile != null : "PSI file is null";
    assert myNewFile.getTextLength() == myNewVirtualFile.getContent().length()
        : "PSI / Virtual file text mismatch";

    myNewVirtualFile.setOriginalFile(origFile.getVirtualFile());
    // suppress possible errors as in injected mode
    myNewFile.putUserData(
        InjectedLanguageUtil.FRANKENSTEIN_INJECTION,
        injectedFile.getUserData(InjectedLanguageUtil.FRANKENSTEIN_INJECTION));
    myNewFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, shreds.getHostPointer());
    myNewDocument = PsiDocumentManager.getInstance(project).getDocument(myNewFile);
    assert myNewDocument != null;
    EditorActionManager.getInstance()
        .setReadonlyFragmentModificationHandler(myNewDocument, new MyQuietHandler());
    myOrigCreationStamp =
        myOrigDocument.getModificationStamp(); // store creation stamp for UNDO tracking
    myOrigDocument.addDocumentListener(this, this);
    myNewDocument.addDocumentListener(this, this);
    EditorFactory editorFactory = ObjectUtils.assertNotNull(EditorFactory.getInstance());
    // not FileEditorManager listener because of RegExp checker and alike
    editorFactory.addEditorFactoryListener(
        new EditorFactoryAdapter() {
          int useCount;

          @Override
          public void editorCreated(@NotNull EditorFactoryEvent event) {
            if (event.getEditor().getDocument() != myNewDocument) return;
            useCount++;
          }

          @Override
          public void editorReleased(@NotNull EditorFactoryEvent event) {
            if (event.getEditor().getDocument() != myNewDocument) return;
            if (--useCount > 0) return;
            if (Boolean.TRUE.equals(
                myNewVirtualFile.getUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN))) return;

            Disposer.dispose(QuickEditHandler.this);
          }
        },
        this);

    if ("JAVA".equals(firstShred.getHost().getLanguage().getID())) {
      PsiLanguageInjectionHost.Shred lastShred = ContainerUtil.getLastItem(shreds);
      myAltFullRange =
          myOrigDocument.createRangeMarker(
              firstShred.getHostRangeMarker().getStartOffset(),
              lastShred.getHostRangeMarker().getEndOffset());
      myAltFullRange.setGreedyToLeft(true);
      myAltFullRange.setGreedyToRight(true);

      initGuardedBlocks(shreds);
      myInjectedFile = null;
    } else {
      initMarkers(shreds);
      myAltFullRange = null;
      myInjectedFile = injectedFile;
    }
  }