com.intellij.openapi.project.IndexNotReadyException Java Examples

The following examples show how to use com.intellij.openapi.project.IndexNotReadyException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DesktopDeferredIconImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public Image evaluateImage() {
  consulo.ui.image.Image result;
  try {
    result = nonNull(myEvaluator.fun(myParam));
  }
  catch (IndexNotReadyException e) {
    result = EMPTY_ICON;
  }

  if (Holder.CHECK_CONSISTENCY) {
    checkDoesntReferenceThis(result);
  }

  Icon icon = TargetAWT.to(result);

  if (getScale() != 1f && icon instanceof ScalableIcon) {
    icon = ((ScalableIcon)result).scale(getScale());
  }
  return TargetAWT.from(icon);
}
 
Example #2
Source File: PackageNameUtils.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getRawPackageNameFromIndex(AndroidFacet facet) {
  VirtualFile primaryManifest = SourceProviderManager.getInstance(facet).getMainManifestFile();
  if (primaryManifest == null) {
    return null;
  }
  Project project = facet.getModule().getProject();
  try {
    AndroidManifestRawText manifestRawText =
        DumbService.getInstance(project)
            .runReadActionInSmartMode(
                () -> AndroidManifestIndex.getDataForManifestFile(project, primaryManifest));
    return manifestRawText == null ? null : manifestRawText.getPackageName();
  } catch (IndexNotReadyException e) {
    // TODO(142681129): runReadActionInSmartMode doesn't work if we already have read access.
    //  We need to refactor the callers of AndroidManifestUtils#getPackage to require a *smart*
    //  read action, at which point we can remove this try-catch.
    return null;
  }
}
 
Example #3
Source File: ActionUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void performActionDumbAware(AnAction action, AnActionEvent e) {
  Runnable runnable = new Runnable() {
    @Override
    public void run() {
      try {
        action.actionPerformed(e);
      }
      catch (IndexNotReadyException e1) {
        showDumbModeWarning(e);
      }
    }

    @Override
    public String toString() {
      return action + " of " + action.getClass();
    }
  };

  if (action.startInTransaction()) {
    TransactionGuard.getInstance().submitTransactionAndWait(runnable);
  }
  else {
    runnable.run();
  }
}
 
Example #4
Source File: GraphQLSchemasRootNode.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public SimpleNode[] getChildren() {
    try {
        if (DumbService.getInstance(myProject).isDumb() || !configManager.isInitialized()) {
            // empty the tree view during indexing and until the config has been initialized
            return SimpleNode.NO_CHILDREN;
        }
        final List<SimpleNode> children = Lists.newArrayList();
        for (Map.Entry<VirtualFile, GraphQLConfigData> entry : configManager.getConfigurationsByPath().entrySet()) {
            children.add(new GraphQLConfigSchemaNode(myProject, this, configManager, entry.getValue(), entry.getKey()));
        }
        if (children.isEmpty()) {
            children.add(new GraphQLDefaultSchemaNode(myProject, this));
        }
        children.sort(Comparator.comparing(PresentableNodeDescriptor::getName));
        return children.toArray(SimpleNode.NO_CHILDREN);
    } catch (IndexNotReadyException e) {
        return SimpleNode.NO_CHILDREN;
    }
}
 
Example #5
Source File: UsageViewImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void queueUpdateBulk(@Nonnull List<? extends Node> toUpdate, @Nonnull Runnable onCompletedInEdt) {
  if (toUpdate.isEmpty()) return;
  addUpdateRequest(() -> {
    for (Node node : toUpdate) {
      try {
        if (isDisposed()) break;
        if (!runReadActionWithRetries(() -> node.update(this, edtNodeChangedQueue))) {
          ApplicationManager.getApplication().invokeLater(() -> queueUpdateBulk(toUpdate, onCompletedInEdt));
          return;
        }
      }
      catch (IndexNotReadyException ignore) {
      }
    }
    ApplicationManager.getApplication().invokeLater(onCompletedInEdt);
  });
}
 
Example #6
Source File: UsageViewImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private ShowSettings() {
  super("Settings...", null, AllIcons.General.GearPlain);
  final ConfigurableUsageTarget configurableUsageTarget = getConfigurableTarget(myTargets);
  String description = null;
  try {
    description = configurableUsageTarget == null ? null : "Show settings for " + configurableUsageTarget.getLongDescriptiveName();
  }
  catch (IndexNotReadyException ignored) {
  }
  if (description == null) {
    description = "Show find usages settings dialog";
  }
  getTemplatePresentation().setDescription(description);
  KeyboardShortcut shortcut = configurableUsageTarget == null ? getShowUsagesWithSettingsShortcut() : configurableUsageTarget.getShortcut();
  if (shortcut != null) {
    registerCustomShortcutSet(new CustomShortcutSet(shortcut), getComponent());
  }
}
 
Example #7
Source File: BlazeRenderErrorContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private File getSourceFileForClass(String className) {
  return ApplicationManager.getApplication()
      .runReadAction(
          (Computable<File>)
              () -> {
                try {
                  PsiClass psiClass =
                      JavaPsiFacade.getInstance(project)
                          .findClass(className, GlobalSearchScope.projectScope(project));
                  if (psiClass == null) {
                    return null;
                  }
                  return VfsUtilCore.virtualToIoFile(
                      psiClass.getContainingFile().getVirtualFile());
                } catch (IndexNotReadyException ignored) {
                  // We're in dumb mode. Abort! Abort!
                  return null;
                }
              });
}
 
Example #8
Source File: SingleConfigurableEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public ApplyAction() {
  super(CommonBundle.getApplyButtonText());
  final Runnable updateRequest = new Runnable() {
    @Override
    public void run() {
      if (!SingleConfigurableEditor.this.isShowing()) return;
      try {
        ApplyAction.this.setEnabled(myConfigurable != null && myConfigurable.isModified());
      }
      catch (IndexNotReadyException ignored) {
      }
      addUpdateRequest(this);
    }
  };

  // invokeLater necessary to make sure dialog is already shown so we calculate modality state correctly.
  SwingUtilities.invokeLater(() -> addUpdateRequest(updateRequest));
}
 
Example #9
Source File: WholeWestSingleConfigurableEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public ApplyAction() {
  super(CommonLocalize.buttonApply());
  final Runnable updateRequest = new Runnable() {
    @Override
    public void run() {
      if (!WholeWestSingleConfigurableEditor.this.isShowing()) return;
      try {
        ApplyAction.this.setEnabled(myConfigurable != null && myConfigurable.isModified());
      }
      catch (IndexNotReadyException ignored) {
      }
      addUpdateRequest(this);
    }
  };

  // invokeLater necessary to make sure dialog is already shown so we calculate modality state correctly.
  SwingUtilities.invokeLater(() -> addUpdateRequest(updateRequest));
}
 
Example #10
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void executeUpdateParameterInfo(PsiElement elementForUpdating, MyUpdateParameterInfoContext context, Runnable continuation) {
  PsiElement parameterOwner = context.getParameterOwner();
  if (parameterOwner != null && !parameterOwner.equals(elementForUpdating)) {
    context.removeHint();
    return;
  }

  runTask(myProject, ReadAction.nonBlocking(() -> {
    try {
      myHandler.updateParameterInfo(elementForUpdating, context);
      return elementForUpdating;
    }
    catch (IndexNotReadyException e) {
      DumbService.getInstance(myProject).showDumbModeNotification(CodeInsightBundle.message("parameter.info.indexing.mode.not.supported"));
    }
    return null;
  }).withDocumentsCommitted(myProject).expireWhen(() -> !myKeepOnHintHidden && !myHint.isVisible() && !ApplicationManager.getApplication().isHeadlessEnvironment() ||
                                                        getCurrentOffset() != context.getOffset() ||
                                                        !elementForUpdating.isValid()).expireWith(this), element -> {
    if (element != null && continuation != null) {
      context.applyUIChanges();
      continuation.run();
    }
  }, null, myEditor);
}
 
Example #11
Source File: ImplementationSearcher.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param element
 * @param editor
 * @return For the case the search has been cancelled
 */
@Nullable
protected PsiElement[] searchDefinitions(PsiElement element, Editor editor) {
  PsiElement[][] result = new PsiElement[1][];
  if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
    try {
      result[0] = search(element, editor).toArray(PsiElement.EMPTY_ARRAY);
    }
    catch (IndexNotReadyException e) {
      dumbModeNotification(element);
      result[0] = null;
    }
  }, SEARCHING_FOR_IMPLEMENTATIONS, true, element.getProject())) {
    return null;
  }
  return result[0];
}
 
Example #12
Source File: LookupManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showJavadoc(LookupImpl lookup) {
  if (myActiveLookup != lookup) return;

  DocumentationManager docManager = DocumentationManager.getInstance(myProject);
  if (docManager.getDocInfoHint() != null) return; // will auto-update

  LookupElement currentItem = lookup.getCurrentItem();
  CompletionProcess completion = CompletionService.getCompletionService().getCurrentCompletion();
  if (currentItem != null && currentItem.isValid() && isAutoPopupJavadocSupportedBy(currentItem) && completion != null) {
    try {
      boolean hideLookupWithDoc = completion.isAutopopupCompletion() || CodeInsightSettings.getInstance().JAVADOC_INFO_DELAY == 0;
      docManager.showJavaDocInfo(lookup.getEditor(), lookup.getPsiFile(), false, () -> {
        if (hideLookupWithDoc && completion == CompletionService.getCompletionService().getCurrentCompletion()) {
          hideActiveLookup();
        }
      });
    }
    catch (IndexNotReadyException ignored) {
    }
  }
}
 
Example #13
Source File: RunConfigurationsComboBoxAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void update(@Nonnull AnActionEvent e) {
  Presentation presentation = e.getPresentation();
  Project project = e.getData(CommonDataKeys.PROJECT);
  if (ActionPlaces.isMainMenuOrActionSearch(e.getPlace())) {
    presentation.setDescription(ExecutionBundle.message("choose.run.configuration.action.description"));
  }
  try {
    if (project == null || project.isDisposed() || !project.isInitialized()) {
      updatePresentation(null, null, null, presentation);
      presentation.setEnabled(false);
    }
    else {
      updatePresentation(ExecutionTargetManager.getActiveTarget(project), RunManagerEx.getInstanceEx(project).getSelectedConfiguration(), project, presentation);
      presentation.setEnabled(true);
    }
  }
  catch (IndexNotReadyException e1) {
    presentation.setEnabled(false);
  }
}
 
Example #14
Source File: RunConfigurationsComboBoxAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void setConfigurationIcon(final Presentation presentation, final RunnerAndConfigurationSettings settings, final Project project) {
  try {
    Icon icon = TargetAWT.to(RunManagerEx.getInstanceEx(project).getConfigurationIcon(settings));
    ExecutionManagerImpl executionManager = ExecutionManagerImpl.getInstance(project);
    List<RunContentDescriptor> runningDescriptors = executionManager.getRunningDescriptors(s -> s == settings);
    if (runningDescriptors.size() == 1) {
      icon = ExecutionUtil.getLiveIndicator(icon);
    }
    // FIXME [VISTALL] not supported by UI framework
    if (runningDescriptors.size() > 1) {
      icon = IconUtil.addText(icon, String.valueOf(runningDescriptors.size()));
    }
    presentation.setIcon(icon);
  }
  catch (IndexNotReadyException ignored) {
  }
}
 
Example #15
Source File: SimpleProviderBinding.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void addAcceptableReferenceProviders(@Nonnull PsiElement position,
                                            @Nonnull List<ProviderInfo<Provider, ProcessingContext>> list,
                                            @Nonnull PsiReferenceService.Hints hints) {
  for (ProviderInfo<Provider, ElementPattern> trinity : myProviderPairs) {
    if (hints != PsiReferenceService.Hints.NO_HINTS && !((PsiReferenceProvider)trinity.provider).acceptsHints(position, hints)) {
      continue;
    }

    final ProcessingContext context = new ProcessingContext();
    if (hints != PsiReferenceService.Hints.NO_HINTS) {
      context.put(PsiReferenceService.HINTS, hints);
    }
    boolean suitable = false;
    try {
      suitable = trinity.processingContext.accepts(position, context);
    }
    catch (IndexNotReadyException ignored) {
    }
    if (suitable) {
      list.add(new ProviderInfo<Provider, ProcessingContext>(trinity.provider, context, trinity.priority));
    }
  }
}
 
Example #16
Source File: NamedObjectProviderBinding.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void addMatchingProviders(final PsiElement position,
                                  @Nullable final List<ProviderInfo<Provider, ElementPattern>> providerList,
                                  @Nonnull List<ProviderInfo<Provider, ProcessingContext>> ret,
                                  PsiReferenceService.Hints hints) {
  if (providerList == null) return;

  for (ProviderInfo<Provider, ElementPattern> trinity : providerList) {
    if (hints != PsiReferenceService.Hints.NO_HINTS && !((PsiReferenceProvider)trinity.provider).acceptsHints(position, hints)) {
      continue;
    }

    final ProcessingContext context = new ProcessingContext();
    if (hints != PsiReferenceService.Hints.NO_HINTS) {
      context.put(PsiReferenceService.HINTS, hints);
    }
    boolean suitable = false;
    try {
      suitable = trinity.processingContext.accepts(position, context);
    }
    catch (IndexNotReadyException ignored) {
    }
    if (suitable) {
      ret.add(new ProviderInfo<Provider, ProcessingContext>(trinity.provider, context, trinity.priority));
    }
  }
}
 
Example #17
Source File: TodoDirNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
public int getFileCount(PsiDirectory directory) {
  Iterator<PsiFile> iterator = myBuilder.getFiles(directory);
  int count = 0;
  try {
    while (iterator.hasNext()) {
      PsiFile psiFile = iterator.next();
      if (getStructure().accept(psiFile)) {
        count++;
      }
    }
  }
  catch (IndexNotReadyException e) {
    return count;
  }
  return count;
}
 
Example #18
Source File: TodoFileNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void updateImpl(@Nonnull PresentationData data) {
  super.updateImpl(data);
  String newName;
  if (myBuilder.getTodoTreeStructure().isPackagesShown()) {
    newName = getValue().getName();
  }
  else {
    newName = mySingleFileMode ? getValue().getName() : getValue().getVirtualFile().getPresentableUrl();
  }

  data.setPresentableText(newName);
  int todoItemCount;
  try {
    todoItemCount = myBuilder.getTodoTreeStructure().getTodoItemCount(getValue());
  }
  catch (IndexNotReadyException e) {
    return;
  }
  if (todoItemCount > 0) {
    data.setLocationString(IdeBundle.message("node.todo.items", todoItemCount));
  }
}
 
Example #19
Source File: NavBarPresentation.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MethodMayBeStatic")
@Nullable
public Icon getIcon(final Object object) {
  if (!NavBarModel.isValid(object)) return null;
  if (object instanceof Project) return AllIcons.Nodes.ProjectTab;
  if (object instanceof Module) return AllIcons.Nodes.Module;
  try {
    if (object instanceof PsiElement) {
      Icon icon = TargetAWT.to(AccessRule.read(() -> ((PsiElement)object).isValid() ? IconDescriptorUpdaters.getIcon(((PsiElement)object), 0) : null));

      if (icon != null && (icon.getIconHeight() > JBUI.scale(16) || icon.getIconWidth() > JBUI.scale(16))) {
        icon = IconUtil.cropIcon(icon, JBUI.scale(16), JBUI.scale(16));
      }
      return icon;
    }
  }
  catch (IndexNotReadyException e) {
    return null;
  }
  if (object instanceof ModuleExtensionWithSdkOrderEntry) {
    return TargetAWT.to(SdkUtil.getIcon(((ModuleExtensionWithSdkOrderEntry)object).getSdk()));
  }
  if (object instanceof LibraryOrderEntry) return AllIcons.Nodes.PpLibFolder;
  if (object instanceof ModuleOrderEntry) return AllIcons.Nodes.Module;
  return null;
}
 
Example #20
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateOnPsiChanges(@Nonnull LightweightHint hint, @Nonnull Info info, @Nonnull Consumer<? super String> textConsumer, @Nonnull String oldText, @Nonnull Editor editor) {
  if (!hint.isVisible()) return;
  Disposable hintDisposable = Disposable.newDisposable("CtrlMouseHandler.TooltipProvider.updateOnPsiChanges");
  hint.addHintListener(__ -> Disposer.dispose(hintDisposable));
  myProject.getMessageBus().connect(hintDisposable).subscribe(PsiModificationTracker.TOPIC, () -> ReadAction.nonBlocking(() -> {
    try {
      DocInfo newDocInfo = info.getInfo();
      return (Runnable)() -> {
        if (newDocInfo.text != null && !oldText.equals(newDocInfo.text)) {
          updateText(newDocInfo.text, textConsumer, hint, editor);
        }
      };
    }
    catch (IndexNotReadyException e) {
      showDumbModeNotification(myProject);
      return createDisposalContinuation();
    }
  }).finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run).withDocumentsCommitted(myProject).expireWith(hintDisposable).expireWhen(() -> !info.isValid(editor.getDocument()))
          .coalesceBy(hint).submit(AppExecutorUtil.getAppExecutorService()));
}
 
Example #21
Source File: DesktopDeferredIconImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Icon evaluate() {
  consulo.ui.image.Image result;
  try {
    result = nonNull(myEvaluator.fun(myParam));
  }
  catch (IndexNotReadyException e) {
    result = EMPTY_ICON;
  }

  if (Holder.CHECK_CONSISTENCY) {
    checkDoesntReferenceThis(result);
  }

  Icon icon = TargetAWT.to(result);

  if (getScale() != 1f && icon instanceof ScalableIcon) {
    icon = ((ScalableIcon)result).scale(getScale());
  }
  return icon;
}
 
Example #22
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private Runnable doExecute() {
  EditorEx editor = getPossiblyInjectedEditor();
  int offset = getOffset(editor);

  PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
  if (file == null) return createDisposalContinuation();

  final Info info;
  final DocInfo docInfo;
  try {
    info = getInfoAt(editor, file, offset, myBrowseMode);
    if (info == null) return createDisposalContinuation();
    docInfo = info.getInfo();
  }
  catch (IndexNotReadyException e) {
    showDumbModeNotification(myProject);
    return createDisposalContinuation();
  }

  LOG.debug("Obtained info about element under cursor");
  return () -> addHighlighterAndShowHint(info, docInfo, editor);
}
 
Example #23
Source File: UsageInfoSearcherAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void processUsages(final @Nonnull Processor<Usage> processor, @Nonnull Project project) {
  final Ref<UsageInfo[]> refUsages = new Ref<UsageInfo[]>();
  final Ref<Boolean> dumbModeOccurred = new Ref<Boolean>();
  ApplicationManager.getApplication().runReadAction(new Runnable() {
    @Override
    public void run() {
      try {
        refUsages.set(findUsages());
      }
      catch (IndexNotReadyException e) {
        dumbModeOccurred.set(true);
      }
    }
  });
  if (!dumbModeOccurred.isNull()) {
    DumbService.getInstance(project).showDumbModeNotification("Usage search is not available until indices are ready");
    return;
  }
  final Usage[] usages = ApplicationManager.getApplication().runReadAction(new Computable<Usage[]>() {
    @Override
    public Usage[] compute() {
      return UsageInfo2UsageAdapter.convert(refUsages.get());
    }
  });

  for (final Usage usage : usages) {
    ApplicationManager.getApplication().runReadAction(new Runnable() {
      @Override
      public void run() {
        processor.process(usage);
      }
    });
  }
}
 
Example #24
Source File: StructureViewComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Collection<AbstractTreeNode> getChildren() {
  if (ourSettingsModificationCount.get() != modificationCountForChildren) {
    resetChildren();
    modificationCountForChildren = ourSettingsModificationCount.get();
  }

  Object o = unwrapElement(getValue());
  long currentStamp = -1;
  if (o instanceof PsiElement) {
    if (!((PsiElement)o).isValid()) return Collections.emptyList();

    PsiFile file = ((PsiElement)o).getContainingFile();
    if (file != null) {
      currentStamp = file.getModificationStamp();
    }
  }
  else if (o instanceof ModificationTracker) {
    currentStamp = ((ModificationTracker)o).getModificationCount();
  }
  if (childrenStamp != currentStamp) {
    resetChildren();
    childrenStamp = currentStamp;
  }
  try {
    return super.getChildren();
  }
  catch (IndexNotReadyException ignore) {
    return Collections.emptyList();
  }
}
 
Example #25
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean availableFor(@Nonnull PsiFile psiFile, @Nonnull Editor editor, @Nonnull IntentionAction action) {
  if (!psiFile.isValid()) return false;

  try {
    Project project = psiFile.getProject();
    action = IntentionActionDelegate.unwrap(action);
    if (action instanceof SuppressIntentionActionFromFix) {
      final ThreeState shouldBeAppliedToInjectionHost = ((SuppressIntentionActionFromFix)action).isShouldBeAppliedToInjectionHost();
      if (editor instanceof EditorWindow && shouldBeAppliedToInjectionHost == ThreeState.YES) {
        return false;
      }
      if (!(editor instanceof EditorWindow) && shouldBeAppliedToInjectionHost == ThreeState.NO) {
        return false;
      }
    }

    if (action instanceof PsiElementBaseIntentionAction) {
      PsiElementBaseIntentionAction psiAction = (PsiElementBaseIntentionAction)action;
      if (!psiAction.checkFile(psiFile)) {
        return false;
      }
      PsiElement leaf = psiFile.findElementAt(editor.getCaretModel().getOffset());
      if (leaf == null || !psiAction.isAvailable(project, editor, leaf)) {
        return false;
      }
    }
    else if (!action.isAvailable(project, editor, psiFile)) {
      return false;
    }
  }
  catch (IndexNotReadyException e) {
    return false;
  }
  return true;
}
 
Example #26
Source File: AutoPopupControllerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void autoPopupParameterInfo(@Nonnull final Editor editor, @Nullable final Object highlightedMethod) {
  if (DumbService.isDumb(myProject)) return;
  if (PowerSaveMode.isEnabled()) return;

  ApplicationManager.getApplication().assertIsDispatchThread();
  final CodeInsightSettings settings = CodeInsightSettings.getInstance();
  if (settings.AUTO_POPUP_PARAMETER_INFO) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    PsiFile file = documentManager.getPsiFile(editor.getDocument());
    if (file == null) return;

    if (!documentManager.isUncommited(editor.getDocument())) {
      file = documentManager.getPsiFile(InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file).getDocument());
      if (file == null) return;
    }

    Runnable request = () -> {
      if (!myProject.isDisposed() && !DumbService.isDumb(myProject) && !editor.isDisposed() && (EditorActivityManager.getInstance().isVisible(editor))) {
        int lbraceOffset = editor.getCaretModel().getOffset() - 1;
        try {
          PsiFile file1 = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
          if (file1 != null) {
            ShowParameterInfoHandler.invoke(myProject, editor, file1, lbraceOffset, highlightedMethod, false, true, null, e -> {
            });
          }
        }
        catch (IndexNotReadyException ignored) { //anything can happen on alarm
        }
      }
    };

    addRequest(() -> documentManager.performLaterWhenAllCommitted(request), settings.PARAMETER_INFO_DELAY);
  }
}
 
Example #27
Source File: TextEditorPsiDataProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiElement getPsiElementIn(@Nonnull Editor editor, @Nonnull Caret caret, @Nonnull VirtualFile file) {
  final PsiFile psiFile = getPsiFile(editor, file);
  if (psiFile == null) return null;

  try {
    return TargetElementUtil.findTargetElement(editor, TargetElementUtil.getReferenceSearchFlags(), caret.getOffset());
  }
  catch (IndexNotReadyException e) {
    return null;
  }
}
 
Example #28
Source File: RunManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean canRunConfiguration(@Nonnull RunnerAndConfigurationSettings configuration, @Nonnull Executor executor) {
  try {
    configuration.checkSettings(executor);
  }
  catch (IndexNotReadyException | RuntimeConfigurationException ignored) {
    return false;
  }
  return true;
}
 
Example #29
Source File: GraphQLPsiSearchHelper.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Processes all named elements that match the specified word, e.g. the declaration of a type name
 */
public void processElementsWithWord(PsiElement scopedElement, String word, Processor<PsiNamedElement> processor) {
    try {
        final GlobalSearchScope schemaScope = getSchemaScope(scopedElement);

        processElementsWithWordUsingIdentifierIndex(schemaScope, word, processor);

        // also include the built-in schemas
        final PsiRecursiveElementVisitor builtInFileVisitor = new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                if (element instanceof PsiNamedElement && word.equals(element.getText())) {
                    if (!processor.process((PsiNamedElement) element)) {
                        return; // done processing
                    }
                }
                super.visitElement(element);
            }
        };

        // spec schema
        getBuiltInSchema().accept(builtInFileVisitor);

        // relay schema if enabled
        final PsiFile relayModernDirectivesSchema = getRelayModernDirectivesSchema();
        if (schemaScope.contains(relayModernDirectivesSchema.getVirtualFile())) {
            relayModernDirectivesSchema.accept(builtInFileVisitor);
        }

        // finally, look in the current scratch file
        if (GraphQLFileType.isGraphQLScratchFile(myProject, getVirtualFile(scopedElement.getContainingFile()))) {
            scopedElement.getContainingFile().accept(builtInFileVisitor);
        }

    } catch (IndexNotReadyException e) {
        // can't search yet (e.g. during project startup)
    }
}
 
Example #30
Source File: GraphQLJavascriptInjectionSearchHelper.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Uses the {@link GraphQLInjectionIndex} to process injected GraphQL PsiFiles
 *
 * @param scopedElement the starting point of the enumeration settings the scopedElement of the processing
 * @param schemaScope   the search scope to use for limiting the schema definitions
 * @param consumer      a consumer that will be invoked for each injected GraphQL PsiFile
 */
public void processInjectedGraphQLPsiFiles(PsiElement scopedElement, GlobalSearchScope schemaScope, Consumer<PsiFile> consumer) {
    try {
        final PsiManager psiManager = PsiManager.getInstance(scopedElement.getProject());
        final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(scopedElement.getProject());
        FileBasedIndex.getInstance().getFilesWithKey(GraphQLInjectionIndex.NAME, Collections.singleton(GraphQLInjectionIndex.DATA_KEY), virtualFile -> {
            final PsiFile fileWithInjection = psiManager.findFile(virtualFile);
            if (fileWithInjection != null) {
                fileWithInjection.accept(new PsiRecursiveElementVisitor() {
                    @Override
                    public void visitElement(PsiElement element) {
                        if (GraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(element)) {
                            injectedLanguageManager.enumerate(element, (injectedPsi, places) -> {
                                consumer.accept(injectedPsi);
                            });
                        } else {
                            // visit deeper until injection found
                            super.visitElement(element);
                        }
                    }
                });
            }
            return true;
        }, schemaScope);
    } catch (IndexNotReadyException e) {
        // can't search yet (e.g. during project startup)
    }
}