use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class ChangeClassParametersIntention method invoke.
@Override
public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) throws IncorrectOperationException {
final PsiTypeElement typeElement = PsiTreeUtil.getTopmostParentOfType(element, PsiTypeElement.class);
final PsiReferenceParameterList parameterList = PsiTreeUtil.getParentOfType(typeElement, PsiReferenceParameterList.class);
if (parameterList != null) {
final PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
if (aClass instanceof PsiAnonymousClass) {
editor.getCaretModel().moveToOffset(aClass.getTextOffset());
final PsiTypeElement[] typeElements = parameterList.getTypeParameterElements();
final int changeIdx = ArrayUtil.find(typeElements, typeElement);
final PsiClassType.ClassResolveResult result = ((PsiAnonymousClass) aClass).getBaseClassType().resolveGenerics();
final PsiClass baseClass = result.getElement();
LOG.assertTrue(baseClass != null);
final PsiTypeParameter typeParameter = baseClass.getTypeParameters()[changeIdx];
final TemplateBuilderImpl templateBuilder = (TemplateBuilderImpl) TemplateBuilderFactory.getInstance().createTemplateBuilder(aClass);
final String oldTypeText = typeElement.getText();
final String varName = "param";
templateBuilder.replaceElement(typeElement, varName, new TypeExpression(project, new PsiType[] { typeElement.getType() }), true);
final Template template = templateBuilder.buildInlineTemplate();
TemplateManager.getInstance(project).startTemplate(editor, template, false, null, new TemplateEditingAdapter() {
private String myNewType;
@Override
public void beforeTemplateFinished(TemplateState state, Template template) {
final TextResult value = state.getVariableValue(varName);
myNewType = value != null ? value.getText() : "";
final int segmentsCount = state.getSegmentsCount();
final Document document = state.getEditor().getDocument();
ApplicationManager.getApplication().runWriteAction(() -> {
for (int i = 0; i < segmentsCount; i++) {
final TextRange segmentRange = state.getSegmentRange(i);
document.replaceString(segmentRange.getStartOffset(), segmentRange.getEndOffset(), oldTypeText);
}
});
}
@Override
public void templateFinished(Template template, boolean brokenOff) {
if (!brokenOff) {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
try {
final PsiType targetParam = elementFactory.createTypeFromText(myNewType, aClass);
if (!(targetParam instanceof PsiClassType)) {
HintManager.getInstance().showErrorHint(editor, JavaErrorMessages.message("generics.type.argument.cannot.be.of.primitive.type"));
return;
}
final PsiClassType classType = (PsiClassType) targetParam;
final PsiClass target = classType.resolve();
if (target == null) {
HintManager.getInstance().showErrorHint(editor, JavaErrorMessages.message("cannot.resolve.symbol", classType.getPresentableText()));
return;
}
final TypeMigrationRules myRules = new TypeMigrationRules();
final PsiSubstitutor substitutor = result.getSubstitutor().put(typeParameter, targetParam);
final PsiType targetClassType = elementFactory.createType(baseClass, substitutor);
myRules.setBoundScope(new LocalSearchScope(aClass));
TypeMigrationProcessor.runHighlightingTypeMigration(project, editor, myRules, ((PsiAnonymousClass) aClass).getBaseClassReference().getParameterList(), targetClassType);
} catch (IncorrectOperationException e) {
HintManager.getInstance().showErrorHint(editor, "Incorrect type");
}
}
}
});
}
}
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class TypeMigrationTestBase method performAction.
private void performAction(String className, String rootDir, RulesProvider provider) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
final PsiElement[] migrationElements = provider.victims(aClass);
final PsiType migrationType = provider.migrationType(migrationElements[0]);
final TypeMigrationRules rules = new TypeMigrationRules();
rules.setBoundScope(new LocalSearchScope(aClass.getContainingFile()));
final TestTypeMigrationProcessor pr = new TestTypeMigrationProcessor(getProject(), migrationElements, migrationType, rules);
final UsageInfo[] usages = pr.findUsages();
final String report = pr.getLabeler().getMigrationReport();
WriteCommandAction.runWriteCommandAction(null, () -> pr.performRefactoring(usages));
String itemName = className + ".items";
String patternName = getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName;
File patternFile = new File(patternName);
if (!patternFile.exists()) {
PrintWriter writer = new PrintWriter(new FileOutputStream(patternFile));
try {
writer.print(report);
writer.close();
} finally {
writer.close();
}
System.out.println("Pattern not found, file " + patternName + " created.");
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile);
}
File graFile = new File(FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName);
PrintWriter writer = new PrintWriter(new FileOutputStream(graFile));
try {
writer.print(report);
writer.close();
} finally {
writer.close();
}
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile);
FileDocumentManager.getInstance().saveAllDocuments();
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class GlobalInspectionContextBase method cleanupElements.
public static void cleanupElements(@NotNull final Project project, @Nullable final Runnable runnable, final List<SmartPsiElementPointer<PsiElement>> elements) {
Runnable cleanupRunnable = () -> {
final List<PsiElement> psiElements = new ArrayList<>();
for (SmartPsiElementPointer<PsiElement> element : elements) {
PsiElement psiElement = element.getElement();
if (psiElement != null && psiElement.isPhysical()) {
psiElements.add(psiElement);
}
}
if (psiElements.isEmpty()) {
return;
}
GlobalInspectionContextBase globalContext = (GlobalInspectionContextBase) InspectionManager.getInstance(project).createNewGlobalContext(false);
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getCurrentProfile();
AnalysisScope analysisScope = new AnalysisScope(new LocalSearchScope(psiElements.toArray(new PsiElement[psiElements.size()])), project);
globalContext.codeCleanup(analysisScope, profile, null, runnable, true);
};
Application application = ApplicationManager.getApplication();
if (application.isWriteAccessAllowed() && !application.isUnitTestMode()) {
application.invokeLater(cleanupRunnable);
} else {
cleanupRunnable.run();
}
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class GlobalInspectionContextImpl method runTools.
@Override
protected void runTools(@NotNull final AnalysisScope scope, boolean runGlobalToolsOnly, boolean isOfflineInspections) {
final ProgressIndicator progressIndicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
if (progressIndicator == null) {
throw new IncorrectOperationException("Must be run under progress");
}
if (!isOfflineInspections && ApplicationManager.getApplication().isDispatchThread()) {
throw new IncorrectOperationException("Must not start inspections from within EDT");
}
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
throw new IncorrectOperationException("Must not start inspections from within write action");
}
// in offline inspection application we don't care about global read action
if (!isOfflineInspections && ApplicationManager.getApplication().isReadAccessAllowed()) {
throw new IncorrectOperationException("Must not start inspections from within global read action");
}
final InspectionManager inspectionManager = InspectionManager.getInstance(getProject());
((RefManagerImpl) getRefManager()).initializeAnnotators();
final List<Tools> globalTools = new ArrayList<>();
final List<Tools> localTools = new ArrayList<>();
final List<Tools> globalSimpleTools = new ArrayList<>();
initializeTools(globalTools, localTools, globalSimpleTools);
appendPairedInspectionsForUnfairTools(globalTools, globalSimpleTools, localTools);
runGlobalTools(scope, inspectionManager, globalTools, isOfflineInspections);
if (runGlobalToolsOnly || localTools.isEmpty() && globalSimpleTools.isEmpty())
return;
SearchScope searchScope = ReadAction.compute(scope::toSearchScope);
final Set<VirtualFile> localScopeFiles = searchScope instanceof LocalSearchScope ? new THashSet<>() : null;
for (Tools tools : globalSimpleTools) {
GlobalInspectionToolWrapper toolWrapper = (GlobalInspectionToolWrapper) tools.getTool();
GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool) toolWrapper.getTool();
tool.inspectionStarted(inspectionManager, this, getPresentation(toolWrapper));
}
final boolean headlessEnvironment = ApplicationManager.getApplication().isHeadlessEnvironment();
final Map<String, InspectionToolWrapper> map = getInspectionWrappersMap(localTools);
final BlockingQueue<PsiFile> filesToInspect = new ArrayBlockingQueue<>(1000);
// use original progress indicator here since we don't want it to cancel on write action start
ProgressIndicator iteratingIndicator = new SensitiveProgressWrapper(progressIndicator);
Future<?> future = startIterateScopeInBackground(scope, localScopeFiles, headlessEnvironment, filesToInspect, iteratingIndicator);
Processor<PsiFile> processor = file -> {
ProgressManager.checkCanceled();
if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(() -> {
if (!file.isValid()) {
return;
}
LOG.assertTrue(scope.contains(file.getVirtualFile()), file.getName());
inspectFile(file, inspectionManager, localTools, globalSimpleTools, map);
})) {
throw new ProcessCanceledException();
}
boolean includeDoNotShow = includeDoNotShow(getCurrentProfile());
Stream.concat(getWrappersFromTools(localTools, file, includeDoNotShow).stream(), getWrappersFromTools(globalSimpleTools, file, includeDoNotShow).stream()).filter(wrapper -> wrapper.getTool() instanceof ExternalAnnotatorBatchInspection).forEach(wrapper -> {
ProblemDescriptor[] descriptors = ((ExternalAnnotatorBatchInspection) wrapper.getTool()).checkFile(file, this, inspectionManager);
InspectionToolPresentation toolPresentation = getPresentation(wrapper);
ReadAction.run(() -> LocalDescriptorsUtil.addProblemDescriptors(Arrays.asList(descriptors), false, this, null, CONVERT, toolPresentation));
});
return true;
};
try {
final Queue<PsiFile> filesFailedToInspect = new LinkedBlockingQueue<>();
while (true) {
Disposable disposable = Disposer.newDisposable();
ProgressIndicator wrapper = new SensitiveProgressWrapper(progressIndicator);
wrapper.start();
ProgressIndicatorUtils.forceWriteActionPriority(wrapper, disposable);
try {
// use wrapper here to cancel early when write action start but do not affect the original indicator
((JobLauncherImpl) JobLauncher.getInstance()).processQueue(filesToInspect, filesFailedToInspect, wrapper, TOMBSTONE, processor);
break;
} catch (ProcessCanceledException ignored) {
progressIndicator.checkCanceled();
// go on with the write and then resume processing the rest of the queue
assert !ApplicationManager.getApplication().isReadAccessAllowed();
assert !ApplicationManager.getApplication().isDispatchThread();
// wait for write action to complete
ApplicationManager.getApplication().runReadAction(EmptyRunnable.getInstance());
} finally {
Disposer.dispose(disposable);
}
}
} finally {
// tell file scanning thread to stop
iteratingIndicator.cancel();
// let file scanning thread a chance to put TOMBSTONE and complete
filesToInspect.clear();
try {
future.get(30, TimeUnit.SECONDS);
} catch (Exception e) {
LOG.error("Thread dump: \n" + ThreadDumper.dumpThreadsToString(), e);
}
}
progressIndicator.checkCanceled();
for (Tools tools : globalSimpleTools) {
GlobalInspectionToolWrapper toolWrapper = (GlobalInspectionToolWrapper) tools.getTool();
GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool) toolWrapper.getTool();
ProblemDescriptionsProcessor problemDescriptionProcessor = getProblemDescriptionProcessor(toolWrapper, map);
tool.inspectionFinished(inspectionManager, this, problemDescriptionProcessor);
}
addProblemsToView(globalSimpleTools);
}
use of com.intellij.psi.search.LocalSearchScope in project intellij-community by JetBrains.
the class GlobalInspectionContextImpl method cleanup.
private void cleanup(@NotNull final AnalysisScope scope, @NotNull InspectionProfile profile, @Nullable final Runnable postRunnable, @Nullable final String commandName) {
setCurrentScope(scope);
final int fileCount = scope.getFileCount();
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
final SearchScope searchScope = ReadAction.compute(scope::toSearchScope);
final TextRange range;
if (searchScope instanceof LocalSearchScope) {
final PsiElement[] elements = ((LocalSearchScope) searchScope).getScope();
range = elements.length == 1 ? ReadAction.compute(elements[0]::getTextRange) : null;
} else {
range = null;
}
final Iterable<Tools> inspectionTools = ContainerUtil.filter(profile.getAllEnabledInspectionTools(getProject()), tools -> {
assert tools != null;
return tools.getTool().getTool() instanceof CleanupLocalInspectionTool;
});
boolean includeDoNotShow = includeDoNotShow(profile);
final RefManagerImpl refManager = (RefManagerImpl) getRefManager();
refManager.inspectionReadActionStarted();
List<ProblemDescriptor> descriptors = new ArrayList<>();
Set<PsiFile> files = new HashSet<>();
try {
scope.accept(new PsiElementVisitor() {
private int myCount;
@Override
public void visitFile(PsiFile file) {
if (progressIndicator != null) {
progressIndicator.setFraction((double) ++myCount / fileCount);
}
if (isBinary(file))
return;
final List<LocalInspectionToolWrapper> lTools = new ArrayList<>();
for (final Tools tools : inspectionTools) {
final InspectionToolWrapper tool = tools.getEnabledTool(file, includeDoNotShow);
if (tool instanceof LocalInspectionToolWrapper) {
lTools.add((LocalInspectionToolWrapper) tool);
tool.initialize(GlobalInspectionContextImpl.this);
}
}
if (!lTools.isEmpty()) {
try {
final LocalInspectionsPass pass = new LocalInspectionsPass(file, PsiDocumentManager.getInstance(getProject()).getDocument(file), range != null ? range.getStartOffset() : 0, range != null ? range.getEndOffset() : file.getTextLength(), LocalInspectionsPass.EMPTY_PRIORITY_RANGE, true, HighlightInfoProcessor.getEmpty());
Runnable runnable = () -> pass.doInspectInBatch(GlobalInspectionContextImpl.this, InspectionManager.getInstance(getProject()), lTools);
ApplicationManager.getApplication().runReadAction(runnable);
final Set<ProblemDescriptor> localDescriptors = new TreeSet<>(CommonProblemDescriptor.DESCRIPTOR_COMPARATOR);
for (LocalInspectionToolWrapper tool : lTools) {
InspectionToolPresentation toolPresentation = getPresentation(tool);
for (CommonProblemDescriptor descriptor : toolPresentation.getProblemDescriptors()) {
if (descriptor instanceof ProblemDescriptor) {
localDescriptors.add((ProblemDescriptor) descriptor);
}
}
}
if (searchScope instanceof LocalSearchScope) {
for (Iterator<ProblemDescriptor> iterator = localDescriptors.iterator(); iterator.hasNext(); ) {
final ProblemDescriptor descriptor = iterator.next();
final TextRange infoRange = descriptor instanceof ProblemDescriptorBase ? ((ProblemDescriptorBase) descriptor).getTextRange() : null;
if (infoRange != null && !((LocalSearchScope) searchScope).containsRange(file, infoRange)) {
iterator.remove();
}
}
}
if (!localDescriptors.isEmpty()) {
descriptors.addAll(localDescriptors);
files.add(file);
}
} finally {
myPresentationMap.clear();
}
}
}
});
} finally {
refManager.inspectionReadActionFinished();
}
if (files.isEmpty()) {
GuiUtils.invokeLaterIfNeeded(() -> {
if (commandName != null) {
NOTIFICATION_GROUP.createNotification(InspectionsBundle.message("inspection.no.problems.message", scope.getFileCount(), scope.getDisplayName()), MessageType.INFO).notify(getProject());
}
if (postRunnable != null) {
postRunnable.run();
}
}, ModalityState.defaultModalityState());
return;
}
Runnable runnable = () -> {
if (!FileModificationService.getInstance().preparePsiElementsForWrite(files))
return;
CleanupInspectionIntention.applyFixesNoSort(getProject(), "Code Cleanup", descriptors, null);
if (postRunnable != null) {
postRunnable.run();
}
};
TransactionGuard.submitTransaction(getProject(), runnable);
}
Aggregations