下面列出了怎么用com.intellij.psi.util.CachedValuesManager的API类实例代码及写法,或者点击链接到github查看源代码。
@NotNull
private static Map<String, Collection<TemplateAnnotationUsage>> getTemplateAnnotationUsagesMap(@NotNull Project project) {
return CachedValuesManager.getManager(project).getCachedValue(project, PHP_GENERICS_TEMPLATES, () -> {
Map<String, Collection<TemplateAnnotationUsage>> map = new HashMap<>();
FileBasedIndex instance = FileBasedIndex.getInstance();
GlobalSearchScope scope = PhpIndex.getInstance(project).getSearchScope();
instance.processAllKeys(TemplateAnnotationIndex.KEY, (key) -> {
map.putIfAbsent(key, new HashSet<>());
map.get(key).addAll(instance.getValues(TemplateAnnotationIndex.KEY, key, scope));
return true;
}, project);
return CachedValueProvider.Result.create(map, getModificationTracker(project));
}, false);
}
@NotNull
private synchronized static Collection<String> getAllResourceKeys(@NotNull Project project) {
CachedValue<Collection<String>> userData = project.getUserData(RESOURCE_KEYS);
if (userData != null && userData.hasUpToDateValue()) {
return RESOURCE_KEYS_LOCAL_CACHE.getOrDefault(project, new ArrayList<>());
}
CachedValue<Collection<String>> cachedValue = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<String> allKeys = FileBasedIndex.getInstance().getAllKeys(ResourcePathIndex.KEY, project);
if (RESOURCE_KEYS_LOCAL_CACHE.containsKey(project)) {
RESOURCE_KEYS_LOCAL_CACHE.replace(project, allKeys);
} else {
RESOURCE_KEYS_LOCAL_CACHE.put(project, allKeys);
}
return CachedValueProvider.Result.create(new ArrayList<>(), PsiModificationTracker.MODIFICATION_COUNT);
}, false);
project.putUserData(RESOURCE_KEYS, cachedValue);
return RESOURCE_KEYS_LOCAL_CACHE.getOrDefault(project, cachedValue.getValue());
}
@NotNull
private synchronized static Collection<String> getAllKeys(@NotNull Project project) {
CachedValue<Collection<String>> cachedValue = project.getUserData(TRANSLATION_KEYS);
if (cachedValue != null && cachedValue.hasUpToDateValue()) {
return TRANSLATION_KEYS_LOCAL_CACHE.getOrDefault(project, new ArrayList<>());
}
cachedValue = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<String> allKeys = FileBasedIndex.getInstance().getAllKeys(TranslationIndex.KEY, project);
if (TRANSLATION_KEYS_LOCAL_CACHE.containsKey(project)) {
TRANSLATION_KEYS_LOCAL_CACHE.replace(project, allKeys);
} else {
TRANSLATION_KEYS_LOCAL_CACHE.put(project, allKeys);
}
return CachedValueProvider.Result.create(new ArrayList<>(), MODIFICATION_COUNT);
}, false);
project.putUserData(TRANSLATION_KEYS, cachedValue);
return TRANSLATION_KEYS_LOCAL_CACHE.getOrDefault(project, cachedValue.getValue());
}
private synchronized Collection<FluidNamespace> doProvide(@NotNull PsiElement element) {
FileViewProvider viewProvider = element.getContainingFile().getViewProvider();
if (!viewProvider.getLanguages().contains(HTMLLanguage.INSTANCE)) {
return ContainerUtil.emptyList();
}
PsiFile htmlFile = viewProvider.getPsi(HTMLLanguage.INSTANCE);
CachedValue userData = htmlFile.getUserData(HTML_NS_KEY);
if (userData != null) {
return (Collection<FluidNamespace>) userData.getValue();
}
CachedValue<Collection<FluidNamespace>> cachedValue = CachedValuesManager.getManager(element.getProject()).createCachedValue(() -> {
HtmlNSVisitor visitor = new HtmlNSVisitor();
htmlFile.accept(visitor);
return CachedValueProvider.Result.createSingleDependency(visitor.namespaces, htmlFile);
}, false);
htmlFile.putUserData(HTML_NS_KEY, cachedValue);
return cachedValue.getValue();
}
@Nullable
private RunConfigurationContext findTestContext(ConfigurationContext context) {
if (!SmRunnerUtils.getSelectedSmRunnerTreeElements(context).isEmpty()) {
// handled by a different producer
return null;
}
ContextWrapper wrapper = new ContextWrapper(context);
PsiElement psi = context.getPsiLocation();
return psi == null
? null
: CachedValuesManager.getCachedValue(
psi,
cacheKey,
() ->
CachedValueProvider.Result.create(
doFindTestContext(wrapper.context),
PsiModificationTracker.MODIFICATION_COUNT,
BlazeSyncModificationTracker.getInstance(wrapper.context.getProject())));
}
@Nullable
private BinaryRunContext findRunContext(ConfigurationContext context) {
if (!SmRunnerUtils.getSelectedSmRunnerTreeElements(context).isEmpty()) {
// not a binary run context
return null;
}
ContextWrapper wrapper = new ContextWrapper(context);
PsiElement psi = context.getPsiLocation();
return psi == null
? null
: CachedValuesManager.getCachedValue(
psi,
() ->
CachedValueProvider.Result.create(
doFindRunContext(wrapper.context),
PsiModificationTracker.MODIFICATION_COUNT,
BlazeSyncModificationTracker.getInstance(wrapper.context.getProject())));
}
@Nullable
@Override
public RunConfigurationContext getTestContext(ConfigurationContext context) {
PsiElement psi = context.getPsiLocation();
if (!(psi instanceof PsiFileSystemItem) || !(psi instanceof FakePsiElement)) {
return null;
}
VirtualFile vf = ((PsiFileSystemItem) psi).getVirtualFile();
if (vf == null) {
return null;
}
WorkspacePath path = getWorkspacePath(context.getProject(), vf);
if (path == null) {
return null;
}
return CachedValuesManager.getCachedValue(
psi,
() ->
CachedValueProvider.Result.create(
doFindTestContext(context, vf, psi, path),
PsiModificationTracker.MODIFICATION_COUNT,
BlazeSyncModificationTracker.getInstance(context.getProject())));
}
@Nullable
@Override
public PsiFile getFileNavigationElement(ClsFileImpl file) {
if (!enabled.getValue()) {
return null;
}
return CachedValuesManager.getCachedValue(
file,
() -> {
Result<PsiFile> result = getPsiFile(file);
if (result == null) {
result = notFound(file);
}
return result;
});
}
/**
* Based on {@link JUnitUtil#isTestClass}. We don't use that directly because it returns true for
* all inner classes of a test class, regardless of whether they're also test classes.
*/
public static boolean isTestClass(PsiClass psiClass) {
if (psiClass.getQualifiedName() == null) {
return false;
}
if (JUnitUtil.isJUnit5(psiClass) && JUnitUtil.isJUnit5TestClass(psiClass, true)) {
return true;
}
if (!PsiClassUtil.isRunnableClass(psiClass, true, true)) {
return false;
}
if (isJUnit4Class(psiClass)) {
return true;
}
if (isTestCaseInheritor(psiClass)) {
return true;
}
return CachedValuesManager.getCachedValue(
psiClass,
() ->
CachedValueProvider.Result.create(
hasTestOrSuiteMethods(psiClass),
PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT));
}
@RequiredReadAction
public static boolean isPackageSupported(@Nonnull Project project) {
return CachedValuesManager.getManager(project).getCachedValue(project, () -> {
boolean result = false;
PsiPackageSupportProvider[] extensions = PsiPackageSupportProvider.EP_NAME.getExtensions();
ModuleManager moduleManager = ModuleManager.getInstance(project);
loop:
for (Module module : moduleManager.getModules()) {
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
for (ModuleExtension moduleExtension : rootManager.getExtensions()) {
for (PsiPackageSupportProvider extension : extensions) {
if (extension.isSupported(moduleExtension)) {
result = true;
break loop;
}
}
}
}
return CachedValueProvider.Result.create(result, ProjectRootManager.getInstance(project));
});
}
@NotNull
public static Collection<ServiceResource> getIndexedBootstrapResources(@NotNull Project project) {
// cache
CachedValue<Collection<ServiceResource>> cache = project.getUserData(SERVICE_RESOURCE);
if (cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(
getIndexedBootstrapResources(project, BootstrapResource.INIT_RESOURCE, BootstrapResource.AFTER_INIT_RESOURCE, BootstrapResource.AFTER_REGISTER_RESOURCE),
PsiModificationTracker.MODIFICATION_COUNT
), false);
project.putUserData(SERVICE_RESOURCE, cache);
}
return cache.getValue();
}
@Nonnull
public static Unity3dManifest parse(@Nonnull Project project)
{
return CachedValuesManager.getManager(project).getCachedValue(project, () ->
{
Path projectPath = Paths.get(project.getBasePath());
Path manifestJson = projectPath.resolve(Paths.get("Packages", "manifest.json"));
if(Files.exists(manifestJson))
{
Gson gson = new Gson();
try (Reader reader = Files.newBufferedReader(manifestJson))
{
return CachedValueProvider.Result.create(gson.fromJson(reader, Unity3dManifest.class), PsiModificationTracker.MODIFICATION_COUNT);
}
catch(Exception e)
{
LOG.error(e);
}
}
return CachedValueProvider.Result.create(EMPTY, PsiModificationTracker.MODIFICATION_COUNT);
});
}
@Override
@NotNull
public Collection<String> getGlobalNamespaces(@NotNull AnnotationGlobalNamespacesLoaderParameter parameter) {
Project project = parameter.getProject();
CachedValue<Collection<String>> cache = project.getUserData(CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() ->
CachedValueProvider.Result.create(getGlobalNamespacesInner(project), PsiModificationTracker.MODIFICATION_COUNT), false
);
project.putUserData(CACHE, cache);
}
return cache.getValue();
}
@Nonnull
@RequiredReadAction
public static EnumSet<CSharpModifier> getModifiersCached(@Nonnull CSharpModifierList modifierList)
{
if(!modifierList.isValid())
{
return emptySet;
}
return CachedValuesManager.getCachedValue(modifierList, () ->
{
Set<CSharpModifier> modifiers = new THashSet<>();
for(CSharpModifier modifier : CSharpModifier.values())
{
if(hasModifier(modifierList, modifier))
{
modifiers.add(modifier);
}
}
return CachedValueProvider.Result.create(modifiers.isEmpty() ? emptySet : EnumSet.copyOf(modifiers), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
});
}
@RequiredReadAction
@Nonnull
@Override
public DotNetTypeRef[] getExtendTypeRefs()
{
return CachedValuesManager.getCachedValue(this, new CachedValueProvider<DotNetTypeRef[]>()
{
@Nullable
@Override
@RequiredReadAction
public Result<DotNetTypeRef[]> compute()
{
DotNetTypeRef[] extendTypeRefs = CSharpTypeDeclarationImplUtil.getExtendTypeRefs(CSharpTypeDeclarationImpl.this);
return Result.create(extendTypeRefs, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
});
}
/**
* Retrieve the list of classes implemented in the given File.
*
* @param psiRoot - File to search.
* @return A List of found classes, or an empty array if none.
*/
@NotNull
public static List<HaxeClass> getClassList(@NotNull HaxeFile psiRoot) {
CachedValuesManager manager = CachedValuesManager.getManager(psiRoot.getProject());
ArrayList<HaxeClass> classList = manager.getCachedValue(psiRoot, () -> {
ArrayList<HaxeClass> classes = new ArrayList<>();
for (PsiElement child : psiRoot.getChildren()) {
if (child instanceof HaxeClass) {
classes.add((HaxeClass)child);
}
}
return new CachedValueProvider.Result<>(classes, psiRoot);
});
return classList;
}
@NotNull
@Override
public Collection<TwigPath> getNamespaces(@NotNull TwigNamespaceExtensionParameter parameter) {
Project project = parameter.getProject();
Collection<Pair<String, String>> cachedValue = CachedValuesManager.getManager(project).getCachedValue(
project,
CACHE,
() -> CachedValueProvider.Result.create(getTwigPaths(project), PsiModificationTracker.MODIFICATION_COUNT),
false
);
// TwigPath is not cache able as it right now; we need to build it here
return cachedValue.stream()
.map(p -> new TwigPath(p.getFirst(), p.getSecond(), TwigUtil.NamespaceType.ADD_PATH, true))
.collect(Collectors.toList());
}
/**
* @param dataHolderKey Main data to cache
* @param dataHolderNames Cache extracted name Set
*/
static public synchronized <T> Map<String, List<T>> getSetDataCache(@NotNull final Project project, @NotNull Key<CachedValue<Map<String, List<T>>>> dataHolderKey, final @NotNull Key<CachedValue<Set<String>>> dataHolderNames, @NotNull final ID<String, T> ID, @NotNull final GlobalSearchScope scope) {
return CachedValuesManager.getManager(project).getCachedValue(
project,
dataHolderKey,
() -> {
Map<String, List<T>> items = new HashMap<>();
final FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();
getIndexKeysCache(project, dataHolderNames, ID).forEach(service ->
items.put(service, fileBasedIndex.getValues(ID, service, scope))
);
return CachedValueProvider.Result.create(items, getModificationTrackerForIndexId(project, ID));
},
false
);
}
/**
* @param dataHolderKey Main data to cache
* @param dataHolderNames Cache extracted name Set
*/
static public synchronized Map<String, List<String>> getStringDataCache(@NotNull final Project project, @NotNull Key<CachedValue<Map<String, List<String>>>> dataHolderKey, final @NotNull Key<CachedValue<Set<String>>> dataHolderNames, @NotNull final ID<String, String> ID, @NotNull final GlobalSearchScope scope) {
return CachedValuesManager.getManager(project).getCachedValue(
project,
dataHolderKey,
() -> {
Map<String, List<String>> strings = new HashMap<>();
final FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();
getIndexKeysCache(project, dataHolderNames, ID).forEach(parameterName -> {
// just for secure
if(parameterName == null) {
return;
}
strings.put(parameterName, fileBasedIndex.getValues(ID, parameterName, scope));
});
return CachedValueProvider.Result.create(strings, getModificationTrackerForIndexId(project, ID));
},
false
);
}
private static void collectIdeJsonBladePaths(@NotNull Project project, @NotNull Collection<TemplatePath> templatePaths) {
for (PsiFile psiFile : FilenameIndex.getFilesByName(project, "ide-blade.json", GlobalSearchScope.allScope(project))) {
Collection<TemplatePath> cachedValue = CachedValuesManager.getCachedValue(psiFile, new MyJsonCachedValueProvider(psiFile));
if (cachedValue != null) {
templatePaths.addAll(cachedValue);
}
}
}
public CoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
myParentDisposable = parentDisposable;
myEnvironment = applicationEnvironment;
myProject = new MockProject(myEnvironment.getApplication(), myParentDisposable);
preregisterServices();
myFileIndexFacade = createFileIndexFacade();
myMessageBus = (MessageBusImpl)myProject.getMessageBus();
PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(applicationEnvironment.getApplication(), myProject);
myProject.registerService(PsiModificationTracker.class, modificationTracker);
myProject.registerService(FileIndexFacade.class, myFileIndexFacade);
myProject.registerService(ResolveCache.class, new ResolveCache(myProject));
registerProjectExtensionPoint(PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor.class);
myPsiManager = new PsiManagerImpl(myProject, () -> myFileIndexFacade, modificationTracker);
((FileManagerImpl)myPsiManager.getFileManager()).markInitialized();
registerProjectComponent(PsiManager.class, myPsiManager);
registerProjectComponent(PsiDocumentManager.class, new CorePsiDocumentManager(myProject, new MockDocumentCommitProcessor()));
myProject.registerService(ResolveScopeManager.class, createResolveScopeManager(myPsiManager));
myProject.registerService(PsiFileFactory.class, new PsiFileFactoryImpl(myPsiManager));
myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
myProject.registerService(ProjectScopeBuilder.class, createProjectScopeBuilder());
myProject.registerService(DumbService.class, new MockDumbService(myProject));
}
protected void runPreview(boolean forceRefresh) {
if (!isAutoSync() && !forceRefresh)
return;
final Map<String, Object> payload = new HashMap<String, Object>();
Map<String, Map<String, Object>> flowVars = new HashMap<String, Map<String, Object>>();
/*
1. Get input from tabs - if payload exists, use payload, otherwise put in the Map
2. Get text from DW
3. Run preview, put the output to the output tab
*/
int count = inputTabs.getTabCount();
for (int index = 0; index < count; index++) {
String title = inputTabs.getTitleAt(index);
Editor editor = editors.get(title);
Document document = editor.getDocument();
String text = document.getText();
String contentType = contentTypes.get(title);
Map<String, Object> content = WeavePreview.createContent(contentType, text);
if ("payload".equalsIgnoreCase(title)) {
payload.clear();
payload.putAll(content);
} else {
flowVars.put(title, content);
}
}
final CachedValuesManager manager = CachedValuesManager.getManager(project);
List<String> melFunctions = manager.getCachedValue(psiFile, MEL_STRINGS_KEY, new MelStringsCachedProvider());
String dwScript = this.textEditor.getEditor().getDocument().getText();
String output = WeavePreview.runPreview(module, dwScript, payload, flowVars, flowVars, flowVars, flowVars, flowVars, melFunctions);
if (output != null)
editors.get("output").getDocument().setText(output);
}
private static boolean unsyncedFileContainsGtestMacroCalls(OCFile file) {
return CachedValuesManager.getCachedValue(
file,
() ->
CachedValueProvider.Result.create(
computeUnsyncedFileContainsGtestMacroCalls(file),
PsiModificationTracker.MODIFICATION_COUNT));
}
@Override
public List<String> getArtifactsSortedByInclusion() {
if (mySortedArtifacts == null) {
mySortedArtifacts = CachedValuesManager.getManager(myProject).createCachedValue(new CachedValueProvider<List<String>>() {
@Override
public Result<List<String>> compute() {
return Result.create(doGetSortedArtifacts(), ArtifactManager.getInstance(myProject).getModificationTracker());
}
}, false);
}
return mySortedArtifacts.getValue();
}
@NotNull
synchronized public static Collection<PhpToolboxProviderInterface> getProviders(final @NotNull Project project) {
CachedValue<Collection<PhpToolboxProviderInterface>> cache = project.getUserData(PROVIDER_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getProvidersInner(project), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(PROVIDER_CACHE, cache);
}
return cache.getValue();
}
@NotNull
synchronized public static Collection<JsonRegistrar> getTypes(final @NotNull Project project) {
CachedValue<Collection<JsonRegistrar>> cache = project.getUserData(TYPE_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getTypesInner(project), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(TYPE_CACHE, cache);
}
return cache.getValue();
}
private static void collectIdeJsonBladePaths(@NotNull Project project, @NotNull Collection<TemplatePath> templatePaths) {
for (PsiFile psiFile : FilenameIndex.getFilesByName(project, "ide-blade.json", GlobalSearchScope.allScope(project))) {
Collection<TemplatePath> cachedValue = CachedValuesManager.getCachedValue(psiFile, new MyJsonCachedValueProvider(psiFile));
if(cachedValue != null) {
templatePaths.addAll(cachedValue);
}
}
}
@NotNull
private Map<String, PsiVariable> getGlobals(@NotNull Project project) {
return CachedValuesManager.getManager(project).getCachedValue(
project,
CACHE,
() -> CachedValueProvider.Result.create(getGlobalsInner(project), PsiModificationTracker.MODIFICATION_COUNT),
false
);
}
@NotNull
synchronized public static Collection<PhpToolboxProviderInterface> getProviders(final @NotNull Project project) {
CachedValue<Collection<PhpToolboxProviderInterface>> cache = project.getUserData(PROVIDER_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getProvidersInner(project), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(PROVIDER_CACHE, cache);
}
return cache.getValue();
}
@NotNull
synchronized public static Collection<JsonRegistrar> getRegistrar(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
CachedValue<Collection<JsonRegistrar>> cache = project.getUserData(REGISTRAR_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getRegistrarInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(REGISTRAR_CACHE, cache);
}
return cache.getValue();
}