下面列出了com.intellij.psi.PsiReferenceProvider#com.intellij.openapi.project.IndexNotReadyException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
});
}
@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;
}
}
@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;
}
}
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());
}
}
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);
});
}
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();
}
}
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));
}
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));
}
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);
}
/**
*
* @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];
}
@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);
}
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()));
}
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) {
}
}
}
@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);
}
}
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) {
}
}
@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));
}
}
}
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));
}
}
}
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;
}
@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));
}
}
@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;
}
@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;
}
@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);
}
@Nullable
private VirtualFile resolveFile(String relativePath) {
try {
return FileResolver.resolveToVirtualFile(project, relativePath);
} catch (IndexNotReadyException e) {
// Filter was called in dumb mode.
// Not a problem since the console will re-run the filters after exiting dumb mode.
return null;
}
}
@Override
public SimpleNode[] buildChildren() {
if (parent.projectsConfigData != null) {
try {
return parent.projectsConfigData.values().stream().map(config -> {
return new GraphQLConfigSchemaNode(myProject, this, parent.configManager, config, parent.configBaseDir);
}).toArray(SimpleNode[]::new);
} catch (IndexNotReadyException ignored) {
// entered "dumb" mode, so just return no children as the tree view will be rebuilt as empty shortly (GraphQLSchemasRootNode)
}
}
return SimpleNode.NO_CHILDREN;
}
/**
* 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)
}
}
/**
* 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)
}
}
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);
}
});
}
}
private void updateOnSelectionChanged() {
ApplicationManager.getApplication().assertIsDispatchThread();
if (myCurrentUsageContextPanel != null) {
try {
myCurrentUsageContextPanel.updateLayout(getSelectedUsageInfos());
}
catch (IndexNotReadyException ignore) {
}
}
}
private Object[] getChildrenFor(final Object element) {
final Ref<Object[]> passOne = new Ref<>();
try (LockToken ignored = acquireLock()) {
execute(new TreeRunnable("AbstractTreeUi.getChildrenFor") {
@Override
public void perform() {
passOne.set(getTreeStructure().getChildElements(element));
}
});
}
catch (IndexNotReadyException e) {
warnOnIndexNotReady(e);
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
if (!Registry.is("ide.tree.checkStructure")) return passOne.get();
final Object[] passTwo = getTreeStructure().getChildElements(element);
final HashSet<Object> two = new HashSet<>(Arrays.asList(passTwo));
if (passOne.get().length != passTwo.length) {
LOG.error("AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" + element);
}
else {
for (Object eachInOne : passOne.get()) {
if (!two.contains(eachInOne)) {
LOG.error("AbstractTreeStructure.getChildren() must either provide same objects or new objects but with correct hashCode() and equals() methods. Wrong parent element=" + element);
break;
}
}
}
return passOne.get();
}
private boolean collectVirtualFilesWithWord(@Nonnull final Processor<VirtualFile> fileProcessor,
@Nonnull final String word, final short occurrenceMask,
@Nonnull final GlobalSearchScope scope, final boolean caseSensitively) {
if (myProject.isDefault()) {
return true;
}
try {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return FileBasedIndex.getInstance().processValues(IdIndex.NAME, new IdIndexEntry(word, caseSensitively), null, new FileBasedIndex.ValueProcessor<Integer>() {
final FileIndexFacade index = FileIndexFacade.getInstance(myProject);
@Override
public boolean process(final VirtualFile file, final Integer value) {
ProgressIndicatorProvider.checkCanceled();
final int mask = value.intValue();
if ((mask & occurrenceMask) != 0 && index.shouldBeFound(scope, file)) {
if (!fileProcessor.process(file)) return false;
}
return true;
}
}, scope);
}
});
}
catch (IndexNotReadyException e) {
throw new ProcessCanceledException();
}
}