diff --git a/RegExpSupport/src/org/intellij/lang/regexp/intention/CheckRegExpForm.java b/RegExpSupport/src/org/intellij/lang/regexp/intention/CheckRegExpForm.java index 584a0a70f2c4..479c4223c0b8 100644 --- a/RegExpSupport/src/org/intellij/lang/regexp/intention/CheckRegExpForm.java +++ b/RegExpSupport/src/org/intellij/lang/regexp/intention/CheckRegExpForm.java @@ -112,12 +112,7 @@ public class CheckRegExpForm { public void documentChanged(DocumentEvent e) { updater.cancelAllRequests(); if (!updater.isDisposed()) { - updater.addRequest(new Runnable() { - @Override - public void run() { - updateBalloon(); - } - }, 200); + updater.addRequest(() -> updateBalloon(), 200); } } }; @@ -150,12 +145,10 @@ public class CheckRegExpForm { private void updateBalloon() { final Boolean correct = isMatchingText(myRegexpFile, mySampleText.getText()); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - mySampleText.setBackground(correct != null && correct ? BACKGROUND_COLOR_MATCH : BACKGROUND_COLOR_NOMATCH); - myMessage.setText(correct == null ? "Pattern is too complex" : correct ? "Matches!" : "No match"); - myRootPanel.revalidate(); - } + ApplicationManager.getApplication().invokeLater(() -> { + mySampleText.setBackground(correct != null && correct ? BACKGROUND_COLOR_MATCH : BACKGROUND_COLOR_NOMATCH); + myMessage.setText(correct == null ? "Pattern is too complex" : correct ? "Matches!" : "No match"); + myRootPanel.revalidate(); }, new Condition() { @Override public boolean value(Object o) { diff --git a/images/src/org/intellij/images/editor/actions/SetBackgroundImageDialog.java b/images/src/org/intellij/images/editor/actions/SetBackgroundImageDialog.java index a46a8cecb910..1854efa33a21 100644 --- a/images/src/org/intellij/images/editor/actions/SetBackgroundImageDialog.java +++ b/images/src/org/intellij/images/editor/actions/SetBackgroundImageDialog.java @@ -82,12 +82,7 @@ public class SetBackgroundImageDialog extends DialogWrapper { myEditorPreview = createEditorPreview(); myIdePreview = createIdePreview(); myPropertyTmp = IdeBackgroundUtil.BG_PROPERTY_PREFIX + project.getLocationHash(); - UiNotifyConnector.doWhenFirstShown(myRoot, new Runnable() { - @Override - public void run() { - IdeBackgroundUtil.createTemporaryBackgroundTransform(myPreviewPanel, myPropertyTmp, getDisposable()); - } - }); + UiNotifyConnector.doWhenFirstShown(myRoot, () -> IdeBackgroundUtil.createTemporaryBackgroundTransform(myPreviewPanel, myPropertyTmp, getDisposable())); setupComponents(); restoreRecentImages(); setSelectedPath(mySelectedPath); diff --git a/images/src/org/intellij/images/editor/impl/ImageEditorImpl.java b/images/src/org/intellij/images/editor/impl/ImageEditorImpl.java index c6003a3e249f..c4f70f950994 100644 --- a/images/src/org/intellij/images/editor/impl/ImageEditorImpl.java +++ b/images/src/org/intellij/images/editor/impl/ImageEditorImpl.java @@ -139,17 +139,15 @@ public final class ImageEditorImpl implements ImageEditor { void propertyChanged(@NotNull VirtualFilePropertyEvent event) { if (file.equals(event.getFile())) { // Change document - file.refresh(true, false, new Runnable() { - public void run() { - if (ImageFileTypeManager.getInstance().isImage(file)) { - setValue(file); - } - else { - setValue(null); - // Close editor - FileEditorManager editorManager = FileEditorManager.getInstance(project); - editorManager.closeFile(file); - } + file.refresh(true, false, () -> { + if (ImageFileTypeManager.getInstance().isImage(file)) { + setValue(file); + } + else { + setValue(null); + // Close editor + FileEditorManager editorManager = FileEditorManager.getInstance(project); + editorManager.closeFile(file); } }); } @@ -158,11 +156,7 @@ public final class ImageEditorImpl implements ImageEditor { void contentsChanged(@NotNull VirtualFileEvent event) { if (file.equals(event.getFile())) { // Change document - Runnable postRunnable = new Runnable() { - public void run() { - setValue(file); - } - }; + Runnable postRunnable = () -> setValue(file); RefreshQueue.getInstance().refresh(true, false, postRunnable, ModalityState.current(), file); } } diff --git a/images/src/org/intellij/images/options/impl/OptionsUIForm.java b/images/src/org/intellij/images/options/impl/OptionsUIForm.java index 9f945bee3ca1..faa7fa784d98 100644 --- a/images/src/org/intellij/images/options/impl/OptionsUIForm.java +++ b/images/src/org/intellij/images/options/impl/OptionsUIForm.java @@ -249,12 +249,9 @@ final class OptionsUIForm { fileDescriptor.setShowFileSystemRoots(true); fileDescriptor.setTitle(ImagesBundle.message("select.external.executable.title")); fileDescriptor.setDescription(ImagesBundle.message("select.external.executable.message")); - FileChooser.chooseFiles(fileDescriptor, null, previous, new Consumer>() { - @Override - public void consume(final List files) { - String path = files.get(0).getPath(); - externalEditorPath.setText(path); - } + FileChooser.chooseFiles(fileDescriptor, null, previous, files -> { + String path = files.get(0).getPath(); + externalEditorPath.setText(path); }); } } diff --git a/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewImpl.java b/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewImpl.java index 2b04c8822c98..a755af2f13c3 100644 --- a/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewImpl.java +++ b/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewImpl.java @@ -184,11 +184,7 @@ final class ThumbnailViewImpl implements ThumbnailView { private final class LazyScroller implements Runnable { public void run() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - getUI().scrollToSelection(); - } - }); + SwingUtilities.invokeLater(() -> getUI().scrollToSelection()); } } } diff --git a/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewUI.java b/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewUI.java index 83f7679fcc62..a6299d324f27 100644 --- a/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewUI.java +++ b/images/src/org/intellij/images/thumbnail/impl/ThumbnailViewUI.java @@ -71,17 +71,15 @@ final class ThumbnailViewUI extends JPanel implements DataProvider, Disposable { private final DeleteProvider deleteProvider; private ThumbnailListCellRenderer cellRenderer; private JList list; - private static final Comparator VIRTUAL_FILE_COMPARATOR = new Comparator() { - public int compare(VirtualFile o1, VirtualFile o2) { - if (o1.isDirectory() && !o2.isDirectory()) { - return -1; - } - if (o2.isDirectory() && !o1.isDirectory()) { - return 1; - } - - return o1.getPath().toLowerCase().compareTo(o2.getPath().toLowerCase()); + private static final Comparator VIRTUAL_FILE_COMPARATOR = (o1, o2) -> { + if (o1.isDirectory() && !o2.isDirectory()) { + return -1; } + if (o2.isDirectory() && !o1.isDirectory()) { + return 1; + } + + return o1.getPath().toLowerCase().compareTo(o2.getPath().toLowerCase()); }; public ThumbnailViewUI(ThumbnailViewImpl thumbnailView) { diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java index 1de955b041ca..eebc40279d3e 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java @@ -334,12 +334,7 @@ public class BuildArtifactAction extends DumbAwareAction { @Override public PopupStep onChosen(final List selectedValues, boolean finalChoice) { if (finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - doBuild(myProject, selectedValues, false); - } - }); + return doFinalStep(() -> doBuild(myProject, selectedValues, false)); } final List actions = new ArrayList(); actions.add(new BuildArtifactItem(selectedValues, myProject)); diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java index afb6a9035a20..ba404275f63f 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java @@ -50,19 +50,15 @@ public class GenerateAntBuildAction extends CompileActionBase { if (dialog.showAndGet()) { final String[] names = dialog.getRepresentativeModuleNames(); final GenerationOptionsImpl[] genOptions = new GenerationOptionsImpl[1]; - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - genOptions[0] = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public GenerationOptionsImpl compute() { - return new GenerationOptionsImpl(project, dialog.isGenerateSingleFileBuild(), dialog.isFormsCompilationEnabled(), - dialog.isBackupFiles(), dialog.isForceTargetJdk(), dialog.isRuntimeClasspathInlined(), - dialog.isIdeaHomeGenerated(), names, dialog.getOutputFileName()); - } - }); - } - }, "Analyzing project structure...", true, project)) { + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously( + (Runnable)() -> genOptions[0] = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public GenerationOptionsImpl compute() { + return new GenerationOptionsImpl(project, dialog.isGenerateSingleFileBuild(), dialog.isFormsCompilationEnabled(), + dialog.isBackupFiles(), dialog.isForceTargetJdk(), dialog.isRuntimeClasspathInlined(), + dialog.isIdeaHomeGenerated(), names, dialog.getOutputFileName()); + } + }), "Analyzing project structure...", true, project)) { return; } if (!validateGenOptions(project, genOptions[0])) { diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/GenerateAntApplication.java b/java/compiler/impl/src/com/intellij/compiler/ant/GenerateAntApplication.java index 7606b26a87bd..612d21bbb1bf 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/GenerateAntApplication.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/GenerateAntApplication.java @@ -45,23 +45,21 @@ public class GenerateAntApplication { GenerateAntMain.printHelp(); } - SwingUtilities.invokeLater(new Runnable() { - public void run() { - ApplicationEx application = ApplicationManagerEx.getApplicationEx(); - try { - logMessage(0, "Starting app... "); - application.doNotSave(); - application.load(); - logMessageLn(0, "done"); + SwingUtilities.invokeLater(() -> { + ApplicationEx application = ApplicationManagerEx.getApplicationEx(); + try { + logMessage(0, "Starting app... "); + application.doNotSave(); + application.load(); + logMessageLn(0, "done"); - GenerateAntApplication.this.run(); - } - catch (Exception e) { - GenerateAntApplication.LOG.error(e); - } - finally { - application.exit(true, true); - } + GenerateAntApplication.this.run(); + } + catch (Exception e) { + GenerateAntApplication.LOG.error(e); + } + finally { + application.exit(true, true); } }); } diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/LibraryDefinitionsGeneratorFactory.java b/java/compiler/impl/src/com/intellij/compiler/ant/LibraryDefinitionsGeneratorFactory.java index 5565f2178fc4..b8b347df67b9 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/LibraryDefinitionsGeneratorFactory.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/LibraryDefinitionsGeneratorFactory.java @@ -50,15 +50,12 @@ public class LibraryDefinitionsGeneratorFactory { final ModuleManager moduleManager = ModuleManager.getInstance(project); final Module[] modules = moduleManager.getModules(); for (Module module : modules) { - ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - final String name = library.getName(); - if (name != null) { - myUsedLibraries.add(name); - } - return true; + ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(library -> { + final String name = library.getName(); + if (name != null) { + myUsedLibraries.add(name); } + return true; }); } } diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/ModuleChunkClasspath.java b/java/compiler/impl/src/com/intellij/compiler/ant/ModuleChunkClasspath.java index 926fc39375fb..b59eac04e227 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/ModuleChunkClasspath.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/ModuleChunkClasspath.java @@ -101,88 +101,85 @@ public class ModuleChunkClasspath extends Path { if (!generateTestClasspath) { enumerator = enumerator.productionOnly(); } - enumerator.forEach(new Processor() { - @Override - public boolean process(OrderEntry orderEntry) { - if (!orderEntry.isValid()) { - return true; - } - - if (!generateRuntimeClasspath && - !(orderEntry instanceof ModuleOrderEntry) && - !(orderEntry instanceof ModuleSourceOrderEntry)) { - // needed for compilation classpath only - final boolean isExported = (orderEntry instanceof ExportableOrderEntry) && ((ExportableOrderEntry)orderEntry).isExported(); - if (dependencyLevel > 0 && !isExported) { - // non-exported dependencies are excluded and not processed - return true; - } - } - - if (orderEntry instanceof JdkOrderEntry) { - if (genOptions.forceTargetJdk && !generateRuntimeClasspath) { - pathItems - .add(new PathRefItem(BuildProperties.propertyRef(BuildProperties.getModuleChunkJdkClasspathProperty(chunk.getName())))); - } - } - else if (orderEntry instanceof ModuleOrderEntry) { - final ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry; - final Module dependentModule = moduleOrderEntry.getModule(); - if (!chunk.contains(dependentModule)) { - if (generateRuntimeClasspath && !genOptions.inlineRuntimeClasspath) { - // in case of runtime classpath, just an referenced to corresponding classpath is created - final ModuleChunk depChunk = genOptions.getChunkByModule(dependentModule); - if (!processedChunks.contains(depChunk)) { - // chunk references are included in the runtime classpath only once - processedChunks.add(depChunk); - String property = generateTestClasspath ? BuildProperties.getTestRuntimeClasspathProperty(depChunk.getName()) - : BuildProperties.getRuntimeClasspathProperty(depChunk.getName()); - pathItems.add(new PathRefItem(property)); - } - } - else { - // in case of compile classpath or inlined runtime classpath, - // the referenced module is processed recursively - processModule(dependentModule, dependencyLevel + 1, moduleOrderEntry.isExported()); - } - } - } - else if (orderEntry instanceof LibraryOrderEntry) { - final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)orderEntry; - final String libraryName = libraryOrderEntry.getLibraryName(); - if (((LibraryOrderEntry)orderEntry).isModuleLevel()) { - CompositeGenerator gen = new CompositeGenerator(); - gen.setHasLeadingNewline(false); - LibraryDefinitionsGeneratorFactory.genLibraryContent(project, genOptions, libraryOrderEntry.getLibrary(), baseDir, gen); - pathItems.add(new GeneratorItem(libraryName, gen)); - } - else { - pathItems.add(new PathRefItem(BuildProperties.getLibraryPathId(libraryName))); - } - } - else if (orderEntry instanceof ModuleSourceOrderEntry) { - // Module source entry? - for (String url : getCompilationClasses(module, ((GenerationOptionsImpl)genOptions), generateRuntimeClasspath, - generateTestClasspath, dependencyLevel == 0)) { - url = StringUtil.trimEnd(url, JarFileSystem.JAR_SEPARATOR); - final String propertyRef = genOptions.getPropertyRefForUrl(url); - if (propertyRef != null) { - pathItems.add(new PathElementItem(propertyRef)); - } - else { - final String path = VirtualFileManager.extractPath(url); - pathItems.add(new PathElementItem( - GenerationUtils.toRelativePath(path, chunk.getBaseDir(), moduleChunkBasedirProperty, genOptions))); - } - } - } - else { - // Unknown order entry type. If it is actually encountered, extension point should be implemented - pathItems.add(new GeneratorItem(orderEntry.getClass().getName(), - new Comment("Unknown OrderEntryType: " + orderEntry.getClass().getName()))); - } + enumerator.forEach(orderEntry -> { + if (!orderEntry.isValid()) { return true; } + + if (!generateRuntimeClasspath && + !(orderEntry instanceof ModuleOrderEntry) && + !(orderEntry instanceof ModuleSourceOrderEntry)) { + // needed for compilation classpath only + final boolean isExported = (orderEntry instanceof ExportableOrderEntry) && ((ExportableOrderEntry)orderEntry).isExported(); + if (dependencyLevel > 0 && !isExported) { + // non-exported dependencies are excluded and not processed + return true; + } + } + + if (orderEntry instanceof JdkOrderEntry) { + if (genOptions.forceTargetJdk && !generateRuntimeClasspath) { + pathItems + .add(new PathRefItem(BuildProperties.propertyRef(BuildProperties.getModuleChunkJdkClasspathProperty(chunk.getName())))); + } + } + else if (orderEntry instanceof ModuleOrderEntry) { + final ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry; + final Module dependentModule = moduleOrderEntry.getModule(); + if (!chunk.contains(dependentModule)) { + if (generateRuntimeClasspath && !genOptions.inlineRuntimeClasspath) { + // in case of runtime classpath, just an referenced to corresponding classpath is created + final ModuleChunk depChunk = genOptions.getChunkByModule(dependentModule); + if (!processedChunks.contains(depChunk)) { + // chunk references are included in the runtime classpath only once + processedChunks.add(depChunk); + String property = generateTestClasspath ? BuildProperties.getTestRuntimeClasspathProperty(depChunk.getName()) + : BuildProperties.getRuntimeClasspathProperty(depChunk.getName()); + pathItems.add(new PathRefItem(property)); + } + } + else { + // in case of compile classpath or inlined runtime classpath, + // the referenced module is processed recursively + processModule(dependentModule, dependencyLevel + 1, moduleOrderEntry.isExported()); + } + } + } + else if (orderEntry instanceof LibraryOrderEntry) { + final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)orderEntry; + final String libraryName = libraryOrderEntry.getLibraryName(); + if (((LibraryOrderEntry)orderEntry).isModuleLevel()) { + CompositeGenerator gen = new CompositeGenerator(); + gen.setHasLeadingNewline(false); + LibraryDefinitionsGeneratorFactory.genLibraryContent(project, genOptions, libraryOrderEntry.getLibrary(), baseDir, gen); + pathItems.add(new GeneratorItem(libraryName, gen)); + } + else { + pathItems.add(new PathRefItem(BuildProperties.getLibraryPathId(libraryName))); + } + } + else if (orderEntry instanceof ModuleSourceOrderEntry) { + // Module source entry? + for (String url : getCompilationClasses(module, ((GenerationOptionsImpl)genOptions), generateRuntimeClasspath, + generateTestClasspath, dependencyLevel == 0)) { + url = StringUtil.trimEnd(url, JarFileSystem.JAR_SEPARATOR); + final String propertyRef = genOptions.getPropertyRefForUrl(url); + if (propertyRef != null) { + pathItems.add(new PathElementItem(propertyRef)); + } + else { + final String path = VirtualFileManager.extractPath(url); + pathItems.add(new PathElementItem( + GenerationUtils.toRelativePath(path, chunk.getBaseDir(), moduleChunkBasedirProperty, genOptions))); + } + } + } + else { + // Unknown order entry type. If it is actually encountered, extension point should be implemented + pathItems.add(new GeneratorItem(orderEntry.getClass().getName(), + new Comment("Unknown OrderEntryType: " + orderEntry.getClass().getName()))); + } + return true; }); } }.processModule(module, 0, false); diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/artifacts/ArtifactsGenerator.java b/java/compiler/impl/src/com/intellij/compiler/ant/artifacts/ArtifactsGenerator.java index 9aad17533b8f..d8c65b3de514 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/artifacts/ArtifactsGenerator.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/artifacts/ArtifactsGenerator.java @@ -120,25 +120,22 @@ public class ArtifactsGenerator { private Target createArtifactTarget(Artifact artifact) { final StringBuilder depends = new StringBuilder(INIT_ARTIFACTS_TARGET); - ArtifactUtil.processRecursivelySkippingIncludedArtifacts(artifact, new Processor>() { - @Override - public boolean process(@NotNull PackagingElement packagingElement) { - if (packagingElement instanceof ArtifactPackagingElement) { - final Artifact included = ((ArtifactPackagingElement)packagingElement).findArtifact(myResolvingContext); - if (included != null) { - if (depends.length() > 0) depends.append(", "); - depends.append(myContext.getTargetName(included)); - } + ArtifactUtil.processRecursivelySkippingIncludedArtifacts(artifact, packagingElement -> { + if (packagingElement instanceof ArtifactPackagingElement) { + final Artifact included = ((ArtifactPackagingElement)packagingElement).findArtifact(myResolvingContext); + if (included != null) { + if (depends.length() > 0) depends.append(", "); + depends.append(myContext.getTargetName(included)); } - else if (packagingElement instanceof ModuleOutputPackagingElement) { - final Module module = ((ModuleOutputPackagingElement)packagingElement).findModule(myResolvingContext); - if (module != null) { - if (depends.length() > 0) depends.append(", "); - depends.append(BuildProperties.getCompileTargetName(module.getName())); - } - } - return true; } + else if (packagingElement instanceof ModuleOutputPackagingElement) { + final Module module = ((ModuleOutputPackagingElement)packagingElement).findModule(myResolvingContext); + if (module != null) { + if (depends.length() > 0) depends.append(", "); + depends.append(BuildProperties.getCompileTargetName(module.getName())); + } + } + return true; }, myResolvingContext); final Couple xmlNs = getArtifactXmlNs(artifact.getArtifactType()); diff --git a/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/ChainsSearcher.java b/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/ChainsSearcher.java index 51343b9e5d7e..818ac0a66e1f 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/ChainsSearcher.java +++ b/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/ChainsSearcher.java @@ -90,21 +90,17 @@ public final class ChainsSearcher { final LinkedList>> q = new LinkedList>>(ContainerUtil.map(allInitialVertexes, - new Function, WeightAware>>() { - @Override - public WeightAware> fun( - final WeightAware methodIncompleteSignatureWeightAware) { - final MethodIncompleteSignature underlying = methodIncompleteSignatureWeightAware.getUnderlying(); - return new WeightAware>( - Pair.create( - underlying, - new MethodsChain(context.resolveNotDeprecated(underlying), - methodIncompleteSignatureWeightAware.getWeight(), - underlying.getOwner())), - methodIncompleteSignatureWeightAware.getWeight() - ); - } - } + methodIncompleteSignatureWeightAware -> { + final MethodIncompleteSignature underlying = methodIncompleteSignatureWeightAware.getUnderlying(); + return new WeightAware>( + Pair.create( + underlying, + new MethodsChain(context.resolveNotDeprecated(underlying), + methodIncompleteSignatureWeightAware.getWeight(), + underlying.getOwner())), + methodIncompleteSignatureWeightAware.getWeight() + ); + } )); int maxWeight = 0; @@ -265,45 +261,42 @@ public final class ChainsSearcher { } private static List reduceChainsSize(final List chains, final PsiManager psiManager) { - return ContainerUtil.map(chains, new Function() { - @Override - public MethodsChain fun(final MethodsChain chain) { - final Iterator chainIterator = chain.iterator(); - if (!chainIterator.hasNext()) { - LOG.error("empty chain"); + return ContainerUtil.map(chains, chain -> { + final Iterator chainIterator = chain.iterator(); + if (!chainIterator.hasNext()) { + LOG.error("empty chain"); + return chain; + } + final PsiMethod[] first = chainIterator.next(); + while (chainIterator.hasNext()) { + final PsiMethod psiMethod = chainIterator.next()[0]; + if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) { + continue; + } + final PsiClass current = psiMethod.getContainingClass(); + if (current == null) { + LOG.error("containing class must be not null"); return chain; } - final PsiMethod[] first = chainIterator.next(); - while (chainIterator.hasNext()) { - final PsiMethod psiMethod = chainIterator.next()[0]; - if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) { - continue; - } - final PsiClass current = psiMethod.getContainingClass(); - if (current == null) { - LOG.error("containing class must be not null"); - return chain; - } - final PsiMethod[] currentMethods = current.findMethodsByName(first[0].getName(), true); - if (currentMethods.length != 0) { - for (final PsiMethod f : first) { - final PsiMethod[] fSupers = f.findDeepestSuperMethods(); - final PsiMethod fSuper = fSupers.length == 0 ? first[0] : fSupers[0]; - for (final PsiMethod currentMethod : currentMethods) { - if (psiManager.areElementsEquivalent(currentMethod, fSuper)) { - return createChainFromFirstElement(chain, currentMethod.getContainingClass()); - } - for (final PsiMethod method : currentMethod.findDeepestSuperMethods()) { - if (psiManager.areElementsEquivalent(method, fSuper)) { - return createChainFromFirstElement(chain, method.getContainingClass()); - } + final PsiMethod[] currentMethods = current.findMethodsByName(first[0].getName(), true); + if (currentMethods.length != 0) { + for (final PsiMethod f : first) { + final PsiMethod[] fSupers = f.findDeepestSuperMethods(); + final PsiMethod fSuper = fSupers.length == 0 ? first[0] : fSupers[0]; + for (final PsiMethod currentMethod : currentMethods) { + if (psiManager.areElementsEquivalent(currentMethod, fSuper)) { + return createChainFromFirstElement(chain, currentMethod.getContainingClass()); + } + for (final PsiMethod method : currentMethod.findDeepestSuperMethods()) { + if (psiManager.areElementsEquivalent(method, fSuper)) { + return createChainFromFirstElement(chain, method.getContainingClass()); } } } } } - return chain; } + return chain; }); } diff --git a/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/completion/MethodsChainsCompletionContributor.java b/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/completion/MethodsChainsCompletionContributor.java index d96d6dfe0f83..79c0cf2b6c1d 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/completion/MethodsChainsCompletionContributor.java +++ b/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/completion/MethodsChainsCompletionContributor.java @@ -70,21 +70,18 @@ public class MethodsChainsCompletionContributor extends CompletionContributor { contextRelevantTypes.remove(target.getClassQName()); final List elementsFoundByMethodsChainsSearch = searchForLookups(target, contextRelevantTypes, completionContext); if (!IS_UNIT_TEST_MODE) { - result.runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(final CompletionResult completionResult) { - final LookupElement lookupElement = completionResult.getLookupElement(); - final PsiElement lookupElementPsi = lookupElement.getPsiElement(); - if (lookupElementPsi != null) { - for (final LookupElement element : elementsFoundByMethodsChainsSearch) { - if (lookupElementPsi.isEquivalentTo(element.getPsiElement())) { - elementsFoundByMethodsChainsSearch.remove(element); - break; - } + result.runRemainingContributors(parameters, completionResult -> { + final LookupElement lookupElement = completionResult.getLookupElement(); + final PsiElement lookupElementPsi = lookupElement.getPsiElement(); + if (lookupElementPsi != null) { + for (final LookupElement element : elementsFoundByMethodsChainsSearch) { + if (lookupElementPsi.isEquivalentTo(element.getPsiElement())) { + elementsFoundByMethodsChainsSearch.remove(element); + break; } } - result.passResult(completionResult); } + result.passResult(completionResult); }); } else { result.stopHere(); @@ -104,40 +101,34 @@ public class MethodsChainsCompletionContributor extends CompletionContributor { if (searchResult.size() < MAX_SEARCH_RESULT_SIZE) { if (!target.isArray()) { final List inheritorFilteredSearchResult = new SmartList(); - final Processor consumer = new Processor() { - @Override - public boolean process(final TargetType targetType) { - for (final MethodsChain chain : searchChains(targetType, - contextRelevantTypes, - MAX_SEARCH_RESULT_SIZE, - MAX_CHAIN_SIZE, - completionContext, - methodsUsageIndexReader)) { - boolean insert = true; - for (final MethodsChain baseChain : searchResult) { - final MethodsChain.CompareResult r = MethodsChain.compare(baseChain, chain, completionContext.getPsiManager()); - if (r != MethodsChain.CompareResult.NOT_EQUAL) { - insert = false; - break; - } - } - if (insert) { - inheritorFilteredSearchResult.add(chain); + final Processor consumer = targetType -> { + for (final MethodsChain chain : searchChains(targetType, + contextRelevantTypes, + MAX_SEARCH_RESULT_SIZE, + MAX_CHAIN_SIZE, + completionContext, + methodsUsageIndexReader)) { + boolean insert = true; + for (final MethodsChain baseChain : searchResult) { + final MethodsChain.CompareResult r = MethodsChain.compare(baseChain, chain, completionContext.getPsiManager()); + if (r != MethodsChain.CompareResult.NOT_EQUAL) { + insert = false; + break; } } - searchResult.addAll(inheritorFilteredSearchResult); - return searchResult.size() < MAX_SEARCH_RESULT_SIZE; + if (insert) { + inheritorFilteredSearchResult.add(chain); + } } + searchResult.addAll(inheritorFilteredSearchResult); + return searchResult.size() < MAX_SEARCH_RESULT_SIZE; }; - DirectClassInheritorsSearch.search(((PsiClassType)target.getPsiType()).resolve()).forEach(new Processor() { - @Override - public boolean process(final PsiClass psiClass) { - final String inheritorQName = psiClass.getQualifiedName(); - if (inheritorQName == null) { - return true; - } - return consumer.process(new TargetType(inheritorQName, false, new PsiImmediateClassType(psiClass, PsiSubstitutor.EMPTY))); + DirectClassInheritorsSearch.search(((PsiClassType)target.getPsiType()).resolve()).forEach(psiClass -> { + final String inheritorQName = psiClass.getQualifiedName(); + if (inheritorQName == null) { + return true; } + return consumer.process(new TargetType(inheritorQName, false, new PsiImmediateClassType(psiClass, PsiSubstitutor.EMPTY))); }); } } @@ -147,12 +138,7 @@ public class MethodsChainsCompletionContributor extends CompletionContributor { } private static List chooseHead(final List elements) { - Collections.sort(elements, new Comparator() { - @Override - public int compare(final MethodsChain o1, final MethodsChain o2) { - return o2.getChainWeight() - o1.getChainWeight(); - } - }); + Collections.sort(elements, (o1, o2) -> o2.getChainWeight() - o1.getChainWeight()); return elements.subList(0, MAX_CHAIN_SIZE); } diff --git a/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/context/MethodIncompleteSignatureResolver.java b/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/context/MethodIncompleteSignatureResolver.java index f6353f3022eb..1fd7a8407799 100644 --- a/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/context/MethodIncompleteSignatureResolver.java +++ b/java/compiler/impl/src/com/intellij/compiler/classFilesIndex/chainsSearch/context/MethodIncompleteSignatureResolver.java @@ -82,12 +82,7 @@ final class MethodIncompleteSignatureResolver { } } if (filtered.size() > 1) { - Collections.sort(filtered, new Comparator() { - @Override - public int compare(final PsiMethod o1, final PsiMethod o2) { - return o1.getParameterList().getParametersCount() - o2.getParameterList().getParametersCount(); - } - }); + Collections.sort(filtered, (o1, o2) -> o1.getParameterList().getParametersCount() - o2.getParameterList().getParametersCount()); } return filtered.toArray(new PsiMethod[filtered.size()]); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index deec5c2f92f5..c83f80ed8320 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -130,30 +130,28 @@ public class CompileDriver { final Ref result = new Ref(); - task.start(new Runnable() { - public void run() { - final ProgressIndicator indicator = compileContext.getProgressIndicator(); - if (indicator.isCanceled() || myProject.isDisposed()) { - return; - } - try { - final TaskFuture future = compileInExternalProcess(compileContext, true); - if (future != null) { - while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) { - if (indicator.isCanceled()) { - future.cancel(false); - } + task.start(() -> { + final ProgressIndicator indicator = compileContext.getProgressIndicator(); + if (indicator.isCanceled() || myProject.isDisposed()) { + return; + } + try { + final TaskFuture future = compileInExternalProcess(compileContext, true); + if (future != null) { + while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) { + if (indicator.isCanceled()) { + future.cancel(false); } } } - catch (Throwable e) { - LOG.error(e); - } - finally { - result.set(COMPILE_SERVER_BUILD_STATUS.get(compileContext)); - if (!myProject.isDisposed()) { - CompilerCacheManager.getInstance(myProject).flushCaches(); - } + } + catch (Throwable e) { + LOG.error(e); + } + finally { + result.set(COMPILE_SERVER_BUILD_STATUS.get(compileContext)); + if (!myProject.isDisposed()) { + CompilerCacheManager.getInstance(myProject).flushCaches(); } } }, null); @@ -383,86 +381,78 @@ public class CompileDriver { final CompileContextImpl compileContext = new CompileContextImpl(myProject, compileTask, scope, !isRebuild && !forceCompile, isRebuild); - final Runnable compileWork = new Runnable() { - public void run() { - final ProgressIndicator indicator = compileContext.getProgressIndicator(); - if (indicator.isCanceled() || myProject.isDisposed()) { - if (callback != null) { - callback.finished(true, 0, 0, compileContext); - } + final Runnable compileWork = () -> { + final ProgressIndicator indicator = compileContext.getProgressIndicator(); + if (indicator.isCanceled() || myProject.isDisposed()) { + if (callback != null) { + callback.finished(true, 0, 0, compileContext); + } + return; + } + try { + LOG.info("COMPILATION STARTED (BUILD PROCESS)"); + if (message != null) { + compileContext.addMessage(message); + } + if (isRebuild) { + CompilerUtil.runInContext(compileContext, "Clearing build system data...", + (ThrowableRunnable)() -> CompilerCacheManager.getInstance(myProject).clearCaches(compileContext)); + } + final boolean beforeTasksOk = executeCompileTasks(compileContext, true); + + final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); + if (!beforeTasksOk || errorCount > 0) { + COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0 ? ExitStatus.ERRORS : ExitStatus.CANCELLED); return; } - try { - LOG.info("COMPILATION STARTED (BUILD PROCESS)"); - if (message != null) { - compileContext.addMessage(message); - } - if (isRebuild) { - CompilerUtil.runInContext(compileContext, "Clearing build system data...", new ThrowableRunnable() { - @Override - public void run() throws Throwable { - CompilerCacheManager.getInstance(myProject).clearCaches(compileContext); - } - }); - } - final boolean beforeTasksOk = executeCompileTasks(compileContext, true); - final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); - if (!beforeTasksOk || errorCount > 0) { - COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0 ? ExitStatus.ERRORS : ExitStatus.CANCELLED); - return; - } - - final TaskFuture future = compileInExternalProcess(compileContext, false); - if (future != null) { - while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) { - if (indicator.isCanceled()) { - future.cancel(false); - } - } - if (!executeCompileTasks(compileContext, false)) { - COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED); - } - if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS); + final TaskFuture future = compileInExternalProcess(compileContext, false); + if (future != null) { + while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) { + if (indicator.isCanceled()) { + future.cancel(false); } } + if (!executeCompileTasks(compileContext, false)) { + COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED); + } + if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { + COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS); + } } - catch (ProcessCanceledException ignored) { - compileContext.putUserDataIfAbsent(COMPILE_SERVER_BUILD_STATUS, ExitStatus.CANCELLED); - } - catch (Throwable e) { - LOG.error(e); // todo - } - finally { - CompilerCacheManager.getInstance(myProject).flushCaches(); + } + catch (ProcessCanceledException ignored) { + compileContext.putUserDataIfAbsent(COMPILE_SERVER_BUILD_STATUS, ExitStatus.CANCELLED); + } + catch (Throwable e) { + LOG.error(e); // todo + } + finally { + CompilerCacheManager.getInstance(myProject).flushCaches(); - final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext)); - CompilerUtil.logDuration( - "\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + - compileContext.getMessageCount(CompilerMessageCategory.ERROR) + - "; warnings: " + - compileContext.getMessageCount(CompilerMessageCategory.WARNING), - duration - ); - } + final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext)); + CompilerUtil.logDuration( + "\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + + "; warnings: " + + compileContext.getMessageCount(CompilerMessageCategory.WARNING), + duration + ); } }; - compileTask.start(compileWork, new Runnable() { - public void run() { - if (isRebuild) { - final int rv = Messages.showOkCancelDialog( - myProject, "You are about to rebuild the whole project.\nRun 'Make Project' instead?", "Confirm Project Rebuild", - "Make", "Rebuild", Messages.getQuestionIcon() - ); - if (rv == Messages.OK /*yes, please, do run make*/) { - startup(scope, false, false, callback, null); - return; - } + compileTask.start(compileWork, () -> { + if (isRebuild) { + final int rv = Messages.showOkCancelDialog( + myProject, "You are about to rebuild the whole project.\nRun 'Make Project' instead?", "Confirm Project Rebuild", + "Make", "Rebuild", Messages.getQuestionIcon() + ); + if (rv == Messages.OK /*yes, please, do run make*/) { + startup(scope, false, false, callback, null); + return; } - startup(scope, isRebuild, forceCompile, callback, message); } + startup(scope, isRebuild, forceCompile, callback, message); }); } @@ -492,48 +482,41 @@ public class CompileDriver { } } } - SwingUtilities.invokeLater(new Runnable() { - public void run() { - int errorCount = 0; - int warningCount = 0; - try { - errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); - warningCount = compileContext.getMessageCount(CompilerMessageCategory.WARNING); - } - finally { - if (callback != null) { - callback.finished(_status == ExitStatus.CANCELLED, errorCount, warningCount, compileContext); - } - } - - if (!myProject.isDisposed()) { - final String statusMessage = createStatusMessage(_status, warningCount, errorCount, duration); - final MessageType messageType = errorCount > 0 ? MessageType.ERROR : warningCount > 0 ? MessageType.WARNING : MessageType.INFO; - if (duration > ONE_MINUTE_MS && CompilerWorkspaceConfiguration.getInstance(myProject).DISPLAY_NOTIFICATION_POPUP) { - ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, messageType, statusMessage); - } - - final String wrappedMessage = _status != ExitStatus.UP_TO_DATE? "" + statusMessage + "" : statusMessage; - final Notification notification = CompilerManager.NOTIFICATION_GROUP.createNotification( - "", wrappedMessage, - messageType.toNotificationType(), - new MessagesActivationListener(compileContext) - ).setImportant(false); - compileContext.getBuildSession().registerCloseAction(new Runnable() { - @Override - public void run() { - notification.expire(); - } - }); - notification.notify(myProject); - - if (_status != ExitStatus.UP_TO_DATE && compileContext.getMessageCount(null) > 0) { - final String msg = DateFormatUtil.formatDateTime(new Date()) + " - " + statusMessage; - compileContext.addMessage(CompilerMessageCategory.INFORMATION, msg, null, -1, -1); - } - } - + SwingUtilities.invokeLater(() -> { + int errorCount = 0; + int warningCount = 0; + try { + errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); + warningCount = compileContext.getMessageCount(CompilerMessageCategory.WARNING); } + finally { + if (callback != null) { + callback.finished(_status == ExitStatus.CANCELLED, errorCount, warningCount, compileContext); + } + } + + if (!myProject.isDisposed()) { + final String statusMessage = createStatusMessage(_status, warningCount, errorCount, duration); + final MessageType messageType = errorCount > 0 ? MessageType.ERROR : warningCount > 0 ? MessageType.WARNING : MessageType.INFO; + if (duration > ONE_MINUTE_MS && CompilerWorkspaceConfiguration.getInstance(myProject).DISPLAY_NOTIFICATION_POPUP) { + ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, messageType, statusMessage); + } + + final String wrappedMessage = _status != ExitStatus.UP_TO_DATE? "" + statusMessage + "" : statusMessage; + final Notification notification = CompilerManager.NOTIFICATION_GROUP.createNotification( + "", wrappedMessage, + messageType.toNotificationType(), + new MessagesActivationListener(compileContext) + ).setImportant(false); + compileContext.getBuildSession().registerCloseAction(() -> notification.expire()); + notification.notify(myProject); + + if (_status != ExitStatus.UP_TO_DATE && compileContext.getMessageCount(null) > 0) { + final String msg = DateFormatUtil.formatDateTime(new Date()) + " - " + statusMessage; + compileContext.addMessage(CompilerMessageCategory.INFORMATION, msg, null, -1, -1); + } + } + }); return duration; } @@ -589,18 +572,16 @@ public class CompileDriver { FileDocumentManager.getInstance().saveAllDocuments(); - progressManagerTask.start(new Runnable() { - public void run() { - try { - task.execute(compileContext); - } - catch (ProcessCanceledException ex) { - // suppressed - } - finally { - if (onTaskFinished != null) { - onTaskFinished.run(); - } + progressManagerTask.start(() -> { + try { + task.execute(compileContext); + } + catch (ProcessCanceledException ex) { + // suppressed + } + finally { + if (onTaskFinished != null) { + onTaskFinished.run(); } } }, null); @@ -633,11 +614,7 @@ public class CompileDriver { statusBar.setInfo(""); } if (progressIndicator instanceof CompilerTask) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ((CompilerTask)progressIndicator).showCompilerContent(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ((CompilerTask)progressIndicator).showCompilerContent()); } } return true; diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompilerErrorTreeView.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompilerErrorTreeView.java index 132c97dc878e..49ce3ffd6755 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompilerErrorTreeView.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompilerErrorTreeView.java @@ -80,20 +80,14 @@ public class CompilerErrorTreeView extends NewErrorTreeViewPanel { final OpenFileDescriptor navigatable = (OpenFileDescriptor)messageElement.getNavigatable(); final PsiFile file = PsiManager.getInstance(project).findFile(navigatable.getFile()); assert file != null; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - suppressInspectionFix.invoke(project, file.findElementAt(navigatable.getOffset())); - } - catch (IncorrectOperationException e1) { - LOG.error(e1); - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + suppressInspectionFix.invoke(project, file.findElementAt(navigatable.getOffset())); } - }, suppressInspectionFix.getText(), null); + catch (IncorrectOperationException e1) { + LOG.error(e1); + } + }), suppressInspectionFix.getText(), null); } @Override diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java b/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java index fd7d37a0539f..129f9d9b79bc 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java @@ -63,25 +63,23 @@ public class FileProcessingCompilerAdapterTask implements CompileTask { final Ref ex = new Ref(null); final FileProcessingCompilerStateCache cache = getCache(context); final boolean isMake = context.isMake(); - DumbService.getInstance(project).runReadActionInSmartMode(new Runnable() { - public void run() { - try { - for (FileProcessingCompiler.ProcessingItem item : items) { - final VirtualFile file = item.getFile(); - final String url = file.getUrl(); - if (isMake && cache.getTimestamp(url) == file.getTimeStamp()) { - final ValidityState state = cache.getExtState(url); - final ValidityState itemState = item.getValidityState(); - if (state != null ? state.equalsTo(itemState) : itemState == null) { - continue; - } + DumbService.getInstance(project).runReadActionInSmartMode(() -> { + try { + for (FileProcessingCompiler.ProcessingItem item : items) { + final VirtualFile file = item.getFile(); + final String url = file.getUrl(); + if (isMake && cache.getTimestamp(url) == file.getTimeStamp()) { + final ValidityState state = cache.getExtState(url); + final ValidityState itemState = item.getValidityState(); + if (state != null ? state.equalsTo(itemState) : itemState == null) { + continue; } - toProcess.add(item); } + toProcess.add(item); } - catch (IOException e) { - ex.set(e); - } + } + catch (IOException e) { + ex.set(e); } }); @@ -100,24 +98,19 @@ public class FileProcessingCompilerAdapterTask implements CompileTask { return true; } - CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable() { - public void run() throws IOException{ - final List vFiles = new ArrayList(processed.length); - final List> toUpdate = new ArrayList>(processed.length); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (FileProcessingCompiler.ProcessingItem item : processed) { - vFiles.add(item.getFile()); - toUpdate.add(Pair.create(item, item.getValidityState())); - } - } - }); - LocalFileSystem.getInstance().refreshFiles(vFiles); - - for (Pair pair : toUpdate) { - cache.update(pair.getFirst().getFile(), pair.getSecond()); + CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), () -> { + final List vFiles = new ArrayList(processed.length); + final List> toUpdate = new ArrayList>(processed.length); + ApplicationManager.getApplication().runReadAction(() -> { + for (FileProcessingCompiler.ProcessingItem item : processed) { + vFiles.add(item.getFile()); + toUpdate.add(Pair.create(item, item.getValidityState())); } + }); + LocalFileSystem.getInstance().refreshFiles(vFiles); + + for (Pair pair : toUpdate) { + cache.update(pair.getFirst().getFile(), pair.getSecond()); } }); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/FileSetCompileScope.java b/java/compiler/impl/src/com/intellij/compiler/impl/FileSetCompileScope.java index 4a10ad300297..9c869c3ffe26 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/FileSetCompileScope.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/FileSetCompileScope.java @@ -41,12 +41,10 @@ public class FileSetCompileScope extends ExportableUserDataHolderBase implements public FileSetCompileScope(final Collection files, Module[] modules) { myAffectedModules = modules; ApplicationManager.getApplication().runReadAction( - new Runnable() { - public void run() { - for (VirtualFile file : files) { - assert file != null; - addFile(file); - } + () -> { + for (VirtualFile file : files) { + assert file != null; + addFile(file); } } ); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/GenericCompilerRunner.java b/java/compiler/impl/src/com/intellij/compiler/impl/GenericCompilerRunner.java index 5f4ff24b6c05..d691fa2d31e1 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/GenericCompilerRunner.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/GenericCompilerRunner.java @@ -125,17 +125,14 @@ public class GenericCompilerRunner { } final List keys = new ArrayList(); - CompilerUtil.runInContext(myContext, "Processing obsolete targets...", new ThrowableRunnable() { - @Override - public void run() throws IOException { - cache.processSources(id, new CommonProcessors.CollectProcessor(keys)); - List> obsoleteSources = new ArrayList>(); - for (Key key : keys) { - final GenericCompilerCache.PersistentStateData state = cache.getState(id, key); - obsoleteSources.add(new GenericCompilerCacheState(key, state.mySourceState, state.myOutputState)); - } - instance.processObsoleteTarget(target, obsoleteSources); + CompilerUtil.runInContext(myContext, "Processing obsolete targets...", () -> { + cache.processSources(id, new CommonProcessors.CollectProcessor(keys)); + List> obsoleteSources = new ArrayList>(); + for (Key key : keys) { + final GenericCompilerCache.PersistentStateData state = cache.getState(id, key); + obsoleteSources.add(new GenericCompilerCacheState(key, state.mySourceState, state.myOutputState)); } + instance.processObsoleteTarget(target, obsoleteSources); }); checkForErrorsOrCanceled(); for (Key key : keys) { @@ -186,28 +183,25 @@ public class GenericCompilerRunner { final THashSet keySet = new THashSet(new SourceItemHashingStrategy(compiler)); final Ref exception = Ref.create(null); final Map sourceStates = new HashMap(); - DumbService.getInstance(myProject).runReadActionInSmartMode(new Runnable() { - @Override - public void run() { - try { - for (Item item : items) { - final Key key = item.getKey(); - keySet.add(key); - if (item.isExcluded()) continue; + DumbService.getInstance(myProject).runReadActionInSmartMode(() -> { + try { + for (Item item : items) { + final Key key = item.getKey(); + keySet.add(key); + if (item.isExcluded()) continue; - final GenericCompilerCache.PersistentStateData data = cache.getState(targetId, key); - SourceState sourceState = data != null ? data.mySourceState : null; - final OutputState outputState = data != null ? data.myOutputState : null; - if (myForceCompile || sourceState == null || !item.isSourceUpToDate(sourceState) - || outputState == null || !item.isOutputUpToDate(outputState)) { - sourceStates.put(item, item.computeSourceState()); - toProcess.add(new GenericCompilerProcessingItem(item, sourceState, outputState)); - } + final GenericCompilerCache.PersistentStateData data = cache.getState(targetId, key); + SourceState sourceState = data != null ? data.mySourceState : null; + final OutputState outputState = data != null ? data.myOutputState : null; + if (myForceCompile || sourceState == null || !item.isSourceUpToDate(sourceState) + || outputState == null || !item.isOutputUpToDate(outputState)) { + sourceStates.put(item, item.computeSourceState()); + toProcess.add(new GenericCompilerProcessingItem(item, sourceState, outputState)); } } - catch (IOException e) { - exception.set(e); - } + } + catch (IOException e) { + exception.set(e); } }); if (!exception.isNull()) { @@ -215,14 +209,11 @@ public class GenericCompilerRunner { } final List toRemove = new ArrayList(); - cache.processSources(targetId, new Processor() { - @Override - public boolean process(Key key) { - if (!keySet.contains(key)) { - toRemove.add(key); - } - return true; + cache.processSources(targetId, key -> { + if (!keySet.contains(key)) { + toRemove.add(key); } + return true; }); if (LOG.isDebugEnabled()) { @@ -270,39 +261,36 @@ public class GenericCompilerRunner { }); checkForErrorsOrCanceled(); - CompilerUtil.runInContext(myContext, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable() { - @Override - public void run() throws IOException { - for (Key key : toRemove) { - cache.remove(targetId, key); - } - CompilerUtil.refreshIOFiles(filesToRefresh); - CompilerUtil.refreshIODirectories(dirsToRefresh); - if (LOG.isDebugEnabled()) { - LOG.debug("refreshed " + filesToRefresh.size() + " files and " + dirsToRefresh.size() + " dirs"); - for (int i = 0; i < getItemsCountToShowInLog(filesToRefresh.size()); i++) { - LOG.debug("file: " + filesToRefresh.get(i)); - } - for (int i = 0; i < getItemsCountToShowInLog(dirsToRefresh.size()); i++) { - LOG.debug("dir: " + dirsToRefresh.get(i)); - } - } - - final RunResult runResult = new ReadAction() { - protected void run(@NotNull final Result result) throws Throwable { - for (Item item : processedItems) { - SourceState sourceState = sourceStates.get(item); - if (sourceState == null) { - sourceState = item.computeSourceState(); - } - cache.putState(targetId, item.getKey(), sourceState, item.computeOutputState()); - } - } - }.executeSilently(); - Throwable throwable = runResult.getThrowable(); - if (throwable instanceof IOException) throw (IOException) throwable; - else if (throwable != null) throw new RuntimeException(throwable); + CompilerUtil.runInContext(myContext, CompilerBundle.message("progress.updating.caches"), () -> { + for (Key key : toRemove) { + cache.remove(targetId, key); } + CompilerUtil.refreshIOFiles(filesToRefresh); + CompilerUtil.refreshIODirectories(dirsToRefresh); + if (LOG.isDebugEnabled()) { + LOG.debug("refreshed " + filesToRefresh.size() + " files and " + dirsToRefresh.size() + " dirs"); + for (int i = 0; i < getItemsCountToShowInLog(filesToRefresh.size()); i++) { + LOG.debug("file: " + filesToRefresh.get(i)); + } + for (int i = 0; i < getItemsCountToShowInLog(dirsToRefresh.size()); i++) { + LOG.debug("dir: " + dirsToRefresh.get(i)); + } + } + + final RunResult runResult = new ReadAction() { + protected void run(@NotNull final Result result) throws Throwable { + for (Item item : processedItems) { + SourceState sourceState = sourceStates.get(item); + if (sourceState == null) { + sourceState = item.computeSourceState(); + } + cache.putState(targetId, item.getKey(), sourceState, item.computeOutputState()); + } + } + }.executeSilently(); + Throwable throwable = runResult.getThrowable(); + if (throwable instanceof IOException) throw (IOException) throwable; + else if (throwable != null) throw new RuntimeException(throwable); }); return true; diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java index 2a8086db8e88..3e6c5f64b6cb 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java @@ -65,36 +65,30 @@ public class ProblemsViewImpl extends ProblemsView{ Disposer.dispose(myPanel); } }); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) { - return; - } - final ToolWindow tw = wm.registerToolWindow(PROBLEMS_TOOLWINDOW_ID, false, ToolWindowAnchor.BOTTOM, project, true); - final Content content = ContentFactory.SERVICE.getInstance().createContent(myPanel, "", false); - // todo: setup content? - tw.getContentManager().addContent(content); - Disposer.register(project, new Disposable() { - @Override - public void dispose() { - tw.getContentManager().removeAllContents(true); - } - }); - updateIcon(); + UIUtil.invokeLaterIfNeeded(() -> { + if (project.isDisposed()) { + return; } + final ToolWindow tw = wm.registerToolWindow(PROBLEMS_TOOLWINDOW_ID, false, ToolWindowAnchor.BOTTOM, project, true); + final Content content = ContentFactory.SERVICE.getInstance().createContent(myPanel, "", false); + // todo: setup content? + tw.getContentManager().addContent(content); + Disposer.register(project, new Disposable() { + @Override + public void dispose() { + tw.getContentManager().removeAllContents(true); + } + }); + updateIcon(); }); } @Override public void clearOldMessages(@Nullable final CompileScope scope, @NotNull final UUID currentSessionId) { - myViewUpdater.execute(new Runnable() { - @Override - public void run() { - cleanupChildrenRecursively(myPanel.getErrorViewStructure().getRootElement(), scope, currentSessionId); - updateIcon(); - myPanel.reload(); - } + myViewUpdater.execute(() -> { + cleanupChildrenRecursively(myPanel.getErrorViewStructure().getRootElement(), scope, currentSessionId); + updateIcon(); + myPanel.reload(); }); } @@ -130,35 +124,29 @@ public class ProblemsViewImpl extends ProblemsView{ @Nullable final Navigatable navigatable, @Nullable final String exportTextPrefix, @Nullable final String rendererTextPrefix, @Nullable final UUID sessionId) { - myViewUpdater.execute(new Runnable() { - @Override - public void run() { - final ErrorViewStructure structure = myPanel.getErrorViewStructure(); - final GroupingElement group = structure.lookupGroupingElement(groupName); - if (group != null && sessionId != null && !sessionId.equals(group.getData())) { - structure.removeElement(group); - } - if (navigatable != null) { - myPanel.addMessage(type, text, groupName, navigatable, exportTextPrefix, rendererTextPrefix, sessionId); - } - else { - myPanel.addMessage(type, text, null, -1, -1, sessionId); - } - updateIcon(); + myViewUpdater.execute(() -> { + final ErrorViewStructure structure = myPanel.getErrorViewStructure(); + final GroupingElement group = structure.lookupGroupingElement(groupName); + if (group != null && sessionId != null && !sessionId.equals(group.getData())) { + structure.removeElement(group); } + if (navigatable != null) { + myPanel.addMessage(type, text, groupName, navigatable, exportTextPrefix, rendererTextPrefix, sessionId); + } + else { + myPanel.addMessage(type, text, null, -1, -1, sessionId); + } + updateIcon(); }); } private void updateIcon() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed()) { - final ToolWindow tw = ToolWindowManager.getInstance(myProject).getToolWindow(PROBLEMS_TOOLWINDOW_ID); - if (tw != null) { - final boolean active = myPanel.getErrorViewStructure().hasMessages(ALL_MESSAGE_KINDS); - tw.setIcon(active ? myActiveIcon : myPassiveIcon); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (!myProject.isDisposed()) { + final ToolWindow tw = ToolWindowManager.getInstance(myProject).getToolWindow(PROBLEMS_TOOLWINDOW_ID); + if (tw != null) { + final boolean active = myPanel.getErrorViewStructure().hasMessages(ALL_MESSAGE_KINDS); + tw.setIcon(active ? myActiveIcon : myPassiveIcon); } } }); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java index 020b9af3ac24..1f5b07692e95 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java @@ -201,18 +201,14 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { } - private static final Function, Void> NOTIFY_CHANGED = new Function, Void>() { - public Void fun(Collection files) { - notifyFilesChanged(files); - return null; - } + private static final Function, Void> NOTIFY_CHANGED = files -> { + notifyFilesChanged(files); + return null; }; - private static final Function, Void> NOTIFY_DELETED = new Function, Void>() { - public Void fun(Collection files) { - notifyFilesDeleted(files); - return null; - } + private static final Function, Void> NOTIFY_DELETED = files -> { + notifyFilesDeleted(files); + return null; }; private static void collectPathsAndNotify(final VirtualFile file, final Function, Void> notification) { diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerCache.java b/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerCache.java index 4db878623df7..fe7c6a5d0af8 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerCache.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerCache.java @@ -88,12 +88,7 @@ public class GenericCompilerCache { } public void processSources(final int targetId, final Processor processor) throws IOException { - myPersistentMap.processKeysWithExistingMapping(new Processor>() { - @Override - public boolean process(KeyAndTargetData data) { - return targetId == data.myTarget ? processor.process(data.myKey) : true; - } - }); + myPersistentMap.processKeysWithExistingMapping(data -> targetId == data.myTarget ? processor.process(data.myKey) : true); } public void putState(int targetId, @NotNull Key key, @NotNull SourceState sourceState, @NotNull OutputState outputState) throws IOException { diff --git a/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java b/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java index 61ad719aab1a..494097aba69e 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java @@ -92,34 +92,31 @@ public class AnnotationProcessorsPanel extends JPanel { final JBList list = new JBList(profiles); final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle("Move to") - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof ProcessorConfigProfile) { - final ProcessorConfigProfile chosenProfile = (ProcessorConfigProfile)value; - final Module toSelect = (Module)node.getUserObject(); - if (selectedNodes != null) { - for (TreePath selectedNode : selectedNodes) { - final Object node = selectedNode.getLastPathComponent(); - if (node instanceof MyModuleNode) { - final Module module = (Module)((MyModuleNode)node).getUserObject(); - if (nodeProfile != myDefaultProfile) { - nodeProfile.removeModuleName(module.getName()); - } - if (chosenProfile != myDefaultProfile) { - chosenProfile.addModuleName(module.getName()); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof ProcessorConfigProfile) { + final ProcessorConfigProfile chosenProfile = (ProcessorConfigProfile)value; + final Module toSelect = (Module)node.getUserObject(); + if (selectedNodes != null) { + for (TreePath selectedNode : selectedNodes) { + final Object node1 = selectedNode.getLastPathComponent(); + if (node1 instanceof MyModuleNode) { + final Module module = (Module)((MyModuleNode)node1).getUserObject(); + if (nodeProfile != myDefaultProfile) { + nodeProfile.removeModuleName(module.getName()); + } + if (chosenProfile != myDefaultProfile) { + chosenProfile.addModuleName(module.getName()); } } } + } - final RootNode root = (RootNode)myTree.getModel().getRoot(); - root.sync(); - final DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(root, toSelect); - if (node != null) { - TreeUtil.selectNode(myTree, node); - } + final RootNode root = (RootNode)myTree.getModel().getRoot(); + root.sync(); + final DefaultMutableTreeNode node1 = TreeUtil.findNodeWithObject(root, toSelect); + if (node1 != null) { + TreeUtil.selectNode(myTree, node1); } } }) diff --git a/java/compiler/impl/src/com/intellij/compiler/options/CompilerConfigurable.java b/java/compiler/impl/src/com/intellij/compiler/options/CompilerConfigurable.java index 3cb2305d6a66..601003bea3e6 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/CompilerConfigurable.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/CompilerConfigurable.java @@ -89,13 +89,8 @@ public class CompilerConfigurable implements SearchableConfigurable.Parent, Conf public Configurable[] getConfigurables() { if (myKids == null) { final CompilerSettingsFactory[] factories = Extensions.getExtensions(CompilerSettingsFactory.EP_NAME, myProject); - myKids = ContainerUtil.mapNotNull(factories, new NullableFunction() { - @Nullable - @Override - public Configurable fun(CompilerSettingsFactory factory) { - return factory.create(myProject); - } - }, new Configurable[0]); + myKids = ContainerUtil.mapNotNull(factories, + (NullableFunction)factory -> factory.create(myProject), new Configurable[0]); } return myKids; diff --git a/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java b/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java index 8ad281bf1edd..733ef9d32f50 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java @@ -371,12 +371,7 @@ public class ProcessorProfilePanel extends JPanel { for (Map.Entry entry : options.entrySet()) { myRows.add(new KeyValuePair(entry.getKey(), entry.getValue())); } - Collections.sort(myRows, new Comparator() { - @Override - public int compare(KeyValuePair o1, KeyValuePair o2) { - return o1.key.compareToIgnoreCase(o2.key); - } - }); + Collections.sort(myRows, (o1, o2) -> o1.key.compareToIgnoreCase(o2.key)); fireTableRowsInserted(0, options.size()-1); } } @@ -482,11 +477,7 @@ public class ProcessorProfilePanel extends JPanel { for (String processor : processors) { myRows.add(processor); } - Collections.sort(myRows, new Comparator() { - public int compare(String o1, String o2) { - return o1.compareToIgnoreCase(o2); - } - }); + Collections.sort(myRows, (o1, o2) -> o1.compareToIgnoreCase(o2)); fireTableRowsInserted(0, processors.size()-1); } } diff --git a/java/compiler/impl/src/com/intellij/compiler/options/TargetOptionsComponent.java b/java/compiler/impl/src/com/intellij/compiler/options/TargetOptionsComponent.java index 9cf351373618..875f3d1f532a 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/TargetOptionsComponent.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/TargetOptionsComponent.java @@ -132,12 +132,7 @@ public class TargetOptionsComponent extends JPanel { it.remove(); } } - Collections.sort(items, new Comparator() { - @Override - public int compare(Module o1, Module o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(items, (o1, o2) -> o1.getName().compareTo(o2.getName())); final ChooseModulesDialog chooser = new ChooseModulesDialog(this, items, "Choose module"); chooser.show(); final List elements = chooser.getChosenElements(); @@ -230,12 +225,7 @@ public class TargetOptionsComponent extends JPanel { } private void sorItems() { - Collections.sort(myItems, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o1.module.getName().compareTo(o2.module.getName()); - } - }); + Collections.sort(myItems, (o1, o2) -> o1.module.getName().compareTo(o2.module.getName())); } public List getItems() { diff --git a/java/compiler/impl/src/com/intellij/compiler/options/ValidationConfigurable.java b/java/compiler/impl/src/com/intellij/compiler/options/ValidationConfigurable.java index dd9d762fbcb4..b91f04ff96f0 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/ValidationConfigurable.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/ValidationConfigurable.java @@ -124,11 +124,7 @@ public class ValidationConfigurable implements SearchableConfigurable, Configura public void reset() { myValidateBox.setSelected(myConfiguration.VALIDATE_ON_BUILD); final List validators = getValidators(); - Collections.sort(validators, new Comparator() { - public int compare(final Compiler o1, final Compiler o2) { - return o1.getDescription().compareTo(o2.getDescription()); - } - }); + Collections.sort(validators, (o1, o2) -> o1.getDescription().compareTo(o2.getDescription())); myValidators.setElements(validators, false); myValidators.markElements(getMarkedValidators()); myExcludedConfigurable.reset(); @@ -136,11 +132,7 @@ public class ValidationConfigurable implements SearchableConfigurable, Configura private List getMarkedValidators() { final List validators = getValidators(); - return ContainerUtil.mapNotNull(validators, new NullableFunction() { - public Compiler fun(final Compiler validator) { - return myConfiguration.isSelected(validator) ? validator : null; - } - }); + return ContainerUtil.mapNotNull(validators, (NullableFunction)validator -> myConfiguration.isSelected(validator) ? validator : null); } private List getValidators() { diff --git a/java/compiler/impl/src/com/intellij/compiler/progress/CompilerTask.java b/java/compiler/impl/src/com/intellij/compiler/progress/CompilerTask.java index 5175a580bea4..36340d814c18 100644 --- a/java/compiler/impl/src/com/intellij/compiler/progress/CompilerTask.java +++ b/java/compiler/impl/src/com/intellij/compiler/progress/CompilerTask.java @@ -218,19 +218,16 @@ public class CompilerTask extends Task.Backgroundable { return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final Project project = myProject; - if (project == null || project.isDisposed()) { - return; - } - synchronized (myMessageViewLock) { - // clear messages from the previous compilation - if (myErrorTreeView == null) { - // if message view != null, the contents has already been cleared - removeAllContents(project, null); - } + ApplicationManager.getApplication().invokeLater(() -> { + final Project project = myProject; + if (project == null || project.isDisposed()) { + return; + } + synchronized (myMessageViewLock) { + // clear messages from the previous compilation + if (myErrorTreeView == null) { + // if message view != null, the contents has already been cleared + removeAllContents(project, null); } } }); @@ -261,16 +258,13 @@ public class CompilerTask extends Task.Backgroundable { private void selectFirstMessage() { if (!isHeadlessMode()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myProject != null && myProject.isDisposed()) { - return; - } - synchronized (myMessageViewLock) { - if (myErrorTreeView != null) { - myErrorTreeView.selectFirstMessage(); - } + SwingUtilities.invokeLater(() -> { + if (myProject != null && myProject.isDisposed()) { + return; + } + synchronized (myMessageViewLock) { + if (myErrorTreeView != null) { + myErrorTreeView.selectFirstMessage(); } } }); @@ -278,22 +272,19 @@ public class CompilerTask extends Task.Backgroundable { } private void stopAppIconProgress() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myProject != null && myProject.isDisposed()) { - return; + UIUtil.invokeLaterIfNeeded(() -> { + if (myProject != null && myProject.isDisposed()) { + return; + } + final AppIcon appIcon = AppIcon.getInstance(); + if (appIcon.hideProgress(myProject, APP_ICON_ID)) { + if (myErrorCount > 0) { + appIcon.setErrorBadge(myProject, String.valueOf(myErrorCount)); + appIcon.requestAttention(myProject, true); } - final AppIcon appIcon = AppIcon.getInstance(); - if (appIcon.hideProgress(myProject, APP_ICON_ID)) { - if (myErrorCount > 0) { - appIcon.setErrorBadge(myProject, String.valueOf(myErrorCount)); - appIcon.requestAttention(myProject, true); - } - else if (!myCompilationStartedAutomatically) { - appIcon.setOkBadge(myProject, true); - appIcon.requestAttention(myProject, false); - } + else if (!myCompilationStartedAutomatically) { + appIcon.setOkBadge(myProject, true); + appIcon.requestAttention(myProject, false); } } }); @@ -315,12 +306,8 @@ public class CompilerTask extends Task.Backgroundable { public void setFraction(final double fraction) { super.setFraction(fraction); updateProgressText(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - AppIcon.getInstance().setProgress(myProject, APP_ICON_ID, AppIconScheme.Progress.BUILD, fraction, true); - } - }); + UIUtil.invokeLaterIfNeeded( + () -> AppIcon.getInstance().setProgress(myProject, APP_ICON_ID, AppIconScheme.Progress.BUILD, fraction, true)); } @Override @@ -355,13 +342,10 @@ public class CompilerTask extends Task.Backgroundable { else { final Window window = getWindow(); final ModalityState modalityState = window != null ? ModalityState.stateForComponent(window) : ModalityState.NON_MODAL; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myProject != null && !myProject.isDisposed()) { - openMessageView(); - doAddMessage(message); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject != null && !myProject.isDisposed()) { + openMessageView(); + doAddMessage(message); } }, modalityState); } diff --git a/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java b/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java index 8ba9b4d7b6e6..6809ed50bec3 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/AutoMakeMessageHandler.java @@ -82,15 +82,12 @@ class AutoMakeMessageHandler extends DefaultMessageHandler { final int errors = myContext.getMessageCount(CompilerMessageCategory.ERROR); final int warnings = myContext.getMessageCount(CompilerMessageCategory.WARNING); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) { - return; - } - final CompilationStatusListener publisher = myProject.getMessageBus().syncPublisher(CompilerTopics.COMPILATION_STATUS); - publisher.automakeCompilationFinished(errors, warnings, myContext); + SwingUtilities.invokeLater(() -> { + if (myProject.isDisposed()) { + return; } + final CompilationStatusListener publisher = myProject.getMessageBus().syncPublisher(CompilerTopics.COMPILATION_STATUS); + publisher.automakeCompilationFinished(errors, warnings, myContext); }); return; diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 7121706ff5fe..0350af9472bd 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -145,19 +145,9 @@ public class BuildManager implements Disposable { private static final String IPR_EXTENSION = ".ipr"; private static final String IDEA_PROJECT_DIR_PATTERN = "/.idea/"; private static final Function PATH_FILTER = - SystemInfo.isFileSystemCaseSensitive? - new Function() { - @Override - public Boolean fun(String s) { - return !(s.contains(IDEA_PROJECT_DIR_PATTERN) || s.endsWith(IWS_EXTENSION) || s.endsWith(IPR_EXTENSION)); - } - } : - new Function() { - @Override - public Boolean fun(String s) { - return !(StringUtil.endsWithIgnoreCase(s, IWS_EXTENSION) || StringUtil.endsWithIgnoreCase(s, IPR_EXTENSION) || StringUtil.containsIgnoreCase(s, IDEA_PROJECT_DIR_PATTERN)); - } - }; + SystemInfo.isFileSystemCaseSensitive ? + (Function)s -> !(s.contains(IDEA_PROJECT_DIR_PATTERN) || s.endsWith(IWS_EXTENSION) || s.endsWith(IPR_EXTENSION)) : + (Function)s -> !(StringUtil.endsWithIgnoreCase(s, IWS_EXTENSION) || StringUtil.endsWithIgnoreCase(s, IPR_EXTENSION) || StringUtil.containsIgnoreCase(s, IDEA_PROJECT_DIR_PATTERN)); private final File mySystemDirectory; private final ProjectManager myProjectManager; @@ -202,39 +192,30 @@ public class BuildManager implements Disposable { } }; - private final Runnable myGCTask = new Runnable() { - // should be executed from the main queue with runCommand! - @Override - public void run() { - // todo: make customizable in UI? - final int unusedThresholdDays = Registry.intValue("compiler.build.data.unused.threshold", -1); - if (unusedThresholdDays <= 0) { - return; - } - final File buildSystemDir = getBuildSystemDirectory(); - final File[] dirs = buildSystemDir.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.isDirectory() && !TEMP_DIR_NAME.equals(pathname.getName()); - } - }); - if (dirs != null) { - final Date now = new Date(); - for (File buildDataProjectDir : dirs) { - final File usageFile = getUsageFile(buildDataProjectDir); - if (usageFile.exists()) { - final Pair usageData = readUsageFile(usageFile); - if (usageData != null) { - final File projectFile = usageData.second; - if (projectFile != null && !projectFile.exists() || DateFormatUtil.getDifferenceInDays(usageData.first, now) > unusedThresholdDays) { - LOG.info("Clearing project build data because the project does not exist or was not opened for more than " + unusedThresholdDays + " days: " + buildDataProjectDir.getPath()); - FileUtil.delete(buildDataProjectDir); - } + private final Runnable myGCTask = () -> { + // todo: make customizable in UI? + final int unusedThresholdDays = Registry.intValue("compiler.build.data.unused.threshold", -1); + if (unusedThresholdDays <= 0) { + return; + } + final File buildSystemDir = getBuildSystemDirectory(); + final File[] dirs = buildSystemDir.listFiles(pathname -> pathname.isDirectory() && !TEMP_DIR_NAME.equals(pathname.getName())); + if (dirs != null) { + final Date now = new Date(); + for (File buildDataProjectDir : dirs) { + final File usageFile = getUsageFile(buildDataProjectDir); + if (usageFile.exists()) { + final Pair usageData = readUsageFile(usageFile); + if (usageData != null) { + final File projectFile = usageData.second; + if (projectFile != null && !projectFile.exists() || DateFormatUtil.getDifferenceInDays(usageData.first, now) > unusedThresholdDays) { + LOG.info("Clearing project build data because the project does not exist or was not opened for more than " + unusedThresholdDays + " days: " + buildDataProjectDir.getPath()); + FileUtil.delete(buildDataProjectDir); } } - else { - updateUsageFile(null, buildDataProjectDir); // set usage stamp to start countdown - } + } + else { + updateUsageFile(null, buildDataProjectDir); // set usage stamp to start countdown } } } @@ -326,12 +307,7 @@ public class BuildManager implements Disposable { } }); - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - stopListening(); - } - }); + ShutDownTracker.getInstance().registerShutdownTask(() -> stopListening()); ScheduledFuture future = JobScheduler.getScheduler().scheduleWithFixedDelay((Runnable)() -> runCommand(myGCTask), 3, 180, TimeUnit.MINUTES); Disposer.register(this, () -> future.cancel(false)); @@ -373,47 +349,43 @@ public class BuildManager implements Disposable { private void doNotify(final Collection paths, final boolean notifyDeletion) { // ensure events processed in the order they arrived - runCommand(new Runnable() { - - @Override - public void run() { - final List filtered = new ArrayList(paths.size()); - for (File file : paths) { - final String path = FileUtil.toSystemIndependentName(file.getPath()); - if (PATH_FILTER.fun(path)) { - filtered.add(path); + runCommand(() -> { + final List filtered = new ArrayList(paths.size()); + for (File file : paths) { + final String path = FileUtil.toSystemIndependentName(file.getPath()); + if (PATH_FILTER.fun(path)) { + filtered.add(path); + } + } + if (filtered.isEmpty()) { + return; + } + synchronized (myProjectDataMap) { + //if (IS_UNIT_TEST_MODE) { + // if (notifyDeletion) { + // LOG.info("Registering deleted paths: " + filtered); + // } + // else { + // LOG.info("Registering changed paths: " + filtered); + // } + //} + for (Map.Entry entry : myProjectDataMap.entrySet()) { + final ProjectData data = entry.getValue(); + if (notifyDeletion) { + data.addDeleted(filtered); } - } - if (filtered.isEmpty()) { - return; - } - synchronized (myProjectDataMap) { - //if (IS_UNIT_TEST_MODE) { - // if (notifyDeletion) { - // LOG.info("Registering deleted paths: " + filtered); - // } - // else { - // LOG.info("Registering changed paths: " + filtered); - // } - //} - for (Map.Entry entry : myProjectDataMap.entrySet()) { - final ProjectData data = entry.getValue(); - if (notifyDeletion) { - data.addDeleted(filtered); - } - else { - data.addChanged(filtered); - } - final RequestFuture future = myBuildsInProgress.get(entry.getKey()); - if (future != null && !future.isCancelled() && !future.isDone()) { - final UUID sessionId = future.getRequestID(); - final Channel channel = myMessageDispatcher.getConnectedChannel(sessionId); - if (channel != null) { - final CmdlineRemoteProto.Message.ControllerMessage message = - CmdlineRemoteProto.Message.ControllerMessage.newBuilder().setType( - CmdlineRemoteProto.Message.ControllerMessage.Type.FS_EVENT).setFsEvent(data.createNextEvent()).build(); - channel.writeAndFlush(CmdlineProtoUtil.toMessage(sessionId, message)); - } + else { + data.addChanged(filtered); + } + final RequestFuture future = myBuildsInProgress.get(entry.getKey()); + if (future != null && !future.isCancelled() && !future.isDone()) { + final UUID sessionId = future.getRequestID(); + final Channel channel = myMessageDispatcher.getConnectedChannel(sessionId); + if (channel != null) { + final CmdlineRemoteProto.Message.ControllerMessage message = + CmdlineRemoteProto.Message.ControllerMessage.newBuilder().setType( + CmdlineRemoteProto.Message.ControllerMessage.Type.FS_EVENT).setFsEvent(data.createNextEvent()).build(); + channel.writeAndFlush(CmdlineProtoUtil.toMessage(sessionId, message)); } } } @@ -595,34 +567,28 @@ public class BuildManager implements Disposable { } private void cancelPreloadedBuilds(final String projectPath) { - runCommand(new Runnable() { - @Override - public void run() { - Pair, OSProcessHandler> pair = takePreloadedProcess(projectPath); - if (pair != null) { - final RequestFuture future = pair.first; - final OSProcessHandler processHandler = pair.second; - myMessageDispatcher.cancelSession(future.getRequestID()); - // waiting for preloaded process from project's task queue guarantees no build is started for this project - // until this one gracefully exits and closes all its storages - getProjectData(projectPath).taskQueue.submit(new Runnable() { - @Override - public void run() { - Throwable error = null; - try { - while (!processHandler.waitFor()) { - LOG.info("processHandler.waitFor() returned false for session " + future.getRequestID() + ", continue waiting"); - } - } - catch (Throwable e) { - error = e; - } - finally { - notifySessionTerminationIfNeeded(future.getRequestID(), error); - } + runCommand(() -> { + Pair, OSProcessHandler> pair = takePreloadedProcess(projectPath); + if (pair != null) { + final RequestFuture future = pair.first; + final OSProcessHandler processHandler = pair.second; + myMessageDispatcher.cancelSession(future.getRequestID()); + // waiting for preloaded process from project's task queue guarantees no build is started for this project + // until this one gracefully exits and closes all its storages + getProjectData(projectPath).taskQueue.submit(() -> { + Throwable error = null; + try { + while (!processHandler.waitFor()) { + LOG.info("processHandler.waitFor() returned false for session " + future.getRequestID() + ", continue waiting"); } - }); - } + } + catch (Throwable e) { + error = e; + } + finally { + notifySessionTerminationIfNeeded(future.getRequestID(), error); + } + }); } }); } @@ -664,181 +630,172 @@ public class BuildManager implements Disposable { final DelegateFuture _future = new DelegateFuture(); // by using the same queue that processes events we ensure that // the build will be aware of all events that have happened before this request - runCommand(new Runnable() { - @Override - public void run() { - final Pair, OSProcessHandler> preloaded = takePreloadedProcess(projectPath); - final RequestFuture preloadedFuture = preloaded != null? preloaded.first : null; - final boolean usingPreloadedProcess = preloadedFuture != null; + runCommand(() -> { + final Pair, OSProcessHandler> preloaded = takePreloadedProcess(projectPath); + final RequestFuture preloadedFuture = preloaded != null? preloaded.first : null; + final boolean usingPreloadedProcess = preloadedFuture != null; - final UUID sessionId; - if (usingPreloadedProcess) { - LOG.info("Using preloaded build process to compile " + projectPath); - sessionId = preloadedFuture.getRequestID(); - preloadedFuture.getMessageHandler().setDelegateHandler(handler); - } - else { - sessionId = UUID.randomUUID(); - } + final UUID sessionId; + if (usingPreloadedProcess) { + LOG.info("Using preloaded build process to compile " + projectPath); + sessionId = preloadedFuture.getRequestID(); + preloadedFuture.getMessageHandler().setDelegateHandler(handler); + } + else { + sessionId = UUID.randomUUID(); + } - final RequestFuture future = usingPreloadedProcess? preloadedFuture : new RequestFuture(handler, sessionId, new CancelBuildSessionAction()); - // futures we need to wait for: either just "future" or both "future" and "buildFuture" below - TaskFuture[] delegatesToWait = {future}; + final RequestFuture future = usingPreloadedProcess? preloadedFuture : new RequestFuture(handler, sessionId, new CancelBuildSessionAction()); + // futures we need to wait for: either just "future" or both "future" and "buildFuture" below + TaskFuture[] delegatesToWait = {future}; - if (!usingPreloadedProcess && (future.isCancelled() || project.isDisposed())) { - // in case of preloaded process the process was already running, so the handler will be notified upon process termination - handler.sessionTerminated(sessionId); - ((BasicFuture)future).setDone(); - } - else { - final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals = - CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.newBuilder().setGlobalOptionsPath(PathManager.getOptionsPath()) - .build(); - CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges; - final ExecutorService projectTaskQueue; - final boolean needRescan; - synchronized (myProjectDataMap) { - final ProjectData data = getProjectData(projectPath); - if (isRebuild) { - data.dropChanges(); - } - if (IS_UNIT_TEST_MODE) { - LOG.info("Scheduling build for " + - projectPath + - "; CHANGED: " + - new HashSet(convertToStringPaths(data.myChanged)) + - "; DELETED: " + - new HashSet(convertToStringPaths(data.myDeleted))); - } - needRescan = data.getAndResetRescanFlag(); - currentFSChanges = needRescan ? null : data.createNextEvent(); - projectTaskQueue = data.taskQueue; - } - - final CmdlineRemoteProto.Message.ControllerMessage params; + if (!usingPreloadedProcess && (future.isCancelled() || project.isDisposed())) { + // in case of preloaded process the process was already running, so the handler will be notified upon process termination + handler.sessionTerminated(sessionId); + ((BasicFuture)future).setDone(); + } + else { + final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals = + CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.newBuilder().setGlobalOptionsPath(PathManager.getOptionsPath()) + .build(); + CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges; + final ExecutorService projectTaskQueue; + final boolean needRescan; + synchronized (myProjectDataMap) { + final ProjectData data = getProjectData(projectPath); if (isRebuild) { - params = CmdlineProtoUtil.createBuildRequest(projectPath, scopes, Collections.emptyList(), userData, globals, null); + data.dropChanges(); } - else if (onlyCheckUpToDate) { - params = CmdlineProtoUtil.createUpToDateCheckRequest(projectPath, scopes, paths, userData, globals, currentFSChanges); - } - else { - params = CmdlineProtoUtil.createBuildRequest(projectPath, scopes, isMake ? Collections.emptyList() : paths, userData, globals, currentFSChanges); - } - if (!usingPreloadedProcess) { - myMessageDispatcher.registerBuildMessageHandler(future, params); + if (IS_UNIT_TEST_MODE) { + LOG.info("Scheduling build for " + + projectPath + + "; CHANGED: " + + new HashSet(convertToStringPaths(data.myChanged)) + + "; DELETED: " + + new HashSet(convertToStringPaths(data.myDeleted))); } + needRescan = data.getAndResetRescanFlag(); + currentFSChanges = needRescan ? null : data.createNextEvent(); + projectTaskQueue = data.taskQueue; + } - try { - Future buildFuture = projectTaskQueue.submit(new Runnable() { - @Override - public void run() { - Throwable execFailure = null; - try { - if (project.isDisposed()) { - if (usingPreloadedProcess) { - future.cancel(false); - } - else { - return; - } - } - myBuildsInProgress.put(projectPath, future); - final OSProcessHandler processHandler; - CharSequence errorsOnLaunch; - if (usingPreloadedProcess) { - final boolean paramsSent = myMessageDispatcher.sendBuildParameters(future.getRequestID(), params); - if (!paramsSent) { - myMessageDispatcher.cancelSession(future.getRequestID()); - } - processHandler = preloaded.second; - errorsOnLaunch = STDERR_OUTPUT.get(processHandler); - } - else { - if (isAutomake && needRescan) { - // if project state was cleared because of roots changed or this is the first compilation after project opening, - // ensure project model is saved on disk, so that automake sees the latest model state. - // For ordinary make all project, app settings and unsaved docs are always saved before build starts. - try { - TransactionGuard.getInstance().submitTransactionAndWait(project::save); - } - catch (Throwable e) { - LOG.info(e); - } - } + final CmdlineRemoteProto.Message.ControllerMessage params; + if (isRebuild) { + params = CmdlineProtoUtil.createBuildRequest(projectPath, scopes, Collections.emptyList(), userData, globals, null); + } + else if (onlyCheckUpToDate) { + params = CmdlineProtoUtil.createUpToDateCheckRequest(projectPath, scopes, paths, userData, globals, currentFSChanges); + } + else { + params = CmdlineProtoUtil.createBuildRequest(projectPath, scopes, isMake ? Collections.emptyList() : paths, userData, globals, currentFSChanges); + } + if (!usingPreloadedProcess) { + myMessageDispatcher.registerBuildMessageHandler(future, params); + } - processHandler = launchBuildProcess(project, myListenPort, sessionId, false); - errorsOnLaunch = new StringBuffer(); - processHandler.addProcessListener(new StdOutputCollector((StringBuffer)errorsOnLaunch)); - processHandler.startNotify(); - } - - Integer debugPort = processHandler.getUserData(COMPILER_PROCESS_DEBUG_PORT); - if (debugPort != null) { - String message = "Make: waiting for debugger connection on port " + debugPort; - messageHandler - .handleCompileMessage(sessionId, CmdlineProtoUtil.createCompileProgressMessageResponse(message).getCompileMessage()); - } - - while (!processHandler.waitFor()) { - LOG.info("processHandler.waitFor() returned false for session " + sessionId + ", continue waiting"); - } - - final int exitValue = processHandler.getProcess().exitValue(); - if (exitValue != 0) { - final StringBuilder msg = new StringBuilder(); - msg.append("Abnormal build process termination: "); - if (errorsOnLaunch != null && errorsOnLaunch.length() > 0) { - msg.append("\n").append(errorsOnLaunch); - if (StringUtil.contains(errorsOnLaunch, "java.lang.NoSuchMethodError")) { - msg.append( - "\nThe error may be caused by JARs in Java Extensions directory which conflicts with libraries used by the external build process.") - .append( - "\nTry adding -Djava.ext.dirs=\"\" argument to 'Build process VM options' in File | Settings | Build, Execution, Deployment | Compiler to fix the problem."); - } - } - else { - msg.append("unknown error"); - } - handler.handleFailure(sessionId, CmdlineProtoUtil.createFailure(msg.toString(), null)); - } + try { + Future buildFuture = projectTaskQueue.submit(() -> { + Throwable execFailure = null; + try { + if (project.isDisposed()) { + if (usingPreloadedProcess) { + future.cancel(false); } - catch (Throwable e) { - execFailure = e; - } - finally { - myBuildsInProgress.remove(projectPath); - notifySessionTerminationIfNeeded(sessionId, execFailure); - - if (isProcessPreloadingEnabled(project)) { - runCommand(new Runnable() { - @Override - public void run() { - if (!myPreloadedBuilds.containsKey(projectPath)) { - try { - final Future, OSProcessHandler>> preloadResult = - launchPreloadedBuildProcess(project, projectTaskQueue); - myPreloadedBuilds.put(projectPath, preloadResult); - } - catch (Throwable e) { - LOG.info("Error pre-loading build process for project " + projectPath, e); - } - } - } - }); - } + else { + return; } } - }); - delegatesToWait = new TaskFuture[]{future, new TaskFutureAdapter<>(buildFuture)}; - } - catch (Throwable e) { - handleProcessExecutionFailure(sessionId, e); - } + myBuildsInProgress.put(projectPath, future); + final OSProcessHandler processHandler; + CharSequence errorsOnLaunch; + if (usingPreloadedProcess) { + final boolean paramsSent = myMessageDispatcher.sendBuildParameters(future.getRequestID(), params); + if (!paramsSent) { + myMessageDispatcher.cancelSession(future.getRequestID()); + } + processHandler = preloaded.second; + errorsOnLaunch = STDERR_OUTPUT.get(processHandler); + } + else { + if (isAutomake && needRescan) { + // if project state was cleared because of roots changed or this is the first compilation after project opening, + // ensure project model is saved on disk, so that automake sees the latest model state. + // For ordinary make all project, app settings and unsaved docs are always saved before build starts. + try { + TransactionGuard.getInstance().submitTransactionAndWait(project::save); + } + catch (Throwable e) { + LOG.info(e); + } + } + + processHandler = launchBuildProcess(project, myListenPort, sessionId, false); + errorsOnLaunch = new StringBuffer(); + processHandler.addProcessListener(new StdOutputCollector((StringBuffer)errorsOnLaunch)); + processHandler.startNotify(); + } + + Integer debugPort = processHandler.getUserData(COMPILER_PROCESS_DEBUG_PORT); + if (debugPort != null) { + String message = "Make: waiting for debugger connection on port " + debugPort; + messageHandler + .handleCompileMessage(sessionId, CmdlineProtoUtil.createCompileProgressMessageResponse(message).getCompileMessage()); + } + + while (!processHandler.waitFor()) { + LOG.info("processHandler.waitFor() returned false for session " + sessionId + ", continue waiting"); + } + + final int exitValue = processHandler.getProcess().exitValue(); + if (exitValue != 0) { + final StringBuilder msg = new StringBuilder(); + msg.append("Abnormal build process termination: "); + if (errorsOnLaunch != null && errorsOnLaunch.length() > 0) { + msg.append("\n").append(errorsOnLaunch); + if (StringUtil.contains(errorsOnLaunch, "java.lang.NoSuchMethodError")) { + msg.append( + "\nThe error may be caused by JARs in Java Extensions directory which conflicts with libraries used by the external build process.") + .append( + "\nTry adding -Djava.ext.dirs=\"\" argument to 'Build process VM options' in File | Settings | Build, Execution, Deployment | Compiler to fix the problem."); + } + } + else { + msg.append("unknown error"); + } + handler.handleFailure(sessionId, CmdlineProtoUtil.createFailure(msg.toString(), null)); + } + } + catch (Throwable e) { + execFailure = e; + } + finally { + myBuildsInProgress.remove(projectPath); + notifySessionTerminationIfNeeded(sessionId, execFailure); + + if (isProcessPreloadingEnabled(project)) { + runCommand(() -> { + if (!myPreloadedBuilds.containsKey(projectPath)) { + try { + final Future, OSProcessHandler>> preloadResult = + launchPreloadedBuildProcess(project, projectTaskQueue); + myPreloadedBuilds.put(projectPath, preloadResult); + } + catch (Throwable e) { + LOG.info("Error pre-loading build process for project " + projectPath, e); + } + } + }); + } + } + }); + delegatesToWait = new TaskFuture[]{future, new TaskFutureAdapter<>(buildFuture)}; + } + catch (Throwable e) { + handleProcessExecutionFailure(sessionId, e); } - boolean set = _future.setDelegates(delegatesToWait); - assert set; } + boolean set = _future.setDelegates(delegatesToWait); + assert set; }); return _future; @@ -976,27 +933,24 @@ public class BuildManager implements Disposable { ensureListening(); // launching build process from projectTaskQueue ensures that no other build process for this project is currently running - return projectTaskQueue.submit(new Callable, OSProcessHandler>>() { - @Override - public Pair, OSProcessHandler> call() throws Exception { - if (project.isDisposed()) { - return null; - } - final RequestFuture future = new RequestFuture(new PreloadedProcessMessageHandler(), UUID.randomUUID(), new CancelBuildSessionAction()); - try { - myMessageDispatcher.registerBuildMessageHandler(future, null); - final OSProcessHandler processHandler = launchBuildProcess(project, myListenPort, future.getRequestID(), true); - final StringBuffer errors = new StringBuffer(); - processHandler.addProcessListener(new StdOutputCollector(errors)); - STDERR_OUTPUT.set(processHandler, errors); + return projectTaskQueue.submit(() -> { + if (project.isDisposed()) { + return null; + } + final RequestFuture future = new RequestFuture(new PreloadedProcessMessageHandler(), UUID.randomUUID(), new CancelBuildSessionAction()); + try { + myMessageDispatcher.registerBuildMessageHandler(future, null); + final OSProcessHandler processHandler = launchBuildProcess(project, myListenPort, future.getRequestID(), true); + final StringBuffer errors = new StringBuffer(); + processHandler.addProcessListener(new StdOutputCollector(errors)); + STDERR_OUTPUT.set(processHandler, errors); - processHandler.startNotify(); - return Pair.create(future, processHandler); - } - catch (Throwable e) { - handleProcessExecutionFailure(future.getRequestID(), e); - throw e instanceof Exception? (Exception)e : new RuntimeException(e); - } + processHandler.startNotify(); + return Pair.create(future, processHandler); + } + catch (Throwable e) { + handleProcessExecutionFailure(future.getRequestID(), e); + throw e instanceof Exception? (Exception)e : new RuntimeException(e); } }); } @@ -1367,15 +1321,12 @@ public class BuildManager implements Disposable { private abstract static class BuildManagerPeriodicTask implements Runnable { private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); private final AtomicBoolean myInProgress = new AtomicBoolean(false); - private final Runnable myTaskRunnable = new Runnable() { - @Override - public void run() { - try { - runTask(); - } - finally { - myInProgress.set(false); - } + private final Runnable myTaskRunnable = () -> { + try { + runTask(); + } + finally { + myInProgress.set(false); } }; @@ -1545,40 +1496,34 @@ public class BuildManager implements Disposable { } if (!candidates.isEmpty()) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { + ApplicationManager.getApplication().executeOnPooledThread(() -> { + if (project.isDisposed()) { + return; + } + final List rootFiles = new ArrayList(candidates.size()); + for (String root : candidates) { + rootFiles.add(new File(root)); + } + // this will ensure that we'll be able to obtain VirtualFile for existing roots + CompilerUtil.refreshOutputDirectories(rootFiles, false); + + final LocalFileSystem lfs = LocalFileSystem.getInstance(); + final Set filesToRefresh = new HashSet(); + ApplicationManager.getApplication().runReadAction(() -> { if (project.isDisposed()) { return; } - final List rootFiles = new ArrayList(candidates.size()); - for (String root : candidates) { - rootFiles.add(new File(root)); - } - // this will ensure that we'll be able to obtain VirtualFile for existing roots - CompilerUtil.refreshOutputDirectories(rootFiles, false); - - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final Set filesToRefresh = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) { - return; - } - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - for (File root : rootFiles) { - final VirtualFile rootFile = lfs.findFileByIoFile(root); - if (rootFile != null && fileIndex.isInSourceContent(rootFile)) { - filesToRefresh.add(rootFile); - } - } - if (!filesToRefresh.isEmpty()) { - lfs.refreshFiles(filesToRefresh, true, true, null); - } + final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); + for (File root : rootFiles) { + final VirtualFile rootFile = lfs.findFileByIoFile(root); + if (rootFile != null && fileIndex.isInSourceContent(rootFile)) { + filesToRefresh.add(rootFile); } - }); - } + } + if (!filesToRefresh.isEmpty()) { + lfs.refreshFiles(filesToRefresh, true, true, null); + } + }); }); } } @@ -1598,20 +1543,14 @@ public class BuildManager implements Disposable { myProjectDataMap.remove(projectPath); } }); - StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - runCommand(new Runnable() { - @Override - public void run() { - final File projectSystemDir = getProjectSystemDirectory(project); - if (projectSystemDir != null) { - updateUsageFile(project, projectSystemDir); - } - } - }); - scheduleAutoMake(); // run automake after project opened - } + StartupManager.getInstance(project).registerPostStartupActivity(() -> { + runCommand(() -> { + final File projectSystemDir = getProjectSystemDirectory(project); + if (projectSystemDir != null) { + updateUsageFile(project, projectSystemDir); + } + }); + scheduleAutoMake(); // run automake after project opened }); } diff --git a/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java b/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java index 529fcde06fbe..a6f8082b9e2a 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java @@ -106,12 +106,7 @@ public abstract class DefaultMessageHandler implements BuilderMessageHandler { @Override public void onCanceled(@NotNull ProgressIndicator indicator) { - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - handleConstantSearchTask(channel, sessionId, task); - } - }); + DumbService.getInstance(myProject).runWhenSmart(() -> handleConstantSearchTask(channel, sessionId, task)); } }); } @@ -152,22 +147,20 @@ public abstract class DefaultMessageHandler implements BuilderMessageHandler { try { if (isRemoved) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - if (classes.length > 0) { - for (PsiClass aClass : classes) { - final boolean success = aClass.isValid() && performRemovedConstantSearch(aClass, fieldName, accessFlags, affectedPaths); - if (!success) { - isSuccess.set(Boolean.FALSE); - break; - } + ApplicationManager.getApplication().runReadAction(() -> { + if (classes.length > 0) { + for (PsiClass aClass : classes) { + final boolean success = aClass.isValid() && performRemovedConstantSearch(aClass, fieldName, accessFlags, affectedPaths); + if (!success) { + isSuccess.set(Boolean.FALSE); + break; } } - else { - isSuccess.set( - performRemovedConstantSearch(null, fieldName, accessFlags, affectedPaths) - ); - } + } + else { + isSuccess.set( + performRemovedConstantSearch(null, fieldName, accessFlags, affectedPaths) + ); } }); } @@ -329,25 +322,23 @@ public abstract class DefaultMessageHandler implements BuilderMessageHandler { } private void affectDirectUsages(final PsiField psiField, final int fieldAccessFlags, final boolean ignoreAccessScope, final Set affectedPaths) throws ProcessCanceledException { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - if (psiField.isValid()) { - final PsiFile fieldContainingFile = psiField.getContainingFile(); - final Set processedFiles = new HashSet(); - if (fieldContainingFile != null) { - processedFiles.add(fieldContainingFile); - } - // if field is invalid, the file might be changed, so next time it is compiled, - // the constant value change, if any, will be processed - final Collection references = doFindReferences(psiField, fieldAccessFlags, ignoreAccessScope); - for (final PsiReferenceExpression ref : references) { - final PsiElement usage = ref.getElement(); - final PsiFile containingPsi = usage.getContainingFile(); - if (containingPsi != null && processedFiles.add(containingPsi)) { - final VirtualFile vFile = containingPsi.getOriginalFile().getVirtualFile(); - if (vFile != null) { - affectedPaths.add(vFile.getPath()); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (psiField.isValid()) { + final PsiFile fieldContainingFile = psiField.getContainingFile(); + final Set processedFiles = new HashSet(); + if (fieldContainingFile != null) { + processedFiles.add(fieldContainingFile); + } + // if field is invalid, the file might be changed, so next time it is compiled, + // the constant value change, if any, will be processed + final Collection references = doFindReferences(psiField, fieldAccessFlags, ignoreAccessScope); + for (final PsiReferenceExpression ref : references) { + final PsiElement usage = ref.getElement(); + final PsiFile containingPsi = usage.getContainingFile(); + if (containingPsi != null && processedFiles.add(containingPsi)) { + final VirtualFile vFile = containingPsi.getOriginalFile().getVirtualFile(); + if (vFile != null) { + affectedPaths.add(vFile.getPath()); } } } diff --git a/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java b/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java index 157aadfe4ec5..fe1d292f4832 100644 --- a/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java +++ b/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java @@ -153,27 +153,24 @@ public class InspectionValidatorWrapper implements Validator { final ArrayList items = new ArrayList(); - final Processor processor = new Processor() { - @Override - public boolean process(VirtualFile file) { - if (!file.isValid()) { - return true; - } - - if (myCompilerManager.isExcludedFromCompilation(file) || - excludesConfiguration.isExcluded(file)) { - return true; - } - - final Module module = context.getModuleByFile(file); - if (module != null) { - final PsiFile psiFile = myPsiManager.findFile(file); - if (psiFile != null) { - items.add(new MyValidatorProcessingItem(psiFile)); - } - } + final Processor processor = file -> { + if (!file.isValid()) { return true; } + + if (myCompilerManager.isExcludedFromCompilation(file) || + excludesConfiguration.isExcluded(file)) { + return true; + } + + final Module module = context.getModuleByFile(file); + if (module != null) { + final PsiFile psiFile = myPsiManager.findFile(file); + if (psiFile != null) { + items.add(new MyValidatorProcessingItem(psiFile)); + } + } + return true; }; ContainerUtil.process(myValidator.getFilesToProcess(myPsiManager.getProject(), context), processor); return items; diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactManagerImpl.java b/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactManagerImpl.java index 5974ff9d158f..b78fff80c74a 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactManagerImpl.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactManagerImpl.java @@ -126,12 +126,7 @@ public class ArtifactManagerImpl extends ArtifactManager implements ProjectCompo artifactState.getPropertiesList().add(propertiesState); } } - Collections.sort(artifactState.getPropertiesList(), new Comparator() { - @Override - public int compare(@NotNull ArtifactPropertiesState o1, @NotNull ArtifactPropertiesState o2) { - return o1.getId().compareTo(o2.getId()); - } - }); + Collections.sort(artifactState.getPropertiesList(), (o1, o2) -> o1.getId().compareTo(o2.getId())); } state.getArtifacts().add(artifactState); } @@ -369,19 +364,16 @@ public class ArtifactManagerImpl extends ArtifactManager implements ProjectCompo myModificationTracker.incModificationCount(); final ArtifactListener publisher = myProject.getMessageBus().syncPublisher(TOPIC); hasChanges = !removed.isEmpty() || !added.isEmpty() || !changed.isEmpty(); - ProjectRootManagerEx.getInstanceEx(myProject).mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (ArtifactImpl artifact : removed) { - publisher.artifactRemoved(artifact); - } - //it's important to send 'removed' events before 'added'. Otherwise when artifacts are reloaded from xml artifact pointers will be damaged - for (ArtifactImpl artifact : added) { - publisher.artifactAdded(artifact); - } - for (Pair pair : changed) { - publisher.artifactChanged(pair.getFirst(), pair.getSecond()); - } + ProjectRootManagerEx.getInstanceEx(myProject).mergeRootsChangesDuring(() -> { + for (ArtifactImpl artifact : removed) { + publisher.artifactRemoved(artifact); + } + //it's important to send 'removed' events before 'added'. Otherwise when artifacts are reloaded from xml artifact pointers will be damaged + for (ArtifactImpl artifact : added) { + publisher.artifactAdded(artifact); + } + for (Pair pair : changed) { + publisher.artifactChanged(pair.getFirst(), pair.getSecond()); } }); } diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactUtil.java b/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactUtil.java index 3fcfc8df5529..97879676acd7 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactUtil.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/ArtifactUtil.java @@ -544,14 +544,11 @@ public class ArtifactUtil { final Set modules = new THashSet(); final PackagingElementResolvingContext resolvingContext = ArtifactManager.getInstance(project).getResolvingContext(); for (Artifact artifact : artifacts) { - processPackagingElements(artifact, null, new Processor>() { - @Override - public boolean process(PackagingElement element) { - if (element instanceof ModuleOutputPackagingElement) { - ContainerUtil.addIfNotNull(modules, ((ModuleOutputPackagingElement)element).findModule(resolvingContext)); - } - return true; + processPackagingElements(artifact, null, element -> { + if (element instanceof ModuleOutputPackagingElement) { + ContainerUtil.addIfNotNull(modules, ((ModuleOutputPackagingElement)element).findModule(resolvingContext)); } + return true; }, resolvingContext, true); } return modules; @@ -561,18 +558,15 @@ public class ArtifactUtil { ArtifactManager artifactManager = ArtifactManager.getInstance(module.getProject()); final PackagingElementResolvingContext context = artifactManager.getResolvingContext(); final Set result = new HashSet(); - Processor> processor = new Processor>() { - @Override - public boolean process(@NotNull PackagingElement element) { - if (element instanceof ProductionModuleOutputPackagingElement - && module.equals(((ProductionModuleOutputPackagingElement)element).findModule(context))) { - return false; - } - if (element instanceof ArtifactPackagingElement && result.contains(((ArtifactPackagingElement)element).findArtifact(context))) { - return false; - } - return true; + Processor> processor = element -> { + if (element instanceof ProductionModuleOutputPackagingElement + && module.equals(((ProductionModuleOutputPackagingElement)element).findModule(context))) { + return false; } + if (element instanceof ArtifactPackagingElement && result.contains(((ArtifactPackagingElement)element).findArtifact(context))) { + return false; + } + return true; }; for (Artifact artifact : artifactManager.getSortedArtifacts()) { boolean contains = !processPackagingElements(artifact, null, processor, context, true); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/JarFromModulesTemplate.java b/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/JarFromModulesTemplate.java index 07e295673847..5812a8bb07f6 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/JarFromModulesTemplate.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/artifacts/JarFromModulesTemplate.java @@ -113,17 +113,14 @@ public class JarFromModulesTemplate extends ArtifactTemplate { final ModulesProvider modulesProvider = myContext.getModulesProvider(); final OrderEnumerator enumerator = orderEnumerator.using(modulesProvider).withoutSdk().runtimeOnly().recursively(); enumerator.forEachLibrary(new CommonProcessors.CollectProcessor(libraries)); - enumerator.forEachModule(new Processor() { - @Override - public boolean process(Module module) { - if (ProductionModuleOutputElementType.ELEMENT_TYPE.isSuitableModule(modulesProvider, module)) { - archive.addOrFindChild(factory.createModuleOutput(module)); - } - if (includeTests && TestModuleOutputElementType.ELEMENT_TYPE.isSuitableModule(modulesProvider, module)) { - archive.addOrFindChild(factory.createTestModuleOutput(module)); - } - return true; + enumerator.forEachModule(module -> { + if (ProductionModuleOutputElementType.ELEMENT_TYPE.isSuitableModule(modulesProvider, module)) { + archive.addOrFindChild(factory.createModuleOutput(module)); } + if (includeTests && TestModuleOutputElementType.ELEMENT_TYPE.isSuitableModule(modulesProvider, module)) { + archive.addOrFindChild(factory.createTestModuleOutput(module)); + } + return true; }); final JarArtifactType jarArtifactType = JarArtifactType.getInstance(); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactCompileScope.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactCompileScope.java index 5280384dff11..7343c5b0592f 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactCompileScope.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactCompileScope.java @@ -146,15 +146,12 @@ public class ArtifactCompileScope { result.add(artifact); } - ArtifactUtil.processPackagingElements(artifact, ArtifactElementType.ARTIFACT_ELEMENT_TYPE, new Processor() { - @Override - public boolean process(ArtifactPackagingElement element) { - Artifact included = element.findArtifact(context); - if (included != null) { - collectIncludedArtifacts(included, context, processed, result, withOutputPathOnly); - } - return true; - } - }, context, false); + ArtifactUtil.processPackagingElements(artifact, ArtifactElementType.ARTIFACT_ELEMENT_TYPE, element -> { + Artifact included = element.findArtifact(context); + if (included != null) { + collectIncludedArtifacts(included, context, processed, result, withOutputPathOnly); + } + return true; + }, context, false); } } diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArtifactElementType.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArtifactElementType.java index ed599a85bba8..8e53bccad14a 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArtifactElementType.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArtifactElementType.java @@ -69,11 +69,9 @@ public class ArtifactElementType extends ComplexPackagingElementType result = new HashSet(Arrays.asList(context.getArtifactModel().getArtifacts())); if (notIncludedOnly) { - ArtifactUtil.processPackagingElements(artifact, ARTIFACT_ELEMENT_TYPE, new Processor() { - public boolean process(ArtifactPackagingElement artifactPackagingElement) { - result.remove(artifactPackagingElement.findArtifact(context)); - return true; - } + ArtifactUtil.processPackagingElements(artifact, ARTIFACT_ELEMENT_TYPE, artifactPackagingElement -> { + result.remove(artifactPackagingElement.findArtifact(context)); + return true; }, context, true); } result.remove(artifact); @@ -81,11 +79,8 @@ public class ArtifactElementType extends ComplexPackagingElementType() { - public boolean process(ArtifactPackagingElement element) { - return !artifact.getName().equals(element.getArtifactName()); - } - }, context, true); + ArtifactUtil.processPackagingElements(another, ARTIFACT_ELEMENT_TYPE, + element -> !artifact.getName().equals(element.getArtifactName()), context, true); if (!notContainThis) { iterator.remove(); } diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ManifestFileUtil.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ManifestFileUtil.java index 0009426af389..aa9daa0bcec9 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ManifestFileUtil.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ManifestFileUtil.java @@ -206,22 +206,19 @@ public class ManifestFileUtil { ManifestBuilder.setVersionAttribute(mainAttributes); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { + try { + final OutputStream outputStream = file.getOutputStream(ManifestFileUtil.class); try { - final OutputStream outputStream = file.getOutputStream(ManifestFileUtil.class); - try { - manifest.write(outputStream); - } - finally { - outputStream.close(); - } + manifest.write(outputStream); } - catch (IOException e) { - LOG.info(e); + finally { + outputStream.close(); } } + catch (IOException e) { + LOG.info(e); + } }); } @@ -321,12 +318,10 @@ public class ManifestFileUtil { public static void addManifestFileToLayout(final @NotNull String path, final @NotNull ArtifactEditorContext context, final @NotNull CompositePackagingElement element) { - context.editLayout(context.getArtifact(), new Runnable() { - public void run() { - final VirtualFile file = findManifestFile(element, context, context.getArtifactType()); - if (file == null || !FileUtil.pathsEqual(file.getPath(), path)) { - PackagingElementFactory.getInstance().addFileCopy(element, MANIFEST_DIR_NAME, path, MANIFEST_FILE_NAME); - } + context.editLayout(context.getArtifact(), () -> { + final VirtualFile file = findManifestFile(element, context, context.getArtifactType()); + if (file == null || !FileUtil.pathsEqual(file.getPath(), path)) { + PackagingElementFactory.getInstance().addFileCopy(element, MANIFEST_DIR_NAME, path, MANIFEST_FILE_NAME); } }); } diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/run/ArtifactChooser.java b/java/compiler/impl/src/com/intellij/packaging/impl/run/ArtifactChooser.java index c6e7aca3fdf3..d9a2a161dfaa 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/run/ArtifactChooser.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/run/ArtifactChooser.java @@ -31,11 +31,8 @@ import java.util.List; * @author nik */ public class ArtifactChooser extends ElementsChooser { - private static final Comparator ARTIFACT_COMPARATOR = new Comparator() { - public int compare(ArtifactPointer o1, ArtifactPointer o2) { - return o1.getArtifactName().compareToIgnoreCase(o2.getArtifactName()); - } - }; + private static final Comparator ARTIFACT_COMPARATOR = + (o1, o2) -> o1.getArtifactName().compareToIgnoreCase(o2.getArtifactName()); private static final ElementProperties INVALID_ARTIFACT_PROPERTIES = new ElementProperties() { public Icon getIcon() { return AllIcons.Nodes.Artifact; diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java b/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java index 8a72229aea95..0f5c2f996c13 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java @@ -183,17 +183,15 @@ public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider { + if (myProject.isDisposed()) { + return; } + final CompilerManager manager = CompilerManager.getInstance(myProject); + final CompileScope scope = ArtifactCompileScope.createArtifactsScope(myProject, artifacts); + ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env)); + finished.down(); + manager.make(scope, CompilerFilter.ALL, callback); }, ModalityState.NON_MODAL); finished.waitFor(); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java index 9b4cca6aba01..c03e810b8643 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java @@ -96,11 +96,7 @@ public class PackageFileAction extends AnAction { FileDocumentManager.getInstance().saveAllDocuments(); final List files = getFilesToPackage(event, project); Artifact[] allArtifacts = ArtifactManager.getInstance(project).getArtifacts(); - PackageFileWorker.startPackagingFiles(project, files, allArtifacts, new Runnable() { - public void run() { - setStatusText(project, files); - } - }); + PackageFileWorker.startPackagingFiles(project, files, allArtifacts, () -> setStatusText(project, files)); } private static void setStatusText(Project project, List files) { diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java index ca579d7bd4f1..cf604876207e 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java @@ -69,12 +69,8 @@ public class PackageFileWorker { } public static void startPackagingFiles(Project project, List files, Artifact[] artifacts, final @NotNull Runnable onFinishedInAwt) { - startPackagingFiles(project, files, artifacts, true).doWhenProcessed(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(onFinishedInAwt); - } - }); + startPackagingFiles(project, files, artifacts, true).doWhenProcessed( + () -> ApplicationManager.getApplication().invokeLater(onFinishedInAwt)); } public static ActionCallback startPackagingFiles(final Project project, final List files, diff --git a/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java b/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java index 6c79dcb7d6fd..6e0175945352 100644 --- a/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java +++ b/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java @@ -212,27 +212,21 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { protected CompilationLog compile(final CompileScope scope, final CompilerFilter filter, final boolean forceCompile, final boolean errorsExpected) { - return compile(errorsExpected, new ParameterizedRunnable() { - @Override - public void run(CompileStatusNotification callback) { - final CompilerManager compilerManager = getCompilerManager(); - if (forceCompile) { - Assert.assertSame("Only 'ALL' filter is supported for forced compilation", CompilerFilter.ALL, filter); - compilerManager.compile(scope, callback); - } - else { - compilerManager.make(scope, filter, callback); - } + return compile(errorsExpected, callback -> { + final CompilerManager compilerManager = getCompilerManager(); + if (forceCompile) { + Assert.assertSame("Only 'ALL' filter is supported for forced compilation", CompilerFilter.ALL, filter); + compilerManager.compile(scope, callback); + } + else { + compilerManager.make(scope, filter, callback); } }); } protected CompilationLog rebuild() { - return compile(false, new ParameterizedRunnable() { - @Override - public void run(CompileStatusNotification compileStatusNotification) { - getCompilerManager().rebuild(compileStatusNotification); - } + return compile(false, compileStatusNotification -> { + getCompilerManager().rebuild(compileStatusNotification); }); } diff --git a/java/compiler/openapi/src/com/intellij/compiler/ModuleCompilerUtil.java b/java/compiler/openapi/src/com/intellij/compiler/ModuleCompilerUtil.java index 37b7d8ab7e52..66f8acca13b9 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ModuleCompilerUtil.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ModuleCompilerUtil.java @@ -97,11 +97,9 @@ public final class ModuleCompilerUtil { public static void sortModules(final Project project, final List modules) { final Application application = ApplicationManager.getApplication(); - Runnable sort = new Runnable() { - public void run() { - Comparator comparator = ModuleManager.getInstance(project).moduleDependencyComparator(); - Collections.sort(modules, comparator); - } + Runnable sort = () -> { + Comparator comparator = ModuleManager.getInstance(project).moduleDependencyComparator(); + Collections.sort(modules, comparator); }; if (application.isDispatchThread()) { sort.run(); @@ -120,15 +118,12 @@ public final class ModuleCompilerUtil { public Iterator getIn(final ModuleRootModel model) { final List dependencies = new ArrayList(); - model.orderEntries().compileOnly().forEachModule(new Processor() { - @Override - public boolean process(Module module) { - T depModel = models.get(module); - if (depModel != null) { - dependencies.add(depModel); - } - return true; + model.orderEntries().compileOnly().forEachModule(module -> { + T depModel = models.get(module); + if (depModel != null) { + dependencies.add(depModel); } + return true; }); return dependencies.iterator(); } @@ -215,12 +210,9 @@ public final class ModuleCompilerUtil { enumerator = enumerator.productionOnly(); } final List deps = new ArrayList(); - enumerator.forEachModule(new Processor() { - @Override - public boolean process(Module module) { - deps.add(new ModuleSourceSet(module, n.getType())); - return true; - } + enumerator.forEachModule(module -> { + deps.add(new ModuleSourceSet(module, n.getType())); + return true; }); if (n.getType() == ModuleSourceSet.Type.TEST) { deps.add(new ModuleSourceSet(n.getModule(), ModuleSourceSet.Type.PRODUCTION)); diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/ChunkCustomCompilerExtension.java b/java/compiler/openapi/src/com/intellij/compiler/ant/ChunkCustomCompilerExtension.java index 2356389c6b46..285991d304a0 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/ChunkCustomCompilerExtension.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ant/ChunkCustomCompilerExtension.java @@ -37,11 +37,8 @@ public abstract class ChunkCustomCompilerExtension { /** * Comparator that compares extensions using names. It is used for make order of elements predictable. */ - protected static final Comparator COMPARATOR = new Comparator() { - public int compare(ChunkCustomCompilerExtension o1, ChunkCustomCompilerExtension o2) { - return o1.getClass().getName().compareTo(o2.getClass().getName()); - } - }; + protected static final Comparator COMPARATOR = + (o1, o2) -> o1.getClass().getName().compareTo(o2.getClass().getName()); /** * Generate custom compile task inside compile target. Note that if more diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/ModuleChunk.java b/java/compiler/openapi/src/com/intellij/compiler/ant/ModuleChunk.java index 3dbced26844f..0c43e665e3af 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/ModuleChunk.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ant/ModuleChunk.java @@ -62,11 +62,7 @@ public class ModuleChunk { public ModuleChunk(Module[] modules) { myModules = modules; - Arrays.sort(myModules, new Comparator() { - public int compare(final Module o1, final Module o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Arrays.sort(myModules, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); myMainModule = myModules[0]; myCustomCompilers = ChunkCustomCompilerExtension.getCustomCompile(this); } diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/taskdefs/Manifest.java b/java/compiler/openapi/src/com/intellij/compiler/ant/taskdefs/Manifest.java index 505779d07794..130d4d9f6e52 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/taskdefs/Manifest.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ant/taskdefs/Manifest.java @@ -39,12 +39,10 @@ public class Manifest extends Tag{ final Attributes mainAttributes = manifest.getMainAttributes(); List keys = new ArrayList(mainAttributes.keySet()); - Collections.sort(keys, new Comparator() { - public int compare(final Object o1, final Object o2) { - Attributes.Name name1 = (Attributes.Name)o1; - Attributes.Name name2 = (Attributes.Name)o2; - return name1.toString().compareTo(name2.toString()); - } + Collections.sort(keys, (o1, o2) -> { + Attributes.Name name1 = (Attributes.Name)o1; + Attributes.Name name2 = (Attributes.Name)o2; + return name1.toString().compareTo(name2.toString()); }); for (final Object o : keys) { Attributes.Name name = (Attributes.Name)o; diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java index 6ffe84dfdbd7..1fdd0078e907 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java @@ -43,12 +43,7 @@ import java.util.Comparator; public class CompilerPaths { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.compiler.CompilerPaths"); private static volatile String ourSystemPath; - private static final Comparator URLS_COMPARATOR = new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.compareTo(o2); - } - }; + private static final Comparator URLS_COMPARATOR = (o1, o2) -> o1.compareTo(o2); /** * Returns a directory * @return a directory where compiler may generate files. All generated files are not deleted when the application exits diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java index c7a079af73d9..223059850cc2 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java @@ -71,11 +71,9 @@ public class CompilerPathsEx extends CompilerPaths { public static void visitFiles(final Collection directories, final FileVisitor visitor) { for (final VirtualFile outputDir : directories) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final String path = outputDir.getPath(); - visitor.accept(outputDir, path, path); - } + ApplicationManager.getApplication().runReadAction(() -> { + final String path = outputDir.getPath(); + visitor.accept(outputDir, path, path); }); } } diff --git a/java/compiler/openapi/src/com/intellij/packaging/artifacts/ArtifactManager.java b/java/compiler/openapi/src/com/intellij/packaging/artifacts/ArtifactManager.java index 9610bfa3e741..25840d233722 100644 --- a/java/compiler/openapi/src/com/intellij/packaging/artifacts/ArtifactManager.java +++ b/java/compiler/openapi/src/com/intellij/packaging/artifacts/ArtifactManager.java @@ -33,11 +33,7 @@ import java.util.Comparator; */ public abstract class ArtifactManager implements ArtifactModel { public static final Topic TOPIC = Topic.create("artifacts changes", ArtifactListener.class); - public static final Comparator ARTIFACT_COMPARATOR = new Comparator() { - public int compare(Artifact o1, Artifact o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }; + public static final Comparator ARTIFACT_COMPARATOR = (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()); public static ArtifactManager getInstance(@NotNull Project project) { return project.getComponent(ArtifactManager.class); diff --git a/java/debugger/impl/src/com/intellij/debugger/DebuggerInvocationUtil.java b/java/debugger/impl/src/com/intellij/debugger/DebuggerInvocationUtil.java index ebb5bef81ece..c9f6c96c5853 100644 --- a/java/debugger/impl/src/com/intellij/debugger/DebuggerInvocationUtil.java +++ b/java/debugger/impl/src/com/intellij/debugger/DebuggerInvocationUtil.java @@ -32,12 +32,9 @@ public class DebuggerInvocationUtil { return; } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - runnable.run(); - } + SwingUtilities.invokeLater(() -> { + if (!project.isDisposed()) { + runnable.run(); } }); } @@ -56,12 +53,9 @@ public class DebuggerInvocationUtil { public static void invokeAndWait(final Project project, @NotNull final Runnable runnable, ModalityState state) { if (project != null) { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - runnable.run(); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + if (!project.isDisposed()) { + runnable.run(); } }, state); } diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/AddSteppingFilterAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/AddSteppingFilterAction.java index 350641689668..45576c975104 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/AddSteppingFilterAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/AddSteppingFilterAction.java @@ -51,14 +51,11 @@ public class AddSteppingFilterAction extends DebuggerAction { } final Project project = e.getData(CommonDataKeys.PROJECT); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String filter = Messages.showInputDialog(project, "", "Add Stepping Filter", null, name, null); - if (filter != null) { - ClassFilter[] newFilters = ArrayUtil.append(DebuggerSettings.getInstance().getSteppingFilters(), new ClassFilter(filter)); - DebuggerSettings.getInstance().setSteppingFilters(newFilters); - } + ApplicationManager.getApplication().invokeLater(() -> { + String filter = Messages.showInputDialog(project, "", "Add Stepping Filter", null, name, null); + if (filter != null) { + ClassFilter[] newFilters = ArrayUtil.append(DebuggerSettings.getInstance().getSteppingFilters(), new ClassFilter(filter)); + DebuggerSettings.getInstance().setSteppingFilters(newFilters); } }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/CreateRendererAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/CreateRendererAction.java index 8ac0d9630cb3..7449838c7db0 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/CreateRendererAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/CreateRendererAction.java @@ -63,35 +63,32 @@ public class CreateRendererAction extends AnAction { public void threadAction() { Type type = javaValue.getDescriptor().getType(); final String name = type != null ? type.name() :null; - DebuggerUIUtil.invokeLater(new Runnable() { - @Override - public void run() { - final UserRenderersConfigurable ui = new UserRenderersConfigurable(); - ConfigurableBase configurable = - new ConfigurableBase( - "reference.idesettings.debugger.typerenderers", - DebuggerBundle.message("user.renderers.configurable.display.name"), - "reference.idesettings.debugger.typerenderers") { - @NotNull - @Override - protected NodeRendererSettings getSettings() { - return NodeRendererSettings.getInstance(); - } + DebuggerUIUtil.invokeLater(() -> { + final UserRenderersConfigurable ui = new UserRenderersConfigurable(); + ConfigurableBase configurable = + new ConfigurableBase( + "reference.idesettings.debugger.typerenderers", + DebuggerBundle.message("user.renderers.configurable.display.name"), + "reference.idesettings.debugger.typerenderers") { + @NotNull + @Override + protected NodeRendererSettings getSettings() { + return NodeRendererSettings.getInstance(); + } - @Override - protected UserRenderersConfigurable createUi() { - return ui; - } - }; - SingleConfigurableEditor editor = new SingleConfigurableEditor(project, configurable); - if (name != null) { - CompoundReferenceRenderer renderer = - NodeRendererSettings.getInstance().createCompoundReferenceRenderer(name, name, null, null); - renderer.setEnabled(true); - ui.addRenderer(renderer); - } - editor.show(); + @Override + protected UserRenderersConfigurable createUi() { + return ui; + } + }; + SingleConfigurableEditor editor = new SingleConfigurableEditor(project, configurable); + if (name != null) { + CompoundReferenceRenderer renderer = + NodeRendererSettings.getInstance().createCompoundReferenceRenderer(name, name, null, null); + renderer.setEnabled(true); + ui.addRenderer(renderer); } + editor.show(); }); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/DebuggerAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/DebuggerAction.java index d66598d0f617..111f1a627095 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/DebuggerAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/DebuggerAction.java @@ -153,11 +153,9 @@ public abstract class DebuggerAction extends AnAction { } public static void enableAction(final AnActionEvent event, final boolean enable) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - event.getPresentation().setEnabled(enable); - event.getPresentation().setVisible(true); - } + SwingUtilities.invokeLater(() -> { + event.getPresentation().setEnabled(enable); + event.getPresentation().setVisible(true); }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/EditSourceAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/EditSourceAction.java index 59b8b4c4eb12..da7725f88a91 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/EditSourceAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/EditSourceAction.java @@ -101,11 +101,7 @@ public class EditSourceAction extends DebuggerAction{ public void threadAction() { final SourcePosition position = getSourcePosition(node, debuggerContext); if (position == null) { - DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() { - public void run() { - presentation.setEnabled(false); - } - }); + DebuggerInvocationUtil.swingInvokeLater(project, () -> presentation.setEnabled(false)); } } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java index da6c5fbe9553..011a7afe4e3c 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java @@ -49,10 +49,8 @@ public class ExportThreadsAction extends AnAction implements AnAction.Transparen process.getManagerThread().invoke(new DebuggerCommandImpl() { protected void action() throws Exception { final List threads = ThreadDumpAction.buildThreadStates(process.getVirtualMachineProxy()); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ExportToTextFileAction.export(project, ThreadDumpPanel.createToFileExporter(project, threads)); - } + ApplicationManager.getApplication().invokeLater(() -> { + ExportToTextFileAction.export(project, ThreadDumpPanel.createToFileExporter(project, threads)); }, ModalityState.NON_MODAL); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ForceEarlyReturnAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ForceEarlyReturnAction.java index 9f37f2885ab1..29c34dfa486a 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ForceEarlyReturnAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ForceEarlyReturnAction.java @@ -82,12 +82,8 @@ public class ForceEarlyReturnAction extends DebuggerAction { } else { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - new ReturnExpressionDialog(project, debugProcess.getXdebugProcess().getEditorsProvider(), debugProcess, stackFrame).show(); - } - }); + SwingUtilities.invokeLater( + () -> new ReturnExpressionDialog(project, debugProcess.getXdebugProcess().getEditorsProvider(), debugProcess, stackFrame).show()); } } }); @@ -98,28 +94,25 @@ public class ForceEarlyReturnAction extends DebuggerAction { final DebugProcessImpl debugProcess, @Nullable final DialogWrapper dialog) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (PopFrameAction.evaluateFinallyBlocks(debugProcess.getProject(), - UIUtil.removeMnemonic(ActionsBundle.actionText("Debugger.ForceEarlyReturn")), - frame, - new XDebuggerEvaluator.XEvaluationCallback() { - @Override - public void evaluated(@NotNull XValue result) { - forceEarlyReturn(value, frame.getDescriptor().getFrameProxy().threadProxy(), debugProcess, dialog); - } + SwingUtilities.invokeLater(() -> { + if (PopFrameAction.evaluateFinallyBlocks(debugProcess.getProject(), + UIUtil.removeMnemonic(ActionsBundle.actionText("Debugger.ForceEarlyReturn")), + frame, + new XDebuggerEvaluator.XEvaluationCallback() { + @Override + public void evaluated(@NotNull XValue result) { + forceEarlyReturn(value, frame.getDescriptor().getFrameProxy().threadProxy(), debugProcess, dialog); + } - @Override - public void errorOccurred(@NotNull String errorMessage) { - showError(debugProcess.getProject(), - DebuggerBundle.message("error.executing.finally", errorMessage)); - } - })) { - return; - } - forceEarlyReturn(value, frame.getDescriptor().getFrameProxy().threadProxy(), debugProcess, dialog); + @Override + public void errorOccurred(@NotNull String errorMessage) { + showError(debugProcess.getProject(), + DebuggerBundle.message("error.executing.finally", errorMessage)); + } + })) { + return; } + forceEarlyReturn(value, frame.getDescriptor().getFrameProxy().threadProxy(), debugProcess, dialog); }); } @@ -138,14 +131,11 @@ public class ForceEarlyReturnAction extends DebuggerAction { return; } //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (dialog != null) { - dialog.close(DialogWrapper.OK_EXIT_CODE); - } - debugProcess.getSession().stepInto(true, null); + SwingUtilities.invokeLater(() -> { + if (dialog != null) { + dialog.close(DialogWrapper.OK_EXIT_CODE); } + debugProcess.getSession().stepInto(true, null); }); } }); @@ -182,14 +172,11 @@ public class ForceEarlyReturnAction extends DebuggerAction { } private static void showError(final Project project, final String message) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(project, - message, - UIUtil.removeMnemonic(ActionsBundle.actionText("Debugger.ForceEarlyReturn")), - Messages.getErrorIcon()); - } + ApplicationManager.getApplication().invokeLater(() -> { + Messages.showMessageDialog(project, + message, + UIUtil.removeMnemonic(ActionsBundle.actionText("Debugger.ForceEarlyReturn")), + Messages.getErrorIcon()); }, ModalityState.any()); } diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java b/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java index 6bfb5b89095c..98c8a5e88c11 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/JavaMarkObjectActionHandler.java @@ -94,12 +94,10 @@ public class JavaMarkObjectActionHandler extends MarkObjectActionHandler { final Ref> result = new Ref<>(null); try { final boolean suggestAdditionalMarkup = canSuggestAdditionalMarkup(debugProcess, valueDescriptor.getValue()); - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - ObjectMarkupPropertiesDialog dialog = new ObjectMarkupPropertiesDialog(parent, defaultText, suggestAdditionalMarkup); - if (dialog.showAndGet()) { - result.set(Pair.create(dialog.getConfiguredMarkup(), dialog.isMarkAdditionalFields())); - } + SwingUtilities.invokeAndWait(() -> { + ObjectMarkupPropertiesDialog dialog = new ObjectMarkupPropertiesDialog(parent, defaultText, suggestAdditionalMarkup); + if (dialog.showAndGet()) { + result.set(Pair.create(dialog.getConfiguredMarkup(), dialog.isMarkAdditionalFields())); } }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java index 1c3a0275c370..9204323cde84 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/PopFrameAction.java @@ -92,15 +92,10 @@ public class PopFrameAction extends DebuggerAction { @Override public void errorOccurred(@NotNull final String errorMessage) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages - .showMessageDialog(project, DebuggerBundle.message("error.executing.finally", errorMessage), - UIUtil.removeMnemonic(ActionsBundle.actionText(DebuggerActions.POP_FRAME)), - Messages.getErrorIcon()); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages + .showMessageDialog(project, DebuggerBundle.message("error.executing.finally", errorMessage), + UIUtil.removeMnemonic(ActionsBundle.actionText(DebuggerActions.POP_FRAME)), + Messages.getErrorIcon())); } })) return; popFrame(debugProcess, debuggerContext, stackFrame); diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java index df157425e2bb..7ad087cbd75a 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java @@ -61,12 +61,10 @@ public class ThreadDumpAction extends AnAction implements AnAction.TransparentUp vm.suspend(); try { final List threads = buildThreadStates(vm); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - XDebugSession xSession = session.getXDebugSession(); - if (xSession != null) { - DebuggerUtilsEx.addThreadDump(project, threads, xSession.getUI(), session); - } + ApplicationManager.getApplication().invokeLater(() -> { + XDebugSession xSession = session.getXDebugSession(); + if (xSession != null) { + DebuggerUtilsEx.addThreadDump(project, threads, xSession.getUI(), session); } }, ModalityState.NON_MODAL); } diff --git a/java/debugger/impl/src/com/intellij/debugger/codeinsight/JavaWithRuntimeCastSurrounder.java b/java/debugger/impl/src/com/intellij/debugger/codeinsight/JavaWithRuntimeCastSurrounder.java index 7390e87f43c1..730a0d7241bd 100644 --- a/java/debugger/impl/src/com/intellij/debugger/codeinsight/JavaWithRuntimeCastSurrounder.java +++ b/java/debugger/impl/src/com/intellij/debugger/codeinsight/JavaWithRuntimeCastSurrounder.java @@ -87,33 +87,29 @@ public class JavaWithRuntimeCastSurrounder extends JavaExpressionSurrounder { hold(); final Project project = myElement.getProject(); - DebuggerInvocationUtil.invokeLater(project, new Runnable() { - public void run() { - new WriteCommandAction(project, CodeInsightBundle.message("command.name.surround.with.runtime.cast")) { - protected void run(@NotNull Result result) throws Throwable { - try { - PsiElementFactory factory = JavaPsiFacade.getInstance(myElement.getProject()).getElementFactory(); - PsiParenthesizedExpression parenth = - (PsiParenthesizedExpression)factory.createExpressionFromText("((" + type.getCanonicalText() + ")expr)", null); - //noinspection ConstantConditions - ((PsiTypeCastExpression)parenth.getExpression()).getOperand().replace(myElement); - parenth = (PsiParenthesizedExpression)JavaCodeStyleManager.getInstance(project).shortenClassReferences(parenth); - PsiExpression expr = (PsiExpression)myElement.replace(parenth); - TextRange range = expr.getTextRange(); - myEditor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); - myEditor.getCaretModel().moveToOffset(range.getEndOffset()); - myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - } - catch (IncorrectOperationException e) { - // OK here. Can be caused by invalid type like one for proxy starts with . '.Proxy34' - } - finally { - release(); - } - } - }.execute(); + DebuggerInvocationUtil.invokeLater(project, () -> new WriteCommandAction(project, CodeInsightBundle.message("command.name.surround.with.runtime.cast")) { + protected void run(@NotNull Result result) throws Throwable { + try { + PsiElementFactory factory = JavaPsiFacade.getInstance(myElement.getProject()).getElementFactory(); + PsiParenthesizedExpression parenth = + (PsiParenthesizedExpression)factory.createExpressionFromText("((" + type.getCanonicalText() + ")expr)", null); + //noinspection ConstantConditions + ((PsiTypeCastExpression)parenth.getExpression()).getOperand().replace(myElement); + parenth = (PsiParenthesizedExpression)JavaCodeStyleManager.getInstance(project).shortenClassReferences(parenth); + PsiExpression expr = (PsiExpression)myElement.replace(parenth); + TextRange range = expr.getTextRange(); + myEditor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); + myEditor.getCaretModel().moveToOffset(range.getEndOffset()); + myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + } + catch (IncorrectOperationException e) { + // OK here. Can be caused by invalid type like one for proxy starts with . '.Proxy34' + } + finally { + release(); + } } - }, myProgressIndicator.getModalityState()); + }.execute(), myProgressIndicator.getModalityState()); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java index d588c64ae600..d86b1ca245b7 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java @@ -334,13 +334,10 @@ public class DebugProcessEvents extends DebugProcessImpl { myDebugProcessDispatcher.getMulticaster().processAttached(this); // breakpoints should be initialized after all processAttached listeners work - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - XDebugSession session = getSession().getXDebugSession(); - if (session != null) { - session.initBreakpoints(); - } + ApplicationManager.getApplication().runReadAction(() -> { + XDebugSession session = getSession().getXDebugSession(); + if (session != null) { + session.initBreakpoints(); } }); @@ -462,13 +459,10 @@ public class DebugProcessEvents extends DebugProcessImpl { LOG.debug(ex.getMessage()); } final boolean[] considerRequestHit = new boolean[]{true}; - DebuggerInvocationUtil.invokeAndWait(getProject(), new Runnable() { - @Override - public void run() { - final String displayName = requestor instanceof Breakpoint? ((Breakpoint)requestor).getDisplayName() : requestor.getClass().getSimpleName(); - final String message = DebuggerBundle.message("error.evaluating.breakpoint.condition.or.action", displayName, ex.getMessage()); - considerRequestHit[0] = Messages.showYesNoDialog(getProject(), message, ex.getTitle(), Messages.getQuestionIcon()) == Messages.YES; - } + DebuggerInvocationUtil.invokeAndWait(getProject(), () -> { + final String displayName = requestor instanceof Breakpoint? ((Breakpoint)requestor).getDisplayName() : requestor.getClass().getSimpleName(); + final String message = DebuggerBundle.message("error.evaluating.breakpoint.condition.or.action", displayName, ex.getMessage()); + considerRequestHit[0] = Messages.showYesNoDialog(getProject(), message, ex.getTitle(), Messages.getQuestionIcon()) == Messages.YES; }, ModalityState.NON_MODAL); requestHit = considerRequestHit[0]; resumePreferred = !requestHit; @@ -476,15 +470,12 @@ public class DebugProcessEvents extends DebugProcessImpl { if (requestHit && requestor instanceof Breakpoint) { // if requestor is a breakpoint and this breakpoint was hit, no matter its suspend policy - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - XDebugSession session = getSession().getXDebugSession(); - if (session != null) { - XBreakpoint breakpoint = ((Breakpoint)requestor).getXBreakpoint(); - if (breakpoint != null) { - ((XDebugSessionImpl)session).processDependencies(breakpoint); - } + ApplicationManager.getApplication().runReadAction(() -> { + XDebugSession session = getSession().getXDebugSession(); + if (session != null) { + XBreakpoint breakpoint = ((Breakpoint)requestor).getXBreakpoint(); + if (breakpoint != null) { + ((XDebugSessionImpl)session).processDependencies(breakpoint); } } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java index e331359ab13d..1a16a3b1c150 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java @@ -597,12 +597,7 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb public void showStatusText(final String text) { if (!myStatusUpdateAlarm.isDisposed()) { myStatusUpdateAlarm.cancelAllRequests(); - myStatusUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - StatusBarUtil.setStatusBarInfo(myProject, text); - } - }, 50); + myStatusUpdateAlarm.addRequest(() -> StatusBarUtil.setStatusBarInfo(myProject, text), 50); } } @@ -637,15 +632,10 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb private void checkVirtualMachineVersion(VirtualMachine vm) { final String version = vm.version(); if ("1.4.0".equals(version)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMessageDialog( - getProject(), - DebuggerBundle.message("warning.jdk140.unstable"), DebuggerBundle.message("title.jdk140.unstable"), Messages.getWarningIcon() - ); - } - }); + SwingUtilities.invokeLater(() -> Messages.showMessageDialog( + getProject(), + DebuggerBundle.message("warning.jdk140.unstable"), DebuggerBundle.message("title.jdk140.unstable"), Messages.getWarningIcon() + )); } } @@ -1053,74 +1043,71 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb final int invokePolicy = getInvokePolicy(context); final Exception[] exception = new Exception[1]; final Value[] result = new Value[1]; - getManagerThread().startLongProcessAndFork(new Runnable() { - @Override - public void run() { - ThreadReferenceProxyImpl thread = context.getThread(); + getManagerThread().startLongProcessAndFork(() -> { + ThreadReferenceProxyImpl thread = context.getThread(); + try { try { - try { - if (LOG.isDebugEnabled()) { - final VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy(); - virtualMachineProxy.logThreads(); - LOG.debug("Invoke in " + thread.name()); - assertThreadSuspended(thread, context); - } + if (LOG.isDebugEnabled()) { + final VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy(); + virtualMachineProxy.logThreads(); + LOG.debug("Invoke in " + thread.name()); + assertThreadSuspended(thread, context); + } - if (myMethod.isVarArgs()) { - // See IDEA-63581 - // if vararg parameter array is of interface type and Object[] is expected, JDI wrap it into another array, - // in this case we have to unroll the array manually and pass its elements to the method instead of array object - int lastIndex = myArgs.size() - 1; - if (lastIndex >= 0) { - final Object lastArg = myArgs.get(lastIndex); - if (lastArg instanceof ArrayReference) { - final ArrayReference arrayRef = (ArrayReference)lastArg; - if (((ArrayType)arrayRef.referenceType()).componentType() instanceof InterfaceType) { - List argTypes = myMethod.argumentTypeNames(); - if (argTypes.size() > lastIndex && argTypes.get(lastIndex).startsWith(CommonClassNames.JAVA_LANG_OBJECT)) { - // unwrap array of interfaces for vararg param - myArgs.remove(lastIndex); - myArgs.addAll(arrayRef.getValues()); - } + if (myMethod.isVarArgs()) { + // See IDEA-63581 + // if vararg parameter array is of interface type and Object[] is expected, JDI wrap it into another array, + // in this case we have to unroll the array manually and pass its elements to the method instead of array object + int lastIndex = myArgs.size() - 1; + if (lastIndex >= 0) { + final Object lastArg = myArgs.get(lastIndex); + if (lastArg instanceof ArrayReference) { + final ArrayReference arrayRef = (ArrayReference)lastArg; + if (((ArrayType)arrayRef.referenceType()).componentType() instanceof InterfaceType) { + List argTypes = myMethod.argumentTypeNames(); + if (argTypes.size() > lastIndex && argTypes.get(lastIndex).startsWith(CommonClassNames.JAVA_LANG_OBJECT)) { + // unwrap array of interfaces for vararg param + myArgs.remove(lastIndex); + myArgs.addAll(arrayRef.getValues()); } } } } - - if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) { - // ensure args are not collected - for (Object arg : myArgs) { - if (arg instanceof ObjectReference) { - DebuggerUtilsEx.disableCollection((ObjectReference)arg); - } - } - } - - // workaround for jdi hang in trace mode - if (!StringUtil.isEmpty(ourTrace)) { - for (Object arg : myArgs) { - //noinspection ResultOfMethodCallIgnored - arg.toString(); - } - } - - result[0] = invokeMethod(invokePolicy, myMethod, myArgs); } - finally { - // assertThreadSuspended(thread, context); - if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) { - // ensure args are not collected - for (Object arg : myArgs) { - if (arg instanceof ObjectReference) { - DebuggerUtilsEx.enableCollection((ObjectReference)arg); - } + + if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) { + // ensure args are not collected + for (Object arg : myArgs) { + if (arg instanceof ObjectReference) { + DebuggerUtilsEx.disableCollection((ObjectReference)arg); + } + } + } + + // workaround for jdi hang in trace mode + if (!StringUtil.isEmpty(ourTrace)) { + for (Object arg : myArgs) { + //noinspection ResultOfMethodCallIgnored + arg.toString(); + } + } + + result[0] = invokeMethod(invokePolicy, myMethod, myArgs); + } + finally { + // assertThreadSuspended(thread, context); + if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) { + // ensure args are not collected + for (Object arg : myArgs) { + if (arg instanceof ObjectReference) { + DebuggerUtilsEx.enableCollection((ObjectReference)arg); } } } } - catch (Exception e) { - exception[0] = e; - } + } + catch (Exception e) { + exception[0] = e; } }); @@ -1651,18 +1638,15 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb super.contextAction(); } else { - DebuggerInvocationUtil.swingInvokeLater(myProject, new Runnable() { - @Override - public void run() { - Messages.showErrorDialog( - DebuggerBundle.message("error.running.to.cursor.no.executable.code", - myRunToCursorBreakpoint.getSourcePosition().getFile().getName(), - myRunToCursorBreakpoint.getLineIndex() + 1), - UIUtil.removeMnemonic(ActionsBundle.actionText(XDebuggerActions.RUN_TO_CURSOR))); - DebuggerSession session = debugProcess.getSession(); - session.getContextManager().setState(DebuggerContextUtil.createDebuggerContext(session, context), - DebuggerSession.State.PAUSED, DebuggerSession.Event.CONTEXT, null); - } + DebuggerInvocationUtil.swingInvokeLater(myProject, () -> { + Messages.showErrorDialog( + DebuggerBundle.message("error.running.to.cursor.no.executable.code", + myRunToCursorBreakpoint.getSourcePosition().getFile().getName(), + myRunToCursorBreakpoint.getLineIndex() + 1), + UIUtil.removeMnemonic(ActionsBundle.actionText(XDebuggerActions.RUN_TO_CURSOR))); + DebuggerSession session = debugProcess.getSession(); + session.getContextManager().setState(DebuggerContextUtil.createDebuggerContext(session, context), + DebuggerSession.State.PAUSED, DebuggerSession.Event.CONTEXT, null); }); } } @@ -1827,12 +1811,7 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb } if (myStackFrame.isBottom()) { - DebuggerInvocationUtil.swingInvokeLater(myProject, new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(myProject, DebuggerBundle.message("error.pop.bottom.stackframe"), ActionsBundle.actionText(DebuggerActions.POP_FRAME), Messages.getErrorIcon()); - } - }); + DebuggerInvocationUtil.swingInvokeLater(myProject, () -> Messages.showMessageDialog(myProject, DebuggerBundle.message("error.pop.bottom.stackframe"), ActionsBundle.actionText(DebuggerActions.POP_FRAME), Messages.getErrorIcon())); return; } @@ -1840,12 +1819,8 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb thread.popFrames(myStackFrame); } catch (final EvaluateException e) { - DebuggerInvocationUtil.swingInvokeLater(myProject, new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(myProject, DebuggerBundle.message("error.pop.stackframe", e.getLocalizedMessage()), ActionsBundle.actionText(DebuggerActions.POP_FRAME), Messages.getErrorIcon()); - } - }); + DebuggerInvocationUtil.swingInvokeLater(myProject, + () -> Messages.showMessageDialog(myProject, DebuggerBundle.message("error.pop.stackframe", e.getLocalizedMessage()), ActionsBundle.actionText(DebuggerActions.POP_FRAME), Messages.getErrorIcon())); LOG.info(e); } finally { @@ -1992,15 +1967,12 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb } else { fail(); - DebuggerInvocationUtil.swingInvokeLater(myProject, new Runnable() { - @Override - public void run() { - // propagate exception only in case we succeeded to obtain execution result, - // otherwise if the error is induced by the fact that there is nothing to debug, and there is no need to show - // this problem to the user - if (myExecutionResult != null || !connectorIsReady.get()) { - ExecutionUtil.handleExecutionError(myProject, ToolWindowId.DEBUG, sessionName, e); - } + DebuggerInvocationUtil.swingInvokeLater(myProject, () -> { + // propagate exception only in case we succeeded to obtain execution result, + // otherwise if the error is induced by the fact that there is nothing to debug, and there is no need to show + // this problem to the user + if (myExecutionResult != null || !connectorIsReady.get()) { + ExecutionUtil.handleExecutionError(myProject, ToolWindowId.DEBUG, sessionName, e); } }); break; @@ -2014,17 +1986,12 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb if (vm != null) { final VirtualMachine vm1 = vm; - afterProcessStarted(new Runnable() { + afterProcessStarted(() -> getManagerThread().schedule(new DebuggerCommandImpl() { @Override - public void run() { - getManagerThread().schedule(new DebuggerCommandImpl() { - @Override - protected void action() throws Exception { - commitVM(vm1); - } - }); + protected void action() throws Exception { + commitVM(vm1); } - }); + })); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebuggerManagerThreadImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebuggerManagerThreadImpl.java index 76d3affd8c0f..db1ea7abe60f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebuggerManagerThreadImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebuggerManagerThreadImpl.java @@ -111,31 +111,28 @@ public class DebuggerManagerThreadImpl extends InvokeAndWaitThread { + try { + if (currentCommand == myEvents.getCurrentEvent()) { + // if current command is still in progress, cancel it + getCurrentRequest().requestStop(); + try { + getCurrentRequest().join(); + } + catch (InterruptedException ignored) { + } + catch (Exception e) { + throw new RuntimeException(e); + } + finally { + if (!myDisposed) { + startNewWorkerThread(); } } } - finally { - Disposer.dispose(alarm); - } + } + finally { + Disposer.dispose(alarm); } }, terminateTimeout); } @@ -175,17 +172,8 @@ public class DebuggerManagerThreadImpl extends InvokeAndWaitThread ProgressManager.getInstance().runProcess(() -> invokeAndWait(command), progressWindow)); } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java index 4610d4b85104..d1c3a52f4d08 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaDebuggerEvaluator.java @@ -108,20 +108,17 @@ public class JavaDebuggerEvaluator extends XDebuggerEvaluator { @Override public TextRange getExpressionRangeAtOffset(final Project project, final Document document, final int offset, final boolean sideEffectsAllowed) { final Ref currentRange = Ref.create(null); - PsiDocumentManager.getInstance(project).commitAndRunReadAction(new Runnable() { - @Override - public void run() { - try { - PsiElement elementAtCursor = DebuggerUtilsEx.findElementAt(PsiDocumentManager.getInstance(project).getPsiFile(document), offset); - if (elementAtCursor == null || !elementAtCursor.isValid()) { - return; - } - Pair pair = findExpression(elementAtCursor, sideEffectsAllowed); - if (pair != null) { - currentRange.set(pair.getSecond()); - } - } catch (IndexNotReadyException ignored) {} - } + PsiDocumentManager.getInstance(project).commitAndRunReadAction(() -> { + try { + PsiElement elementAtCursor = DebuggerUtilsEx.findElementAt(PsiDocumentManager.getInstance(project).getPsiFile(document), offset); + if (elementAtCursor == null || !elementAtCursor.isValid()) { + return; + } + Pair pair = findExpression(elementAtCursor, sideEffectsAllowed); + if (pair != null) { + currentRange.set(pair.getSecond()); + } + } catch (IndexNotReadyException ignored) {} }); return currentRange.get(); } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java index fa73416618d0..c1f23635ff67 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaStackFrame.java @@ -282,11 +282,8 @@ public class JavaStackFrame extends XStackFrame { final SourcePosition sourcePosition = debuggerContext.getSourcePosition(); final Map visibleVariables = ContainerUtil.map2Map(getVisibleVariables(), - new Function>() { - @Override - public Pair fun(LocalVariableProxyImpl var) { - return Pair.create(var.name(), var); - } + var -> { + return Pair.create(var.name(), var); }); Pair, Set> usedVars = EMPTY_USED_VARS; diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java index c3eaa34e2059..9e6e545a63a3 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaValue.java @@ -439,19 +439,16 @@ public class JavaValue extends XNamedValue implements NodeDescriptorProvider, XV @Override public void contextAction() throws Exception { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - SourcePosition position = SourcePositionProvider.getSourcePosition(myValueDescriptor, getProject(), getDebuggerContext(), false); + ApplicationManager.getApplication().runReadAction(() -> { + SourcePosition position = SourcePositionProvider.getSourcePosition(myValueDescriptor, getProject(), getDebuggerContext(), false); + if (position != null) { + navigatable.setSourcePosition(DebuggerUtilsEx.toXSourcePosition(position)); + } + if (inline) { + position = SourcePositionProvider.getSourcePosition(myValueDescriptor, getProject(), getDebuggerContext(), true); if (position != null) { navigatable.setSourcePosition(DebuggerUtilsEx.toXSourcePosition(position)); } - if (inline) { - position = SourcePositionProvider.getSourcePosition(myValueDescriptor, getProject(), getDebuggerContext(), true); - if (position != null) { - navigatable.setSourcePosition(DebuggerUtilsEx.toXSourcePosition(position)); - } - } } }); } @@ -491,11 +488,8 @@ public class JavaValue extends XNamedValue implements NodeDescriptorProvider, XV @Override protected void doAction(@Nullable final SourcePosition sourcePosition) { if (sourcePosition != null) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - navigatable.setSourcePosition(DebuggerUtilsEx.toXSourcePosition(sourcePosition)); - } + ApplicationManager.getApplication().runReadAction(() -> { + navigatable.setSourcePosition(DebuggerUtilsEx.toXSourcePosition(sourcePosition)); }); } } @@ -618,12 +612,9 @@ public class JavaValue extends XNamedValue implements NodeDescriptorProvider, XV public void reBuild(final XValueNodeImpl node) { DebuggerManagerThreadImpl.assertIsManagerThread(); myCurrentChildrenStart = 0; - node.getTree().getLaterInvocator().offer(new Runnable() { - @Override - public void run() { - node.clearChildren(); - computePresentation(node, XValuePlace.TREE); - } + node.getTree().getLaterInvocator().offer(() -> { + node.clearChildren(); + computePresentation(node, XValuePlace.TREE); }); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/JavaValueModifier.java b/java/debugger/impl/src/com/intellij/debugger/engine/JavaValueModifier.java index 4be3d1a80986..93d2d6ea3734 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/JavaValueModifier.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/JavaValueModifier.java @@ -91,12 +91,10 @@ public abstract class JavaValueModifier extends XValueModifier { //} // protected static void update(final DebuggerContextImpl context) { - DebuggerInvocationUtil.swingInvokeLater(context.getProject(), new Runnable() { - public void run() { - final DebuggerSession session = context.getDebuggerSession(); - if (session != null) { - session.refresh(false); - } + DebuggerInvocationUtil.swingInvokeLater(context.getProject(), () -> { + final DebuggerSession session = context.getDebuggerSession(); + if (session != null) { + session.refresh(false); } }); //node.setState(context); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java index afdecfdf3802..72cb73568322 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java @@ -194,15 +194,12 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio int lambdaOrdinal = -1; if (LambdaMethodFilter.isLambdaName(method.name())) { Set lambdas = - ContainerUtil.map2SetNotNull(locationsOfLine(location.declaringType(), sourcePosition), new Function() { - @Override - public Method fun(Location location) { - Method method = location.method(); - if (LambdaMethodFilter.isLambdaName(method.name())) { - return method; - } - return null; + ContainerUtil.map2SetNotNull(locationsOfLine(location.declaringType(), sourcePosition), location1 -> { + Method method1 = location1.method(); + if (LambdaMethodFilter.isLambdaName(method1.name())) { + return method1; } + return null; }); if (lambdas.size() > 1) { ArrayList lambdasList = new ArrayList<>(lambdas); @@ -417,36 +414,31 @@ public class PositionManagerImpl implements PositionManager, MultiRequestPositio final Ref classAtPositionRef = new Ref<>(null); final Ref isLocalOrAnonymous = new Ref<>(Boolean.FALSE); final Ref requiredDepth = new Ref<>(0); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - classAtPositionRef.set(psiClass); - String className = JVMNameUtil.getNonAnonymousClassName(psiClass); - if (className == null) { - isLocalOrAnonymous.set(Boolean.TRUE); - final PsiClass topLevelClass = JVMNameUtil.getTopLevelParentClass(psiClass); - if (topLevelClass != null) { - final String parentClassName = JVMNameUtil.getNonAnonymousClassName(topLevelClass); - if (parentClassName != null) { - requiredDepth.set(getNestingDepth(psiClass)); - baseClassNameRef.set(parentClassName); - } - } - else { - final StringBuilder sb = new StringBuilder(); - PsiTreeUtil.treeWalkUp(psiClass, null, new PairProcessor() { - @Override - public boolean process(PsiElement element, PsiElement element2) { - sb.append('\n').append(element); - return true; - } - }); - LOG.info("Local or anonymous class " + psiClass + " has no non-local parent, parents:" + sb); + ApplicationManager.getApplication().runReadAction(() -> { + classAtPositionRef.set(psiClass); + String className = JVMNameUtil.getNonAnonymousClassName(psiClass); + if (className == null) { + isLocalOrAnonymous.set(Boolean.TRUE); + final PsiClass topLevelClass = JVMNameUtil.getTopLevelParentClass(psiClass); + if (topLevelClass != null) { + final String parentClassName = JVMNameUtil.getNonAnonymousClassName(topLevelClass); + if (parentClassName != null) { + requiredDepth.set(getNestingDepth(psiClass)); + baseClassNameRef.set(parentClassName); } } else { - baseClassNameRef.set(className); + final StringBuilder sb = new StringBuilder(); + PsiTreeUtil.treeWalkUp(psiClass, null, (element, element2) -> { + sb.append('\n').append(element); + return true; + }); + LOG.info("Local or anonymous class " + psiClass + " has no non-local parent, parents:" + sb); } } + else { + baseClassNameRef.set(className); + } }); final String className = baseClassNameRef.get(); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java index 384928766380..8c2e101ac155 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/SuspendContextImpl.java @@ -267,14 +267,11 @@ public abstract class SuspendContextImpl extends XSuspendContext implements Susp }); } - private static final Comparator THREADS_COMPARATOR = new Comparator() { - @Override - public int compare(JavaExecutionStack th1, JavaExecutionStack th2) { - int res = Comparing.compare(th2.getThreadProxy().isSuspended(), th1.getThreadProxy().isSuspended()); - if (res == 0) { - return th1.getDisplayName().compareToIgnoreCase(th2.getDisplayName()); - } - return res; + private static final Comparator THREADS_COMPARATOR = (th1, th2) -> { + int res = Comparing.compare(th2.getThreadProxy().isSuspended(), th1.getThreadProxy().isSuspended()); + if (res == 0) { + return th1.getDisplayName().compareToIgnoreCase(th2.getDisplayName()); } + return res; }; } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java index 830ecbb70a63..5ef52db0834e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/DefaultCodeFragmentFactory.java @@ -75,43 +75,41 @@ public class DefaultCodeFragmentFactory extends CodeFragmentFactory { fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE); //noinspection HardCodedStringLiteral fragment.putUserData(KEY, "DebuggerComboBoxEditor.IS_DEBUGGER_EDITOR"); - fragment.putCopyableUserData(JavaCompletionUtil.DYNAMIC_TYPE_EVALUATOR, new PairFunction() { - public PsiType fun(PsiExpression expression, CompletionParameters parameters) { - if (!RuntimeTypeEvaluator.isSubtypeable(expression)) { - return null; - } + fragment.putCopyableUserData(JavaCompletionUtil.DYNAMIC_TYPE_EVALUATOR, (expression, parameters) -> { + if (!RuntimeTypeEvaluator.isSubtypeable(expression)) { + return null; + } - if (parameters.getInvocationCount() <= 1 && JavaCompletionUtil.mayHaveSideEffects(expression)) { - final CompletionService service = CompletionService.getCompletionService(); - if (parameters.getInvocationCount() < 2) { - service.setAdvertisementText("Invoke completion once more to see runtime type variants"); - } - return null; - } - - final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(project).getContext(); - DebuggerSession debuggerSession = debuggerContext.getDebuggerSession(); - if (debuggerSession != null && debuggerContext.getSuspendContext() != null) { - final Semaphore semaphore = new Semaphore(); - semaphore.down(); - final AtomicReference nameRef = new AtomicReference<>(); - final RuntimeTypeEvaluator worker = - new RuntimeTypeEvaluator(null, expression, debuggerContext, ProgressManager.getInstance().getProgressIndicator()) { - @Override - protected void typeCalculationFinished(@Nullable PsiType type) { - nameRef.set(type); - semaphore.up(); - } - }; - debuggerSession.getProcess().getManagerThread().invoke(worker); - for (int i = 0; i < 50; i++) { - ProgressManager.checkCanceled(); - if (semaphore.waitFor(20)) break; - } - return nameRef.get(); + if (parameters.getInvocationCount() <= 1 && JavaCompletionUtil.mayHaveSideEffects(expression)) { + final CompletionService service = CompletionService.getCompletionService(); + if (parameters.getInvocationCount() < 2) { + service.setAdvertisementText("Invoke completion once more to see runtime type variants"); } return null; } + + final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(project).getContext(); + DebuggerSession debuggerSession = debuggerContext.getDebuggerSession(); + if (debuggerSession != null && debuggerContext.getSuspendContext() != null) { + final Semaphore semaphore = new Semaphore(); + semaphore.down(); + final AtomicReference nameRef = new AtomicReference<>(); + final RuntimeTypeEvaluator worker = + new RuntimeTypeEvaluator(null, expression, debuggerContext, ProgressManager.getInstance().getProgressIndicator()) { + @Override + protected void typeCalculationFinished(@Nullable PsiType type) { + nameRef.set(type); + semaphore.up(); + } + }; + debuggerSession.getProcess().getManagerThread().invoke(worker); + for (int i = 0; i < 50; i++) { + ProgressManager.checkCanceled(); + if (semaphore.waitFor(20)) break; + } + return nameRef.get(); + } + return null; }); return fragment; diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java index 10380971cf3b..4aa7d2d690a7 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java @@ -165,14 +165,11 @@ public final class DebuggerContextImpl implements DebuggerContext { } if (myFrameProxy != null) { - PsiDocumentManager.getInstance(getProject()).commitAndRunReadAction(new Runnable() { - @Override - public void run() { - if (mySourcePosition == null) { - mySourcePosition = ContextUtil.getSourcePosition(DebuggerContextImpl.this); - } - myContextElement = ContextUtil.getContextElement(mySourcePosition); + PsiDocumentManager.getInstance(getProject()).commitAndRunReadAction(() -> { + if (mySourcePosition == null) { + mySourcePosition = ContextUtil.getSourcePosition(DebuggerContextImpl.this); } + myContextElement = ContextUtil.getContextElement(mySourcePosition); }); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java index 0a7bf12aa608..e031aac98a93 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextUtil.java @@ -57,12 +57,9 @@ public class DebuggerContextUtil { SuspendManagerUtil.findContextByThread(session.getProcess().getSuspendManager(), stackFrame.threadProxy()); final DebuggerContextImpl newContext = DebuggerContextImpl.createDebuggerContext(session, threadSuspendContext, stackFrame.threadProxy(), stackFrame); - DebuggerInvocationUtil.swingInvokeLater(session.getProject(), new Runnable() { - @Override - public void run() { - manager.setState(newContext, session.getState(), DebuggerSession.Event.REFRESH, null); - SourceCodeChecker.checkSource(newContext); - } + DebuggerInvocationUtil.swingInvokeLater(session.getProject(), () -> { + manager.setState(newContext, session.getState(), DebuggerSession.Event.REFRESH, null); + SourceCodeChecker.checkSource(newContext); }); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerManagerImpl.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerManagerImpl.java index 37f52a4c8506..4694f9f4ac9f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerManagerImpl.java @@ -279,12 +279,9 @@ public class DebuggerManagerImpl extends DebuggerManagerEx implements Persistent // if processWillTerminate() is called from AWT thread debugProcess.waitFor() will block it and the whole app will hang if (!DebuggerManagerThreadImpl.isManagerThread()) { if (SwingUtilities.isEventDispatchThread()) { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true); - debugProcess.waitFor(10000); - } + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + ProgressManager.getInstance().getProgressIndicator().setIndeterminate(true); + debugProcess.waitFor(10000); }, "Waiting For Debugger Response", false, debugProcess.getProject()); } else { @@ -514,43 +511,39 @@ public class DebuggerManagerImpl extends DebuggerManagerEx implements Persistent } final String _debuggeeRunProperties = debuggeeRunProperties; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - @SuppressWarnings({"HardCodedStringLiteral"}) - public void run() { - JavaSdkUtil.addRtJar(parameters.getClassPath()); + ApplicationManager.getApplication().runReadAction(() -> { + JavaSdkUtil.addRtJar(parameters.getClassPath()); - final Sdk jdk = parameters.getJdk(); - final boolean forceClassicVM = shouldForceClassicVM(jdk); - final boolean forceNoJIT = shouldForceNoJIT(jdk); - final String debugKey = System.getProperty(DEBUG_KEY_NAME, "-Xdebug"); - final boolean needDebugKey = shouldAddXdebugKey(jdk) || !"-Xdebug".equals(debugKey) /*the key is non-standard*/; + final Sdk jdk = parameters.getJdk(); + final boolean forceClassicVM = shouldForceClassicVM(jdk); + final boolean forceNoJIT = shouldForceNoJIT(jdk); + final String debugKey = System.getProperty(DEBUG_KEY_NAME, "-Xdebug"); + final boolean needDebugKey = shouldAddXdebugKey(jdk) || !"-Xdebug".equals(debugKey) /*the key is non-standard*/; - if (forceClassicVM || forceNoJIT || needDebugKey || !isJVMTIAvailable(jdk)) { - parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "-Xrunjdwp:" + _debuggeeRunProperties); - } - else { - // use newer JVMTI if available - parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", ""); - parameters.getVMParametersList().replaceOrPrepend("-agentlib:jdwp=", "-agentlib:jdwp=" + _debuggeeRunProperties); - } - - if (forceNoJIT) { - parameters.getVMParametersList().replaceOrPrepend("-Djava.compiler=", "-Djava.compiler=NONE"); - parameters.getVMParametersList().replaceOrPrepend("-Xnoagent", "-Xnoagent"); - } - - if (needDebugKey) { - parameters.getVMParametersList().replaceOrPrepend(debugKey, debugKey); - } - else { - // deliberately skip outdated parameter because it can disable full-speed debugging for some jdk builds - // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6272174 - parameters.getVMParametersList().replaceOrPrepend("-Xdebug", ""); - } - - parameters.getVMParametersList().replaceOrPrepend("-classic", forceClassicVM ? "-classic" : ""); + if (forceClassicVM || forceNoJIT || needDebugKey || !isJVMTIAvailable(jdk)) { + parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "-Xrunjdwp:" + _debuggeeRunProperties); } + else { + // use newer JVMTI if available + parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", ""); + parameters.getVMParametersList().replaceOrPrepend("-agentlib:jdwp=", "-agentlib:jdwp=" + _debuggeeRunProperties); + } + + if (forceNoJIT) { + parameters.getVMParametersList().replaceOrPrepend("-Djava.compiler=", "-Djava.compiler=NONE"); + parameters.getVMParametersList().replaceOrPrepend("-Xnoagent", "-Xnoagent"); + } + + if (needDebugKey) { + parameters.getVMParametersList().replaceOrPrepend(debugKey, debugKey); + } + else { + // deliberately skip outdated parameter because it can disable full-speed debugging for some jdk builds + // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6272174 + parameters.getVMParametersList().replaceOrPrepend("-Xdebug", ""); + } + + parameters.getVMParametersList().replaceOrPrepend("-classic", forceClassicVM ? "-classic" : ""); }); return new RemoteConnection(useSockets, "127.0.0.1", address, debuggerInServerMode); diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java index db892fdfbbcb..7e9f568978a4 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java @@ -152,20 +152,17 @@ public class DebuggerSession implements AbstractDebuggerSession { ApplicationManager.getApplication().assertIsDispatchThread(); final DebuggerSession session = context.getDebuggerSession(); LOG.assertTrue(session == DebuggerSession.this || session == null); - final Runnable setStateRunnable = new Runnable() { - @Override - public void run() { - LOG.assertTrue(myDebuggerContext.isInitialised()); - myDebuggerContext = context; - if (LOG.isDebugEnabled()) { - LOG.debug("DebuggerSession state = " + state + ", event = " + event); - } - - myIsEvaluating = false; - - myState = new DebuggerSessionState(state, description); - fireStateChanged(context, event); + final Runnable setStateRunnable = () -> { + LOG.assertTrue(myDebuggerContext.isInitialised()); + myDebuggerContext = context; + if (LOG.isDebugEnabled()) { + LOG.debug("DebuggerSession state = " + state + ", event = " + event); } + + myIsEvaluating = false; + + myState = new DebuggerSessionState(state, description); + fireStateChanged(context, event); }; if(context.getSuspendContext() == null) { @@ -388,12 +385,8 @@ public class DebuggerSession implements AbstractDebuggerSession { public void dispose() { getProcess().dispose(); Disposer.dispose(myUpdateAlarm); - DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { - @Override - public void run() { - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.DISPOSED, Event.DISPOSE, null); - } - }); + DebuggerInvocationUtil.swingInvokeLater(getProject(), + () -> getContextManager().setState(SESSION_EMPTY_CONTEXT, State.DISPOSED, Event.DISPOSE, null)); } // ManagerCommands @@ -450,16 +443,13 @@ public class DebuggerSession implements AbstractDebuggerSession { //executed in manager thread @Override public void connectorIsReady() { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - RemoteConnection connection = myDebugProcess.getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); - final String connectionStatusMessage = connection.isServerMode() ? DebuggerBundle.message("status.listening", addressDisplayName, transportName) : DebuggerBundle.message("status.connecting", addressDisplayName, transportName); - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAITING_ATTACH, - Event.START_WAIT_ATTACH, connectionStatusMessage); - } + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + RemoteConnection connection = myDebugProcess.getConnection(); + final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); + final String transportName = DebuggerBundle.getTransportName(connection); + final String connectionStatusMessage = connection.isServerMode() ? DebuggerBundle.message("status.listening", addressDisplayName, transportName) : DebuggerBundle.message("status.connecting", addressDisplayName, transportName); + getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAITING_ATTACH, + Event.START_WAIT_ATTACH, connectionStatusMessage); }); } @@ -470,12 +460,7 @@ public class DebuggerSession implements AbstractDebuggerSession { ThreadReferenceProxyImpl currentThread = suspendContext.getThread(); if (!shouldSetAsActiveContext(suspendContext)) { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - getContextManager().fireStateChanged(getContextManager().getContext(), Event.THREADS_REFRESH); - } - }); + DebuggerInvocationUtil.invokeLater(getProject(), () -> getContextManager().fireStateChanged(getContextManager().getContext(), Event.THREADS_REFRESH)); ThreadReferenceProxyImpl thread = suspendContext.getThread(); if (thread != null) { List> descriptors = DebuggerUtilsEx.getEventDescriptors(suspendContext); @@ -494,12 +479,8 @@ public class DebuggerSession implements AbstractDebuggerSession { final DebuggerContextImpl debuggerContext = DebuggerContextUtil.createDebuggerContext(DebuggerSession.this, suspendContext); - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE, null); - } - }); + DebuggerInvocationUtil.invokeLater(getProject(), + () -> getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE, null)); } }); } @@ -633,12 +614,7 @@ public class DebuggerSession implements AbstractDebuggerSession { debuggerContext.setPositionCache(position); } - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE, getDescription(debuggerContext)); - } - }); + DebuggerInvocationUtil.invokeLater(getProject(), () -> getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE, getDescription(debuggerContext))); } private boolean shouldSetAsActiveContext(final SuspendContextImpl suspendContext) { @@ -677,15 +653,12 @@ public class DebuggerSession implements AbstractDebuggerSession { null) : null; - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - if (debuggerContext != null) { - getContextManager().setState(debuggerContext, State.PAUSED, Event.CONTEXT, getDescription(debuggerContext)); - } - else { - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.CONTEXT, null); - } + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + if (debuggerContext != null) { + getContextManager().setState(debuggerContext, State.PAUSED, Event.CONTEXT, getDescription(debuggerContext)); + } + else { + getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.CONTEXT, null); } }); } @@ -698,26 +671,19 @@ public class DebuggerSession implements AbstractDebuggerSession { final String message = DebuggerBundle.message("status.connected", addressDisplayName, transportName); process.printToConsole(message + "\n"); - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.ATTACHED, message); - } - }); + DebuggerInvocationUtil.invokeLater(getProject(), + () -> getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.ATTACHED, message)); } @Override public void attachException(final RunProfileState state, final ExecutionException exception, final RemoteConnection remoteConnection) { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - String message = ""; - if (state instanceof RemoteState) { - message = DebuggerBundle.message("status.connect.failed", DebuggerBundle.getAddressDisplayName(remoteConnection), DebuggerBundle.getTransportName(remoteConnection)); - } - message += exception.getMessage(); - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, message); + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + String message = ""; + if (state instanceof RemoteState) { + message = DebuggerBundle.message("status.connect.failed", DebuggerBundle.getAddressDisplayName(remoteConnection), DebuggerBundle.getTransportName(remoteConnection)); } + message += exception.getMessage(); + getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, message); }); } @@ -732,15 +698,12 @@ public class DebuggerSession implements AbstractDebuggerSession { processHandler.notifyTextAvailable(DebuggerBundle.message("status.disconnected", addressDisplayName, transportName) + "\n", ProcessOutputTypes.SYSTEM); } } - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - final RemoteConnection connection = getProcess().getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, - DebuggerBundle.message("status.disconnected", addressDisplayName, transportName)); - } + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + final RemoteConnection connection = getProcess().getConnection(); + final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); + final String transportName = DebuggerBundle.getTransportName(connection); + getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, + DebuggerBundle.message("status.disconnected", addressDisplayName, transportName)); }); clearSteppingThrough(); } @@ -766,12 +729,9 @@ public class DebuggerSession implements AbstractDebuggerSession { private void notifyThreadsRefresh() { if (!myUpdateAlarm.isDisposed()) { myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - final DebuggerStateManager contextManager = getContextManager(); - contextManager.fireStateChanged(contextManager.getContext(), Event.THREADS_REFRESH); - } + myUpdateAlarm.addRequest(() -> { + final DebuggerStateManager contextManager = getContextManager(); + contextManager.fireStateChanged(contextManager.getContext(), Event.THREADS_REFRESH); }, 100, ModalityState.NON_MODAL); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java index c9553e460e90..ed49db4d7934 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsEx.java @@ -933,12 +933,8 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils { return getContainingMethod(position.getElementAt()); } - public static final Comparator LAMBDA_ORDINAL_COMPARATOR = new Comparator() { - @Override - public int compare(Method m1, Method m2) { - return LambdaMethodFilter.getLambdaOrdinal(m1.name()) - LambdaMethodFilter.getLambdaOrdinal(m2.name()); - } - }; + public static final Comparator LAMBDA_ORDINAL_COMPARATOR = + (m1, m2) -> LambdaMethodFilter.getLambdaOrdinal(m1.name()) - LambdaMethodFilter.getLambdaOrdinal(m2.name()); public static void disableCollection(ObjectReference reference) { try { diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java b/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java index 7f12d75fd127..f1a7e7e43e3e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java @@ -74,12 +74,10 @@ public class HotSwapManager extends AbstractProjectComponent { final Map modifiedClasses = new HashMap<>(); final List outputRoots = new ArrayList<>(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final List allDirs = OrderEnumerator.orderEntries(myProject).withoutSdk().withoutLibraries().getPathsList().getRootDirs(); - for (VirtualFile dir : allDirs) { - outputRoots.add(new File(dir.getPath())); - } + ApplicationManager.getApplication().runReadAction(() -> { + final List allDirs = OrderEnumerator.orderEntries(myProject).withoutSdk().withoutLibraries().getPathsList().getRootDirs(); + for (VirtualFile dir : allDirs) { + outputRoots.add(new File(dir.getPath())); } }); for (File root : outputRoots) { @@ -168,11 +166,7 @@ public class HotSwapManager extends AbstractProjectComponent { final MultiProcessCommand scanClassesCommand = new MultiProcessCommand(); - swapProgress.setCancelWorker(new Runnable() { - public void run() { - scanClassesCommand.cancel(); - } - }); + swapProgress.setCancelWorker(() -> scanClassesCommand.cancel()); for (final DebuggerSession debuggerSession : sessions) { if (debuggerSession.isAttached()) { @@ -204,11 +198,7 @@ public class HotSwapManager extends AbstractProjectComponent { public static void reloadModifiedClasses(final Map> modifiedClasses, final HotSwapProgress reloadClassesProgress) { final MultiProcessCommand reloadClassesCommand = new MultiProcessCommand(); - reloadClassesProgress.setCancelWorker(new Runnable() { - public void run() { - reloadClassesCommand.cancel(); - } - }); + reloadClassesProgress.setCancelWorker(() -> reloadClassesCommand.cancel()); for (final DebuggerSession debuggerSession : modifiedClasses.keySet()) { reloadClassesCommand.addCommand(debuggerSession.getProcess(), new DebuggerCommandImpl() { diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java b/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java index 64a560affa41..b3a3cd01416f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java @@ -180,31 +180,29 @@ class ReloadClassesWorker { final Semaphore waitSemaphore = new Semaphore(); waitSemaphore.down(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - try { - if (!project.isDisposed()) { - final BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager(); - breakpointManager.reloadBreakpoints(); - debugProcess.getRequestsManager().clearWarnings(); - if (LOG.isDebugEnabled()) { - LOG.debug("requests updated"); - LOG.debug("time stamp set"); - } - myDebuggerSession.refresh(false); + SwingUtilities.invokeLater(() -> { + try { + if (!project.isDisposed()) { + final BreakpointManager breakpointManager1 = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager(); + breakpointManager1.reloadBreakpoints(); + debugProcess.getRequestsManager().clearWarnings(); + if (LOG.isDebugEnabled()) { + LOG.debug("requests updated"); + LOG.debug("time stamp set"); + } + myDebuggerSession.refresh(false); - XDebugSession session = myDebuggerSession.getXDebugSession(); - if (session != null) { - session.rebuildViews(); - } + XDebugSession session = myDebuggerSession.getXDebugSession(); + if (session != null) { + session.rebuildViews(); } } - catch (Throwable e) { - LOG.error(e); - } - finally { - waitSemaphore.up(); - } + } + catch (Throwable e) { + LOG.error(e); + } + finally { + waitSemaphore.up(); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/jdi/DecompiledLocalVariable.java b/java/debugger/impl/src/com/intellij/debugger/jdi/DecompiledLocalVariable.java index 3809313d006a..0ec16bc8b16a 100644 --- a/java/debugger/impl/src/com/intellij/debugger/jdi/DecompiledLocalVariable.java +++ b/java/debugger/impl/src/com/intellij/debugger/jdi/DecompiledLocalVariable.java @@ -27,12 +27,7 @@ import java.util.Comparator; * Date: 10/7/13 */ public class DecompiledLocalVariable{ - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(DecompiledLocalVariable v1, DecompiledLocalVariable v2) { - return v1.getSlot() - v2.getSlot(); - } - }; + public static final Comparator COMPARATOR = (v1, v2) -> v1.getSlot() - v2.getSlot(); private final int mySlot; private final String mySignature; diff --git a/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java b/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java index a4fba5a9f5ec..4cb81a717955 100644 --- a/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java @@ -46,15 +46,12 @@ public final class ThreadReferenceProxyImpl extends ObjectReferenceProxyImpl imp private ThreadGroupReferenceProxyImpl myThreadGroupProxy; - public static final Comparator ourComparator = new Comparator() { - @Override - public int compare(ThreadReferenceProxyImpl th1, ThreadReferenceProxyImpl th2) { - int res = Comparing.compare(th2.isSuspended(), th1.isSuspended()); - if (res == 0) { - return th1.name().compareToIgnoreCase(th2.name()); - } - return res; + public static final Comparator ourComparator = (th1, th2) -> { + int res = Comparing.compare(th2.isSuspended(), th1.isSuspended()); + if (res == 0) { + return th1.name().compareToIgnoreCase(th2.name()); } + return res; }; public ThreadReferenceProxyImpl(VirtualMachineProxyImpl virtualMachineProxy, ThreadReference threadReference) { diff --git a/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java b/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java index 42902c4351db..d614bc060e45 100644 --- a/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java +++ b/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java @@ -198,17 +198,14 @@ class CompoundRendererConfigurable extends JPanel { } private void updateContext(final String qName) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final Project project = myProject; - final PsiClass psiClass = project != null ? DebuggerUtils.findClass(qName, project, GlobalSearchScope.allScope(project)) : null; - XSourcePositionImpl position = XSourcePositionImpl.createByElement(psiClass); - myLabelEditor.setSourcePosition(position); - myChildrenEditor.setSourcePosition(position); - myChildrenExpandedEditor.setSourcePosition(position); - myListChildrenEditor.setSourcePosition(position); - } + ApplicationManager.getApplication().runReadAction(() -> { + final Project project = myProject; + final PsiClass psiClass = project != null ? DebuggerUtils.findClass(qName, project, GlobalSearchScope.allScope(project)) : null; + XSourcePositionImpl position = XSourcePositionImpl.createByElement(psiClass); + myLabelEditor.setSourcePosition(position); + myChildrenEditor.setSourcePosition(position); + myChildrenExpandedEditor.setSourcePosition(position); + myListChildrenEditor.setSourcePosition(position); }); } @@ -515,15 +512,12 @@ class CompoundRendererConfigurable extends JPanel { private static class ClassNameEditorWithBrowseButton extends ReferenceEditorWithBrowseButton { private ClassNameEditorWithBrowseButton(ActionListener browseActionListener, final Project project) { super(browseActionListener, project, - new Function() { - @Override - public Document fun(String s) { - PsiPackage defaultPackage = JavaPsiFacade.getInstance(project).findPackage(""); - final JavaCodeFragment fragment = - JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment(s, defaultPackage, true, true); - fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE); - return PsiDocumentManager.getInstance(project).getDocument(fragment); - } + s -> { + PsiPackage defaultPackage = JavaPsiFacade.getInstance(project).findPackage(""); + final JavaCodeFragment fragment = + JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment(s, defaultPackage, true, true); + fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE); + return PsiDocumentManager.getInstance(project).getDocument(fragment); }, ""); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/AlternativeSourceNotificationProvider.java b/java/debugger/impl/src/com/intellij/debugger/ui/AlternativeSourceNotificationProvider.java index 43d5851da610..0ba1e8147345 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/AlternativeSourceNotificationProvider.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/AlternativeSourceNotificationProvider.java @@ -119,11 +119,8 @@ public class AlternativeSourceNotificationProvider extends EditorNotifications.P ComboBoxClassElement[] elems = ContainerUtil.map2Array(alts, ComboBoxClassElement.class, - new Function() { - @Override - public ComboBoxClassElement fun(PsiClass psiClass) { - return new ComboBoxClassElement((PsiClass)psiClass.getNavigationElement()); - } + psiClass -> { + return new ComboBoxClassElement((PsiClass)psiClass.getNavigationElement()); }); return new AlternativeSourceNotificationPanel(elems, baseClass, myProject, file); @@ -180,12 +177,9 @@ public class AlternativeSourceNotificationProvider extends EditorNotifications.P if (location != null) { DebuggerUtilsEx.setAlternativeSourceUrl(location.declaringType().name(), vFile.getUrl(), project); } - DebuggerUIUtil.invokeLater(new Runnable() { - @Override - public void run() { - FileEditorManager.getInstance(project).closeFile(file); - session.refresh(true); - } + DebuggerUIUtil.invokeLater(() -> { + FileEditorManager.getInstance(project).closeFile(file); + session.refresh(true); }); } }); @@ -197,16 +191,13 @@ public class AlternativeSourceNotificationProvider extends EditorNotifications.P } }); myLinksPanel.add(switcher); - createActionLabel(DebuggerBundle.message("action.disable.text"), new Runnable() { - @Override - public void run() { - DebuggerSettings.getInstance().SHOW_ALTERNATIVE_SOURCE = false; - FILE_PROCESSED_KEY.set(file, null); - FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); - FileEditor editor = fileEditorManager.getSelectedEditor(file); - if (editor != null) { - fileEditorManager.removeTopComponent(editor, AlternativeSourceNotificationPanel.this); - } + createActionLabel(DebuggerBundle.message("action.disable.text"), () -> { + DebuggerSettings.getInstance().SHOW_ALTERNATIVE_SOURCE = false; + FILE_PROCESSED_KEY.set(file, null); + FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); + FileEditor editor = fileEditorManager.getSelectedEditor(file); + if (editor != null) { + fileEditorManager.removeTopComponent(editor, AlternativeSourceNotificationPanel.this); } }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/EditorEvaluationCommand.java b/java/debugger/impl/src/com/intellij/debugger/ui/EditorEvaluationCommand.java index 76648d1aaff6..215d3c85050f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/EditorEvaluationCommand.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/EditorEvaluationCommand.java @@ -70,11 +70,7 @@ public abstract class EditorEvaluationCommand extends DebuggerContextCommandI return result; } catch (final EvaluateException e) { if (myEditor != null) { - DebuggerInvocationUtil.invokeLater(myDebuggerContext.getProject(), new Runnable() { - public void run() { - showEvaluationHint(myEditor, myElement, e); - } - }, myProgressIndicator.getModalityState()); + DebuggerInvocationUtil.invokeLater(myDebuggerContext.getProject(), () -> showEvaluationHint(myEditor, myElement, e), myProgressIndicator.getModalityState()); } throw e; } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapProgressImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapProgressImpl.java index 48341a6ca1c3..790931d85da8 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapProgressImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapProgressImpl.java @@ -136,11 +136,9 @@ public class HotSwapProgressImpl extends HotSwapProgress{ myUpdateQueue.queue(new Update("Text") { @Override public void run() { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - public void run() { - if (!myProgressWindow.isCanceled() && myProgressWindow.isRunning()) { - myProgressWindow.setText(text); - } + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + if (!myProgressWindow.isCanceled() && myProgressWindow.isRunning()) { + myProgressWindow.setText(text); } }, myProgressWindow.getModalityState()); } @@ -148,22 +146,18 @@ public class HotSwapProgressImpl extends HotSwapProgress{ } public void setTitle(final String text) { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - public void run() { - if (!myProgressWindow.isCanceled() && myProgressWindow.isRunning()) { - myProgressWindow.setTitle(text); - } + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + if (!myProgressWindow.isCanceled() && myProgressWindow.isRunning()) { + myProgressWindow.setTitle(text); } }, myProgressWindow.getModalityState()); } public void setFraction(final double v) { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - public void run() { - if (!myProgressWindow.isCanceled() && myProgressWindow.isRunning()) { - myProgressWindow.setFraction(v); - } + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + if (!myProgressWindow.isCanceled() && myProgressWindow.isRunning()) { + myProgressWindow.setFraction(v); } }, myProgressWindow.getModalityState()); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java index 83b401f2c663..498f61105d49 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java @@ -165,117 +165,102 @@ public class HotSwapUIImpl extends HotSwapUI implements ProjectComponent { findClassesProgress = createProgress ? new HotSwapProgressImpl(myProject) : null; } - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - final Map> modifiedClasses; - if (shouldPerformScan) { - modifiedClasses = scanForModifiedClassesWithProgress(sessions, findClassesProgress); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final Map> modifiedClasses; + if (shouldPerformScan) { + modifiedClasses = scanForModifiedClassesWithProgress(sessions, findClassesProgress); + } + else { + final List toScan = new ArrayList<>(); + final List toUseGenerated = new ArrayList<>(); + for (DebuggerSession session : sessions) { + (session.isModifiedClassesScanRequired() ? toScan : toUseGenerated).add(session); + session.setModifiedClassesScanRequired(false); + } + modifiedClasses = new HashMap<>(); + if (!toUseGenerated.isEmpty()) { + modifiedClasses.putAll(HotSwapManager.findModifiedClasses(toUseGenerated, generatedPaths)); + } + if (!toScan.isEmpty()) { + modifiedClasses.putAll(scanForModifiedClassesWithProgress(toScan, findClassesProgress)); + } + } + + final Application application = ApplicationManager.getApplication(); + if (modifiedClasses.isEmpty()) { + final String message = DebuggerBundle.message("status.hotswap.uptodate"); + HotSwapProgressImpl.NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION).notify(myProject); + return; + } + + application.invokeLater(() -> { + if (shouldAskBeforeHotswap && !DebuggerSettings.RUN_HOTSWAP_ALWAYS.equals(runHotswap)) { + final RunHotswapDialog dialog = new RunHotswapDialog(myProject, sessions, shouldDisplayHangWarning); + if (!dialog.showAndGet()) { + for (DebuggerSession session : modifiedClasses.keySet()) { + session.setModifiedClassesScanRequired(true); + } + return; + } + final Set toReload = new HashSet<>(dialog.getSessionsToReload()); + for (DebuggerSession session : modifiedClasses.keySet()) { + if (!toReload.contains(session)) { + session.setModifiedClassesScanRequired(true); + } + } + modifiedClasses.keySet().retainAll(toReload); } else { - final List toScan = new ArrayList<>(); - final List toUseGenerated = new ArrayList<>(); - for (DebuggerSession session : sessions) { - (session.isModifiedClassesScanRequired() ? toScan : toUseGenerated).add(session); - session.setModifiedClassesScanRequired(false); - } - modifiedClasses = new HashMap<>(); - if (!toUseGenerated.isEmpty()) { - modifiedClasses.putAll(HotSwapManager.findModifiedClasses(toUseGenerated, generatedPaths)); - } - if (!toScan.isEmpty()) { - modifiedClasses.putAll(scanForModifiedClassesWithProgress(toScan, findClassesProgress)); - } - } - - final Application application = ApplicationManager.getApplication(); - if (modifiedClasses.isEmpty()) { - final String message = DebuggerBundle.message("status.hotswap.uptodate"); - HotSwapProgressImpl.NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION).notify(myProject); - return; - } - - application.invokeLater(new Runnable() { - public void run() { - if (shouldAskBeforeHotswap && !DebuggerSettings.RUN_HOTSWAP_ALWAYS.equals(runHotswap)) { - final RunHotswapDialog dialog = new RunHotswapDialog(myProject, sessions, shouldDisplayHangWarning); - if (!dialog.showAndGet()) { - for (DebuggerSession session : modifiedClasses.keySet()) { - session.setModifiedClassesScanRequired(true); - } - return; + if (shouldDisplayHangWarning) { + final int answer = Messages.showCheckboxMessageDialog( + DebuggerBundle.message("hotswap.dialog.hang.warning"), + DebuggerBundle.message("hotswap.dialog.title"), + new String[]{"Perform &Reload Classes", "&Skip Reload Classes"}, + CommonBundle.message("dialog.options.do.not.show"), + false, 1, 1, Messages.getWarningIcon(), + (exitCode, cb) -> { + settings.HOTSWAP_HANG_WARNING_ENABLED = !cb.isSelected(); + return exitCode == DialogWrapper.OK_EXIT_CODE ? exitCode : DialogWrapper.CANCEL_EXIT_CODE; } - final Set toReload = new HashSet<>(dialog.getSessionsToReload()); + ); + if (answer == DialogWrapper.CANCEL_EXIT_CODE) { for (DebuggerSession session : modifiedClasses.keySet()) { - if (!toReload.contains(session)) { - session.setModifiedClassesScanRequired(true); - } + session.setModifiedClassesScanRequired(true); } - modifiedClasses.keySet().retainAll(toReload); - } - else { - if (shouldDisplayHangWarning) { - final int answer = Messages.showCheckboxMessageDialog( - DebuggerBundle.message("hotswap.dialog.hang.warning"), - DebuggerBundle.message("hotswap.dialog.title"), - new String[]{"Perform &Reload Classes", "&Skip Reload Classes"}, - CommonBundle.message("dialog.options.do.not.show"), - false, 1, 1, Messages.getWarningIcon(), - new PairFunction() { - @Override - public Integer fun(Integer exitCode, JCheckBox cb) { - settings.HOTSWAP_HANG_WARNING_ENABLED = !cb.isSelected(); - return exitCode == DialogWrapper.OK_EXIT_CODE ? exitCode : DialogWrapper.CANCEL_EXIT_CODE; - } - } - ); - if (answer == DialogWrapper.CANCEL_EXIT_CODE) { - for (DebuggerSession session : modifiedClasses.keySet()) { - session.setModifiedClassesScanRequired(true); - } - return; - } - } - } - - if (!modifiedClasses.isEmpty()) { - final HotSwapProgressImpl progress = new HotSwapProgressImpl(myProject); - if (modifiedClasses.keySet().size() == 1) { - progress.setSessionToRestartOnFail(ContainerUtil.getFirstItem(modifiedClasses.keySet())); - } - application.executeOnPooledThread(new Runnable() { - public void run() { - reloadModifiedClasses(modifiedClasses, progress); - } - }); + return; } } - }, ModalityState.NON_MODAL); - } + } + + if (!modifiedClasses.isEmpty()) { + final HotSwapProgressImpl progress = new HotSwapProgressImpl(myProject); + if (modifiedClasses.keySet().size() == 1) { + progress.setSessionToRestartOnFail(ContainerUtil.getFirstItem(modifiedClasses.keySet())); + } + application.executeOnPooledThread(() -> reloadModifiedClasses(modifiedClasses, progress)); + } + }, ModalityState.NON_MODAL); }); } private static Map> scanForModifiedClassesWithProgress(final List sessions, final HotSwapProgressImpl progress) { final Ref>> result = Ref.create(null); - ProgressManager.getInstance().runProcess(new Runnable() { - public void run() { - try { - result.set(HotSwapManager.scanForModifiedClasses(sessions, progress)); - } - finally { - progress.finished(); - } + ProgressManager.getInstance().runProcess(() -> { + try { + result.set(HotSwapManager.scanForModifiedClasses(sessions, progress)); + } + finally { + progress.finished(); } }, progress.getProgressIndicator()); return result.get(); } private static void reloadModifiedClasses(final Map> modifiedClasses, final HotSwapProgressImpl progress) { - ProgressManager.getInstance().runProcess(new Runnable() { - public void run() { - HotSwapManager.reloadModifiedClasses(modifiedClasses, progress); - progress.finished(); - } + ProgressManager.getInstance().runProcess(() -> { + HotSwapManager.reloadModifiedClasses(modifiedClasses, progress); + progress.finished(); }, progress.getProgressIndicator()); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/RunHotswapDialog.java b/java/debugger/impl/src/com/intellij/debugger/ui/RunHotswapDialog.java index fcf1dada1633..29a362802a76 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/RunHotswapDialog.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/RunHotswapDialog.java @@ -53,11 +53,7 @@ public class RunHotswapDialog extends OptionsDialog { for (DebuggerSession session : sessions) { items.add(new SessionItem(session)); } - Collections.sort(items, new Comparator() { - public int compare(SessionItem debuggerSession, SessionItem debuggerSession1) { - return debuggerSession.getSession().getSessionName().compareTo(debuggerSession1.getSession().getSessionName()); - } - }); + Collections.sort(items, (debuggerSession, debuggerSession1) -> debuggerSession.getSession().getSessionName().compareTo(debuggerSession1.getSession().getSessionName())); myElementsChooser = new ElementsChooser<>(items, true); myPanel.setBorder(IdeBorderFactory.createEmptyBorder(10, 0, 5, 0)); //myElementsChooser.setBorder(IdeBorderFactory.createEmptyBorder(5, 0, 0, 0)); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/ValueHint.java b/java/debugger/impl/src/com/intellij/debugger/ui/ValueHint.java index 9034e5c82b13..ebac8ed49565 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/ValueHint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/ValueHint.java @@ -174,12 +174,7 @@ public class ValueHint extends AbstractValueHint { private void createAndShowTree(final String expressionText, final NodeDescriptorImpl descriptor) { final DebuggerTreeCreatorImpl creator = new DebuggerTreeCreatorImpl(getProject()); - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - showTreePopup(creator, Pair.create(descriptor, expressionText)); - } - }); + DebuggerInvocationUtil.invokeLater(getProject(), () -> showTreePopup(creator, Pair.create(descriptor, expressionText))); } private static boolean isActiveTooltipApplicable(final Value value) { @@ -187,41 +182,35 @@ public class ValueHint extends AbstractValueHint { } private void showHint(final SimpleColoredText text, final WatchItemDescriptor descriptor) { - DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { - @Override - public void run() { - if(!isHintHidden()) { - JComponent component; - if (!isActiveTooltipApplicable(descriptor.getValue())) { - component = HintUtil.createInformationLabel(text); - } - else { - component = createExpandableHintComponent(text, new Runnable() { - @Override - public void run() { - final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(getProject()).getContext(); - final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess(); - debugProcess.getManagerThread().schedule(new DebuggerContextCommandImpl(debuggerContext) { + DebuggerInvocationUtil.invokeLater(getProject(), () -> { + if(!isHintHidden()) { + JComponent component; + if (!isActiveTooltipApplicable(descriptor.getValue())) { + component = HintUtil.createInformationLabel(text); + } + else { + component = createExpandableHintComponent(text, () -> { + final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(getProject()).getContext(); + final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess(); + debugProcess.getManagerThread().schedule(new DebuggerContextCommandImpl(debuggerContext) { + @Override + public void threadAction() { + descriptor.setRenderer(debugProcess.getAutoRenderer(descriptor)); + final String expressionText = ApplicationManager.getApplication().runReadAction(new Computable() { @Override - public void threadAction() { - descriptor.setRenderer(debugProcess.getAutoRenderer(descriptor)); - final String expressionText = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public String compute() { - return myCurrentExpression.getText(); - } - }); - - createAndShowTree(expressionText, descriptor); + public String compute() { + return myCurrentExpression.getText(); } }); - } - }); - } - if (!showHint(component)) return; - if(getType() == ValueHintType.MOUSE_CLICK_HINT) { - HintUtil.createInformationLabel(text).requestFocusInWindow(); - } + + createAndShowTree(expressionText, descriptor); + } + }); + }); + } + if (!showHint(component)) return; + if(getType() == ValueHintType.MOUSE_CLICK_HINT) { + HintUtil.createInformationLabel(text).requestFocusInWindow(); } } }); @@ -257,80 +246,77 @@ public class ValueHint extends AbstractValueHint { final Ref currentRange = Ref.create(null); final Ref preCalculatedValue = Ref.create(null); - PsiDocumentManager.getInstance(project).commitAndRunReadAction(new Runnable() { - @Override - public void run() { - // Point -> offset - final int offset = calculateOffset(editor, point); + PsiDocumentManager.getInstance(project).commitAndRunReadAction(() -> { + // Point -> offset + final int offset = calculateOffset(editor, point); - PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); + PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); - if(psiFile == null || !psiFile.isValid()) { + if(psiFile == null || !psiFile.isValid()) { + return; + } + + int selectionStart = editor.getSelectionModel().getSelectionStart(); + int selectionEnd = editor.getSelectionModel().getSelectionEnd(); + + if((type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT) && (selectionStart <= offset && offset <= selectionEnd)) { + PsiElement ctx = (selectionStart > 0) ? psiFile.findElementAt(selectionStart - 1) : psiFile.findElementAt(selectionStart); + try { + String text = editor.getSelectionModel().getSelectedText(); + if(text != null && ctx != null) { + final JVMElementFactory factory = JVMElementFactories.getFactory(ctx.getLanguage(), project); + if (factory == null) { + return; + } + selectedExpression.set(factory.createExpressionFromText(text, ctx)); + currentRange.set(new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd())); + } + } + catch (IncorrectOperationException ignored) { + } + } + + if(currentRange.get() == null) { + PsiElement elementAtCursor = psiFile.findElementAt(offset); + if (elementAtCursor == null) { return; } - - int selectionStart = editor.getSelectionModel().getSelectionStart(); - int selectionEnd = editor.getSelectionModel().getSelectionEnd(); - - if((type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT) && (selectionStart <= offset && offset <= selectionEnd)) { - PsiElement ctx = (selectionStart > 0) ? psiFile.findElementAt(selectionStart - 1) : psiFile.findElementAt(selectionStart); - try { - String text = editor.getSelectionModel().getSelectedText(); - if(text != null && ctx != null) { - final JVMElementFactory factory = JVMElementFactories.getFactory(ctx.getLanguage(), project); - if (factory == null) { - return; - } - selectedExpression.set(factory.createExpressionFromText(text, ctx)); - currentRange.set(new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd())); - } - } - catch (IncorrectOperationException ignored) { - } - } - - if(currentRange.get() == null) { - PsiElement elementAtCursor = psiFile.findElementAt(offset); - if (elementAtCursor == null) { - return; - } - Pair pair = findExpression(elementAtCursor, type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT); - if (pair == null) { - if (type == ValueHintType.MOUSE_OVER_HINT) { - final DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(project).getContext().getDebuggerSession(); - if(debuggerSession != null && debuggerSession.isPaused()) { - final Pair lastExecuted = debuggerSession.getProcess().getLastExecutedMethod(); - if (lastExecuted != null) { - final Method method = lastExecuted.getFirst(); - if (method != null) { - final Pair expressionPair = findExpression(elementAtCursor, true); - if (expressionPair != null && expressionPair.getFirst() instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expressionPair.getFirst(); - final PsiMethod psiMethod = methodCallExpression.resolveMethod(); - if (psiMethod != null) { - final JVMName jvmSignature = JVMNameUtil.getJVMSignature(psiMethod); - try { - if (method.name().equals(psiMethod.getName()) && method.signature().equals(jvmSignature.getName(debuggerSession.getProcess()))) { - pair = expressionPair; - preCalculatedValue.set(lastExecuted.getSecond()); - } - } - catch (EvaluateException ignored) { + Pair pair = findExpression(elementAtCursor, type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT); + if (pair == null) { + if (type == ValueHintType.MOUSE_OVER_HINT) { + final DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(project).getContext().getDebuggerSession(); + if(debuggerSession != null && debuggerSession.isPaused()) { + final Pair lastExecuted = debuggerSession.getProcess().getLastExecutedMethod(); + if (lastExecuted != null) { + final Method method = lastExecuted.getFirst(); + if (method != null) { + final Pair expressionPair = findExpression(elementAtCursor, true); + if (expressionPair != null && expressionPair.getFirst() instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expressionPair.getFirst(); + final PsiMethod psiMethod = methodCallExpression.resolveMethod(); + if (psiMethod != null) { + final JVMName jvmSignature = JVMNameUtil.getJVMSignature(psiMethod); + try { + if (method.name().equals(psiMethod.getName()) && method.signature().equals(jvmSignature.getName(debuggerSession.getProcess()))) { + pair = expressionPair; + preCalculatedValue.set(lastExecuted.getSecond()); } } + catch (EvaluateException ignored) { + } } } } } } } - if (pair == null) { - return; - } - selectedExpression.set(pair.getFirst()); - currentRange.set(pair.getSecond()); } + if (pair == null) { + return; + } + selectedExpression.set(pair.getFirst()); + currentRange.set(pair.getSecond()); } }); return Trinity.create(selectedExpression.get(), currentRange.get(), preCalculatedValue.get()); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java index 90a21b251329..f51e194a24b4 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java @@ -435,12 +435,7 @@ public abstract class Breakpoint

implements } private void removeBreakpoint() { - AppUIUtil.invokeOnEdt(new Runnable() { - @Override - public void run() { - DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().removeBreakpoint(Breakpoint.this); - } - }); + AppUIUtil.invokeOnEdt(() -> DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().removeBreakpoint(Breakpoint.this)); debugProcess.removeDebugProcessListener(this); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java index 71a885c85552..581d5ec6744b 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java @@ -303,35 +303,29 @@ public abstract class BreakpointWithHighlighter

{ + if (!isValid()) { + return; + } - DebuggerContextImpl context = DebuggerManagerEx.getInstanceEx(project).getContext(); - final DebugProcessImpl debugProcess = context.getDebugProcess(); - if (debugProcess == null || !debugProcess.isAttached()) { - updateCaches(null); - updateGutter(); - } - else { - debugProcess.getManagerThread().invoke(new DebuggerCommandImpl() { - @Override - protected void action() throws Exception { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - updateCaches(debugProcess); - } - } - }); - DebuggerInvocationUtil.swingInvokeLater(project, BreakpointWithHighlighter.this::updateGutter); - } - }); - } + DebuggerContextImpl context = DebuggerManagerEx.getInstanceEx(project).getContext(); + final DebugProcessImpl debugProcess = context.getDebugProcess(); + if (debugProcess == null || !debugProcess.isAttached()) { + updateCaches(null); + updateGutter(); + } + else { + debugProcess.getManagerThread().invoke(new DebuggerCommandImpl() { + @Override + protected void action() throws Exception { + ApplicationManager.getApplication().runReadAction(() -> { + if (!project.isDisposed()) { + updateCaches(debugProcess); + } + }); + DebuggerInvocationUtil.swingInvokeLater(project, BreakpointWithHighlighter.this::updateGutter); + } + }); } }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpoint.java index e2d960eea928..44a004a47adb 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpoint.java @@ -345,16 +345,13 @@ public class FieldBreakpoint extends BreakpointWithHighlighter() { - @Override - public boolean process(PsiElement element) { - PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class, false); - if(field != null) { - fld[0] = field; - return false; - } - return true; + XDebuggerUtil.getInstance().iterateLine(project, document, line, element1 -> { + PsiField field1 = PsiTreeUtil.getParentOfType(element1, PsiField.class, false); + if(field1 != null) { + fld[0] = field1; + return false; } + return true; }); field = fld[0]; } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaFieldBreakpointType.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaFieldBreakpointType.java index af6ac86965dd..d40bc8023c8c 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaFieldBreakpointType.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaFieldBreakpointType.java @@ -146,13 +146,10 @@ public class JavaFieldBreakpointType extends JavaLineBreakpointTypeBase fieldBreakpoint = XDebuggerManager.getInstance(project).getBreakpointManager() - .addLineBreakpoint(JavaFieldBreakpointType.this, psiFile.getVirtualFile().getUrl(), line, new JavaFieldBreakpointProperties(fieldName, className)); - result.set(fieldBreakpoint); - } + ApplicationManager.getApplication().runWriteAction(() -> { + XLineBreakpoint fieldBreakpoint = XDebuggerManager.getInstance(project).getBreakpointManager() + .addLineBreakpoint(JavaFieldBreakpointType.this, psiFile.getVirtualFile().getUrl(), line, new JavaFieldBreakpointProperties(fieldName, className)); + result.set(fieldBreakpoint); }); return true; } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointTypeBase.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointTypeBase.java index 6d10ff718ce3..b536d1ee83e1 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointTypeBase.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/JavaLineBreakpointTypeBase.java @@ -95,56 +95,53 @@ public abstract class JavaLineBreakpointTypeBase

> result = Ref.create(); - XDebuggerUtil.getInstance().iterateLine(project, document, line, new Processor() { - @Override - public boolean process(PsiElement element) { - // avoid comments - if ((element instanceof PsiWhiteSpace) - || (PsiTreeUtil.getParentOfType(element, PsiComment.class, PsiImportStatementBase.class, PsiPackageStatement.class) != null)) { - return true; - } - PsiElement parent = element; - while(element != null) { - // skip modifiers - if (element instanceof PsiModifierList) { - element = element.getParent(); - continue; - } - - final int offset = element.getTextOffset(); - if (offset >= 0) { - if (document.getLineNumber(offset) != line) { - break; - } - } - parent = element; - element = element.getParent(); - } - - if(parent instanceof PsiMethod) { - if (parent.getTextRange().getEndOffset() >= document.getLineEndOffset(line)) { - PsiCodeBlock body = ((PsiMethod)parent).getBody(); - if (body != null) { - PsiStatement[] statements = body.getStatements(); - if (statements.length > 0 && document.getLineNumber(statements[0].getTextOffset()) == line) { - result.set(JavaLineBreakpointType.class); - } - } - } - if (result.isNull()) { - result.set(JavaMethodBreakpointType.class); - } - } - else if (parent instanceof PsiField) { - if (result.isNull()) { - result.set(JavaFieldBreakpointType.class); - } - } - else { - result.set(JavaLineBreakpointType.class); - } + XDebuggerUtil.getInstance().iterateLine(project, document, line, element -> { + // avoid comments + if ((element instanceof PsiWhiteSpace) + || (PsiTreeUtil.getParentOfType(element, PsiComment.class, PsiImportStatementBase.class, PsiPackageStatement.class) != null)) { return true; } + PsiElement parent = element; + while(element != null) { + // skip modifiers + if (element instanceof PsiModifierList) { + element = element.getParent(); + continue; + } + + final int offset = element.getTextOffset(); + if (offset >= 0) { + if (document.getLineNumber(offset) != line) { + break; + } + } + parent = element; + element = element.getParent(); + } + + if(parent instanceof PsiMethod) { + if (parent.getTextRange().getEndOffset() >= document.getLineEndOffset(line)) { + PsiCodeBlock body = ((PsiMethod)parent).getBody(); + if (body != null) { + PsiStatement[] statements = body.getStatements(); + if (statements.length > 0 && document.getLineNumber(statements[0].getTextOffset()) == line) { + result.set(JavaLineBreakpointType.class); + } + } + } + if (result.isNull()) { + result.set(JavaMethodBreakpointType.class); + } + } + else if (parent instanceof PsiField) { + if (result.isNull()) { + result.set(JavaFieldBreakpointType.class); + } + } + else { + result.set(JavaLineBreakpointType.class); + } + return true; }); return result.get() == getClass(); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java index b3dd75bb6d78..e9bc4509f5b6 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java @@ -486,40 +486,37 @@ public class LineBreakpoint

extends Breakpoi PsiDocumentManager.getInstance(project).commitDocument(document); final boolean[] canAdd = new boolean[]{false}; - XDebuggerUtil.getInstance().iterateLine(project, document, lineIndex, new Processor() { - @Override - public boolean process(PsiElement element) { - if ((element instanceof PsiWhiteSpace) || (PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null)) { - return true; - } - PsiElement child = element; - while(element != null) { + XDebuggerUtil.getInstance().iterateLine(project, document, lineIndex, element -> { + if ((element instanceof PsiWhiteSpace) || (PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null)) { + return true; + } + PsiElement child = element; + while(element != null) { - final int offset = element.getTextOffset(); - if (offset >= 0) { - if (document.getLineNumber(offset) != lineIndex) { - break; - } + final int offset = element.getTextOffset(); + if (offset >= 0) { + if (document.getLineNumber(offset) != lineIndex) { + break; } - child = element; - element = element.getParent(); } + child = element; + element = element.getParent(); + } - if(child instanceof PsiMethod && child.getTextRange().getEndOffset() >= document.getLineEndOffset(lineIndex)) { - PsiCodeBlock body = ((PsiMethod)child).getBody(); - if(body == null) { - canAdd[0] = false; - } - else { - PsiStatement[] statements = body.getStatements(); - canAdd[0] = statements.length > 0 && document.getLineNumber(statements[0].getTextOffset()) == lineIndex; - } + if(child instanceof PsiMethod && child.getTextRange().getEndOffset() >= document.getLineEndOffset(lineIndex)) { + PsiCodeBlock body = ((PsiMethod)child).getBody(); + if(body == null) { + canAdd[0] = false; } else { - canAdd[0] = true; + PsiStatement[] statements = body.getStatements(); + canAdd[0] = statements.length > 0 && document.getLineNumber(statements[0].getTextOffset()) == lineIndex; } - return false; } + else { + canAdd[0] = true; + } + return false; }); return canAdd[0]; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreePanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreePanel.java index af717ceeee0e..d5664b7e8732 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreePanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreePanel.java @@ -41,19 +41,16 @@ import java.awt.*; public abstract class DebuggerTreePanel extends UpdatableDebuggerView implements DataProvider, Disposable { public static final DataKey DATA_KEY = DataKey.create("DebuggerPanel"); - private final SingleAlarm myRebuildAlarm = new SingleAlarm(new Runnable() { - @Override - public void run() { - try { - final DebuggerContextImpl context = getContext(); - if(context.getDebuggerSession() != null) { - getTree().rebuild(context); - } + private final SingleAlarm myRebuildAlarm = new SingleAlarm(() -> { + try { + final DebuggerContextImpl context = getContext(); + if(context.getDebuggerSession() != null) { + getTree().rebuild(context); } - catch (VMDisconnectedException ignored) { - } - } + catch (VMDisconnectedException ignored) { + } + }, 100); protected DebuggerTree myTree; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/InspectDebuggerTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/InspectDebuggerTree.java index 275e08b55e99..0da35f320358 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/InspectDebuggerTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/InspectDebuggerTree.java @@ -73,15 +73,13 @@ public class InspectDebuggerTree extends DebuggerTree{ public void threadAction() { final DebuggerTreeNodeImpl node = getNodeFactory().createNode(myInspectDescriptor, context.createEvaluationContext()); - DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { - public void run() { - DebuggerTreeNodeImpl root = (DebuggerTreeNodeImpl) getModel().getRoot(); - root.removeAllChildren(); + DebuggerInvocationUtil.swingInvokeLater(getProject(), () -> { + DebuggerTreeNodeImpl root = (DebuggerTreeNodeImpl) getModel().getRoot(); + root.removeAllChildren(); - root.add(node); - treeChanged(); - root.getTree().expandRow(0); - } + root.add(node); + treeChanged(); + root.getTree().expandRow(0); }); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/ThreadsDebuggerTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/ThreadsDebuggerTree.java index 6e4da1c03257..43d3941b1c10 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/ThreadsDebuggerTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/ThreadsDebuggerTree.java @@ -172,13 +172,11 @@ public class ThreadsDebuggerTree extends DebuggerTree { groups = Collections.emptyList(); } - DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { - public void run() { - getMutableModel().setRoot(root); - treeChanged(); - if (hasThreadToSelect) { - selectThread(groups, suspendContextThread, true); - } + DebuggerInvocationUtil.swingInvokeLater(getProject(), () -> { + getMutableModel().setRoot(root); + treeChanged(); + if (hasThreadToSelect) { + selectThread(groups, suspendContextThread, true); } }); } @@ -214,11 +212,7 @@ public class ThreadsDebuggerTree extends DebuggerTree { private void removeListener() { final TreeModelAdapter listener = this; - SwingUtilities.invokeLater(new Runnable() { - public void run() { - getModel().removeTreeModelListener(listener); - } - }); + SwingUtilities.invokeLater(() -> getModel().removeTreeModelListener(listener)); } public void treeStructureChanged(TreeModelEvent event) { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/TipManager.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/TipManager.java index 7cc7cdbb47e0..82e7f85d0906 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/TipManager.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/TipManager.java @@ -176,12 +176,9 @@ public class TipManager implements Disposable, PopupMenuListener { private void tryTooltip(final InputEvent e, final boolean auto) { myShowAlarm.cancelAllRequests(); myHideAlarm.cancelAllRequests(); - myShowAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!myIsDisposed && !myPopupShown) { - showTooltip(e, auto); - } + myShowAlarm.addRequest(() -> { + if (!myIsDisposed && !myPopupShown) { + showTooltip(e, auto); } }, auto ? XDebuggerSettingsManager.getInstance().getDataViewSettings().getValueLookupDelay() : 10); } @@ -248,12 +245,9 @@ public class TipManager implements Disposable, PopupMenuListener { myTipPopup = null; myCurrentTooltip = null; } else { - myHideAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myInsideComponent) { - hideTooltip(true); - } + myHideAlarm.addRequest(() -> { + if (myInsideComponent) { + hideTooltip(true); } }, 100); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java index d7fa265556b8..f73350ab0bb1 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java @@ -432,15 +432,12 @@ public abstract class DebuggerTree extends DebuggerTreeBase implements DataProvi } protected void updateUI(final boolean scrollToVisible) { - DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { - @Override - public void run() { - myNode.removeAllChildren(); - for (DebuggerTreeNodeImpl debuggerTreeNode : myChildren) { - myNode.add(debuggerTreeNode); - } - myNode.childrenChanged(scrollToVisible); + DebuggerInvocationUtil.swingInvokeLater(getProject(), () -> { + myNode.removeAllChildren(); + for (DebuggerTreeNodeImpl debuggerTreeNode : myChildren) { + myNode.add(debuggerTreeNode); } + myNode.childrenChanged(scrollToVisible); }); } } @@ -567,15 +564,12 @@ public abstract class DebuggerTree extends DebuggerTreeBase implements DataProvi } catch (ObjectCollectedException e) { final String message = e.getMessage(); - DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { - @Override - public void run() { - node.removeAllChildren(); - node.add(getNodeFactory().createMessageNode( - new MessageDescriptor(DebuggerBundle.message("error.cannot.build.node.children.object.collected", message))) - ); - node.childrenChanged(false); - } + DebuggerInvocationUtil.swingInvokeLater(getProject(), () -> { + node.removeAllChildren(); + node.add(getNodeFactory().createMessageNode( + new MessageDescriptor(DebuggerBundle.message("error.cannot.build.node.children.object.collected", message))) + ); + node.childrenChanged(false); }); } } @@ -734,15 +728,12 @@ public abstract class DebuggerTree extends DebuggerTreeBase implements DataProvi } protected void updateUI(final boolean scrollToVisible) { - DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { - @Override - public void run() { - myNode.removeAllChildren(); - for (DebuggerTreeNodeImpl debuggerTreeNode : myChildren) { - myNode.add(debuggerTreeNode); - } - myNode.childrenChanged(scrollToVisible); + DebuggerInvocationUtil.swingInvokeLater(getProject(), () -> { + myNode.removeAllChildren(); + for (DebuggerTreeNodeImpl debuggerTreeNode : myChildren) { + myNode.add(debuggerTreeNode); } + myNode.childrenChanged(scrollToVisible); }); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java index 87b0275e9139..bc94266cf4c5 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java @@ -167,54 +167,41 @@ public class DebuggerTreeNodeImpl extends TreeBuilderNode implements DebuggerTre public void calcLabel() { final DebuggerContextImpl context = getTree().getDebuggerContext(); - update(context, new Runnable() { + update(context, () -> getDescriptor().updateRepresentation(context.createEvaluationContext(), new DescriptorLabelListener() { @Override - public void run() { - getDescriptor().updateRepresentation(context.createEvaluationContext(), new DescriptorLabelListener() { - @Override - public void labelChanged() { - updateCaches(); - DebuggerTreeNodeImpl.this.labelChanged(); - } - }); + public void labelChanged() { + updateCaches(); + DebuggerTreeNodeImpl.this.labelChanged(); } - }, true); + }), true); } public void calcRepresentation() { final DebuggerContextImpl context = getTree().getDebuggerContext(); - update(context, new Runnable() { + update(context, () -> getDescriptor().updateRepresentation(context.createEvaluationContext(), new DescriptorLabelListener() { @Override - public void run() { - getDescriptor().updateRepresentation(context.createEvaluationContext(), new DescriptorLabelListener() { - @Override - public void labelChanged() { - updateCaches(); - DebuggerTreeNodeImpl.this.labelChanged(); - } - }); + public void labelChanged() { + updateCaches(); + DebuggerTreeNodeImpl.this.labelChanged(); } - }, false); + }), false); } public void calcValue() { final DebuggerContextImpl context = getTree().getDebuggerContext(); update( context, - new Runnable() { - @Override - public void run() { - EvaluationContextImpl evaluationContext = context.createEvaluationContext(); - getDescriptor().setContext(evaluationContext); - getDescriptor().updateRepresentation(evaluationContext, new DescriptorLabelListener() { - @Override - public void labelChanged() { - updateCaches(); - DebuggerTreeNodeImpl.this.labelChanged(); - } - }); - childrenChanged(true); - } + () -> { + EvaluationContextImpl evaluationContext = context.createEvaluationContext(); + getDescriptor().setContext(evaluationContext); + getDescriptor().updateRepresentation(evaluationContext, new DescriptorLabelListener() { + @Override + public void labelChanged() { + updateCaches(); + DebuggerTreeNodeImpl.this.labelChanged(); + } + }); + childrenChanged(true); }, false); } @@ -228,22 +215,16 @@ public class DebuggerTreeNodeImpl extends TreeBuilderNode implements DebuggerTre } public void labelChanged() { - invoke(new Runnable() { - @Override - public void run() { - updateCaches(); - getTree().getMutableModel().nodeChanged(DebuggerTreeNodeImpl.this); - } + invoke(() -> { + updateCaches(); + getTree().getMutableModel().nodeChanged(DebuggerTreeNodeImpl.this); }); } public void childrenChanged(final boolean scrollToVisible) { - invoke(new Runnable() { - @Override - public void run() { - getTree().getMutableModel().nodeStructureChanged(DebuggerTreeNodeImpl.this); - getTree().restoreState(DebuggerTreeNodeImpl.this); - } + invoke(() -> { + getTree().getMutableModel().nodeStructureChanged(DebuggerTreeNodeImpl.this); + getTree().restoreState(DebuggerTreeNodeImpl.this); }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ClassObjectRenderer.java b/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ClassObjectRenderer.java index 3a6b36e860ee..030a0a18c88d 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ClassObjectRenderer.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ClassObjectRenderer.java @@ -64,20 +64,12 @@ class ClassObjectRenderer extends ToStringBasedRenderer implements FullValueEval if (res instanceof StringReference) { callback.evaluated(""); final String line = ((StringReference)res).value(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiClass psiClass = DebuggerUtils.findClass(line, - valueDescriptor.getProject(), - process.getSearchScope()); - if (psiClass != null) { - DebuggerUIUtil.invokeLater(new Runnable() { - @Override - public void run() { - psiClass.navigate(true); - } - }); - } + ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass psiClass = DebuggerUtils.findClass(line, + valueDescriptor.getProject(), + process.getSearchScope()); + if (psiClass != null) { + DebuggerUIUtil.invokeLater(() -> psiClass.navigate(true)); } }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/CustomPopupFullValueEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/CustomPopupFullValueEvaluator.java index 3c05ea06e373..fb8ad8b4605a 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/CustomPopupFullValueEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/CustomPopupFullValueEvaluator.java @@ -45,23 +45,20 @@ public abstract class CustomPopupFullValueEvaluator extends JavaValue.JavaFul @Override public void evaluate(@NotNull final XFullValueEvaluationCallback callback) { final T data = getData(); - DebuggerUIUtil.invokeLater(new Runnable() { - @Override - public void run() { - if (callback.isObsolete()) return; - final JComponent comp = createComponent(data); - Project project = getEvaluationContext().getProject(); - JBPopup popup = DebuggerUIUtil.createValuePopup(project, comp, null); - JFrame frame = WindowManager.getInstance().getFrame(project); - Dimension frameSize = frame.getSize(); - Dimension size = new Dimension(frameSize.width / 2, frameSize.height / 2); - popup.setSize(size); - if (comp instanceof Disposable) { - Disposer.register(popup, (Disposable)comp); - } - callback.evaluated(""); - popup.show(new RelativePoint(frame, new Point(size.width / 2, size.height / 2))); + DebuggerUIUtil.invokeLater(() -> { + if (callback.isObsolete()) return; + final JComponent comp = createComponent(data); + Project project = getEvaluationContext().getProject(); + JBPopup popup = DebuggerUIUtil.createValuePopup(project, comp, null); + JFrame frame = WindowManager.getInstance().getFrame(project); + Dimension frameSize = frame.getSize(); + Dimension size = new Dimension(frameSize.width / 2, frameSize.height / 2); + popup.setSize(size); + if (comp instanceof Disposable) { + Disposer.register(popup, (Disposable)comp); } + callback.evaluated(""); + popup.show(new RelativePoint(frame, new Point(size.width / 2, size.height / 2))); }); } } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/StackTraceElementObjectRenderer.java b/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/StackTraceElementObjectRenderer.java index a0388342514a..ce6e1a024f9d 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/StackTraceElementObjectRenderer.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/tree/render/StackTraceElementObjectRenderer.java @@ -63,21 +63,13 @@ class StackTraceElementObjectRenderer extends ToStringBasedRenderer implements F if (res instanceof StringReference) { callback.evaluated(""); final String line = ((StringReference)res).value(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ExceptionFilter filter = new ExceptionFilter(evaluationContext.getDebugProcess().getSession().getSearchScope()); - Filter.Result result = filter.applyFilter(line, line.length()); - if (result != null) { - final HyperlinkInfo info = result.getFirstHyperlinkInfo(); - if (info != null) { - DebuggerUIUtil.invokeLater(new Runnable() { - @Override - public void run() { - info.navigate(valueDescriptor.getProject()); - } - }); - } + ApplicationManager.getApplication().runReadAction(() -> { + ExceptionFilter filter = new ExceptionFilter(evaluationContext.getDebugProcess().getSession().getSearchScope()); + Filter.Result result = filter.applyFilter(line, line.length()); + if (result != null) { + final HyperlinkInfo info = result.getFirstHyperlinkInfo(); + if (info != null) { + DebuggerUIUtil.invokeLater(() -> info.navigate(valueDescriptor.getProject())); } } }); diff --git a/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java b/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java index c63eed7f6519..8450a2de01fb 100644 --- a/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java +++ b/java/debugger/openapi/src/com/intellij/debugger/SourcePosition.java @@ -87,14 +87,11 @@ public abstract class SourcePosition implements Navigatable{ @Override public void navigate(final boolean requestFocus) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!canNavigate()) { - return; - } - openEditor(requestFocus); + ApplicationManager.getApplication().invokeLater(() -> { + if (!canNavigate()) { + return; } + openEditor(requestFocus); }); } diff --git a/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java b/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java index 1723cb388b40..4ba10078c0ea 100644 --- a/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java +++ b/java/execution/impl/src/com/intellij/compiler/options/CompileStepBeforeRun.java @@ -141,39 +141,37 @@ public class CompileStepBeforeRun extends BeforeRunTaskProvider { + CompileScope scope; + final CompilerManager compilerManager = CompilerManager.getInstance(myProject); + if (forceMakeProject) { + // user explicitly requested whole-project make + scope = compilerManager.createProjectCompileScope(myProject); + } + else { + final Module[] modules = runConfiguration.getModules(); + if (modules.length > 0) { + for (Module module : modules) { + if (module == null) { + LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + + runConfiguration.getClass().getName()); + } + } + scope = compilerManager.createModulesCompileScope(modules, true, true); + } + else { scope = compilerManager.createProjectCompileScope(myProject); } - else { - final Module[] modules = runConfiguration.getModules(); - if (modules.length > 0) { - for (Module module : modules) { - if (module == null) { - LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + - runConfiguration.getClass().getName()); - } - } - scope = compilerManager.createModulesCompileScope(modules, true, true); - } - else { - scope = compilerManager.createProjectCompileScope(myProject); - } - } + } - if (!myProject.isDisposed()) { - scope.putUserData(RUN_CONFIGURATION, configuration); - scope.putUserData(RUN_CONFIGURATION_TYPE_ID, configuration.getType().getId()); - ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env)); - compilerManager.make(scope, callback); - } - else { - done.up(); - } + if (!myProject.isDisposed()) { + scope.putUserData(RUN_CONFIGURATION, configuration); + scope.putUserData(RUN_CONFIGURATION_TYPE_ID, configuration.getType().getId()); + ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env)); + compilerManager.make(scope, callback); + } + else { + done.up(); } }); done.waitFor(); diff --git a/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkDebuggerRunner.java b/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkDebuggerRunner.java index cdc14700c164..a3b0fdd8429d 100644 --- a/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkDebuggerRunner.java +++ b/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkDebuggerRunner.java @@ -76,16 +76,13 @@ public abstract class JavaTestFrameworkDebuggerRunner extends GenericDebuggerRun if (process == null) break; final RemoteConnection connection = new RemoteConnection(true, "127.0.0.1", String.valueOf(read), true); final DebugEnvironment env = new DefaultDebugEnvironment(environment, state, connection, true); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - ((DebugProcessImpl)process).reattach(env); - accept.getOutputStream().write(0); - } - catch (Exception e) { - e.printStackTrace(); - } + SwingUtilities.invokeLater(() -> { + try { + ((DebugProcessImpl)process).reattach(env); + accept.getOutputStream().write(0); + } + catch (Exception e) { + e.printStackTrace(); } }); read = stream.readInt(); diff --git a/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java b/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java index 7e50f1f99670..2925a8feb49c 100644 --- a/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java +++ b/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java @@ -152,12 +152,10 @@ public abstract class JavaTestFrameworkRunnableState { + root.flush(); + deleteTempFiles(); + clear(); }; UIUtil.invokeLaterIfNeeded(runnable); handler.removeProcessListener(this); diff --git a/java/execution/impl/src/com/intellij/execution/MethodListDlg.java b/java/execution/impl/src/com/intellij/execution/MethodListDlg.java index 3fbf3b5115fb..bc5c8a55b152 100644 --- a/java/execution/impl/src/com/intellij/execution/MethodListDlg.java +++ b/java/execution/impl/src/com/intellij/execution/MethodListDlg.java @@ -37,11 +37,8 @@ import java.util.Comparator; public class MethodListDlg extends DialogWrapper { private final PsiClass myClass; - private static final Comparator METHOD_NAME_COMPARATOR = new Comparator() { - public int compare(final PsiMethod psiMethod, final PsiMethod psiMethod1) { - return psiMethod.getName().compareToIgnoreCase(psiMethod1.getName()); - } - }; + private static final Comparator METHOD_NAME_COMPARATOR = + (psiMethod, psiMethod1) -> psiMethod.getName().compareToIgnoreCase(psiMethod1.getName()); private final SortedListModel myListModel = new SortedListModel(METHOD_NAME_COMPARATOR); private final JList myList = new JBList(myListModel); private final JPanel myWholePanel = new JPanel(new BorderLayout()); diff --git a/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java b/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java index 3a01aff51b21..52641f8ab4f6 100644 --- a/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java +++ b/java/execution/impl/src/com/intellij/execution/application/ApplicationRunLineMarkerProvider.java @@ -41,17 +41,9 @@ public class ApplicationRunLineMarkerProvider extends RunLineMarkerContributor { if (element instanceof PsiClass && PsiMethodUtil.findMainInClass((PsiClass)element) != null || element instanceof PsiMethod && "main".equals(((PsiMethod)element).getName()) && PsiMethodUtil.isMainMethod((PsiMethod)element)) { final AnAction[] actions = ExecutorAction.getActions(0); - return new Info(AllIcons.RunConfigurations.TestState.Run, new Function() { - @Override - public String fun(final PsiElement element) { - return StringUtil.join(ContainerUtil.mapNotNull(actions, new Function() { - @Override - public String fun(AnAction action) { - return getText(action, element); - } - }), "\n"); - } - }, actions); + return new Info(AllIcons.RunConfigurations.TestState.Run, element1 -> StringUtil.join(ContainerUtil.mapNotNull(actions, action -> { + return getText(action, element1); + }), "\n"), actions); } } return null; diff --git a/java/execution/impl/src/com/intellij/execution/filters/YourkitFilter.java b/java/execution/impl/src/com/intellij/execution/filters/YourkitFilter.java index ff0aef31f283..864ec87c56d3 100644 --- a/java/execution/impl/src/com/intellij/execution/filters/YourkitFilter.java +++ b/java/execution/impl/src/com/intellij/execution/filters/YourkitFilter.java @@ -97,16 +97,14 @@ public class YourkitFilter implements Filter{ final PopupChooserBuilder builder = new PopupChooserBuilder(list); renderer.installSpeedSearch(builder); - final Runnable runnable = new Runnable() { - public void run() { - int[] ids = list.getSelectedIndices(); - if (ids == null || ids.length == 0) return; - Object[] selectedElements = list.getSelectedValues(); - for (Object element : selectedElements) { - Navigatable descriptor = EditSourceUtil.getDescriptor((PsiElement)element); - if (descriptor != null && descriptor.canNavigate()) { - descriptor.navigate(true); - } + final Runnable runnable = () -> { + int[] ids = list.getSelectedIndices(); + if (ids == null || ids.length == 0) return; + Object[] selectedElements = list.getSelectedValues(); + for (Object element : selectedElements) { + Navigatable descriptor = EditSourceUtil.getDescriptor((PsiElement)element); + if (descriptor != null && descriptor.canNavigate()) { + descriptor.navigate(true); } } }; diff --git a/java/execution/impl/src/com/intellij/execution/impl/DefaultJavaProgramRunner.java b/java/execution/impl/src/com/intellij/execution/impl/DefaultJavaProgramRunner.java index fe5fe383dcc8..579ab6e098c0 100644 --- a/java/execution/impl/src/com/intellij/execution/impl/DefaultJavaProgramRunner.java +++ b/java/execution/impl/src/com/intellij/execution/impl/DefaultJavaProgramRunner.java @@ -194,39 +194,32 @@ public class DefaultJavaProgramRunner extends JavaPatchableProgramRunner { myProcessHandler.removeProcessListener(myListener); return; } - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - if (myProcessHandler.isProcessTerminated() || myProcessHandler.isProcessTerminating()) return; - List threadStates = null; - final long start = System.currentTimeMillis(); - while ((System.currentTimeMillis() - start) < 1000) { - final String stdout = myListener.getOutput().getStdout(); - threadStates = ThreadDumpParser.parse(stdout); - if (threadStates == null || threadStates.isEmpty()) { - TimeoutUtil.sleep(50); - threadStates = null; - continue; - } - break; - } - myProcessHandler.removeProcessListener(myListener); - if (threadStates != null && ! threadStates.isEmpty()) { - showThreadDump(myListener.getOutput().getStdout(), threadStates); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + if (myProcessHandler.isProcessTerminated() || myProcessHandler.isProcessTerminating()) return; + List threadStates = null; + final long start = System.currentTimeMillis(); + while ((System.currentTimeMillis() - start) < 1000) { + final String stdout = myListener.getOutput().getStdout(); + threadStates = ThreadDumpParser.parse(stdout); + if (threadStates == null || threadStates.isEmpty()) { + TimeoutUtil.sleep(50); + threadStates = null; + continue; } + break; + } + myProcessHandler.removeProcessListener(myListener); + if (threadStates != null && ! threadStates.isEmpty()) { + showThreadDump(myListener.getOutput().getStdout(), threadStates); } - }); } private void showThreadDump(final String out, final List threadStates) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - AnalyzeStacktraceUtil.addConsole(myProject, threadStates.size() > 1 ? - new ThreadDumpConsoleFactory(myProject, threadStates) : null, - " " + DateFormatUtil.formatDateTime(System.currentTimeMillis()), out); - } + ApplicationManager.getApplication().invokeLater(() -> { + AnalyzeStacktraceUtil.addConsole(myProject, threadStates.size() > 1 ? + new ThreadDumpConsoleFactory(myProject, threadStates) : null, + " " + DateFormatUtil.formatDateTime(System.currentTimeMillis()), out); }, ModalityState.NON_MODAL); } } diff --git a/java/execution/impl/src/com/intellij/execution/junit/InheritorChooser.java b/java/execution/impl/src/com/intellij/execution/junit/InheritorChooser.java index d52bb86f8fcc..57d01b9a7cf7 100644 --- a/java/execution/impl/src/com/intellij/execution/junit/InheritorChooser.java +++ b/java/execution/impl/src/com/intellij/execution/junit/InheritorChooser.java @@ -86,20 +86,14 @@ public class InheritorChooser { } final List classes = new ArrayList(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - final boolean isJUnit5 = ApplicationManager.getApplication().runReadAction((Computable)() -> JUnitUtil.isJUnit5(containingClass)); - ClassInheritorsSearch.search(containingClass).forEach(new Processor() { - @Override - public boolean process(PsiClass aClass) { - if (PsiClassUtil.isRunnableClass(aClass, !isJUnit5, true)) { - classes.add(aClass); - } - return true; - } - }); - } + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final boolean isJUnit5 = ApplicationManager.getApplication().runReadAction((Computable)() -> JUnitUtil.isJUnit5(containingClass)); + ClassInheritorsSearch.search(containingClass).forEach(aClass -> { + if (PsiClassUtil.isRunnableClass(aClass, !isJUnit5, true)) { + classes.add(aClass); + } + return true; + }); }, "Search for " + containingClass.getQualifiedName() + " inheritors", true, containingClass.getProject())) { return true; } @@ -149,12 +143,10 @@ public class InheritorChooser { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - public void run() { - final Object[] values = list.getSelectedValues(); - if (values == null) return; - chooseAndPerform(values, psiMethod, context, performRunnable, classes); - } + .setItemChoosenCallback(() -> { + final Object[] values = list.getSelectedValues(); + if (values == null) return; + chooseAndPerform(values, psiMethod, context, performRunnable, classes); }).createPopup().showInBestPositionFor(context.getDataContext()); return true; } diff --git a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java index d1e29e03714d..a355974a994f 100644 --- a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java +++ b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java @@ -260,15 +260,12 @@ public class JUnitUtil { assert containingClass != null : psiMethod + "; " + psiMethod.getClass() + "; " + psiMethod.getParent(); if (containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) { final boolean[] foundNonAbstractInheritor = new boolean[1]; - ClassInheritorsSearch.search(containingClass).forEach(new Processor() { - @Override - public boolean process(PsiClass psiClass) { - if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - foundNonAbstractInheritor[0] = true; - return false; - } - return true; + ClassInheritorsSearch.search(containingClass).forEach(psiClass -> { + if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + foundNonAbstractInheritor[0] = true; + return false; } + return true; }); if (foundNonAbstractInheritor[0]) { return true; diff --git a/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java b/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java index 4f5f4a96020a..e59102eda0ed 100644 --- a/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java +++ b/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java @@ -81,23 +81,13 @@ public class Extractor implements Disposable { myEventsDispatcher = new OutputPacketProcessor() { @Override public void processPacket(final String packet) { - myFulfilledWorkGate.addLast(new Runnable() { - @Override - public void run() { - packetProcessor.processPacket(packet); - } - }); + myFulfilledWorkGate.addLast(() -> packetProcessor.processPacket(packet)); } @Override public void processOutput(final Printable printable) { LOG.assertTrue(packetProcessor instanceof OutputPacketProcessor); - myFulfilledWorkGate.addLast(new Runnable() { - @Override - public void run() { - ((OutputPacketProcessor)packetProcessor).processOutput(printable); - } - }); + myFulfilledWorkGate.addLast(() -> ((OutputPacketProcessor)packetProcessor).processOutput(printable)); } }; myStream.setEventsDispatcher(myEventsDispatcher); @@ -105,29 +95,25 @@ public class Extractor implements Disposable { private void scheduleTask(final DeferredActionsQueue queue, final Runnable task) { myTaskQueue.add(task); - myExecutor.execute(new Runnable() { - public void run() { - final List currentTasks = new ArrayList(MAX_TASKS_TO_PROCESS_AT_ONCE); - if (myTaskQueue.drainTo(currentTasks, MAX_TASKS_TO_PROCESS_AT_ONCE) > 0) { - // there is a requirement that these activities must be run from the swing thread - // will be blocking one of pooled threads here, which is ok - try { - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - for (Runnable task : currentTasks) { - try { - queue.addLast(task); - } - catch (Throwable e) { - LOG.info(e); - } - } + myExecutor.execute(() -> { + final List currentTasks = new ArrayList(MAX_TASKS_TO_PROCESS_AT_ONCE); + if (myTaskQueue.drainTo(currentTasks, MAX_TASKS_TO_PROCESS_AT_ONCE) > 0) { + // there is a requirement that these activities must be run from the swing thread + // will be blocking one of pooled threads here, which is ok + try { + SwingUtilities.invokeAndWait(() -> { + for (Runnable task1 : currentTasks) { + try { + queue.addLast(task1); } - }); - } - catch (Throwable e) { - LOG.info("Task rejected: " + currentTasks, e); - } + catch (Throwable e) { + LOG.info(e); + } + } + }); + } + catch (Throwable e) { + LOG.info("Task rejected: " + currentTasks, e); } } }); diff --git a/java/execution/impl/src/com/intellij/execution/scratch/JavaScratchCompilationSupport.java b/java/execution/impl/src/com/intellij/execution/scratch/JavaScratchCompilationSupport.java index 26be9ec53d5f..3212ea5b4700 100644 --- a/java/execution/impl/src/com/intellij/execution/scratch/JavaScratchCompilationSupport.java +++ b/java/execution/impl/src/com/intellij/execution/scratch/JavaScratchCompilationSupport.java @@ -163,15 +163,12 @@ public class JavaScratchCompilationSupport implements ProjectComponent, CompileT } }; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (String s : orderEnumerator.compute().compileOnly().recursively().exportedOnly().withoutSdk().getPathsList().getPathList()) { - cp.add(new File(s)); - } - for (String s : orderEnumerator.compute().compileOnly().sdkOnly().getPathsList().getPathList()) { - platformCp.add(new File(s)); - } + ApplicationManager.getApplication().runReadAction(() -> { + for (String s : orderEnumerator.compute().compileOnly().recursively().exportedOnly().withoutSdk().getPathsList().getPathList()) { + cp.add(new File(s)); + } + for (String s : orderEnumerator.compute().compileOnly().sdkOnly().getPathsList().getPathList()) { + platformCp.add(new File(s)); } }); diff --git a/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryExtension.java b/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryExtension.java index 5e772667557a..e2fb9b4cd5cd 100644 --- a/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryExtension.java +++ b/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryExtension.java @@ -89,12 +89,7 @@ public class TestDiscoveryExtension extends RunConfigurationExtension { if (myCompletedMethodNames.size() > 50) { final String[] fullTestNames = ArrayUtil.toStringArray(myCompletedMethodNames); myCompletedMethodNames.clear(); - processTracesAlarm.addRequest(new Runnable() { - @Override - public void run() { - processAvailableTraces(configuration, fullTestNames); - } - }, 100); + processTracesAlarm.addRequest(() -> processAvailableTraces(configuration, fullTestNames), 100); } } } @@ -104,12 +99,9 @@ public class TestDiscoveryExtension extends RunConfigurationExtension { public void onTestingFinished(@NotNull SMTestProxy.SMRootTestProxy testsRoot) { if (testsRoot.getHandler() == handler) { processTracesAlarm.cancelAllRequests(); - processTracesAlarm.addRequest(new Runnable() { - @Override - public void run() { - processAvailableTraces(configuration); - Disposer.dispose(processTracesAlarm); - } + processTracesAlarm.addRequest(() -> { + processAvailableTraces(configuration); + Disposer.dispose(processTracesAlarm); }, 0); connection.disconnect(); } @@ -164,11 +156,8 @@ public class TestDiscoveryExtension extends RunConfigurationExtension { final TestDiscoveryIndex coverageIndex = TestDiscoveryIndex.getInstance(configuration.getProject()); synchronized (ourTracesLock) { final File tracesDirectoryFile = new File(tracesDirectory); - final File[] testMethodTraces = tracesDirectoryFile.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".tr"); - } + final File[] testMethodTraces = tracesDirectoryFile.listFiles((dir, name) -> { + return name.endsWith(".tr"); }); if (testMethodTraces != null) { for (File testMethodTrace : testMethodTraces) { diff --git a/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryIndex.java b/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryIndex.java index 416006f1c712..73e19855dfed 100644 --- a/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryIndex.java +++ b/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoveryIndex.java @@ -51,17 +51,9 @@ public class TestDiscoveryIndex implements ProjectComponent { String path = TestDiscoveryExtension.baseTestDiscoveryPathForProject(myProject); if (new File(path).exists()) { - StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - getHolder(); // proactively init with maybe io costly compact - } - }); - } - }); + StartupManager.getInstance(project).registerPostStartupActivity(() -> ApplicationManager.getApplication().executeOnPooledThread(() -> { + getHolder(); // proactively init with maybe io costly compact + })); } } @@ -256,22 +248,19 @@ public class TestDiscoveryIndex implements ProjectComponent { myMethodEnumeratorCache = new CachingEnumerator(methodNameEnumerator, EnumeratorStringDescriptor.INSTANCE); myClassEnumeratorCache = new CachingEnumerator(classNameEnumerator, EnumeratorStringDescriptor.INSTANCE); - myFlushingFuture = FlushingDaemon.everyFiveSeconds(new Runnable() { - @Override - public void run() { - synchronized (ourLock) { - if (myDisposed) { - myFlushingFuture.cancel(false); - return; - } - for(PersistentEnumeratorDelegate dataFile:myConstructedDataFiles) { - if (dataFile.isDirty()) { - dataFile.force(); - } - } - myClassEnumeratorCache.clear(); - myMethodEnumeratorCache.clear(); + myFlushingFuture = FlushingDaemon.everyFiveSeconds(() -> { + synchronized (ourLock) { + if (myDisposed) { + myFlushingFuture.cancel(false); + return; } + for(PersistentEnumeratorDelegate dataFile:myConstructedDataFiles) { + if (dataFile.isDirty()) { + dataFile.force(); + } + } + myClassEnumeratorCache.clear(); + myMethodEnumeratorCache.clear(); } }); } diff --git a/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoverySearchHelper.java b/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoverySearchHelper.java index dfeaf6a1c59e..d2def757602a 100644 --- a/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoverySearchHelper.java +++ b/java/execution/impl/src/com/intellij/execution/testDiscovery/TestDiscoverySearchHelper.java @@ -54,49 +54,46 @@ public class TestDiscoverySearchHelper { final PsiManager psiManager = PsiManager.getInstance(project); final TestDiscoveryIndex discoveryIndex = TestDiscoveryIndex.getInstance(project); for (final VirtualFile file : files) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiFile psiFile = psiManager.findFile(file); - if (psiFile instanceof PsiClassOwner) { - if (position != null) { - final PsiClass[] classes = ((PsiClassOwner)psiFile).getClasses(); - if (classes.length == 0 || TestFrameworks.detectFramework(classes[0]) == null) return; - } - try { - final List changedTextRanges = FormatChangedTextUtil.getInstance().getChangedTextRanges(project, psiFile); - for (TextRange textRange : changedTextRanges) { - final PsiElement start = psiFile.findElementAt(textRange.getStartOffset()); - final PsiElement end = psiFile.findElementAt(textRange.getEndOffset()); - final PsiElement parent = PsiTreeUtil.findCommonParent(new PsiElement[]{start, end}); - final Collection methods = new ArrayList(PsiTreeUtil.findChildrenOfType(parent, PsiMethod.class)); - final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(parent, PsiMethod.class); - if (containingMethod != null) { - methods.add(containingMethod); + ApplicationManager.getApplication().runReadAction(() -> { + final PsiFile psiFile = psiManager.findFile(file); + if (psiFile instanceof PsiClassOwner) { + if (position != null) { + final PsiClass[] classes = ((PsiClassOwner)psiFile).getClasses(); + if (classes.length == 0 || TestFrameworks.detectFramework(classes[0]) == null) return; + } + try { + final List changedTextRanges = FormatChangedTextUtil.getInstance().getChangedTextRanges(project, psiFile); + for (TextRange textRange : changedTextRanges) { + final PsiElement start = psiFile.findElementAt(textRange.getStartOffset()); + final PsiElement end = psiFile.findElementAt(textRange.getEndOffset()); + final PsiElement parent = PsiTreeUtil.findCommonParent(new PsiElement[]{start, end}); + final Collection methods = new ArrayList(PsiTreeUtil.findChildrenOfType(parent, PsiMethod.class)); + final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(parent, PsiMethod.class); + if (containingMethod != null) { + methods.add(containingMethod); + } + for (PsiMethod changedMethod : methods) { + final LinkedHashSet detectedPatterns = position == null ? collectPatterns(changedMethod, frameworkPrefix) : null; + if (detectedPatterns != null) { + patterns.addAll(detectedPatterns); } - for (PsiMethod changedMethod : methods) { - final LinkedHashSet detectedPatterns = position == null ? collectPatterns(changedMethod, frameworkPrefix) : null; - if (detectedPatterns != null) { - patterns.addAll(detectedPatterns); - } - final PsiClass containingClass = changedMethod.getContainingClass(); - if (containingClass != null && containingClass.getParent() == psiFile) { - final String classQualifiedName = containingClass.getQualifiedName(); - final String changedMethodName = changedMethod.getName(); - try { - if (classQualifiedName != null && - (position == null && TestFrameworks.detectFramework(containingClass) != null || - position != null && !discoveryIndex.hasTestTrace(frameworkPrefix + classQualifiedName + "-" + changedMethodName))) { - patterns.add(classQualifiedName + "," + changedMethodName); - } + final PsiClass containingClass = changedMethod.getContainingClass(); + if (containingClass != null && containingClass.getParent() == psiFile) { + final String classQualifiedName = containingClass.getQualifiedName(); + final String changedMethodName = changedMethod.getName(); + try { + if (classQualifiedName != null && + (position == null && TestFrameworks.detectFramework(containingClass) != null || + position != null && !discoveryIndex.hasTestTrace(frameworkPrefix + classQualifiedName + "-" + changedMethodName))) { + patterns.add(classQualifiedName + "," + changedMethodName); } - catch (IOException ignore) {} } + catch (IOException ignore) {} } } } - catch (FilesTooBigForDiffException ignore) { - } + } + catch (FilesTooBigForDiffException ignore) { } } }); diff --git a/java/execution/impl/src/com/intellij/execution/testframework/ResetConfigurationModuleAdapter.java b/java/execution/impl/src/com/intellij/execution/testframework/ResetConfigurationModuleAdapter.java index 7e12f3c4a5eb..c836f6635a1f 100644 --- a/java/execution/impl/src/com/intellij/execution/testframework/ResetConfigurationModuleAdapter.java +++ b/java/execution/impl/src/com/intellij/execution/testframework/ResetConfigurationModuleAdapter.java @@ -83,12 +83,9 @@ public class ResetConfigurationModuleAdapter extends HyperlinkAdapter { if (!modulesWithPackage.isEmpty()) { final String testRunDebugId = isDebug ? ToolWindowId.DEBUG : ToolWindowId.RUN; final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); - final Function moduleNameRef = new Function() { - @Override - public String fun(Module module) { - final String moduleName = module.getName(); - return "" + moduleName + ""; - } + final Function moduleNameRef = module1 -> { + final String moduleName = module1.getName(); + return "" + moduleName + ""; }; String message = "Tests were not found in module \"" + module.getName() + "\".\n" + "Use "; diff --git a/java/execution/impl/src/com/intellij/execution/testframework/SearchForTestsTask.java b/java/execution/impl/src/com/intellij/execution/testframework/SearchForTestsTask.java index bbbc45e57405..4ca27f544091 100644 --- a/java/execution/impl/src/com/intellij/execution/testframework/SearchForTestsTask.java +++ b/java/execution/impl/src/com/intellij/execution/testframework/SearchForTestsTask.java @@ -94,15 +94,12 @@ public abstract class SearchForTestsTask extends Task.Backgroundable { try { mySocket = myServerSocket.accept(); final ExecutionException[] ex = new ExecutionException[1]; - DumbService.getInstance(getProject()).repeatUntilPassesInSmartMode(new Runnable() { - @Override - public void run() { - try { - search(); - } - catch (ExecutionException e) { - ex[0] = e; - } + DumbService.getInstance(getProject()).repeatUntilPassesInSmartMode(() -> { + try { + search(); + } + catch (ExecutionException e) { + ex[0] = e; } }); if (ex[0] != null) { @@ -131,13 +128,10 @@ public abstract class SearchForTestsTask extends Task.Backgroundable { @Override public void onSuccess() { - DumbService.getInstance(getProject()).runWhenSmart(new Runnable() { - @Override - public void run() { - onFound(); - finish(); - startListening(); - } + DumbService.getInstance(getProject()).runWhenSmart(() -> { + onFound(); + finish(); + startListening(); }); } diff --git a/java/execution/impl/src/com/intellij/execution/ui/JrePathEditor.java b/java/execution/impl/src/com/intellij/execution/ui/JrePathEditor.java index 5fabcc8809cd..080b1cdcdc00 100644 --- a/java/execution/impl/src/com/intellij/execution/ui/JrePathEditor.java +++ b/java/execution/impl/src/com/intellij/execution/ui/JrePathEditor.java @@ -64,15 +64,12 @@ public class JrePathEditor extends JPanel implements PanelWithAnchor { public JrePathEditor() { myLabel = new JBLabel(ExecutionBundle.message("run.configuration.jre.label")); - myComboBoxModel = new SortedComboBoxModel(new Comparator() { - @Override - public int compare(JreComboBoxItem o1, JreComboBoxItem o2) { - int result = Comparing.compare(o1.getOrder(), o2.getOrder()); - if (result != 0) { - return result; - } - return o1.getPresentableText().compareToIgnoreCase(o2.getPresentableText()); + myComboBoxModel = new SortedComboBoxModel((o1, o2) -> { + int result = Comparing.compare(o1.getOrder(), o2.getOrder()); + if (result != 0) { + return result; } + return o1.getPresentableText().compareToIgnoreCase(o2.getPresentableText()); }); myDefaultJreItem = new DefaultJreItem(); myComboBoxModel.add(myDefaultJreItem); @@ -152,12 +149,7 @@ public class JrePathEditor extends JPanel implements PanelWithAnchor { public void setDefaultJreSelector(DefaultJreSelector defaultJreSelector) { myDefaultJreSelector = defaultJreSelector; - myDefaultJreSelector.addChangeListener(new Runnable() { - @Override - public void run() { - updateDefaultJrePresentation(); - } - }); + myDefaultJreSelector.addChangeListener(() -> updateDefaultJrePresentation()); } public void setPathOrName(@Nullable String pathOrName, boolean useAlternativeJre) { diff --git a/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java b/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java index 06432484a68c..6db44898676f 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java +++ b/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java @@ -42,12 +42,9 @@ public class DeadTestsCleaner implements Runnable { private void processUrl(final String url) { final Ref locationRef = Ref.create(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - Location location = myTestLocator.getLocation(url); - locationRef.set(location); - } + ApplicationManager.getApplication().runReadAction(() -> { + Location location = myTestLocator.getLocation(url); + locationRef.set(location); }); if (locationRef.get() == null) { myTestStorage.removeState(url); diff --git a/java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java b/java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java index 81048d7b7d10..9af7485c3937 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java +++ b/java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java @@ -62,28 +62,16 @@ public class RecentTestsListProvider { } class RecentTestsData { - private static Comparator BY_PATH_COMPARATOR = new Comparator() { - @Override - public int compare(TestInfo o1, TestInfo o2) { - String path1 = VirtualFileManager.extractPath(o1.getUrl()); - String path2 = VirtualFileManager.extractPath(o2.getUrl()); - return path1.compareTo(path2); - } + private static Comparator BY_PATH_COMPARATOR = (o1, o2) -> { + String path1 = VirtualFileManager.extractPath(o1.getUrl()); + String path2 = VirtualFileManager.extractPath(o2.getUrl()); + return path1.compareTo(path2); }; - private static Comparator SUITE_BY_RECENT_COMPARATOR = new Comparator() { - @Override - public int compare(SuiteInfo o1, SuiteInfo o2) { - return -o1.getMostRecentRunDate().compareTo(o2.getMostRecentRunDate()); - } - }; + private static Comparator SUITE_BY_RECENT_COMPARATOR = + (o1, o2) -> -o1.getMostRecentRunDate().compareTo(o2.getMostRecentRunDate()); - private static Comparator TEST_BY_RECENT_COMPARATOR = new Comparator() { - @Override - public int compare(TestInfo o1, TestInfo o2) { - return -o1.getRunDate().compareTo(o2.getRunDate()); - } - }; + private static Comparator TEST_BY_RECENT_COMPARATOR = (o1, o2) -> -o1.getRunDate().compareTo(o2.getRunDate()); private final Map mySuites = ContainerUtil.newHashMap(); @@ -183,21 +171,15 @@ class RecentTestsData { result.add(suite.getUrl()); } else if (failedTests.size() < 3) { - result.addAll(ContainerUtil.map(failedTests, new Function() { - @Override - public String fun(TestInfo testInfo) { - return testInfo.getUrl(); - } + result.addAll(ContainerUtil.map(failedTests, testInfo -> { + return testInfo.getUrl(); })); result.add(suite.getUrl()); } else { result.add(suite.getUrl()); - result.addAll(ContainerUtil.map(failedTests, new Function() { - @Override - public String fun(TestInfo testInfo) { - return testInfo.getUrl(); - } + result.addAll(ContainerUtil.map(failedTests, testInfo -> { + return testInfo.getUrl(); })); } diff --git a/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java b/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java index c453c16d222d..f4a7c20f230b 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java +++ b/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java @@ -65,11 +65,8 @@ public class ShowRecentTests extends AnAction { final Map records = testStorage.getRecentTests(TEST_LIMIT, getSinceDate()); RecentTestsListProvider listProvider = new RecentTestsListProvider(records); List urls = listProvider.getUrlsToShowFromHistory(); - Map icons = ContainerUtil.map2Map(urls, new Function>() { - @Override - public Pair fun(String url) { - return Pair.create(url, getIconFor(url, records)); - } + Map icons = ContainerUtil.map2Map(urls, url -> { + return Pair.create(url, getIconFor(url, records)); }); SelectTestStep selectStepTest = new SelectTestStep(urls, icons, testRunner, testLocator); diff --git a/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java b/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java index e7022a5b26f5..1b3361ff9292 100644 --- a/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java +++ b/java/execution/openapi/src/com/intellij/execution/configurations/JavaParameters.java @@ -97,15 +97,11 @@ public class JavaParameters extends SimpleJavaParameters { @Nullable private static NotNullFunction computeRootProvider(@MagicConstant(valuesFromClass = JavaParameters.class) int classPathType, final Sdk jdk) { - return (classPathType & JDK_ONLY) == 0 ? null : new NotNullFunction() { - @NotNull - @Override - public VirtualFile[] fun(OrderEntry orderEntry) { - if (orderEntry instanceof JdkOrderEntry) { - return jdk.getRootProvider().getFiles(OrderRootType.CLASSES); - } - return orderEntry.getFiles(OrderRootType.CLASSES); + return (classPathType & JDK_ONLY) == 0 ? null : (NotNullFunction)orderEntry -> { + if (orderEntry instanceof JdkOrderEntry) { + return jdk.getRootProvider().getFiles(OrderRootType.CLASSES); } + return orderEntry.getFiles(OrderRootType.CLASSES); }; } @@ -150,15 +146,12 @@ public class JavaParameters extends SimpleJavaParameters { if (productionOnly) { enumerator = enumerator.productionOnly(); } - enumerator.forEachModule(new Processor() { - @Override - public boolean process(Module module) { - Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); - if (sdk != null && sdk.getSdkType().equals(moduleSdk.getSdkType())) { - sdksFromDependencies.add(sdk); - } - return true; + enumerator.forEachModule(module1 -> { + Sdk sdk = ModuleRootManager.getInstance(module1).getSdk(); + if (sdk != null && sdk.getSdkType().equals(moduleSdk.getSdkType())) { + sdksFromDependencies.add(sdk); } + return true; }); return findLatestVersion(moduleSdk, sdksFromDependencies); } diff --git a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java index 0b930ea93924..847c661ec0d2 100644 --- a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java +++ b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java @@ -128,12 +128,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi } } - Collections.sort(actions, new Comparator() { - @Override - public int compare(AttachSourcesProvider.AttachSourcesAction o1, AttachSourcesProvider.AttachSourcesAction o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Collections.sort(actions, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); AttachSourcesProvider.AttachSourcesAction defaultAction; if (findSourceFileInSameJar(file) != null) { @@ -145,30 +140,24 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi actions.add(defaultAction); for (final AttachSourcesProvider.AttachSourcesAction action : actions) { - panel.createActionLabel(GuiUtils.getTextWithoutMnemonicEscaping(action.getName()), new Runnable() { - @Override - public void run() { - List entries = findLibraryEntriesForFile(file); - if (!Comparing.equal(libraries, entries)) { - Messages.showErrorDialog(myProject, "Can't find library for " + file.getName(), "Error"); - return; - } - - panel.setText(action.getBusyText()); - - action.perform(entries); + panel.createActionLabel(GuiUtils.getTextWithoutMnemonicEscaping(action.getName()), () -> { + List entries = findLibraryEntriesForFile(file); + if (!Comparing.equal(libraries, entries)) { + Messages.showErrorDialog(myProject, "Can't find library for " + file.getName(), "Error"); + return; } + + panel.setText(action.getBusyText()); + + action.perform(entries); }); } } } else { - panel.createActionLabel(ProjectBundle.message("class.file.open.source.action"), new Runnable() { - @Override - public void run() { - OpenFileDescriptor descriptor = new OpenFileDescriptor(myProject, sourceFile); - FileEditorManager.getInstance(myProject).openTextEditor(descriptor, true); - } + panel.createActionLabel(ProjectBundle.message("class.file.open.source.action"), () -> { + OpenFileDescriptor descriptor = new OpenFileDescriptor(myProject, sourceFile); + FileEditorManager.getInstance(myProject).openTextEditor(descriptor, true); }); } @@ -349,15 +338,12 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi } private static void appendSources(final Library library, final VirtualFile[] files) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Library.ModifiableModel model = library.getModifiableModel(); - for (VirtualFile virtualFile : files) { - model.addRoot(virtualFile, OrderRootType.SOURCES); - } - model.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + Library.ModifiableModel model = library.getModifiableModel(); + for (VirtualFile virtualFile : files) { + model.addRoot(virtualFile, OrderRootType.SOURCES); } + model.commit(); }); } } diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java b/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java index d7a7baab0f51..bb6361a2a214 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/FacetEditorImpl.java @@ -117,11 +117,9 @@ public class FacetEditorImpl extends UnnamedConfigurableGroup implements Unnamed if (myVisitedTabs.add(selectedTab)) { final JComponent preferredFocusedComponent = selectedTab.getPreferredFocusedComponent(); if (preferredFocusedComponent != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (preferredFocusedComponent.isShowing()) { - preferredFocusedComponent.requestFocus(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (preferredFocusedComponent.isShowing()) { + preferredFocusedComponent.requestFocus(); } }); } diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FacetLibrariesValidatorImpl.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FacetLibrariesValidatorImpl.java index bb5735d109e0..82491b1ffe78 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FacetLibrariesValidatorImpl.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FacetLibrariesValidatorImpl.java @@ -104,12 +104,9 @@ public class FacetLibrariesValidatorImpl extends FacetLibrariesValidator { private List collectRoots(final @NotNull ModuleRootModel rootModel) { final ArrayList roots = new ArrayList(); - rootModel.orderEntries().using(myContext.getModulesProvider()).recursively().librariesOnly().forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - ContainerUtil.addAll(roots, myContext.getLibrariesContainer().getLibraryFiles(library, OrderRootType.CLASSES)); - return true; - } + rootModel.orderEntries().using(myContext.getModulesProvider()).recursively().librariesOnly().forEachLibrary(library -> { + ContainerUtil.addAll(roots, myContext.getLibrariesContainer().getLibraryFiles(library, OrderRootType.CLASSES)); + return true; }); return roots; } diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FrameworkLibraryValidatorImpl.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FrameworkLibraryValidatorImpl.java index 36a77fc7e18a..04010824acfb 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FrameworkLibraryValidatorImpl.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/FrameworkLibraryValidatorImpl.java @@ -56,15 +56,12 @@ public class FrameworkLibraryValidatorImpl extends FrameworkLibraryValidator { public ValidationResult check() { final Set libraryKinds = myLibraryDescription.getSuitableLibraryKinds(); final Ref found = Ref.create(false); - myContext.getRootModel().orderEntries().using(myContext.getModulesProvider()).recursively().librariesOnly().forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - if (LibraryPresentationManager.getInstance().isLibraryOfKind(library, myContext.getLibrariesContainer(), libraryKinds)) { - found.set(true); - return false; - } - return true; + myContext.getRootModel().orderEntries().using(myContext.getModulesProvider()).recursively().librariesOnly().forEachLibrary(library -> { + if (LibraryPresentationManager.getInstance().isLibraryOfKind(library, myContext.getLibrariesContainer(), libraryKinds)) { + found.set(true); + return false; } + return true; }); if (found.get()) return ValidationResult.OK; diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibrariesValidationComponentImpl.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibrariesValidationComponentImpl.java index f733ee52e1c8..afcfb0a6931b 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibrariesValidationComponentImpl.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibrariesValidationComponentImpl.java @@ -41,11 +41,7 @@ public class LibrariesValidationComponentImpl implements LibrariesValidationComp myLibrariesValidator = new FacetLibrariesValidatorImpl(requiredLibraries, description, new LibrariesValidatorContextImpl(myModule), myErrorPanel.getValidatorsManager()); myErrorPanel.getValidatorsManager().registerValidator(myLibrariesValidator); - myErrorPanel.addListener(new Runnable() { - public void run() { - myDispatcher.getMulticaster().valididyChanged(myErrorPanel.isOk()); - } - }); + myErrorPanel.addListener(() -> myDispatcher.getMulticaster().valididyChanged(myErrorPanel.isOk())); } public JComponent getComponent() { diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java index 15f961246bec..c5da667dd56c 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java @@ -138,13 +138,10 @@ public class LibraryOptionsPanel implements Disposable { @Override public void onSuccess(@NotNull final List versions) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!myDisposed) { - showSettingsPanel(libraryDescription, pathProvider, versionFilter, showDoNotCreateOption, versions); - onVersionChanged(getPresentableVersion()); - } + SwingUtilities.invokeLater(() -> { + if (!myDisposed) { + showSettingsPanel(libraryDescription, pathProvider, versionFilter, showDoNotCreateOption, versions); + onVersionChanged(getPresentableVersion()); } }); } @@ -217,13 +214,10 @@ public class LibraryOptionsPanel implements Disposable { }); myDoNotCreateRadioButton.setVisible(showDoNotCreateOption); - myLibraryComboBoxModel = new SortedComboBoxModel(new Comparator() { - @Override - public int compare(LibraryEditor o1, LibraryEditor o2) { - final String name1 = o1.getName(); - final String name2 = o2.getName(); - return -StringUtil.notNullize(name1).compareToIgnoreCase(StringUtil.notNullize(name2)); - } + myLibraryComboBoxModel = new SortedComboBoxModel((o1, o2) -> { + final String name1 = o1.getName(); + final String name2 = o2.getName(); + return -StringUtil.notNullize(name1).compareToIgnoreCase(StringUtil.notNullize(name2)); }); for (Library library : libraries) { @@ -303,12 +297,7 @@ public class LibraryOptionsPanel implements Disposable { }); myConfigureButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - doConfigure(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> doConfigure()); } }); updateState(); diff --git a/java/idea-ui/src/com/intellij/framework/addSupport/impl/AddSupportForSingleFrameworkDialog.java b/java/idea-ui/src/com/intellij/framework/addSupport/impl/AddSupportForSingleFrameworkDialog.java index 95306df0f605..00e2dc96d69c 100644 --- a/java/idea-ui/src/com/intellij/framework/addSupport/impl/AddSupportForSingleFrameworkDialog.java +++ b/java/idea-ui/src/com/intellij/framework/addSupport/impl/AddSupportForSingleFrameworkDialog.java @@ -91,12 +91,7 @@ public class AddSupportForSingleFrameworkDialog extends DialogWrapper { protected void doOKAction() { final Ref result = Ref.create(false); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - result.set(addSupport()); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> result.set(addSupport())); if (result.get()) { super.doOKAction(); diff --git a/java/idea-ui/src/com/intellij/framework/impl/FrameworkTypeUtil.java b/java/idea-ui/src/com/intellij/framework/impl/FrameworkTypeUtil.java index d9fd50d50444..64941f8bb359 100644 --- a/java/idea-ui/src/com/intellij/framework/impl/FrameworkTypeUtil.java +++ b/java/idea-ui/src/com/intellij/framework/impl/FrameworkTypeUtil.java @@ -26,12 +26,8 @@ import java.util.Map; * @author nik */ public class FrameworkTypeUtil { - public static final Comparator FRAMEWORK_TYPE_COMPARATOR = new Comparator() { - @Override - public int compare(FrameworkType o1, FrameworkType o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }; + public static final Comparator FRAMEWORK_TYPE_COMPARATOR = + (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); public static Map computeFrameworkTypeByIdMap() { Map frameworkTypes = new HashMap(); diff --git a/java/idea-ui/src/com/intellij/framework/library/impl/DownloadableLibraryPropertiesEditor.java b/java/idea-ui/src/com/intellij/framework/library/impl/DownloadableLibraryPropertiesEditor.java index cf9ac42af5c3..0996c363362c 100644 --- a/java/idea-ui/src/com/intellij/framework/library/impl/DownloadableLibraryPropertiesEditor.java +++ b/java/idea-ui/src/com/intellij/framework/library/impl/DownloadableLibraryPropertiesEditor.java @@ -56,36 +56,33 @@ public class DownloadableLibraryPropertiesEditor extends LibraryPropertiesEditor myDescription.fetchVersions(new DownloadableFileSetVersions.FileSetVersionsCallback() { @Override public void onSuccess(@NotNull final List versions) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String pathForDownloaded = ""; - final VirtualFile existingRootDirectory = myEditorComponent.getExistingRootDirectory(); - if (existingRootDirectory != null) { - pathForDownloaded = existingRootDirectory.getPath(); + ApplicationManager.getApplication().invokeLater(() -> { + String pathForDownloaded = ""; + final VirtualFile existingRootDirectory = myEditorComponent.getExistingRootDirectory(); + if (existingRootDirectory != null) { + pathForDownloaded = existingRootDirectory.getPath(); + } + else { + final VirtualFile baseDir = myEditorComponent.getBaseDirectory(); + if (baseDir != null) { + pathForDownloaded = baseDir.getPath() + "/lib"; } - else { - final VirtualFile baseDir = myEditorComponent.getBaseDirectory(); - if (baseDir != null) { - pathForDownloaded = baseDir.getPath() + "/lib"; - } - } - final LibraryDownloadSettings initialSettings = new LibraryDownloadSettings(getCurrentVersion(versions), myLibraryType, - LibrariesContainer.LibraryLevel.PROJECT, - pathForDownloaded); - final LibraryDownloadSettings settings = DownloadingOptionsDialog.showDialog(getMainPanel(), initialSettings, versions, false); - if (settings != null) { - final NewLibraryEditor editor = settings.download(getMainPanel(), null); - if (editor != null) { - final LibraryEditorBase target = (LibraryEditorBase)myEditorComponent.getLibraryEditor(); - target.removeAllRoots(); - myEditorComponent.renameLibrary(editor.getName()); - target.setType(myLibraryType); - editor.applyTo(target); - myEditorComponent.updateRootsTree(); - myCurrentVersionString = settings.getVersion().getVersionString(); - setModified(); - } + } + final LibraryDownloadSettings initialSettings = new LibraryDownloadSettings(getCurrentVersion(versions), myLibraryType, + LibrariesContainer.LibraryLevel.PROJECT, + pathForDownloaded); + final LibraryDownloadSettings settings = DownloadingOptionsDialog.showDialog(getMainPanel(), initialSettings, versions, false); + if (settings != null) { + final NewLibraryEditor editor = settings.download(getMainPanel(), null); + if (editor != null) { + final LibraryEditorBase target = (LibraryEditorBase)myEditorComponent.getLibraryEditor(); + target.removeAllRoots(); + myEditorComponent.renameLibrary(editor.getName()); + target.setType(myLibraryType); + editor.applyTo(target); + myEditorComponent.updateRootsTree(); + myCurrentVersionString = settings.getVersion().getVersionString(); + setModified(); } } }, current); diff --git a/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java b/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java index edd6516ce5c5..4f016086ee73 100644 --- a/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java +++ b/java/idea-ui/src/com/intellij/ide/impl/NewProjectUtil.java @@ -61,10 +61,8 @@ public class NewProjectUtil { } public static void createNewProject(Project projectToClose, AbstractProjectWizard wizard) { - final boolean proceed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - ProjectManager.getInstance().getDefaultProject(); //warm up components - } + final boolean proceed = ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + ProjectManager.getInstance().getDefaultProject(); //warm up components }, ProjectBundle.message("project.new.wizard.progress.title"), true, null); if (!proceed) return; if (!wizard.showAndGet()) { @@ -79,12 +77,7 @@ public class NewProjectUtil { return doCreate(dialog, projectToClose); } catch (final IOException e) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(e.getMessage(), "Project Initialization Failed"); - } - }); + UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(e.getMessage(), "Project Initialization Failed")); return null; } } @@ -118,35 +111,23 @@ public class NewProjectUtil { final Sdk jdk = dialog.getNewProjectJdk(); if (jdk != null) { - CommandProcessor.getInstance().executeCommand(newProject, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - applyJdkToProject(newProject, jdk); - } - }); - } - }, null, null); + CommandProcessor.getInstance().executeCommand(newProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + applyJdkToProject(newProject, jdk); + }), null, null); } final String compileOutput = dialog.getNewCompileOutput(); - CommandProcessor.getInstance().executeCommand(newProject, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - String canonicalPath = compileOutput; - try { - canonicalPath = FileUtil.resolveShortWindowsName(compileOutput); - } - catch (IOException e) { - //file doesn't exist - } - canonicalPath = FileUtil.toSystemIndependentName(canonicalPath); - CompilerProjectExtension.getInstance(newProject).setCompilerOutputUrl(VfsUtilCore.pathToUrl(canonicalPath)); - } - }); + CommandProcessor.getInstance().executeCommand(newProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + String canonicalPath = compileOutput; + try { + canonicalPath = FileUtil.resolveShortWindowsName(compileOutput); } - }, null, null); + catch (IOException e) { + //file doesn't exist + } + canonicalPath = FileUtil.toSystemIndependentName(canonicalPath); + CompilerProjectExtension.getInstance(newProject).setCompilerOutputUrl(VfsUtilCore.pathToUrl(canonicalPath)); + }), null, null); if (!ApplicationManager.getApplication().isUnitTestMode()) { newProject.save(); @@ -165,28 +146,22 @@ public class NewProjectUtil { } final boolean need2OpenProjectStructure = projectBuilder == null || projectBuilder.isOpenProjectSettingsAfter(); - StartupManager.getInstance(newProject).registerPostStartupActivity(new Runnable() { - public void run() { - // ensure the dialog is shown after all startup activities are done - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (newProject.isDisposed() || ApplicationManager.getApplication().isUnitTestMode()) return; - if (need2OpenProjectStructure) { - ModulesConfigurator.showDialog(newProject, null, null); - } - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (newProject.isDisposed()) return; - final ToolWindow toolWindow = ToolWindowManager.getInstance(newProject).getToolWindow(ToolWindowId.PROJECT_VIEW); - if (toolWindow != null) { - toolWindow.activate(null); - } - } - }, ModalityState.NON_MODAL); + StartupManager.getInstance(newProject).registerPostStartupActivity(() -> { + // ensure the dialog is shown after all startup activities are done + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + if (newProject.isDisposed() || ApplicationManager.getApplication().isUnitTestMode()) return; + if (need2OpenProjectStructure) { + ModulesConfigurator.showDialog(newProject, null, null); + } + ApplicationManager.getApplication().invokeLater(() -> { + if (newProject.isDisposed()) return; + final ToolWindow toolWindow = ToolWindowManager.getInstance(newProject).getToolWindow(ToolWindowId.PROJECT_VIEW); + if (toolWindow != null) { + toolWindow.activate(null); } - }); - } + }, ModalityState.NON_MODAL); + }); }); if (newProject != projectToClose) { diff --git a/java/idea-ui/src/com/intellij/ide/impl/ProjectStructureSelectInTarget.java b/java/idea-ui/src/com/intellij/ide/impl/ProjectStructureSelectInTarget.java index dc178a2b75e2..64719bc65a6d 100644 --- a/java/idea-ui/src/com/intellij/ide/impl/ProjectStructureSelectInTarget.java +++ b/java/idea-ui/src/com/intellij/ide/impl/ProjectStructureSelectInTarget.java @@ -73,15 +73,12 @@ public class ProjectStructureSelectInTarget extends SelectInTargetBase implement facet = fileIndex.isInSourceContent(file) ? null : findFacet(project, file); } if (module != null || facet != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (facet != null) { - ModulesConfigurator.showFacetSettingsDialog(facet, null); - } - else { - ProjectSettingsService.getInstance(project).openModuleSettings(module); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (facet != null) { + ModulesConfigurator.showFacetSettingsDialog(facet, null); + } + else { + ProjectSettingsService.getInstance(project).openModuleSettings(module); } }); return; @@ -89,12 +86,8 @@ public class ProjectStructureSelectInTarget extends SelectInTargetBase implement final OrderEntry orderEntry = LibraryUtil.findLibraryEntry(file, project); if (orderEntry != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ProjectSettingsService.getInstance(project).openLibraryOrSdkSettings(orderEntry); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> ProjectSettingsService.getInstance(project).openLibraryOrSdkSettings(orderEntry)); } } diff --git a/java/idea-ui/src/com/intellij/ide/projectView/actions/CreateLibraryFromFilesDialog.java b/java/idea-ui/src/com/intellij/ide/projectView/actions/CreateLibraryFromFilesDialog.java index 2110e12e9843..79f150c3ad38 100644 --- a/java/idea-ui/src/com/intellij/ide/projectView/actions/CreateLibraryFromFilesDialog.java +++ b/java/idea-ui/src/com/intellij/ide/projectView/actions/CreateLibraryFromFilesDialog.java @@ -133,12 +133,7 @@ public class CreateLibraryFromFilesDialog extends DialogWrapper { @Override protected void doOKAction() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - addLibrary(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> addLibrary()); super.doOKAction(); } diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java index be586661f0d3..be2272c6750a 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java @@ -108,12 +108,7 @@ public class ProjectTemplateList extends JPanel { } public void setTemplates(List list, boolean preserveSelection) { - Collections.sort(list, new Comparator() { - @Override - public int compare(ProjectTemplate o1, ProjectTemplate o2) { - return Comparing.compare(o1 instanceof ArchivedProjectTemplate, o2 instanceof ArchivedProjectTemplate); - } - }); + Collections.sort(list, (o1, o2) -> Comparing.compare(o1 instanceof ArchivedProjectTemplate, o2 instanceof ArchivedProjectTemplate)); int index = preserveSelection ? myList.getSelectedIndex() : -1; //noinspection unchecked diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java index 63e4c9ba79d4..3d1257c02706 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java @@ -90,12 +90,7 @@ public class ProjectTypeStep extends ModuleWizardStep implements SettingsStep, D return o.getId(); } }; - public static final Function NODE_STRING_FUNCTION = new Function() { - @Override - public String fun(FrameworkSupportNode node) { - return node.getId(); - } - }; + public static final Function NODE_STRING_FUNCTION = node -> node.getId(); private static final String TEMPLATES_CARD = "templates card"; private static final String FRAMEWORKS_CARD = "frameworks card"; private static final String PROJECT_WIZARD_GROUP = "project.wizard.group"; @@ -341,22 +336,16 @@ public class ProjectTypeStep extends ModuleWizardStep implements SettingsStep, D ModuleType type = getModuleType(group); moduleTypes.putValue(type, group); } - Collections.sort(groups, new Comparator() { - @Override - public int compare(TemplatesGroup o1, TemplatesGroup o2) { - int i = o2.getWeight() - o1.getWeight(); - if (i != 0) return i; - int i1 = moduleTypes.get(getModuleType(o2)).size() - moduleTypes.get(getModuleType(o1)).size(); - if (i1 != 0) return i1; - return o1.compareTo(o2); - } + Collections.sort(groups, (o1, o2) -> { + int i = o2.getWeight() - o1.getWeight(); + if (i != 0) return i; + int i1 = moduleTypes.get(getModuleType(o2)).size() - moduleTypes.get(getModuleType(o1)).size(); + if (i1 != 0) return i1; + return o1.compareTo(o2); }); - Set groupNames = ContainerUtil.map2Set(groups, new Function() { - @Override - public String fun(TemplatesGroup group) { - return group.getParentGroup(); - } + Set groupNames = ContainerUtil.map2Set(groups, group -> { + return group.getParentGroup(); }); // move subgroups diff --git a/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java b/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java index f6ee8e6ebb35..055f57985d82 100644 --- a/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java +++ b/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java @@ -89,18 +89,13 @@ public class AddFrameworkSupportDialog extends DialogWrapper { if (!myAddSupportPanel.validate()) return; if (!myAddSupportPanel.downloadLibraries(myAddSupportPanel.getMainPanel())) return; - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - new WriteAction() { - protected void run(@NotNull final Result result) { - ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); - myAddSupportPanel.addSupport(myModule, model); - model.commit(); - } - }.execute(); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> new WriteAction() { + protected void run(@NotNull final Result result) { + ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); + myAddSupportPanel.addSupport(myModule, model); + model.commit(); } - }); + }.execute()); } super.doOKAction(); } diff --git a/java/idea-ui/src/com/intellij/ide/util/importProject/DetectedRootsChooser.java b/java/idea-ui/src/com/intellij/ide/util/importProject/DetectedRootsChooser.java index d21c884ef4ff..d3ade099e488 100644 --- a/java/idea-ui/src/com/intellij/ide/util/importProject/DetectedRootsChooser.java +++ b/java/idea-ui/src/com/intellij/ide/util/importProject/DetectedRootsChooser.java @@ -220,12 +220,7 @@ public class DetectedRootsChooser { column.setMaxWidth(width); myTable.updateColumnSizes(); List sortedRoots = new ArrayList(roots); - Collections.sort(sortedRoots, new Comparator() { - @Override - public int compare(DetectedRootData o1, DetectedRootData o2) { - return o1.getDirectory().compareTo(o2.getDirectory()); - } - }); + Collections.sort(sortedRoots, (o1, o2) -> o1.getDirectory().compareTo(o2.getDirectory())); myModel.setItems(sortedRoots); } diff --git a/java/idea-ui/src/com/intellij/ide/util/importProject/ModuleInsight.java b/java/idea-ui/src/com/intellij/ide/util/importProject/ModuleInsight.java index 4364f8e7cbc1..c7c5929fd615 100644 --- a/java/idea-ui/src/com/intellij/ide/util/importProject/ModuleInsight.java +++ b/java/idea-ui/src/com/intellij/ide/util/importProject/ModuleInsight.java @@ -420,11 +420,7 @@ public abstract class ModuleInsight { myProgress.setText2(file.getName()); try { final char[] chars = FileUtil.loadFileText(file); - scanSourceFileForImportedPackages(StringFactory.createShared(chars), new Consumer() { - public void consume(final String s) { - usedPackages.add(myInterner.intern(s)); - } - }); + scanSourceFileForImportedPackages(StringFactory.createShared(chars), s -> usedPackages.add(myInterner.intern(s))); } catch (IOException e) { LOG.info(e); @@ -454,11 +450,9 @@ public abstract class ModuleInsight { myProgress.pushState(); myProgress.setText2(file.getName()); try { - scanLibraryForDeclaredPackages(file, new Consumer() { - public void consume(final String s) { - if (!libraryPackages.contains(s)) { - libraryPackages.add(myInterner.intern(s)); - } + scanLibraryForDeclaredPackages(file, s -> { + if (!libraryPackages.contains(s)) { + libraryPackages.add(myInterner.intern(s)); } }); } diff --git a/java/idea-ui/src/com/intellij/ide/util/importProject/ProjectLayoutPanel.java b/java/idea-ui/src/com/intellij/ide/util/importProject/ProjectLayoutPanel.java index 44f232d1a36b..c1fcc58145f5 100644 --- a/java/idea-ui/src/com/intellij/ide/util/importProject/ProjectLayoutPanel.java +++ b/java/idea-ui/src/com/intellij/ide/util/importProject/ProjectLayoutPanel.java @@ -58,15 +58,13 @@ abstract class ProjectLayoutPanel extends JPanel { private final JList myDependenciesList; private final ModuleInsight myInsight; - private final Comparator COMPARATOR = new Comparator() { - public int compare(final T o1, final T o2) { - final int w1 = getWeight(o1); - final int w2 = getWeight(o2); - if (w1 != w2) { - return w1 - w2; - } - return getElementText(o1).compareToIgnoreCase(getElementText(o2)); + private final Comparator COMPARATOR = (o1, o2) -> { + final int w1 = getWeight(o1); + final int w2 = getWeight(o2); + if (w1 != w2) { + return w1 - w2; } + return getElementText(o1).compareToIgnoreCase(getElementText(o2)); }; public ProjectLayoutPanel(final ModuleInsight insight) { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java index 053a3aeebf36..6c3d1f817017 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java @@ -165,12 +165,7 @@ public abstract class AbstractProjectWizard extends AbstractWizard result = Ref.create(false); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - result.set(doFinishAction()); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> result.set(doFinishAction())); if (!result.get()) return; super.doOKAction(); diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java index 180964199abf..4e50be8eb687 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java @@ -311,12 +311,8 @@ public class AddSupportForFrameworksPanel implements Disposable { createNode(provider, nodes, groups, roots, providers, associated, associatedNodes); } - FrameworkSupportNodeBase.sortByName(roots, new Comparator() { - @Override - public int compare(FrameworkSupportNodeBase o1, FrameworkSupportNodeBase o2) { - return Comparing.compare(preselected.contains(o2.getId()), preselected.contains(o1.getId())); - } - }); + FrameworkSupportNodeBase.sortByName(roots, + (o1, o2) -> Comparing.compare(preselected.contains(o2.getId()), preselected.contains(o1.getId()))); myRoots = roots; return associatedNodes.values(); } @@ -407,16 +403,13 @@ public class AddSupportForFrameworksPanel implements Disposable { public boolean downloadLibraries(@NotNull final JComponent parentComponent) { final Ref result = Ref.create(true); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - applyLibraryOptionsForSelected(); - List list = getLibrariesCompositionSettingsList(); - for (LibraryCompositionSettings compositionSettings : list) { - if (!compositionSettings.downloadFiles(parentComponent)) { - result.set(false); - return; - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + applyLibraryOptionsForSelected(); + List list = getLibrariesCompositionSettingsList(); + for (LibraryCompositionSettings compositionSettings : list) { + if (!compositionSettings.downloadFiles(parentComponent)) { + result.set(false); + return; } } }); @@ -490,10 +483,6 @@ public class AddSupportForFrameworksPanel implements Disposable { private void sortFrameworks(final List nodes) { final Comparator comparator = FrameworkSupportUtil.getFrameworkSupportProvidersComparator(myProviders); - Collections.sort(nodes, new Comparator() { - public int compare(final FrameworkSupportNode o1, final FrameworkSupportNode o2) { - return comparator.compare(o1.getUserObject(), o2.getUserObject()); - } - }); + Collections.sort(nodes, (o1, o2) -> comparator.compare(o1.getUserObject(), o2.getUserObject())); } } diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java index 2fee50a4301b..611ee3edac1f 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java @@ -48,18 +48,16 @@ public abstract class FrameworkSupportNodeBase exten public static void sortByName(@Nullable List nodes, @Nullable final Comparator comparator) { if (nodes == null) return; - Collections.sort(nodes, new Comparator() { - public int compare(final FrameworkSupportNodeBase o1, final FrameworkSupportNodeBase o2) { - if (comparator != null) { - int compare = comparator.compare(o1, o2); - if (compare != 0) return compare; - } - if (o1 instanceof FrameworkGroupNode && !(o2 instanceof FrameworkGroupNode)) return -1; - if (o2 instanceof FrameworkGroupNode && !(o1 instanceof FrameworkGroupNode)) return 1; - if (o1.getChildCount() < o2.getChildCount()) return 1; - if (o1.getChildCount() > o2.getChildCount()) return -1; - return o1.getTitle().compareToIgnoreCase(o2.getTitle()); + Collections.sort(nodes, (o1, o2) -> { + if (comparator != null) { + int compare = comparator.compare(o1, o2); + if (compare != 0) return compare; } + if (o1 instanceof FrameworkGroupNode && !(o2 instanceof FrameworkGroupNode)) return -1; + if (o2 instanceof FrameworkGroupNode && !(o1 instanceof FrameworkGroupNode)) return 1; + if (o1.getChildCount() < o2.getChildCount()) return 1; + if (o1.getChildCount() > o2.getChildCount()) return -1; + return o1.getTitle().compareToIgnoreCase(o2.getTitle()); }); for (FrameworkSupportNodeBase node : nodes) { sortByName((List)node.children, null); diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java index 7a502443fcdb..3de2ec6b5c70 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java @@ -99,13 +99,11 @@ public class ProjectTypesList implements Disposable { } } //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - int index = myList.getSelectedIndex(); - myModel.remove(myLoadingItem); - myModel.add(items); - myList.setSelectedIndex(index); - } + SwingUtilities.invokeLater(() -> { + int index = myList.getSelectedIndex(); + myModel.remove(myLoadingItem); + myModel.add(items); + myList.setSelectedIndex(index); }); } finally { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/ImportMode.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/ImportMode.java index 27474cc2c098..93341434a191 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/ImportMode.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/ImportMode.java @@ -58,10 +58,8 @@ public class ImportMode extends WizardMode { final String productName = ApplicationNamesInfo.getInstance().getFullProductName(); return ProjectBundle.message("project.new.wizard.import.description", productName, context.getPresentationName(), StringUtil.join( Arrays.asList(Extensions.getExtensions(ProjectImportProvider.PROJECT_IMPORT_PROVIDER)), - new Function() { - public String fun(final ProjectImportProvider provider) { - return provider.getName(); - } + provider -> { + return provider.getName(); }, ", ")); } diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java index b7cdbe2f5a85..355ac8abf241 100644 --- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java +++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java @@ -157,34 +157,22 @@ public abstract class AbstractStepWithProgress extends ModuleWizardStep return; } - UiNotifyConnector.doWhenFirstShown(myPanel, new Runnable() { - @Override - public void run() { - - new SwingWorker() { - public Object construct() { - final Ref result = Ref.create(null); - ProgressManager.getInstance().runProcess(new Runnable() { - public void run() { - result.set(calculate()); - } - }, progress); - return result.get(); - } - - public void finished() { - myProgressIndicator = null; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - final Result result = (Result)get(); - onFinished(result, progress.isCanceled()); - showCard(RESULTS_PANEL); - } - }); - } - }.start(); + UiNotifyConnector.doWhenFirstShown(myPanel, () -> new SwingWorker() { + public Object construct() { + final Ref result = Ref.create(null); + ProgressManager.getInstance().runProcess(() -> result.set(calculate()), progress); + return result.get(); } - }); + + public void finished() { + myProgressIndicator = null; + ApplicationManager.getApplication().invokeLater(() -> { + final Result result = (Result)get(); + onFinished(result, progress.isCanceled()); + showCard(RESULTS_PANEL); + }); + } + }.start()); } private void showCard(final String id) { @@ -222,11 +210,7 @@ public abstract class AbstractStepWithProgress extends ModuleWizardStep } private void updateLabel(final JLabel label, final String text) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - label.setText(text); - } - }); + UIUtil.invokeLaterIfNeeded(() -> label.setText(text)); } } } diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/JdkChooserPanel.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/JdkChooserPanel.java index e6dffc990d01..f2546564f16b 100644 --- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/JdkChooserPanel.java +++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/JdkChooserPanel.java @@ -169,11 +169,7 @@ public class JdkChooserPanel extends JPanel { final Collection collection = projectJdksModel.getProjectSdks().values(); jdks = getCompatibleJdks(type, collection); } - Arrays.sort(jdks, new Comparator() { - public int compare(final Sdk o1, final Sdk o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Arrays.sort(jdks, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Sdk jdk : jdks) { myListModel.addElement(jdk); } @@ -243,10 +239,8 @@ public class JdkChooserPanel extends JPanel { if (jdk == null) { return null; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ProjectRootManager.getInstance(project).setProjectSdk(jdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManager.getInstance(project).setProjectSdk(jdk); }); return jdk; } diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectJdkForModuleStep.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectJdkForModuleStep.java index 331da7c24fd0..c0218e94731c 100644 --- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectJdkForModuleStep.java +++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/ProjectJdkForModuleStep.java @@ -92,18 +92,16 @@ public class ProjectJdkForModuleStep extends ModuleWizardStep { final ProjectSdksModel projectJdksModel = projectConfig.getProjectJdksModel(); final boolean[] successfullyAdded = new boolean[1]; projectJdksModel.reset(project); - projectJdksModel.doAdd(myPanel, type, new Consumer() { - public void consume(final Sdk jdk) { - successfullyAdded[0] = jdkConfig.addJdkNode(jdk, false); - myJdkChooser.updateList(jdk, type, projectJdksModel.getSdks()); + projectJdksModel.doAdd(myPanel, type, jdk -> { + successfullyAdded[0] = jdkConfig.addJdkNode(jdk, false); + myJdkChooser.updateList(jdk, type, projectJdksModel.getSdks()); - if (!successfullyAdded[0]) { - try { - projectJdksModel.apply(jdkConfig); - } - catch (ConfigurationException e1) { - //name can't be wrong - } + if (!successfullyAdded[0]) { + try { + projectJdksModel.apply(jdkConfig); + } + catch (ConfigurationException e1) { + //name can't be wrong } } }); @@ -116,11 +114,7 @@ public class ProjectJdkForModuleStep extends ModuleWizardStep { public void actionPerformed(ActionEvent e) { final Sdk jdk = getJdk(); - final Runnable runnable = new Runnable() { - public void run() { - ProjectRootManagerEx.getInstanceEx(defaultProject).setProjectSdk(jdk); - } - }; + final Runnable runnable = () -> ProjectRootManagerEx.getInstanceEx(defaultProject).setProjectSdk(jdk); ApplicationManager.getApplication().runWriteAction(runnable); mySetAsDefaultButton.setEnabled(false); } diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/importSources/impl/JavaProjectStructureDetector.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/importSources/impl/JavaProjectStructureDetector.java index ac706cc5efd3..e507678b2c78 100644 --- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/importSources/impl/JavaProjectStructureDetector.java +++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/importSources/impl/JavaProjectStructureDetector.java @@ -63,11 +63,6 @@ public class JavaProjectStructureDetector extends JavaSourceRootDetector { @NotNull protected NullableFunction getPackageNameFetcher() { - return new NullableFunction() { - @Override - public String fun(CharSequence charSequence) { - return JavaSourceRootDetectionUtil.getPackageName(charSequence); - } - }; + return charSequence -> JavaSourceRootDetectionUtil.getPackageName(charSequence); } } diff --git a/java/idea-ui/src/com/intellij/jarFinder/AbstractAttachSourceProvider.java b/java/idea-ui/src/com/intellij/jarFinder/AbstractAttachSourceProvider.java index 3d22cdc860e1..2c1a09605f2e 100644 --- a/java/idea-ui/src/com/intellij/jarFinder/AbstractAttachSourceProvider.java +++ b/java/idea-ui/src/com/intellij/jarFinder/AbstractAttachSourceProvider.java @@ -169,28 +169,22 @@ public abstract class AbstractAttachSourceProvider implements AttachSourcesProvi } catch (IOException e) { LOG.warn(e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String message = "Failed to download sources: " + myUrl; - new Notification(myMessageGroupId, "Downloading failed", message, NotificationType.ERROR).notify(getProject()); - callback.setDone(); - } + ApplicationManager.getApplication().invokeLater(() -> { + String message = "Failed to download sources: " + myUrl; + new Notification(myMessageGroupId, "Downloading failed", message, NotificationType.ERROR).notify(getProject()); + callback.setDone(); }); return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - AccessToken accessToken = WriteAction.start(); - try { - storeFile(bytes); - } - finally { - accessToken.finish(); - callback.setDone(); - } + ApplicationManager.getApplication().invokeLater(() -> { + AccessToken accessToken = WriteAction.start(); + try { + storeFile(bytes); + } + finally { + accessToken.finish(); + callback.setDone(); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/ProjectJdksEditor.java b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/ProjectJdksEditor.java index 86c08243bade..52fbdf67998f 100644 --- a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/ProjectJdksEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/ProjectJdksEditor.java @@ -46,12 +46,7 @@ public class ProjectJdksEditor extends DialogWrapper { public ProjectJdksEditor(final Sdk jdk, Component parent, ProjectJdksConfigurable configurable) { super(parent, true); myConfigurable = configurable; - SwingUtilities.invokeLater(new Runnable(){ - @Override - public void run() { - myConfigurable.selectNodeInTree(jdk != null ? jdk.getName() : null); - } - }); + SwingUtilities.invokeLater(() -> myConfigurable.selectNodeInTree(jdk != null ? jdk.getName() : null)); setTitle(ProjectBundle.message("sdk.configure.title")); Disposer.register(myDisposable, new Disposable() { @Override diff --git a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java index 731b1b979585..75f8540ffd0b 100644 --- a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java @@ -216,11 +216,8 @@ public class SdkEditor implements Configurable, Place.Navigator { for (SdkPathEditor pathEditor : myPathEditors.values()) { pathEditor.apply(sdkModificator); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { // fix SCR #29193 - @Override - public void run() { - sdkModificator.commitChanges(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + sdkModificator.commitChanges(); }); final AdditionalDataConfigurable configurable = getAdditionalDataConfigurable(); if (configurable != null) { @@ -300,12 +297,7 @@ public class SdkEditor implements Configurable, Place.Navigator { private void doSelectHomePath(){ final SdkType sdkType = (SdkType)mySdk.getSdkType(); - SdkConfigurationUtil.selectSdkHome(sdkType, new Consumer() { - @Override - public void consume(final String path) { - doSetHomePath(path, sdkType); - } - }); + SdkConfigurationUtil.selectSdkHome(sdkType, path -> doSetHomePath(path, sdkType)); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/BuildElementsEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/BuildElementsEditor.java index fc62945801b4..72fb6ce4eecb 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/BuildElementsEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/BuildElementsEditor.java @@ -196,27 +196,24 @@ public class BuildElementsEditor extends ModuleElementsEditor { outputPathsChooserDescriptor.setHideIgnored(false); InsertPathAction.addTo(textField, outputPathsChooserDescriptor); FileChooserFactory.getInstance().installFileCompletion(textField, outputPathsChooserDescriptor, true, null); - final Runnable commitRunnable = new Runnable() { - @Override - public void run() { - if (!getModel().isWritable()) { - return; + final Runnable commitRunnable = () -> { + if (!getModel().isWritable()) { + return; + } + final String path = textField.getText().trim(); + if (path.length() == 0) { + commitPathRunnable.saveUrl(null); + } + else { + // should set only absolute paths + String canonicalPath; + try { + canonicalPath = FileUtil.resolveShortWindowsName(path); } - final String path = textField.getText().trim(); - if (path.length() == 0) { - commitPathRunnable.saveUrl(null); - } - else { - // should set only absolute paths - String canonicalPath; - try { - canonicalPath = FileUtil.resolveShortWindowsName(path); - } - catch (IOException e) { - canonicalPath = path; - } - commitPathRunnable.saveUrl(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(canonicalPath))); + catch (IOException e) { + canonicalPath = path; } + commitPathRunnable.saveUrl(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(canonicalPath))); } }; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ConfigurationErrors.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ConfigurationErrors.java index e0d39838b081..3c6a586f7d98 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ConfigurationErrors.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ConfigurationErrors.java @@ -37,34 +37,24 @@ public interface ConfigurationErrors { @SuppressWarnings({"UtilityClassWithoutPrivateConstructor"}) class Bus { public static void addError(@NotNull final ConfigurationError error, @NotNull final Project project) { - _do(error, project, new PairProcessor() { - @Override - public boolean process(final ConfigurationErrors configurationErrors, final ConfigurationError configurationError) { - configurationErrors.addError(configurationError); - return false; - } + _do(error, project, (configurationErrors, configurationError) -> { + configurationErrors.addError(configurationError); + return false; }); } public static void removeError(@NotNull final ConfigurationError error, @NotNull final Project project) { - _do(error, project, new PairProcessor() { - @Override - public boolean process(final ConfigurationErrors configurationErrors, final ConfigurationError configurationError) { - configurationErrors.removeError(configurationError); - return false; - } + _do(error, project, (configurationErrors, configurationError) -> { + configurationErrors.removeError(configurationError); + return false; }); } public static void _do(@NotNull final ConfigurationError error, @NotNull final Project project, @NotNull final PairProcessor fun) { if (!project.isInitialized()) { - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - @Override - public void run() { - fun.process(project.getMessageBus().syncPublisher(TOPIC), error); - } - }); + StartupManager.getInstance(project).runWhenProjectIsInitialized( + () -> fun.process(project.getMessageBus().syncPublisher(TOPIC), error)); return; } @@ -73,12 +63,7 @@ public interface ConfigurationErrors { if (EventQueue.isDispatchThread()) fun.process(bus.syncPublisher(TOPIC), error); else { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - fun.process(bus.syncPublisher(TOPIC), error); - } - }); + SwingUtilities.invokeLater(() -> fun.process(bus.syncPublisher(TOPIC), error)); } } } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ErrorPaneConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ErrorPaneConfigurable.java index 5641f2b0ae74..87f40e6bebf2 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ErrorPaneConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ErrorPaneConfigurable.java @@ -125,72 +125,69 @@ public class ErrorPaneConfigurable extends JPanel implements Configurable, Dispo public void refresh() { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - final String header = "" + - "

" + - "
" + - ""; - final StringBuilder html = new StringBuilder(header); - int i = 0; - html.append("
    "); - ConfigurationError[] errors; - int currentStamp; - synchronized (myLock) { - errors = myErrors.toArray(new ConfigurationError[0]); - currentStamp = myComputedErrorsStamp; - } + myAlarm.addRequest(() -> { + final String header = "" + + "
    " + + "
    " + + ""; + final StringBuilder html = new StringBuilder(header); + int i = 0; + html.append("
      "); + ConfigurationError[] errors; + int currentStamp; + synchronized (myLock) { + errors = myErrors.toArray(new ConfigurationError[0]); + currentStamp = myComputedErrorsStamp; + } - for (ConfigurationError error : errors) { - i++; - if (i > 100) break; - html.append("
    1. "); - String description; - if (error instanceof ProjectConfigurationProblem) { - //todo[nik] pass ProjectStructureProblemDescription directly and get rid of ConfigurationError at all - ProjectStructureProblemDescription problemDescription = ((ProjectConfigurationProblem)error).getProblemDescription(); - description = problemDescription.getDescription(); - if (description == null) { - ProjectStructureElement place = problemDescription.getPlace().getContainingElement(); - description = XmlStringUtil.convertToHtmlContent(problemDescription.getMessage(false)); - if (problemDescription.canShowPlace()) { - description = place.getTypeName() + " " - + XmlStringUtil.convertToHtmlContent(place.getPresentableName()) + ": " - + StringUtil.decapitalize(description); - } - } - else { - description = XmlStringUtil.convertToHtmlContent(description); + for (ConfigurationError error : errors) { + i++; + if (i > 100) break; + html.append("
    2. "); + String description; + if (error instanceof ProjectConfigurationProblem) { + //todo[nik] pass ProjectStructureProblemDescription directly and get rid of ConfigurationError at all + ProjectStructureProblemDescription problemDescription = ((ProjectConfigurationProblem)error).getProblemDescription(); + description = problemDescription.getDescription(); + if (description == null) { + ProjectStructureElement place = problemDescription.getPlace().getContainingElement(); + description = XmlStringUtil.convertToHtmlContent(problemDescription.getMessage(false)); + if (problemDescription.canShowPlace()) { + description = place.getTypeName() + " " + + XmlStringUtil.convertToHtmlContent(place.getPresentableName()) + ": " + + StringUtil.decapitalize(description); } } else { - description = XmlStringUtil.convertToHtmlContent(error.getDescription()); + description = XmlStringUtil.convertToHtmlContent(description); } - if (error.canBeFixed()) { - description += " [Fix]"; - } - html.append(description).append("
    3. "); } - html.append("
    "); - myContentUpdateQueue.queue(new ShowErrorsUpdate(currentStamp, html.toString())); - if (myOnErrorsChanged != null) { - myOnErrorsChanged.run(); + else { + description = XmlStringUtil.convertToHtmlContent(error.getDescription()); } + if (error.canBeFixed()) { + description += " [Fix]"; + } + html.append(description).append(""); + } + html.append("
"); + myContentUpdateQueue.queue(new ShowErrorsUpdate(currentStamp, html.toString())); + if (myOnErrorsChanged != null) { + myOnErrorsChanged.run(); } }, 100); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/IdeaProjectSettingsService.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/IdeaProjectSettingsService.java index f677f20c173c..e0830afbd0c1 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/IdeaProjectSettingsService.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/IdeaProjectSettingsService.java @@ -44,33 +44,24 @@ public class IdeaProjectSettingsService extends ProjectSettingsService implement @Override public void openProjectSettings() { final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(myProject); - ShowSettingsUtil.getInstance().editConfigurable(myProject, config, new Runnable() { - @Override - public void run() { - config.selectProjectGeneralSettings(true); - } + ShowSettingsUtil.getInstance().editConfigurable(myProject, config, () -> { + config.selectProjectGeneralSettings(true); }); } @Override public void openGlobalLibraries() { final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(myProject); - ShowSettingsUtil.getInstance().editConfigurable(myProject, config, new Runnable() { - @Override - public void run() { - config.selectGlobalLibraries(true); - } + ShowSettingsUtil.getInstance().editConfigurable(myProject, config, () -> { + config.selectGlobalLibraries(true); }); } @Override public void openLibrary(@NotNull final Library library) { final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(myProject); - ShowSettingsUtil.getInstance().editConfigurable(myProject, config, new Runnable() { - @Override - public void run() { - config.selectProjectOrGlobalLibrary(library, true); - } + ShowSettingsUtil.getInstance().editConfigurable(myProject, config, () -> { + config.selectProjectOrGlobalLibrary(library, true); }); } @@ -111,11 +102,8 @@ public class IdeaProjectSettingsService extends ProjectSettingsService implement @Override public void openModuleDependenciesSettings(@NotNull final Module module, @Nullable final OrderEntry orderEntry) { - ShowSettingsUtil.getInstance().editConfigurable(myProject, ProjectStructureConfigurable.getInstance(myProject), new Runnable() { - @Override - public void run() { - ProjectStructureConfigurable.getInstance(myProject).selectOrderEntry(module, orderEntry); - } + ShowSettingsUtil.getInstance().editConfigurable(myProject, ProjectStructureConfigurable.getInstance(myProject), () -> { + ProjectStructureConfigurable.getInstance(myProject).selectOrderEntry(module, orderEntry); }); } @@ -127,14 +115,11 @@ public class IdeaProjectSettingsService extends ProjectSettingsService implement @Override public void openLibraryOrSdkSettings(@NotNull final OrderEntry orderEntry) { final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(myProject); - ShowSettingsUtil.getInstance().editConfigurable(myProject, config, new Runnable() { - @Override - public void run() { - if (orderEntry instanceof JdkOrderEntry) { - config.select(((JdkOrderEntry)orderEntry).getJdk(), true); - } else { - config.select((LibraryOrderEntry)orderEntry, true); - } + ShowSettingsUtil.getInstance().editConfigurable(myProject, config, () -> { + if (orderEntry instanceof JdkOrderEntry) { + config.select(((JdkOrderEntry)orderEntry).getJdk(), true); + } else { + config.select((LibraryOrderEntry)orderEntry, true); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java index feaed160e646..19d33c2fe3a5 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntriesEditor.java @@ -59,12 +59,7 @@ public class JavaContentEntriesEditor extends CommonContentEntriesEditor { List contentEntries = super.addContentEntries(files); if (!contentEntries.isEmpty()) { final ContentEntry[] contentEntriesArray = contentEntries.toArray(new ContentEntry[contentEntries.size()]); - addSourceRoots(myProject, contentEntriesArray, new Runnable() { - @Override - public void run() { - addContentEntryPanels(contentEntriesArray); - } - }); + addSourceRoots(myProject, contentEntriesArray, () -> addContentEntryPanels(contentEntriesArray)); } return contentEntries; } @@ -83,42 +78,33 @@ public class JavaContentEntriesEditor extends CommonContentEntriesEditor { final ProgressWindow progressWindow = new ProgressWindow(true, project); final ProgressIndicator progressIndicator = new SmoothProgressAdapter(progressWindow, project); - final Runnable searchRunnable = new Runnable() { - @Override - public void run() { - final Runnable process = new Runnable() { - @Override - public void run() { - for (final File file : fileToEntryMap.keySet()) { - progressIndicator.setText(ProjectBundle.message("module.paths.searching.source.roots.progress", file.getPath())); - final Collection roots = JavaSourceRootDetectionUtil.suggestRoots(file); - entryToRootMap.put(fileToEntryMap.get(file), roots); - } - } - }; - progressWindow.setTitle(ProjectBundle.message("module.paths.searching.source.roots.title")); - ProgressManager.getInstance().runProcess(process, progressIndicator); - } + final Runnable searchRunnable = () -> { + final Runnable process = () -> { + for (final File file : fileToEntryMap.keySet()) { + progressIndicator.setText(ProjectBundle.message("module.paths.searching.source.roots.progress", file.getPath())); + final Collection roots = JavaSourceRootDetectionUtil.suggestRoots(file); + entryToRootMap.put(fileToEntryMap.get(file), roots); + } + }; + progressWindow.setTitle(ProjectBundle.message("module.paths.searching.source.roots.title")); + ProgressManager.getInstance().runProcess(process, progressIndicator); }; - final Runnable addSourcesRunnable = new Runnable() { - @Override - public void run() { - for (final ContentEntry contentEntry : contentEntries) { - final Collection suggestedRoots = entryToRootMap.get(contentEntry); - if (suggestedRoots != null) { - for (final JavaModuleSourceRoot suggestedRoot : suggestedRoots) { - final VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByIoFile(suggestedRoot.getDirectory()); - final VirtualFile fileContent = contentEntry.getFile(); - if (sourceRoot != null && fileContent != null && VfsUtilCore.isAncestor(fileContent, sourceRoot, false)) { - contentEntry.addSourceFolder(sourceRoot, false, suggestedRoot.getPackagePrefix()); - } + final Runnable addSourcesRunnable = () -> { + for (final ContentEntry contentEntry : contentEntries) { + final Collection suggestedRoots = entryToRootMap.get(contentEntry); + if (suggestedRoots != null) { + for (final JavaModuleSourceRoot suggestedRoot : suggestedRoots) { + final VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByIoFile(suggestedRoot.getDirectory()); + final VirtualFile fileContent = contentEntry.getFile(); + if (sourceRoot != null && fileContent != null && VfsUtilCore.isAncestor(fileContent, sourceRoot, false)) { + contentEntry.addSourceFolder(sourceRoot, false, suggestedRoot.getPackagePrefix()); } } } - if (finishRunnable != null) { - finishRunnable.run(); - } + } + if (finishRunnable != null) { + finishRunnable.run(); } }; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java index ca72f1376e55..9ab06d0bf60b 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java @@ -87,16 +87,13 @@ public abstract class JavaResourceRootEditHandlerBase extends ModuleSourceRootEd final IconActionComponent iconComponent = new IconActionComponent(AllIcons.Modules.SetPackagePrefix, AllIcons.Modules.SetPackagePrefixRollover, ProjectBundle.message("module.paths.edit.properties.tooltip"), - new Runnable() { - @Override - public void run() { - JavaResourceRootProperties properties = folder.getJpsElement().getProperties( JavaModuleSourceRootTypes.RESOURCES); - assert properties != null; - ResourceRootPropertiesDialog - dialog = new ResourceRootPropertiesDialog(parentComponent, properties); - if (dialog.showAndGet()) { - callback.onSourceRootPropertiesChanged(folder); - } + () -> { + JavaResourceRootProperties properties = folder.getJpsElement().getProperties( JavaModuleSourceRootTypes.RESOURCES); + assert properties != null; + ResourceRootPropertiesDialog + dialog = new ResourceRootPropertiesDialog(parentComponent, properties); + if (dialog.showAndGet()) { + callback.onSourceRootPropertiesChanged(folder); } }); final JPanel panel = new JPanel(new BorderLayout()); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java index 41899d69db0b..21852614aa7a 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java @@ -147,19 +147,16 @@ public class JdkComboBox extends ComboBoxWithWidePopup { @Override public void actionPerformed(ActionEvent e) { DefaultActionGroup group = new DefaultActionGroup(); - jdksModel.createAddActions(group, JdkComboBox.this, new Consumer() { - @Override - public void consume(final Sdk jdk) { - if (project != null) { - final JdkListConfigurable configurable = JdkListConfigurable.getInstance(project); - configurable.addJdkNode(jdk, false); - } - reloadModel(new JdkComboBoxItem(jdk), project); - setSelectedJdk(jdk); //restore selection - if (additionalSetup != null) { - if (additionalSetup.value(jdk)) { //leave old selection - setSelectedJdk(firstItem.getJdk()); - } + jdksModel.createAddActions(group, JdkComboBox.this, jdk -> { + if (project != null) { + final JdkListConfigurable configurable = JdkListConfigurable.getInstance(project); + configurable.addJdkNode(jdk, false); + } + reloadModel(new JdkComboBoxItem(jdk), project); + setSelectedJdk(jdk); //restore selection + if (additionalSetup != null) { + if (additionalSetup.value(jdk)) { //leave old selection + setSelectedJdk(firstItem.getJdk()); } } }, myCreationFilter); @@ -279,12 +276,7 @@ public class JdkComboBox extends ComboBoxWithWidePopup { if (myFilter != null) { projectJdks = ContainerUtil.filter(projectJdks, getSdkFilter(myFilter)); } - Collections.sort(projectJdks, new Comparator() { - @Override - public int compare(final Sdk o1, final Sdk o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Collections.sort(projectJdks, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Sdk projectJdk : projectJdks) { model.addElement(new JdkComboBox.JdkComboBoxItem(projectJdk)); } @@ -297,12 +289,7 @@ public class JdkComboBox extends ComboBoxWithWidePopup { final List filtered = ContainerUtil.filter(jdks, sdkFilter); jdks = filtered.toArray(new Sdk[filtered.size()]); } - Arrays.sort(jdks, new Comparator() { - @Override - public int compare(final Sdk s1, final Sdk s2) { - return s1.getName().compareToIgnoreCase(s2.getName()); - } - }); + Arrays.sort(jdks, (s1, s2) -> s1.getName().compareToIgnoreCase(s2.getName())); for (Sdk jdk : jdks) { addElement(new JdkComboBoxItem(jdk)); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java index c6565634a5bc..4c40a9c88e6d 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java @@ -73,17 +73,14 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change private final Project myProject; - private final Map myModuleEditors = new TreeMap(new Comparator() { - @Override - public int compare(Module o1, Module o2) { - String n1 = o1.getName(); - String n2 = o2.getName(); - int result = n1.compareToIgnoreCase(n2); - if (result != 0) { - return result; - } - return n1.compareTo(n2); + private final Map myModuleEditors = new TreeMap((o1, o2) -> { + String n1 = o1.getName(); + String n2 = o2.getName(); + int result = n1.compareToIgnoreCase(n2); + if (result != 0) { + return result; } + return n1.compareTo(n2); }); private boolean myModified = false; @@ -109,19 +106,16 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change } public void disposeUIResources() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (final ModuleEditor moduleEditor : myModuleEditors.values()) { - Disposer.dispose(moduleEditor); - } - myModuleEditors.clear(); + ApplicationManager.getApplication().runWriteAction(() -> { + for (final ModuleEditor moduleEditor : myModuleEditors.values()) { + Disposer.dispose(moduleEditor); + } + myModuleEditors.clear(); - myModuleModel.dispose(); + myModuleModel.dispose(); - if (myFacetsConfigurator != null) { - myFacetsConfigurator.disposeEditors(); - } + if (myFacetsConfigurator != null) { + myFacetsConfigurator.disposeEditors(); } }); } @@ -189,18 +183,15 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change public void resetModuleEditors() { myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (!myModuleEditors.isEmpty()) { - LOG.error("module editors was not disposed"); - myModuleEditors.clear(); - } - final Module[] modules = myModuleModel.getModules(); - if (modules.length > 0) { - for (Module module : modules) { - getOrCreateModuleEditor(module); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (!myModuleEditors.isEmpty()) { + LOG.error("module editors was not disposed"); + myModuleEditors.clear(); + } + final Module[] modules = myModuleModel.getModules(); + if (modules.length > 0) { + for (Module module : modules) { + getOrCreateModuleEditor(module); } } }); @@ -296,47 +287,44 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change } final Ref exceptionRef = Ref.create(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - for (final ModuleEditor moduleEditor : myModuleEditors.values()) { - final ModifiableRootModel model = moduleEditor.apply(); - if (model != null) { - if (!model.isSdkInherited()) { - // make sure the sdk is set to original SDK stored in the JDK Table - final Sdk modelSdk = model.getSdk(); - if (modelSdk != null) { - final Sdk original = modifiedToOriginalMap.get(modelSdk); - if (original != null) { - model.setSdk(original); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + for (final ModuleEditor moduleEditor : myModuleEditors.values()) { + final ModifiableRootModel model = moduleEditor.apply(); + if (model != null) { + if (!model.isSdkInherited()) { + // make sure the sdk is set to original SDK stored in the JDK Table + final Sdk modelSdk = model.getSdk(); + if (modelSdk != null) { + final Sdk original = modifiedToOriginalMap.get(modelSdk); + if (original != null) { + model.setSdk(original); } } - models.add(model); } + models.add(model); } - myFacetsConfigurator.applyEditors(); - } - catch (ConfigurationException e) { - exceptionRef.set(e); - return; } + myFacetsConfigurator.applyEditors(); + } + catch (ConfigurationException e) { + exceptionRef.set(e); + return; + } - try { - final ModifiableRootModel[] rootModels = models.toArray(new ModifiableRootModel[models.size()]); - ModifiableModelCommitter.multiCommit(rootModels, myModuleModel); - myModuleModelCommitted = true; - myFacetsConfigurator.commitFacets(); + try { + final ModifiableRootModel[] rootModels = models.toArray(new ModifiableRootModel[models.size()]); + ModifiableModelCommitter.multiCommit(rootModels, myModuleModel); + myModuleModelCommitted = true; + myFacetsConfigurator.commitFacets(); - } - finally { - ModuleStructureConfigurable.getInstance(myProject).getFacetEditorFacade().clearMaps(false); + } + finally { + ModuleStructureConfigurable.getInstance(myProject).getFacetEditorFacade().clearMaps(false); - myFacetsConfigurator = createFacetsConfigurator(); - myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel(); - myModuleModelCommitted = false; - } + myFacetsConfigurator = createFacetsConfigurator(); + myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel(); + myModuleModelCommitted = false; } }); @@ -386,30 +374,24 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change final ProjectBuilder builder = runModuleWizard(parent, anImport); if (builder != null ) { final List modules = new ArrayList(); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - final List committedModules; - if (builder instanceof ProjectImportBuilder) { - final ModifiableArtifactModel artifactModel = - ProjectStructureConfigurable.getInstance(myProject).getArtifactsStructureConfigurable().getModifiableArtifactModel(); - committedModules = ((ProjectImportBuilder)builder).commit(myProject, myModuleModel, ModulesConfigurator.this, artifactModel); - } - else { - committedModules = builder.commit(myProject, myModuleModel, ModulesConfigurator.this); - } - if (committedModules != null) { - modules.addAll(committedModules); - } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (Module module : modules) { - getOrCreateModuleEditor(module); - } - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + final List committedModules; + if (builder instanceof ProjectImportBuilder) { + final ModifiableArtifactModel artifactModel = + ProjectStructureConfigurable.getInstance(myProject).getArtifactsStructureConfigurable().getModifiableArtifactModel(); + committedModules = ((ProjectImportBuilder)builder).commit(myProject, myModuleModel, ModulesConfigurator.this, artifactModel); } + else { + committedModules = builder.commit(myProject, myModuleModel, ModulesConfigurator.this); + } + if (committedModules != null) { + modules.addAll(committedModules); + } + ApplicationManager.getApplication().runWriteAction(() -> { + for (Module module : modules) { + getOrCreateModuleEditor(module); + } + }); }); return modules; } @@ -436,11 +418,8 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change public Module addModule(final ModuleBuilder moduleBuilder) { final Module module = createModule(moduleBuilder); if (module != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - getOrCreateModuleEditor(module); - } + ApplicationManager.getApplication().runWriteAction(() -> { + getOrCreateModuleEditor(module); }); processModuleCountChanged(); } @@ -544,11 +523,8 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change public static boolean showArtifactSettings(@NotNull Project project, @Nullable final Artifact artifact) { final ProjectStructureConfigurable configurable = ProjectStructureConfigurable.getInstance(project); - return ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - configurable.select(artifact, true); - } + return ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + configurable.select(artifact, true); }); } @@ -556,30 +532,21 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change @Nullable final String tabNameToSelect) { final Project project = facet.getModule().getProject(); final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(project); - return ShowSettingsUtil.getInstance().editConfigurable(project, config, new Runnable() { - @Override - public void run() { - final ModuleStructureConfigurable modulesConfig = config.getModulesConfig(); - config.select(facet, true).doWhenDone(new Runnable() { - @Override - public void run() { - if (tabNameToSelect != null) { - FacetEditorImpl facetEditor = modulesConfig.getFacetConfigurator().getOrCreateEditor(facet); - facetEditor.setSelectedTabName(tabNameToSelect); - } - } - }); - } + return ShowSettingsUtil.getInstance().editConfigurable(project, config, () -> { + final ModuleStructureConfigurable modulesConfig = config.getModulesConfig(); + config.select(facet, true).doWhenDone(() -> { + if (tabNameToSelect != null) { + FacetEditorImpl facetEditor = modulesConfig.getFacetConfigurator().getOrCreateEditor(facet); + facetEditor.setSelectedTabName(tabNameToSelect); + } + }); }); } public static boolean showDialog(Project project, @Nullable final String moduleToSelect, @Nullable final String editorNameToSelect) { final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(project); - return ShowSettingsUtil.getInstance().editConfigurable(project, config, new Runnable() { - @Override - public void run() { - config.select(moduleToSelect, editorNameToSelect, true); - } + return ShowSettingsUtil.getInstance().editConfigurable(project, config, () -> { + config.select(moduleToSelect, editorNameToSelect, true); }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java index b39243e32253..c7ba4bd48505 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java @@ -224,38 +224,35 @@ public class ProjectConfigurable extends ProjectStructureElementConfigurable 0) { - try { - canonicalPath = FileUtil.resolveShortWindowsName(canonicalPath); - } - catch (IOException e) { - //file doesn't exist yet - } - canonicalPath = FileUtil.toSystemIndependentName(canonicalPath); - compilerProjectExtension.setCompilerOutputUrl(VfsUtilCore.pathToUrl(canonicalPath)); + ApplicationManager.getApplication().runWriteAction(() -> { + // set the output path first so that handlers of RootsChanged event sent after JDK is set + // would see the updated path + String canonicalPath = myProjectCompilerOutput.getText(); + if (canonicalPath != null && canonicalPath.length() > 0) { + try { + canonicalPath = FileUtil.resolveShortWindowsName(canonicalPath); } - else { - compilerProjectExtension.setCompilerOutputPointer(null); + catch (IOException e) { + //file doesn't exist yet } + canonicalPath = FileUtil.toSystemIndependentName(canonicalPath); + compilerProjectExtension.setCompilerOutputUrl(VfsUtilCore.pathToUrl(canonicalPath)); + } + else { + compilerProjectExtension.setCompilerOutputPointer(null); + } - LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(myProject); - LanguageLevel level = myLanguageLevelCombo.getSelectedLevel(); - if (level != null) { - extension.setLanguageLevel(level); - } - extension.setDefault(myLanguageLevelCombo.isDefault()); - myProjectJdkConfigurable.apply(); + LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(myProject); + LanguageLevel level = myLanguageLevelCombo.getSelectedLevel(); + if (level != null) { + extension.setLanguageLevel(level); + } + extension.setDefault(myLanguageLevelCombo.isDefault()); + myProjectJdkConfigurable.apply(); - if (myProjectName != null) { - ((ProjectEx)myProject).setProjectName(getProjectName()); - if (myDetailsComponent != null) myDetailsComponent.setText(getBannerSlogan()); - } + if (myProjectName != null) { + ((ProjectEx)myProject).setProjectName(getProjectName()); + if (myDetailsComponent != null) myDetailsComponent.setText(getBannerSlogan()); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectJdksConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectJdksConfigurable.java index c03abc08f361..c64af9493c1b 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectJdksConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectJdksConfigurable.java @@ -163,12 +163,9 @@ public class ProjectJdksConfigurable extends MasterDetailsComponent { final ArrayList actions = new ArrayList(); DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.new.jdk.text"), true); group.getTemplatePresentation().setIcon(IconUtil.getAddIcon()); - myProjectJdksModel.createAddActions(group, myTree, new Consumer() { - @Override - public void consume(final Sdk projectJdk) { - addNode(new MyNode(new JdkConfigurable(((ProjectJdkImpl)projectJdk), myProjectJdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot); - selectNodeInTree(findNodeByObject(myRoot, projectJdk)); - } + myProjectJdksModel.createAddActions(group, myTree, projectJdk -> { + addNode(new MyNode(new JdkConfigurable(((ProjectJdkImpl)projectJdk), myProjectJdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot); + selectNodeInTree(findNodeByObject(myRoot, projectJdk)); }); actions.add(new MyActionGroupWrapper(group)); actions.add(new MyDeleteAction(Conditions.alwaysTrue())); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectStructureConfigurable.java index 5e4850c8fc2c..ea309509be0b 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectStructureConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectStructureConfigurable.java @@ -292,12 +292,7 @@ public class ProjectStructureConfigurable extends BaseConfigurable implements Se } private void addErrorPane() { - addConfigurable(new ErrorPaneConfigurable(myProject, myContext, new Runnable() { - @Override - public void run() { - mySidePanel.getList().repaint(); - } - }), true); + addConfigurable(new ErrorPaneConfigurable(myProject, myContext, () -> mySidePanel.getList().repaint()), true); } private void addGlobalLibrariesConfig() { @@ -342,11 +337,7 @@ public class ProjectStructureConfigurable extends BaseConfigurable implements Se } myContext.getDaemonAnalyzer().clearCaches(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - BuildManager.getInstance().scheduleAutoMake(); - } - }); + SwingUtilities.invokeLater(() -> BuildManager.getInstance().scheduleAutoMake()); } @Override diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactEditorImpl.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactEditorImpl.java index 5c72bf201337..ec222e86f6c2 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactEditorImpl.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactEditorImpl.java @@ -424,19 +424,16 @@ public class ArtifactEditorImpl implements ArtifactEditorEx { } private void doReplaceElement(final @NotNull String pathToParent, final @NotNull PackagingElement element, final @Nullable PackagingElement replacement) { - myLayoutTreeComponent.editLayout(new Runnable() { - @Override - public void run() { - final CompositePackagingElement parent = findCompositeElementByPath(pathToParent); - if (parent == null) return; - for (PackagingElement child : parent.getChildren()) { - if (child.isEqualTo(element)) { - parent.removeChild(child); - if (replacement != null) { - parent.addOrFindChild(replacement); - } - break; + myLayoutTreeComponent.editLayout(() -> { + final CompositePackagingElement parent = findCompositeElementByPath(pathToParent); + if (parent == null) return; + for (PackagingElement child : parent.getChildren()) { + if (child.isEqualTo(element)) { + parent.removeChild(child); + if (replacement != null) { + parent.addOrFindChild(replacement); } + break; } } }); @@ -487,12 +484,8 @@ public class ArtifactEditorImpl implements ArtifactEditorEx { final String fileName = FileUtil.getNameWithoutExtension(name); final String extension = FileUtilRt.getExtension(name); if (fileName.equals(oldFileName) && extension.length() > 0) { - myLayoutTreeComponent.editLayout(new Runnable() { - @Override - public void run() { - ((ArchivePackagingElement)getRootElement()).setArchiveFileName(ArtifactUtil.suggestArtifactFileName(newArtifactName) + "." + extension); - } - }); + myLayoutTreeComponent.editLayout( + () -> ((ArchivePackagingElement)getRootElement()).setArchiveFileName(ArtifactUtil.suggestArtifactFileName(newArtifactName) + "." + extension)); myLayoutTreeComponent.updateRootNode(); } } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactPropertiesEditors.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactPropertiesEditors.java index 1828daa47940..aa792a0972cc 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactPropertiesEditors.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactPropertiesEditors.java @@ -69,18 +69,15 @@ public class ArtifactPropertiesEditors { public void addTabs(TabbedPaneWrapper tabbedPane) { List sortedTabs = new ArrayList(myMainPanels.keySet()); - Collections.sort(sortedTabs, new Comparator() { - @Override - public int compare(String o1, String o2) { - int i1 = STANDARD_TABS_ORDER.indexOf(o1); - if (i1 == -1) i1 = STANDARD_TABS_ORDER.size(); - int i2 = STANDARD_TABS_ORDER.indexOf(o2); - if (i2 == -1) i2 = STANDARD_TABS_ORDER.size(); - if (i1 != i2) { - return i1 - i2; - } - return o1.compareTo(o2); + Collections.sort(sortedTabs, (o1, o2) -> { + int i1 = STANDARD_TABS_ORDER.indexOf(o1); + if (i1 == -1) i1 = STANDARD_TABS_ORDER.size(); + int i2 = STANDARD_TABS_ORDER.indexOf(o2); + if (i2 == -1) i2 = STANDARD_TABS_ORDER.size(); + if (i1 != i2) { + return i1 - i2; } + return o1.compareTo(o2); }); for (String tab : sortedTabs) { tabbedPane.addTab(tab, myMainPanels.get(tab)); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactsStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactsStructureConfigurable.java index b0141f0e12e1..b619aa8183c6 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactsStructureConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactsStructureConfigurable.java @@ -128,20 +128,17 @@ public class ArtifactsStructureConfigurable extends BaseStructureConfigurable { }, myPackagingEditorContext, false, artifact.getArtifactType())) { return; } - myPackagingEditorContext.editLayout(artifact, new Runnable() { - @Override - public void run() { - final ModifiableArtifact modifiableArtifact = myPackagingEditorContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(artifact); - ArtifactUtil.processPackagingElements(modifiableArtifact, LibraryElementType.LIBRARY_ELEMENT_TYPE, new PackagingElementProcessor() { - @Override - public boolean process(@NotNull LibraryPackagingElement element, @NotNull PackagingElementPath path) { - if (isResolvedToLibrary(element, library, oldName)) { - element.setLibraryName(newName); - } - return true; + myPackagingEditorContext.editLayout(artifact, () -> { + final ModifiableArtifact modifiableArtifact = myPackagingEditorContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(artifact); + ArtifactUtil.processPackagingElements(modifiableArtifact, LibraryElementType.LIBRARY_ELEMENT_TYPE, new PackagingElementProcessor() { + @Override + public boolean process(@NotNull LibraryPackagingElement element, @NotNull PackagingElementPath path) { + if (isResolvedToLibrary(element, library, oldName)) { + element.setLibraryName(newName); } - }, myPackagingEditorContext, false); - } + return true; + } + }, myPackagingEditorContext, false); }); final ArtifactEditorImpl artifactEditor = myPackagingEditorContext.getArtifactEditor(artifact); if (artifactEditor != null) { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTree.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTree.java index 9ac88ac60f82..51c9343fe101 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTree.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTree.java @@ -220,12 +220,7 @@ public class LayoutTree extends SimpleDnDAwareTree implements AdvancedDnDSource final boolean stopped = super.stopCellEditing(); if (stopped && currentElement != null) { final RenameablePackagingElement finalCurrentElement = currentElement; - myArtifactsEditor.getLayoutTreeComponent().editLayout(new Runnable() { - @Override - public void run() { - finalCurrentElement.rename(newValue); - } - }); + myArtifactsEditor.getLayoutTreeComponent().editLayout(() -> finalCurrentElement.rename(newValue)); myArtifactsEditor.queueValidation(); myArtifactsEditor.getLayoutTreeComponent().updatePropertiesPanel(true); addSubtreeToUpdate((DefaultMutableTreeNode)path.getLastPathComponent()); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java index 9af028023322..4ec706a1daaa 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/LayoutTreeComponent.java @@ -185,13 +185,10 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { final List> children = type.chooseAndCreate(myContext, getArtifact(), parent); final PackagingElementNode finalParentNode = parentNode; - editLayout(new Runnable() { - @Override - public void run() { - CompositePackagingElement actualParent = getOrCreateModifiableParent(parent, finalParentNode); - for (PackagingElement child : children) { - actualParent.addOrFindChild(child); - } + editLayout(() -> { + CompositePackagingElement actualParent = getOrCreateModifiableParent(parent, finalParentNode); + for (PackagingElement child : children) { + actualParent.addOrFindChild(child); } }); updateAndSelect(parentNode, children); @@ -291,12 +288,9 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { public void updateAndSelect(PackagingElementNode node, final List> toSelect) { myArtifactsEditor.queueValidation(); myTreeStructure.clearCaches(); - myBuilder.queueUpdateFrom(node, true).doWhenDone(new Runnable() { - @Override - public void run() { - List> nodes = myTree.findNodes(toSelect); - myBuilder.select(ArrayUtil.toObjectArray(nodes), null); - } + myBuilder.queueUpdateFrom(node, true).doWhenDone(() -> { + List> nodes = myTree.findNodes(toSelect); + myBuilder.select(ArrayUtil.toObjectArray(nodes), null); }); } @@ -340,12 +334,7 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { final LayoutTreeSelection selection = myTree.getSelection(); if (!checkCanRemove(selection.getNodes())) return; - editLayout(new Runnable() { - @Override - public void run() { - removeNodes(selection.getNodes()); - } - }); + editLayout(() -> removeNodes(selection.getNodes())); myArtifactsEditor.rebuildTries(); } @@ -458,15 +447,12 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { return; } final List> toSelect = new ArrayList>(); - editLayout(new Runnable() { - @Override - public void run() { - draggingObject.beforeDrop(); - final CompositePackagingElement parent = getOrCreateModifiableParent(targetElement, targetNode); - for (PackagingElement element : draggingObject.createPackagingElements(myContext)) { - toSelect.add(element); - parent.addOrFindChild(element); - } + editLayout(() -> { + draggingObject.beforeDrop(); + final CompositePackagingElement parent = getOrCreateModifiableParent(targetElement, targetNode); + for (PackagingElement element : draggingObject.createPackagingElements(myContext)) { + toSelect.add(element); + parent.addOrFindChild(element); } }); updateAndSelect(targetNode, toSelect); @@ -532,24 +518,21 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { public void putIntoDefaultLocations(@NotNull final List items) { final List> toSelect = new ArrayList>(); - editLayout(new Runnable() { - @Override - public void run() { - final CompositePackagingElement rootElement = getArtifact().getRootElement(); - final ArtifactType artifactType = getArtifact().getArtifactType(); - for (PackagingSourceItem item : items) { - final String path = artifactType.getDefaultPathFor(item); - if (path != null) { - final CompositePackagingElement parent; - if (path.endsWith(URLUtil.JAR_SEPARATOR)) { - parent = PackagingElementFactory.getInstance().getOrCreateArchive(rootElement, StringUtil.trimEnd(path, URLUtil.JAR_SEPARATOR)); - } - else { - parent = PackagingElementFactory.getInstance().getOrCreateDirectory(rootElement, path); - } - final List> elements = item.createElements(myContext); - toSelect.addAll(parent.addOrFindChildren(elements)); + editLayout(() -> { + final CompositePackagingElement rootElement = getArtifact().getRootElement(); + final ArtifactType artifactType = getArtifact().getArtifactType(); + for (PackagingSourceItem item : items) { + final String path = artifactType.getDefaultPathFor(item); + if (path != null) { + final CompositePackagingElement parent; + if (path.endsWith(URLUtil.JAR_SEPARATOR)) { + parent = PackagingElementFactory.getInstance().getOrCreateArchive(rootElement, StringUtil.trimEnd(path, URLUtil.JAR_SEPARATOR)); } + else { + parent = PackagingElementFactory.getInstance().getOrCreateDirectory(rootElement, path); + } + final List> elements = item.createElements(myContext); + toSelect.addAll(parent.addOrFindChildren(elements)); } } }); @@ -560,13 +543,10 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { public void putElements(@NotNull final String path, @NotNull final List> elements) { final List> toSelect = new ArrayList>(); - editLayout(new Runnable() { - @Override - public void run() { - final CompositePackagingElement directory = - PackagingElementFactory.getInstance().getOrCreateDirectory(getArtifact().getRootElement(), path); - toSelect.addAll(directory.addOrFindChildren(elements)); - } + editLayout(() -> { + final CompositePackagingElement directory = + PackagingElementFactory.getInstance().getOrCreateDirectory(getArtifact().getRootElement(), path); + toSelect.addAll(directory.addOrFindChildren(elements)); }); myArtifactsEditor.getSourceItemsTree().rebuildTree(); updateAndSelect(myTree.getRootPackagingNode(), toSelect); @@ -575,16 +555,13 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { public void packInto(@NotNull final List items, final String pathToJar) { final List> toSelect = new ArrayList>(); final CompositePackagingElement rootElement = getArtifact().getRootElement(); - editLayout(new Runnable() { - @Override - public void run() { - final CompositePackagingElement archive = PackagingElementFactory.getInstance().getOrCreateArchive(rootElement, pathToJar); - for (PackagingSourceItem item : items) { - final List> elements = item.createElements(myContext); - archive.addOrFindChildren(elements); - } - toSelect.add(archive); + editLayout(() -> { + final CompositePackagingElement archive = PackagingElementFactory.getInstance().getOrCreateArchive(rootElement, pathToJar); + for (PackagingSourceItem item : items) { + final List> elements = item.createElements(myContext); + archive.addOrFindChildren(elements); } + toSelect.add(archive); }); myArtifactsEditor.getSourceItemsTree().rebuildTree(); @@ -627,12 +604,7 @@ public class LayoutTreeComponent implements DnDTarget, Disposable { public void save() { if (myCurrentPanel != null && myCurrentPanel.isModified()) { - editLayout(new Runnable() { - @Override - public void run() { - myCurrentPanel.apply(); - } - }); + editLayout(() -> myCurrentPanel.apply()); } } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/PlaceInArtifact.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/PlaceInArtifact.java index 7e451e77b192..1478e79a439c 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/PlaceInArtifact.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/PlaceInArtifact.java @@ -60,13 +60,10 @@ public class PlaceInArtifact extends PlaceInProjectStructure { @Override public ActionCallback navigate() { final Artifact artifact = myContext.getArtifactModel().getArtifactByOriginal(myArtifact); - return ProjectStructureConfigurable.getInstance(myContext.getProject()).select(myArtifact, true).doWhenDone(new Runnable() { - @Override - public void run() { - final ArtifactEditorEx artifactEditor = (ArtifactEditorEx)myContext.getOrCreateEditor(artifact); - if (myParentPath != null && myPackagingElement != null) { - artifactEditor.getLayoutTreeComponent().selectNode(myParentPath, myPackagingElement); - } + return ProjectStructureConfigurable.getInstance(myContext.getProject()).select(myArtifact, true).doWhenDone(() -> { + final ArtifactEditorEx artifactEditor = (ArtifactEditorEx)myContext.getOrCreateEditor(artifact); + if (myParentPath != null && myPackagingElement != null) { + artifactEditor.getLayoutTreeComponent().selectNode(myParentPath, myPackagingElement); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/ExtractArtifactAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/ExtractArtifactAction.java index 379086aec94a..ad9f9e78844f 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/ExtractArtifactAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/ExtractArtifactAction.java @@ -73,17 +73,14 @@ public class ExtractArtifactAction extends LayoutTreeActionBase { final Project project = myArtifactEditor.getContext().getProject(); final ModifiableArtifactModel model = myArtifactEditor.getContext().getOrCreateModifiableArtifactModel(); final ModifiableArtifact artifact = model.addArtifact(dialog.getArtifactName(), dialog.getArtifactType()); - treeComponent.editLayout(new Runnable() { - @Override - public void run() { - for (PackagingElement element : selectedElements) { - artifact.getRootElement().addOrFindChild(ArtifactUtil.copyWithChildren(element, project)); - } - for (PackagingElement element : selectedElements) { - parent.removeChild(element); - } - parent.addOrFindChild(new ArtifactPackagingElement(project, ArtifactPointerManager.getInstance(project).createPointer(artifact, myArtifactEditor.getContext().getArtifactModel()))); + treeComponent.editLayout(() -> { + for (PackagingElement element : selectedElements) { + artifact.getRootElement().addOrFindChild(ArtifactUtil.copyWithChildren(element, project)); } + for (PackagingElement element : selectedElements) { + parent.removeChild(element); + } + parent.addOrFindChild(new ArtifactPackagingElement(project, ArtifactPointerManager.getInstance(project).createPointer(artifact, myArtifactEditor.getContext().getArtifactModel()))); }); treeComponent.rebuildTree(); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/InlineArtifactAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/InlineArtifactAction.java index b54b57ce4136..1eb631642d4e 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/InlineArtifactAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/InlineArtifactAction.java @@ -67,23 +67,20 @@ public class InlineArtifactAction extends DumbAwareAction { } if (!treeComponent.checkCanModifyChildren(parent, parentNode, Collections.singletonList(node))) return; - treeComponent.editLayout(new Runnable() { - @Override - public void run() { - parent.removeChild(element); - final ArtifactEditorContext context = myEditor.getContext(); - final Artifact artifact = ((ArtifactPackagingElement)element).findArtifact(context); - if (artifact != null) { - final CompositePackagingElement rootElement = artifact.getRootElement(); - if (rootElement instanceof ArtifactRootElement) { - for (PackagingElement child : rootElement.getChildren()) { - parent.addOrFindChild(ArtifactUtil.copyWithChildren(child, context.getProject())); - } - } - else { - parent.addOrFindChild(ArtifactUtil.copyWithChildren(rootElement, context.getProject())); + treeComponent.editLayout(() -> { + parent.removeChild(element); + final ArtifactEditorContext context = myEditor.getContext(); + final Artifact artifact = ((ArtifactPackagingElement)element).findArtifact(context); + if (artifact != null) { + final CompositePackagingElement rootElement = artifact.getRootElement(); + if (rootElement instanceof ArtifactRootElement) { + for (PackagingElement child : rootElement.getChildren()) { + parent.addOrFindChild(ArtifactUtil.copyWithChildren(child, context.getProject())); } } + else { + parent.addOrFindChild(ArtifactUtil.copyWithChildren(rootElement, context.getProject())); + } } }); treeComponent.rebuildTree(); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/MovePackagingElementAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/MovePackagingElementAction.java index 85e316d01053..e5544de185bd 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/MovePackagingElementAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/MovePackagingElementAction.java @@ -82,14 +82,11 @@ public class MovePackagingElementAction extends DumbAwareAction { if (!myLayoutTreeComponent.checkCanModifyChildren(parentElement, parent, Arrays.asList(node))) return; final List> toSelect = new ArrayList>(); - myLayoutTreeComponent.editLayout(new Runnable() { - @Override - public void run() { - final int index = parentElement.getChildren().indexOf(element); - final PackagingElement moved = parentElement.moveChild(index, myDirection); - if (moved != null) { - toSelect.add(moved); - } + myLayoutTreeComponent.editLayout(() -> { + final int index = parentElement.getChildren().indexOf(element); + final PackagingElement moved = parentElement.moveChild(index, myDirection); + if (moved != null) { + toSelect.add(moved); } }); if (!toSelect.isEmpty()) { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/SurroundElementWithAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/SurroundElementWithAction.java index e3b0a7aa0858..a33f5c62b0e5 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/SurroundElementWithAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/actions/SurroundElementWithAction.java @@ -101,17 +101,14 @@ public class SurroundElementWithAction extends LayoutTreeActionBase { final String baseName = PathUtil.suggestFileName(elementName); final CompositePackagingElement newParent = type.createComposite(parent, baseName, myArtifactEditor.getContext()); if (newParent != null) { - treeComponent.editLayout(new Runnable() { - @Override - public void run() { - for (PackagingElement element : selected) { - newParent.addOrFindChild(ArtifactUtil.copyWithChildren(element, project)); - } - for (PackagingElement element : selected) { - parent.removeChild(element); - } - parent.addOrFindChild(newParent); + treeComponent.editLayout(() -> { + for (PackagingElement element : selected) { + newParent.addOrFindChild(ArtifactUtil.copyWithChildren(element, project)); } + for (PackagingElement element : selected) { + parent.removeChild(element); + } + parent.addOrFindChild(newParent); }); treeComponent.rebuildTree(); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/FacetBasedPackagingSourceItemsProvider.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/FacetBasedPackagingSourceItemsProvider.java index 3d15845a4f3a..11c9ff88da10 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/FacetBasedPackagingSourceItemsProvider.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/FacetBasedPackagingSourceItemsProvider.java @@ -49,15 +49,12 @@ public abstract class FacetBasedPackagingSourceItemsProvider facets = new HashSet(editorContext.getFacetsProvider().getFacetsByType(module, myFacetTypeId)); - ArtifactUtil.processPackagingElements(artifact, myElementType, new Processor() { - @Override - public boolean process(E e) { - F facet = getFacet(e); - if (facet != null) { - facets.remove(facet); - } - return true; + ArtifactUtil.processPackagingElements(artifact, myElementType, e -> { + F facet = getFacet(e); + if (facet != null) { + facets.remove(facet); } + return true; }, editorContext, true); if (!facets.isEmpty()) { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/ModulesAndLibrariesSourceItemsProvider.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/ModulesAndLibrariesSourceItemsProvider.java index 5ff0a85fef05..5867f010153f 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/ModulesAndLibrariesSourceItemsProvider.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/ModulesAndLibrariesSourceItemsProvider.java @@ -125,15 +125,12 @@ public class ModulesAndLibrariesSourceItemsProvider extends PackagingSourceItems private static List getNotAddedLibraries(@NotNull final ArtifactEditorContext context, @NotNull Artifact artifact, List librariesList) { final Set roots = new HashSet(); - ArtifactUtil.processPackagingElements(artifact, PackagingElementFactoryImpl.FILE_COPY_ELEMENT_TYPE, new Processor() { - @Override - public boolean process(FileCopyPackagingElement fileCopyPackagingElement) { - final VirtualFile root = fileCopyPackagingElement.getLibraryRoot(); - if (root != null) { - roots.add(root); - } - return true; + ArtifactUtil.processPackagingElements(artifact, PackagingElementFactoryImpl.FILE_COPY_ELEMENT_TYPE, fileCopyPackagingElement -> { + final VirtualFile root = fileCopyPackagingElement.getLibraryRoot(); + if (root != null) { + roots.add(root); } + return true; }, context, true); final List result = new ArrayList(); for (Library library : librariesList) { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/actions/PutSourceItemIntoParentAndLinkViaManifestAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/actions/PutSourceItemIntoParentAndLinkViaManifestAction.java index 96e99ffd870f..7d4f65f4eb48 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/actions/PutSourceItemIntoParentAndLinkViaManifestAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/sourceItems/actions/PutSourceItemIntoParentAndLinkViaManifestAction.java @@ -111,14 +111,11 @@ public class PutSourceItemIntoParentAndLinkViaManifestAction extends PutIntoDefa final CompositePackagingElement grandParent = parentsInfo.getGrandparentElement(); final List classpath = new ArrayList(); - context.editLayout(artifact, new Runnable() { - @Override - public void run() { - for (PackagingSourceItem item : items) { - final List> elements = item.createElements(context); - grandParent.addOrFindChildren(elements); - classpath.addAll(ManifestFileUtil.getClasspathForElements(elements, context, artifact.getArtifactType())); - } + context.editLayout(artifact, () -> { + for (PackagingSourceItem item : items) { + final List> elements = item.createElements(context); + grandParent.addOrFindChildren(elements); + classpath.addAll(ManifestFileUtil.getClasspathForElements(elements, context, artifact.getArtifactType())); } }); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddLibraryDependencyAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddLibraryDependencyAction.java index a671153aaab4..c1d97143c948 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddLibraryDependencyAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddLibraryDependencyAction.java @@ -54,12 +54,8 @@ class AddLibraryDependencyAction extends AddItemPopupAction { @Override public PopupStep createSubStep() { - return LibraryEditingUtil.createChooseTypeStep(myClasspathPanel, new ParameterizedRunnable() { - @Override - public void run(LibraryType libraryType) { - new AddNewLibraryDependencyAction(myClasspathPanel, myContext, libraryType).execute(); - } - }); + return LibraryEditingUtil.createChooseTypeStep(myClasspathPanel, + libraryType -> new AddNewLibraryDependencyAction(myClasspathPanel, myContext, libraryType).execute()); } @Override diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddNewLibraryDependencyAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddNewLibraryDependencyAction.java index b35b469de54c..b15eaad20569 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddNewLibraryDependencyAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/AddNewLibraryDependencyAction.java @@ -66,12 +66,8 @@ class AddNewLibraryDependencyAction extends ChooseAndAddAction { final StructureConfigurableContext context, final JButton contextButton, @NotNull final LibraryCreatedCallback callback) { if (LibraryEditingUtil.hasSuitableTypes(classpathPanel)) { - final ListPopup popup = JBPopupFactory.getInstance().createListPopup(LibraryEditingUtil.createChooseTypeStep(classpathPanel, new ParameterizedRunnable() { - @Override - public void run(LibraryType libraryType) { - doCreateLibrary(classpathPanel, context, callback, contextButton, libraryType); - } - })); + final ListPopup popup = JBPopupFactory.getInstance().createListPopup(LibraryEditingUtil.createChooseTypeStep(classpathPanel, + libraryType -> doCreateLibrary(classpathPanel, context, callback, contextButton, libraryType))); popup.showUnderneathOf(contextButton); } else { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathPanelImpl.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathPanelImpl.java index 76f33318392c..a66d24ea06e4 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathPanelImpl.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathPanelImpl.java @@ -413,12 +413,7 @@ public class ClasspathPanelImpl extends JPanel implements ClasspathPanel { if (selectedValue.hasSubStep()) { return selectedValue.createSubStep(); } - return doFinalStep(new Runnable() { - @Override - public void run() { - selectedValue.execute(); - } - }); + return doFinalStep(() -> selectedValue.execute()); } @Override diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathTableModel.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathTableModel.java index 5eb886c70cc8..07177a5f3410 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathTableModel.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/classpath/ClasspathTableModel.java @@ -62,19 +62,10 @@ class ClasspathTableModel extends ListTableModel> implemen } }; private static final String SCOPE_COLUMN_NAME = ProjectBundle.message("modules.order.export.scope.column"); - private static final Comparator DEPENDENCY_SCOPE_COMPARATOR = new Comparator() { - @Override - public int compare(DependencyScope o1, DependencyScope o2) { - return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); - } - }; + private static final Comparator DEPENDENCY_SCOPE_COMPARATOR = + (o1, o2) -> o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); private static final Comparator> CLASSPATH_ITEM_SCOPE_COMPARATOR = - new Comparator>() { - @Override - public int compare(ClasspathTableItem o1, ClasspathTableItem o2) { - return Comparing.compare(o1.getScope(), o2.getScope(), DEPENDENCY_SCOPE_COMPARATOR); - } - }; + (o1, o2) -> Comparing.compare(o1.getScope(), o2.getScope(), DEPENDENCY_SCOPE_COMPARATOR); private static final ColumnInfo, DependencyScope> SCOPE_COLUMN_INFO = new ColumnInfo, DependencyScope>(SCOPE_COLUMN_NAME) { @Nullable @Override @@ -169,13 +160,10 @@ class ClasspathTableModel extends ListTableModel> implemen public ClasspathTableItemClasspathColumnInfo(final StructureConfigurableContext context) { super(""); - myItemComparator = new Comparator>() { - @Override - public int compare(ClasspathTableItem o1, ClasspathTableItem o2) { - String text1 = ClasspathPanelImpl.getCellAppearance(o1, context, false).getText(); - String text2 = ClasspathPanelImpl.getCellAppearance(o2, context, false).getText(); - return text1.compareToIgnoreCase(text2); - } + myItemComparator = (o1, o2) -> { + String text1 = ClasspathPanelImpl.getCellAppearance(o1, context, false).getText(); + String text2 = ClasspathPanelImpl.getCellAppearance(o2, context, false).getText(); + return text1.compareToIgnoreCase(text2); }; } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/dependencyAnalysis/ModuleDependenciesAnalyzer.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/dependencyAnalysis/ModuleDependenciesAnalyzer.java index 26600290af93..c35676a399fc 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/dependencyAnalysis/ModuleDependenciesAnalyzer.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/dependencyAnalysis/ModuleDependenciesAnalyzer.java @@ -189,38 +189,35 @@ public class ModuleDependenciesAnalyzer { else { e.runtimeOnly(); } - e.forEach(new Processor() { - @Override - public boolean process(OrderEntry orderEntry) { - myStack.add(new OrderEntryPathElement(orderEntry)); - try { - if (orderEntry instanceof ModuleOrderEntry) { - ModuleOrderEntry o = (ModuleOrderEntry)orderEntry; - examine(o.getModule(), level + 1); - } - else if (orderEntry instanceof ModuleSourceOrderEntry) { - if (!myProduction || !myCompile) { - CompilerModuleExtension e = CompilerModuleExtension.getInstance(m); - final OrderPath p = new OrderPath(myStack); - for (String u : e.getOutputRootUrls(!myCompile ? !myProduction : level > 0 && !myProduction)) { - addUrlPath(p, u); - } - addEntryPath(orderEntry, p); - } - } - else { + e.forEach(orderEntry -> { + myStack.add(new OrderEntryPathElement(orderEntry)); + try { + if (orderEntry instanceof ModuleOrderEntry) { + ModuleOrderEntry o = (ModuleOrderEntry)orderEntry; + examine(o.getModule(), level + 1); + } + else if (orderEntry instanceof ModuleSourceOrderEntry) { + if (!myProduction || !myCompile) { + CompilerModuleExtension e1 = CompilerModuleExtension.getInstance(m); final OrderPath p = new OrderPath(myStack); - for (String u : orderEntry.getUrls(OrderRootType.CLASSES)) { + for (String u : e1.getOutputRootUrls(!myCompile ? !myProduction : level > 0 && !myProduction)) { addUrlPath(p, u); } addEntryPath(orderEntry, p); } } - finally { - myStack.remove(myStack.size() - 1); + else { + final OrderPath p = new OrderPath(myStack); + for (String u : orderEntry.getUrls(OrderRootType.CLASSES)) { + addUrlPath(p, u); + } + addEntryPath(orderEntry, p); } - return true; } + finally { + myStack.remove(myStack.size() - 1); + } + return true; }); } finally { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java index aa38e4be14f8..466d7c37e663 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java @@ -89,27 +89,24 @@ public class AddCustomLibraryDialog extends DialogWrapper { @Override protected void doOKAction() { final LibraryCompositionSettings settings = myPanel.apply(); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - if (settings != null && settings.downloadFiles(myPanel.getMainPanel())) { - if (myModifiableRootModel == null) { - final ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); - new WriteAction() { - @Override - protected void run(@NotNull final Result result) { - addLibraries(model, settings); - model.commit(); - } - }.execute(); - } - else { - addLibraries(myModifiableRootModel, settings); - } - + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + if (settings != null && settings.downloadFiles(myPanel.getMainPanel())) { + if (myModifiableRootModel == null) { + final ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); + new WriteAction() { + @Override + protected void run(@NotNull final Result result) { + addLibraries(model, settings); + model.commit(); + } + }.execute(); } - AddCustomLibraryDialog.super.doOKAction(); + else { + addLibraries(myModifiableRootModel, settings); + } + } + AddCustomLibraryDialog.super.doOKAction(); }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/LibraryEditingUtil.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/LibraryEditingUtil.java index 01bae640c333..6b8f7f6b8928 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/LibraryEditingUtil.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/LibraryEditingUtil.java @@ -187,12 +187,7 @@ public class LibraryEditingUtil { @Override public PopupStep onChosen(final LibraryType selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - action.run(selectedValue); - } - }); + return doFinalStep(() -> action.run(selectedValue)); } }; } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/impl/LibraryUsageCollector.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/impl/LibraryUsageCollector.java index 2b8f425032f6..cfb7ced5e727 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/impl/LibraryUsageCollector.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/impl/LibraryUsageCollector.java @@ -42,12 +42,9 @@ public class LibraryUsageCollector extends AbstractApplicationUsagesCollector { @Override public Set getProjectUsages(@NotNull Project project) { final Set usedKinds = new HashSet(); - final Processor processor = new Processor() { - @Override - public boolean process(Library library) { - usedKinds.addAll(LibraryPresentationManagerImpl.getLibraryKinds(library, null)); - return true; - } + final Processor processor = library -> { + usedKinds.addAll(LibraryPresentationManagerImpl.getLibraryKinds(library, null)); + return true; }; for (Module module : ModuleManager.getInstance(project).getModules()) { ModuleRootManager.getInstance(module).orderEntries().librariesOnly().forEachLibrary(processor); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java index bff81af457ad..263ab20698f4 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java @@ -179,25 +179,22 @@ public class LibraryRootsComponent implements Disposable, LibraryEditorComponent if (selectedElements.length == 0) { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (Object selectedElement : selectedElements) { - if (selectedElement instanceof ItemElement) { - final ItemElement itemElement = (ItemElement)selectedElement; - getLibraryEditor().removeRoot(itemElement.getUrl(), itemElement.getRootType()); - } - else if (selectedElement instanceof OrderRootTypeElement) { - final OrderRootType rootType = ((OrderRootTypeElement)selectedElement).getOrderRootType(); - final String[] urls = getLibraryEditor().getUrls(rootType); - for (String url : urls) { - getLibraryEditor().removeRoot(url, rootType); - } - } - else if (selectedElement instanceof ExcludedRootElement) { - getLibraryEditor().removeExcludedRoot(((ExcludedRootElement)selectedElement).getUrl()); + ApplicationManager.getApplication().runWriteAction(() -> { + for (Object selectedElement : selectedElements) { + if (selectedElement instanceof ItemElement) { + final ItemElement itemElement = (ItemElement)selectedElement; + getLibraryEditor().removeRoot(itemElement.getUrl(), itemElement.getRootType()); + } + else if (selectedElement instanceof OrderRootTypeElement) { + final OrderRootType rootType = ((OrderRootTypeElement)selectedElement).getOrderRootType(); + final String[] urls = getLibraryEditor().getUrls(rootType); + for (String url : urls) { + getLibraryEditor().removeRoot(url, rootType); } } + else if (selectedElement instanceof ExcludedRootElement) { + getLibraryEditor().removeExcludedRoot(((ExcludedRootElement)selectedElement).getUrl()); + } } }); libraryChanged(true); @@ -455,11 +452,8 @@ public class LibraryRootsComponent implements Disposable, LibraryEditorComponent private List attachFiles(List roots) { final List rootsToAttach = filterAlreadyAdded(roots); if (!rootsToAttach.isEmpty()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - getLibraryEditor().addRoots(rootsToAttach); - } + ApplicationManager.getApplication().runWriteAction(() -> { + getLibraryEditor().addRoots(rootsToAttach); }); updatePropertiesLabel(); onRootsChanged(); @@ -546,12 +540,9 @@ public class LibraryRootsComponent implements Disposable, LibraryEditorComponent } final VirtualFile[] files = FileChooser.chooseFiles(descriptor, myPanel, myProject, toSelect); if (files.length > 0) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (VirtualFile file : files) { - getLibraryEditor().addExcludedRoot(file.getUrl()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (VirtualFile file : files) { + getLibraryEditor().addExcludedRoot(file.getUrl()); } }); myLastChosen = files[0]; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java index 88abf70358c5..1e0dcc71359b 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java @@ -155,13 +155,10 @@ public abstract class BaseLibrariesConfigurable extends BaseStructureConfigurabl for (Library library : libraries) { myRoot.add(new MyNode(new LibraryConfigurable(modelProvider, library, myContext, TREE_UPDATER))); } - TreeUtil.sort(myRoot, new Comparator() { - @Override - public int compare(final Object o1, final Object o2) { - MyNode node1 = (MyNode)o1; - MyNode node2 = (MyNode)o2; - return node1.getDisplayName().compareToIgnoreCase(node2.getDisplayName()); - } + TreeUtil.sort(myRoot, (o1, o2) -> { + MyNode node1 = (MyNode)o1; + MyNode node2 = (MyNode)o2; + return node1.getDisplayName().compareToIgnoreCase(node2.getDisplayName()); }); ((DefaultTreeModel)myTree.getModel()).reload(myRoot); } @@ -169,12 +166,9 @@ public abstract class BaseLibrariesConfigurable extends BaseStructureConfigurabl @Override public void apply() throws ConfigurationException { super.apply(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (final LibrariesModifiableModel provider : myContext.myLevel2Providers.values()) { - provider.deferredCommit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (final LibrariesModifiableModel provider : myContext.myLevel2Providers.values()) { + provider.deferredCommit(); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java index 723515e31591..09492ff2b5ac 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java @@ -110,22 +110,14 @@ public abstract class BaseStructureConfigurable extends MasterDetailsComponent i config = nodeByName.getConfigurable(); } - final ActionCallback result = new ActionCallback().doWhenDone(new Runnable() { - @Override - public void run() { - myAutoScrollEnabled = true; - } - }); + final ActionCallback result = new ActionCallback().doWhenDone(() -> myAutoScrollEnabled = true); myAutoScrollEnabled = false; myAutoScrollHandler.cancelAllRequests(); final MyNode nodeToSelect = node != null ? node : nodeByName; - selectNodeInTree(nodeToSelect, requestFocus).doWhenDone(new Runnable() { - @Override - public void run() { - setSelectedNode(nodeToSelect); - Place.goFurther(config, place, requestFocus).notifyWhenDone(result); - } + selectNodeInTree(nodeToSelect, requestFocus).doWhenDone(() -> { + setSelectedNode(nodeToSelect); + Place.goFurther(config, place, requestFocus).notifyWhenDone(result); }); return result; @@ -377,12 +369,9 @@ public abstract class BaseStructureConfigurable extends MasterDetailsComponent i } private List removeFromModel(final TreePath[] paths) { - List nodes = ContainerUtil.mapNotNull(paths, new Function() { - @Override - public MyNode fun(TreePath path) { - Object node = path.getLastPathComponent(); - return node instanceof MyNode ? (MyNode)node : null; - } + List nodes = ContainerUtil.mapNotNull(paths, path -> { + Object node = path.getLastPathComponent(); + return node instanceof MyNode ? (MyNode)node : null; }); MultiMap grouped = groupNodes(nodes); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ChangeLibraryLevelAction.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ChangeLibraryLevelAction.java index 979b9db7ded1..af600301c20a 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ChangeLibraryLevelAction.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ChangeLibraryLevelAction.java @@ -59,22 +59,19 @@ public class ChangeLibraryLevelAction extends ChangeLibraryLevelActionBase { final LibraryEx oldLibrary = (LibraryEx)context.getLibrary(libraryElement.getLibrary().getName(), mySourceConfigurable.getLevel()); LOG.assertTrue(oldLibrary != null); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - final Library newLibrary = doCopy(oldLibrary); - if (newLibrary == null) return; + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + final Library newLibrary = doCopy(oldLibrary); + if (newLibrary == null) return; - final Collection usages = context.getDaemonAnalyzer().getUsages(libraryElement); - for (ProjectStructureElementUsage usage : usages) { - usage.replaceElement(new LibraryProjectStructureElement(context, newLibrary)); - } - - if (!myCopy) { - mySourceConfigurable.removeLibrary(libraryElement); - } - ProjectStructureConfigurable.getInstance(myProject).selectProjectOrGlobalLibrary(newLibrary, true); + final Collection usages = context.getDaemonAnalyzer().getUsages(libraryElement); + for (ProjectStructureElementUsage usage : usages) { + usage.replaceElement(new LibraryProjectStructureElement(context, newLibrary)); } + + if (!myCopy) { + mySourceConfigurable.removeLibrary(libraryElement); + } + ProjectStructureConfigurable.getInstance(myProject).selectProjectOrGlobalLibrary(newLibrary, true); }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java index b952f5a658c6..1c895d6f0869 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FacetStructureConfigurable.java @@ -147,16 +147,13 @@ public class FacetStructureConfigurable extends BaseStructureConfigurable { @Override protected Comparator getNodeComparator() { - return new Comparator() { - @Override - public int compare(MyNode node1, MyNode node2) { - final NamedConfigurable c1 = node1.getConfigurable(); - final NamedConfigurable c2 = node2.getConfigurable(); - if (c1 instanceof FrameworkDetectionConfigurable && !(c2 instanceof FrameworkDetectionConfigurable)) return 1; - if (!(c1 instanceof FrameworkDetectionConfigurable) && c2 instanceof FrameworkDetectionConfigurable) return -1; + return (node1, node2) -> { + final NamedConfigurable c1 = node1.getConfigurable(); + final NamedConfigurable c2 = node2.getConfigurable(); + if (c1 instanceof FrameworkDetectionConfigurable && !(c2 instanceof FrameworkDetectionConfigurable)) return 1; + if (!(c1 instanceof FrameworkDetectionConfigurable) && c2 instanceof FrameworkDetectionConfigurable) return -1; - return StringUtil.naturalCompare(node1.getDisplayName(), node2.getDisplayName()); - } + return StringUtil.naturalCompare(node1.getDisplayName(), node2.getDisplayName()); }; } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FindUsagesInProjectStructureActionBase.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FindUsagesInProjectStructureActionBase.java index 67b9f3509db1..29c1197e4212 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FindUsagesInProjectStructureActionBase.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/FindUsagesInProjectStructureActionBase.java @@ -75,12 +75,7 @@ public abstract class FindUsagesInProjectStructureActionBase extends AnAction im RelativePoint point = getPointToShowResults(); final ProjectStructureElementUsage[] usagesArray = usages.toArray(new ProjectStructureElementUsage[usages.size()]); - Arrays.sort(usagesArray, new Comparator() { - @Override - public int compare(ProjectStructureElementUsage o1, ProjectStructureElementUsage o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }); + Arrays.sort(usagesArray, (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName())); BaseListPopupStep step = new BaseListPopupStep(ProjectBundle.message("dependencies.used.in.popup.title"), usagesArray) { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/JdkListConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/JdkListConfigurable.java index e5da6977035a..ee2793f73fe6 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/JdkListConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/JdkListConfigurable.java @@ -197,12 +197,7 @@ public class JdkListConfigurable extends BaseStructureConfigurable { @Override public AnAction[] getChildren(@Nullable final AnActionEvent e) { DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.new.jdk.text"), true); - myJdksTreeModel.createAddActions(group, myTree, new Consumer() { - @Override - public void consume(final Sdk projectJdk) { - addJdkNode(projectJdk, true); - } - }); + myJdksTreeModel.createAddActions(group, myTree, projectJdk -> addJdkNode(projectJdk, true)); return group.getChildren(null); } }; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibrariesContainerFactory.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibrariesContainerFactory.java index 9519484703ef..32e38c1b745e 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibrariesContainerFactory.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibrariesContainerFactory.java @@ -186,12 +186,7 @@ public class LibrariesContainerFactory { @Override public String suggestUniqueLibraryName(@NotNull String baseName) { if (myNameGenerator == null) { - myNameGenerator = new UniqueNameGenerator(Arrays.asList(getAllLibraries()), new Function() { - @Override - public String fun(Library o) { - return o.getName(); - } - }); + myNameGenerator = new UniqueNameGenerator(Arrays.asList(getAllLibraries()), o -> o.getName()); } return myNameGenerator.generateUniqueName(baseName, "", "", " (", ")"); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibraryConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibraryConfigurable.java index 0408dedac415..28e9376584a6 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibraryConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/LibraryConfigurable.java @@ -67,12 +67,9 @@ public class LibraryConfigurable extends ProjectStructureElementConfigurable { + myContext.getDaemonAnalyzer().queueUpdate(myProjectStructureElement); + updateName(); }); return myLibraryEditorComponent.getComponent(); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java index 2456fa472ef3..a8b7c0f81022 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ModuleStructureConfigurable.java @@ -82,28 +82,25 @@ import java.util.List; * Date: 02-Jun-2006 */ public class ModuleStructureConfigurable extends BaseStructureConfigurable implements Place.Navigator { - private static final Comparator NODE_COMPARATOR = new Comparator() { - @Override - public int compare(final MyNode o1, final MyNode o2) { - final NamedConfigurable configurable1 = o1.getConfigurable(); - final NamedConfigurable configurable2 = o2.getConfigurable(); - if (configurable1.getClass() == configurable2.getClass()) { - return StringUtil.naturalCompare(o1.getDisplayName(), o2.getDisplayName()); - } - final Object editableObject1 = configurable1.getEditableObject(); - final Object editableObject2 = configurable2.getEditableObject(); - - if (editableObject2 instanceof Module && editableObject1 instanceof ModuleGroup) return -1; - if (editableObject1 instanceof Module && editableObject2 instanceof ModuleGroup) return 1; - - if (editableObject2 instanceof Module && editableObject1 instanceof String) return 1; - if (editableObject1 instanceof Module && editableObject2 instanceof String) return -1; - - if (editableObject2 instanceof ModuleGroup && editableObject1 instanceof String) return 1; - if (editableObject1 instanceof ModuleGroup && editableObject2 instanceof String) return -1; - - return 0; + private static final Comparator NODE_COMPARATOR = (o1, o2) -> { + final NamedConfigurable configurable1 = o1.getConfigurable(); + final NamedConfigurable configurable2 = o2.getConfigurable(); + if (configurable1.getClass() == configurable2.getClass()) { + return StringUtil.naturalCompare(o1.getDisplayName(), o2.getDisplayName()); } + final Object editableObject1 = configurable1.getEditableObject(); + final Object editableObject2 = configurable2.getEditableObject(); + + if (editableObject2 instanceof Module && editableObject1 instanceof ModuleGroup) return -1; + if (editableObject1 instanceof Module && editableObject2 instanceof ModuleGroup) return 1; + + if (editableObject2 instanceof Module && editableObject1 instanceof String) return 1; + if (editableObject1 instanceof Module && editableObject2 instanceof String) return -1; + + if (editableObject2 instanceof ModuleGroup && editableObject1 instanceof String) return 1; + if (editableObject1 instanceof ModuleGroup && editableObject2 instanceof String) return -1; + + return 0; }; private boolean myPlainMode; @@ -239,18 +236,10 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple else { final MyNode moduleGroupNode = ModuleGroupUtil .buildModuleGroupPath(new ModuleGroup(groupPath), myRoot, moduleGroup2NodeMap, - new Consumer>() { - @Override - public void consume(final ModuleGroupUtil.ParentChildRelation parentChildRelation) { - parentChildRelation.getParent().add(parentChildRelation.getChild()); - } - }, - new Function() { - @Override - public MyNode fun(final ModuleGroup moduleGroup) { - final NamedConfigurable moduleGroupConfigurable = createModuleGroupConfigurable(moduleGroup); - return new MyNode(moduleGroupConfigurable, true); - } + parentChildRelation -> parentChildRelation.getParent().add(parentChildRelation.getChild()), + moduleGroup -> { + final NamedConfigurable moduleGroupConfigurable = createModuleGroupConfigurable(moduleGroup); + return new MyNode(moduleGroupConfigurable, true); }); moduleGroupNode.add(moduleNode); } @@ -300,23 +289,9 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple myRoot.add(moduleNode); } else { final MyNode moduleGroupNode = ModuleGroupUtil - .updateModuleGroupPath(new ModuleGroup(groupPath), myRoot, new Function() { - @Override - @Nullable - public MyNode fun(final ModuleGroup group) { - return findNodeByObject(myRoot, group); - } - }, new Consumer>() { - @Override - public void consume(final ModuleGroupUtil.ParentChildRelation parentChildRelation) { - parentChildRelation.getParent().add(parentChildRelation.getChild()); - } - }, new Function() { - @Override - public MyNode fun(final ModuleGroup moduleGroup) { - final NamedConfigurable moduleGroupConfigurable = createModuleGroupConfigurable(moduleGroup); - return new MyNode(moduleGroupConfigurable, true); - } + .updateModuleGroupPath(new ModuleGroup(groupPath), myRoot, group1 -> findNodeByObject(myRoot, group1), parentChildRelation -> parentChildRelation.getParent().add(parentChildRelation.getChild()), moduleGroup -> { + final NamedConfigurable moduleGroupConfigurable = createModuleGroupConfigurable(moduleGroup); + return new MyNode(moduleGroupConfigurable, true); }); moduleGroupNode.add(moduleNode); } @@ -331,11 +306,8 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple @Override protected Comparator getNodeComparator() { List> comparators = ContainerUtil - .mapNotNull(ModuleStructureExtension.EP_NAME.getExtensions(), new Function>() { - @Override - public Comparator fun(final ModuleStructureExtension moduleStructureExtension) { - return moduleStructureExtension.getNodeComparator(); - } + .mapNotNull(ModuleStructureExtension.EP_NAME.getExtensions(), moduleStructureExtension -> { + return moduleStructureExtension.getNodeComparator(); }); return new MergingComparator(ContainerUtil.concat(comparators, Collections.singletonList(NODE_COMPARATOR))); } @@ -473,15 +445,12 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple if (node != null) { p.putPath(TREE_OBJECT, module); p.putPath(ModuleEditor.SELECTED_EDITOR_NAME, ClasspathEditor.NAME); - r = new Runnable() { - @Override - public void run() { - if (orderEntry != null) { - ModuleEditor moduleEditor = ((ModuleConfigurable)node.getConfigurable()).getModuleEditor(); - ModuleConfigurationEditor editor = moduleEditor.getEditor(ClasspathEditor.NAME); - if (editor instanceof ClasspathEditor) { - ((ClasspathEditor)editor).selectOrderEntry(orderEntry); - } + r = () -> { + if (orderEntry != null) { + ModuleEditor moduleEditor = ((ModuleConfigurable)node.getConfigurable()).getModuleEditor(); + ModuleConfigurationEditor editor = moduleEditor.getEditor(ClasspathEditor.NAME); + if (editor instanceof ClasspathEditor) { + ((ClasspathEditor)editor).selectOrderEntry(orderEntry); } } }; @@ -882,32 +851,29 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple dialogBuilder.setTitle(ProjectBundle.message("copy.module.dialog.title")); dialogBuilder.setCenterPanel(component); dialogBuilder.setPreferredFocusComponent(component.getNameComponent()); - dialogBuilder.setOkOperation(new Runnable() { - @Override - public void run() { - final String name = component.getNameValue(); - if (name.length() == 0) { - Messages.showErrorDialog(ProjectBundle.message("enter.module.copy.name.error.message"), CommonBundle.message("title.error")); - return; - } - if (getModule(name) != null) { - Messages.showErrorDialog(ProjectBundle.message("module.0.already.exists.error.message", name), CommonBundle.message("title.error")); - return; - } - - if (component.getPath().length() == 0) { - Messages.showErrorDialog(IdeBundle.message("prompt.enter.project.file.location", modulePresentation), - CommonBundle.message("title.error")); - return; - } - if (!ProjectWizardUtil - .createDirectoryIfNotExists(IdeBundle.message("directory.project.file.directory", modulePresentation), component.getPath(), - true)) { - Messages.showErrorDialog(ProjectBundle.message("path.0.is.invalid.error.message", component.getPath()), CommonBundle.message("title.error")); - return; - } - dialogBuilder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); + dialogBuilder.setOkOperation(() -> { + final String name = component.getNameValue(); + if (name.length() == 0) { + Messages.showErrorDialog(ProjectBundle.message("enter.module.copy.name.error.message"), CommonBundle.message("title.error")); + return; } + if (getModule(name) != null) { + Messages.showErrorDialog(ProjectBundle.message("module.0.already.exists.error.message", name), CommonBundle.message("title.error")); + return; + } + + if (component.getPath().length() == 0) { + Messages.showErrorDialog(IdeBundle.message("prompt.enter.project.file.location", modulePresentation), + CommonBundle.message("title.error")); + return; + } + if (!ProjectWizardUtil + .createDirectoryIfNotExists(IdeBundle.message("directory.project.file.directory", modulePresentation), component.getPath(), + true)) { + Messages.showErrorDialog(ProjectBundle.message("path.0.is.invalid.error.message", component.getPath()), CommonBundle.message("title.error")); + return; + } + dialogBuilder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); }); if (dialogBuilder.show() != DialogWrapper.OK_EXIT_CODE) return; @@ -953,13 +919,10 @@ public class ModuleStructureConfigurable extends BaseStructureConfigurable imple }; builder.setName(component.getNameValue()); builder.setModuleFilePath(path + "/" + builder.getName() + ModuleFileType.DOT_DEFAULT_EXTENSION); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - final Module module = myContext.myModulesConfigurator.addModule(builder); - if (module != null) { - addModuleNode(module); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + final Module module = myContext.myModulesConfigurator.addModule(builder); + if (module != null) { + addModuleNode(module); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java index 53a6fff3afa6..680563395455 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java @@ -197,13 +197,10 @@ public class LibraryProjectStructureElement extends ProjectStructureElement { } myContext.getDaemonAnalyzer().queueUpdate(LibraryProjectStructureElement.this); final ProjectStructureConfigurable structureConfigurable = ProjectStructureConfigurable.getInstance(myContext.getProject()); - navigate().doWhenDone(new Runnable() { - @Override - public void run() { - final NamedConfigurable configurable = structureConfigurable.getConfigurableFor(myLibrary).getSelectedConfigurable(); - if (configurable instanceof LibraryConfigurable) { - ((LibraryConfigurable)configurable).updateComponent(); - } + navigate().doWhenDone(() -> { + final NamedConfigurable configurable = structureConfigurable.getConfigurableFor(myLibrary).getSelectedConfigurable(); + if (configurable instanceof LibraryConfigurable) { + ((LibraryConfigurable)configurable).updateComponent(); } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectConfigurationProblem.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectConfigurationProblem.java index f69cda0f2c9c..d2a3308cb58e 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectConfigurationProblem.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectConfigurationProblem.java @@ -83,12 +83,7 @@ public class ProjectConfigurationProblem extends ConfigurationError { @Override public PopupStep onChosen(final ConfigurationErrorQuickFix selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - selectedValue.performFix(); - } - }); + return doFinalStep(() -> selectedValue.performFix()); } }).show(relativePoint); } diff --git a/java/idea-ui/src/com/intellij/projectImport/ImportChooserStep.java b/java/idea-ui/src/com/intellij/projectImport/ImportChooserStep.java index 07f5a8bbda8f..b479fd51d1d7 100644 --- a/java/idea-ui/src/com/intellij/projectImport/ImportChooserStep.java +++ b/java/idea-ui/src/com/intellij/projectImport/ImportChooserStep.java @@ -155,11 +155,7 @@ public class ImportChooserStep extends ProjectImportWizardStep { private static List sorted(ProjectImportProvider[] providers) { List result = new ArrayList(); Collections.addAll(result, providers); - Collections.sort(result, new Comparator() { - public int compare(ProjectImportProvider l, ProjectImportProvider r) { - return l.getName().compareToIgnoreCase(r.getName()); - } - }); + Collections.sort(result, (l, r) -> l.getName().compareToIgnoreCase(r.getName())); return result; } diff --git a/java/idea-ui/src/com/intellij/projectImport/ProjectOpenProcessorBase.java b/java/idea-ui/src/com/intellij/projectImport/ProjectOpenProcessorBase.java index d23dfbfd0305..1a8185d774f3 100644 --- a/java/idea-ui/src/com/intellij/projectImport/ProjectOpenProcessorBase.java +++ b/java/idea-ui/src/com/intellij/projectImport/ProjectOpenProcessorBase.java @@ -213,20 +213,17 @@ public abstract class ProjectOpenProcessorBase e projectToOpen.save(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Sdk jdk = wizardContext.getProjectJdk(); - if (jdk != null) { - NewProjectUtil.applyJdkToProject(projectToOpen, jdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Sdk jdk1 = wizardContext.getProjectJdk(); + if (jdk1 != null) { + NewProjectUtil.applyJdkToProject(projectToOpen, jdk1); + } - String projectDirPath = wizardContext.getProjectFileDirectory(); - String path = StringUtil.endsWithChar(projectDirPath, '/') ? projectDirPath + "classes" : projectDirPath + "/classes"; - CompilerProjectExtension extension = CompilerProjectExtension.getInstance(projectToOpen); - if (extension != null) { - extension.setCompilerOutputUrl(getUrl(path)); - } + String projectDirPath = wizardContext.getProjectFileDirectory(); + String path = StringUtil.endsWithChar(projectDirPath, '/') ? projectDirPath + "classes" : projectDirPath + "/classes"; + CompilerProjectExtension extension = CompilerProjectExtension.getInstance(projectToOpen); + if (extension != null) { + extension.setCompilerOutputUrl(getUrl(path)); } }); diff --git a/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileFactoryImpl.java b/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileFactoryImpl.java index 954765b86fe7..ac1a599304e9 100644 --- a/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileFactoryImpl.java +++ b/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileFactoryImpl.java @@ -110,13 +110,9 @@ public class ConfigFileFactoryImpl extends ConfigFileFactory { } catch (final IOException e) { LOG.info(e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(IdeBundle.message("message.text.error.creating.deployment.descriptor", e.getLocalizedMessage()), - IdeBundle.message("message.text.creating.deployment.descriptor")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(IdeBundle.message("message.text.error.creating.deployment.descriptor", e.getLocalizedMessage()), + IdeBundle.message("message.text.creating.deployment.descriptor"))); } return null; } diff --git a/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileInfoSetImpl.java b/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileInfoSetImpl.java index d86bbe51637a..ee77447420f7 100644 --- a/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileInfoSetImpl.java +++ b/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileInfoSetImpl.java @@ -130,11 +130,9 @@ public class ConfigFileInfoSetImpl implements ConfigFileInfoSet { @SuppressWarnings({"HardCodedStringLiteral"}) public void writeExternal(final Element element) throws WriteExternalException { - final TreeSet sortedConfigFiles = new TreeSet(new Comparator() { - public int compare(final ConfigFileInfo o1, final ConfigFileInfo o2) { - final int id = Comparing.compare(o1.getMetaData().getId(), o2.getMetaData().getId()); - return id != 0? id : Comparing.compare(o1.getUrl(), o2.getUrl()); - } + final TreeSet sortedConfigFiles = new TreeSet((o1, o2) -> { + final int id = Comparing.compare(o1.getMetaData().getId(), o2.getMetaData().getId()); + return id != 0? id : Comparing.compare(o1.getUrl(), o2.getUrl()); }); sortedConfigFiles.addAll(myConfigFiles.collectValues()); for (ConfigFileInfo configuration : sortedConfigFiles) { diff --git a/java/idea-ui/src/com/intellij/util/ui/classpath/ChooseLibrariesDialogBase.java b/java/idea-ui/src/com/intellij/util/ui/classpath/ChooseLibrariesDialogBase.java index ab0318f26ce7..f974f8ef5acc 100644 --- a/java/idea-ui/src/com/intellij/util/ui/classpath/ChooseLibrariesDialogBase.java +++ b/java/idea-ui/src/com/intellij/util/ui/classpath/ChooseLibrariesDialogBase.java @@ -136,12 +136,7 @@ public abstract class ChooseLibrariesDialogBase extends DialogWrapper { } protected void queueUpdateAndSelect(@NotNull final Library library) { - myBuilder.queueUpdate().doWhenDone(new Runnable() { - @Override - public void run() { - myBuilder.select(library); - } - }); + myBuilder.queueUpdate().doWhenDone(() -> myBuilder.select(library)); } private boolean processSelection(final Processor processor) { diff --git a/java/java-analysis-impl/src/com/intellij/analysis/JavaAnalysisScope.java b/java/java-analysis-impl/src/com/intellij/analysis/JavaAnalysisScope.java index 9faf4da5ccb5..1d0a85b4d2ed 100644 --- a/java/java-analysis-impl/src/com/intellij/analysis/JavaAnalysisScope.java +++ b/java/java-analysis-impl/src/com/intellij/analysis/JavaAnalysisScope.java @@ -119,11 +119,8 @@ public class JavaAnalysisScope extends AnalysisScope { if (myElement instanceof PsiPackage) { final PsiPackage pack = (PsiPackage)myElement; final Set dirs = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ContainerUtil.addAll(dirs, pack.getDirectories(GlobalSearchScope.projectScope(myElement.getProject()))); - } + ApplicationManager.getApplication().runReadAction(() -> { + ContainerUtil.addAll(dirs, pack.getDirectories(GlobalSearchScope.projectScope(myElement.getProject()))); }); for (PsiDirectory dir : dirs) { if (!accept(dir, processor)) return false; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/UnusedSymbolUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/UnusedSymbolUtil.java index a68f794c578e..27fe3660346f 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/UnusedSymbolUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/UnusedSymbolUtil.java @@ -167,20 +167,17 @@ public class UnusedSymbolUtil { final PsiFile ignoreFile = helper.isCurrentFileAlreadyChecked() ? containingFile : null; - boolean sure = processUsages(project, containingFile, member, progress, ignoreFile, new Processor() { - @Override - public boolean process(UsageInfo info) { - PsiFile psiFile = info.getFile(); - if (psiFile == ignoreFile || psiFile == null) { - return true; // ignore usages in containingFile because isLocallyUsed() method would have caught that - } - int offset = info.getNavigationOffset(); - if (offset == -1) return true; - PsiElement element = psiFile.findElementAt(offset); - boolean inComment = element instanceof PsiComment; - log("* "+member.getName()+": usage :"+element); - return inComment; // ignore comments + boolean sure = processUsages(project, containingFile, member, progress, ignoreFile, info -> { + PsiFile psiFile = info.getFile(); + if (psiFile == ignoreFile || psiFile == null) { + return true; // ignore usages in containingFile because isLocallyUsed() method would have caught that } + int offset = info.getNavigationOffset(); + if (offset == -1) return true; + PsiElement element = psiFile.findElementAt(offset); + boolean inComment = element instanceof PsiComment; + log("* "+member.getName()+": usage :"+element); + return inComment; // ignore comments }); log("* "+member.getName()+": result:"+sure); return sure; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java index df96f75f5f7f..9ed21b232289 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressWarningsFoldingBuilder.java @@ -62,11 +62,8 @@ public class SuppressWarningsFoldingBuilder extends FoldingBuilderEx { public String getPlaceholderText(@NotNull ASTNode node) { final PsiElement element = node.getPsi(); if (element instanceof PsiAnnotation) { - return "/" + StringUtil.join(((PsiAnnotation)element).getParameterList().getAttributes(), new Function() { - @Override - public String fun(PsiNameValuePair value) { - return getMemberValueText(value.getValue()); - } + return "/" + StringUtil.join(((PsiAnnotation)element).getParameterList().getAttributes(), value -> { + return getMemberValueText(value.getValue()); }, ", ") + "/"; } return element.getText(); @@ -75,11 +72,8 @@ public class SuppressWarningsFoldingBuilder extends FoldingBuilderEx { private static String getMemberValueText(PsiAnnotationMemberValue memberValue) { if (memberValue instanceof PsiArrayInitializerMemberValue) { final PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue)memberValue).getInitializers(); - return StringUtil.join(initializers, new Function() { - @Override - public String fun(PsiAnnotationMemberValue psiAnnotationMemberValue) { - return getMemberValueText(psiAnnotationMemberValue); - } + return StringUtil.join(initializers, psiAnnotationMemberValue -> { + return getMemberValueText(psiAnnotationMemberValue); }, ", "); } if (memberValue instanceof PsiLiteral) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java index 09f879b0d795..61cd53734ca8 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java @@ -70,13 +70,10 @@ public class AddTypeArgumentsConditionalFix implements IntentionAction { @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { final PsiTypeParameter[] typeParameters = myMethod.getTypeParameters(); - final String typeArguments = "<" + StringUtil.join(typeParameters, new Function() { - @Override - public String fun(PsiTypeParameter parameter) { - final PsiType substituteTypeParam = mySubstitutor.substitute(parameter); - LOG.assertTrue(substituteTypeParam != null); - return GenericsUtil.eliminateWildcards(substituteTypeParam).getCanonicalText(); - } + final String typeArguments = "<" + StringUtil.join(typeParameters, parameter -> { + final PsiType substituteTypeParam = mySubstitutor.substitute(parameter); + LOG.assertTrue(substituteTypeParam != null); + return GenericsUtil.eliminateWildcards(substituteTypeParam).getCanonicalText(); }, ", ") + ">"; final PsiExpression expression = myExpression.getMethodExpression().getQualifierExpression(); String withTypeArgsText; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeTypeArgumentsFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeTypeArgumentsFix.java index b4a8d5b99d17..77cac5e596e8 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeTypeArgumentsFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeTypeArgumentsFix.java @@ -60,12 +60,9 @@ public class ChangeTypeArgumentsFix implements IntentionAction, HighPriorityActi @NotNull public String getText() { final PsiSubstitutor substitutor = inferTypeArguments(); - return "Change type arguments to <" + StringUtil.join(myPsiClass.getTypeParameters(), new Function() { - @Override - public String fun(PsiTypeParameter typeParameter) { - final PsiType substituted = substitutor.substitute(typeParameter); - return substituted != null ? substituted.getPresentableText() : CommonClassNames.JAVA_LANG_OBJECT; - } + return "Change type arguments to <" + StringUtil.join(myPsiClass.getTypeParameters(), typeParameter -> { + final PsiType substituted = substitutor.substitute(typeParameter); + return substituted != null ? substituted.getPresentableText() : CommonClassNames.JAVA_LANG_OBJECT; }, ", ") + ">"; } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeleteRepeatedInterfaceFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeleteRepeatedInterfaceFix.java index 7551488f1edf..324e3ddb2573 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeleteRepeatedInterfaceFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeleteRepeatedInterfaceFix.java @@ -74,11 +74,8 @@ public class DeleteRepeatedInterfaceFix implements IntentionAction { public boolean value(PsiTypeElement element) { return element != myConjunct; } - }), new Function() { - @Override - public String fun(PsiTypeElement element) { - return element.getText(); - } + }), element -> { + return element.getText(); }, " & "); final PsiTypeCastExpression newCastExpr = (PsiTypeCastExpression)JavaPsiFacade.getElementFactory(project).createExpressionFromText("(" + typeText + ")a", castType); diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java index 8eed99632fda..4da3f485021e 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java @@ -78,11 +78,8 @@ public class FlipIntersectionSidesFix implements IntentionAction { myConjuncts.remove(myConjunct); myConjuncts.add(0, myConjunct); - final String intersectionTypeText = StringUtil.join(myConjuncts, new Function() { - @Override - public String fun(PsiTypeElement element) { - return element.getText(); - } + final String intersectionTypeText = StringUtil.join(myConjuncts, element -> { + return element.getText(); }, " & "); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiTypeCastExpression fixedCast = diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java index 914cc34cfc4d..cc608eed9d3a 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java @@ -83,11 +83,8 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement { if (!isAvailable()) return; final PsiExpression expression = getSubExpression(); if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - simplifyExpression(project, expression, mySubExpressionValue); - } + ApplicationManager.getApplication().runWriteAction(() -> { + simplifyExpression(project, expression, mySubExpressionValue); }); } @@ -296,11 +293,8 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement { if (expressions.isEmpty()) { resultExpression = negate ? trueExpression : falseExpression; } else { - String simplifiedText = StringUtil.join(expressions, new Function() { - @Override - public String fun(PsiExpression expression) { - return expression.getText(); - } + String simplifiedText = StringUtil.join(expressions, expression1 -> { + return expression1.getText(); }, " ^ "); if (negate) { if (expressions.size() > 1) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Solver.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Solver.java index e9479009fe51..4741fd085f60 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Solver.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Solver.java @@ -104,13 +104,7 @@ class ResultUtil { class HResultUtil { private static final HKey[] EMPTY_PRODUCT = new HKey[0]; - private static final ArrayFactory HCOMPONENT_ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public HComponent[] create(int count) { - return new HComponent[count]; - } - }; + private static final ArrayFactory HCOMPONENT_ARRAY_FACTORY = count -> new HComponent[count]; private final ELattice lattice; final Value top; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java index de94ee7bb9c2..372cf34db459 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java @@ -247,12 +247,9 @@ public class DataFlowRunner { } } // and still in queue - if (!queue.processAll(new Processor() { - @Override - public boolean process(DfaInstructionState state) { - Instruction instruction = state.getInstruction(); - return !inSameLoop(prevInstruction, instruction, loopNumber); - } + if (!queue.processAll(state -> { + Instruction instruction = state.getInstruction(); + return !inSameLoop(prevInstruction, instruction, loopNumber); })) return; // now remove obsolete memory states diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaInstructionState.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaInstructionState.java index 43247ab322a1..0e3ba50f3905 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaInstructionState.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaInstructionState.java @@ -115,11 +115,8 @@ class StateQueue { } - return ContainerUtil.map(memoryStates, new Function() { - @Override - public DfaInstructionState fun(DfaMemoryStateImpl state) { - return new DfaInstructionState(instruction, state); - } + return ContainerUtil.map(memoryStates, state1 -> { + return new DfaInstructionState(instruction, state1); }); } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java index fe0a493aebdc..355433204e4a 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java @@ -991,11 +991,8 @@ public class DfaMemoryStateImpl implements DfaMemoryState { @Override public void flushVariable(@NotNull final DfaVariableValue variable) { - List updatedStack = ContainerUtil.map(myStack, new Function() { - @Override - public DfaValue fun(DfaValue value) { - return handleFlush(variable, value); - } + List updatedStack = ContainerUtil.map(myStack, value -> { + return handleFlush(variable, value); }); myStack.clear(); for (DfaValue value : updatedStack) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java index d0233181daff..f4db3360f72b 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java @@ -289,36 +289,33 @@ public class DfaPsiUtil { final int placeOffset = codeBlock != null? place.getTextRange().getStartOffset() : 0; List list = ContainerUtil.mapNotNull( ReferencesSearch.search(psiVariable, new LocalSearchScope(new PsiElement[] {psiVariable.getContainingFile()}, null, true)).findAll(), - new NullableFunction() { - @Override - public PsiExpression fun(final PsiReference psiReference) { - if (modificationRef.get()) return null; - final PsiElement parent = psiReference.getElement().getParent(); - if (parent instanceof PsiAssignmentExpression) { - final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent; - final IElementType operation = assignmentExpression.getOperationTokenType(); - if (assignmentExpression.getLExpression() == psiReference) { - if (JavaTokenType.EQ.equals(operation)) { - final PsiExpression rValue = assignmentExpression.getRExpression(); - if (!literalsOnly || allOperandsAreLiterals(rValue)) { - // if there's a codeBlock omit the values assigned later - if (codeBlock != null && PsiTreeUtil.isAncestor(codeBlock, parent, true) - && placeOffset < parent.getTextRange().getStartOffset()) { - return null; - } - return rValue; - } - else { - modificationRef.set(Boolean.TRUE); + (NullableFunction)psiReference -> { + if (modificationRef.get()) return null; + final PsiElement parent = psiReference.getElement().getParent(); + if (parent instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent; + final IElementType operation = assignmentExpression.getOperationTokenType(); + if (assignmentExpression.getLExpression() == psiReference) { + if (JavaTokenType.EQ.equals(operation)) { + final PsiExpression rValue = assignmentExpression.getRExpression(); + if (!literalsOnly || allOperandsAreLiterals(rValue)) { + // if there's a codeBlock omit the values assigned later + if (codeBlock != null && PsiTreeUtil.isAncestor(codeBlock, parent, true) + && placeOffset < parent.getTextRange().getStartOffset()) { + return null; } + return rValue; } - else if (JavaTokenType.PLUSEQ.equals(operation)) { + else { modificationRef.set(Boolean.TRUE); } } + else if (JavaTokenType.PLUSEQ.equals(operation)) { + modificationRef.set(Boolean.TRUE); + } } - return null; } + return null; }); if (modificationRef.get()) return Collections.emptyList(); PsiExpression initializer = psiVariable.getInitializer(); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaUtil.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaUtil.java index fa6208115eb0..b3c1e28e9474 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaUtil.java @@ -54,11 +54,8 @@ public class DfaUtil { ValuableInstructionVisitor.PlaceResult placeResult = value.get(context); final Collection> concatenations = placeResult == null ? null : placeResult.myValues.get(variable); if (concatenations != null) { - return ContainerUtil.map(concatenations, new Function, PsiExpression>() { - @Override - public PsiExpression fun(FList expressions) { - return concatenateExpressions(expressions); - } + return ContainerUtil.map(concatenations, expressions -> { + return concatenateExpressions(expressions); }); } return Collections.emptyList(); @@ -260,11 +257,8 @@ public class DfaUtil { return concatenation.getHead(); } String text = StringUtil - .join(ContainerUtil.reverse(new ArrayList(concatenation)), new Function() { - @Override - public String fun(PsiExpression expression) { - return expression.getText(); - } + .join(ContainerUtil.reverse(new ArrayList(concatenation)), expression -> { + return expression.getText(); }, "+"); try { return JavaPsiFacade.getElementFactory(concatenation.getHead().getProject()).createExpressionFromText(text, concatenation.getHead()); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/LiveVariablesAnalyzer.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/LiveVariablesAnalyzer.java index 937caa84e24d..d21613507293 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/LiveVariablesAnalyzer.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/LiveVariablesAnalyzer.java @@ -156,41 +156,38 @@ public class LiveVariablesAnalyzer { private Map findLiveVars() { final Map result = ContainerUtil.newHashMap(); - boolean ok = runDfa(false, new PairFunction() { - @Override - public BitSet fun(Instruction instruction, BitSet liveVars) { - if (instruction instanceof FinishElementInstruction) { - BitSet set = result.get(instruction); - if (set != null) { - set.or(liveVars); - return set; - } else { - result.put((FinishElementInstruction)instruction, liveVars); - } - } - - DfaVariableValue written = getWrittenVariable(instruction); - if (written != null) { - liveVars = (BitSet)liveVars.clone(); - liveVars.clear(written.getID()); - for (DfaVariableValue var : myFactory.getVarFactory().getAllQualifiedBy(written)) { - liveVars.clear(var.getID()); - } + boolean ok = runDfa(false, (instruction, liveVars) -> { + if (instruction instanceof FinishElementInstruction) { + BitSet set = result.get(instruction); + if (set != null) { + set.or(liveVars); + return set; } else { - boolean cloned = false; - for (DfaVariableValue value : getReadVariables(instruction)) { - if (!liveVars.get(value.getID())) { - if (!cloned) { - liveVars = (BitSet)liveVars.clone(); - cloned = true; - } - liveVars.set(value.getID()); + result.put((FinishElementInstruction)instruction, liveVars); + } + } + + DfaVariableValue written = getWrittenVariable(instruction); + if (written != null) { + liveVars = (BitSet)liveVars.clone(); + liveVars.clear(written.getID()); + for (DfaVariableValue var : myFactory.getVarFactory().getAllQualifiedBy(written)) { + liveVars.clear(var.getID()); + } + } else { + boolean cloned = false; + for (DfaVariableValue value : getReadVariables(instruction)) { + if (!liveVars.get(value.getID())) { + if (!cloned) { + liveVars = (BitSet)liveVars.clone(); + cloned = true; } + liveVars.set(value.getID()); } } - - return liveVars; } + + return liveVars; }); return ok ? result : null; } @@ -201,29 +198,25 @@ public class LiveVariablesAnalyzer { final MultiMap toFlush = MultiMap.createSet(); - boolean ok = runDfa(true, new PairFunction() { - @Override - @NotNull - public BitSet fun(Instruction instruction, @NotNull BitSet prevLiveVars) { - if (instruction instanceof FinishElementInstruction) { - BitSet currentlyLive = liveVars.get(instruction); - if (currentlyLive == null) { - return new BitSet(); // an instruction unreachable from the end? - } - int index = 0; - while (true) { - int setBit = prevLiveVars.nextSetBit(index); - if (setBit < 0) break; - if (!currentlyLive.get(setBit)) { - toFlush.putValue((FinishElementInstruction)instruction, (DfaVariableValue)myFactory.getValue(setBit)); - } - index = setBit + 1; - } - return currentlyLive; + boolean ok = runDfa(true, (instruction, prevLiveVars) -> { + if (instruction instanceof FinishElementInstruction) { + BitSet currentlyLive = liveVars.get(instruction); + if (currentlyLive == null) { + return new BitSet(); // an instruction unreachable from the end? } - - return prevLiveVars; + int index = 0; + while (true) { + int setBit = prevLiveVars.nextSetBit(index); + if (setBit < 0) break; + if (!currentlyLive.get(setBit)) { + toFlush.putValue((FinishElementInstruction)instruction, (DfaVariableValue)myFactory.getValue(setBit)); + } + index = setBit + 1; + } + return currentlyLive; } + + return prevLiveVars; }); if (ok) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/MethodContract.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/MethodContract.java index 1167210f917e..8e092099302e 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/MethodContract.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/MethodContract.java @@ -47,11 +47,8 @@ public class MethodContract { @Override public String toString() { - return StringUtil.join(arguments, new Function() { - @Override - public String fun(ValueConstraint constraint) { - return constraint.toString(); - } + return StringUtil.join(arguments, constraint -> { + return constraint.toString(); }, ", ") + " -> " + returnValue; } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StateMerger.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StateMerger.java index e07ed22d6681..75670fb9f780 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StateMerger.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StateMerger.java @@ -65,16 +65,13 @@ class StateMerger { final Collection group = ContainerUtil.newArrayList(ContainerUtil.concat(group1, group2)); final Set unknowns = getAllUnknownVariables(group); - replacements.stripAndMerge(group, new Function() { - @Override - public DfaMemoryStateImpl fun(DfaMemoryStateImpl original) { - DfaMemoryStateImpl copy = withUnknownVariables(original, unknowns); - fact.removeFromState(copy); - if (fact.myType == FactType.equality) { - restoreOtherInequalities(fact, group, copy); - } - return copy; + replacements.stripAndMerge(group, original -> { + DfaMemoryStateImpl copy = withUnknownVariables(original, unknowns); + fact.removeFromState(copy); + if (fact.myType == FactType.equality) { + restoreOtherInequalities(fact, group, copy); } + return copy; }); } @@ -227,12 +224,7 @@ class StateMerger { final Set toFlush = getAllUnknownVariables(complementary); if (toFlush.isEmpty()) return false; - return replacements.stripAndMerge(complementary, new Function() { - @Override - public DfaMemoryStateImpl fun(DfaMemoryStateImpl original) { - return withUnknownVariables(original, toFlush); - } - }); + return replacements.stripAndMerge(complementary, original -> withUnknownVariables(original, toFlush)); } private boolean areEquivalentModuloVar(@NotNull DfaMemoryStateImpl state1, @NotNull DfaMemoryStateImpl state2, @NotNull DfaVariableValue var) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java index 47fb7a64bca7..e499780c27d5 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java @@ -100,12 +100,7 @@ public class UnusedDeclarationInspectionBase extends GlobalInspectionTool { LOG.error(e); } } - Collections.sort(deadCodeAddIns, new Comparator() { - @Override - public int compare(final EntryPoint o1, final EntryPoint o2) { - return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); - } - }); + Collections.sort(deadCodeAddIns, (o1, o2) -> o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName())); myExtensions.addAll(deadCodeAddIns); myEnabledInEditor = enabledInEditor; } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java index d7ef822d828f..235e8718ab26 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java @@ -63,17 +63,14 @@ public class DefUseInspectionBase extends BaseJavaBatchLocalInspectionTool { List unusedDefs = DefUseUtil.getUnusedDefs(body, usedVariables); if (unusedDefs != null && !unusedDefs.isEmpty()) { - Collections.sort(unusedDefs, new Comparator() { - @Override - public int compare(DefUseUtil.Info o1, DefUseUtil.Info o2) { - int offset1 = o1.getContext().getTextOffset(); - int offset2 = o2.getContext().getTextOffset(); + Collections.sort(unusedDefs, (o1, o2) -> { + int offset1 = o1.getContext().getTextOffset(); + int offset2 = o2.getContext().getTextOffset(); - if (offset1 == offset2) return 0; - if (offset1 < offset2) return -1; + if (offset1 == offset2) return 0; + if (offset1 < offset2) return -1; - return 1; - } + return 1; }); for (DefUseUtil.Info info : unusedDefs) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java index 1a5e464551eb..02ea97f1e558 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java @@ -96,12 +96,9 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen public void extensionRemoved(@NotNull EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) { if (ADDITIONAL_ANNOS != null) { ADDITIONAL_ANNOS = null; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (ApplicationManager.getApplication().isDisposed()) return; - InspectionProfileManager.getInstance().fireProfileChanged(null); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (ApplicationManager.getApplication().isDisposed()) return; + InspectionProfileManager.getInstance().fireProfileChanged(null); }); } DaemonCodeAnalyzer.getInstance(project).restart(); // annotations changed @@ -172,15 +169,12 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen cleanup(); validateEntryPoints(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (SmartRefElementPointer entryPoint : myPersistentEntryPoints.values()) { - if (entryPoint.resolve(manager)) { - RefEntity refElement = entryPoint.getRefElement(); - ((RefElementImpl)refElement).setEntry(true); - ((RefElementImpl)refElement).setPermanentEntry(entryPoint.isPersistent()); - } + ApplicationManager.getApplication().runReadAction(() -> { + for (SmartRefElementPointer entryPoint : myPersistentEntryPoints.values()) { + if (entryPoint.resolve(manager)) { + RefEntity refElement = entryPoint.getRefElement(); + ((RefElementImpl)refElement).setEntry(true); + ((RefElementImpl)refElement).setPermanentEntry(entryPoint.isPersistent()); } } }); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/ChangeSuperClassFix.java b/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/ChangeSuperClassFix.java index eaab7a329fdb..057adc218cbb 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/ChangeSuperClassFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/ChangeSuperClassFix.java @@ -84,47 +84,39 @@ public class ChangeSuperClassFix implements LocalQuickFix { if (!FileModificationService.getInstance().preparePsiElementForWrite(aClass)) return; if (!FileModificationService.getInstance().prepareFileForWrite(aClass.getContainingFile())) return; - CommandProcessor.getInstance().executeCommand(newSuperClass.getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); - if (aClass instanceof PsiAnonymousClass) { - ((PsiAnonymousClass)aClass).getBaseClassReference().replace(factory.createClassReferenceElement(newSuperClass)); - } - else if (oldSuperClass.isInterface()) { - final PsiReferenceList interfaceList = aClass.getImplementsList(); - if (interfaceList != null) { - for (final PsiJavaCodeReferenceElement interfaceRef : interfaceList.getReferenceElements()) { - final PsiElement aInterface = interfaceRef.resolve(); - if (aInterface != null && aInterface.isEquivalentTo(oldSuperClass)) { - interfaceRef.delete(); - } - } - } - - final PsiReferenceList extendsList = aClass.getExtendsList(); - if (extendsList != null) { - final PsiJavaCodeReferenceElement newClassReference = factory.createClassReferenceElement(newSuperClass); - if (extendsList.getReferenceElements().length == 0) { - extendsList.add(newClassReference); - } - } - } - else { - final PsiReferenceList extendsList = aClass.getExtendsList(); - if (extendsList != null && extendsList.getReferenceElements().length == 1) { - extendsList.getReferenceElements()[0].delete(); - PsiElement ref = extendsList.add(factory.createClassReferenceElement(newSuperClass)); - JavaCodeStyleManager.getInstance(aClass.getProject()).shortenClassReferences(ref); - } + CommandProcessor.getInstance().executeCommand(newSuperClass.getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); + if (aClass instanceof PsiAnonymousClass) { + ((PsiAnonymousClass)aClass).getBaseClassReference().replace(factory.createClassReferenceElement(newSuperClass)); + } + else if (oldSuperClass.isInterface()) { + final PsiReferenceList interfaceList = aClass.getImplementsList(); + if (interfaceList != null) { + for (final PsiJavaCodeReferenceElement interfaceRef : interfaceList.getReferenceElements()) { + final PsiElement aInterface = interfaceRef.resolve(); + if (aInterface != null && aInterface.isEquivalentTo(oldSuperClass)) { + interfaceRef.delete(); } } - }); + } + + final PsiReferenceList extendsList = aClass.getExtendsList(); + if (extendsList != null) { + final PsiJavaCodeReferenceElement newClassReference = factory.createClassReferenceElement(newSuperClass); + if (extendsList.getReferenceElements().length == 0) { + extendsList.add(newClassReference); + } + } } - }, "Changing inheritance", null); + else { + final PsiReferenceList extendsList = aClass.getExtendsList(); + if (extendsList != null && extendsList.getReferenceElements().length == 1) { + extendsList.getReferenceElements()[0].delete(); + PsiElement ref = extendsList.add(factory.createClassReferenceElement(newSuperClass)); + JavaCodeStyleManager.getInstance(aClass.getProject()).shortenClassReferences(ref); + } + } + }), "Changing inheritance", null); } public static class LowPriority extends ChangeSuperClassFix implements LowPriorityAction { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java index 44a28e2c7062..967700c15111 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java @@ -387,11 +387,8 @@ public class NullableStuffInspectionBase extends BaseJavaBatchLocalInspectionToo Annotated annotated = check(method, holder, method.getReturnType()); List superMethods = ContainerUtil.map( - method.findSuperMethodSignaturesIncludingStatic(true), new Function() { - @Override - public PsiMethod fun(MethodSignatureBackedByPsiMethod signature) { - return signature.getMethod(); - } + method.findSuperMethodSignaturesIncludingStatic(true), signature -> { + return signature.getMethod(); }); final NullableNotNullManager nullableManager = NullableNotNullManager.getInstance(holder.getProject()); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefClassImpl.java b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefClassImpl.java index f8377eab6831..6bdf0d5e810f 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefClassImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefClassImpl.java @@ -289,11 +289,8 @@ public class RefClassImpl extends RefJavaElementImpl implements RefClass { @Override public void accept(@NotNull final RefVisitor visitor) { if (visitor instanceof RefJavaVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ((RefJavaVisitor)visitor).visitClass(RefClassImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + ((RefJavaVisitor)visitor).visitClass(RefClassImpl.this); }); } else { super.accept(visitor); @@ -435,13 +432,10 @@ public class RefClassImpl extends RefJavaElementImpl implements RefClass { @Override public String getExternalName() { final String[] result = new String[1]; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() {//todo synthetic JSP - final PsiClass psiClass = getElement(); - LOG.assertTrue(psiClass != null); - result[0] = PsiFormatUtil.getExternalName(psiClass); - } + ApplicationManager.getApplication().runReadAction(() -> {//todo synthetic JSP + final PsiClass psiClass = getElement(); + LOG.assertTrue(psiClass != null); + result[0] = PsiFormatUtil.getExternalName(psiClass); }); return result[0]; } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefFieldImpl.java b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefFieldImpl.java index cc31cddd6b98..6b5e588a28b7 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefFieldImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefFieldImpl.java @@ -105,11 +105,8 @@ public class RefFieldImpl extends RefJavaElementImpl implements RefField { @Override public void accept(@NotNull final RefVisitor visitor) { if (visitor instanceof RefJavaVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ((RefJavaVisitor)visitor).visitField(RefFieldImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + ((RefJavaVisitor)visitor).visitField(RefFieldImpl.this); }); } else { super.accept(visitor); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefMethodImpl.java b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefMethodImpl.java index f2d887dc6b61..c28e9d50a0b0 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefMethodImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefMethodImpl.java @@ -338,11 +338,8 @@ public class RefMethodImpl extends RefJavaElementImpl implements RefMethod { @Override public void accept(@NotNull final RefVisitor visitor) { if (visitor instanceof RefJavaVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ((RefJavaVisitor)visitor).visitMethod(RefMethodImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + ((RefJavaVisitor)visitor).visitMethod(RefMethodImpl.this); }); } else { super.accept(visitor); @@ -432,20 +429,17 @@ public class RefMethodImpl extends RefJavaElementImpl implements RefMethod { public String getName() { if (isValid()) { final String[] result = new String[1]; - final Runnable runnable = new Runnable() { - @Override - public void run() { - PsiMethod psiMethod = (PsiMethod) getElement(); - if (psiMethod instanceof SyntheticElement) { - result[0] = psiMethod.getName(); - } - else { - result[0] = PsiFormatUtil.formatMethod(psiMethod, - PsiSubstitutor.EMPTY, - PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, - PsiFormatUtilBase.SHOW_TYPE - ); - } + final Runnable runnable = () -> { + PsiMethod psiMethod = (PsiMethod) getElement(); + if (psiMethod instanceof SyntheticElement) { + result[0] = psiMethod.getName(); + } + else { + result[0] = PsiFormatUtil.formatMethod(psiMethod, + PsiSubstitutor.EMPTY, + PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, + PsiFormatUtilBase.SHOW_TYPE + ); } }; @@ -460,13 +454,10 @@ public class RefMethodImpl extends RefJavaElementImpl implements RefMethod { @Override public String getExternalName() { final String[] result = new String[1]; - final Runnable runnable = new Runnable() { - @Override - public void run() { - final PsiMethod psiMethod = (PsiMethod)getElement(); - LOG.assertTrue(psiMethod != null); - result[0] = PsiFormatUtil.getExternalName(psiMethod, true, Integer.MAX_VALUE); - } + final Runnable runnable = () -> { + final PsiMethod psiMethod = (PsiMethod)getElement(); + LOG.assertTrue(psiMethod != null); + result[0] = PsiFormatUtil.getExternalName(psiMethod, true, Integer.MAX_VALUE); }; ApplicationManager.getApplication().runReadAction(runnable); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefPackageImpl.java b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefPackageImpl.java index b00f25abb82f..b010fc9ca17c 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefPackageImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefPackageImpl.java @@ -55,11 +55,8 @@ public class RefPackageImpl extends RefEntityImpl implements RefPackage { @Override public void accept(@NotNull final RefVisitor visitor) { if (visitor instanceof RefJavaVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ((RefJavaVisitor)visitor).visitPackage(RefPackageImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + ((RefJavaVisitor)visitor).visitPackage(RefPackageImpl.this); }); } else { super.accept(visitor); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefParameterImpl.java b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefParameterImpl.java index cef4ea166238..a5a1b9b7ca30 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefParameterImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/reference/RefParameterImpl.java @@ -86,11 +86,8 @@ public class RefParameterImpl extends RefJavaElementImpl implements RefParameter @Override public void accept(@NotNull final RefVisitor visitor) { if (visitor instanceof RefJavaVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ((RefJavaVisitor)visitor).visitParameter(RefParameterImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + ((RefJavaVisitor)visitor).visitParameter(RefParameterImpl.this); }); } else { super.accept(visitor); @@ -151,13 +148,10 @@ public class RefParameterImpl extends RefJavaElementImpl implements RefParameter @Override public String getExternalName() { final String[] result = new String[1]; - final Runnable runnable = new Runnable() { - @Override - public void run() { - PsiParameter parameter = getElement(); - LOG.assertTrue(parameter != null); - result[0] = PsiFormatUtil.getExternalName(parameter); - } + final Runnable runnable = () -> { + PsiParameter parameter = getElement(); + LOG.assertTrue(parameter != null); + result[0] = PsiFormatUtil.getExternalName(parameter); }; ApplicationManager.getApplication().runReadAction(runnable); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/unneededThrows/RedundantThrows.java b/java/java-analysis-impl/src/com/intellij/codeInspection/unneededThrows/RedundantThrows.java index ff1f366c42e5..bb713865f3fe 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/unneededThrows/RedundantThrows.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/unneededThrows/RedundantThrows.java @@ -301,14 +301,11 @@ public class RedundantThrows extends GlobalJavaBatchInspectionTool { } } else { final Query> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass()); - query.forEach(new Processor>(){ - @Override - public boolean process(final Pair pair) { - if (pair.first == psiMethod) { - removeException(null, exceptionType, refsToDelete, pair.second); - } - return true; + query.forEach(pair -> { + if (pair.first == psiMethod) { + removeException(null, exceptionType, refsToDelete, pair.second); } + return true; }); } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/unusedLibraries/UnusedLibrariesInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/unusedLibraries/UnusedLibrariesInspection.java index 5c609b1227d9..32b1e019c3b7 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/unusedLibraries/UnusedLibrariesInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/unusedLibraries/UnusedLibrariesInspection.java @@ -84,11 +84,8 @@ public class UnusedLibrariesInspection extends GlobalInspectionTool { final Set files = new HashSet(Arrays.asList(((LibraryOrderEntry)entry).getRootFiles(OrderRootType.CLASSES))); files.removeAll(usedRoots); if (!files.isEmpty()) { - final String unusedLibraryRoots = StringUtil.join(files, new Function() { - @Override - public String fun(final VirtualFile file) { - return file.getPresentableName(); - } + final String unusedLibraryRoots = StringUtil.join(files, file -> { + return file.getPresentableName(); }, ","); String message = InspectionsBundle.message("unused.library.roots.problem.descriptor", unusedLibraryRoots, entry.getPresentableName()); @@ -157,29 +154,26 @@ public class UnusedLibrariesInspection extends GlobalInspectionTool { public void applyFix(@NotNull final Project project, @NotNull final CommonProblemDescriptor descriptor) { final Module module = myRefModule.getModule(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); - for (OrderEntry entry : model.getOrderEntries()) { - if (entry instanceof LibraryOrderEntry && Comparing.strEqual(entry.getPresentableName(), myOrderEntry.getPresentableName())) { - if (myFiles == null) { - model.removeOrderEntry(entry); - } - else { - final Library library = ((LibraryOrderEntry)entry).getLibrary(); - if (library != null) { - final Library.ModifiableModel modifiableModel = library.getModifiableModel(); - for (VirtualFile file : myFiles) { - modifiableModel.removeRoot(file.getUrl(), OrderRootType.CLASSES); - } - modifiableModel.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); + for (OrderEntry entry : model.getOrderEntries()) { + if (entry instanceof LibraryOrderEntry && Comparing.strEqual(entry.getPresentableName(), myOrderEntry.getPresentableName())) { + if (myFiles == null) { + model.removeOrderEntry(entry); + } + else { + final Library library = ((LibraryOrderEntry)entry).getLibrary(); + if (library != null) { + final Library.ModifiableModel modifiableModel = library.getModifiableModel(); + for (VirtualFile file : myFiles) { + modifiableModel.removeRoot(file.getUrl(), OrderRootType.CLASSES); } + modifiableModel.commit(); } } } - model.commit(); } + model.commit(); }); } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java index 9f20f4c29476..bf71a48ece14 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java @@ -79,31 +79,25 @@ public class FieldCanBeLocalInspectionBase extends BaseJavaBatchLocalInspectionT for (final PsiField field : candidates) { if (usedFields.contains(field) && !hasImplicitReadOrWriteUsage(field, implicitUsageProviders)) { - if (!ReferencesSearch.search(field, new LocalSearchScope(aClass)).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element instanceof PsiReferenceExpression) { - final PsiElement qualifier = ((PsiReferenceExpression)element).getQualifier(); - return qualifier == null || qualifier instanceof PsiThisExpression && ((PsiThisExpression)qualifier).getQualifier() == null; - } - return true; + if (!ReferencesSearch.search(field, new LocalSearchScope(aClass)).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element instanceof PsiReferenceExpression) { + final PsiElement qualifier = ((PsiReferenceExpression)element).getQualifier(); + return qualifier == null || qualifier instanceof PsiThisExpression && ((PsiThisExpression)qualifier).getQualifier() == null; } + return true; })) { continue; } final String message = InspectionsBundle.message("inspection.field.can.be.local.problem.descriptor"); final ArrayList fixes = new ArrayList(); - SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(field, new Processor() { - @Override - public boolean process(String qualifiedName) { - final LocalQuickFix quickFix = SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix( - InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", qualifiedName), - QuickFixBundle.message("fix.add.special.annotation.family"), - EXCLUDE_ANNOS, qualifiedName, field); - fixes.add(quickFix); - return true; - } + SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(field, qualifiedName -> { + final LocalQuickFix quickFix = SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix( + InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", qualifiedName), + QuickFixBundle.message("fix.add.special.annotation.family"), + EXCLUDE_ANNOS, qualifiedName, field); + fixes.add(quickFix); + return true; }); final LocalQuickFix fix = createFix(); if (fix != null) { diff --git a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesHelper.java b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesHelper.java index 53a3a670c1c9..7451bda44cdb 100644 --- a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesHelper.java +++ b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesHelper.java @@ -64,48 +64,45 @@ public class JavaFindUsagesHelper { final Set result = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (element instanceof PsiPackage) { - ContainerUtil.addIfNotNull(result, ((PsiPackage)element).getQualifiedName()); - } - else if (element instanceof PsiClass) { - final String qname = ((PsiClass)element).getQualifiedName(); - if (qname != null) { - result.add(qname); - PsiClass topLevelClass = PsiUtil.getTopLevelClass(element); - if (topLevelClass != null) { - String topName = topLevelClass.getQualifiedName(); - assert topName != null; - if (qname.length() > topName.length()) { - result.add(topName + qname.substring(topName.length()).replace('.', '$')); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (element instanceof PsiPackage) { + ContainerUtil.addIfNotNull(result, ((PsiPackage)element).getQualifiedName()); + } + else if (element instanceof PsiClass) { + final String qname = ((PsiClass)element).getQualifiedName(); + if (qname != null) { + result.add(qname); + PsiClass topLevelClass = PsiUtil.getTopLevelClass(element); + if (topLevelClass != null) { + String topName = topLevelClass.getQualifiedName(); + assert topName != null; + if (qname.length() > topName.length()) { + result.add(topName + qname.substring(topName.length()).replace('.', '$')); } } } - else if (element instanceof PsiMethod) { - ContainerUtil.addIfNotNull(result, ((PsiMethod)element).getName()); - } - else if (element instanceof PsiVariable) { - ContainerUtil.addIfNotNull(result, ((PsiVariable)element).getName()); - } - else if (element instanceof PsiMetaOwner) { - final PsiMetaData metaData = ((PsiMetaOwner)element).getMetaData(); - if (metaData != null) { - ContainerUtil.addIfNotNull(result, metaData.getName()); - } - } - else if (element instanceof PsiNamedElement) { - ContainerUtil.addIfNotNull(result, ((PsiNamedElement)element).getName()); - } - else if (element instanceof XmlAttributeValue) { - ContainerUtil.addIfNotNull(result, ((XmlAttributeValue)element).getValue()); - } - else { - LOG.error("Unknown element type: " + element); + } + else if (element instanceof PsiMethod) { + ContainerUtil.addIfNotNull(result, ((PsiMethod)element).getName()); + } + else if (element instanceof PsiVariable) { + ContainerUtil.addIfNotNull(result, ((PsiVariable)element).getName()); + } + else if (element instanceof PsiMetaOwner) { + final PsiMetaData metaData = ((PsiMetaOwner)element).getMetaData(); + if (metaData != null) { + ContainerUtil.addIfNotNull(result, metaData.getName()); } } + else if (element instanceof PsiNamedElement) { + ContainerUtil.addIfNotNull(result, ((PsiNamedElement)element).getName()); + } + else if (element instanceof XmlAttributeValue) { + ContainerUtil.addIfNotNull(result, ((XmlAttributeValue)element).getValue()); + } + else { + LOG.error("Unknown element type: " + element); + } }); return result; @@ -121,16 +118,13 @@ public class JavaFindUsagesHelper { if (!addElementUsages(element, options, processor)) return false; } else{ - if (!addElementUsages(element, varOptions, new Processor() { - @Override - public boolean process(UsageInfo info) { - final PsiElement element = info.getElement(); - boolean isWrite = element instanceof PsiExpression && PsiUtil.isAccessedForWriting((PsiExpression)element); - if (isWrite == varOptions.isWriteAccess) { - if (!processor.process(info)) return false; - } - return true; + if (!addElementUsages(element, varOptions, info -> { + final PsiElement element1 = info.getElement(); + boolean isWrite = element1 instanceof PsiExpression && PsiUtil.isAccessedForWriting((PsiExpression)element1); + if (isWrite == varOptions.isWriteAccess) { + if (!processor.process(info)) return false; } + return true; })) return false; } } @@ -341,16 +335,13 @@ public class JavaFindUsagesHelper { private static void addClassesInDirectory(@NotNull final PsiDirectory dir, final boolean includeSubdirs, @NotNull final List array) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(dir); - ContainerUtil.addAll(array, classes); - if (includeSubdirs) { - PsiDirectory[] dirs = dir.getSubdirectories(); - for (PsiDirectory directory : dirs) { - addClassesInDirectory(directory, true, array); - } + ApplicationManager.getApplication().runReadAction(() -> { + PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(dir); + ContainerUtil.addAll(array, classes); + if (includeSubdirs) { + PsiDirectory[] dirs = dir.getSubdirectories(); + for (PsiDirectory directory : dirs) { + addClassesInDirectory(directory, true, array); } } }); diff --git a/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodUtil.java b/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodUtil.java index 82ed68a44228..b49edb35e365 100644 --- a/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodUtil.java +++ b/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodUtil.java @@ -46,11 +46,9 @@ public class ExtractMethodUtil { final Map ret = new HashMap(); encodeInClass(targetClass, overloadName, extractedFragment, ret); - ClassInheritorsSearch.search(targetClass, processConflictsScope, true).forEach(new Processor() { - public boolean process(PsiClass inheritor) { - encodeInClass(inheritor, overloadName, extractedFragment, ret); - return true; - } + ClassInheritorsSearch.search(targetClass, processConflictsScope, true).forEach(inheritor -> { + encodeInClass(inheritor, overloadName, extractedFragment, ret); + return true; }); return ret; diff --git a/java/java-impl/src/com/intellij/analysis/BaseClassesAnalysisAction.java b/java/java-impl/src/com/intellij/analysis/BaseClassesAnalysisAction.java index 42d3722fbaf3..fe1ad16e81a2 100644 --- a/java/java-impl/src/com/intellij/analysis/BaseClassesAnalysisAction.java +++ b/java/java-impl/src/com/intellij/analysis/BaseClassesAnalysisAction.java @@ -54,29 +54,26 @@ public abstract class BaseClassesAnalysisAction extends BaseAnalysisAction { final CompilerManager compilerManager = CompilerManager.getInstance(project); final boolean upToDate = compilerManager.isUpToDate(compilerManager.createProjectCompileScope(project)); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) { - return; - } - if (!upToDate) { - final int i = Messages.showYesNoCancelDialog(getProject(), AnalysisScopeBundle.message("recompile.confirmation.message"), - AnalysisScopeBundle.message("project.is.out.of.date"), Messages.getWarningIcon()); + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) { + return; + } + if (!upToDate) { + final int i = Messages.showYesNoCancelDialog(getProject(), AnalysisScopeBundle.message("recompile.confirmation.message"), + AnalysisScopeBundle.message("project.is.out.of.date"), Messages.getWarningIcon()); - if (i == Messages.CANCEL) return; + if (i == Messages.CANCEL) return; - if (i == Messages.YES) { - compileAndAnalyze(project, scope); - } - else { - doAnalyze(project, scope); - } + if (i == Messages.YES) { + compileAndAnalyze(project, scope); } else { doAnalyze(project, scope); } } + else { + doAnalyze(project, scope); + } }); } }); @@ -106,12 +103,7 @@ public abstract class BaseClassesAnalysisAction extends BaseAnalysisAction { @Override public void finished(final boolean aborted, final int errors, final int warnings, final CompileContext compileContext) { if (aborted || errors != 0) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - doAnalyze(project, scope); - } - }); + ApplicationManager.getApplication().invokeLater(() -> doAnalyze(project, scope)); }}); } } diff --git a/java/java-impl/src/com/intellij/application/options/editor/ExcludeTable.java b/java/java-impl/src/com/intellij/application/options/editor/ExcludeTable.java index 6673a8a75bf6..20f116df0e63 100644 --- a/java/java-impl/src/com/intellij/application/options/editor/ExcludeTable.java +++ b/java/java-impl/src/com/intellij/application/options/editor/ExcludeTable.java @@ -196,12 +196,7 @@ class ExcludeTable extends ListTableWithButtons { for (String s : JavaProjectCodeInsightSettings.getSettings(myProject).excludedNames) { rows.add(new Item(s, ExclusionScope.Project)); } - Collections.sort(rows, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o1.exclude.compareTo(o2.exclude); - } - }); + Collections.sort(rows, (o1, o2) -> o1.exclude.compareTo(o2.exclude)); setValues(rows); } diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java index d75884bf76a5..9c005893ccd9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java @@ -1099,17 +1099,14 @@ public class ExpectedTypesProvider { return function.fun(containingClass); } final PsiType[] type = {null}; - DeepestSuperMethodsSearch.search(method).forEach(new Processor() { - @Override - public boolean process(@NotNull PsiMethod psiMethod) { - final PsiClass rootClass = psiMethod.getContainingClass(); - assert rootClass != null; - if (className.equals(rootClass.getQualifiedName())) { - type[0] = function.fun(rootClass); - return false; - } - return true; + DeepestSuperMethodsSearch.search(method).forEach(psiMethod -> { + final PsiClass rootClass = psiMethod.getContainingClass(); + assert rootClass != null; + if (className.equals(rootClass.getQualifiedName())) { + type[0] = function.fun(rootClass); + return false; } + return true; }); return type[0]; } @@ -1122,43 +1119,32 @@ public class ExpectedTypesProvider { @NonNls final String name = method.getName(); if ("contains".equals(name) || "remove".equals(name)) { - final PsiType type = checkMethod(method, CommonClassNames.JAVA_UTIL_COLLECTION, new NullableFunction() { - @Override - public PsiType fun(@NotNull final PsiClass psiClass) { - return getTypeParameterValue(psiClass, containingClass, substitutor, 0); - } - }); + final PsiType type = checkMethod(method, CommonClassNames.JAVA_UTIL_COLLECTION, + psiClass -> getTypeParameterValue(psiClass, containingClass, substitutor, 0)); if (type != null) return type; } if ("containsKey".equals(name) || "remove".equals(name) || "get".equals(name) || "containsValue".equals(name)) { - final PsiType type = checkMethod(method, CommonClassNames.JAVA_UTIL_MAP, new NullableFunction() { - @Override - public PsiType fun(@NotNull final PsiClass psiClass) { - return getTypeParameterValue(psiClass, containingClass, substitutor, name.equals("containsValue") ? 1 : 0); - } - }); + final PsiType type = checkMethod(method, CommonClassNames.JAVA_UTIL_MAP, + psiClass -> getTypeParameterValue(psiClass, containingClass, substitutor, name.equals("containsValue") ? 1 : 0)); if (type != null) return type; } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(containingClass.getProject()); if ("equals".equals(name)) { - final PsiType type = checkMethod(method, CommonClassNames.JAVA_LANG_OBJECT, new NullableFunction() { - @Override - public PsiType fun(final PsiClass psiClass) { - final PsiElement parent = argument.getParent().getParent(); - if (parent instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression expression = (PsiMethodCallExpression)parent; - final PsiExpression qualifierExpression = expression.getMethodExpression().getQualifierExpression(); - if (qualifierExpression != null) { - return qualifierExpression.getType(); - } - final PsiClass aClass = PsiTreeUtil.getContextOfType(parent, PsiClass.class, true); - if (aClass != null) { - return factory.createType(aClass); - } + final PsiType type = checkMethod(method, CommonClassNames.JAVA_LANG_OBJECT, psiClass -> { + final PsiElement parent = argument.getParent().getParent(); + if (parent instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression expression = (PsiMethodCallExpression)parent; + final PsiExpression qualifierExpression = expression.getMethodExpression().getQualifierExpression(); + if (qualifierExpression != null) { + return qualifierExpression.getType(); + } + final PsiClass aClass = PsiTreeUtil.getContextOfType(parent, PsiClass.class, true); + if (aClass != null) { + return factory.createType(aClass); } - return null; } + return null; }); if (type != null) return type; } diff --git a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java index 29b7523df02d..990e12f4bede 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsLineMarkerProvider.java @@ -53,28 +53,25 @@ import java.util.Collection; import java.util.List; public class ExternalAnnotationsLineMarkerProvider extends LineMarkerProviderDescriptor { - private static final Function ourTooltipProvider = new Function() { - @Override - public String fun(PsiElement nameIdentifier) { - PsiModifierListOwner owner = (PsiModifierListOwner)nameIdentifier.getParent(); - - boolean hasInferred = false; - boolean hasExternal = false; - for (PsiAnnotation annotation : findSignatureNonCodeAnnotations(owner, true)) { - hasExternal |= AnnotationUtil.isExternalAnnotation(annotation); - hasInferred |= AnnotationUtil.isInferredAnnotation(annotation); - } - - String header; - if (hasInferred && hasExternal) { - header = "External and inferred"; - } else if (hasInferred) { - header = "Inferred"; - } else { - header = "External"; - } - return XmlStringUtil.wrapInHtml(header + " annotations available. Full signature:

\n" + JavaDocInfoGenerator.generateSignature(owner)); + private static final Function ourTooltipProvider = nameIdentifier -> { + PsiModifierListOwner owner = (PsiModifierListOwner)nameIdentifier.getParent(); + + boolean hasInferred = false; + boolean hasExternal = false; + for (PsiAnnotation annotation : findSignatureNonCodeAnnotations(owner, true)) { + hasExternal |= AnnotationUtil.isExternalAnnotation(annotation); + hasInferred |= AnnotationUtil.isInferredAnnotation(annotation); } + + String header; + if (hasInferred && hasExternal) { + header = "External and inferred"; + } else if (hasInferred) { + header = "Inferred"; + } else { + header = "External"; + } + return XmlStringUtil.wrapInHtml(header + " annotations available. Full signature:

\n" + JavaDocInfoGenerator.generateSignature(owner)); }; @Nullable diff --git a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java index a1b709b8b6c3..554d58eca949 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java @@ -159,16 +159,9 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM notifyAfterAnnotationChanging(listOwner, annotationFQName, false); return; } - application.invokeLater(new Runnable() { - @Override - public void run() { - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - setupRootAndAnnotateExternally(entry, project, listOwner, annotationFQName, fromFile, packageName, value); - } - }); - } + application.invokeLater(() -> { + DumbService.getInstance(project).withAlternativeResolveEnabled( + () -> setupRootAndAnnotateExternally(entry, project, listOwner, annotationFQName, fromFile, packageName, value)); }, project.getDisposed()); } break; @@ -347,18 +340,15 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM @Override public boolean deannotate(@NotNull final PsiModifierListOwner listOwner, @NotNull final String annotationFQN) { ApplicationManager.getApplication().assertIsDispatchThread(); - return processExistingExternalAnnotations(listOwner, annotationFQN, new Processor() { - @Override - public boolean process(XmlTag annotationTag) { - PsiElement parent = annotationTag.getParent(); - annotationTag.delete(); - if (parent instanceof XmlTag) { - if (((XmlTag)parent).getSubTags().length == 0) { - parent.delete(); - } + return processExistingExternalAnnotations(listOwner, annotationFQN, annotationTag -> { + PsiElement parent = annotationTag.getParent(); + annotationTag.delete(); + if (parent instanceof XmlTag) { + if (((XmlTag)parent).getSubTags().length == 0) { + parent.delete(); } - return true; } + return true; }); } @@ -367,13 +357,10 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM @NotNull final String annotationFQN, @Nullable final PsiNameValuePair[] value) { ApplicationManager.getApplication().assertIsDispatchThread(); - return processExistingExternalAnnotations(listOwner, annotationFQN, new Processor() { - @Override - public boolean process(XmlTag annotationTag) { - annotationTag.replace(XmlElementFactory.getInstance(myPsiManager.getProject()).createTagFromText( - createAnnotationTag(annotationFQN, value))); - return true; - } + return processExistingExternalAnnotations(listOwner, annotationFQN, annotationTag -> { + annotationTag.replace(XmlElementFactory.getInstance(myPsiManager.getProject()).createTagFromText( + createAnnotationTag(annotationFQN, value))); + return true; }); } @@ -423,19 +410,16 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM continue; } - CommandProcessor.getInstance().executeCommand(myPsiManager.getProject(), new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(myPsiManager.getProject()).commitAllDocuments(); - try { - for (XmlTag annotationTag : tagsToProcess) { - annotationTagProcessor.process(annotationTag); - } - commitChanges(file); - } - catch (IncorrectOperationException e) { - LOG.error(e); + CommandProcessor.getInstance().executeCommand(myPsiManager.getProject(), () -> { + PsiDocumentManager.getInstance(myPsiManager.getProject()).commitAllDocuments(); + try { + for (XmlTag annotationTag : tagsToProcess) { + annotationTagProcessor.process(annotationTag); } + commitChanges(file); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }, ExternalAnnotationsManagerImpl.class.getName(), null); } @@ -626,14 +610,11 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM } List sorted = new ArrayList(itemTags); - Collections.sort(sorted, new Comparator() { - @Override - public int compare(XmlTag item1, XmlTag item2) { - String externalName1 = item1.getAttributeValue("name"); - String externalName2 = item2.getAttributeValue("name"); - assert externalName1 != null && externalName2 != null; // null names were not added - return externalName1.compareTo(externalName2); - } + Collections.sort(sorted, (item1, item2) -> { + String externalName1 = item1.getAttributeValue("name"); + String externalName2 = item2.getAttributeValue("name"); + assert externalName1 != null && externalName2 != null; // null names were not added + return externalName1.compareTo(externalName2); }); if (!sorted.equals(itemTags)) { for (XmlTag item : sorted) { @@ -658,16 +639,9 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM @NonNls String text; if (values != null && values.length != 0) { text = " \n"; - text += StringUtil.join(values, new Function() { - @NonNls - @NotNull - @Override - public String fun(@NotNull PsiNameValuePair pair) { - return ""; - } - }, " \n"); + text += StringUtil.join(values, pair -> "", " \n"); text += " "; } else { diff --git a/java/java-impl/src/com/intellij/codeInsight/FunctionalInterfaceSuggester.java b/java/java-impl/src/com/intellij/codeInsight/FunctionalInterfaceSuggester.java index edde071f1ef4..0f88a526e569 100644 --- a/java/java-impl/src/com/intellij/codeInsight/FunctionalInterfaceSuggester.java +++ b/java/java-impl/src/com/intellij/codeInsight/FunctionalInterfaceSuggester.java @@ -67,13 +67,7 @@ public class FunctionalInterfaceSuggester { public static Collection suggestFunctionalInterfaces(final @NotNull PsiFunctionalExpression expression) { final PsiType qualifierType = expression instanceof PsiMethodReferenceExpression ? PsiMethodReferenceUtil.getQualifierType((PsiMethodReferenceExpression)expression) : null; - return suggestFunctionalInterfaces(expression, new NullableFunction() { - @Nullable - @Override - public PsiType fun(PsiClass aClass) { - return composeAcceptableType(aClass, expression, qualifierType); - } - }); + return suggestFunctionalInterfaces(expression, aClass -> composeAcceptableType(aClass, expression, qualifierType)); } public static Collection suggestFunctionalInterfaces(final @NotNull PsiMethod method) { @@ -81,89 +75,82 @@ public class FunctionalInterfaceSuggester { return Collections.emptyList(); } - return suggestFunctionalInterfaces(method, new NullableFunction() { - @Nullable - @Override - public PsiType fun(PsiClass aClass) { - final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(aClass); - if (interfaceMethod != null) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - final PsiParameter[] interfaceMethodParameters = interfaceMethod.getParameterList().getParameters(); - if (parameters.length != interfaceMethodParameters.length) { - return null; - } - - final PsiType[] left = new PsiType[parameters.length + 1]; - final PsiType[] right = new PsiType[parameters.length + 1]; - - for (int i = 0; i < parameters.length; i++) { - left[i] = interfaceMethodParameters[i].getType(); - right[i] = parameters[i].getType(); - } - - left[parameters.length] = method.getReturnType(); - right[parameters.length] = interfaceMethod.getReturnType(); - - final PsiTypeParameter[] typeParameters = aClass.getTypeParameters(); - final PsiSubstitutor substitutor = PsiResolveHelper.SERVICE.getInstance(aClass.getProject()) - .inferTypeArguments(typeParameters, left, right, PsiUtil.getLanguageLevel(method)); - if (PsiUtil.isRawSubstitutor(aClass, substitutor)) { - return null; - } - - for (int i = 0; i < interfaceMethodParameters.length; i++) { - if (!TypeConversionUtil.isAssignable(parameters[i].getType(), substitutor.substitute(interfaceMethodParameters[i].getType()))) { - return null; - } - } - - final PsiType returnType = method.getReturnType(); - PsiType interfaceMethodReturnType = interfaceMethod.getReturnType(); - if (returnType != null && !TypeConversionUtil.isAssignable(returnType, substitutor.substitute(interfaceMethodReturnType))) { - return null; - } - - if (PsiType.VOID.equals(returnType) && !PsiType.VOID.equals(interfaceMethodReturnType)) { - return null; - } - - final PsiClassType[] interfaceThrownTypes = interfaceMethod.getThrowsList().getReferencedTypes(); - final PsiClassType[] thrownTypes = method.getThrowsList().getReferencedTypes(); - for (PsiClassType thrownType : thrownTypes) { - if (!ExceptionUtil.isHandledBy(thrownType, interfaceThrownTypes, substitutor)) { - return null; - } - } - - for (PsiClassType thrownType : interfaceThrownTypes) { - final PsiCodeBlock codeBlock = PsiTreeUtil.getContextOfType(method, PsiCodeBlock.class); - if (codeBlock == null || !ExceptionUtil.isHandled(thrownType, codeBlock)) { - return null; - } - } - - final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(aClass.getProject()); - return elementFactory.createType(aClass, substitutor); + return suggestFunctionalInterfaces(method, aClass -> { + final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(aClass); + if (interfaceMethod != null) { + final PsiParameter[] parameters = method.getParameterList().getParameters(); + final PsiParameter[] interfaceMethodParameters = interfaceMethod.getParameterList().getParameters(); + if (parameters.length != interfaceMethodParameters.length) { + return null; } - return null; + + final PsiType[] left = new PsiType[parameters.length + 1]; + final PsiType[] right = new PsiType[parameters.length + 1]; + + for (int i = 0; i < parameters.length; i++) { + left[i] = interfaceMethodParameters[i].getType(); + right[i] = parameters[i].getType(); + } + + left[parameters.length] = method.getReturnType(); + right[parameters.length] = interfaceMethod.getReturnType(); + + final PsiTypeParameter[] typeParameters = aClass.getTypeParameters(); + final PsiSubstitutor substitutor = PsiResolveHelper.SERVICE.getInstance(aClass.getProject()) + .inferTypeArguments(typeParameters, left, right, PsiUtil.getLanguageLevel(method)); + if (PsiUtil.isRawSubstitutor(aClass, substitutor)) { + return null; + } + + for (int i = 0; i < interfaceMethodParameters.length; i++) { + if (!TypeConversionUtil.isAssignable(parameters[i].getType(), substitutor.substitute(interfaceMethodParameters[i].getType()))) { + return null; + } + } + + final PsiType returnType = method.getReturnType(); + PsiType interfaceMethodReturnType = interfaceMethod.getReturnType(); + if (returnType != null && !TypeConversionUtil.isAssignable(returnType, substitutor.substitute(interfaceMethodReturnType))) { + return null; + } + + if (PsiType.VOID.equals(returnType) && !PsiType.VOID.equals(interfaceMethodReturnType)) { + return null; + } + + final PsiClassType[] interfaceThrownTypes = interfaceMethod.getThrowsList().getReferencedTypes(); + final PsiClassType[] thrownTypes = method.getThrowsList().getReferencedTypes(); + for (PsiClassType thrownType : thrownTypes) { + if (!ExceptionUtil.isHandledBy(thrownType, interfaceThrownTypes, substitutor)) { + return null; + } + } + + for (PsiClassType thrownType : interfaceThrownTypes) { + final PsiCodeBlock codeBlock = PsiTreeUtil.getContextOfType(method, PsiCodeBlock.class); + if (codeBlock == null || !ExceptionUtil.isHandled(thrownType, codeBlock)) { + return null; + } + } + + final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(aClass.getProject()); + return elementFactory.createType(aClass, substitutor); } + return null; }); } private static Collection suggestFunctionalInterfaces(final @NotNull T element, final NullableFunction acceptanceChecker) { final Project project = element.getProject(); final Set types = new HashSet(); - final Processor consumer = new Processor() { - @Override - public boolean process(PsiMember member) { - if (member instanceof PsiClass && !Java15APIUsageInspectionBase.isForbiddenApiUsage(member, PsiUtil.getLanguageLevel(element))) { - if (!JavaResolveUtil.isAccessible(member, null, member.getModifierList(), element, null, null)) { - return true; - } - ContainerUtil.addIfNotNull(types, acceptanceChecker.fun((PsiClass)member)); + final Processor consumer = member -> { + if (member instanceof PsiClass && !Java15APIUsageInspectionBase.isForbiddenApiUsage(member, PsiUtil.getLanguageLevel(element))) { + if (!JavaResolveUtil.isAccessible(member, null, member.getModifierList(), element, null, null)) { + return true; } - return true; + ContainerUtil.addIfNotNull(types, acceptanceChecker.fun((PsiClass)member)); } + return true; }; final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final GlobalSearchScope allScope = GlobalSearchScope.allScope(project); @@ -180,12 +167,7 @@ public class FunctionalInterfaceSuggester { } final ArrayList typesToSuggest = new ArrayList(types); - Collections.sort(typesToSuggest, new Comparator() { - @Override - public int compare(PsiType o1, PsiType o2) { - return o1.getCanonicalText().compareTo(o2.getCanonicalText()); - } - }); + Collections.sort(typesToSuggest, (o1, o2) -> o1.getCanonicalText().compareTo(o2.getCanonicalText())); return typesToSuggest; } diff --git a/java/java-impl/src/com/intellij/codeInsight/MakeInferredAnnotationExplicit.java b/java/java-impl/src/com/intellij/codeInsight/MakeInferredAnnotationExplicit.java index 807d361fe053..74bf57d177c6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/MakeInferredAnnotationExplicit.java +++ b/java/java-impl/src/com/intellij/codeInsight/MakeInferredAnnotationExplicit.java @@ -58,13 +58,10 @@ public class MakeInferredAnnotationExplicit extends BaseIntentionAction { PsiUtil.getLanguageLevel(file).isAtLeast(LanguageLevel.JDK_1_5)) { final PsiAnnotation[] annotations = InferredAnnotationsManager.getInstance(project).findInferredAnnotations(owner); if (annotations.length > 0) { - final String annos = StringUtil.join(annotations, new Function() { - @Override - public String fun(PsiAnnotation annotation) { - final PsiJavaCodeReferenceElement nameRef = correctAnnotation(annotation).getNameReferenceElement(); - final String name = nameRef != null ? nameRef.getReferenceName() : annotation.getQualifiedName(); - return "@" + name + annotation.getParameterList().getText(); - } + final String annos = StringUtil.join(annotations, annotation -> { + final PsiJavaCodeReferenceElement nameRef = correctAnnotation(annotation).getNameReferenceElement(); + final String name = nameRef != null ? nameRef.getReferenceName() : annotation.getQualifiedName(); + return "@" + name + annotation.getParameterList().getText(); }, " "); setText("Insert '" + annos + "'"); return true; @@ -97,16 +94,9 @@ public class MakeInferredAnnotationExplicit extends BaseIntentionAction { return; } - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - JavaCodeStyleManager.getInstance(project).shortenClassReferences(modifierList.addAfter(toInsert, null)); - } - }); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + DumbService.getInstance(project).withAlternativeResolveEnabled( + () -> JavaCodeStyleManager.getInstance(project).shortenClassReferences(modifierList.addAfter(toInsert, null))); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java index 99247cfd287f..c34fcb602a52 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java @@ -191,12 +191,9 @@ public class AllClassesGetter { @NotNull GlobalSearchScope scope, @NotNull Processor processor) { final Set names = new THashSet(10000); - AllClassesSearchExecutor.processClassNames(project, scope, new Consumer() { - @Override - public void consume(String s) { - if (prefixMatcher.prefixMatches(s)) { - names.add(s); - } + AllClassesSearchExecutor.processClassNames(project, scope, s -> { + if (prefixMatcher.prefixMatches(s)) { + names.add(s); } }); LinkedHashSet sorted = CompletionUtil.sortMatching(prefixMatcher, names); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java b/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java index 4c81a4e2a87a..88d14aa13d77 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java @@ -259,48 +259,39 @@ public class ConstructorInsertHandler implements InsertHandler candidatesToImplement = OverrideImplementExploreUtil.getMethodsToOverrideImplement(aClass, true); - for (Iterator iterator = candidatesToImplement.iterator(); iterator.hasNext(); ) { - final CandidateInfo candidate = iterator.next(); - final PsiElement element = candidate.getElement(); - if (element instanceof PsiMethod && ((PsiMethod)element).hasModifierProperty(PsiModifier.DEFAULT)) { - iterator.remove(); - } - } - boolean invokeOverride = candidatesToImplement.isEmpty(); - if (invokeOverride) { - OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false); - } - else { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - List methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false); - List> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods); - List> resultMembers = - GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes); - resultMembers.get(0).positionCaret(editor, true); - } - catch (IncorrectOperationException ioe) { - LOG.error(ioe); - } - } - }); - } + return () -> { + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + final PsiAnonymousClass + aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false); + if (aClass == null) return; + CommandProcessor.getInstance().executeCommand(project, () -> { + final Collection candidatesToImplement = OverrideImplementExploreUtil.getMethodsToOverrideImplement(aClass, true); + for (Iterator iterator = candidatesToImplement.iterator(); iterator.hasNext(); ) { + final CandidateInfo candidate = iterator.next(); + final PsiElement element = candidate.getElement(); + if (element instanceof PsiMethod && ((PsiMethod)element).hasModifierProperty(PsiModifier.DEFAULT)) { + iterator.remove(); } - }, getCommandName(), getCommandName(), UndoConfirmationPolicy.DEFAULT, editor.getDocument()); - } + } + boolean invokeOverride = candidatesToImplement.isEmpty(); + if (invokeOverride) { + OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false); + } + else { + ApplicationManager.getApplication().runWriteAction(() -> { + try { + List methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false); + List> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods); + List> resultMembers = + GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes); + resultMembers.get(0).positionCaret(editor, true); + } + catch (IncorrectOperationException ioe) { + LOG.error(ioe); + } + }); + } + }, getCommandName(), getCommandName(), UndoConfirmationPolicy.DEFAULT, editor.getDocument()); }; } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/InstanceofTypeProvider.java b/java/java-impl/src/com/intellij/codeInsight/completion/InstanceofTypeProvider.java index 3287750e54c5..97a92a3c7d54 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/InstanceofTypeProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/InstanceofTypeProvider.java @@ -58,17 +58,14 @@ class InstanceofTypeProvider extends CompletionProvider { } JavaInheritorsGetter - .processInheritors(parameters, expectedClassTypes, result.getPrefixMatcher(), new Consumer() { - @Override - public void consume(PsiType type) { - final PsiClass psiClass = PsiUtil.resolveClassInType(type); - if (psiClass == null || psiClass instanceof PsiTypeParameter) return; + .processInheritors(parameters, expectedClassTypes, result.getPrefixMatcher(), type -> { + final PsiClass psiClass = PsiUtil.resolveClassInType(type); + if (psiClass == null || psiClass instanceof PsiTypeParameter) return; - //noinspection SuspiciousMethodCalls - if (expectedClassTypes.contains(type)) return; + //noinspection SuspiciousMethodCalls + if (expectedClassTypes.contains(type)) return; - result.addElement(createInstanceofLookupElement(psiClass, parameterizedTypes)); - } + result.addElement(createInstanceofLookupElement(psiClass, parameterizedTypes)); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java index fbac2bb0e9bc..491c3fe33d1c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java @@ -363,96 +363,93 @@ public class JavaCompletionContributor extends CompletionContributor { final boolean isAfterNew = JavaClassNameCompletionContributor.AFTER_NEW.accepts(position); final boolean pkgContext = JavaCompletionUtil.inSomePackage(position); final PsiType[] expectedTypes = ExpectedTypesGetter.getExpectedTypes(parameters.getPosition(), true); - LegacyCompletionContributor.processReferences(parameters, result, new PairConsumer() { - @Override - public void consume(final PsiReference reference, final CompletionResultSet result) { - if (reference instanceof PsiJavaReference) { - ElementFilter filter = getReferenceFilter(position); - if (filter != null) { - if (INSIDE_CONSTRUCTOR.accepts(position) && - (parameters.getInvocationCount() <= 1 || CheckInitialized.isInsideConstructorCall(position))) { - filter = new AndFilter(filter, new CheckInitialized(position)); + LegacyCompletionContributor.processReferences(parameters, result, (reference, result1) -> { + if (reference instanceof PsiJavaReference) { + ElementFilter filter = getReferenceFilter(position); + if (filter != null) { + if (INSIDE_CONSTRUCTOR.accepts(position) && + (parameters.getInvocationCount() <= 1 || CheckInitialized.isInsideConstructorCall(position))) { + filter = new AndFilter(filter, new CheckInitialized(position)); + } + final PsiFile originalFile = parameters.getOriginalFile(); + JavaCompletionProcessor.Options options = + JavaCompletionProcessor.Options.DEFAULT_OPTIONS + .withCheckAccess(first) + .withFilterStaticAfterInstance(first) + .withShowInstanceInStaticContext(!first); + for (LookupElement element : JavaCompletionUtil.processJavaReference(position, + (PsiJavaReference)reference, + new ElementExtractorFilter(filter), + options, + result1.getPrefixMatcher(), parameters)) { + if (session.alreadyProcessed(element)) { + continue; } - final PsiFile originalFile = parameters.getOriginalFile(); - JavaCompletionProcessor.Options options = - JavaCompletionProcessor.Options.DEFAULT_OPTIONS - .withCheckAccess(first) - .withFilterStaticAfterInstance(first) - .withShowInstanceInStaticContext(!first); - for (LookupElement element : JavaCompletionUtil.processJavaReference(position, - (PsiJavaReference)reference, - new ElementExtractorFilter(filter), - options, - result.getPrefixMatcher(), parameters)) { - if (session.alreadyProcessed(element)) { - continue; - } - if (isSwitchLabel) { - result.addElement(new IndentingDecorator(TailTypeDecorator.withTail(element, TailType.createSimpleTailType(':')))); + if (isSwitchLabel) { + result1.addElement(new IndentingDecorator(TailTypeDecorator.withTail(element, TailType.createSimpleTailType(':')))); + } + else { + final LookupItem item = element.as(LookupItem.CLASS_CONDITION_KEY); + if (originalFile instanceof PsiJavaCodeReferenceCodeFragment && + !((PsiJavaCodeReferenceCodeFragment)originalFile).isClassesAccepted() && item != null) { + item.setTailType(TailType.NONE); } - else { - final LookupItem item = element.as(LookupItem.CLASS_CONDITION_KEY); - if (originalFile instanceof PsiJavaCodeReferenceCodeFragment && - !((PsiJavaCodeReferenceCodeFragment)originalFile).isClassesAccepted() && item != null) { - item.setTailType(TailType.NONE); - } - if (item instanceof JavaMethodCallElement) { - JavaMethodCallElement call = (JavaMethodCallElement)item; - final PsiMethod method = call.getObject(); - if (method.getTypeParameters().length > 0) { - final PsiType returned = TypeConversionUtil.erasure(method.getReturnType()); - PsiType matchingExpectation = returned == null - ? null - : ContainerUtil.find(expectedTypes, type -> type.isAssignableFrom(returned)); - if (matchingExpectation != null) { - call.setInferenceSubstitutor(SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, matchingExpectation), position); - } + if (item instanceof JavaMethodCallElement) { + JavaMethodCallElement call = (JavaMethodCallElement)item; + final PsiMethod method = call.getObject(); + if (method.getTypeParameters().length > 0) { + final PsiType returned = TypeConversionUtil.erasure(method.getReturnType()); + PsiType matchingExpectation = returned == null + ? null + : ContainerUtil.find(expectedTypes, type -> type.isAssignableFrom(returned)); + if (matchingExpectation != null) { + call.setInferenceSubstitutor(SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, matchingExpectation), position); } } - - result.addElement(element); } + + result1.addElement(element); } } - return; - } - if (reference instanceof PsiLabelReference) { - LabelReferenceCompletion.processLabelReference(result, (PsiLabelReference)reference); - return; } + return; + } + if (reference instanceof PsiLabelReference) { + LabelReferenceCompletion.processLabelReference(result1, (PsiLabelReference)reference); + return; + } - final Object[] variants = reference.getVariants(); - //noinspection ConstantConditions - if (variants == null) { - LOG.error("Reference=" + reference); + final Object[] variants = reference.getVariants(); + //noinspection ConstantConditions + if (variants == null) { + LOG.error("Reference=" + reference); + } + for (Object completion : variants) { + if (completion == null) { + LOG.error("Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(variants)); } - for (Object completion : variants) { - if (completion == null) { - LOG.error("Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(variants)); + if (completion instanceof LookupElement && !session.alreadyProcessed((LookupElement)completion)) { + usedWords.add(((LookupElement)completion).getLookupString()); + result1.addElement((LookupElement)completion); + } + else if (completion instanceof PsiClass) { + Condition condition = psiClass -> !session.alreadyProcessed(psiClass) && + JavaCompletionUtil.isSourceLevelAccessible(position, psiClass, pkgContext); + for (JavaPsiClassReferenceElement item : JavaClassNameCompletionContributor.createClassLookupItems((PsiClass)completion, + isAfterNew, + JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, + condition)) { + usedWords.add(item.getLookupString()); + result1.addElement(item); } - if (completion instanceof LookupElement && !session.alreadyProcessed((LookupElement)completion)) { - usedWords.add(((LookupElement)completion).getLookupString()); - result.addElement((LookupElement)completion); - } - else if (completion instanceof PsiClass) { - Condition condition = psiClass -> !session.alreadyProcessed(psiClass) && - JavaCompletionUtil.isSourceLevelAccessible(position, psiClass, pkgContext); - for (JavaPsiClassReferenceElement item : JavaClassNameCompletionContributor.createClassLookupItems((PsiClass)completion, - isAfterNew, - JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, - condition)) { - usedWords.add(item.getLookupString()); - result.addElement(item); - } - } - else { - //noinspection deprecation - LookupElement element = LookupItemUtil.objectToLookupItem(completion); - usedWords.add(element.getLookupString()); - result.addElement(element); - } + } + else { + //noinspection deprecation + LookupElement element = LookupItemUtil.objectToLookupItem(completion); + usedWords.add(element.getLookupString()); + result1.addElement(element); } } }); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java index 43abfda82732..26a5e55a8b45 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java @@ -277,16 +277,13 @@ public class JavaCompletionSorting { public PreferDefaultTypeWeigher(ExpectedTypeInfo[] expectedTypes, CompletionParameters parameters) { super("defaultType"); - myExpectedTypes = expectedTypes == null ? null : ContainerUtil.map2Array(expectedTypes, ExpectedTypeInfo.class, new Function() { - @Override - public ExpectedTypeInfo fun(ExpectedTypeInfo info) { - PsiType type = removeClassWildcard(info.getType()); - PsiType defaultType = removeClassWildcard(info.getDefaultType()); - if (type == info.getType() && defaultType == info.getDefaultType()) { - return info; - } - return new ExpectedTypeInfoImpl(type, info.getKind(), defaultType, info.getTailType(), null, ExpectedTypeInfoImpl.NULL); + myExpectedTypes = expectedTypes == null ? null : ContainerUtil.map2Array(expectedTypes, ExpectedTypeInfo.class, info -> { + PsiType type = removeClassWildcard(info.getType()); + PsiType defaultType = removeClassWildcard(info.getDefaultType()); + if (type == info.getType() && defaultType == info.getDefaultType()) { + return info; } + return new ExpectedTypeInfoImpl(type, info.getKind(), defaultType, info.getTailType(), null, ExpectedTypeInfoImpl.NULL); }); myParameters = parameters; diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java index fe139162f1bc..6167af4a18a9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java @@ -112,11 +112,8 @@ public class JavaCompletionUtil { } public static void putAllMethods(LookupElement item, List methods) { - item.putUserData(ALL_METHODS_ATTRIBUTE, ContainerUtil.map(methods, new Function>() { - @Override - public SmartPsiElementPointer fun(PsiMethod method) { - return SmartPointerManager.getInstance(method.getProject()).createSmartPsiElementPointer(method); - } + item.putUserData(ALL_METHODS_ATTRIBUTE, ContainerUtil.map(methods, method -> { + return SmartPointerManager.getInstance(method.getProject()).createSmartPsiElementPointer(method); })); } @@ -124,11 +121,8 @@ public class JavaCompletionUtil { List> pointers = item.getUserData(ALL_METHODS_ATTRIBUTE); if (pointers == null) return null; - return ContainerUtil.mapNotNull(pointers, new Function, PsiMethod>() { - @Override - public PsiMethod fun(SmartPsiElementPointer pointer) { - return pointer.getElement(); - } + return ContainerUtil.mapNotNull(pointers, pointer -> { + return pointer.getElement(); }); } @@ -338,12 +332,9 @@ public class JavaCompletionUtil { PsiElement refQualifier = ((PsiJavaCodeReferenceElement)javaReference).getQualifier(); if (refQualifier == null) { final StaticMemberProcessor memberProcessor = new JavaStaticMemberProcessor(parameters); - memberProcessor.processMembersOfRegisteredClasses(matcher, new PairConsumer() { - @Override - public void consume(PsiMember member, PsiClass psiClass) { - if (!mentioned.contains(member) && processor.satisfies(member, ResolveState.initial())) { - set.add(memberProcessor.createLookupElement(member, psiClass, true)); - } + memberProcessor.processMembersOfRegisteredClasses(matcher, (member, psiClass) -> { + if (!mentioned.contains(member) && processor.satisfies(member, ResolveState.initial())) { + set.add(memberProcessor.createLookupElement(member, psiClass, true)); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaDocCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaDocCompletionContributor.java index ec1a3956c3b7..12a96c284555 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaDocCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaDocCompletionContributor.java @@ -353,15 +353,12 @@ public class JavaDocCompletionContributor extends CompletionContributor { if ("see".equals(tagName)) { PsiMember member = PsiTreeUtil.getParentOfType(comment, PsiMember.class); if (member instanceof PsiClass) { - InheritanceUtil.processSupers((PsiClass)member, false, new Processor() { - @Override - public boolean process(PsiClass psiClass) { - String name = psiClass.getQualifiedName(); - if (StringUtil.isNotEmpty(name) && !CommonClassNames.JAVA_LANG_OBJECT.equals(name)) { - result.add("see " + name); - } - return true; + InheritanceUtil.processSupers((PsiClass)member, false, psiClass -> { + String name = psiClass.getQualifiedName(); + if (StringUtil.isNotEmpty(name) && !CommonClassNames.JAVA_LANG_OBJECT.equals(name)) { + result.add("see " + name); } + return true; }); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java index dd571666f247..47a4418c25e2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java @@ -90,11 +90,8 @@ public class JavaSmartCompletionContributor extends CompletionContributor { if (psiElement().afterLeaf(psiElement().withText(".")).withSuperParent(2, psiElement(PsiNewExpression.class)).accepts(element)) { if (((PsiNewExpression)element.getParent().getParent()).getClassReference() == element.getParent()) { PsiType[] types = ExpectedTypesGetter.getExpectedTypes(element, false); - return new OrFilter(ContainerUtil.map2Array(types, ElementFilter.class, new Function() { - @Override - public ElementFilter fun(PsiType type) { - return new AssignableFromFilter(type); - } + return new OrFilter(ContainerUtil.map2Array(types, ElementFilter.class, (Function)type -> { + return new AssignableFromFilter(type); })); } } @@ -184,13 +181,10 @@ public class JavaSmartCompletionContributor extends CompletionContributor { } for (final ExpectedTypeInfo info : mergedInfos) { - BasicExpressionCompletionContributor.fillCompletionVariants(new JavaSmartCompletionParameters(params, info), new Consumer() { - @Override - public void consume(LookupElement lookupElement) { - final PsiType psiType = JavaCompletionUtil.getLookupElementType(lookupElement); - if (psiType != null && info.getType().isAssignableFrom(psiType)) { - result.addElement(decorate(lookupElement, _infos)); - } + BasicExpressionCompletionContributor.fillCompletionVariants(new JavaSmartCompletionParameters(params, info), lookupElement -> { + final PsiType psiType = JavaCompletionUtil.getLookupElementType(lookupElement); + if (psiType != null && info.getType().isAssignableFrom(psiType)) { + result.addElement(decorate(lookupElement, _infos)); } }, result.getPrefixMatcher()); @@ -224,12 +218,7 @@ public class JavaSmartCompletionContributor extends CompletionContributor { @NotNull static Consumer decorateWithoutTypeCheck(final CompletionResultSet result, final Collection infos) { - return new Consumer() { - @Override - public void consume(final LookupElement lookupElement) { - result.addElement(decorate(lookupElement, infos)); - } - }; + return lookupElement -> result.addElement(decorate(lookupElement, infos)); } private static void addExpectedTypeMembers(CompletionParameters params, diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/RefactoringCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/RefactoringCompletionContributor.java index 9264599a4e1b..8ffbfb8d2ab6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/RefactoringCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/RefactoringCompletionContributor.java @@ -36,20 +36,17 @@ public class RefactoringCompletionContributor extends CompletionContributor { return; } - resultSet.runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(CompletionResult result) { - LookupElement element = result.getLookupElement(); - Object object = element.getObject(); - if (object instanceof PsiClass) { - Module module = ModuleUtil.findModuleForPsiElement((PsiClass)object); - if (module != null) { - resultSet.consume(LookupElementDecorator.withRenderer(element, new AppendModuleName(module))); - return; - } + resultSet.runRemainingContributors(parameters, result -> { + LookupElement element = result.getLookupElement(); + Object object = element.getObject(); + if (object instanceof PsiClass) { + Module module = ModuleUtil.findModuleForPsiElement((PsiClass)object); + if (module != null) { + resultSet.consume(LookupElementDecorator.withRenderer(element, new AppendModuleName(module))); + return; } - resultSet.passResult(result); } + resultSet.passResult(result); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java b/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java index 4ac1fb63facc..af5d6d814dd0 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java @@ -76,11 +76,8 @@ class SameSignatureCallParametersProvider extends CompletionProvider() { - @Override - public String fun(PsiParameter psiParameter) { - return psiParameter.getName(); - } + final String lookupString = StringUtil.join(parameters, psiParameter -> { + return psiParameter.getName(); }, ", "); final int w = PlatformIcons.PARAMETER_ICON.getIconWidth(); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java b/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java index fdd56255e8c9..b3e794319eb3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/SlowerTypeConversions.java @@ -67,28 +67,18 @@ class SlowerTypeConversions implements Runnable { public void run() { final Set> processedChains = ContainerUtil.newHashSet(); for (final LookupElement item : myBase) { - addSecondCompletionVariants(myElement, myReference, item, myParameters, new Consumer() { - @Override - public void consume(LookupElement lookupElement) { - ContainerUtil.addIfNotNull(processedChains, chainInfo(lookupElement)); - myResult.consume(lookupElement); - } + addSecondCompletionVariants(myElement, myReference, item, myParameters, lookupElement -> { + ContainerUtil.addIfNotNull(processedChains, chainInfo(lookupElement)); + myResult.consume(lookupElement); }); } if (!psiElement().afterLeaf(".").accepts(myElement)) { - BasicExpressionCompletionContributor.processDataflowExpressionTypes(myElement, null, TRUE_MATCHER, new Consumer() { - @Override - public void consume(LookupElement baseItem) { - addSecondCompletionVariants(myElement, myReference, baseItem, myParameters, new Consumer() { - @Override - public void consume(LookupElement lookupElement) { - if (!processedChains.contains(chainInfo(lookupElement))) { - myResult.consume(lookupElement); - } - } - }); - } - }); + BasicExpressionCompletionContributor.processDataflowExpressionTypes(myElement, null, TRUE_MATCHER, + baseItem -> addSecondCompletionVariants(myElement, myReference, baseItem, myParameters, lookupElement -> { + if (!processedChains.contains(chainInfo(lookupElement))) { + myResult.consume(lookupElement); + } + })); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/TypeArgumentCompletionProvider.java b/java/java-impl/src/com/intellij/codeInsight/completion/TypeArgumentCompletionProvider.java index 53bc078de0c2..6db4a0c3b023 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/TypeArgumentCompletionProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/TypeArgumentCompletionProvider.java @@ -143,15 +143,12 @@ class TypeArgumentCompletionProvider extends CompletionProvider typeList = Collections.singletonList((PsiClassType)TypeConversionUtil.typeParameterErasure( referencedClass.getTypeParameters()[parameterIndex])); - JavaInheritorsGetter.processInheritors(parameters, typeList, resultSet.getPrefixMatcher(), new Consumer() { - @Override - public void consume(final PsiType type) { - final PsiClass psiClass = PsiUtil.resolveClassInType(type); - if (psiClass == null) return; + JavaInheritorsGetter.processInheritors(parameters, typeList, resultSet.getPrefixMatcher(), type -> { + final PsiClass psiClass = PsiUtil.resolveClassInType(type); + if (psiClass == null) return; - resultSet.addElement(TailTypeDecorator.withTail(new JavaPsiClassReferenceElement(psiClass), - getTail(parameterIndex == referencedClass.getTypeParameters().length - 1))); - } + resultSet.addElement(TailTypeDecorator.withTail(new JavaPsiClassReferenceElement(psiClass), + getTail(parameterIndex == referencedClass.getTypeParameters().length - 1))); }); } @@ -202,11 +199,8 @@ class TypeArgumentCompletionProvider extends CompletionProvider() { - @Override - public String fun(PsiTypeLookupItem item) { - return item.getType().getPresentableText(); - } + myLookupString = StringUtil.join(myTypeItems, item -> { + return item.getType().getPresentableText(); }, ", "); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/XmlBasicToClassNameDelegator.java b/java/java-impl/src/com/intellij/codeInsight/completion/XmlBasicToClassNameDelegator.java index 310cf1444e88..f4c64439af11 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/XmlBasicToClassNameDelegator.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/XmlBasicToClassNameDelegator.java @@ -46,17 +46,14 @@ public class XmlBasicToClassNameDelegator extends CompletionContributor { if (empty && JavaClassReferenceCompletionContributor.findJavaClassReference(file, parameters.getOffset()) != null || parameters.isExtendedCompletion()) { - CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, new Consumer() { - @Override - public void consume(final CompletionResult completionResult) { - LookupElement lookupElement = completionResult.getLookupElement(); - JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); - if (classElement != null) { - classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); - } - lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction - result.passResult(completionResult); + CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, completionResult -> { + LookupElement lookupElement = completionResult.getLookupElement(); + JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); + if (classElement != null) { + classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); } + lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction + result.passResult(completionResult); }); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaColorProvider.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaColorProvider.java index 5e5109971fb9..e45361bf55fb 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaColorProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaColorProvider.java @@ -147,12 +147,7 @@ public class JavaColorProvider implements ElementColorProvider { final Document document = PsiDocumentManager.getInstance(element.getProject()).getDocument(element.getContainingFile()); if (isIntLiteralInsideNewJBColorExpression(element)) { - command = new Runnable() { - @Override - public void run() { - replaceInt((PsiExpression)element, color.getRGB(), true, color.getAlpha() != 255); - } - }; + command = () -> replaceInt((PsiExpression)element, color.getRGB(), true, color.getAlpha() != 255); } else { PsiExpressionList argumentList = ((PsiNewExpression)element).getArgumentList(); assert argumentList != null; @@ -161,39 +156,36 @@ public class JavaColorProvider implements ElementColorProvider { ColorConstructors type = getConstructorType(argumentList.getExpressionTypes()); assert type != null; - command = new Runnable() { - @Override - public void run() { - switch (type) { - case INT: - case INT_BOOL: - replaceInt(expr[0], color.getRGB(), true); - return; - case INT_x3: - case INT_x4: - replaceInt(expr[0], color.getRed()); - replaceInt(expr[1], color.getGreen()); - replaceInt(expr[2], color.getBlue()); - if (type == ColorConstructors.INT_x4) { - replaceInt(expr[3], color.getAlpha()); - } - else if (color.getAlpha() != 255) { - //todo add alpha - } - return; - case FLOAT_x3: - case FLOAT_x4: - float[] rgba = color.getColorComponents(null); - replaceFloat(expr[0], rgba[0]); - replaceFloat(expr[1], rgba[1]); - replaceFloat(expr[2], rgba[2]); - if (type == ColorConstructors.FLOAT_x4) { - replaceFloat(expr[3], rgba.length == 4 ? rgba[3] : 0f); - } - else if (color.getAlpha() != 255) { - //todo add alpha - } - } + command = () -> { + switch (type) { + case INT: + case INT_BOOL: + replaceInt(expr[0], color.getRGB(), true); + return; + case INT_x3: + case INT_x4: + replaceInt(expr[0], color.getRed()); + replaceInt(expr[1], color.getGreen()); + replaceInt(expr[2], color.getBlue()); + if (type == ColorConstructors.INT_x4) { + replaceInt(expr[3], color.getAlpha()); + } + else if (color.getAlpha() != 255) { + //todo add alpha + } + return; + case FLOAT_x3: + case FLOAT_x4: + float[] rgba = color.getColorComponents(null); + replaceFloat(expr[0], rgba[0]); + replaceFloat(expr[1], rgba[1]); + replaceFloat(expr[2], rgba[2]); + if (type == ColorConstructors.FLOAT_x4) { + replaceFloat(expr[3], rgba.length == 4 ? rgba[3] : 0f); + } + else if (color.getAlpha() != 255) { + //todo add alpha + } } }; } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java index fce394b9462b..c8747fdc82fa 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java @@ -77,12 +77,7 @@ public class MarkerType { handler = new GutterIconNavigationHandler() { @Override public void navigate(final MouseEvent e, final PsiElement elt) { - DumbService.getInstance(elt.getProject()).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - navigator.browse(e, elt); - } - }); + DumbService.getInstance(elt.getProject()).withAlternativeResolveEnabled(() -> navigator.browse(e, elt)); } }; } @@ -102,15 +97,12 @@ public class MarkerType { return myTooltip; } - static final MarkerType OVERRIDING_METHOD = new MarkerType("OVERRIDING_METHOD", new NullableFunction() { - @Override - public String fun(PsiElement element) { - PsiElement parent = getParentMethod(element); - if (!(parent instanceof PsiMethod)) return null; - PsiMethod method = (PsiMethod)parent; + static final MarkerType OVERRIDING_METHOD = new MarkerType("OVERRIDING_METHOD", (NullableFunction)element -> { + PsiElement parent = getParentMethod(element); + if (!(parent instanceof PsiMethod)) return null; + PsiMethod method = (PsiMethod)parent; - return calculateOverridingMethodTooltip(method, method != element.getParent()); - } + return calculateOverridingMethodTooltip(method, method != element.getParent()); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { @@ -120,16 +112,14 @@ public class MarkerType { navigateToOverridingMethod(e, method, method != element.getParent()); } }); - static final MarkerType SIBLING_OVERRIDING_METHOD = new MarkerType("SIBLING_OVERRIDING_METHOD", new NullableFunction() { - @Override - public String fun(PsiElement element) { - PsiElement parent = getParentMethod(element); - if (!(parent instanceof PsiMethod)) return null; - PsiMethod method = (PsiMethod)parent; + static final MarkerType SIBLING_OVERRIDING_METHOD = new MarkerType("SIBLING_OVERRIDING_METHOD", + (NullableFunction)element -> { + PsiElement parent = getParentMethod(element); + if (!(parent instanceof PsiMethod)) return null; + PsiMethod method = (PsiMethod)parent; - return calculateOverridingSiblingMethodTooltip(method); - } - }, new LineMarkerNavigator() { + return calculateOverridingSiblingMethodTooltip(method); + }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = getParentMethod(element); @@ -206,12 +196,7 @@ public class MarkerType { private static PsiMethod[] composeSuperMethods(@NotNull PsiMethod method, boolean acceptSelf) { PsiElement[] superElements = FindSuperElementsHelper.findSuperElements(method); - PsiMethod[] superMethods = ContainerUtil.map(superElements, new Function() { - @Override - public PsiMethod fun(PsiElement element) { - return (PsiMethod)element; - } - }, PsiMethod.EMPTY_ARRAY); + PsiMethod[] superMethods = ContainerUtil.map(superElements, element -> (PsiMethod)element, PsiMethod.EMPTY_ARRAY); if (acceptSelf) { superMethods = ArrayUtil.prepend(method, superMethods); } @@ -225,15 +210,12 @@ public class MarkerType { } public static final String SEARCHING_FOR_OVERRIDING_METHODS = "Searching for Overriding Methods"; - static final MarkerType OVERRIDDEN_METHOD = new MarkerType("OVERRIDDEN_METHOD", new NullableFunction() { - @Override - public String fun(PsiElement element) { - PsiElement parent = element.getParent(); - if (!(parent instanceof PsiMethod)) return null; - PsiMethod method = (PsiMethod)parent; + static final MarkerType OVERRIDDEN_METHOD = new MarkerType("OVERRIDDEN_METHOD", (NullableFunction)element -> { + PsiElement parent = element.getParent(); + if (!(parent instanceof PsiMethod)) return null; + PsiMethod method = (PsiMethod)parent; - return getOverriddenMethodTooltip(method); - } + return getOverriddenMethodTooltip(method); }, new LineMarkerNavigator(){ @Override public void browse(MouseEvent e, PsiElement element) { @@ -283,20 +265,17 @@ public class MarkerType { final PsiElementProcessor.CollectElementsWithLimit collectExprProcessor = new PsiElementProcessor.CollectElementsWithLimit(2, new THashSet()); final boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - OverridingMethodsSearch.search(method).forEach(new PsiElementProcessorAdapter(collectProcessor)); - if (isAbstract && collectProcessor.getCollection().size() < 2) { - final PsiClass aClass = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public PsiClass compute() { - return method.getContainingClass(); - } - }); - if (aClass != null) { - FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter(collectExprProcessor)); + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + OverridingMethodsSearch.search(method).forEach(new PsiElementProcessorAdapter(collectProcessor)); + if (isAbstract && collectProcessor.getCollection().size() < 2) { + final PsiClass aClass = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public PsiClass compute() { + return method.getContainingClass(); } + }); + if (aClass != null) { + FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter(collectExprProcessor)); } } }, SEARCHING_FOR_OVERRIDING_METHODS, true, method.getProject(), (JComponent)e.getComponent())) { @@ -316,14 +295,11 @@ public class MarkerType { } private static final String SEARCHING_FOR_OVERRIDDEN_METHODS = "Searching for Overridden Methods"; - static final MarkerType SUBCLASSED_CLASS = new MarkerType("SUBCLASSED_CLASS", new NullableFunction() { - @Override - public String fun(PsiElement element) { - PsiElement parent = element.getParent(); - if (!(parent instanceof PsiClass)) return null; - PsiClass aClass = (PsiClass)parent; - return getSubclassedClassTooltip(aClass); - } + static final MarkerType SUBCLASSED_CLASS = new MarkerType("SUBCLASSED_CLASS", (NullableFunction)element -> { + PsiElement parent = element.getParent(); + if (!(parent instanceof PsiClass)) return null; + PsiClass aClass = (PsiClass)parent; + return getSubclassedClassTooltip(aClass); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { @@ -376,13 +352,10 @@ public class MarkerType { final PsiElementProcessor.CollectElementsWithLimit collectProcessor = new PsiElementProcessor.CollectElementsWithLimit(2, new THashSet()); final PsiElementProcessor.CollectElementsWithLimit collectExprProcessor = new PsiElementProcessor.CollectElementsWithLimit(2, new THashSet()); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ClassInheritorsSearch.search(aClass).forEach(new PsiElementProcessorAdapter(collectProcessor)); - if (collectProcessor.getCollection().size() < 2) { - FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter(collectExprProcessor)); - } + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + ClassInheritorsSearch.search(aClass).forEach(new PsiElementProcessorAdapter(collectProcessor)); + if (collectProcessor.getCollection().size() < 2) { + FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter(collectExprProcessor)); } }, SEARCHING_FOR_OVERRIDDEN_METHODS, true, aClass.getProject(), (JComponent)e.getComponent())) { return; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java index dabbbd097fff..43ced2a7bc5e 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/actions/AddImportAction.java @@ -186,20 +186,14 @@ public class AddImportAction implements QuestionAction { } public static void excludeFromImport(final Project project, final String prefix) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; - final AutoImportOptionsConfigurable configurable = new AutoImportOptionsConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - final JavaAutoImportOptions options = ContainerUtil.findInstance(configurable.getConfigurables(), JavaAutoImportOptions.class); - options.addExcludePackage(prefix); - } - }); - } + final AutoImportOptionsConfigurable configurable = new AutoImportOptionsConfigurable(project); + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + final JavaAutoImportOptions options = ContainerUtil.findInstance(configurable.getConfigurables(), JavaAutoImportOptions.class); + options.addExcludePackage(prefix); + }); }); } @@ -216,22 +210,9 @@ public class AddImportAction implements QuestionAction { private void addImport(final PsiReference ref, final PsiClass targetClass) { StatisticsManager.getInstance().incUseCount(JavaStatisticsManager.createInfo(null, targetClass)); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - _addImport(ref, targetClass); - } - }); - } - }); - } - }, QuickFixBundle.message("add.import"), null); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> _addImport(ref, targetClass)); + }), QuickFixBundle.message("add.import"), null); } private void _addImport(PsiReference ref, PsiClass targetClass) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionFromFieldInitializerToConstructorThrowsFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionFromFieldInitializerToConstructorThrowsFix.java index 1bac4a9539fd..e21bad023b76 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionFromFieldInitializerToConstructorThrowsFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionFromFieldInitializerToConstructorThrowsFix.java @@ -82,11 +82,8 @@ public class AddExceptionFromFieldInitializerToConstructorThrowsFix extends Base PsiMethod[] constructors = aClass.getConstructors(); if (constructors.length == 0) { final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(aClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - defaultConstructorFix.invoke(project, null, file); - } + ApplicationManager.getApplication().runWriteAction(() -> { + defaultConstructorFix.invoke(project, null, file); }); constructors = aClass.getConstructors(); LOG.assertTrue(constructors.length != 0); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionToThrowsFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionToThrowsFix.java index 84f332d4a4e6..009781cbdafc 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionToThrowsFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExceptionToThrowsFix.java @@ -94,28 +94,25 @@ public class AddExceptionToThrowsFix extends BaseIntentionAction { } ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - if (!FileModificationService.getInstance().prepareFileForWrite(targetMethod.getContainingFile())) return; + () -> { + if (!FileModificationService.getInstance().prepareFileForWrite(targetMethod.getContainingFile())) return; + if (processSuperMethods) { + for (PsiMethod superMethod : superMethods) { + if (!FileModificationService.getInstance().prepareFileForWrite(superMethod.getContainingFile())) return; + } + } + + try { + processMethod(project, targetMethod, unhandledExceptions); + if (processSuperMethods) { for (PsiMethod superMethod : superMethods) { - if (!FileModificationService.getInstance().prepareFileForWrite(superMethod.getContainingFile())) return; + processMethod(project, superMethod, unhandledExceptions); } } - - try { - processMethod(project, targetMethod, unhandledExceptions); - - if (processSuperMethods) { - for (PsiMethod superMethod : superMethods) { - processMethod(project, superMethod, unhandledExceptions); - } - } - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + } + catch (IncorrectOperationException e) { + LOG.error(e); } } ); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExternalLibraryToDependenciesQuickFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExternalLibraryToDependenciesQuickFix.java index beef70a865a0..2372a44992e3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExternalLibraryToDependenciesQuickFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddExternalLibraryToDependenciesQuickFix.java @@ -72,15 +72,10 @@ class AddExternalLibraryToDependenciesQuickFix extends OrderEntryFix { public void invoke(@NotNull Project project, final Editor editor, PsiFile file) throws IncorrectOperationException { DependencyScope scope = suggestScopeByLocation(myCurrentModule, myReference.getElement()); JavaProjectModelModificationService.getInstance(project).addDependency(myCurrentModule, myLibraryDescriptor, scope).done( - new Consumer() { - @Override - public void consume(Void aVoid) { - new WriteAction() { - protected void run(@NotNull final Result result) { - importClass(myCurrentModule, editor, myReference, myQualifiedClassName); - } - }.execute(); + aVoid -> new WriteAction() { + protected void run(@NotNull final Result result) { + importClass(myCurrentModule, editor, myReference, myQualifiedClassName); } - }); + }.execute()); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java index ce0ee8fefe91..ab5997d6a3ba 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java @@ -129,11 +129,8 @@ public class AddMethodQualifierFix implements IntentionAction { @Override public PopupStep onChosen(final PsiVariable selectedValue, final boolean finalChoice) { if (selectedValue != null && finalChoice) { - WriteCommandAction.runWriteCommandAction(selectedValue.getProject(), new Runnable() { - @Override - public void run() { - qualify(selectedValue, editor); - } + WriteCommandAction.runWriteCommandAction(selectedValue.getProject(), () -> { + qualify(selectedValue, editor); }); } return FINAL_CHOICE; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java index f48383f0c1cb..7ed9a6a81324 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMissingRequiredAnnotationParametersFix.java @@ -83,12 +83,8 @@ public class AddMissingRequiredAnnotationParametersFix implements IntentionActio final TObjectIntHashMap annotationsOrderMap = getAnnotationsOrderMap(); final SortedSet> - newParameters = new TreeSet>(new Comparator>() { - @Override - public int compare(final Pair o1, final Pair o2) { - return annotationsOrderMap.get(o1.getFirst()) - annotationsOrderMap.get(o2.getFirst()); - } - }); + newParameters = new TreeSet>( + (o1, o2) -> annotationsOrderMap.get(o1.getFirst()) - annotationsOrderMap.get(o2.getFirst())); final boolean order = isAlreadyAddedOrdered(annotationsOrderMap, addedParameters); if (order) { if (addedParameters.length != 0) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDependencyFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDependencyFix.java index 3b6f16fa86ff..bc735d51a836 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDependencyFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDependencyFix.java @@ -121,13 +121,10 @@ class AddModuleDependencyFix extends OrderEntryFix { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof Module) { - addDependencyOnModule(project, editor, (Module)value); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof Module) { + addDependencyOnModule(project, editor, (Module)value); } }).createPopup(); if (editor != null) { @@ -139,23 +136,20 @@ class AddModuleDependencyFix extends OrderEntryFix { } private void addDependencyOnModule(final Project project, final Editor editor, final Module module) { - final Runnable doit = new Runnable() { - @Override - public void run() { - final boolean test = ModuleRootManager.getInstance(myCurrentModule).getFileIndex().isInTestSourceContent(myClassVFile); - JavaProjectModelModificationService.getInstance(project).addDependency(myCurrentModule, module, - test ? DependencyScope.TEST : DependencyScope.COMPILE); - if (editor != null) { - final List targetClasses = new ArrayList(); - for (PsiClass psiClass : myClasses) { - if (ModuleUtilCore.findModuleForPsiElement(psiClass) == module) { - targetClasses.add(psiClass); - } - } - if (!DumbService.isDumb(project)) { - new AddImportAction(project, myReference, editor, targetClasses.toArray(new PsiClass[targetClasses.size()])).execute(); + final Runnable doit = () -> { + final boolean test = ModuleRootManager.getInstance(myCurrentModule).getFileIndex().isInTestSourceContent(myClassVFile); + JavaProjectModelModificationService.getInstance(project).addDependency(myCurrentModule, module, + test ? DependencyScope.TEST : DependencyScope.COMPILE); + if (editor != null) { + final List targetClasses = new ArrayList(); + for (PsiClass psiClass : myClasses) { + if (ModuleUtilCore.findModuleForPsiElement(psiClass) == module) { + targetClasses.add(psiClass); } } + if (!DumbService.isDumb(project)) { + new AddImportAction(project, myReference, editor, targetClasses.toArray(new PsiClass[targetClasses.size()])).execute(); + } } }; Couple circularModules = ModuleCompilerUtil.addingDependencyFormsCircularity(myCurrentModule, module); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java index 40093816e2e1..61fe89b7f421 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java @@ -200,18 +200,10 @@ public class ChangeMethodSignatureFromUsageFix implements IntentionAction/*, Hig options.isUsages = true; options.isSearchForTextOccurrences = false; final int[] usagesFound = new int[1]; - Runnable runnable = new Runnable() { - @Override - public void run() { - Processor processor = new Processor() { - @Override - public boolean process(final UsageInfo t) { - return ++usagesFound[0] < minUsagesNumber; - } - }; + Runnable runnable = () -> { + Processor processor = t -> ++usagesFound[0] < minUsagesNumber; - handler.processElementUsages(method, processor, options); - } + handler.processElementUsages(method, processor, options); }; String progressTitle = QuickFixBundle.message("searching.for.usages.progress.title"); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, progressTitle, true, project)) return null; @@ -237,11 +229,8 @@ public class ChangeMethodSignatureFromUsageFix implements IntentionAction/*, Hig } }; processor.run(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - UndoUtil.markPsiFileForUndo(file); - } + ApplicationManager.getApplication().runWriteAction(() -> { + UndoUtil.markPsiFileForUndo(file); }); return Arrays.asList(newParametersInfo); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java index 5e91052a46eb..c4c79c02d31b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java @@ -71,11 +71,8 @@ public class ChangeParameterClassFix extends ExtendsListFix { final PsiClass myClass = (PsiClass)startElement; if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - invokeImpl(myClass); - } + () -> { + invokeImpl(myClass); } ); final Editor editor1 = CodeInsightUtil.positionCursorAtLBrace(project, myClass.getContainingFile(), myClass); @@ -84,18 +81,12 @@ public class ChangeParameterClassFix extends ExtendsListFix { if (!toImplement.isEmpty()) { if (ApplicationManager.getApplication().isUnitTestMode()) { ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - Collection members = - ContainerUtil.map2List(toImplement, new Function() { - @Override - public PsiMethodMember fun(final CandidateInfo s) { - return new PsiMethodMember(s); - } - }); - OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(editor1, myClass, members, false); - } + () -> { + Collection members = + ContainerUtil.map2List(toImplement, s -> { + return new PsiMethodMember(s); + }); + OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(editor1, myClass, members, false); }); } else { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromNewFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromNewFix.java index e18c205745b2..0dbd91930ab7 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromNewFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromNewFix.java @@ -54,36 +54,29 @@ public class CreateClassFromNewFix extends CreateFromUsageBaseFix { assert ApplicationManager.getApplication().isWriteAccessAllowed(); final Project project = targetClass.getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) { - return; - } - - PsiDocumentManager.getInstance(project).commitAllDocuments(); - - final PsiNewExpression newExpression = getNewExpression(); - if (newExpression == null) { - return; - } - - final PsiJavaCodeReferenceElement referenceElement = getReferenceElement(newExpression); - final PsiClass[] psiClass = new PsiClass[1]; - CommandProcessor.getInstance().executeCommand(newExpression.getProject(), new Runnable() { - @Override - public void run() { - psiClass[0] = CreateFromUsageUtils.createClass(referenceElement, CreateClassKind.CLASS, null); - } - }, getText(), getText()); - - new WriteCommandAction(project, getText(), getText()) { - @Override - protected void run(@NotNull Result result) throws Throwable { - setupClassFromNewExpression(psiClass[0], newExpression); - } - }.execute(); + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) { + return; } + + PsiDocumentManager.getInstance(project).commitAllDocuments(); + + final PsiNewExpression newExpression = getNewExpression(); + if (newExpression == null) { + return; + } + + final PsiJavaCodeReferenceElement referenceElement = getReferenceElement(newExpression); + final PsiClass[] psiClass = new PsiClass[1]; + CommandProcessor.getInstance().executeCommand(newExpression.getProject(), () -> + psiClass[0] = CreateFromUsageUtils.createClass(referenceElement, CreateClassKind.CLASS, null), getText(), getText()); + + new WriteCommandAction(project, getText(), getText()) { + @Override + protected void run(@NotNull Result result) throws Throwable { + setupClassFromNewExpression(psiClass[0], newExpression); + } + }.execute(); }); } @@ -119,22 +112,19 @@ public class CreateClassFromNewFix extends CreateFromUsageBaseFix { final Editor editor = positionCursor(project, aClass.getContainingFile(), aClass); if (editor == null) return; final RangeMarker textRange = editor.getDocument().createRangeMarker(aClass.getTextRange()); - final Runnable runnable = new Runnable() { - @Override - public void run() { - new WriteCommandAction(project, getText(), getText()) { - @Override - protected void run(@NotNull Result result) throws Throwable { - try { - editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset()); - } - finally { - textRange.dispose(); - } + final Runnable runnable = () -> { + new WriteCommandAction(project, getText(), getText()) { + @Override + protected void run(@NotNull Result result) throws Throwable { + try { + editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset()); } - }.execute(); - startTemplate(editor, template, project, null, getText()); - } + finally { + textRange.dispose(); + } + } + }.execute(); + startTemplate(editor, template, project, null, getText()); }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageFix.java index 8eda6b6684aa..47bb8a6c1e33 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageFix.java @@ -56,23 +56,20 @@ public class CreateClassFromUsageFix extends CreateClassFromUsageBaseFix { if (aClass == null) return; ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - PsiJavaCodeReferenceElement refElement = element; - try { - refElement = (PsiJavaCodeReferenceElement)refElement.bindToElement(aClass); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - - IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); - - OpenFileDescriptor descriptor = new OpenFileDescriptor(refElement.getProject(), aClass.getContainingFile().getVirtualFile(), - aClass.getTextOffset()); - FileEditorManager.getInstance(aClass.getProject()).openTextEditor(descriptor, true); + () -> { + PsiJavaCodeReferenceElement refElement = element; + try { + refElement = (PsiJavaCodeReferenceElement)refElement.bindToElement(aClass); } + catch (IncorrectOperationException e) { + LOG.error(e); + } + + IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); + + OpenFileDescriptor descriptor = new OpenFileDescriptor(refElement.getProject(), aClass.getContainingFile().getVirtualFile(), + aClass.getTextOffset()); + FileEditorManager.getInstance(aClass.getProject()).openTextEditor(descriptor, true); } ); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromCallFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromCallFix.java index efde701fa61f..f13ce291e6e8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromCallFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromCallFix.java @@ -76,23 +76,20 @@ public class CreateConstructorFromCallFix extends CreateFromUsageBaseFix { startTemplate(editor, template, project, new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); - final int offset = editor.getCaretModel().getOffset(); - PsiMethod constructor = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false); - if (superConstructor == null) { - CreateFromUsageUtils.setupMethodBody(constructor); - } else { - OverrideImplementUtil.setupMethodBody(constructor, superConstructor, targetClass); - } - CreateFromUsageUtils.setupEditor(constructor, editor); - } - catch (IncorrectOperationException e) { - LOG.error(e); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + final int offset = editor.getCaretModel().getOffset(); + PsiMethod constructor1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false); + if (superConstructor == null) { + CreateFromUsageUtils.setupMethodBody(constructor1); + } else { + OverrideImplementUtil.setupMethodBody(constructor1, superConstructor, targetClass); } + CreateFromUsageUtils.setupEditor(constructor1, editor); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java index 4249e579aedf..a21ff256a7a3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java @@ -113,21 +113,18 @@ public abstract class CreateConstructorFromThisOrSuperFix extends CreateFromUsag startTemplate(editor, template, project, new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); - final int offset = editor.getCaretModel().getOffset(); - PsiMethod constructor = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false); - CreateFromUsageUtils.setupMethodBody(constructor); - CreateFromUsageUtils.setupEditor(constructor, editor); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + final int offset = editor.getCaretModel().getOffset(); + PsiMethod constructor1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false); + CreateFromUsageUtils.setupMethodBody(constructor1); + CreateFromUsageUtils.setupEditor(constructor1, editor); - UndoUtil.markPsiFileForUndo(callSite); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + UndoUtil.markPsiFileForUndo(callSite); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorMatchingSuperFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorMatchingSuperFix.java index b3c868a562c8..f2af0d4e6da3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorMatchingSuperFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorMatchingSuperFix.java @@ -108,58 +108,55 @@ public class CreateConstructorMatchingSuperFix extends BaseIntentionAction { final PsiMethodMember[] constructors1 = constructors; final boolean isCopyJavadoc1 = isCopyJavadoc; ApplicationManager.getApplication().runWriteAction ( - new Runnable() { - @Override - public void run() { - try { - if (targetClass.getLBrace() == null) { - PsiClass psiClass = JavaPsiFacade.getInstance(targetClass.getProject()).getElementFactory().createClass("X"); - targetClass.addRangeAfter(psiClass.getLBrace(), psiClass.getRBrace(), targetClass.getLastChild()); - } - JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), project); - CodeStyleManager formatter = CodeStyleManager.getInstance(project); - PsiMethod derived = null; - for (PsiMethodMember candidate : constructors1) { - PsiMethod base = candidate.getElement(); - derived = GenerateMembersUtil.substituteGenericMethod(base, candidate.getSubstitutor(), targetClass); - - if (!isCopyJavadoc1) { - final PsiDocComment docComment = derived.getDocComment(); - if (docComment != null) { - docComment.delete(); - } - } - - final String targetClassName = targetClass.getName(); - LOG.assertTrue(targetClassName != null, targetClass); - derived.setName(targetClassName); - - ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(derived.getLanguage()); - if (generator != null) { - StringBuilder buffer = new StringBuilder(); - generator.start(buffer, derived.getName(), PsiParameter.EMPTY_ARRAY); - generator.generateSuperCallIfNeeded(buffer, derived.getParameterList().getParameters()); - generator.finish(buffer); - PsiMethod stub = factory.createMethodFromText(buffer.toString(), targetClass); - derived.getBody().replace(stub.getBody()); - } - derived = (PsiMethod)formatter.reformat(derived); - derived = (PsiMethod)JavaCodeStyleManager.getInstance(project).shortenClassReferences(derived); - PsiGenerationInfo info = OverrideImplementUtil.createGenerationInfo(derived); - info.insert(targetClass, null, true); - derived = info.getPsiMember(); - } - if (derived != null) { - editor.getCaretModel().moveToOffset(derived.getTextRange().getStartOffset()); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); + () -> { + try { + if (targetClass.getLBrace() == null) { + PsiClass psiClass = JavaPsiFacade.getInstance(targetClass.getProject()).getElementFactory().createClass("X"); + targetClass.addRangeAfter(psiClass.getLBrace(), psiClass.getRBrace(), targetClass.getLastChild()); } + JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), project); + CodeStyleManager formatter = CodeStyleManager.getInstance(project); + PsiMethod derived = null; + for (PsiMethodMember candidate : constructors1) { + PsiMethod base = candidate.getElement(); + derived = GenerateMembersUtil.substituteGenericMethod(base, candidate.getSubstitutor(), targetClass); - UndoUtil.markPsiFileForUndo(targetClass.getContainingFile()); + if (!isCopyJavadoc1) { + final PsiDocComment docComment = derived.getDocComment(); + if (docComment != null) { + docComment.delete(); + } + } + + final String targetClassName = targetClass.getName(); + LOG.assertTrue(targetClassName != null, targetClass); + derived.setName(targetClassName); + + ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(derived.getLanguage()); + if (generator != null) { + StringBuilder buffer = new StringBuilder(); + generator.start(buffer, derived.getName(), PsiParameter.EMPTY_ARRAY); + generator.generateSuperCallIfNeeded(buffer, derived.getParameterList().getParameters()); + generator.finish(buffer); + PsiMethod stub = factory.createMethodFromText(buffer.toString(), targetClass); + derived.getBody().replace(stub.getBody()); + } + derived = (PsiMethod)formatter.reformat(derived); + derived = (PsiMethod)JavaCodeStyleManager.getInstance(project).shortenClassReferences(derived); + PsiGenerationInfo info = OverrideImplementUtil.createGenerationInfo(derived); + info.insert(targetClass, null, true); + derived = info.getPsiMember(); + } + if (derived != null) { + editor.getCaretModel().moveToOffset(derived.getTextRange().getStartOffset()); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + } } + catch (IncorrectOperationException e) { + LOG.error(e); + } + + UndoUtil.markPsiFileForUndo(targetClass.getContainingFile()); } ); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java index 91732b67b6ad..5dbc30cd978e 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java @@ -103,11 +103,8 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { PsiMethod[] constructors = myClass.getConstructors(); if (constructors.length == 0) { final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(myClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - defaultConstructorFix.invoke(project, editor, file); - } + ApplicationManager.getApplication().runWriteAction(() -> { + defaultConstructorFix.invoke(project, editor, file); }); constructors = myClass.getConstructors(); } @@ -292,12 +289,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { } private static String createDummyMethod(PsiMethod constructor, ParameterInfoImpl[] newParamInfos) { - return constructor.getName() + "(" + StringUtil.join(newParamInfos, new Function() { - @Override - public String fun(ParameterInfoImpl info) { - return info.getTypeText() + " " + info.getName(); - } - }, ", ") + "){}"; + return constructor.getName() + "(" + StringUtil.join(newParamInfos, info -> info.getTypeText() + " " + info.getName(), ", ") + "){}"; } private static String getUniqueParameterName(PsiParameter[] parameters, PsiVariable variable, Map usedNames) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateEnumConstantFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateEnumConstantFromUsageFix.java index 4defdd35de1d..ec0ccbaa7934 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateEnumConstantFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateEnumConstantFromUsageFix.java @@ -60,11 +60,8 @@ public class CreateEnumConstantFromUsageFix extends CreateVarFromUsageFix implem final PsiMethod constructor = constructors[0]; final PsiParameter[] parameters = constructor.getParameterList().getParameters(); if (parameters.length > 0) { - final String params = StringUtil.join(parameters, new Function() { - @Override - public String fun(PsiParameter psiParameter) { - return psiParameter.getName(); - } + final String params = StringUtil.join(parameters, psiParameter -> { + return psiParameter.getName(); }, ","); enumConstant = (PsiEnumConstant)enumConstant.replace(elementFactory.createEnumConstantFromText(name + "(" + params + ")", null)); final TemplateBuilderImpl builder = new TemplateBuilderImpl(enumConstant); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFieldFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFieldFromUsageFix.java index 1e9d1a88cb99..f30b610ca101 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFieldFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFieldFromUsageFix.java @@ -129,11 +129,8 @@ public class CreateFieldFromUsageFix extends CreateVarFromUsageFix { final int offset = newEditor.getCaretModel().getOffset(); final PsiField psiField = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset, PsiField.class, false); if (psiField != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(project).reformat(psiField); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CodeStyleManager.getInstance(project).reformat(psiField); }); newEditor.getCaretModel().moveToOffset(psiField.getTextRange().getEndOffset() - 1); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageBaseFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageBaseFix.java index 5a9e3cbce898..5531d26b1999 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageBaseFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageBaseFix.java @@ -107,11 +107,8 @@ public abstract class CreateFromUsageBaseFix extends BaseIntentionAction { } IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - invokeImpl(targetClass); - } + ApplicationManager.getApplication().runWriteAction(() -> { + invokeImpl(targetClass); }); } @@ -134,20 +131,12 @@ public abstract class CreateFromUsageBaseFix extends BaseIntentionAction { list.setSelectedValue(preselection, true); } - Runnable runnable = new Runnable() { - @Override - public void run() { - int index = list.getSelectedIndex(); - if (index < 0) return; - final PsiClass aClass = (PsiClass) list.getSelectedValue(); - AnonymousTargetClassPreselectionUtil.rememberSelection(aClass, firstClass); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - doInvoke(project, aClass); - } - }, getText(), null); - } + Runnable runnable = () -> { + int index = list.getSelectedIndex(); + if (index < 0) return; + final PsiClass aClass = (PsiClass) list.getSelectedValue(); + AnonymousTargetClassPreselectionUtil.rememberSelection(aClass, firstClass); + CommandProcessor.getInstance().executeCommand(project, () -> doInvoke(project, aClass), getText(), null); }; builder. @@ -428,17 +417,10 @@ public abstract class CreateFromUsageBaseFix extends BaseIntentionAction { @NotNull final Project project, final TemplateEditingListener listener, final String commandName) { - Runnable runnable = new Runnable() { - @Override - public void run() { - if (project.isDisposed() || editor.isDisposed()) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - TemplateManager.getInstance(project).startTemplate(editor, template, listener); - } - }, commandName, commandName); - } + Runnable runnable = () -> { + if (project.isDisposed() || editor.isDisposed()) return; + CommandProcessor.getInstance().executeCommand(project, + () -> TemplateManager.getInstance(project).startTemplate(editor, template, listener), commandName, commandName); }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java index fafe647b4137..01fa773353d1 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java @@ -171,13 +171,9 @@ public class CreateFromUsageUtils { m = factory.createMethodFromText(methodText, aClass); } catch (IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(QuickFixBundle.message("new.method.body.template.error.text"), - QuickFixBundle.message("new.method.body.template.error.title")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(QuickFixBundle.message("new.method.body.template.error.text"), + QuickFixBundle.message("new.method.body.template.error.title"))); return; } PsiCodeBlock oldBody = method.getBody(); @@ -479,15 +475,10 @@ public class CreateFromUsageUtils { public static void scheduleFileOrPackageCreationFailedMessageBox(final IncorrectOperationException e, final String name, final PsiDirectory directory, final boolean isPackage) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(QuickFixBundle.message( - isPackage ? "cannot.create.java.package.error.text" : "cannot.create.java.file.error.text", name, directory.getVirtualFile().getName(), e.getLocalizedMessage()), - QuickFixBundle.message( - isPackage ? "cannot.create.java.package.error.title" : "cannot.create.java.file.error.title")); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(QuickFixBundle.message( + isPackage ? "cannot.create.java.package.error.text" : "cannot.create.java.file.error.text", name, directory.getVirtualFile().getName(), e.getLocalizedMessage()), + QuickFixBundle.message( + isPackage ? "cannot.create.java.package.error.title" : "cannot.create.java.file.error.title"))); } public static PsiReferenceExpression[] collectExpressions(final PsiExpression expression, Class... scopes) { @@ -588,12 +579,7 @@ public class CreateFromUsageUtils { if (!(parent instanceof PsiReferenceExpression)) { ExpectedTypeInfo[] someExpectedTypes = ExpectedTypesProvider.getExpectedTypes(expr, PsiUtil.skipParenthesizedExprUp(parent) instanceof PsiExpressionList); if (someExpectedTypes.length > 0) { - Arrays.sort(someExpectedTypes, new Comparator() { - @Override - public int compare(ExpectedTypeInfo o1, ExpectedTypeInfo o2) { - return compareExpectedTypes(o1, o2, expression); - } - }); + Arrays.sort(someExpectedTypes, (o1, o2) -> compareExpectedTypes(o1, o2, expression)); types.add(someExpectedTypes); } continue; @@ -610,12 +596,7 @@ public class CreateFromUsageUtils { if (refName.equals("equals")) { ExpectedTypeInfo[] someExpectedTypes = equalsExpectedTypes((PsiMethodCallExpression)pparent); if (someExpectedTypes.length > 0) { - Arrays.sort(someExpectedTypes, new Comparator() { - @Override - public int compare(ExpectedTypeInfo o1, ExpectedTypeInfo o2) { - return compareExpectedTypes(o1, o2, expression); - } - }); + Arrays.sort(someExpectedTypes, (o1, o2) -> compareExpectedTypes(o1, o2, expression)); types.add(someExpectedTypes); } } @@ -807,12 +788,7 @@ public class CreateFromUsageUtils { final PsiExpression expression, List types, PsiElementFactory factory) { - Arrays.sort(members, new Comparator() { - @Override - public int compare(final PsiMember m1, final PsiMember m2) { - return compareMembers(m1, m2, expression); - } - }); + Arrays.sort(members, (m1, m2) -> compareMembers(m1, m2, expression)); List l = new ArrayList(); PsiManager manager = expression.getManager(); @@ -928,12 +904,9 @@ public class CreateFromUsageUtils { final String qName = getQualifiedName(containingClass); if (qName == null) continue; - ClassInheritorsSearch.search(containingClass, descendantsSearchScope, true, true, false).forEach(new Processor() { - @Override - public boolean process(PsiClass psiClass) { - ContainerUtil.addIfNotNull(getQualifiedName(psiClass), possibleClassNames); - return true; - } + ClassInheritorsSearch.search(containingClass, descendantsSearchScope, true, true, false).forEach(psiClass -> { + ContainerUtil.addIfNotNull(getQualifiedName(psiClass), possibleClassNames); + return true; }); possibleClassNames.add(qName); @@ -946,20 +919,17 @@ public class CreateFromUsageUtils { private static boolean handleObjectMethod(Set possibleClassNames, final JavaPsiFacade facade, final GlobalSearchScope searchScope, final boolean method, final String memberName, final boolean staticAccess, boolean addInheritors) { final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(facade.getProject()); final boolean[] allClasses = {false}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiClass objectClass = facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, searchScope); - if (objectClass != null) { - if (method && objectClass.findMethodsByName(memberName, false).length > 0) { + ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass objectClass = facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, searchScope); + if (objectClass != null) { + if (method && objectClass.findMethodsByName(memberName, false).length > 0) { + allClasses[0] = true; + } + else if (!method) { + final PsiField field = objectClass.findFieldByName(memberName, false); + if (hasCorrectModifiers(field, staticAccess)) { allClasses[0] = true; } - else if (!method) { - final PsiField field = objectClass.findFieldByName(memberName, false); - if (hasCorrectModifiers(field, staticAccess)) { - allClasses[0] = true; - } - } } } }); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java index ed7d3c933938..7373756a2fad 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java @@ -109,30 +109,18 @@ public class CreateInnerClassFromUsageFix extends CreateClassFromUsageBaseFix { final PopupChooserBuilder builder = new PopupChooserBuilder(list); renderer.installSpeedSearch(builder); - Runnable runnable = new Runnable() { - @Override - public void run() { - int index = list.getSelectedIndex(); - if (index < 0) return; - final PsiClass aClass = (PsiClass)list.getSelectedValue(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - doInvoke(aClass, superClassName); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); - - } - }, getText(), null); - } + Runnable runnable = () -> { + int index = list.getSelectedIndex(); + if (index < 0) return; + final PsiClass aClass = (PsiClass)list.getSelectedValue(); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + doInvoke(aClass, superClassName); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), getText(), null); }; builder. diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java index bae4cd9e8bee..cdb6522a04d2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalFromUsageFix.java @@ -144,11 +144,8 @@ public class CreateLocalFromUsageFix extends CreateVarFromUsageFix { if (localVariable != null) { TypeSelectorManagerImpl.typeSelected(localVariable.getType(), defaultType.getType()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(project).reformat(localVariable); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CodeStyleManager.getInstance(project).reformat(localVariable); }); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalVarFromInstanceofAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalVarFromInstanceofAction.java index 88b1a11a942f..ea3235831801 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalVarFromInstanceofAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateLocalVarFromInstanceofAction.java @@ -222,19 +222,16 @@ public class CreateLocalVarFromInstanceofAction extends BaseIntentionAction { CreateFromUsageBaseFix.startTemplate(newEditor, template, project, new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); - CaretModel caretModel = editor.getCaretModel(); - PsiElement elementAt = file.findElementAt(caretModel.getOffset()); - PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementAt, PsiDeclarationStatement.class); - if (declarationStatement != null) { - caretModel.moveToOffset(declarationStatement.getTextRange().getEndOffset()); - } - new EnterAction().actionPerformed(editor, DataManager.getInstance().getDataContext()); + CaretModel caretModel = editor.getCaretModel(); + PsiElement elementAt = file.findElementAt(caretModel.getOffset()); + PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementAt, PsiDeclarationStatement.class); + if (declarationStatement != null) { + caretModel.moveToOffset(declarationStatement.getTextRange().getEndOffset()); } + new EnterAction().actionPerformed(editor, DataManager.getInstance().getDataContext()); }); } }); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java index 74df48381201..8c3c587f9811 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java @@ -127,11 +127,8 @@ public class CreateMethodFromMethodReferenceFix extends CreateFromUsageBaseFix { final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, classResolveResult); final ExpectedTypeInfo[] expectedTypes = {new ExpectedTypeInfoImpl(interfaceReturnType, ExpectedTypeInfo.TYPE_OR_SUBTYPE, interfaceReturnType, TailType.NONE, null, ExpectedTypeInfoImpl.NULL)}; CreateMethodFromUsageFix.doCreate(targetClass, method, false, - ContainerUtil.map2List(interfaceMethod.getParameterList().getParameters(), new Function>() { - @Override - public Pair fun(PsiParameter parameter) { - return Pair.create(null, substitutor.substitute(parameter.getType())); - } + ContainerUtil.map2List(interfaceMethod.getParameterList().getParameters(), parameter -> { + return Pair.create(null, substitutor.substitute(parameter.getType())); }), PsiSubstitutor.EMPTY, expectedTypes, context); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java index 66a932d49661..5c505da612f5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java @@ -97,12 +97,8 @@ public class CreateMethodFromUsageFix extends CreateFromUsageBaseFix { return !DaemonCodeAnalyzerEx.processHighlights(document, project, HighlightSeverity.ERROR, //strictly inside arg list argRange.getStartOffset() + 1, - argRange.getEndOffset() - 1, new Processor() { - @Override - public boolean process(HighlightInfo info) { - return !(info.getActualStartOffset() > argRange.getStartOffset() && info.getActualEndOffset() < argRange.getEndOffset()); - } - }); + argRange.getEndOffset() - 1, + info -> !(info.getActualStartOffset() > argRange.getStartOffset() && info.getActualEndOffset() < argRange.getEndOffset())); } @Override @@ -263,22 +259,19 @@ public class CreateMethodFromUsageFix extends CreateFromUsageBaseFix { startTemplate(newEditor, template, project, new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument()); - final int offset = newEditor.getCaretModel().getOffset(); - PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false); - if (method != null) { - try { - CreateFromUsageUtils.setupMethodBody(method); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - - CreateFromUsageUtils.setupEditor(method, newEditor); + WriteCommandAction.runWriteCommandAction(project, () -> { + PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument()); + final int offset = newEditor.getCaretModel().getOffset(); + PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false); + if (method1 != null) { + try { + CreateFromUsageUtils.setupMethodBody(method1); } + catch (IncorrectOperationException e) { + LOG.error(e); + } + + CreateFromUsageUtils.setupEditor(method1, newEditor); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateParameterFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateParameterFromUsageFix.java index 30e9efeaa5b4..a7f38a2edc95 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateParameterFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateParameterFromUsageFix.java @@ -98,48 +98,45 @@ public class CreateParameterFromUsageFix extends CreateVarFromUsageFix { final Application application = ApplicationManager.getApplication(); final PsiMethod finalMethod = method; - application.invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; - if (application.isUnitTestMode()) { - ParameterInfoImpl[] array = parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()]); - String modifier = PsiUtil.getAccessModifier(PsiUtil.getAccessLevel(finalMethod.getModifierList())); - ChangeSignatureProcessor processor = - new ChangeSignatureProcessor(project, finalMethod, false, modifier, finalMethod.getName(), finalMethod.getReturnType(), array); - processor.run(); - } - else { - try { - JavaChangeSignatureDialog dialog = - JavaChangeSignatureDialog.createAndPreselectNew(project, finalMethod, parameterInfos, true, myReferenceExpression); - dialog.setParameterInfos(parameterInfos); - if (dialog.showAndGet()) { - for (ParameterInfoImpl info : parameterInfos) { - if (info.getOldIndex() == -1) { - final String newParamName = info.getName(); - if (!Comparing.strEqual(varName, newParamName)) { - final PsiExpression newExpr = - JavaPsiFacade.getElementFactory(project).createExpressionFromText(newParamName, finalMethod); - new WriteCommandAction(project) { - @Override - protected void run(@NotNull Result result) throws Throwable { - final PsiReferenceExpression[] refs = - CreateFromUsageUtils.collectExpressions(myReferenceExpression, PsiMember.class, PsiFile.class); - for (PsiReferenceExpression ref : refs) { - ref.replace(newExpr.copy()); - } + application.invokeLater(() -> { + if (project.isDisposed()) return; + if (application.isUnitTestMode()) { + ParameterInfoImpl[] array = parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()]); + String modifier = PsiUtil.getAccessModifier(PsiUtil.getAccessLevel(finalMethod.getModifierList())); + ChangeSignatureProcessor processor = + new ChangeSignatureProcessor(project, finalMethod, false, modifier, finalMethod.getName(), finalMethod.getReturnType(), array); + processor.run(); + } + else { + try { + JavaChangeSignatureDialog dialog = + JavaChangeSignatureDialog.createAndPreselectNew(project, finalMethod, parameterInfos, true, myReferenceExpression); + dialog.setParameterInfos(parameterInfos); + if (dialog.showAndGet()) { + for (ParameterInfoImpl info : parameterInfos) { + if (info.getOldIndex() == -1) { + final String newParamName = info.getName(); + if (!Comparing.strEqual(varName, newParamName)) { + final PsiExpression newExpr = + JavaPsiFacade.getElementFactory(project).createExpressionFromText(newParamName, finalMethod); + new WriteCommandAction(project) { + @Override + protected void run(@NotNull Result result) throws Throwable { + final PsiReferenceExpression[] refs = + CreateFromUsageUtils.collectExpressions(myReferenceExpression, PsiMember.class, PsiFile.class); + for (PsiReferenceExpression ref : refs) { + ref.replace(newExpr.copy()); } - }.execute(); - } - break; + } + }.execute(); } + break; } } } - catch (Exception e) { - throw new RuntimeException(e); - } + } + catch (Exception e) { + throw new RuntimeException(e); } } }); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java index 50449e141dfc..d26277ca7246 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java @@ -128,11 +128,8 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix implement public FieldExpression(final PsiField field, PsiClass aClass, PsiType[] expectedTypes) { myField = field; myClass = aClass; - myExpectedTypes = ContainerUtil.map(expectedTypes, new Function() { - @Override - public SmartTypePointer fun(PsiType type) { - return SmartTypePointerManager.getInstance(field.getProject()).createSmartTypePointer(type); - } + myExpectedTypes = ContainerUtil.map(expectedTypes, type -> { + return SmartTypePointerManager.getInstance(field.getProject()).createSmartTypePointer(type); }); myDefaultFieldName = field.getName(); } @@ -272,37 +269,34 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix implement startTemplate(editor, template, project, new TemplateEditingAdapter() { @Override public void beforeTemplateFinished(final TemplateState state, Template template) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - String fieldName = state.getVariableValue(FIELD_VARIABLE).getText(); - if (!PsiNameHelper.getInstance(project).isIdentifier(fieldName)) return; - String fieldType = state.getVariableValue(TYPE_VARIABLE).getText(); + ApplicationManager.getApplication().runWriteAction(() -> { + String fieldName1 = state.getVariableValue(FIELD_VARIABLE).getText(); + if (!PsiNameHelper.getInstance(project).isIdentifier(fieldName1)) return; + String fieldType = state.getVariableValue(TYPE_VARIABLE).getText(); - PsiElement element = file.findElementAt(editor.getCaretModel().getOffset()); - PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); - if (aClass == null) return; - PsiField field = aClass.findFieldByName(fieldName, true); - if (field != null){ - CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field); - return; - } - PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); + PsiElement element = file.findElementAt(editor.getCaretModel().getOffset()); + PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); + if (aClass == null) return; + PsiField field1 = aClass.findFieldByName(fieldName1, true); + if (field1 != null){ + CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field1); + return; + } + PsiElementFactory factory1 = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); + try { + PsiType type1 = factory1.createTypeFromText(fieldType, aClass); try { - PsiType type = factory.createTypeFromText(fieldType, aClass); - try { - field = factory.createField(fieldName, type); - field = (PsiField)aClass.add(field); - PsiUtil.setModifierProperty(field, PsiModifier.STATIC, isStatic1); - CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + field1 = factory1.createField(fieldName1, type1); + field1 = (PsiField)aClass.add(field1); + PsiUtil.setModifierProperty(field1, PsiModifier.STATIC, isStatic1); + CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field1); } catch (IncorrectOperationException e) { + LOG.error(e); } } + catch (IncorrectOperationException e) { + } }); } @@ -312,11 +306,8 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix implement final int offset = editor.getCaretModel().getOffset(); final PsiMethod generatedMethod = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiMethod.class, false); if (generatedMethod != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(project).reformat(generatedMethod); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CodeStyleManager.getInstance(project).reformat(generatedMethod); }); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateStaticMethodQuickFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateStaticMethodQuickFix.java index 8268ee58d44a..6a176a439d45 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateStaticMethodQuickFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateStaticMethodQuickFix.java @@ -66,11 +66,8 @@ public class CreateStaticMethodQuickFix implements LocalQuickFix { } PsiUtil.setModifierProperty(method, PsiModifier.STATIC, true); - List> args = ContainerUtil.map(types, new Function>() { - @Override - public Pair fun(String s) { - return new Pair(null, PsiType.getTypeByName(s, project, GlobalSearchScope.allScope(project))); - } + List> args = ContainerUtil.map(types, s -> { + return new Pair(null, PsiType.getTypeByName(s, project, GlobalSearchScope.allScope(project))); }); CreateMethodFromUsageFix.doCreate(targetClass, method, false, args, diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java index de61943fa242..d3bbc2bed94d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java @@ -94,13 +94,10 @@ public class DelegateWithDefaultParamValueIntentionAction extends PsiElementBase } final PsiParameterList parameterList = method.getParameterList(); - Arrays.sort(params, new Comparator() { - @Override - public int compare(PsiParameter p1, PsiParameter p2) { - final int parameterIndex1 = parameterList.getParameterIndex(p1); - final int parameterIndex2 = parameterList.getParameterIndex(p2); - return parameterIndex1 > parameterIndex2 ? -1 : 1; - } + Arrays.sort(params, (p1, p2) -> { + final int parameterIndex1 = parameterList.getParameterIndex(p1); + final int parameterIndex2 = parameterList.getParameterIndex(p2); + return parameterIndex1 > parameterIndex2 ? -1 : 1; }); for (PsiParameter param : params) { @@ -126,58 +123,52 @@ public class DelegateWithDefaultParamValueIntentionAction extends PsiElementBase if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return; - Runnable runnable = new Runnable() { - @Override - public void run() { - - final PsiMethod prototype = (PsiMethod)method.getContainingClass().addBefore(methodPrototype, method); - RefactoringUtil.fixJavadocsForParams(prototype, new HashSet(Arrays.asList(prototype.getParameterList().getParameters()))); - TemplateBuilderImpl builder = new TemplateBuilderImpl(prototype); + Runnable runnable = () -> { - PsiCodeBlock body = prototype.getBody(); - final String callArgs = - "(" + StringUtil.join(method.getParameterList().getParameters(), new Function() { - @Override - public String fun(PsiParameter psiParameter) { - if (ArrayUtil.find(parameters, psiParameter) > -1) return "IntelliJIDEARulezzz"; - return psiParameter.getName(); - } - }, ",") + ");"; - final String methodCall; - if (method.getReturnType() == null) { - methodCall = "this"; - } else if (!PsiType.VOID.equals(method.getReturnType())) { - methodCall = "return " + method.getName(); - } else { - methodCall = method.getName(); - } - body.add(JavaPsiFacade.getElementFactory(project).createStatementFromText(methodCall + callArgs, method)); - body = (PsiCodeBlock)CodeStyleManager.getInstance(project).reformat(body); - final PsiStatement stmt = body.getStatements()[0]; - PsiExpression expr = null; - if (stmt instanceof PsiReturnStatement) { - expr = ((PsiReturnStatement)stmt).getReturnValue(); - } else if (stmt instanceof PsiExpressionStatement) { - expr = ((PsiExpressionStatement)stmt).getExpression(); - } - if (expr instanceof PsiMethodCallExpression) { - PsiMethodCallExpression methodCallExp = (PsiMethodCallExpression)expr; - RangeMarker rangeMarker = editor.getDocument().createRangeMarker(prototype.getTextRange()); - for (PsiParameter parameter : parameters) { - final PsiExpression exprToBeDefault = - methodCallExp.getArgumentList().getExpressions()[method.getParameterList().getParameterIndex(parameter)]; - builder.replaceElement(exprToBeDefault, new TextExpression("")); - } - Template template = builder.buildTemplate(); - editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset()); - - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); - editor.getDocument().deleteString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset()); - - rangeMarker.dispose(); - - CreateFromUsageBaseFix.startTemplate(editor, template, project); + final PsiMethod prototype = (PsiMethod)method.getContainingClass().addBefore(methodPrototype, method); + RefactoringUtil.fixJavadocsForParams(prototype, new HashSet(Arrays.asList(prototype.getParameterList().getParameters()))); + TemplateBuilderImpl builder = new TemplateBuilderImpl(prototype); + + PsiCodeBlock body = prototype.getBody(); + final String callArgs = + "(" + StringUtil.join(method.getParameterList().getParameters(), psiParameter -> { + if (ArrayUtil.find(parameters, psiParameter) > -1) return "IntelliJIDEARulezzz"; + return psiParameter.getName(); + }, ",") + ");"; + final String methodCall; + if (method.getReturnType() == null) { + methodCall = "this"; + } else if (!PsiType.VOID.equals(method.getReturnType())) { + methodCall = "return " + method.getName(); + } else { + methodCall = method.getName(); + } + body.add(JavaPsiFacade.getElementFactory(project).createStatementFromText(methodCall + callArgs, method)); + body = (PsiCodeBlock)CodeStyleManager.getInstance(project).reformat(body); + final PsiStatement stmt = body.getStatements()[0]; + PsiExpression expr = null; + if (stmt instanceof PsiReturnStatement) { + expr = ((PsiReturnStatement)stmt).getReturnValue(); + } else if (stmt instanceof PsiExpressionStatement) { + expr = ((PsiExpressionStatement)stmt).getExpression(); + } + if (expr instanceof PsiMethodCallExpression) { + PsiMethodCallExpression methodCallExp = (PsiMethodCallExpression)expr; + RangeMarker rangeMarker = editor.getDocument().createRangeMarker(prototype.getTextRange()); + for (PsiParameter parameter : parameters) { + final PsiExpression exprToBeDefault = + methodCallExp.getArgumentList().getExpressions()[method.getParameterList().getParameterIndex(parameter)]; + builder.replaceElement(exprToBeDefault, new TextExpression("")); } + Template template = builder.buildTemplate(); + editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset()); + + PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); + editor.getDocument().deleteString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset()); + + rangeMarker.dispose(); + + CreateFromUsageBaseFix.startTemplate(editor, template, project); } }; if (startInWriteAction()) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java index e81650091260..961ada033e99 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java @@ -269,16 +269,13 @@ public abstract class ImportClassFixBase probableTypes = new HashSet(); - InheritanceUtil.processSupers(aClass, false, new Processor() { - @Override - public boolean process(PsiClass psiClass) { - for (PsiMethod psiMethod : psiClass.findMethodsByName(method.getName(), false)) { - for (PsiParameter psiParameter : psiMethod.getParameterList().getParameters()) { - ContainerUtil.addIfNotNull(probableTypes, PsiUtil.resolveClassInClassTypeOnly(psiParameter.getType())); - } + InheritanceUtil.processSupers(aClass, false, psiClass -> { + for (PsiMethod psiMethod : psiClass.findMethodsByName(method.getName(), false)) { + for (PsiParameter psiParameter : psiMethod.getParameterList().getParameters()) { + ContainerUtil.addIfNotNull(probableTypes, PsiUtil.resolveClassInClassTypeOnly(psiParameter.getType())); } - return true; } + return true; }); List filtered = ContainerUtil.filter(candidates, new Condition() { @Override @@ -339,12 +336,7 @@ public abstract class ImportClassFixBase action.execute()); return Result.CLASS_AUTO_IMPORTED; } @@ -435,16 +427,13 @@ public abstract class ImportClassFixBase classesToImport = getClassesToImport(true); - PsiClass[] classes = classesToImport.toArray(new PsiClass[classesToImport.size()]); - if (classes.length == 0) return; + ApplicationManager.getApplication().runWriteAction(() -> { + List classesToImport = getClassesToImport(true); + PsiClass[] classes = classesToImport.toArray(new PsiClass[classesToImport.size()]); + if (classes.length == 0) return; - AddImportAction action = createAddImportAction(classes, project, editor); - action.execute(); - } + AddImportAction action = createAddImportAction(classes, project, editor); + action.execute(); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InitializeFinalFieldInConstructorFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InitializeFinalFieldInConstructorFix.java index a069a94e0033..3eae157e3722 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InitializeFinalFieldInConstructorFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InitializeFinalFieldInConstructorFix.java @@ -87,11 +87,8 @@ public class InitializeFinalFieldInConstructorFix implements IntentionAction { final List constructors = choose(filterIfFieldAlreadyAssigned(myField, myClass.getConstructors()), project); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - addFieldInitialization(constructors, myField, project, editor); - } + ApplicationManager.getApplication().runWriteAction(() -> { + addFieldInitialization(constructors, myField, project, editor); }); } @@ -185,11 +182,8 @@ public class InitializeFinalFieldInConstructorFix implements IntentionAction { private static void createDefaultConstructor(PsiClass psiClass, @NotNull final Project project, final Editor editor, final PsiFile file) { final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(psiClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - defaultConstructorFix.invoke(project, editor, file); - } + ApplicationManager.getApplication().runWriteAction(() -> { + defaultConstructorFix.invoke(project, editor, file); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ModifierFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ModifierFix.java index 78d9a8191d55..4219b1124652 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ModifierFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ModifierFix.java @@ -145,15 +145,12 @@ public class ModifierFix extends LocalQuickFixAndIntentionActionOnPsiElement { final PsiFile containingFile = myModifierList.getContainingFile(); final PsiModifierList modifierList; if (variable != null && variable.isValid()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - variable.normalizeDeclaration(); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + variable.normalizeDeclaration(); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); modifierList = variable.getModifierList(); @@ -185,27 +182,21 @@ public class ModifierFix extends LocalQuickFixAndIntentionActionOnPsiElement { QuickFixBundle.message("change.inheritors.visibility.warning.text"), QuickFixBundle.message("change.inheritors.visibility.warning.title"), Messages.getQuestionIcon()) == Messages.YES) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (!FileModificationService.getInstance().preparePsiElementsForWrite(modifierLists)) { - return; - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (!FileModificationService.getInstance().preparePsiElementsForWrite(modifierLists)) { + return; + } - for (final PsiModifierList modifierList : modifierLists) { - changeModifierList(modifierList); - } + for (final PsiModifierList modifierList1 : modifierLists) { + changeModifierList(modifierList1); } }); } } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - changeModifierList(modifierList); - UndoUtil.markPsiFileForUndo(containingFile); - } + ApplicationManager.getApplication().runWriteAction(() -> { + changeModifierList(modifierList); + UndoUtil.markPsiFileForUndo(containingFile); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/MoveClassToModuleFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/MoveClassToModuleFix.java index 9c1d38853b2c..2492361fef67 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/MoveClassToModuleFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/MoveClassToModuleFix.java @@ -135,13 +135,10 @@ public class MoveClassToModuleFix implements IntentionAction { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof PsiClass) { - moveClass(project, editor, file, (PsiClass)value); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof PsiClass) { + moveClass(project, editor, file, (PsiClass)value); } }).createPopup().showInBestPositionFor(editor); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/OrderEntryFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/OrderEntryFix.java index cdd8e6814326..f40d7ebd476f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/OrderEntryFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/OrderEntryFix.java @@ -190,14 +190,11 @@ public abstract class OrderEntryFix implements IntentionAction, LocalQuickFix { @Nullable @NonNls final String className) { final Project project = currentModule.getProject(); if (editor != null && reference != null && className != null) { - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - GlobalSearchScope scope = GlobalSearchScope.moduleWithLibrariesScope(currentModule); - PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(className, scope); - if (aClass != null) { - new AddImportAction(project, reference, editor, aClass).execute(); - } + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { + GlobalSearchScope scope = GlobalSearchScope.moduleWithLibrariesScope(currentModule); + PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(className, scope); + if (aClass != null) { + new AddImportAction(project, reference, editor, aClass).execute(); } }); } @@ -217,12 +214,9 @@ public abstract class OrderEntryFix implements IntentionAction, LocalQuickFix { @NotNull public static List refreshAndConvertToUrls(@NotNull List jarPaths) { - return ContainerUtil.map(jarPaths, new Function() { - @Override - public String fun(String path) { - return refreshAndConvertToUrl(path); - } - }); + return ContainerUtil.map(jarPaths, path -> { + return refreshAndConvertToUrl(path); + }); } @NotNull diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java index 8c080beb4a05..b2137620f3f7 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableFix.java @@ -98,15 +98,12 @@ public class RemoveUnusedVariableFix implements IntentionAction { final RemoveUnusedVariableUtil.RemoveMode deleteMode = showSideEffectsWarning(sideEffects, myVariable, editor, canCopeWithSideEffects[0]); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - RemoveUnusedVariableUtil.deleteReferences(myVariable, references, deleteMode); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + RemoveUnusedVariableUtil.deleteReferences(myVariable, references, deleteMode); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SetupJDKFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SetupJDKFix.java index 21742dadca7d..73a01977da28 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SetupJDKFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SetupJDKFix.java @@ -67,13 +67,10 @@ public class SetupJDKFix implements IntentionAction, HighPriorityAction { public void invoke(@NotNull Project project, Editor editor, final PsiFile file) { Sdk projectJdk = ProjectSettingsService.getInstance(project).chooseAndSetSdk(); if (projectJdk == null) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Module module = ModuleUtilCore.findModuleForPsiElement(file); - if (module != null) { - ModuleRootModificationUtil.setSdkInherited(module); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Module module = ModuleUtilCore.findModuleForPsiElement(file); + if (module != null) { + ModuleRootModificationUtil.setSdkInherited(module); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java index b321c52280dd..4385d89ac0fa 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/StaticImportMemberFix.java @@ -89,13 +89,10 @@ public abstract class StaticImportMemberFix implements Inte @Override public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final List methodsToImport = getMembersToImport(false); - if (methodsToImport.isEmpty()) return; - createQuestionAction(methodsToImport, project, editor).execute(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final List methodsToImport = getMembersToImport(false); + if (methodsToImport.isEmpty()) return; + createQuestionAction(methodsToImport, project, editor).execute(); }); } @@ -121,12 +118,7 @@ public abstract class StaticImportMemberFix implements Inte CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY) && (ApplicationManager.getApplication().isUnitTestMode() || DaemonListeners.canChangeFileSilently(psiFile)) && !LaterInvocator.isInModalContext()) { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - action.execute(); - } - }); + CommandProcessor.getInstance().runUndoTransparentAction(() -> action.execute()); return ImportClassFixBase.Result.CLASS_AUTO_IMPORTED; } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java index 25f7927aad06..39bcce5b0833 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java @@ -134,11 +134,8 @@ public class CreateClassOrPackageFix extends LocalQuickFixAndIntentionActionOnPs protected void run(@NotNull Result result) throws Throwable { final PsiDirectory directory = chooseDirectory(project, file); if (directory == null) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - doCreate(directory, startElement); - } + ApplicationManager.getApplication().runWriteAction(() -> { + doCreate(directory, startElement); }); } }.execute(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/RedundantLambdaParameterTypeIntention.java b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/RedundantLambdaParameterTypeIntention.java index 2a43212b535e..3f8b378ef813 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/RedundantLambdaParameterTypeIntention.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/RedundantLambdaParameterTypeIntention.java @@ -75,11 +75,8 @@ public class RedundantLambdaParameterTypeIntention extends PsiElementBaseIntenti final PsiExpression[] arguments = ((PsiExpressionList)lambdaParent).getExpressions(); final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); arguments[idx] = javaPsiFacade.getElementFactory().createExpressionFromText( - "(" + StringUtil.join(expression.getParameterList().getParameters(), new Function() { - @Override - public String fun(PsiParameter parameter) { - return parameter.getName(); - } + "(" + StringUtil.join(expression.getParameterList().getParameters(), parameter -> { + return parameter.getName(); }, ", ") + ") -> {}", expression); final PsiParameter[] methodParams = method.getParameterList().getParameters(); final PsiSubstitutor substitutor = javaPsiFacade.getResolveHelper() @@ -126,11 +123,8 @@ public class RedundantLambdaParameterTypeIntention extends PsiElementBaseIntenti text = parameters[0].getName(); } else { - text = "(" + StringUtil.join(parameters, new Function() { - @Override - public String fun(PsiParameter parameter) { - return parameter.getName(); - } + text = "(" + StringUtil.join(parameters, parameter -> { + return parameter.getName(); }, ", ") + ")"; } final PsiLambdaExpression expression = (PsiLambdaExpression)JavaPsiFacade.getElementFactory(lambdaExpression.getProject()) diff --git a/java/java-impl/src/com/intellij/codeInsight/documentation/JavaDocCommentFixer.java b/java/java-impl/src/com/intellij/codeInsight/documentation/JavaDocCommentFixer.java index 1e89d39d57de..461ab84f71ba 100644 --- a/java/java-impl/src/com/intellij/codeInsight/documentation/JavaDocCommentFixer.java +++ b/java/java-impl/src/com/intellij/codeInsight/documentation/JavaDocCommentFixer.java @@ -66,12 +66,8 @@ public class JavaDocCommentFixer implements DocCommentFixer { */ @NotNull private static final Set CARET_ANCHOR_TAGS = ContainerUtilRt.newHashSet(PARAM_TAG, "@throws", "@return"); - @NotNull private static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(PsiElement e1, PsiElement e2) { - return e2.getTextRange().getEndOffset() - e1.getTextRange().getEndOffset(); - } - }; + @NotNull private static final Comparator COMPARATOR = + (e1, e2) -> e2.getTextRange().getEndOffset() - e1.getTextRange().getEndOffset(); @NotNull private static final String PARAM_TAG_NAME = "param"; diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java index 192a64cf8d29..701e6c83d98d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/CopyPasteReferenceProcessor.java @@ -121,11 +121,8 @@ public abstract class CopyPasteReferenceProcessor exten askReferencesToRestore(project, refs, referenceData); } PsiDocumentManager.getInstance(project).commitAllDocuments(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - restoreReferences(referenceData, refs); - } + ApplicationManager.getApplication().runWriteAction(() -> { + restoreReferences(referenceData, refs); }); } @@ -190,13 +187,10 @@ public abstract class CopyPasteReferenceProcessor exten Object[] selectedObjects = ArrayUtil.toObjectArray(array); Arrays.sort( selectedObjects, - new Comparator() { - @Override - public int compare(Object o1, Object o2) { - String fqName1 = getFQName(o1); - String fqName2 = getFQName(o2); - return fqName1.compareToIgnoreCase(fqName2); - } + (o1, o2) -> { + String fqName1 = getFQName(o1); + String fqName2 = getFQName(o2); + return fqName1.compareToIgnoreCase(fqName2); } ); diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaTypedHandler.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaTypedHandler.java index 6526192a4d5c..0ea5adfab4d7 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaTypedHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaTypedHandler.java @@ -133,12 +133,7 @@ public class JavaTypedHandler extends TypedHandlerDelegate { PsiElement prev = offset > 1 ? file.findElementAt(offset - 1) : null; if (CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET && isRparenth(leaf) && (st instanceof PsiWhileStatement || st instanceof PsiIfStatement) && shouldInsertStatementBody(st, doc, prev)) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - new JavaSmartEnterProcessor().process(project, editor, file); - } - }, "Insert block statement", null); + CommandProcessor.getInstance().executeCommand(project, () -> new JavaSmartEnterProcessor().process(project, editor, file), "Insert block statement", null); return Result.STOP; } diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/CollapseBlockHandler.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/CollapseBlockHandler.java index 9b60f1e49d01..4a39b0738fca 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/CollapseBlockHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/CollapseBlockHandler.java @@ -34,56 +34,53 @@ public class CollapseBlockHandler implements CodeInsightActionHandler { @Override public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - final EditorFoldingInfo info = EditorFoldingInfo.get(editor); - FoldingModelEx model = (FoldingModelEx) editor.getFoldingModel(); - PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 1); - if (!(element instanceof PsiJavaToken) || ((PsiJavaToken) element).getTokenType() != JavaTokenType.RBRACE) { - element = file.findElementAt(editor.getCaretModel().getOffset()); - } - if (element == null) return; - PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class); - FoldRegion previous = null; - FoldRegion myPrevious = null; - while (block != null) { - int start = block.getTextRange().getStartOffset(); - int end = block.getTextRange().getEndOffset(); - FoldRegion existing = FoldingUtil.findFoldRegion(editor, start, end); - if (existing != null) { - if (existing.isExpanded()) { - existing.setExpanded(false); - editor.getCaretModel().moveToOffset(existing.getEndOffset()); - return; - } - previous = existing; - if (info.getPsiElement(existing) == null) myPrevious = existing; - block = PsiTreeUtil.getParentOfType(block, PsiCodeBlock.class); - continue; - } - if (!model.intersectsRegion(start, end)) { - FoldRegion region = model.addFoldRegion(start, end, ourPlaceHolderText); - LOG.assertTrue(region != null); - region.setExpanded(false); - if (myPrevious != null && info.getPsiElement(region) == null) { - info.removeRegion(myPrevious); - model.removeFoldRegion(myPrevious); - } - int offset = block.getTextRange().getEndOffset() < editor.getCaretModel().getOffset() ? - start : end; - editor.getCaretModel().moveToOffset(offset); + editor.getFoldingModel().runBatchFoldingOperation(() -> { + final EditorFoldingInfo info = EditorFoldingInfo.get(editor); + FoldingModelEx model = (FoldingModelEx) editor.getFoldingModel(); + PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 1); + if (!(element instanceof PsiJavaToken) || ((PsiJavaToken) element).getTokenType() != JavaTokenType.RBRACE) { + element = file.findElementAt(editor.getCaretModel().getOffset()); + } + if (element == null) return; + PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class); + FoldRegion previous = null; + FoldRegion myPrevious = null; + while (block != null) { + int start = block.getTextRange().getStartOffset(); + int end = block.getTextRange().getEndOffset(); + FoldRegion existing = FoldingUtil.findFoldRegion(editor, start, end); + if (existing != null) { + if (existing.isExpanded()) { + existing.setExpanded(false); + editor.getCaretModel().moveToOffset(existing.getEndOffset()); return; - } else break; + } + previous = existing; + if (info.getPsiElement(existing) == null) myPrevious = existing; + block = PsiTreeUtil.getParentOfType(block, PsiCodeBlock.class); + continue; } - if (previous != null) { - previous.setExpanded(false); - if (myPrevious != null) { + if (!model.intersectsRegion(start, end)) { + FoldRegion region = model.addFoldRegion(start, end, ourPlaceHolderText); + LOG.assertTrue(region != null); + region.setExpanded(false); + if (myPrevious != null && info.getPsiElement(region) == null) { info.removeRegion(myPrevious); model.removeFoldRegion(myPrevious); } - editor.getCaretModel().moveToOffset(previous.getEndOffset()); + int offset = block.getTextRange().getEndOffset() < editor.getCaretModel().getOffset() ? + start : end; + editor.getCaretModel().moveToOffset(offset); + return; + } else break; + } + if (previous != null) { + previous.setExpanded(false); + if (myPrevious != null) { + info.removeRegion(myPrevious); + model.removeFoldRegion(myPrevious); } + editor.getCaretModel().moveToOffset(previous.getEndOffset()); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateAccessorProviderRegistrar.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateAccessorProviderRegistrar.java index e6183c0978e8..f1e63fd84d53 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateAccessorProviderRegistrar.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateAccessorProviderRegistrar.java @@ -47,11 +47,8 @@ public class GenerateAccessorProviderRegistrar { } protected synchronized static List getEncapsulatableClassMembers(final PsiClass psiClass) { - return ContainerUtil.concat(ourProviders, new Function>, Collection>() { - @Override - public Collection fun(NotNullFunction> s) { - return s.fun(psiClass); - } + return ContainerUtil.concat(ourProviders, s -> { + return s.fun(psiClass); }); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java index 8a0d43451563..d75058de9430 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java @@ -95,11 +95,8 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase { } else { final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY); - PsiMethodMember[] constructors = ContainerUtil.map2Array(array, PsiMethodMember.class, new Function() { - @Override - public PsiMethodMember fun(final PsiMethod s) { - return new PsiMethodMember(s, substitutor); - } + PsiMethodMember[] constructors = ContainerUtil.map2Array(array, PsiMethodMember.class, s -> { + return new PsiMethodMember(s, substitutor); }); MemberChooser chooser = new MemberChooser(constructors, false, true, project); chooser.setTitle(CodeInsightBundle.message("generate.constructor.super.constructor.chooser.title")); @@ -299,11 +296,8 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase { generator.generateSuperCallIfNeeded(buffer, baseConstructor.getParameterList().getParameters()); } final PsiParameter[] parameters = fieldParams.toArray(new PsiParameter[fieldParams.size()]); - final List existingNames = ContainerUtil.map(dummyConstructor.getParameterList().getParameters(), new Function() { - @Override - public String fun(PsiParameter parameter) { - return parameter.getName(); - } + final List existingNames = ContainerUtil.map(dummyConstructor.getParameterList().getParameters(), parameter -> { + return parameter.getName(); }); if (generator instanceof ConstructorBodyGeneratorEx) { ((ConstructorBodyGeneratorEx)generator).generateFieldInitialization(buffer, fields, parameters, existingNames); diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java index 30071b845e9d..63e0171928c6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java @@ -69,34 +69,31 @@ public class GenerateDelegateHandler implements LanguageCodeInsightActionHandler if (candidates == null || candidates.length == 0) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - int offset = editor.getCaretModel().getOffset(); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + int offset = editor.getCaretModel().getOffset(); - List> prototypes = new ArrayList>(candidates.length); - for (PsiMethodMember candidate : candidates) { - prototypes.add(generateDelegatePrototype(candidate, target.getElement())); - } - - List> results = GenerateMembersUtil.insertMembersAtOffset(file, offset, prototypes); - - if (!results.isEmpty()) { - PsiMethod firstMethod = results.get(0).getPsiMember(); - final PsiCodeBlock block = firstMethod.getBody(); - assert block != null; - final PsiElement first = block.getFirstBodyElement(); - assert first != null; - editor.getCaretModel().moveToOffset(first.getTextRange().getStartOffset()); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - editor.getSelectionModel().removeSelection(); - } + List> prototypes = new ArrayList>(candidates.length); + for (PsiMethodMember candidate : candidates) { + prototypes.add(generateDelegatePrototype(candidate, target.getElement())); } - catch (IncorrectOperationException e) { - LOG.error(e); + + List> results = GenerateMembersUtil.insertMembersAtOffset(file, offset, prototypes); + + if (!results.isEmpty()) { + PsiMethod firstMethod = results.get(0).getPsiMember(); + final PsiCodeBlock block = firstMethod.getBody(); + assert block != null; + final PsiElement first = block.getFirstBodyElement(); + assert first != null; + editor.getCaretModel().moveToOffset(first.getTextRange().getStartOffset()); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + editor.getSelectionModel().removeSelection(); } } + catch (IncorrectOperationException e) { + LOG.error(e); + } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java index efce7063dac8..87c21210e2de 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java @@ -54,19 +54,15 @@ public abstract class GenerateGetterSetterHandlerBase extends GenerateMembersHan private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateGetterSetterHandlerBase"); static { - GenerateAccessorProviderRegistrar.registerProvider(new NotNullFunction>() { - @Override - @NotNull - public Collection fun(PsiClass s) { - if (s.getLanguage() != StdLanguages.JAVA) return Collections.emptyList(); - final List result = new ArrayList(); - for (PsiField field : s.getFields()) { - if (!(field instanceof PsiEnumConstant)) { - result.add(new PsiFieldMember(field)); - } + GenerateAccessorProviderRegistrar.registerProvider(s -> { + if (s.getLanguage() != StdLanguages.JAVA) return Collections.emptyList(); + final List result = new ArrayList(); + for (PsiField field : s.getFields()) { + if (!(field instanceof PsiEnumConstant)) { + result.add(new PsiFieldMember(field)); } - return result; } + return result; }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java index 1f9e4a55ad83..3a72d31e6b65 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java @@ -84,25 +84,19 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan final ClassMember[] members = chooseOriginalMembers(aClass, project, editor); if (members == null) return; - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - final int offset = editor.getCaretModel().getOffset(); - try { - doGenerate(project, editor, aClass, members); - } - catch (GenerateCodeException e) { - final String message = e.getMessage(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!editor.isDisposed()) { - editor.getCaretModel().moveToOffset(offset); - HintManager.getInstance().showErrorHint(editor, message); - } - } - }, project.getDisposed()); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + final int offset = editor.getCaretModel().getOffset(); + try { + doGenerate(project, editor, aClass, members); + } + catch (GenerateCodeException e) { + final String message = e.getMessage(); + ApplicationManager.getApplication().invokeLater(() -> { + if (!editor.isDisposed()) { + editor.getCaretModel().moveToOffset(offset); + HintManager.getInstance().showErrorHint(editor, message); + } + }, project.getDisposed()); } }); } @@ -202,17 +196,12 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan @Override public void templateFinished(Template template, boolean brokenOff) { if (index + 1 < templates.size()){ - ApplicationManager.getApplication().invokeLater(new Runnable() { + ApplicationManager.getApplication().invokeLater(() -> new WriteCommandAction(myProject) { @Override - public void run() { - new WriteCommandAction(myProject) { - @Override - protected void run(@NotNull Result result) throws Throwable { - runTemplates(myProject, editor, templates, index + 1); - } - }.execute(); + protected void run(@NotNull Result result) throws Throwable { + runTemplates(myProject, editor, templates, index + 1); } - }); + }.execute()); } } }); diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideImplementMemberChooser.java b/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideImplementMemberChooser.java index a6a36efdd3b0..6b705ef8bb82 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideImplementMemberChooser.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideImplementMemberChooser.java @@ -185,11 +185,8 @@ public class JavaOverrideImplementMemberChooser extends MemberChooser candidates) { - return ContainerUtil.map2Array(candidates, PsiMethodMember.class, new Function() { - @Override - public PsiMethodMember fun(final CandidateInfo s) { - return new PsiMethodMember(s); - } + return ContainerUtil.map2Array(candidates, PsiMethodMember.class, s -> { + return new PsiMethodMember(s); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java index 2ac11993dc07..0858f5d9176d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java @@ -170,12 +170,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { final PsiMethod method, final boolean toCopyJavaDoc, final boolean insertOverrideIfPossible) { - return new Consumer() { - @Override - public void consume(PsiMethod result) { - decorateMethod(aClass, method, toCopyJavaDoc, insertOverrideIfPossible, result); - } - }; + return result -> decorateMethod(aClass, method, toCopyJavaDoc, insertOverrideIfPossible, result); } private static PsiMethod decorateMethod(PsiClass aClass, @@ -286,11 +281,8 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { boolean toCopyJavaDoc, boolean toInsertAtOverride) throws IncorrectOperationException { - List candidateInfos = ContainerUtil.map2List(candidates, new Function() { - @Override - public CandidateInfo fun(final PsiMethodMember s) { - return new CandidateInfo(s.getElement(), s.getSubstitutor()); - } + List candidateInfos = ContainerUtil.map2List(candidates, s -> { + return new CandidateInfo(s.getElement(), s.getSubstitutor()); }); final List methods = overrideOrImplementMethodCandidates(aClass, candidateInfos, toCopyJavaDoc, toInsertAtOverride); return convert2GenerationInfos(methods); @@ -310,11 +302,8 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { } public static List> convert2GenerationInfos(final Collection methods) { - return ContainerUtil.map2List(methods, new Function>() { - @Override - public PsiGenerationInfo fun(final PsiMethod s) { - return createGenerationInfo(s); - } + return ContainerUtil.map2List(methods, s -> { + return createGenerationInfo(s); }); } @@ -403,13 +392,9 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { m = factory.createMethodFromText(methodText, originalMethod); } catch (IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(CodeInsightBundle.message("override.implement.broken.file.template.message"), - CodeInsightBundle.message("override.implement.broken.file.template.title")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(CodeInsightBundle.message("override.implement.broken.file.template.message"), + CodeInsightBundle.message("override.implement.broken.file.template.title"))); return; } PsiCodeBlock oldBody = result.getBody(); @@ -525,12 +510,9 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { chooser.close(DialogWrapper.CANCEL_EXIT_CODE); // invoke later in order to close previous modal dialog - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final CodeInsightActionHandler handler = toImplement ? new OverrideMethodsHandler(): new ImplementMethodsHandler(); - handler.invoke(project, editor, aClass.getContainingFile()); - } + ApplicationManager.getApplication().invokeLater(() -> { + final CodeInsightActionHandler handler = toImplement ? new OverrideMethodsHandler(): new ImplementMethodsHandler(); + handler.invoke(project, editor, aClass.getContainingFile()); }); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/PsiMethodWithOverridingPercentMember.java b/java/java-impl/src/com/intellij/codeInsight/generation/PsiMethodWithOverridingPercentMember.java index 47f63a8acf19..6dfe4ca235dd 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/PsiMethodWithOverridingPercentMember.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/PsiMethodWithOverridingPercentMember.java @@ -53,26 +53,23 @@ public class PsiMethodWithOverridingPercentMember extends PsiMethodMember { return myOverridingPercent; } - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(PsiMethodMember e1, PsiMethodMember e2) { - if (!(e1 instanceof PsiMethodWithOverridingPercentMember)) { - if (!(e2 instanceof PsiMethodWithOverridingPercentMember)) { - return e1.equals(e2) ? 0 : -1; - } else { - return -1; - } - } - - + public static final Comparator COMPARATOR = (e1, e2) -> { + if (!(e1 instanceof PsiMethodWithOverridingPercentMember)) { if (!(e2 instanceof PsiMethodWithOverridingPercentMember)) { - return 1; + return e1.equals(e2) ? 0 : -1; + } else { + return -1; } - int sub = - ((PsiMethodWithOverridingPercentMember)e2).myOverridingPercent - ((PsiMethodWithOverridingPercentMember)e1).myOverridingPercent; - if (sub != 0) return sub; - return String.CASE_INSENSITIVE_ORDER.compare(e1.getText(), e2.getText()); } + + + if (!(e2 instanceof PsiMethodWithOverridingPercentMember)) { + return 1; + } + int sub = + ((PsiMethodWithOverridingPercentMember)e2).myOverridingPercent - ((PsiMethodWithOverridingPercentMember)e1).myOverridingPercent; + if (sub != 0) return sub; + return String.CASE_INSENSITIVE_ORDER.compare(e1.getText(), e2.getText()); }; @NotNull diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java index 9ae19918b5c2..f897a8bfefb0 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java @@ -100,31 +100,25 @@ public class HighlightImportedElementsHandler extends HighlightUsagesHandlerBase final ListCellRenderer renderer = new NavigationItemListCellRenderer(); list.setCellRenderer(renderer); final PopupChooserBuilder builder = new PopupChooserBuilder(list); - builder.setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - if (o instanceof PsiMember) { - final PsiMember member = (PsiMember)o; - return member.getName(); - } - return o.toString(); + builder.setFilteringEnabled(o -> { + if (o instanceof PsiMember) { + final PsiMember member = (PsiMember)o; + return member.getName(); } + return o.toString(); }); if (myImportStatic) { builder.setTitle(CodeInsightBundle.message("highlight.imported.members.chooser.title")); } else { builder.setTitle(CodeInsightBundle.message("highlight.imported.classes.chooser.title")); } - builder.setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final int index= list.getSelectedIndex(); - if (index == 0) { - selectionConsumer.consume(targets); - } - else { - selectionConsumer.consume(Collections.singletonList(targets.get(index - 1))); - } + builder.setItemChoosenCallback(() -> { + final int index= list.getSelectedIndex(); + if (index == 0) { + selectionConsumer.consume(targets); + } + else { + selectionConsumer.consume(Collections.singletonList(targets.get(index - 1))); } }); final JBPopup popup = builder.createPopup(); diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java index 52fbd2397d7b..d7b001b5d122 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java @@ -139,12 +139,7 @@ public class HighlightSuppressedWarningsHandler extends HighlightUsagesHandlerBa } ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted(); ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - Runnable inspect = new Runnable() { - @Override - public void run() { - pass.doInspectInBatch(context, managerEx, toolsCopy); - } - }; + Runnable inspect = () -> pass.doInspectInBatch(context, managerEx, toolsCopy); if (indicator == null) { ProgressManager.getInstance().executeProcessUnderProgress(inspect, new ProgressIndicatorBase()); } diff --git a/java/java-impl/src/com/intellij/codeInsight/hint/actions/ShowSiblingsAction.java b/java/java-impl/src/com/intellij/codeInsight/hint/actions/ShowSiblingsAction.java index c464205f1b25..2993d34ed5a6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/hint/actions/ShowSiblingsAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/hint/actions/ShowSiblingsAction.java @@ -63,12 +63,8 @@ public class ShowSiblingsAction extends ShowImplementationsAction { final boolean isMethod = superElements[0] instanceof PsiMethod; NavigatablePsiElement[] navigatablePsiElements = ContainerUtil.findAllAsArray(superElements, NavigatablePsiElement.class); final JBPopup popup = PsiElementListNavigator.navigateOrCreatePopup(navigatablePsiElements, "Choose super " + (isMethod ? "method" : "class or interface"), "Super " + (isMethod ? "methods" : "classes/interfaces"), - isMethod ? new MethodCellRenderer(false) : new PsiClassListCellRenderer(), null, new Consumer() { - @Override - public void consume(Object[] objects) { - showSiblings(invokedByShortcut, project, editor, file, editor != null, (PsiElement)objects[0]); - } - }); + isMethod ? new MethodCellRenderer(false) : new PsiClassListCellRenderer(), null, + objects -> showSiblings(invokedByShortcut, project, editor, file, editor != null, (PsiElement)objects[0])); if (popup != null) { if (editor != null) { popup.showInBestPositionFor(editor); diff --git a/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/ReferenceParameterInfoHandler.java b/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/ReferenceParameterInfoHandler.java index b1f882c6214d..07649f26b5ec 100644 --- a/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/ReferenceParameterInfoHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/ReferenceParameterInfoHandler.java @@ -106,11 +106,8 @@ public class ReferenceParameterInfoHandler implements ParameterInfoHandler() { - @Override - public String fun(final PsiClassType t) { - return t.getPresentableText(); - } + t -> { + return t.getPresentableText(); }, ", ")); context.setupUIComponentPresentation(buffer.toString(), 0, highlightEndOffset, false, false, false, diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/BindFieldsFromParametersAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/BindFieldsFromParametersAction.java index 380d185e649b..e4679760e27d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/BindFieldsFromParametersAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/BindFieldsFromParametersAction.java @@ -210,13 +210,8 @@ public class BindFieldsFromParametersAction extends BaseIntentionAction implemen @NotNull private static ParameterClassMember[] sortByParameterIndex(@NotNull ParameterClassMember[] members, @NotNull PsiMethod method) { final PsiParameterList parameterList = method.getParameterList(); - Arrays.sort(members, new Comparator() { - @Override - public int compare(ParameterClassMember o1, ParameterClassMember o2) { - return parameterList.getParameterIndex(o1.getParameter()) - - parameterList.getParameterIndex(o2.getParameter()); - } - }); + Arrays.sort(members, (o1, o2) -> parameterList.getParameterIndex(o1.getParameter()) - + parameterList.getParameterIndex(o2.getParameter())); return members; } @@ -301,23 +296,20 @@ public class BindFieldsFromParametersAction extends BaseIntentionAction implemen final String fieldName = usedNames.add(name) ? name : JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName(name, parameter, true); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - FieldFromParameterUtils.createFieldAndAddAssignment( - project, - targetClass, - method, - parameter, - type, - fieldName, - isMethodStatic, - isFinal); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + FieldFromParameterUtils.createFieldAndAddAssignment( + project, + targetClass, + method, + parameter, + type, + fieldName, + isMethodStatic, + isFinal); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CopyAbstractMethodImplementationHandler.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CopyAbstractMethodImplementationHandler.java index 32aa6fcd37d2..ccb306c80985 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CopyAbstractMethodImplementationHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CopyAbstractMethodImplementationHandler.java @@ -65,17 +65,9 @@ public class CopyAbstractMethodImplementationHandler { } public void invoke() { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - searchExistingImplementations(); - } - }); - } - }, CodeInsightBundle.message("searching.for.implementations"), false, myProject); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + searchExistingImplementations(); + }), CodeInsightBundle.message("searching.for.implementations"), false, myProject); if (mySourceMethods.isEmpty()) { Messages.showErrorDialog(myProject, CodeInsightBundle.message("copy.abstract.method.no.existing.implementations.found"), CodeInsightBundle.message("copy.abstract.method.title")); @@ -85,25 +77,19 @@ public class CopyAbstractMethodImplementationHandler { copyImplementation(mySourceMethods.get(0)); } else { - Collections.sort(mySourceMethods, new Comparator() { - @Override - public int compare(final PsiMethod o1, final PsiMethod o2) { - PsiClass c1 = o1.getContainingClass(); - PsiClass c2 = o2.getContainingClass(); - return Comparing.compare(c1.getName(), c2.getName()); - } + Collections.sort(mySourceMethods, (o1, o2) -> { + PsiClass c1 = o1.getContainingClass(); + PsiClass c2 = o2.getContainingClass(); + return Comparing.compare(c1.getName(), c2.getName()); }); final PsiMethod[] methodArray = mySourceMethods.toArray(new PsiMethod[mySourceMethods.size()]); final JList list = new JBList(methodArray); list.setCellRenderer(new MethodCellRenderer(true)); - final Runnable runnable = new Runnable() { - @Override - public void run() { - int index = list.getSelectedIndex(); - if (index < 0) return; - PsiMethod element = (PsiMethod)list.getSelectedValue(); - copyImplementation(element); - } + final Runnable runnable = () -> { + int index = list.getSelectedIndex(); + if (index < 0) return; + PsiMethod element = (PsiMethod)list.getSelectedValue(); + copyImplementation(element); }; new PopupChooserBuilder(list) .setTitle(CodeInsightBundle.message("copy.abstract.method.popup.title")) diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java index 53c55ccd6b5a..ab7661750498 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateClassDialog.java @@ -240,28 +240,25 @@ public class CreateClassDialog extends DialogWrapper { final String packageName = getPackageName(); final String[] errorString = new String[1]; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - try { - final PackageWrapper targetPackage = new PackageWrapper(PsiManager.getInstance(myProject), packageName); - final MoveDestination destination = myDestinationCB.selectDirectory(targetPackage, false); - if (destination == null) return; - myTargetDirectory = ApplicationManager.getApplication().runWriteAction(new Computable() { - @Override - public PsiDirectory compute() { - return destination.getTargetDirectory(getBaseDir(packageName)); - } - }); - if (myTargetDirectory == null) { - errorString[0] = ""; // message already reported by PackageUtil - return; + CommandProcessor.getInstance().executeCommand(myProject, () -> { + try { + final PackageWrapper targetPackage = new PackageWrapper(PsiManager.getInstance(myProject), packageName); + final MoveDestination destination = myDestinationCB.selectDirectory(targetPackage, false); + if (destination == null) return; + myTargetDirectory = ApplicationManager.getApplication().runWriteAction(new Computable() { + @Override + public PsiDirectory compute() { + return destination.getTargetDirectory(getBaseDir(packageName)); } - errorString[0] = RefactoringMessageUtil.checkCanCreateClass(myTargetDirectory, getClassName()); - } - catch (IncorrectOperationException e) { - errorString[0] = e.getMessage(); + }); + if (myTargetDirectory == null) { + errorString[0] = ""; // message already reported by PackageUtil + return; } + errorString[0] = RefactoringMessageUtil.checkCanCreateClass(myTargetDirectory, getClassName()); + } + catch (IncorrectOperationException e) { + errorString[0] = e.getMessage(); } }, CodeInsightBundle.message("create.directory.command"), null); diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateFieldFromParameterActionBase.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateFieldFromParameterActionBase.java index e0a0037fb6b4..4b102680ecfc 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateFieldFromParameterActionBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateFieldFromParameterActionBase.java @@ -125,15 +125,12 @@ public abstract class CreateFieldFromParameterActionBase extends BaseIntentionAc final boolean isFinal = isFinalToCalc; final String fieldName = fieldNameToCalc; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - performRefactoring(project, targetClass, method, myParameter, type, fieldName, isMethodStatic, isFinal); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + performRefactoring(project, targetClass, method, myParameter, type, fieldName, isMethodStatic, isFinal); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSubclassAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSubclassAction.java index ea264d391819..81b4a30dbf89 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSubclassAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/CreateSubclassAction.java @@ -206,14 +206,10 @@ public class CreateSubclassAction extends BaseIntentionAction { targetClass[0] = JavaDirectoryService.getInstance().createClass(targetDirectory, className); } catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(project, CodeInsightBundle.message("intention.error.cannot.create.class.message", className) + - "\n"+e.getLocalizedMessage(), - CodeInsightBundle.message("intention.error.cannot.create.class.title")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(project, CodeInsightBundle.message("intention.error.cannot.create.class.message", className) + + "\n" + e.getLocalizedMessage(), + CodeInsightBundle.message("intention.error.cannot.create.class.title"))); return; } startTemplate(oldTypeParameterList, project, psiClass, targetClass[0], false); diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java index 41b2e6cf456a..0086d270d826 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java @@ -68,39 +68,31 @@ public class ImplementAbstractMethodHandler { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); final PsiElement[][] result = new PsiElement[1][]; - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiClass psiClass = myMethod.getContainingClass(); - if (!psiClass.isValid()) return; - if (!psiClass.isEnum()) { - result[0] = getClassImplementations(psiClass); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass psiClass = myMethod.getContainingClass(); + if (!psiClass.isValid()) return; + if (!psiClass.isEnum()) { + result[0] = getClassImplementations(psiClass); + } + else { + final List enumConstants = new ArrayList(); + for (PsiField field : psiClass.getFields()) { + if (field instanceof PsiEnumConstant) { + final PsiEnumConstantInitializer initializingClass = ((PsiEnumConstant)field).getInitializingClass(); + if (initializingClass != null) { + PsiMethod method = initializingClass.findMethodBySignature(myMethod, true); + if (method == null || !method.getContainingClass().equals(initializingClass)) { + enumConstants.add(initializingClass); + } } else { - final List enumConstants = new ArrayList(); - for (PsiField field : psiClass.getFields()) { - if (field instanceof PsiEnumConstant) { - final PsiEnumConstantInitializer initializingClass = ((PsiEnumConstant)field).getInitializingClass(); - if (initializingClass != null) { - PsiMethod method = initializingClass.findMethodBySignature(myMethod, true); - if (method == null || !method.getContainingClass().equals(initializingClass)) { - enumConstants.add(initializingClass); - } - } - else { - enumConstants.add(field); - } - } - } - result[0] = PsiUtilCore.toPsiElementArray(enumConstants); + enumConstants.add(field); } } - }); + } + result[0] = PsiUtilCore.toPsiElementArray(enumConstants); } - }, CodeInsightBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"), true, myProject); + }), CodeInsightBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"), true, myProject); if (result[0] == null) return; @@ -121,13 +113,10 @@ public class ImplementAbstractMethodHandler { elementListCellRenderer.sort(result[0]); myList = new JBList(result[0]); myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - final Runnable runnable = new Runnable(){ - @Override - public void run() { - int index = myList.getSelectedIndex(); - if (index < 0) return; - implementInClass(myList.getSelectedValues()); - } + final Runnable runnable = () -> { + int index = myList.getSelectedIndex(); + if (index < 0) return; + implementInClass(myList.getSelectedValues()); }; myList.setCellRenderer(elementListCellRenderer); final PopupChooserBuilder builder = new PopupChooserBuilder(myList); @@ -144,38 +133,32 @@ public class ImplementAbstractMethodHandler { for (Object o : selection) { if (!((PsiElement)o).isValid()) return; } - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final LinkedHashSet classes = new LinkedHashSet(); - for (final Object o : selection) { - if (o instanceof PsiEnumConstant) { - classes.add(ApplicationManager.getApplication().runWriteAction(new Computable(){ - @Override - public PsiClass compute() { - return ((PsiEnumConstant) o).getOrCreateInitializingClass(); - } - })); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final LinkedHashSet classes = new LinkedHashSet(); + for (final Object o : selection) { + if (o instanceof PsiEnumConstant) { + classes.add(ApplicationManager.getApplication().runWriteAction(new Computable(){ + @Override + public PsiClass compute() { + return ((PsiEnumConstant) o).getOrCreateInitializingClass(); + } + })); + } + else { + classes.add((PsiClass)o); + } + } + if (!FileModificationService.getInstance().preparePsiElementsForWrite(classes)) return; + ApplicationManager.getApplication().runWriteAction(() -> { + for (PsiClass psiClass : classes) { + try { + OverrideImplementUtil.overrideOrImplement(psiClass, myMethod); } - else { - classes.add((PsiClass)o); + catch (IncorrectOperationException e) { + LOG.error(e); } } - if (!FileModificationService.getInstance().preparePsiElementsForWrite(classes)) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (PsiClass psiClass : classes) { - try { - OverrideImplementUtil.overrideOrImplement(psiClass, myMethod); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - } - }); - } + }); }, CodeInsightBundle.message("intention.implement.abstract.method.command.name"), null); } @@ -203,16 +186,13 @@ public class ImplementAbstractMethodHandler { void sort(PsiElement[] result) { final Comparator comparator = myRenderer.getComparator(); - Arrays.sort(result, new Comparator() { - @Override - public int compare(PsiElement o1, PsiElement o2) { - if (o1 instanceof PsiEnumConstant && o2 instanceof PsiEnumConstant) { - return ((PsiEnumConstant)o1).getName().compareTo(((PsiEnumConstant)o2).getName()); - } - if (o1 instanceof PsiEnumConstant) return -1; - if (o2 instanceof PsiEnumConstant) return 1; - return comparator.compare((PsiClass)o1, (PsiClass)o2); + Arrays.sort(result, (o1, o2) -> { + if (o1 instanceof PsiEnumConstant && o2 instanceof PsiEnumConstant) { + return ((PsiEnumConstant)o1).getName().compareTo(((PsiEnumConstant)o2).getName()); } + if (o1 instanceof PsiEnumConstant) return -1; + if (o2 instanceof PsiEnumConstant) return 1; + return comparator.compare((PsiClass)o1, (PsiClass)o2); }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java index a1ae33516673..295098fcefa7 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java @@ -641,12 +641,7 @@ public class QuickFixFactoryImpl extends QuickFixFactory { @Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { - invokeOnTheFlyImportOptimizer(new Runnable() { - @Override - public void run() { - fix.invoke(project, editor, file); - } - }, file); + invokeOnTheFlyImportOptimizer(() -> fix.invoke(project, editor, file), file); } @Override @@ -730,24 +725,21 @@ public class QuickFixFactoryImpl extends QuickFixFactory { final Document document = PsiDocumentManager.getInstance(project).getDocument(file); if (document == null) return; final long stamp = document.getModificationStamp(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed() || document.getModificationStamp() != stamp) return; - //no need to optimize imports on the fly during undo/redo - final UndoManager undoManager = UndoManager.getInstance(project); - if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return; - PsiDocumentManager.getInstance(project).commitAllDocuments(); - String beforeText = file.getText(); - final long oldStamp = document.getModificationStamp(); - DocumentUtil.writeInRunUndoTransparentAction(runnable); - if (oldStamp != document.getModificationStamp()) { - String afterText = file.getText(); - if (Comparing.strEqual(beforeText, afterText)) { - LOG.error( - LogMessageEx.createEvent("Import optimizer hasn't optimized any imports", file.getViewProvider().getVirtualFile().getPath(), - AttachmentFactory.createAttachment(file.getViewProvider().getVirtualFile()))); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed() || document.getModificationStamp() != stamp) return; + //no need to optimize imports on the fly during undo/redo + final UndoManager undoManager = UndoManager.getInstance(project); + if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return; + PsiDocumentManager.getInstance(project).commitAllDocuments(); + String beforeText = file.getText(); + final long oldStamp = document.getModificationStamp(); + DocumentUtil.writeInRunUndoTransparentAction(runnable); + if (oldStamp != document.getModificationStamp()) { + String afterText = file.getText(); + if (Comparing.strEqual(beforeText, afterText)) { + LOG.error( + LogMessageEx.createEvent("Import optimizer hasn't optimized any imports", file.getViewProvider().getVirtualFile().getPath(), + AttachmentFactory.createAttachment(file.getViewProvider().getVirtualFile()))); } } }); @@ -806,14 +798,11 @@ public class QuickFixFactoryImpl extends QuickFixFactory { PsiImportList importList = ((PsiJavaFile)file).getImportList(); final TextRange importsRange = importList == null ? TextRange.EMPTY_RANGE : importList.getTextRange(); boolean hasErrorsExceptUnresolvedImports = !DaemonCodeAnalyzerEx - .processHighlights(document, file.getProject(), HighlightSeverity.ERROR, 0, document.getTextLength(), new Processor() { - @Override - public boolean process(HighlightInfo error) { - int infoStart = error.getActualStartOffset(); - int infoEnd = error.getActualEndOffset(); + .processHighlights(document, file.getProject(), HighlightSeverity.ERROR, 0, document.getTextLength(), error -> { + int infoStart = error.getActualStartOffset(); + int infoEnd = error.getActualEndOffset(); - return importsRange.containsRange(infoStart, infoEnd) && error.type.equals(HighlightInfoType.WRONG_REF); - } + return importsRange.containsRange(infoStart, infoEnd) && error.type.equals(HighlightInfoType.WRONG_REF); }); return hasErrorsExceptUnresolvedImports; diff --git a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 86fdab7daf63..b9cb797331c3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -446,11 +446,8 @@ public class JavaDocInfoGenerator { buffer.append(""); } String errorSection = "

Following external urls were checked:
   " + - StringUtil.join(docURLs, new Function() { - @Override - public String fun(String url) { - return XmlStringUtil.escapeString(url); - } + StringUtil.join(docURLs, url -> { + return XmlStringUtil.escapeString(url); }, "
   ") + "
The documentation for this element is not found. Please add all the needed paths to API docs in " + "Project Settings.

"; diff --git a/java/java-impl/src/com/intellij/codeInsight/template/ExpressionUtil.java b/java/java-impl/src/com/intellij/codeInsight/template/ExpressionUtil.java index 2b4bf11cdfb2..e643a196a841 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/ExpressionUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/ExpressionUtil.java @@ -50,16 +50,13 @@ import org.jetbrains.annotations.Nullable; } else{ final PsiFile fileCopy = (PsiFile)file.copy(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - BlockSupport blockSupport = BlockSupport.getInstance(project); - try{ - blockSupport.reparseRange(fileCopy, offset, offset, "xxx"); - } - catch(IncorrectOperationException e){ - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + BlockSupport blockSupport = BlockSupport.getInstance(project); + try{ + blockSupport.reparseRange(fileCopy, offset, offset, "xxx"); + } + catch(IncorrectOperationException e){ + LOG.error(e); } }); PsiElement identifierCopy = fileCopy.findElementAt(offset); diff --git a/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateUtil.java b/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateUtil.java index 5600ce4623af..f0249949958c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/impl/JavaTemplateUtil.java @@ -140,14 +140,11 @@ public class JavaTemplateUtil { } if (parent instanceof PsiJavaCodeReferenceElement && !((PsiJavaCodeReferenceElement) parent).isQualified()) { final PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) parent; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - ref.bindToElement(aClass); - } catch (IncorrectOperationException e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + ref.bindToElement(aClass); + } catch (IncorrectOperationException e) { + LOG.error(e); } }); } diff --git a/java/java-impl/src/com/intellij/codeInsight/template/macro/GroovyScriptMacro.java b/java/java-impl/src/com/intellij/codeInsight/template/macro/GroovyScriptMacro.java index 096ba92412f5..a0a158cb4e49 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/macro/GroovyScriptMacro.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/macro/GroovyScriptMacro.java @@ -67,11 +67,8 @@ public class GroovyScriptMacro extends Macro { Result paramResult = params[i].calculateResult(context); Object value = null; if (paramResult instanceof ListResult) { - value = ContainerUtil.map2List(((ListResult)paramResult).getComponents(), new Function() { - @Override - public String fun(Result result) { - return result.toString(); - } + value = ContainerUtil.map2List(((ListResult)paramResult).getComponents(), result1 -> { + return result1.toString(); }); } else if (paramResult != null) { value = paramResult.toString(); diff --git a/java/java-impl/src/com/intellij/codeInsight/template/macro/SubtypesMacro.java b/java/java-impl/src/com/intellij/codeInsight/template/macro/SubtypesMacro.java index 5f86cb58b781..a168e5cc07df 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/macro/SubtypesMacro.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/macro/SubtypesMacro.java @@ -69,12 +69,8 @@ public class SubtypesMacro extends Macro { final Set set = new LinkedHashSet(); JavaTemplateUtil.addTypeLookupItem(set, type); - CodeInsightUtil.processSubTypes(type, element, false, PrefixMatcher.ALWAYS_TRUE, new Consumer() { - @Override - public void consume(PsiType psiType) { - JavaTemplateUtil.addTypeLookupItem(set, psiType); - } - }); + CodeInsightUtil.processSubTypes(type, element, false, PrefixMatcher.ALWAYS_TRUE, + psiType -> JavaTemplateUtil.addTypeLookupItem(set, psiType)); return set.toArray(new LookupElement[set.size()]); } return LookupElement.EMPTY_ARRAY; diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java index 3bfacc324d9d..ac4683d8e48a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/JavaPostfixTemplatesUtils.java @@ -244,12 +244,9 @@ public abstract class JavaPostfixTemplatesUtils { @NotNull public static Function getRenderer() { - return new Function() { - @Override - public String fun(PsiElement element) { - assert element instanceof PsiExpression; - return new PsiExpressionTrimRenderer.RenderFunction().fun((PsiExpression)element); - } + return element -> { + assert element instanceof PsiExpression; + return new PsiExpressionTrimRenderer.RenderFunction().fun((PsiExpression)element); }; } diff --git a/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java b/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java index 90dcd38474bd..7e523b53a4a5 100644 --- a/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java @@ -279,12 +279,8 @@ public class CollectionAddAllCanBeReplacedWithConstructorInspection extends Base if (psiExpression instanceof PsiReferenceExpression) { references.add((PsiReferenceExpression)psiExpression); } - return ContainerUtil.mapNotNull(references, new NullableFunction() { - @Nullable - @Override - public PsiElement fun(PsiReferenceExpression expression) { - return expression.resolve(); - } + return ContainerUtil.mapNotNull(references, (NullableFunction)expression1 -> { + return expression1.resolve(); }); } diff --git a/java/java-impl/src/com/intellij/codeInspection/actions/ReplaceImplementsWithStaticImportAction.java b/java/java-impl/src/com/intellij/codeInspection/actions/ReplaceImplementsWithStaticImportAction.java index 0a74489bc056..0d9348c83c39 100644 --- a/java/java-impl/src/com/intellij/codeInspection/actions/ReplaceImplementsWithStaticImportAction.java +++ b/java/java-impl/src/com/intellij/codeInspection/actions/ReplaceImplementsWithStaticImportAction.java @@ -127,117 +127,87 @@ public class ReplaceImplementsWithStaticImportAction extends BaseIntentionAction targetClass = (PsiClass)element; } final Map>> refs = new HashMap>>(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (PsiField field : targetClass.getAllFields()) { - final PsiClass containingClass = field.getContainingClass(); - for (PsiReference reference : ReferencesSearch.search(field)) { - if (reference == null) { - continue; - } - final PsiElement refElement = reference.getElement(); - if (encodeQualifier(containingClass, reference, targetClass)) continue; - final PsiFile psiFile = refElement.getContainingFile(); - if (psiFile instanceof PsiJavaFile) { - Map> references = refs.get(psiFile); - if (references == null) { - references = new HashMap>(); - refs.put(psiFile, references); - } - Set fieldsRefs = references.get(field); - if (fieldsRefs == null) { - fieldsRefs = new HashSet(); - references.put(field, fieldsRefs); - } - fieldsRefs.add(reference); - } - } - } + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + for (PsiField field : targetClass.getAllFields()) { + final PsiClass containingClass = field.getContainingClass(); + for (PsiReference reference : ReferencesSearch.search(field)) { + if (reference == null) { + continue; } - }); + final PsiElement refElement = reference.getElement(); + if (encodeQualifier(containingClass, reference, targetClass)) continue; + final PsiFile psiFile = refElement.getContainingFile(); + if (psiFile instanceof PsiJavaFile) { + Map> references = refs.get(psiFile); + if (references == null) { + references = new HashMap>(); + refs.put(psiFile, references); + } + Set fieldsRefs = references.get(field); + if (fieldsRefs == null) { + fieldsRefs = new HashSet(); + references.put(field, fieldsRefs); + } + fieldsRefs.add(reference); + } + } } - }, FIND_CONSTANT_FIELD_USAGES, true, project)) { + }), FIND_CONSTANT_FIELD_USAGES, true, project)) { return; } final Set refs2Unimplement = new HashSet(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (PsiClass psiClass : DirectClassInheritorsSearch.search(targetClass)) { - PsiFile containingFile = psiClass.getContainingFile(); - if (!refs.containsKey(containingFile)) { - refs.put(containingFile, new HashMap>()); - } - if (collectExtendsImplements(targetClass, psiClass.getExtendsList(), refs2Unimplement)) continue; - collectExtendsImplements(targetClass, psiClass.getImplementsList(), refs2Unimplement); - } - } - }); + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + for (PsiClass psiClass : DirectClassInheritorsSearch.search(targetClass)) { + PsiFile containingFile = psiClass.getContainingFile(); + if (!refs.containsKey(containingFile)) { + refs.put(containingFile, new HashMap>()); + } + if (collectExtendsImplements(targetClass, psiClass.getExtendsList(), refs2Unimplement)) continue; + collectExtendsImplements(targetClass, psiClass.getImplementsList(), refs2Unimplement); } - }, "Find References in Implement/Extends Lists...", true, project)) { + }), "Find References in Implement/Extends Lists...", true, project)) { return; } if (!FileModificationService.getInstance().preparePsiElementsForWrite(refs.keySet())) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (PsiFile psiFile : refs.keySet()) { - final Map> map = refs.get(psiFile); - for (PsiField psiField : map.keySet()) { - final PsiClass containingClass = psiField.getContainingClass(); - final String fieldName = psiField.getName(); - for (PsiReference reference : map.get(psiField)) { - bindReference(psiFile, psiField, containingClass, fieldName, reference, project); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (PsiFile psiFile : refs.keySet()) { + final Map> map = refs.get(psiFile); + for (PsiField psiField : map.keySet()) { + final PsiClass containingClass = psiField.getContainingClass(); + final String fieldName = psiField.getName(); + for (PsiReference reference : map.get(psiField)) { + bindReference(psiFile, psiField, containingClass, fieldName, reference, project); } } + } - for (PsiJavaCodeReferenceElement referenceElement : refs2Unimplement) { - referenceElement.delete(); - } + for (PsiJavaCodeReferenceElement referenceElement : refs2Unimplement) { + referenceElement.delete(); } }); final Map redundant = new HashMap(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){ - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (PsiFile psiFile : refs.keySet()) { - if (psiFile instanceof PsiJavaFile) { - final PsiImportList prepared = codeStyleManager.prepareOptimizeImportsResult((PsiJavaFile)psiFile); - if (prepared != null) { - redundant.put((PsiJavaFile)psiFile, prepared); - } - } - } + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + for (PsiFile psiFile : refs.keySet()) { + if (psiFile instanceof PsiJavaFile) { + final PsiImportList prepared = codeStyleManager.prepareOptimizeImportsResult((PsiJavaFile)psiFile); + if (prepared != null) { + redundant.put((PsiJavaFile)psiFile, prepared); } - }); + } } - }, "Optimize Imports...", true, project)) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (PsiJavaFile file : redundant.keySet()) { - final PsiImportList importList = redundant.get(file); - if (importList != null) { - final PsiImportList list = file.getImportList(); - if (list != null) { - list.replace(importList); - } + }), "Optimize Imports...", true, project)) return; + ApplicationManager.getApplication().runWriteAction(() -> { + for (PsiJavaFile file1 : redundant.keySet()) { + final PsiImportList importList = redundant.get(file1); + if (importList != null) { + final PsiImportList list = file1.getImportList(); + if (list != null) { + list.replace(importList); } } } diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java index b0bb7ba19c66..508cd361f7b7 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java @@ -193,18 +193,11 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta psiElements.add(psiElement); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final Project project = getContext().getProject(); - if (isDisposed() || project.isDisposed()) return; - SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElements), false, new Runnable() { - @Override - public void run() { - removeElements(refElements, project, myToolWrapper); - } - }); - } + ApplicationManager.getApplication().invokeLater(() -> { + final Project project = getContext().getProject(); + if (isDisposed() || project.isDisposed()) return; + SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElements), false, + () -> removeElements(refElements, project, myToolWrapper)); }); return false; //refresh after safe delete dialog is closed @@ -478,13 +471,8 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (myElement != null && myElement.isValid()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - SafeDeleteHandler - .invoke(myElement.getProject(), new PsiElement[]{PsiTreeUtil.getParentOfType(myElement, PsiModifierListOwner.class)}, false); - } - }); + ApplicationManager.getApplication().invokeLater(() -> SafeDeleteHandler + .invoke(myElement.getProject(), new PsiElement[]{PsiTreeUtil.getParentOfType(myElement, PsiModifierListOwner.class)}, false)); } } diff --git a/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/DefaultFileTemplateUsageInspection.java b/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/DefaultFileTemplateUsageInspection.java index 12d7ca386c03..e0927704d563 100644 --- a/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/DefaultFileTemplateUsageInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/DefaultFileTemplateUsageInspection.java @@ -99,20 +99,14 @@ public class DefaultFileTemplateUsageInspection extends BaseJavaLocalInspectionT @Override public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) { final FileTemplateConfigurable configurable = new FileTemplateConfigurable(project); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - configurable.setTemplate(myTemplateToEdit, null); - boolean ok = ShowSettingsUtil.getInstance().editConfigurable(project, configurable); - if (ok) { - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - FileTemplateManager.getInstance(project).saveAllTemplates(); - myReplaceTemplateFix.applyFix(project, descriptor); - } - }); - } + ApplicationManager.getApplication().invokeLater(() -> { + configurable.setTemplate(myTemplateToEdit, null); + boolean ok = ShowSettingsUtil.getInstance().editConfigurable(project, configurable); + if (ok) { + WriteCommandAction.runWriteCommandAction(project, () -> { + FileTemplateManager.getInstance(project).saveAllTemplates(); + myReplaceTemplateFix.applyFix(project, descriptor); + }); } }); } diff --git a/java/java-impl/src/com/intellij/codeInspection/emptyMethod/EmptyMethodInspection.java b/java/java-impl/src/com/intellij/codeInspection/emptyMethod/EmptyMethodInspection.java index 34acba1f3c8f..d344ebc9c2b4 100644 --- a/java/java-impl/src/com/intellij/codeInspection/emptyMethod/EmptyMethodInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/emptyMethod/EmptyMethodInspection.java @@ -138,15 +138,12 @@ public class EmptyMethodInspection extends GlobalJavaBatchInspectionTool { if (message != null) { final ArrayList fixes = new ArrayList(); fixes.add(getFix(processor, needToDeleteHierarchy)); - SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(refMethod.getElement(), new Processor() { - @Override - public boolean process(final String qualifiedName) { - fixes.add(SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix( - QuickFixBundle.message("fix.add.special.annotation.text", qualifiedName), - QuickFixBundle.message("fix.add.special.annotation.family"), - EXCLUDE_ANNOS, qualifiedName, refMethod.getElement())); - return true; - } + SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(refMethod.getElement(), qualifiedName -> { + fixes.add(SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix( + QuickFixBundle.message("fix.add.special.annotation.text", qualifiedName), + QuickFixBundle.message("fix.add.special.annotation.family"), + EXCLUDE_ANNOS, qualifiedName, refMethod.getElement())); + return true; }); final ProblemDescriptor descriptor = manager.createProblemDescriptor(refMethod.getElement().getNavigationElement(), message, false, @@ -328,22 +325,16 @@ public class EmptyMethodInspection extends GlobalJavaBatchInspectionTool { psiElements.add(psiMethod); if (Boolean.valueOf(myHint).booleanValue()) { final Query> query = AllOverridingMethodsSearch.search(psiMethod.getContainingClass()); - query.forEach(new Processor>() { - @Override - public boolean process(final Pair pair) { - if (pair.first == psiMethod) { - psiElements.add(pair.second); - } - return true; + query.forEach(pair -> { + if (pair.first == psiMethod) { + psiElements.add(pair.second); } + return true; }); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElements), false); - } + ApplicationManager.getApplication().invokeLater(() -> { + SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElements), false); }, project.getDisposed()); } } @@ -408,11 +399,8 @@ public class EmptyMethodInspection extends GlobalJavaBatchInspectionTool { } } } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElementsToIgnore), false, refreshViews); - } + ApplicationManager.getApplication().invokeLater(() -> { + SafeDeleteHandler.invoke(project, PsiUtilCore.toPsiElementArray(psiElementsToIgnore), false, refreshViews); }, project.getDisposed()); } } diff --git a/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java b/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java index f4d9be9d3ed1..2e7605cd9dc8 100644 --- a/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java +++ b/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java @@ -359,30 +359,24 @@ public class GlobalJavaInspectionContextImpl extends GlobalJavaInspectionContext private static List getSortedIDs(final Map requests) { final List result = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (SmartPsiElementPointer id : requests.keySet()) { - if (id != null) { - final PsiElement psi = id.getElement(); - if (psi != null) { - result.add(id); - } + ApplicationManager.getApplication().runReadAction(() -> { + for (SmartPsiElementPointer id : requests.keySet()) { + if (id != null) { + final PsiElement psi = id.getElement(); + if (psi != null) { + result.add(id); } } - Collections.sort(result, new Comparator() { - @Override - public int compare(final SmartPsiElementPointer o1, final SmartPsiElementPointer o2) { - PsiElement p1 = o1.getElement(); - PsiElement p2 = o2.getElement(); - final PsiFile psiFile1 = p1 != null ? p1.getContainingFile() : null; - LOG.assertTrue(psiFile1 != null); - final PsiFile psiFile2 = p2 != null ? p2.getContainingFile() : null; - LOG.assertTrue(psiFile2 != null); - return psiFile1.getName().compareTo(psiFile2.getName()); - } - }); } + Collections.sort(result, (o1, o2) -> { + PsiElement p1 = o1.getElement(); + PsiElement p2 = o2.getElement(); + final PsiFile psiFile1 = p1 != null ? p1.getContainingFile() : null; + LOG.assertTrue(psiFile1 != null); + final PsiFile psiFile2 = p2 != null ? p2.getContainingFile() : null; + LOG.assertTrue(psiFile2 != null); + return psiFile1.getName().compareTo(psiFile2.getName()); + }); }); return result; diff --git a/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java b/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java index 25d1294818e9..2b33f2d50c37 100644 --- a/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java +++ b/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java @@ -88,37 +88,32 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); final String defaultNullable = NullableNotNullManager.getInstance(project).getDefaultNullable(); final int[] fileCount = new int[] {0}; - if (!progressManager.runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - scope.accept(new PsiElementVisitor() { - final private Set processed = new HashSet(); + if (!progressManager.runProcessWithProgressSynchronously(() -> scope.accept(new PsiElementVisitor() { + final private Set processed = new HashSet(); - @Override - public void visitFile(PsiFile file) { - fileCount[0]++; - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - if (progressIndicator != null) { - final VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile != null) { - progressIndicator.setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project)); - } - progressIndicator.setText(AnalysisScopeBundle.message("scanning.scope.progress.title")); - } - if (!(file instanceof PsiJavaFile)) return; - final Module module = ModuleUtilCore.findModuleForPsiElement(file); - if (module != null && processed.add(module)) { - if (PsiUtil.getLanguageLevel(file).compareTo(LanguageLevel.JDK_1_5) < 0) { - modulesWithLL.add(module); - } - else if (javaPsiFacade.findClass(defaultNullable, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) == null) { - modulesWithoutAnnotations.add(module); - } - } + @Override + public void visitFile(PsiFile file) { + fileCount[0]++; + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + if (progressIndicator != null) { + final VirtualFile virtualFile = file.getVirtualFile(); + if (virtualFile != null) { + progressIndicator.setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project)); } - }); + progressIndicator.setText(AnalysisScopeBundle.message("scanning.scope.progress.title")); + } + if (!(file instanceof PsiJavaFile)) return; + final Module module = ModuleUtilCore.findModuleForPsiElement(file); + if (module != null && processed.add(module)) { + if (PsiUtil.getLanguageLevel(file).compareTo(LanguageLevel.JDK_1_5) < 0) { + modulesWithLL.add(module); + } + else if (javaPsiFacade.findClass(defaultNullable, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) == null) { + modulesWithoutAnnotations.add(module); + } + } } - }, "Check Applicability...", true, project)) { + }), "Check Applicability...", true, project)) { return; } if (!modulesWithLL.isEmpty()) { @@ -161,12 +156,9 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { "' library with IntelliJ IDEA nullity annotations. Would you like to add the dependenc"; message += (modulesWithoutAnnotations.size() == 1 ? "y" : "ies") + " now?"; if (Messages.showOkCancelDialog(project, message, title, Messages.getErrorIcon()) == Messages.OK) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (Module module : modulesWithoutAnnotations) { - ModuleRootModificationUtil.addDependency(module, annotationsLib); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (Module module : modulesWithoutAnnotations) { + ModuleRootModificationUtil.addDependency(module, annotationsLib); } }); return true; @@ -193,31 +185,26 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { final int fileCount) { final NullityInferrer inferrer = new NullityInferrer(isAnnotateLocalVariables(), project); final PsiManager psiManager = PsiManager.getInstance(project); - final Runnable searchForUsages = new Runnable() { - @Override - public void run() { - scope.accept(new PsiElementVisitor() { - int myFileCount; + final Runnable searchForUsages = () -> scope.accept(new PsiElementVisitor() { + int myFileCount; - @Override - public void visitFile(final PsiFile file) { - myFileCount++; - final VirtualFile virtualFile = file.getVirtualFile(); - final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile); - final Document document = viewProvider == null ? null : viewProvider.getDocument(); - if (document == null || virtualFile.getFileType().isBinary()) return; //do not inspect binary files - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - if (progressIndicator != null) { - progressIndicator.setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project)); - progressIndicator.setFraction(((double)myFileCount) / fileCount); - } - if (file instanceof PsiJavaFile) { - inferrer.collect(file); - } - } - }); + @Override + public void visitFile(final PsiFile file) { + myFileCount++; + final VirtualFile virtualFile = file.getVirtualFile(); + final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile); + final Document document = viewProvider == null ? null : viewProvider.getDocument(); + if (document == null || virtualFile.getFileType().isBinary()) return; //do not inspect binary files + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + if (progressIndicator != null) { + progressIndicator.setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project)); + progressIndicator.setFraction(((double)myFileCount) / fileCount); + } + if (file instanceof PsiJavaFile) { + inferrer.collect(file); + } } - }; + }); if (ApplicationManager.getApplication().isDispatchThread()) { if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(searchForUsages, INFER_NULLITY_ANNOTATIONS, true, project)) { return null; @@ -236,39 +223,36 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { } private static Runnable applyRunnable(final Project project, final Computable computable) { - return new Runnable() { - @Override - public void run() { - final LocalHistoryAction action = LocalHistory.getInstance().startAction(INFER_NULLITY_ANNOTATIONS); - try { - new WriteCommandAction(project, INFER_NULLITY_ANNOTATIONS) { - @Override - protected void run(@NotNull Result result) throws Throwable { - final UsageInfo[] infos = computable.compute(); - if (infos.length > 0) { + return () -> { + final LocalHistoryAction action = LocalHistory.getInstance().startAction(INFER_NULLITY_ANNOTATIONS); + try { + new WriteCommandAction(project, INFER_NULLITY_ANNOTATIONS) { + @Override + protected void run(@NotNull Result result) throws Throwable { + final UsageInfo[] infos = computable.compute(); + if (infos.length > 0) { - final Set elements = new LinkedHashSet(); - for (UsageInfo info : infos) { - final PsiElement element = info.getElement(); - if (element != null) { - ContainerUtil.addIfNotNull(elements, element.getContainingFile()); - } + final Set elements = new LinkedHashSet(); + for (UsageInfo info : infos) { + final PsiElement element = info.getElement(); + if (element != null) { + ContainerUtil.addIfNotNull(elements, element.getContainingFile()); } - if (!FileModificationService.getInstance().preparePsiElementsForWrite(elements)) return; - - final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, INFER_NULLITY_ANNOTATIONS, false); - progressTask.setMinIterationTime(200); - progressTask.setTask(new AnnotateTask(project, progressTask, infos)); - ProgressManager.getInstance().run(progressTask); - } else { - NullityInferrer.nothingFoundMessage(project); } + if (!FileModificationService.getInstance().preparePsiElementsForWrite(elements)) return; + + final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, INFER_NULLITY_ANNOTATIONS, false); + progressTask.setMinIterationTime(200); + progressTask.setTask(new AnnotateTask(project, progressTask, infos)); + ProgressManager.getInstance().run(progressTask); + } else { + NullityInferrer.nothingFoundMessage(project); } - }.execute(); - } - finally { - action.finish(); - } + } + }.execute(); + } + finally { + action.finish(); } }; } @@ -289,17 +273,9 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { private void showUsageView(@NotNull Project project, final UsageInfo[] usageInfos, @NotNull AnalysisScope scope) { final UsageTarget[] targets = UsageTarget.EMPTY_ARRAY; final Ref convertUsagesRef = new Ref(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos)); - } - }); - } - }, "Preprocess Usages", true, project)) return; + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos)); + }), "Preprocess Usages", true, project)) return; if (convertUsagesRef.isNull()) return; final Usage[] usages = convertUsagesRef.get(); diff --git a/java/java-impl/src/com/intellij/codeInspection/inferNullity/NullityInferrer.java b/java/java-impl/src/com/intellij/codeInspection/inferNullity/NullityInferrer.java index b9dbaea0d79f..213ff180fb86 100644 --- a/java/java-impl/src/com/intellij/codeInspection/inferNullity/NullityInferrer.java +++ b/java/java-impl/src/com/intellij/codeInspection/inferNullity/NullityInferrer.java @@ -158,12 +158,8 @@ public class NullityInferrer { } public static void nothingFoundMessage(final Project project) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Messages.showInfoMessage(project, "No places found to infer @Nullable/@NotNull", "Infer Nullity Results"); - } - }); + SwingUtilities.invokeLater( + () -> Messages.showInfoMessage(project, "No places found to infer @Nullable/@NotNull", "Infer Nullity Results")); } private static void annotateNotNull(Project project, @@ -186,11 +182,8 @@ public class NullityInferrer { private static void invoke(final Project project, final PsiModifierListOwner element, final String fqn, final String toRemove) { - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - new AddAnnotationFix(fqn, element, toRemove).invoke(project, null, element.getContainingFile()); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + new AddAnnotationFix(fqn, element, toRemove).invoke(project, null, element.getContainingFile()); }); } diff --git a/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/AddMethodsDialog.java b/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/AddMethodsDialog.java index b89db939b902..ff5ba95f034b 100644 --- a/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/AddMethodsDialog.java +++ b/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/AddMethodsDialog.java @@ -209,11 +209,8 @@ public class AddMethodsDialog extends DialogWrapper { final String fqn = aClass.getQualifiedName(); LOG.assertTrue(fqn != null); final String parameters = - StringUtil.join(ContainerUtil.map(method.getParameterList().getParameters(), new Function() { - @Override - public String fun(PsiParameter parameter) { - return parameter.getName(); - } + StringUtil.join(ContainerUtil.map(method.getParameterList().getParameters(), parameter -> { + return parameter.getName(); }), ", "); final String expressionText = fqn + "." + method.getName() + "(" + parameters + ")"; final PsiExpression psiExpression = JavaPsiFacade.getElementFactory(method.getProject()) diff --git a/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/PseudoLambdaReplaceTemplate.java b/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/PseudoLambdaReplaceTemplate.java index e49046f99587..bc976a85f807 100644 --- a/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/PseudoLambdaReplaceTemplate.java +++ b/java/java-impl/src/com/intellij/codeInspection/java18StreamApi/PseudoLambdaReplaceTemplate.java @@ -95,11 +95,8 @@ public class PseudoLambdaReplaceTemplate { public ValidationInfo validate(final PsiMethod method) { final PsiParameter[] parameters = method.getParameterList().getParameters(); final PsiType[] parameterTypes = - ContainerUtil.map2Array(Arrays.asList(parameters), new PsiType[parameters.length], new Function() { - @Override - public PsiType fun(PsiParameter parameter) { - return parameter.getType(); - } + ContainerUtil.map2Array(Arrays.asList(parameters), new PsiType[parameters.length], parameter -> { + return parameter.getType(); }); final PsiType returnType = method.getReturnType(); diff --git a/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java b/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java index 8ee442b77e10..fc1153d8a038 100644 --- a/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java @@ -134,23 +134,20 @@ public class JavaDocReferenceInspection extends JavaDocReferenceInspectionBase { Collections.sort(originalClasses, new PsiProximityComparator(referenceElement.getElement())); final JList list = new JBList(originalClasses.toArray(new PsiClass[originalClasses.size()])); list.setCellRenderer(new FQNameCellRenderer()); - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (!element.isValid()) return; - final int index = list.getSelectedIndex(); - if (index < 0) return; - new WriteCommandAction(project, element.getContainingFile()){ - @Override - protected void run(@NotNull final Result result) throws Throwable { - final PsiClass psiClass = originalClasses.get(index); - if (psiClass.isValid()) { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - referenceElement.bindToElement(psiClass); - } + final Runnable runnable = () -> { + if (!element.isValid()) return; + final int index = list.getSelectedIndex(); + if (index < 0) return; + new WriteCommandAction(project, element.getContainingFile()){ + @Override + protected void run(@NotNull final Result result) throws Throwable { + final PsiClass psiClass = originalClasses.get(index); + if (psiClass.isValid()) { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + referenceElement.bindToElement(psiClass); } - }.execute(); - } + } + }.execute(); }; final AsyncResult asyncResult = DataManager.getInstance().getDataContextFromFocus(); asyncResult.doWhenDone(new Consumer() { diff --git a/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java b/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java index 2a4a758cdf1b..a44e1402d558 100644 --- a/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java @@ -222,16 +222,13 @@ public class MagicCompletionContributor extends CompletionContributor { allowed.add(value); } - result.runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(CompletionResult completionResult) { - LookupElement element = completionResult.getLookupElement(); - Object object = element.getObject(); - if (object instanceof PsiElement && allowed.contains(object)) { - return; - } - result.passResult(completionResult); + result.runRemainingContributors(parameters, completionResult -> { + LookupElement element = completionResult.getLookupElement(); + Object object = element.getObject(); + if (object instanceof PsiElement && allowed.contains(object)) { + return; } + result.passResult(completionResult); }); } diff --git a/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java b/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java index d9bd3099459b..a6a698db5a27 100644 --- a/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/sameParameterValue/SameParameterValueInspection.java @@ -104,26 +104,23 @@ public class SameParameterValueInspection extends SameParameterValueInspectionBa public static void inlineSameParameterValue(final PsiMethod method, final PsiParameter parameter, final PsiExpression defToInline) { final Collection refsToInline = ReferencesSearch.search(parameter).findAll(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - PsiExpression[] exprs = new PsiExpression[refsToInline.size()]; - int idx = 0; - for (PsiReference reference : refsToInline) { - if (reference instanceof PsiJavaCodeReferenceElement) { - exprs[idx++] = InlineUtil.inlineVariable(parameter, defToInline, (PsiJavaCodeReferenceElement)reference); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + PsiExpression[] exprs = new PsiExpression[refsToInline.size()]; + int idx = 0; + for (PsiReference reference : refsToInline) { + if (reference instanceof PsiJavaCodeReferenceElement) { + exprs[idx++] = InlineUtil.inlineVariable(parameter, defToInline, (PsiJavaCodeReferenceElement)reference); } + } - for (final PsiExpression expr : exprs) { - if (expr != null) InlineUtil.tryToInlineArrayCreationForVarargs(expr); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); + for (final PsiExpression expr : exprs) { + if (expr != null) InlineUtil.tryToInlineArrayCreationForVarargs(expr); } } + catch (IncorrectOperationException e) { + LOG.error(e); + } }); removeParameter(method, parameter); diff --git a/java/java-impl/src/com/intellij/codeInspection/util/SpecialAnnotationsUtil.java b/java/java-impl/src/com/intellij/codeInspection/util/SpecialAnnotationsUtil.java index b51cea429a47..62e1b3ddb024 100644 --- a/java/java-impl/src/com/intellij/codeInspection/util/SpecialAnnotationsUtil.java +++ b/java/java-impl/src/com/intellij/codeInspection/util/SpecialAnnotationsUtil.java @@ -55,12 +55,7 @@ public class SpecialAnnotationsUtil { public static JPanel createSpecialAnnotationsListControl(final List list, final String borderTitle, final boolean acceptPatterns) { - final SortedListModel listModel = new SortedListModel(new Comparator() { - @Override - public int compare(final String o1, final String o2) { - return o1.compareTo(o2); - } - }); + final SortedListModel listModel = new SortedListModel((o1, o2) -> o1.compareTo(o2)); final JList injectionList = new JBList(listModel); for (String s : list) { listModel.add(s); diff --git a/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/BaseConvertToLocalQuickFix.java b/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/BaseConvertToLocalQuickFix.java index 2b2ea1634dfb..84b6ac1ae91a 100644 --- a/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/BaseConvertToLocalQuickFix.java +++ b/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/BaseConvertToLocalQuickFix.java @@ -118,15 +118,11 @@ public abstract class BaseConvertToLocalQuickFix implemen variable, refsSet, delete, - new NotNullFunction() { - @NotNull - @Override - public PsiElement fun(PsiDeclarationStatement declaration) { - if (!mayBeFinal(firstElement, references)) { - PsiUtil.setModifierProperty((PsiModifierListOwner)declaration.getDeclaredElements()[0], PsiModifier.FINAL, false); - } - return anchor.replace(declaration); + declaration -> { + if (!mayBeFinal(firstElement, references)) { + PsiUtil.setModifierProperty((PsiModifierListOwner)declaration.getDeclaredElements()[0], PsiModifier.FINAL, false); } + return anchor.replace(declaration); } ); } @@ -138,13 +134,7 @@ public abstract class BaseConvertToLocalQuickFix implemen variable, references, delete, - new NotNullFunction() { - @NotNull - @Override - public PsiElement fun(PsiDeclarationStatement declaration) { - return anchorBlock.addBefore(declaration, anchor); - } - } + declaration -> anchorBlock.addBefore(declaration, anchor) ); } diff --git a/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspection.java b/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspection.java index 51beb4239fc3..da232e20271a 100644 --- a/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspection.java @@ -70,12 +70,10 @@ public class FieldCanBeLocalInspection extends FieldCanBeLocalInspectionBase { } if (element != null) { final PsiElement finalElement = element; - Runnable runnable = new Runnable() { - public void run() { - beforeDelete(project, variable, finalElement); - variable.normalizeDeclaration(); - variable.delete(); - } + Runnable runnable = () -> { + beforeDelete(project, variable, finalElement); + variable.normalizeDeclaration(); + variable.delete(); }; ApplicationManager.getApplication().runWriteAction(runnable); } diff --git a/java/java-impl/src/com/intellij/cyclicDependencies/actions/CyclicDependenciesHandler.java b/java/java-impl/src/com/intellij/cyclicDependencies/actions/CyclicDependenciesHandler.java index c1bfd16e2de8..bb4eeb452e98 100644 --- a/java/java-impl/src/com/intellij/cyclicDependencies/actions/CyclicDependenciesHandler.java +++ b/java/java-impl/src/com/intellij/cyclicDependencies/actions/CyclicDependenciesHandler.java @@ -43,25 +43,15 @@ public class CyclicDependenciesHandler { public void analyze() { final CyclicDependenciesBuilder builder = new CyclicDependenciesBuilder(myProject, myScope); - final Runnable process = new Runnable() { - public void run() { - builder.analyze(); - } - }; - final Runnable successRunnable = new Runnable() { - public void run() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - CyclicDependenciesPanel panel = new CyclicDependenciesPanel(myProject, builder); - Content content = ContentFactory.SERVICE.getInstance().createContent(panel, AnalysisScopeBundle.message( - "action.analyzing.cyclic.dependencies.in.scope", builder.getScope().getDisplayName()), false); - content.setDisposer(panel); - panel.setContent(content); - DependenciesToolWindow.getInstance(myProject).addContent(content); - } - }); - } - }; + final Runnable process = () -> builder.analyze(); + final Runnable successRunnable = () -> SwingUtilities.invokeLater(() -> { + CyclicDependenciesPanel panel = new CyclicDependenciesPanel(myProject, builder); + Content content = ContentFactory.SERVICE.getInstance().createContent(panel, AnalysisScopeBundle.message( + "action.analyzing.cyclic.dependencies.in.scope", builder.getScope().getDisplayName()), false); + content.setDisposer(panel); + panel.setContent(content); + DependenciesToolWindow.getInstance(myProject).addContent(content); + }); ProgressManager.getInstance() .runProcessWithProgressAsynchronously(myProject, AnalysisScopeBundle.message("package.dependencies.progress.title"), process, successRunnable, null, new PerformAnalysisInBackgroundOption(myProject)); diff --git a/java/java-impl/src/com/intellij/cyclicDependencies/ui/CyclicDependenciesPanel.java b/java/java-impl/src/com/intellij/cyclicDependencies/ui/CyclicDependenciesPanel.java index 9d09e393a2cc..27d7dd2b3bd2 100644 --- a/java/java-impl/src/com/intellij/cyclicDependencies/ui/CyclicDependenciesPanel.java +++ b/java/java-impl/src/com/intellij/cyclicDependencies/ui/CyclicDependenciesPanel.java @@ -124,28 +124,26 @@ public class CyclicDependenciesPanel extends JPanel implements Disposable, DataP myRightTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - Set searchIn = getSelectedScope(myRightTree); - final PackageNode selectedPackageNode = getSelectedPackage(myRightTree); - if (selectedPackageNode == null) { - return; - } - final PackageDependenciesNode nextPackageNode = getNextPackageNode(selectedPackageNode); - Set searchFor = new HashSet(); - Set packNodes = new HashSet(); - getPackageNodesHierarchy(selectedPackageNode, packNodes); - for (PackageNode packageNode : packNodes) { - searchFor.addAll(myBuilder.getDependentFilesInPackage((PsiPackage)packageNode.getPsiElement(), - ((PsiPackage)nextPackageNode.getPsiElement()))); - } - if (searchIn.isEmpty() || searchFor.isEmpty()) { - myUsagesPanel.setToInitialPosition(); - } - else { - myBuilder.setRootNodeNameInUsageView(AnalysisScopeBundle.message("cyclic.dependencies.usage.view.root.node.text", ((PsiPackage)nextPackageNode.getPsiElement()).getQualifiedName(), ((PsiPackage)selectedPackageNode.getPsiElement()).getQualifiedName())); - myUsagesPanel.findUsages(searchIn, searchFor); - } + SwingUtilities.invokeLater(() -> { + Set searchIn = getSelectedScope(myRightTree); + final PackageNode selectedPackageNode = getSelectedPackage(myRightTree); + if (selectedPackageNode == null) { + return; + } + final PackageDependenciesNode nextPackageNode = getNextPackageNode(selectedPackageNode); + Set searchFor = new HashSet(); + Set packNodes = new HashSet(); + getPackageNodesHierarchy(selectedPackageNode, packNodes); + for (PackageNode packageNode : packNodes) { + searchFor.addAll(myBuilder.getDependentFilesInPackage((PsiPackage)packageNode.getPsiElement(), + ((PsiPackage)nextPackageNode.getPsiElement()))); + } + if (searchIn.isEmpty() || searchFor.isEmpty()) { + myUsagesPanel.setToInitialPosition(); + } + else { + myBuilder.setRootNodeNameInUsageView(AnalysisScopeBundle.message("cyclic.dependencies.usage.view.root.node.text", ((PsiPackage)nextPackageNode.getPsiElement()).getQualifiedName(), ((PsiPackage)selectedPackageNode.getPsiElement()).getQualifiedName())); + myUsagesPanel.findUsages(searchIn, searchFor); } }); } @@ -515,11 +513,7 @@ public class CyclicDependenciesPanel extends JPanel implements Disposable, DataP public void actionPerformed(AnActionEvent e) { DependenciesToolWindow.getInstance(myProject).closeContent(myContent); mySettings.copyToApplicationDependencySettings(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - new CyclicDependenciesHandler(myProject, myBuilder.getScope()).analyze(); - } - }); + SwingUtilities.invokeLater(() -> new CyclicDependenciesHandler(myProject, myBuilder.getScope()).analyze()); } } diff --git a/java/java-impl/src/com/intellij/ide/JavaFilePasteProvider.java b/java/java-impl/src/com/intellij/ide/JavaFilePasteProvider.java index 20a0cb12bb4c..9704019fdf17 100644 --- a/java/java-impl/src/com/intellij/ide/JavaFilePasteProvider.java +++ b/java/java-impl/src/com/intellij/ide/JavaFilePasteProvider.java @@ -88,25 +88,23 @@ public class JavaFilePasteProvider implements PasteProvider { final Project project = javaFile.getProject(); if ((oldStatement != null && !oldStatement.getPackageName().equals(aPackage.getQualifiedName()) || (oldStatement == null && aPackage.getQualifiedName().length() > 0))) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - try { - PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final PsiPackageStatement newStatement = factory.createPackageStatement(aPackage.getQualifiedName()); - if (oldStatement != null) { - oldStatement.replace(newStatement); - } - else { - final PsiElement addedStatement = javaFile.addAfter(newStatement, null); - final TextRange textRange = addedStatement.getTextRange(); - // ensure line break is added after the statement - CodeStyleManager.getInstance(project).reformatRange(javaFile, textRange.getStartOffset(), textRange.getEndOffset()+1); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + try { + PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiPackageStatement newStatement = factory.createPackageStatement(aPackage.getQualifiedName()); + if (oldStatement != null) { + oldStatement.replace(newStatement); } - catch (IncorrectOperationException e) { - // ignore + else { + final PsiElement addedStatement = javaFile.addAfter(newStatement, null); + final TextRange textRange = addedStatement.getTextRange(); + // ensure line break is added after the statement + CodeStyleManager.getInstance(project).reformatRange(javaFile, textRange.getStartOffset(), textRange.getEndOffset()+1); } } + catch (IncorrectOperationException e) { + // ignore + } }, "Updating package statement", null); } } diff --git a/java/java-impl/src/com/intellij/ide/actions/JavaQualifiedNameProvider.java b/java/java-impl/src/com/intellij/ide/actions/JavaQualifiedNameProvider.java index 07cc6f64e33c..0a30e26ea5ff 100644 --- a/java/java-impl/src/com/intellij/ide/actions/JavaQualifiedNameProvider.java +++ b/java/java-impl/src/com/intellij/ide/actions/JavaQualifiedNameProvider.java @@ -259,18 +259,15 @@ public class JavaQualifiedNameProvider implements QualifiedNameProvider { } private static String getParameterString(PsiMethod method, final boolean erasure) { - return "(" + StringUtil.join(method.getParameterList().getParameters(), new Function() { - @Override - public String fun(PsiParameter parameter) { - PsiType type = parameter.getType(); - if (erasure) { - final PsiType erased = TypeConversionUtil.erasure(type); - if (erased != null) { - type = erased; - } + return "(" + StringUtil.join(method.getParameterList().getParameters(), parameter -> { + PsiType type = parameter.getType(); + if (erasure) { + final PsiType erased = TypeConversionUtil.erasure(type); + if (erased != null) { + type = erased; } - return type.getCanonicalText(); } + return type.getCanonicalText(); }, ", ") + ")"; } diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java index b49879f6f883..e2819bd1565a 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java @@ -83,14 +83,11 @@ public final class CallerMethodsTreeStructure extends HierarchyTreeStructure { for (final PsiMethod methodToFind : methodsToFind) { final JavaCallHierarchyData data = new JavaCallHierarchyData(originalClass, methodToFind, originalType, method, methodsToFind, descriptor, methodToDescriptorMap, myProject); - MethodReferencesSearch.search(methodToFind, searchScope, true).forEach(new Processor() { - @Override - public boolean process(final PsiReference reference) { - for (CallReferenceProcessor processor : CallReferenceProcessor.EP_NAME.getExtensions()) { - if (!processor.process(reference, data)) break; - } - return true; + MethodReferencesSearch.search(methodToFind, searchScope, true).forEach(reference -> { + for (CallReferenceProcessor processor : CallReferenceProcessor.EP_NAME.getExtensions()) { + if (!processor.process(reference, data)) break; } + return true; }); } diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java b/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java index 58ff518990ba..71c2bd039fdb 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java @@ -174,12 +174,9 @@ public final class MethodHierarchyTreeStructure extends HierarchyTreeStructure { final PsiMethod existingMethod = ((MethodHierarchyNodeDescriptor)descriptor).getMethod(psiClass, false); if (existingMethod != null) { - FunctionalExpressionSearch.search(existingMethod).forEach(new Processor() { - @Override - public boolean process(PsiFunctionalExpression expression) { - descriptors.add(new MethodHierarchyNodeDescriptor(myProject, descriptor, expression, false, MethodHierarchyTreeStructure.this)); - return true; - } + FunctionalExpressionSearch.search(existingMethod).forEach(expression -> { + descriptors.add(new MethodHierarchyNodeDescriptor(myProject, descriptor, expression, false, MethodHierarchyTreeStructure.this)); + return true; }); } diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/method/OverrideImplementMethodAction.java b/java/java-impl/src/com/intellij/ide/hierarchy/method/OverrideImplementMethodAction.java index 73504e6db865..ecbb97ddede9 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/method/OverrideImplementMethodAction.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/method/OverrideImplementMethodAction.java @@ -47,49 +47,42 @@ abstract class OverrideImplementMethodAction extends AnAction { if (project == null) return; final String commandName = event.getPresentation().getText(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> { - try{ - final HierarchyNodeDescriptor[] selectedDescriptors = methodHierarchyBrowser.getSelectedDescriptors(); - if (selectedDescriptors.length > 0) { - final List files = new ArrayList(selectedDescriptors.length); - for (HierarchyNodeDescriptor selectedDescriptor : selectedDescriptors) { - final PsiFile containingFile = ((MethodHierarchyNodeDescriptor)selectedDescriptor).getPsiClass().getContainingFile(); - if (containingFile != null) { - final VirtualFile vFile = containingFile.getVirtualFile(); - if (vFile != null) { - files.add(vFile); - } - } - } - final ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(VfsUtil.toVirtualFileArray(files)); - if (!status.hasReadonlyFiles()) { - for (HierarchyNodeDescriptor selectedDescriptor : selectedDescriptors) { - final PsiElement aClass = ((MethodHierarchyNodeDescriptor)selectedDescriptor).getPsiClass(); - if (aClass instanceof PsiClass) { - OverrideImplementUtil.overrideOrImplement((PsiClass)aClass, methodHierarchyBrowser.getBaseMethod()); - } - } - ToolWindowManager.getInstance(project).activateEditorComponent(); - } - else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Messages.showErrorDialog(project, status.getReadonlyFilesMessage(), commandName); - } - }); + try{ + final HierarchyNodeDescriptor[] selectedDescriptors = methodHierarchyBrowser.getSelectedDescriptors(); + if (selectedDescriptors.length > 0) { + final List files = new ArrayList(selectedDescriptors.length); + for (HierarchyNodeDescriptor selectedDescriptor : selectedDescriptors) { + final PsiFile containingFile = ((MethodHierarchyNodeDescriptor)selectedDescriptor).getPsiClass().getContainingFile(); + if (containingFile != null) { + final VirtualFile vFile = containingFile.getVirtualFile(); + if (vFile != null) { + files.add(vFile); } } } - catch(IncorrectOperationException e){ - LOG.error(e); + final ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(VfsUtil.toVirtualFileArray(files)); + if (!status.hasReadonlyFiles()) { + for (HierarchyNodeDescriptor selectedDescriptor : selectedDescriptors) { + final PsiElement aClass = ((MethodHierarchyNodeDescriptor)selectedDescriptor).getPsiClass(); + if (aClass instanceof PsiClass) { + OverrideImplementUtil.overrideOrImplement((PsiClass)aClass, methodHierarchyBrowser.getBaseMethod()); + } + } + ToolWindowManager.getInstance(project).activateEditorComponent(); + } + else { + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(project, status.getReadonlyFilesMessage(), commandName)); } } - }, commandName, null); - } + } + catch(IncorrectOperationException e){ + LOG.error(e); + } + }, commandName, null); }); } diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/type/SubtypesHierarchyTreeStructure.java b/java/java-impl/src/com/intellij/ide/hierarchy/type/SubtypesHierarchyTreeStructure.java index dd104332c617..d5d5b1d87d23 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/type/SubtypesHierarchyTreeStructure.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/type/SubtypesHierarchyTreeStructure.java @@ -59,12 +59,9 @@ public class SubtypesHierarchyTreeStructure extends HierarchyTreeStructure { for (PsiClass aClass : classes) { descriptors.add(new TypeHierarchyNodeDescriptor(myProject, descriptor, aClass, false)); } - FunctionalExpressionSearch.search(psiClass, searchScope).forEach(new Processor() { - @Override - public boolean process(PsiFunctionalExpression expression) { - descriptors.add(new TypeHierarchyNodeDescriptor(myProject, descriptor, expression, false)); - return true; - } + FunctionalExpressionSearch.search(psiClass, searchScope).forEach(expression -> { + descriptors.add(new TypeHierarchyNodeDescriptor(myProject, descriptor, expression, false)); + return true; }); return descriptors.toArray(new HierarchyNodeDescriptor[descriptors.size()]); } diff --git a/java/java-impl/src/com/intellij/ide/util/PackageChooserDialog.java b/java/java-impl/src/com/intellij/ide/util/PackageChooserDialog.java index a8380b5aa288..ff7f70b67bb0 100644 --- a/java/java-impl/src/com/intellij/ide/util/PackageChooserDialog.java +++ b/java/java-impl/src/com/intellij/ide/util/PackageChooserDialog.java @@ -188,12 +188,7 @@ public class PackageChooserDialog extends PackageChooser { @Override public void documentChanged(DocumentEvent e) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - updateTreeFromPath(); - } - }, 300); + myAlarm.addRequest(() -> updateTreeFromPath(), 300); } }); myPathEditor.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0)); @@ -295,14 +290,12 @@ public class PackageChooserDialog extends PackageChooser { } ); - TreeUtil.sort(myModel, new Comparator() { - public int compare(Object o1, Object o2) { - DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1; - DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2; - PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject(); - PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject(); - return element1.getName().compareToIgnoreCase(element2.getName()); - } + TreeUtil.sort(myModel, (o1, o2) -> { + DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1; + DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2; + PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject(); + PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject(); + return element1.getName().compareToIgnoreCase(element2.getName()); }); } @@ -380,57 +373,53 @@ public class PackageChooserDialog extends PackageChooser { }); if (newPackageName == null) return; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - final Runnable action = new Runnable() { - public void run() { + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final Runnable action = () -> { - try { - String newQualifiedName = selectedPackage.getQualifiedName(); - if (!Comparing.strEqual(newQualifiedName,"")) newQualifiedName += "."; - newQualifiedName += newPackageName; - final PsiDirectory dir = PackageUtil.findOrCreateDirectoryForPackage(myProject, newQualifiedName, null, false); - if (dir == null) return; - final PsiPackage newPackage = JavaDirectoryService.getInstance().getPackage(dir); + try { + String newQualifiedName = selectedPackage.getQualifiedName(); + if (!Comparing.strEqual(newQualifiedName,"")) newQualifiedName += "."; + newQualifiedName += newPackageName; + final PsiDirectory dir = PackageUtil.findOrCreateDirectoryForPackage(myProject, newQualifiedName, null, false); + if (dir == null) return; + final PsiPackage newPackage = JavaDirectoryService.getInstance().getPackage(dir); - DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTree.getSelectionPath().getLastPathComponent(); - final DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(); - newChild.setUserObject(newPackage); - node.add(newChild); + DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTree.getSelectionPath().getLastPathComponent(); + final DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(); + newChild.setUserObject(newPackage); + node.add(newChild); - final DefaultTreeModel model = (DefaultTreeModel)myTree.getModel(); - model.nodeStructureChanged(node); + final DefaultTreeModel model = (DefaultTreeModel)myTree.getModel(); + model.nodeStructureChanged(node); - final TreePath selectionPath = myTree.getSelectionPath(); - TreePath path; - if (selectionPath == null) { - path = new TreePath(newChild.getPath()); - } else { - path = selectionPath.pathByAddingChild(newChild); - } - myTree.setSelectionPath(path); - myTree.scrollPathToVisible(path); - myTree.expandPath(path); + final TreePath selectionPath = myTree.getSelectionPath(); + TreePath path; + if (selectionPath == null) { + path = new TreePath(newChild.getPath()); + } else { + path = selectionPath.pathByAddingChild(newChild); + } + myTree.setSelectionPath(path); + myTree.scrollPathToVisible(path); + myTree.expandPath(path); - } - catch (IncorrectOperationException e) { - Messages.showMessageDialog( - getContentPane(), - StringUtil.getMessage(e), - CommonBundle.getErrorTitle(), - Messages.getErrorIcon() - ); - if (LOG.isDebugEnabled()) { - LOG.debug(e); - } - } - } - }; - ApplicationManager.getApplication().runReadAction(action); - } + } + catch (IncorrectOperationException e) { + Messages.showMessageDialog( + getContentPane(), + StringUtil.getMessage(e), + CommonBundle.getErrorTitle(), + Messages.getErrorIcon() + ); + if (LOG.isDebugEnabled()) { + LOG.debug(e); + } + } + }; + ApplicationManager.getApplication().runReadAction(action); }, - IdeBundle.message("command.create.new.package"), - null); + IdeBundle.message("command.create.new.package"), + null); } private class NewPackageAction extends AnAction { diff --git a/java/java-impl/src/com/intellij/ide/util/PackageUtil.java b/java/java-impl/src/com/intellij/ide/util/PackageUtil.java index 0530f34e653a..59c6bc7e15ed 100644 --- a/java/java-impl/src/com/intellij/ide/util/PackageUtil.java +++ b/java/java-impl/src/com/intellij/ide/util/PackageUtil.java @@ -169,21 +169,17 @@ public class PackageUtil { final PsiDirectory[] psiDirectory = new PsiDirectory[1]; final IncorrectOperationException[] exception = new IncorrectOperationException[1]; - CommandProcessor.getInstance().executeCommand(project, new Runnable(){ - public void run() { - psiDirectory[0] = ApplicationManager.getApplication().runWriteAction(new Computable() { - public PsiDirectory compute() { - try { - return oldDirectory.createSubdirectory(name); - } - catch (IncorrectOperationException e) { - exception[0] = e; - return null; - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> psiDirectory[0] = ApplicationManager.getApplication().runWriteAction(new Computable() { + public PsiDirectory compute() { + try { + return oldDirectory.createSubdirectory(name); + } + catch (IncorrectOperationException e) { + exception[0] = e; + return null; + } } - }, IdeBundle.message("command.create.new.subdirectory"), null); + }), IdeBundle.message("command.create.new.subdirectory"), null); if (exception[0] != null) throw exception[0]; diff --git a/java/java-impl/src/com/intellij/ide/util/SuperMethodWarningUtil.java b/java/java-impl/src/com/intellij/ide/util/SuperMethodWarningUtil.java index fd3b7659c4c5..4f44a4cc5ab0 100644 --- a/java/java-impl/src/com/intellij/ide/util/SuperMethodWarningUtil.java +++ b/java/java-impl/src/com/intellij/ide/util/SuperMethodWarningUtil.java @@ -165,13 +165,10 @@ public class SuperMethodWarningUtil { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof String) { - processor.execute(methods[value.equals(renameBase) ? 0 : 1]); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof String) { + processor.execute(methods[value.equals(renameBase) ? 0 : 1]); } }).createPopup().showInBestPositionFor(editor); } diff --git a/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java b/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java index b768eccdc10b..62da82888732 100644 --- a/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java +++ b/java/java-impl/src/com/intellij/ide/util/gotoByName/DefaultSymbolNavigationContributor.java @@ -99,21 +99,18 @@ public class DefaultSymbolNavigationContributor implements ChooseByNameContribut if (containingClass == null) return false; final int parametersCount = method.getParameterList().getParametersCount(); - return !InheritanceUtil.processSupers(containingClass, false, new Processor() { - @Override - public boolean process(PsiClass superClass) { - if (PsiSearchScopeUtil.isInScope(scope, superClass)) { - for (PsiMethod candidate : superClass.findMethodsByName(method.getName(), false)) { - if (parametersCount == candidate.getParameterList().getParametersCount() && - !candidate.hasModifierProperty(PsiModifier.PRIVATE) && - !candidate.hasModifierProperty(PsiModifier.STATIC) && - qualifiedMatcher.value(candidate)) { - return false; - } + return !InheritanceUtil.processSupers(containingClass, false, superClass -> { + if (PsiSearchScopeUtil.isInScope(scope, superClass)) { + for (PsiMethod candidate : superClass.findMethodsByName(method.getName(), false)) { + if (parametersCount == candidate.getParameterList().getParametersCount() && + !candidate.hasModifierProperty(PsiModifier.PRIVATE) && + !candidate.hasModifierProperty(PsiModifier.STATIC) && + qualifiedMatcher.value(candidate)) { + return false; } } - return true; } + return true; }); } @@ -152,28 +149,19 @@ public class DefaultSymbolNavigationContributor implements ChooseByNameContribut //noinspection UnusedDeclaration final Set collectedMethods = new THashSet(); - boolean success = cache.processFieldsWithName(name, new Processor() { - @Override - public boolean process(PsiField field) { - if (isOpenable(field) && qualifiedMatcher.value(field)) return processor.process(field); - return true; - } + boolean success = cache.processFieldsWithName(name, field -> { + if (isOpenable(field) && qualifiedMatcher.value(field)) return processor.process(field); + return true; }, scope, filter) && - cache.processClassesWithName(name, new Processor() { - @Override - public boolean process(PsiClass aClass) { + cache.processClassesWithName(name, aClass -> { if (isOpenable(aClass) && qualifiedMatcher.value(aClass)) return processor.process(aClass); return true; + }, scope, filter) && + cache.processMethodsWithName(name, method -> { + if(!method.isConstructor() && isOpenable(method) && qualifiedMatcher.value(method)) { + collectedMethods.add(method); } - }, scope, filter) && - cache.processMethodsWithName(name, new Processor() { - @Override - public boolean process(PsiMethod method) { - if(!method.isConstructor() && isOpenable(method) && qualifiedMatcher.value(method)) { - collectedMethods.add(method); - } - return true; - } + return true; }, scope, filter); if (success) { // hashSuperMethod accesses index and can not be invoked without risk of the deadlock in processMethodsWithName diff --git a/java/java-impl/src/com/intellij/ide/util/scopeChooser/ClassHierarchyScopeDescriptor.java b/java/java-impl/src/com/intellij/ide/util/scopeChooser/ClassHierarchyScopeDescriptor.java index 30486f5f5ac3..511974a70681 100644 --- a/java/java-impl/src/com/intellij/ide/util/scopeChooser/ClassHierarchyScopeDescriptor.java +++ b/java/java-impl/src/com/intellij/ide/util/scopeChooser/ClassHierarchyScopeDescriptor.java @@ -77,12 +77,9 @@ public class ClassHierarchyScopeDescriptor extends ScopeDescriptor { classesToSearch.addAll(ClassInheritorsSearch.search(aClass).findAll()); - FunctionalExpressionSearch.search(aClass).forEach(new Processor() { - @Override - public boolean process(PsiFunctionalExpression expression) { - classesToSearch.add(expression); - return true; - } + FunctionalExpressionSearch.search(aClass).forEach(expression -> { + classesToSearch.add(expression); + return true; }); myCachedScope = new LocalSearchScope(PsiUtilCore.toPsiElementArray(classesToSearch), diff --git a/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java b/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java index 310954c56883..ba4cb56311a5 100644 --- a/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java +++ b/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java @@ -45,12 +45,7 @@ public class TreeViewUtil { final ConcurrentMap newMap = ContainerUtil.createConcurrentWeakMap(); map = ((UserDataHolderEx)project).putUserDataIfAbsent(SHOULD_ABBREV_PACK_KEY, newMap); if (map == newMap) { - PsiManagerEx.getInstanceEx(project).registerRunnableToRunOnChange(new Runnable() { - @Override - public void run() { - newMap.clear(); - } - }); + PsiManagerEx.getInstanceEx(project).registerRunnableToRunOnChange(() -> newMap.clear()); } } diff --git a/java/java-impl/src/com/intellij/internal/BuildIcons.java b/java/java-impl/src/com/intellij/internal/BuildIcons.java index 0c7a10566af5..4fb1f8144e5c 100644 --- a/java/java-impl/src/com/intellij/internal/BuildIcons.java +++ b/java/java-impl/src/com/intellij/internal/BuildIcons.java @@ -38,17 +38,14 @@ public class BuildIcons { walk(root, dimToPath, root); ArrayList> keys = new ArrayList>(dimToPath.keySet()); - Collections.sort(keys, new Comparator>() { - @Override - public int compare(Couple o1, Couple o2) { - int d0 = dimToPath.get(o2).size() - dimToPath.get(o1).size(); - if (d0 != 0) return d0; - int d1 = o1.first - o2.first; - if (d1 != 0) { - return d1; - } - return o1.second - o2.second; + Collections.sort(keys, (o1, o2) -> { + int d0 = dimToPath.get(o2).size() - dimToPath.get(o1).size(); + if (d0 != 0) return d0; + int d1 = o1.first - o2.first; + if (d1 != 0) { + return d1; } + return o1.second - o2.second; }); int total = 0; diff --git a/java/java-impl/src/com/intellij/internal/StaticIconFieldsAction.java b/java/java-impl/src/com/intellij/internal/StaticIconFieldsAction.java index 7fae15f159b7..c7deee36b44e 100644 --- a/java/java-impl/src/com/intellij/internal/StaticIconFieldsAction.java +++ b/java/java-impl/src/com/intellij/internal/StaticIconFieldsAction.java @@ -74,27 +74,21 @@ public class StaticIconFieldsAction extends AnAction { } private static void searchFields(final PsiClass allIcons, final UsageView view, final ProgressIndicator indicator) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - indicator.setText("Searching for: " + allIcons.getQualifiedName()); - } + ApplicationManager.getApplication().runReadAction(() -> { + indicator.setText("Searching for: " + allIcons.getQualifiedName()); }); - ReferencesSearch.search(allIcons).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - PsiElement elt = reference.getElement(); + ReferencesSearch.search(allIcons).forEach(reference -> { + PsiElement elt = reference.getElement(); - while (elt instanceof PsiExpression) elt = elt.getParent(); + while (elt instanceof PsiExpression) elt = elt.getParent(); - if (elt instanceof PsiField) { - UsageInfo info = new UsageInfo(elt, false); - view.appendUsage(new UsageInfo2UsageAdapter(info)); - } - - return true; + if (elt instanceof PsiField) { + UsageInfo info = new UsageInfo(elt, false); + view.appendUsage(new UsageInfo2UsageAdapter(info)); } + + return true; }); } } diff --git a/java/java-impl/src/com/intellij/internal/UsedIconsListingAction.java b/java/java-impl/src/com/intellij/internal/UsedIconsListingAction.java index 65eb2d2c54bc..450f73b3e80b 100644 --- a/java/java-impl/src/com/intellij/internal/UsedIconsListingAction.java +++ b/java/java-impl/src/com/intellij/internal/UsedIconsListingAction.java @@ -159,21 +159,18 @@ public class UsedIconsListingAction extends AnAction { PsiClass presentation = psiFacade.findClass("com.intellij.ide.presentation.Presentation", allScope); final MultiMap annotations = new MultiMap(); - AnnotationTargetsSearch.search(presentation).forEach(new Processor() { - @Override - public boolean process(PsiModifierListOwner owner) { - PsiAnnotation annotation = owner.getModifierList().findAnnotation("com.intellij.ide.presentation.Presentation"); + AnnotationTargetsSearch.search(presentation).forEach(owner -> { + PsiAnnotation annotation = owner.getModifierList().findAnnotation("com.intellij.ide.presentation.Presentation"); - PsiAnnotationMemberValue icon = annotation.findAttributeValue("icon"); - if (icon instanceof PsiLiteralExpression) { - Object value = ((PsiLiteralExpression)icon).getValue(); - if (value instanceof String) { - annotations.putValue((String)value, annotation); - } + PsiAnnotationMemberValue icon = annotation.findAttributeValue("icon"); + if (icon instanceof PsiLiteralExpression) { + Object value = ((PsiLiteralExpression)icon).getValue(); + if (value instanceof String) { + annotations.putValue((String)value, annotation); } - - return true; } + + return true; }); doReplacements(project, calls, xmlAttributes, annotations, psiFacade.findClass("com.intellij.icons.AllIcons", allScope)); diff --git a/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarStatisticsService.java b/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarStatisticsService.java index 7ab6ee5c6c57..4ee54b15c773 100644 --- a/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarStatisticsService.java +++ b/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarStatisticsService.java @@ -102,12 +102,7 @@ public class LibraryJarStatisticsService extends SettingsConnectionService imple public void runActivity(@NotNull Project project) { final Application application = ApplicationManager.getApplication(); if (application.isUnitTestMode() || application.isHeadlessEnvironment()) return; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - getInstance().getTechnologyDescriptors(); - } - }); + ApplicationManager.getApplication().executeOnPooledThread((Runnable)() -> getInstance().getTechnologyDescriptors()); ; } } diff --git a/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java b/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java index e82f79652074..eeaad1b55b17 100644 --- a/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java +++ b/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java @@ -105,13 +105,10 @@ public abstract class FindJarFix implements IntentionActio JBPopupFactory.getInstance() .createListPopupBuilder(listOfFqns) .setTitle("Select Qualified Name") - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = listOfFqns.getSelectedValue(); - if (value instanceof String) { - findJarsForFqn(((String)value), editor); - } + .setItemChoosenCallback(() -> { + final Object value = listOfFqns.getSelectedValue(); + if (value instanceof String) { + findJarsForFqn(((String)value), editor); } }).createPopup().showInBestPositionFor(editor); } @@ -123,35 +120,33 @@ public abstract class FindJarFix implements IntentionActio private void findJarsForFqn(final String fqn, final Editor editor) { final Map libs = new HashMap(); - final Runnable runnable = new Runnable() { - public void run() { - try { - final DOMParser parser = new DOMParser(); - parser.parse(CLASS_ROOT_URL + fqn.replace('.', '/') + CLASS_PAGE_EXT); - final Document doc = parser.getDocument(); - if (doc != null) { - final NodeList links = doc.getElementsByTagName(LINK_TAG_NAME); - for (int i = 0; i < links.getLength(); i++) { - final Node link = links.item(i); - final String libName = link.getTextContent(); - final NamedNodeMap attributes = link.getAttributes(); - if (attributes != null) { - final Node href = attributes.getNamedItem(LINK_ATTR_NAME); - if (href != null) { - final String pathToJar = href.getTextContent(); - if (pathToJar != null && (pathToJar.startsWith("/jar/") || pathToJar.startsWith("/class/../"))) { - libs.put(libName, SERVICE_URL + pathToJar); - } + final Runnable runnable = () -> { + try { + final DOMParser parser = new DOMParser(); + parser.parse(CLASS_ROOT_URL + fqn.replace('.', '/') + CLASS_PAGE_EXT); + final Document doc = parser.getDocument(); + if (doc != null) { + final NodeList links = doc.getElementsByTagName(LINK_TAG_NAME); + for (int i = 0; i < links.getLength(); i++) { + final Node link = links.item(i); + final String libName = link.getTextContent(); + final NamedNodeMap attributes = link.getAttributes(); + if (attributes != null) { + final Node href = attributes.getNamedItem(LINK_ATTR_NAME); + if (href != null) { + final String pathToJar = href.getTextContent(); + if (pathToJar != null && (pathToJar.startsWith("/jar/") || pathToJar.startsWith("/class/../"))) { + libs.put(libName, SERVICE_URL + pathToJar); } } } } } - catch (IOException ignore) {// - } - catch (Exception e) {// - LOG.warn(e); - } + } + catch (IOException ignore) {// + } + catch (Exception e) {// + LOG.warn(e); } }; @@ -169,20 +164,9 @@ public abstract class FindJarFix implements IntentionActio HintManager.getInstance().showInformationHint(editor, "No libraries found for '" + fqn + "'"); } else { final ArrayList variants = new ArrayList(libs.keySet()); - Collections.sort(variants, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.compareTo(o2); - } - }); + Collections.sort(variants, (o1, o2) -> o1.compareTo(o2)); final JBList libNames = new JBList(variants); - libNames.installCellRenderer(new NotNullFunction() { - @NotNull - @Override - public JComponent fun(Object o) { - return new JLabel(o.toString(), PlatformIcons.JAR_ICON, SwingConstants.LEFT); - } - }); + libNames.installCellRenderer(o -> new JLabel(o.toString(), PlatformIcons.JAR_ICON, SwingConstants.LEFT)); if (libs.size() == 1) { final String jarName = libs.keySet().iterator().next(); final String url = libs.get(jarName); @@ -191,16 +175,13 @@ public abstract class FindJarFix implements IntentionActio JBPopupFactory.getInstance() .createListPopupBuilder(libNames) .setTitle("Select a JAR file") - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = libNames.getSelectedValue(); - if (value instanceof String) { - final String jarName = (String)value; - final String url = libs.get(jarName); - if (url != null) { - initiateDownload(url, jarName); - } + .setItemChoosenCallback(() -> { + final Object value = libNames.getSelectedValue(); + if (value instanceof String) { + final String jarName = (String)value; + final String url = libs.get(jarName); + if (url != null) { + initiateDownload(url, jarName); } } }) diff --git a/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java b/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java index e4b333fde599..43a24fbb65c6 100644 --- a/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java +++ b/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java @@ -61,12 +61,9 @@ public class EnterInJavadocParamDescriptionHandler extends EnterHandlerDelegateA if (editor.offsetToLogicalPosition(offsetAfterLastWs).column < desiredPosition.column) { final int lineStartOffset = document.getLineStartOffset(desiredPosition.line); final String toInsert = StringUtil.repeat(" ", desiredPosition.column - (offsetAfterLastWs - lineStartOffset)); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.insertString(caretOffset, toInsert); - PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.insertString(caretOffset, toInsert); + PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); }); } diff --git a/java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java b/java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java index b18a5b38ef6f..dc858f8fe7f4 100644 --- a/java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java +++ b/java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java @@ -212,15 +212,13 @@ public class JavadocGeneratorRunProfile implements ModuleRunProfile { try { final Collection packages = new HashSet(); final Collection sources = new HashSet(); - final Runnable findRunnable = new Runnable() { - public void run() { - final int scopeType = myGenerationOptions.getScopeType(); - final boolean usePackageNotation = scopeType == AnalysisScope.MODULE || - scopeType == AnalysisScope.MODULES || - scopeType == AnalysisScope.PROJECT || - scopeType == AnalysisScope.DIRECTORY; - myGenerationOptions.accept(new MyContentIterator(myProject, packages, sources, modules, usePackageNotation)); - } + final Runnable findRunnable = () -> { + final int scopeType = myGenerationOptions.getScopeType(); + final boolean usePackageNotation = scopeType == AnalysisScope.MODULE || + scopeType == AnalysisScope.MODULES || + scopeType == AnalysisScope.PROJECT || + scopeType == AnalysisScope.DIRECTORY; + myGenerationOptions.accept(new MyContentIterator(myProject, packages, sources, modules, usePackageNotation)); }; if (!ProgressManager .getInstance() diff --git a/java/java-impl/src/com/intellij/javadoc/JavadocHelper.java b/java/java-impl/src/com/intellij/javadoc/JavadocHelper.java index 3db349967b4f..a1c25c497ae7 100644 --- a/java/java-impl/src/com/intellij/javadoc/JavadocHelper.java +++ b/java/java-impl/src/com/intellij/javadoc/JavadocHelper.java @@ -74,12 +74,9 @@ public class JavadocHelper { final LogicalPosition endLinePosition = editor.offsetToLogicalPosition(endLineOffset); if (endLinePosition.column < position.column && !editor.getSettings().isVirtualSpace() && !editor.isViewer()) { final String toInsert = StringUtil.repeat(" ", position.column - endLinePosition.column); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.insertString(endLineOffset, toInsert); - PsiDocumentManager.getInstance(project).commitDocument(document); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.insertString(endLineOffset, toInsert); + PsiDocumentManager.getInstance(project).commitDocument(document); }); } diff --git a/java/java-impl/src/com/intellij/openapi/projectRoots/JdkPopupAction.java b/java/java-impl/src/com/intellij/openapi/projectRoots/JdkPopupAction.java index dad14c114ef1..827b8e9ac214 100644 --- a/java/java-impl/src/com/intellij/openapi/projectRoots/JdkPopupAction.java +++ b/java/java-impl/src/com/intellij/openapi/projectRoots/JdkPopupAction.java @@ -84,23 +84,14 @@ public class JdkPopupAction extends AnAction { if (!isEnabledInCurrentOS() || component == null) return; - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final ArrayList> jdkLocations = retrieveJDKLocations(); - @Override - public void run() { - final ArrayList> jdkLocations = retrieveJDKLocations(); - - if (jdkLocations.isEmpty()) { - return; - } - - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showPopupMenu(e, jdkLocations, showInMiddle, component); - } - }); + if (jdkLocations.isEmpty()) { + return; } + + ApplicationManager.getApplication().invokeLater(() -> showPopupMenu(e, jdkLocations, showInMiddle, component)); }, "Looking for JDK locations...", false, e.getProject(), component); } diff --git a/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java b/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java index bac9dd1a3951..6c826405fcc7 100644 --- a/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java +++ b/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java @@ -266,18 +266,12 @@ public class JavaSdkImpl extends JavaSdk { } private static void scanFolder(File javasFolder, ArrayList result) { - File[] candidates = javasFolder.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - return JdkUtil.checkForJdk(pathname); - } + File[] candidates = javasFolder.listFiles(pathname -> { + return JdkUtil.checkForJdk(pathname); }); if (candidates != null) { - result.addAll(ContainerUtil.map2List(candidates, new Function() { - @Override - public String fun(File file) { - return file.getAbsolutePath(); - } + result.addAll(ContainerUtil.map2List(candidates, file -> { + return file.getAbsolutePath(); })); } } @@ -553,12 +547,7 @@ public class JavaSdkImpl extends JavaSdk { result.add(vFile); } } - Collections.sort(result, new Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - return o1.getPath().compareTo(o2.getPath()); - } - }); + Collections.sort(result, (o1, o2) -> o1.getPath().compareTo(o2.getPath())); return result; } diff --git a/java/java-impl/src/com/intellij/openapi/roots/impl/LanguageLevelUsagesCollector.java b/java/java-impl/src/com/intellij/openapi/roots/impl/LanguageLevelUsagesCollector.java index 7eda1d20f763..ca4bdc161aeb 100644 --- a/java/java-impl/src/com/intellij/openapi/roots/impl/LanguageLevelUsagesCollector.java +++ b/java/java-impl/src/com/intellij/openapi/roots/impl/LanguageLevelUsagesCollector.java @@ -55,11 +55,8 @@ public class LanguageLevelUsagesCollector extends AbstractApplicationUsagesColle } languageLevels.add(LanguageLevelProjectExtension.getInstance(project).getLanguageLevel().toString()); - return ContainerUtil.map2Set(languageLevels, new Function() { - @Override - public UsageDescriptor fun(String languageLevel) { - return new UsageDescriptor(languageLevel, 1); - } + return ContainerUtil.map2Set(languageLevels, languageLevel -> { + return new UsageDescriptor(languageLevel, 1); }); } } diff --git a/java/java-impl/src/com/intellij/openapi/vcs/contentAnnotation/VcsContentAnnotationExceptionFilter.java b/java/java-impl/src/com/intellij/openapi/vcs/contentAnnotation/VcsContentAnnotationExceptionFilter.java index af31a1f6f64c..450ebf885e07 100644 --- a/java/java-impl/src/com/intellij/openapi/vcs/contentAnnotation/VcsContentAnnotationExceptionFilter.java +++ b/java/java-impl/src/com/intellij/openapi/vcs/contentAnnotation/VcsContentAnnotationExceptionFilter.java @@ -107,12 +107,9 @@ public class VcsContentAnnotationExceptionFilter implements Filter, FilterMixin final int lineEndOffset = copiedFragment.getLineEndOffset(i); final ExceptionWorker worker = new ExceptionWorker(myCache); final String[] lineText = new String[1]; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - lineText[0] = copiedFragment.getText(new TextRange(lineStartOffset, lineEndOffset)); - worker.execute(lineText[0], lineEndOffset); - } + ApplicationManager.getApplication().runReadAction(() -> { + lineText[0] = copiedFragment.getText(new TextRange(lineStartOffset, lineEndOffset)); + worker.execute(lineText[0], lineEndOffset); }); if (worker.getResult() != null) { VirtualFile vf = worker.getFile().getVirtualFile(); diff --git a/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java b/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java index 6a7f23070da2..f2e50bcaa85d 100644 --- a/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java +++ b/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java @@ -162,29 +162,27 @@ public class TreeModelBuilder { } public TreeModel build(final Project project) { - Runnable buildingRunnable = new Runnable() { - public void run() { - countFiles(project); - myFileIndex.iterateContent(new ContentIterator() { - PackageDependenciesNode lastParent; - VirtualFile dir; - public boolean processFile(VirtualFile fileOrDir) { - if (!fileOrDir.isDirectory()) { - if (lastParent != null && !Comparing.equal(dir, fileOrDir.getParent())) { - lastParent = null; - } - lastParent = buildFileNode(fileOrDir, lastParent); - dir = fileOrDir.getParent(); - } else { + Runnable buildingRunnable = () -> { + countFiles(project); + myFileIndex.iterateContent(new ContentIterator() { + PackageDependenciesNode lastParent; + VirtualFile dir; + public boolean processFile(VirtualFile fileOrDir) { + if (!fileOrDir.isDirectory()) { + if (lastParent != null && !Comparing.equal(dir, fileOrDir.getParent())) { lastParent = null; } - return true; + lastParent = buildFileNode(fileOrDir, lastParent); + dir = fileOrDir.getParent(); + } else { + lastParent = null; } - }); - - for (VirtualFile root : LibraryUtil.getLibraryRoots(project)) { - processFilesRecursively(root); + return true; } + }); + + for (VirtualFile root : LibraryUtil.getLibraryRoots(project)) { + processFilesRecursively(root); } }; @@ -242,12 +240,10 @@ public class TreeModelBuilder { myShowFiles = true; } - Runnable buildingRunnable = new Runnable() { - public void run() { - for (final PsiFile file : files) { - if (file != null) { - buildFileNode(file.getVirtualFile(), null); - } + Runnable buildingRunnable = () -> { + for (final PsiFile file : files) { + if (file != null) { + buildFileNode(file.getVirtualFile(), null); } } }; diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java index f042bb316c40..100fa709f79e 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java @@ -168,12 +168,7 @@ public class JavaArrangementParseInfo { public List getOverriddenMethods() { List result = new ArrayList(); final TObjectIntHashMap weights = new TObjectIntHashMap(); - Comparator> comparator = new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return weights.get(o1.first) - weights.get(o2.first); - } - }; + Comparator> comparator = (o1, o2) -> weights.get(o1.first) - weights.get(o2.first); for (Map.Entry>> entry : myOverriddenMethods.entrySet()) { JavaArrangementOverriddenMethodsInfo info = new JavaArrangementOverriddenMethodsInfo(entry.getKey().getName()); weights.clear(); diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java index 6a2e3a630a6f..cac9667abb50 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java @@ -85,13 +85,10 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { myGroupingRules = getGroupingRules(settings); myMethodBodyProcessor = new MethodBodyProcessor(infoHolder); - mySectionDetector = new ArrangementSectionDetector(document, settings, new Consumer() { - @Override - public void consume(ArrangementSectionEntryTemplate data) { - TextRange range = data.getTextRange(); - JavaSectionArrangementEntry entry = new JavaSectionArrangementEntry(getCurrent(), data.getToken(), range, data.getText(), true); - registerEntry(data.getElement(), entry); - } + mySectionDetector = new ArrangementSectionDetector(document, settings, data -> { + TextRange range = data.getTextRange(); + JavaSectionArrangementEntry entry = new JavaSectionArrangementEntry(getCurrent(), data.getToken(), range, data.getText(), true); + registerEntry(data.getElement(), entry); }); } @@ -127,17 +124,14 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { return; } - processChildrenWithinEntryScope(entry, new Runnable() { - @Override - public void run() { - PsiElement current = lBrace; - while (current != rBrace) { - current = current.getNextSibling(); - if (current == null) { - break; - } - current.accept(JavaArrangementVisitor.this); + processChildrenWithinEntryScope(entry, () -> { + PsiElement current = lBrace; + while (current != rBrace) { + current = current.getNextSibling(); + if (current == null) { + break; } + current.accept(JavaArrangementVisitor.this); } }); } @@ -168,16 +162,13 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { if (entry == null) { return; } - processChildrenWithinEntryScope(entry, new Runnable() { - @Override - public void run() { - PsiExpressionList list = aClass.getArgumentList(); - if (list != null && list.getTextLength() > 0) { - JavaElementArrangementEntry listEntry = createNewEntry(list, list.getTextRange(), ANON_CLASS_PARAMETER_LIST, aClass.getName(), true); - processEntry(listEntry, null, list); - } - createAndProcessAnonymousClassBodyEntry(aClass); + processChildrenWithinEntryScope(entry, () -> { + PsiExpressionList list = aClass.getArgumentList(); + if (list != null && list.getTextLength() > 0) { + JavaElementArrangementEntry listEntry = createNewEntry(list, list.getTextRange(), ANON_CLASS_PARAMETER_LIST, aClass.getName(), true); + processEntry(listEntry, null, list); } + createAndProcessAnonymousClassBodyEntry(aClass); }); } @@ -485,12 +476,7 @@ public class JavaArrangementVisitor extends JavaRecursiveElementVisitor { if (nextPsiRoot == null) { return; } - processChildrenWithinEntryScope(entry, new Runnable() { - @Override - public void run() { - nextPsiRoot.acceptChildren(JavaArrangementVisitor.this); - } - }); + processChildrenWithinEntryScope(entry, () -> nextPsiRoot.acceptChildren(JavaArrangementVisitor.this)); } private void processChildrenWithinEntryScope(@NotNull JavaElementArrangementEntry entry, @NotNull Runnable childrenProcessing) { diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/extractor/differ/JavaExtractor.java b/java/java-impl/src/com/intellij/psi/codeStyle/extractor/differ/JavaExtractor.java index 9032144354ca..8846a06dad46 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/extractor/differ/JavaExtractor.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/extractor/differ/JavaExtractor.java @@ -47,14 +47,11 @@ public class JavaExtractor implements LangCodeStyleExtractor { final JavaCodeFragment file = JavaCodeFragmentFactory.getInstance(project). createCodeBlockCodeFragment(myOrigText, myFile, false); - WriteCommandAction.runWriteCommandAction(myProject, "CodeStyleSettings extractor", "CodeStyleSettings extractor", new Runnable() { - @Override - public void run() { - final ASTNode treeElement = SourceTreeToPsiMap.psiElementToTree(file); - assert (treeElement != null); + WriteCommandAction.runWriteCommandAction(myProject, "CodeStyleSettings extractor", "CodeStyleSettings extractor", () -> { + final ASTNode treeElement = SourceTreeToPsiMap.psiElementToTree(file); + assert (treeElement != null); - SourceTreeToPsiMap.treeElementToPsi(new CodeFormatterFacade(mySettings, file.getLanguage()).processElement(treeElement)); - } + SourceTreeToPsiMap.treeElementToPsi(new CodeFormatterFacade(mySettings, file.getLanguage()).processElement(treeElement)); }, file); return file.getText(); } diff --git a/java/java-impl/src/com/intellij/psi/filters/getters/ClassLiteralGetter.java b/java/java-impl/src/com/intellij/psi/filters/getters/ClassLiteralGetter.java index b1b4f674cda7..b806ac57a275 100644 --- a/java/java-impl/src/com/intellij/psi/filters/getters/ClassLiteralGetter.java +++ b/java/java-impl/src/com/intellij/psi/filters/getters/ClassLiteralGetter.java @@ -70,12 +70,7 @@ public class ClassLiteralGetter { return; } - CodeInsightUtil.processSubTypes(classParameter, context, true, matcher, new Consumer() { - @Override - public void consume(PsiType type) { - addClassLiteralLookupElement(type, result, context); - } - }); + CodeInsightUtil.processSubTypes(classParameter, context, true, matcher, type -> addClassLiteralLookupElement(type, result, context)); } private static void addClassLiteralLookupElement(@Nullable final PsiType type, final Consumer resultSet, final PsiFile context) { diff --git a/java/java-impl/src/com/intellij/psi/filters/getters/JavaMembersGetter.java b/java/java-impl/src/com/intellij/psi/filters/getters/JavaMembersGetter.java index 1d84b8e07bb2..32bb9e84f24e 100644 --- a/java/java-impl/src/com/intellij/psi/filters/getters/JavaMembersGetter.java +++ b/java/java-impl/src/com/intellij/psi/filters/getters/JavaMembersGetter.java @@ -64,13 +64,10 @@ public class JavaMembersGetter extends MembersGetter { ContainerUtil.addIfNotNull(classes, field.getContainingClass()); } for (PsiClass aClass : classes) { - processMembers(new Consumer() { - @Override - public void consume(LookupElement element) { - //noinspection SuspiciousMethodCalls - if (!fields.contains(element.getObject())) { - results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON)); - } + processMembers(element -> { + //noinspection SuspiciousMethodCalls + if (!fields.contains(element.getObject())) { + results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON)); } }, aClass, true, false); } diff --git a/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java b/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java index 14f4e7e67731..3d1f97f934ba 100644 --- a/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java +++ b/java/java-impl/src/com/intellij/psi/filters/getters/MembersGetter.java @@ -52,12 +52,7 @@ public abstract class MembersGetter { protected MembersGetter(StaticMemberProcessor processor, @NotNull final PsiElement place) { myPlace = place; - processor.processMembersOfRegisteredClasses(PrefixMatcher.ALWAYS_TRUE, new PairConsumer() { - @Override - public void consume(PsiMember member, PsiClass psiClass) { - myImportedStatically.add(member); - } - }); + processor.processMembersOfRegisteredClasses(PrefixMatcher.ALWAYS_TRUE, (member, psiClass) -> myImportedStatically.add(member)); PsiClass current = PsiTreeUtil.getContextOfType(place, PsiClass.class); while (current != null) { @@ -100,24 +95,21 @@ public abstract class MembersGetter { final GlobalSearchScope scope = myPlace.getResolveScope(); final PsiClassType baseType = JavaPsiFacade.getElementFactory(project).createType(where); - Consumer consumer = new Consumer() { - @Override - public void consume(PsiType psiType) { - PsiClass psiClass = PsiUtil.resolveClassInType(psiType); - if (psiClass == null) { - return; - } - psiClass = CompletionUtil.getOriginalOrSelf(psiClass); - if (mayProcessMembers(psiClass)) { - final FilterScopeProcessor declProcessor = new FilterScopeProcessor(TrueFilter.INSTANCE); - psiClass.processDeclarations(declProcessor, ResolveState.initial(), null, myPlace); - doProcessMembers(acceptMethods, results, psiType == baseType, declProcessor.getResults()); + Consumer consumer = psiType -> { + PsiClass psiClass = PsiUtil.resolveClassInType(psiType); + if (psiClass == null) { + return; + } + psiClass = CompletionUtil.getOriginalOrSelf(psiClass); + if (mayProcessMembers(psiClass)) { + final FilterScopeProcessor declProcessor = new FilterScopeProcessor(TrueFilter.INSTANCE); + psiClass.processDeclarations(declProcessor, ResolveState.initial(), null, myPlace); + doProcessMembers(acceptMethods, results, psiType == baseType, declProcessor.getResults()); - String name = psiClass.getName(); - if (name != null && searchFactoryMethods) { - Collection factoryMethods = JavaStaticMemberTypeIndex.getInstance().getStaticMembers(name, project, scope); - doProcessMembers(acceptMethods, results, false, factoryMethods); - } + String name = psiClass.getName(); + if (name != null && searchFactoryMethods) { + Collection factoryMethods = JavaStaticMemberTypeIndex.getInstance().getStaticMembers(name, project, scope); + doProcessMembers(acceptMethods, results, false, factoryMethods); } } }; diff --git a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImplementationHelperImpl.java b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImplementationHelperImpl.java index 0c49938053f0..328dd72cae64 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImplementationHelperImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/PsiPackageImplementationHelperImpl.java @@ -138,14 +138,11 @@ public class PsiPackageImplementationHelperImpl extends PsiPackageImplementation final Project project = psiPackage.getProject(); ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW); window.activate(null); - window.getActivation().doWhenDone(new Runnable() { - @Override - public void run() { - final ProjectView projectView = ProjectView.getInstance(project); - PsiDirectory[] directories = suggestMostAppropriateDirectories(psiPackage); - if (directories.length == 0) return; - projectView.select(directories[0], directories[0].getVirtualFile(), requestFocus); - } + window.getActivation().doWhenDone(() -> { + final ProjectView projectView = ProjectView.getInstance(project); + PsiDirectory[] directories = suggestMostAppropriateDirectories(psiPackage); + if (directories.length == 0) return; + projectView.select(directories[0], directories[0].getVirtualFile(), requestFocus); }); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java index 7d7e392f55bd..5646b290a4b2 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java @@ -74,12 +74,7 @@ public class ImportHelper{ List nonImports = new ArrayList(); // Note: this array may contain ".*" for unresolved imports! List> names = new ArrayList>(collectNamesToImport(file, nonImports)); - Collections.sort(names, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return o1.getFirst().compareTo(o2.getFirst()); - } - }); + Collections.sort(names, (o1, o2) -> o1.getFirst().compareTo(o2.getFirst())); List> resultList = sortItemsAccordingToSettings(names, mySettings); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java index 923eafebf786..b252a974ea1a 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java @@ -351,14 +351,11 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager { } if (psiClass != null && psiClass.getContainingClass() != null) { - InheritanceUtil.processSupers(psiClass, false, new Processor() { - @Override - public boolean process(PsiClass superClass) { - if (PsiTreeUtil.isAncestor(superClass, psiClass, true)) { - ContainerUtil.addAll(suggestions, getSuggestionsByName(superClass.getName(), variableKind, false, correctKeywords)); - } - return false; + InheritanceUtil.processSupers(psiClass, false, superClass -> { + if (PsiTreeUtil.isAncestor(superClass, psiClass, true)) { + ContainerUtil.addAll(suggestions, getSuggestionsByName(superClass.getName(), variableKind, false, correctKeywords)); } + return false; }); } @@ -666,12 +663,7 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager { PsiMethod method = expr.resolveMethod(); if (method == null) return false; - return isJavaUtilMethod(method) || !MethodDeepestSuperSearcher.processDeepestSuperMethods(method, new Processor() { - @Override - public boolean process(PsiMethod method) { - return !isJavaUtilMethod(method); - } - }); + return isJavaUtilMethod(method) || !MethodDeepestSuperSearcher.processDeepestSuperMethods(method, method1 -> !isJavaUtilMethod(method1)); } private static boolean isJavaUtilMethod(@NotNull PsiMethod method) { @@ -1017,13 +1009,10 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager { } } - Comparator comparator = new Comparator() { - @Override - public int compare(@NotNull String s1, @NotNull String s2) { - int count1 = JavaStatisticsManager.getVariableNameUseCount(s1, variableKind, propertyName, type); - int count2 = JavaStatisticsManager.getVariableNameUseCount(s2, variableKind, propertyName, type); - return count2 - count1; - } + Comparator comparator = (s1, s2) -> { + int count1 = JavaStatisticsManager.getVariableNameUseCount(s1, variableKind, propertyName, type); + int count2 = JavaStatisticsManager.getVariableNameUseCount(s2, variableKind, propertyName, type); + return count2 - count1; }; Arrays.sort(names, comparator); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java index 6ad081b95ff4..007ccb57afdd 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java @@ -147,13 +147,10 @@ public class JavaClassReferenceProvider extends GenericReferenceProvider impleme } private static Collection getSubPackages(final PsiPackage defaultPackage) { - return ContainerUtil.mapNotNull(defaultPackage.getSubPackages(), new NullableFunction() { - @Override - public PsiPackage fun(final PsiPackage psiPackage) { - final String packageName = psiPackage.getName(); - return PsiNameHelper.getInstance(psiPackage.getProject()) - .isIdentifier(packageName, PsiUtil.getLanguageLevel(psiPackage)) ? psiPackage : null; - } + return ContainerUtil.mapNotNull(defaultPackage.getSubPackages(), (NullableFunction)psiPackage -> { + final String packageName = psiPackage.getName(); + return PsiNameHelper.getInstance(psiPackage.getProject()) + .isIdentifier(packageName, PsiUtil.getLanguageLevel(psiPackage)) ? psiPackage : null; }); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PackageReferenceSet.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PackageReferenceSet.java index 36e63c5924c6..f82d67e1e4bb 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PackageReferenceSet.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PackageReferenceSet.java @@ -77,12 +77,8 @@ public class PackageReferenceSet extends ReferenceSetBase { if (packageReference == null) { return Collections.emptyList(); } - return ContainerUtil.map2List(packageReference.multiResolve(false), new NullableFunction() { - @Override - public PsiPackage fun(final ResolveResult resolveResult) { - return (PsiPackage)resolveResult.getElement(); - } - }); + return ContainerUtil.map2List(packageReference.multiResolve(false), + (NullableFunction)resolveResult -> (PsiPackage)resolveResult.getElement()); } public Set getInitialContext() { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PatternPackageReferenceSet.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PatternPackageReferenceSet.java index 72860f50394a..4f42ba7a957f 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PatternPackageReferenceSet.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PatternPackageReferenceSet.java @@ -44,15 +44,12 @@ public class PatternPackageReferenceSet extends PackageReferenceSet { int indexOf = packageName.indexOf("*"); if (indexOf == 0 || context.getQualifiedName().startsWith(packageName.substring(0, indexOf))) { final Pattern pattern = PatternUtil.fromMask(packageName); - processSubPackages(context, new Processor() { - @Override - public boolean process(PsiPackage psiPackage) { - String name = psiPackage.getName(); - if (name != null && pattern.matcher(name).matches()) { - packages.add(psiPackage); - } - return true; + processSubPackages(context, psiPackage -> { + String name = psiPackage.getName(); + if (name != null && pattern.matcher(name).matches()) { + packages.add(psiPackage); } + return true; }); } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java index 195f06fb9cd3..aeee1200fc7e 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java @@ -54,11 +54,8 @@ public class JavaConcatenationInjectorManager extends SimpleModificationTracker unregisterConcatenationInjector(injector); } }); - psiManagerEx.registerRunnableToRunOnAnyChange(new Runnable() { - @Override - public void run() { - incModificationCount(); // clear caches even on non-physical changes - } + psiManagerEx.registerRunnableToRunOnAnyChange(() -> { + incModificationCount(); // clear caches even on non-physical changes }); } diff --git a/java/java-impl/src/com/intellij/psi/refResolve/RefResolveServiceImpl.java b/java/java-impl/src/com/intellij/psi/refResolve/RefResolveServiceImpl.java index 6a486935ebba..e9e4c8f0e262 100644 --- a/java/java-impl/src/com/intellij/psi/refResolve/RefResolveServiceImpl.java +++ b/java/java-impl/src/com/intellij/psi/refResolve/RefResolveServiceImpl.java @@ -124,12 +124,9 @@ public class RefResolveServiceImpl extends RefResolveService implements Runnable } Disposer.register(this, storage); if (!application.isUnitTestMode()) { - startupManager.runWhenProjectIsInitialized(new Runnable() { - @Override - public void run() { - initListeners(messageBus, psiManager); - startThread(); - } + startupManager.runWhenProjectIsInitialized(() -> { + initListeners(messageBus, psiManager); + startThread(); }); } Disposer.register(this, new Disposable() { @@ -173,12 +170,9 @@ public class RefResolveServiceImpl extends RefResolveService implements Runnable @NotNull private static String toVfString(@NotNull Collection list) { List sub = new ArrayList(list).subList(0, Math.min(list.size(), 100)); - return list.size() + " files: " + StringUtil.join(sub, new Function() { - @Override - public String fun(VirtualFile file) { - return file.getName(); - } - }, ", ")+(list.size()==sub.size() ? "" : "..."); + return list.size() + " files: " + StringUtil.join(sub, file -> { + return file.getName(); + }, ", ") + (list.size() == sub.size() ? "" : "..."); } private void initListeners(@NotNull MessageBus messageBus, @NotNull PsiManager psiManager) { @@ -434,35 +428,32 @@ public class RefResolveServiceImpl extends RefResolveService implements Runnable upToDate = false; - myApplication.invokeLater(new Runnable() { - @Override - public void run() { - if (!resolveProcess.isDone()) return; - log("Started to resolve " + files.size() + " files"); + myApplication.invokeLater(() -> { + if (!resolveProcess.isDone()) return; + log("Started to resolve " + files.size() + " files"); - Task.Backgroundable backgroundable = new Task.Backgroundable(myProject, "Resolving files...", false) { - @Override - public void run(@NotNull final ProgressIndicator indicator) { - if (!myApplication.isDisposed()) { - try { - processBatch(indicator, files); - } - catch (RuntimeInterruptedException ignore) { - // see future.cancel() in disable() - } + Task.Backgroundable backgroundable = new Task.Backgroundable(myProject, "Resolving files...", false) { + @Override + public void run(@NotNull final ProgressIndicator indicator) { + if (!myApplication.isDisposed()) { + try { + processBatch(indicator, files); + } + catch (RuntimeInterruptedException ignore) { + // see future.cancel() in disable() } } - }; - ProgressIndicator indicator; - if (files.size() > 1) { - //show progress - indicator = new BackgroundableProcessIndicator(backgroundable); } - else { - indicator = new MyProgress(); - } - resolveProcess = ((ProgressManagerImpl)ProgressManager.getInstance()).runProcessWithProgressAsynchronously(backgroundable, indicator, null); + }; + ProgressIndicator indicator; + if (files.size() > 1) { + //show progress + indicator = new BackgroundableProcessIndicator(backgroundable); } + else { + indicator = new MyProgress(); + } + resolveProcess = ((ProgressManagerImpl)ProgressManager.getInstance()).runProcessWithProgressAsynchronously(backgroundable, indicator, null); }, myProject.getDisposed()); flushLog(); @@ -479,31 +470,28 @@ public class RefResolveServiceImpl extends RefResolveService implements Runnable indicator.setIndeterminate(false); ProgressIndicatorUtils.forceWriteActionPriority(indicator, (Disposable)indicator); long start = System.currentTimeMillis(); - Processor processor = new Processor() { - @Override - public boolean process(VirtualFile file) { - double fraction = 1 - toProcess.size() * 1.0 / totalSize; - indicator.setFraction(fraction); - try { - if (!file.isDirectory() && toResolve(file, myProject)) { - int fileId = getAbsId(file); - int i = totalSize - toProcess.size(); - indicator.setText(i + "/" + totalSize + ": Resolving " + file.getPresentableUrl()); - int[] forwardIds = processFile(file, fileId, indicator); - if (forwardIds == null) { - //queueUpdate(file); - return false; - } - fileToForwardIds.put(fileId, forwardIds); + Processor processor = file -> { + double fraction = 1 - toProcess.size() * 1.0 / totalSize; + indicator.setFraction(fraction); + try { + if (!file.isDirectory() && toResolve(file, myProject)) { + int fileId = getAbsId(file); + int i = totalSize - toProcess.size(); + indicator.setText(i + "/" + totalSize + ": Resolving " + file.getPresentableUrl()); + int[] forwardIds = processFile(file, fileId, indicator); + if (forwardIds == null) { + //queueUpdate(file); + return false; } - toProcess.remove(file); - return true; - } - catch (RuntimeException e) { - indicator.checkCanceled(); + fileToForwardIds.put(fileId, forwardIds); } + toProcess.remove(file); return true; } + catch (RuntimeException e) { + indicator.checkCanceled(); + } + return true; }; boolean success = true; try { @@ -536,50 +524,38 @@ public class RefResolveServiceImpl extends RefResolveService implements Runnable //return JobLauncher.getInstance().invokeConcurrentlyUnderProgress(fileList, indicator, false, false, processor); int parallelism = CacheUpdateRunner.indexingThreadCount(); - final Callable processFileFromSet = new Callable() { - @Override - public Boolean call() throws Exception { - final boolean[] result = {true}; - ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { - @Override - public void run() { - while (true) { - ProgressManager.checkCanceled(); - VirtualFile file; - synchronized (fileList) { - file = fileList.isEmpty() ? null : fileList.remove(fileList.size() - 1); - } - if (file == null) { - break; - } - if (!processor.process(file)) { - result[0] = false; - break; - } - } + final Callable processFileFromSet = () -> { + final boolean[] result = {true}; + ProgressManager.getInstance().executeProcessUnderProgress(() -> { + while (true) { + ProgressManager.checkCanceled(); + VirtualFile file; + synchronized (fileList) { + file = fileList.isEmpty() ? null : fileList.remove(fileList.size() - 1); } - }, indicator); - return result[0]; - } + if (file == null) { + break; + } + if (!processor.process(file)) { + result[0] = false; + break; + } + } + }, indicator); + return result[0]; }; - List> futures = ContainerUtil.map(Collections.nCopies(parallelism, ""), new Function>() { - @Override - public Future fun(String s) { - return myApplication.executeOnPooledThread(processFileFromSet); - } + List> futures = ContainerUtil.map(Collections.nCopies(parallelism, ""), s -> { + return myApplication.executeOnPooledThread(processFileFromSet); }); - List results = ContainerUtil.map(futures, new Function, Boolean>() { - @Override - public Boolean fun(Future future) { - try { - return future.get(); - } - catch (Exception e) { - LOG.error(e); - } - return false; + List results = ContainerUtil.map(futures, future -> { + try { + return future.get(); } + catch (Exception e) { + LOG.error(e); + } + return false; }); return !ContainerUtil.exists(results, new Condition() { @@ -723,18 +699,15 @@ public class RefResolveServiceImpl extends RefResolveService implements Runnable assert forwardSize == backwardSize; // wrap in read action so that sudden quit (in write action) would not interrupt us - myApplication.runReadAction(new Runnable() { - @Override - public void run() { - if (!myApplication.isDisposed()) { - fileToBackwardIds.forEachEntry(new TIntObjectProcedure() { - @Override - public boolean execute(int fileId, TIntArrayList backIds) { - storage.addAll(fileId, backIds.toNativeArray()); - return true; - } - }); - } + myApplication.runReadAction(() -> { + if (!myApplication.isDisposed()) { + fileToBackwardIds.forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(int fileId, TIntArrayList backIds) { + storage.addAll(fileId, backIds.toNativeArray()); + return true; + } + }); } }); } diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiEnter.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiEnter.java index 87b883af1f52..2d72db1372d6 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiEnter.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiEnter.java @@ -42,11 +42,8 @@ public class PsiEnter { } void enter(final PsiClassOwner psiClassOwner) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - enterTopLevels(psiClassOwner); - } + ApplicationManager.getApplication().runReadAction(() -> { + enterTopLevels(psiClassOwner); }); } diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiHierachyConnector.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiHierachyConnector.java index fa6dd6d67372..16397ee6a580 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiHierachyConnector.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/PsiHierachyConnector.java @@ -32,11 +32,8 @@ public class PsiHierachyConnector implements HierarchyConnector { @Override public void connect(final Symbol sym) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - connectInternal((Symbol.ClassSymbol)sym); - } + ApplicationManager.getApplication().runReadAction(() -> { + connectInternal((Symbol.ClassSymbol)sym); }); } diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchy.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchy.java index 953c4b48725a..cfcef07f3d91 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchy.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchy.java @@ -115,18 +115,15 @@ public class SingleClassHierarchy { // compacting result = Arrays.copyOf(result, i); - Arrays.sort(result, new Comparator() { - @Override - public int compare(SmartClassAnchor o1, SmartClassAnchor o2) { - int i1 = o1.myFileId; - int i2 = o2.myFileId; - if (i1 < i2) { - return -1; - } else if (i1 > i2) { - return +1; - } else { - return 0; - } + Arrays.sort(result, (o1, o2) -> { + int i1 = o1.myFileId; + int i2 = o2.myFileId; + if (i1 < i2) { + return -1; + } else if (i1 > i2) { + return +1; + } else { + return 0; } }); return result; diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java index 7127414b5962..912113f7a67d 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java @@ -104,11 +104,8 @@ public class SingleClassHierarchyBuilder { // 1. entering classes LOG.info("read classes start"); indicator.setText("Reading classes"); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - StubIndex.getInstance().processAllKeys(JavaStubIndexKeys.UNITS, myProject, processor); - } + ApplicationManager.getApplication().runReadAction(() -> { + StubIndex.getInstance().processAllKeys(JavaStubIndexKeys.UNITS, myProject, processor); }); indicator.setFraction(classes); testMemory("0"); @@ -124,11 +121,8 @@ public class SingleClassHierarchyBuilder { LOG.info("read sources start"); indicator.setText("Reading sources"); processor.isInSourceMode = true; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - StubIndex.getInstance().processAllKeys(JavaStubIndexKeys.UNITS, myProject, processor); - } + ApplicationManager.getApplication().runReadAction(() -> { + StubIndex.getInstance().processAllKeys(JavaStubIndexKeys.UNITS, myProject, processor); }); indicator.setFraction(classes + completeClasses + sources); diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Symbol.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Symbol.java index 84efec6c2335..3f8f9c0c8bd6 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Symbol.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Symbol.java @@ -149,12 +149,9 @@ public abstract class Symbol { } } - public static final Comparator CLASS_SYMBOL_BY_NAME_COMPARATOR = new Comparator() { - @Override - public int compare(ClassSymbol s1, ClassSymbol s2) { - int name1 = s1.myShortName; - int name2 = s2.myShortName; - return (name1 < name2) ? -1 : ((name1 == name2) ? 0 : 1); - } + public static final Comparator CLASS_SYMBOL_BY_NAME_COMPARATOR = (s1, s2) -> { + int name1 = s1.myShortName; + int name2 = s2.myShortName; + return (name1 < name2) ? -1 : ((name1 == name2) ? 0 : 1); }; } diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/GetAllInheritorsAction.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/GetAllInheritorsAction.java index ca40933c9858..fbaafc038869 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/GetAllInheritorsAction.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/GetAllInheritorsAction.java @@ -39,12 +39,9 @@ public class GetAllInheritorsAction extends InheritanceAction { LOG.info("STARTED Inheritors: " + psiClass.getQualifiedName()); SearchScope scope = psiClass.getUseScope(); final int[] count = new int[]{0}; - ClassInheritorsSearch.search(psiClass, scope, true, true, false).forEach(new Processor() { - @Override - public boolean process(PsiClass psiClass) { - count[0] += 1; - return true; - } + ClassInheritorsSearch.search(psiClass, scope, true, true, false).forEach(psiClass1 -> { + count[0] += 1; + return true; }); LOG.info("FINISHED Inheritors. Found: " + count[0]); } diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/TestStubHierarchyAction.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/TestStubHierarchyAction.java index c841574e8b9d..a91b3a325957 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/TestStubHierarchyAction.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/test/TestStubHierarchyAction.java @@ -58,11 +58,8 @@ public class TestStubHierarchyAction extends InheritanceAction { int size = symbols.myClassAnchors.length; for (int i = 0; i < size; i++) { final int finalI = i; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - test(classes[finalI]); - } + ApplicationManager.getApplication().runReadAction(() -> { + test(classes[finalI]); }); indicator.setFraction(i * 1.0 / (double)size); } diff --git a/java/java-impl/src/com/intellij/psi/util/proximity/JavaInheritanceWeigher.java b/java/java-impl/src/com/intellij/psi/util/proximity/JavaInheritanceWeigher.java index 34265f07112f..9faad94bae48 100644 --- a/java/java-impl/src/com/intellij/psi/util/proximity/JavaInheritanceWeigher.java +++ b/java/java-impl/src/com/intellij/psi/util/proximity/JavaInheritanceWeigher.java @@ -40,12 +40,9 @@ public class JavaInheritanceWeigher extends ProximityWeigher { public Set fun(ProximityLocation location) { final HashSet result = new HashSet(); PsiClass contextClass = PsiTreeUtil.getContextOfType(location.getPosition(), PsiClass.class, false); - Processor processor = new Processor() { - @Override - public boolean process(PsiClass psiClass) { - ContainerUtilRt.addIfNotNull(result, psiClass.getQualifiedName()); - return true; - } + Processor processor = psiClass -> { + ContainerUtilRt.addIfNotNull(result, psiClass.getQualifiedName()); + return true; }; while (contextClass != null) { InheritanceUtil.processSupers(contextClass, true, processor); diff --git a/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java b/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java index 731cefdf02e7..843ba1abacb6 100644 --- a/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java @@ -61,49 +61,38 @@ public class OptimizeImportsRefactoringHelper implements RefactoringHelper> redundants = new HashSet>(); - final Runnable findRedundantImports = new Runnable() { - @Override - public void run() { - DumbService.getInstance(project).runReadActionInSmartMode(new Runnable() { - @Override - public void run() { - final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); - int i = 0; - final int fileCount = javaFiles.size(); - for (PsiJavaFile file : javaFiles) { - if (file.isValid()) { - final VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile != null) { - if (progressIndicator != null) { - progressIndicator.setText2(virtualFile.getPresentableUrl()); - progressIndicator.setFraction((double)i++ / fileCount); - } - final Collection perFile = styleManager.findRedundantImports(file); - if (perFile != null) { - for (PsiImportStatementBase redundant : perFile) { - redundants.add(pointerManager.createSmartPsiElementPointer(redundant)); - } - } - } + final Runnable findRedundantImports = () -> DumbService.getInstance(project).runReadActionInSmartMode(() -> { + final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); + int i = 0; + final int fileCount = javaFiles.size(); + for (PsiJavaFile file : javaFiles) { + if (file.isValid()) { + final VirtualFile virtualFile = file.getVirtualFile(); + if (virtualFile != null) { + if (progressIndicator != null) { + progressIndicator.setText2(virtualFile.getPresentableUrl()); + progressIndicator.setFraction((double)i++ / fileCount); + } + final Collection perFile = styleManager.findRedundantImports(file); + if (perFile != null) { + for (PsiImportStatementBase redundant : perFile) { + redundants.add(pointerManager.createSmartPsiElementPointer(redundant)); } } } - }); + } } - }; + }); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRedundantImports, REMOVING_REDUNDANT_IMPORTS_TITLE, false, project)) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, REMOVING_REDUNDANT_IMPORTS_TITLE, false); - progressTask.setMinIterationTime(200); - progressTask.setTask(new OptimizeImportsTask(progressTask, redundants)); - ProgressManager.getInstance().run(progressTask); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, REMOVING_REDUNDANT_IMPORTS_TITLE, false); + progressTask.setMinIterationTime(200); + progressTask.setTask(new OptimizeImportsTask(progressTask, redundants)); + ProgressManager.getInstance().run(progressTask); }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerDialog.java b/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerDialog.java index ad2a88c025a3..005997bd69d4 100644 --- a/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerDialog.java @@ -87,18 +87,16 @@ class AnonymousToInnerDialog extends DialogWrapper{ String name = myAnonClass.getBaseClassReference().getReferenceName(); PsiType[] typeParameters = myAnonClass.getBaseClassReference().getTypeParameters(); - final String typeParamsList = StringUtil.join(typeParameters, new Function() { - public String fun(PsiType psiType) { - PsiType type = psiType; - if (psiType instanceof PsiClassType) { - type = TypeConversionUtil.erasure(psiType); - } - if (type == null || type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return ""; - if (type instanceof PsiArrayType) { - type = type.getDeepComponentType(); - } - return StringUtil.getShortName(type.getPresentableText()); + final String typeParamsList = StringUtil.join(typeParameters, psiType -> { + PsiType type = psiType; + if (psiType instanceof PsiClassType) { + type = TypeConversionUtil.erasure(psiType); } + if (type == null || type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return ""; + if (type instanceof PsiArrayType) { + type = type.getDeepComponentType(); + } + return StringUtil.getShortName(type.getPresentableText()); }, "") + name; if (!typeParamsList.equals(name)) { diff --git a/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java b/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java index aed5ded1af1b..a3cb2f3e3260 100644 --- a/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java @@ -118,39 +118,32 @@ public class AnonymousToInnerHandler implements RefactoringActionHandler { collectUsedVariables(variableInfoMap, myAnonClass); final VariableInfo[] infos = variableInfoMap.values().toArray(new VariableInfo[variableInfoMap.values().size()]); myVariableInfos = infos; - Arrays.sort(myVariableInfos, new Comparator() { - @Override - public int compare(VariableInfo o1, VariableInfo o2) { - final PsiType type1 = o1.variable.getType(); - final PsiType type2 = o2.variable.getType(); - if (type1 instanceof PsiEllipsisType) { - return 1; - } - if (type2 instanceof PsiEllipsisType) { - return -1; - } - return ArrayUtil.find(infos, o1) > ArrayUtil.find(infos, o2) ? 1 : -1; + Arrays.sort(myVariableInfos, (o1, o2) -> { + final PsiType type1 = o1.variable.getType(); + final PsiType type2 = o2.variable.getType(); + if (type1 instanceof PsiEllipsisType) { + return 1; } + if (type2 instanceof PsiEllipsisType) { + return -1; + } + return ArrayUtil.find(infos, o1) > ArrayUtil.find(infos, o2) ? 1 : -1; }); if (!showRefactoringDialog()) return; CommandProcessor.getInstance().executeCommand( - myProject, new Runnable() { - public void run() { - final Runnable action = new Runnable() { - public void run() { - try { - doRefactoring(); - } catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }; - ApplicationManager.getApplication().runWriteAction(action); - } - }, - REFACTORING_NAME, - null + myProject, () -> { + final Runnable action = () -> { + try { + doRefactoring(); + } catch (IncorrectOperationException e) { + LOG.error(e); + } + }; + ApplicationManager.getApplication().runWriteAction(action); + }, + REFACTORING_NAME, + null ); } @@ -408,11 +401,7 @@ public class AnonymousToInnerHandler implements RefactoringActionHandler { } } - Collections.sort(toAdd, new Comparator() { - public int compare(PsiElement e1, PsiElement e2) { - return e1.getTextRange().getStartOffset() - e2.getTextRange().getStartOffset(); - } - }); + Collections.sort(toAdd, (e1, e2) -> e1.getTextRange().getStartOffset() - e2.getTextRange().getStartOffset()); for (PsiElement element : toAdd) { if (element instanceof PsiClassInitializer) { diff --git a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureDialog.java b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureDialog.java index e6b143497da7..5c672d1af986 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureDialog.java @@ -156,12 +156,7 @@ public class ChangeClassSignatureDialog extends RefactoringDialog { final TableColumnAnimator animator = new TableColumnAnimator(myTable); animator.setStep(20); animator.addColumn(defaultValue, myTable.getWidth() / 2); - animator.startAndDoWhenDone(new Runnable() { - @Override - public void run() { - myTable.editCellAt(myTable.getRowCount() - 1, 0); - } - }); + animator.startAndDoWhenDone(() -> myTable.editCellAt(myTable.getRowCount() - 1, 0)); animator.start(); } } diff --git a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/TypeParameterInfo.java b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/TypeParameterInfo.java index 3d83b388f104..5ecda1c11d86 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/TypeParameterInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/TypeParameterInfo.java @@ -90,11 +90,8 @@ public interface TypeParameterInfo { private static String getCanonicalText(PsiType boundType) { if (boundType instanceof PsiIntersectionType) { - return StringUtil.join(ContainerUtil.map(((PsiIntersectionType)boundType).getConjuncts(), new Function() { - @Override - public String fun(PsiType type) { - return type.getCanonicalText(); - } + return StringUtil.join(ContainerUtil.map(((PsiIntersectionType)boundType).getConjuncts(), type -> { + return type.getCanonicalText(); }), " & "); } return boundType.getCanonicalText(); diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/DetectedJavaChangeInfo.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/DetectedJavaChangeInfo.java index 81c6acf4d4e6..9c9cde121bbc 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/DetectedJavaChangeInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/DetectedJavaChangeInfo.java @@ -287,12 +287,9 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl { @Override protected void invokeRefactoring(final BaseRefactoringProcessor processor) { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - temporallyRevertChanges(method, oldText); - doRefactor(processor); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + temporallyRevertChanges(method, oldText); + doRefactor(processor); }, RefactoringBundle.message("changing.signature.of.0", DescriptiveNameUtil.getDescriptiveName(currentMethod)), null); } @@ -310,16 +307,13 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl { private static void temporallyRevertChanges(final PsiElement psiElement, final String oldText, final TextRange textRange) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final PsiFile file = psiElement.getContainingFile(); - final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiElement.getProject()); - final Document document = documentManager.getDocument(file); - if (document != null) { - document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), oldText); - documentManager.commitDocument(document); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final PsiFile file = psiElement.getContainingFile(); + final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiElement.getProject()); + final Document document = documentManager.getDocument(file); + if (document != null) { + document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), oldText); + documentManager.commitDocument(document); } }); } diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java index 479b69964da6..11fd628bf091 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java @@ -182,12 +182,9 @@ public class JavaChangeSignatureDialog extends ChangeSignatureDialogBase chooser = new Ref(); - Consumer> callback = new Consumer>() { - @Override - public void consume(Set psiMethods) { - myMethodsToPropagateExceptions = psiMethods; - myExceptionPropagationTree = chooser.get().getTree(); - } + Consumer> callback = psiMethods -> { + myMethodsToPropagateExceptions = psiMethods; + myExceptionPropagationTree = chooser.get().getTree(); }; chooser.set(new JavaCallerChooser(myMethod.getMethod(), myProject, @@ -455,12 +452,7 @@ public class JavaChangeSignatureDialog extends ChangeSignatureDialogBase t.editCellAt(t.getRowCount() - 1, 0)); animator.start(); } } diff --git a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java index 1743d08030f4..47e70cd0b247 100644 --- a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java @@ -268,50 +268,39 @@ public class CopyClassesHandler extends CopyHandlerDelegateBase { final boolean selectInActivePanel, final boolean openInEditor) { final boolean[] result = new boolean[] {false}; - Runnable command = new Runnable() { - public void run() { - final Runnable action = new Runnable() { - public void run() { - try { - PsiDirectory target; - if (targetDirectory instanceof PsiDirectory) { - target = (PsiDirectory)targetDirectory; - } else { - target = ((MoveDestination)targetDirectory).getTargetDirectory(defaultTargetDirectory); - } - Collection files = doCopyClasses(classes, map, copyClassName, target, project); - if (files != null) { - if (openInEditor) { - for (PsiFile file : files) { - CopyHandler.updateSelectionInActiveProjectView(file, project, selectInActivePanel); - } - EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()])); - } - - result[0] = true; - } - } - catch (final IncorrectOperationException ex) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Messages.showMessageDialog(project, ex.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon()); - } - }); - } + Runnable command = () -> { + final Runnable action = () -> { + try { + PsiDirectory target; + if (targetDirectory instanceof PsiDirectory) { + target = (PsiDirectory)targetDirectory; + } else { + target = ((MoveDestination)targetDirectory).getTargetDirectory(defaultTargetDirectory); } - }; - ApplicationManager.getApplication().runWriteAction(action); - } + Collection files = doCopyClasses(classes, map, copyClassName, target, project); + if (files != null) { + if (openInEditor) { + for (PsiFile file : files) { + CopyHandler.updateSelectionInActiveProjectView(file, project, selectInActivePanel); + } + EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()])); + } + + result[0] = true; + } + } + catch (final IncorrectOperationException ex) { + ApplicationManager.getApplication().invokeLater( + () -> Messages.showMessageDialog(project, ex.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon())); + } + }; + ApplicationManager.getApplication().runWriteAction(action); }; CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand(project, command, commandName, null); if (result[0]) { - ToolWindowManager.getInstance(project).invokeLater(new Runnable() { - public void run() { - ToolWindowManager.getInstance(project).activateEditorComponent(); - } - }); + ToolWindowManager.getInstance(project).invokeLater(() -> ToolWindowManager.getInstance(project).activateEditorComponent()); } } diff --git a/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceHandler.java b/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceHandler.java index 6188ef3f6712..b65b9fafbd6a 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractInterfaceHandler.java @@ -92,24 +92,18 @@ public class ExtractInterfaceHandler implements RefactoringActionHandler, Elemen final MultiMap conflicts = new MultiMap(); ExtractSuperClassUtil.checkSuperAccessible(dialog.getTargetDirectory(), conflicts, myClass); if (!ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject)) return; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myInterfaceName = dialog.getExtractedSuperName(); - mySelectedMembers = ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class); - myTargetDir = dialog.getTargetDirectory(); - myJavaDocPolicy = new DocCommentPolicy(dialog.getDocCommentPolicy()); - try { - doRefactoring(); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + myInterfaceName = dialog.getExtractedSuperName(); + mySelectedMembers = ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class); + myTargetDir = dialog.getTargetDirectory(); + myJavaDocPolicy = new DocCommentPolicy(dialog.getDocCommentPolicy()); + try { + doRefactoring(); } - }, REFACTORING_NAME, null); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), REFACTORING_NAME, null); } @@ -126,12 +120,7 @@ public class ExtractInterfaceHandler implements RefactoringActionHandler, Elemen if (anInterface != null) { final SmartPsiElementPointer classPointer = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(myClass); final SmartPsiElementPointer interfacePointer = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(anInterface); - final Runnable turnRefsToSuperRunnable = new Runnable() { - @Override - public void run() { - ExtractClassUtil.askAndTurnRefsToSuper(myProject, classPointer, interfacePointer); - } - }; + final Runnable turnRefsToSuperRunnable = () -> ExtractClassUtil.askAndTurnRefsToSuper(myProject, classPointer, interfacePointer); SwingUtilities.invokeLater(turnRefsToSuperRunnable); } } diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java index 11df15fbd9ac..455f8ca123ff 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ControlFlowWrapper.java @@ -264,16 +264,14 @@ public class ControlFlowWrapper { myInputVariables = inputVariableList; } //varargs variables go last, otherwise order is induced by original ordering - Collections.sort(myInputVariables, new Comparator() { - public int compare(final PsiVariable v1, final PsiVariable v2) { - if (v1.getType() instanceof PsiEllipsisType) { - return 1; - } - if (v2.getType() instanceof PsiEllipsisType) { - return -1; - } - return v1.getTextOffset() - v2.getTextOffset(); + Collections.sort(myInputVariables, (v1, v2) -> { + if (v1.getType() instanceof PsiEllipsisType) { + return 1; } + if (v2.getType() instanceof PsiEllipsisType) { + return -1; + } + return v1.getTextOffset() - v2.getTextOffset(); }); return myInputVariables; } diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java index 9e146ce1d3b8..375d7a66964b 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java @@ -165,28 +165,23 @@ public class ExtractMethodHandler implements RefactoringActionHandler, ContextAw } public static void run(@NotNull final Project project, final Editor editor, final ExtractMethodProcessor processor) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() { - public void run() { - try { - final RefactoringEventData beforeData = new RefactoringEventData(); - beforeData.addElements(processor.myElements); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted("refactoring.extract.method", beforeData); - - processor.doRefactoring(); + CommandProcessor.getInstance().executeCommand(project, + () -> PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(() -> { + try { + final RefactoringEventData beforeData = new RefactoringEventData(); + beforeData.addElements(processor.myElements); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted("refactoring.extract.method", beforeData); - final RefactoringEventData data = new RefactoringEventData(); - data.addElement(processor.getExtractedMethod()); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone("refactoring.extract.method", data); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); - } - }, REFACTORING_NAME, null); + processor.doRefactoring(); + + final RefactoringEventData data = new RefactoringEventData(); + data.addElement(processor.getExtractedMethod()); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone("refactoring.extract.method", data); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), REFACTORING_NAME, null); } @Nullable diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java index afc0bbb0df36..b595c3e67d34 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java @@ -462,20 +462,18 @@ public class ExtractMethodProcessor implements MatchProvider { final boolean classExtracted = isExtractedElement(localClass); final List extractedReferences = Collections.synchronizedList(new ArrayList()); final List remainingReferences = Collections.synchronizedList(new ArrayList()); - ReferencesSearch.search(localClass).forEach(new Processor() { - public boolean process(final PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - final boolean elementExtracted = isExtractedElement(element); - if (elementExtracted && !classExtracted) { - extractedReferences.add(element); - return false; - } - if (!elementExtracted && classExtracted) { - remainingReferences.add(element); - return false; - } - return true; + ReferencesSearch.search(localClass).forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + final boolean elementExtracted = isExtractedElement(element); + if (elementExtracted && !classExtracted) { + extractedReferences.add(element); + return false; } + if (!elementExtracted && classExtracted) { + remainingReferences.add(element); + return false; + } + return true; }); if (!extractedReferences.isEmpty()) { throw new PrepareFailedException("Cannot extract method because the selected code fragment uses local classes defined outside of the fragment", extractedReferences.get(0)); @@ -620,11 +618,8 @@ public class ExtractMethodProcessor implements MatchProvider { return statement instanceof PsiReturnStatement && ((PsiReturnStatement)statement).getReturnValue() != null; } }); - final List map = ContainerUtil.map(filter, new Function() { - @Override - public PsiExpression fun(PsiStatement statement) { - return ((PsiReturnStatement)statement).getReturnValue(); - } + final List map = ContainerUtil.map(filter, statement -> { + return ((PsiReturnStatement)statement).getReturnValue(); }); return map.toArray(new PsiExpression[map.size()]); } @@ -672,16 +667,13 @@ public class ExtractMethodProcessor implements MatchProvider { final String nameByComment = getNameByComment(); final PsiField field = JavaPsiFacade.getElementFactory(myProject).createField("fieldNameToReplace", myReturnType instanceof PsiEllipsisType ? ((PsiEllipsisType)myReturnType).toArrayType() : myReturnType); - final List getters = new ArrayList(ContainerUtil.map(initialMethodNames, new Function() { - @Override - public String fun(String propertyName) { - if (!PsiNameHelper.getInstance(myProject).isIdentifier(propertyName)) { - LOG.info(propertyName + "; " + myExpression); - return null; - } - field.setName(propertyName); - return GenerateMembersUtil.suggestGetterName(field); + final List getters = new ArrayList(ContainerUtil.map(initialMethodNames, propertyName -> { + if (!PsiNameHelper.getInstance(myProject).isIdentifier(propertyName)) { + LOG.info(propertyName + "; " + myExpression); + return null; } + field.setName(propertyName); + return GenerateMembersUtil.suggestGetterName(field); })); ContainerUtil.addIfNotNull(nameByComment, getters); return ArrayUtil.toStringArray(getters); @@ -790,22 +782,14 @@ public class ExtractMethodProcessor implements MatchProvider { GlobalSearchScope.projectScope(myProject); final Map overloadsResolveMap = new HashMap(); - final Runnable collectOverloads = new Runnable() { - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - Map overloads = - ExtractMethodUtil.encodeOverloadTargets(myTargetClass, processConflictsScope, myMethodName, myCodeFragmentMember); - overloadsResolveMap.putAll(overloads); - } - }); - } - }; - final Runnable extract = new Runnable() { - public void run() { - doExtract(); - ExtractMethodUtil.decodeOverloadTargets(overloadsResolveMap, myExtractedMethod, myCodeFragmentMember); - } + final Runnable collectOverloads = () -> ApplicationManager.getApplication().runReadAction(() -> { + Map overloads = + ExtractMethodUtil.encodeOverloadTargets(myTargetClass, processConflictsScope, myMethodName, myCodeFragmentMember); + overloadsResolveMap.putAll(overloads); + }); + final Runnable extract = () -> { + doExtract(); + ExtractMethodUtil.decodeOverloadTargets(overloadsResolveMap, myExtractedMethod, myCodeFragmentMember); }; if (ApplicationManager.getApplication().isWriteAccessAllowed()) { collectOverloads.run(); diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodSignatureSuggester.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodSignatureSuggester.java index c6d73d3df141..94acdf4abe43 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodSignatureSuggester.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodSignatureSuggester.java @@ -96,12 +96,9 @@ public class ExtractMethodSignatureSuggester { if (ApplicationManager.getApplication().isUnitTestMode() || new PreviewDialog(method, myExtractedMethod, methodCall, myMethodCall, duplicates.size()).showAndGet()) { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { - @Override - public void run() { - myMethodCall = (PsiMethodCallExpression)methodCall.replace(myMethodCall); - myExtractedMethod = (PsiMethod)method.replace(myExtractedMethod); - } + WriteCommandAction.runWriteCommandAction(myProject, () -> { + myMethodCall = (PsiMethodCallExpression)methodCall.replace(myMethodCall); + myExtractedMethod = (PsiMethod)method.replace(myExtractedMethod); }); final DuplicatesFinder finder = MethodDuplicatesHandler.createDuplicatesFinder(myExtractedMethod); diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractLightMethodObjectHandler.java b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractLightMethodObjectHandler.java index 0b4d34fb3531..b69b8a604381 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractLightMethodObjectHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractLightMethodObjectHandler.java @@ -174,12 +174,7 @@ public class ExtractLightMethodObjectHandler { }); - final String outputVariables = StringUtil.join(variables, new Function() { - @Override - public String fun(PsiVariable variable) { - return "\"variable: \" + " + variable.getName(); - } - }, " +"); + final String outputVariables = StringUtil.join(variables, variable -> "\"variable: \" + " + variable.getName(), " +"); PsiStatement outStatement = elementFactory.createStatementFromText("System.out.println(" + outputVariables + ");", anchor); outStatement = (PsiStatement)container.addAfter(outStatement, elementsCopy[elementsCopy.length - 1]); diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectDialog.java b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectDialog.java index be4e56dc2119..d148cf645d4e 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectDialog.java @@ -367,11 +367,7 @@ public class ExtractMethodObjectDialog extends DialogWrapper implements Abstract buffer.append("\n}."); buffer.append(myMethodName.getText()); buffer.append("("); - buffer.append(StringUtil.join(myInputVariables, new Function() { - public String fun(final VariableData variableData) { - return variableData.name; - } - }, ", ")); + buffer.append(StringUtil.join(myInputVariables, variableData -> variableData.name, ", ")); buffer.append(")"); } diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectHandler.java b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectHandler.java index 911c55047624..9c5292388fb1 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectHandler.java @@ -100,56 +100,40 @@ public class ExtractMethodObjectHandler implements RefactoringActionHandler, Con } else { marker = null; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() { - public void run() { - try { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - extractProcessor.doRefactoring(); - } - }); - processor.run(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - processor.runChangeSignature(); - } - }); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + CommandProcessor.getInstance().executeCommand(project, + () -> PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(() -> { + try { + ApplicationManager.getApplication().runWriteAction(() -> { + extractProcessor.doRefactoring(); + }); + processor.run(); + ApplicationManager.getApplication().runWriteAction(() -> { + processor.runChangeSignature(); + }); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } - PsiDocumentManager.getInstance(project).commitAllDocuments(); - if (processor.isCreateInnerClass()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - processor.moveUsedMethodsToInner(); - } - }); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - if (editor != null) { - DuplicatesImpl.processDuplicates(extractProcessor, project, editor); - } - } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (processor.isCreateInnerClass()) { - processor.changeInstanceAccess(project); - } - final PsiElement method = processor.getMethod(); - LOG.assertTrue(method != null); - method.delete(); - } - }); - } - }); - } - }, ExtractMethodObjectProcessor.REFACTORING_NAME, ExtractMethodObjectProcessor.REFACTORING_NAME); + PsiDocumentManager.getInstance(project).commitAllDocuments(); + if (processor.isCreateInnerClass()) { + ApplicationManager.getApplication().runWriteAction(() -> { + processor.moveUsedMethodsToInner(); + }); + PsiDocumentManager.getInstance(project).commitAllDocuments(); + if (editor != null) { + DuplicatesImpl.processDuplicates(extractProcessor, project, editor); + } + } + ApplicationManager.getApplication().runWriteAction(() -> { + if (processor.isCreateInnerClass()) { + processor.changeInstanceAccess(project); + } + final PsiElement method = processor.getMethod(); + LOG.assertTrue(method != null); + method.delete(); + }); + }), ExtractMethodObjectProcessor.REFACTORING_NAME, ExtractMethodObjectProcessor.REFACTORING_NAME); if (editor != null) { editor.getCaretModel().moveToOffset(marker.getStartOffset()); marker.dispose(); diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java index 5bb01dbda9d0..d96332336342 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java @@ -182,11 +182,9 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor { if (myMultipleExitPoints) { addOutputVariableFieldsWithGetters(); } - myCopyMethodToInner = new Runnable() { - public void run() { - copyMethodWithoutParameters(); - copyMethodTypeParameters(); - } + myCopyMethodToInner = () -> { + copyMethodWithoutParameters(); + copyMethodTypeParameters(); }; } else { for (UsageInfo usage : usages) { @@ -232,13 +230,11 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor { } }; if (dlg.showAndGet()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - for (MemberInfoBase memberInfo : panel.getTable().getSelectedMemberInfos()) { - if (memberInfo.isChecked()) { - myInnerClass.add(memberInfo.getMember().copy()); - memberInfo.getMember().delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (MemberInfoBase memberInfo : panel.getTable().getSelectedMemberInfos()) { + if (memberInfo.isChecked()) { + myInnerClass.add(memberInfo.getMember().copy()); + memberInfo.getMember().delete(); } } }); @@ -420,13 +416,11 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor { public PsiExpression processMethodDeclaration( PsiExpressionList expressionList) throws IncorrectOperationException { if (isCreateInnerClass()) { final String typeArguments = getMethod().hasTypeParameters() ? "<" + StringUtil.join(Arrays.asList(getMethod().getTypeParameters()), - new Function() { - public String fun(final PsiTypeParameter typeParameter) { - final String typeParameterName = - typeParameter.getName(); - LOG.assertTrue(typeParameterName != null); - return typeParameterName; - } + typeParameter -> { + final String typeParameterName = + typeParameter.getName(); + LOG.assertTrue(typeParameterName != null); + return typeParameterName; }, ", ") + ">" : ""; final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)myElementFactory.createExpressionFromText("invoke" + expressionList.getText(), null); diff --git a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperClassUtil.java b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperClassUtil.java index 7e6b86b732a8..28d9bb93c06a 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperClassUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperClassUtil.java @@ -268,12 +268,7 @@ public class ExtractSuperClassUtil { public static RefactoringEventData createBeforeData(final PsiClass subclassClass, final MemberInfo[] members) { RefactoringEventData data = new RefactoringEventData(); data.addElement(subclassClass); - data.addMembers(members, new Function() { - @Override - public PsiElement fun(MemberInfo info) { - return info.getMember(); - } - }); + data.addMembers(members, info -> info.getMember()); return data; } diff --git a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java index 815f9450a8dc..db102a468441 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java @@ -111,17 +111,9 @@ public class ExtractSuperclassHandler implements RefactoringActionHandler, Extra return; } - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final Runnable action = new Runnable() { - @Override - public void run() { - doRefactoring(project, mySubclass, dialog); - } - }; - ApplicationManager.getApplication().runWriteAction(action); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final Runnable action = () -> doRefactoring(project, mySubclass, dialog); + ApplicationManager.getApplication().runWriteAction(action); }, REFACTORING_NAME, null); } @@ -137,20 +129,12 @@ public class ExtractSuperclassHandler implements RefactoringActionHandler, Extra targetPackage = null; } final MultiMap conflicts = new MultiMap(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiClass superClass = - mySubclass.getExtendsListTypes().length > 0 || mySubclass instanceof PsiAnonymousClass ? mySubclass.getSuperClass() : null; - conflicts.putAllValues(PullUpConflictsUtil.checkConflicts(infos, mySubclass, superClass, targetPackage, targetDirectory, - dialog.getContainmentVerifier(), false)); - } - }); - } - }, RefactoringBundle.message("detecting.possible.conflicts"), true, myProject)) return false; + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass superClass = + mySubclass.getExtendsListTypes().length > 0 || mySubclass instanceof PsiAnonymousClass ? mySubclass.getSuperClass() : null; + conflicts.putAllValues(PullUpConflictsUtil.checkConflicts(infos, mySubclass, superClass, targetPackage, targetDirectory, + dialog.getContainmentVerifier(), false)); + }), RefactoringBundle.message("detecting.possible.conflicts"), true, myProject)) return false; ExtractSuperClassUtil.checkSuperAccessible(targetDirectory, conflicts, mySubclass); return ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject); } @@ -177,12 +161,7 @@ public class ExtractSuperclassHandler implements RefactoringActionHandler, Extra if (superclass != null) { final SmartPsiElementPointer classPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(subclass); final SmartPsiElementPointer interfacePointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(superclass); - final Runnable turnRefsToSuperRunnable = new Runnable() { - @Override - public void run() { - ExtractClassUtil.askAndTurnRefsToSuper(project, classPointer, interfacePointer); - } - }; + final Runnable turnRefsToSuperRunnable = () -> ExtractClassUtil.askAndTurnRefsToSuper(project, classPointer, interfacePointer); SwingUtilities.invokeLater(turnRefsToSuperRunnable); } } diff --git a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassDialog.java b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassDialog.java index e2a6657c34c4..52aa755b89f1 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassDialog.java @@ -143,11 +143,7 @@ class ExtractClassDialog extends RefactoringDialog implements MemberInfoChangeLi final String newClassName = getClassName(); final String packageName = getPackageName(); - Collections.sort(enumConstants, new Comparator() { - public int compare(MemberInfo o1, MemberInfo o2) { - return o1.getMember().getTextOffset() - o2.getMember().getTextOffset(); - } - }); + Collections.sort(enumConstants, (o1, o2) -> o1.getMember().getTextOffset() - o2.getMember().getTextOffset()); final ExtractClassProcessor processor = new ExtractClassProcessor(sourceClass, fields, methods, classes, packageName, myDestinationFolderComboBox.selectDirectory( new PackageWrapper(PsiManager.getInstance(myProject), packageName), diff --git a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java index 944100216317..c2a652dc08c6 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java @@ -163,10 +163,8 @@ public class ExtractClassProcessor extends FixableUsagesRefactoringProcessor { myClass.getContainingFile().getContainingDirectory().getVirtualFile())) { conflicts.putValue(sourceClass, "Extracted class won't be accessible in " + RefactoringUIUtil.getDescription(sourceClass, true)); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myClass.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myClass.delete(); }); final Project project = sourceClass.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); diff --git a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java index 4e42bd3cab93..b87f16f5165d 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java +++ b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java @@ -257,16 +257,14 @@ class ExtractedClassBuilder { private void outputFieldsAndInitializers(final StringBuffer out, boolean normalizeDeclaration) { if (hasEnumConstants()) { - out.append(StringUtil.join(enumConstantFields, new Function() { - public String fun(PsiField field) { - final StringBuffer fieldStr = new StringBuffer(field.getName() + "("); - final PsiExpression initializer = field.getInitializer(); - if (initializer != null) { - initializer.accept(new Mutator(fieldStr)); - } - fieldStr.append(")"); - return fieldStr.toString(); + out.append(StringUtil.join(enumConstantFields, field -> { + final StringBuffer fieldStr = new StringBuffer(field.getName() + "("); + final PsiExpression initializer = field.getInitializer(); + if (initializer != null) { + initializer.accept(new Mutator(fieldStr)); } + fieldStr.append(")"); + return fieldStr.toString(); }, ", ")); out.append(";"); } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java index cd0f28c6aa4d..afd0e3f65dc5 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java @@ -88,27 +88,25 @@ public class InlineLocalHandler extends JavaInlineActionHandler { final PsiClass containingClass = PsiTreeUtil.getParentOfType(local, PsiClass.class); final List innerClassesWithUsages = Collections.synchronizedList(new ArrayList()); final List innerClassUsages = Collections.synchronizedList(new ArrayList()); - query.forEach(new Processor() { - public boolean process(final PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - PsiElement innerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class, PsiLambdaExpression.class); - while (innerClass != containingClass && innerClass != null) { - final PsiClass parentPsiClass = PsiTreeUtil.getParentOfType(innerClass, PsiClass.class, true); - if (parentPsiClass == containingClass) { - if (innerClass instanceof PsiLambdaExpression) { - if (PsiTreeUtil.isAncestor(innerClass, local, false)) { - innerClassesWithUsages.add(element); - innerClass = parentPsiClass; - continue; - } + query.forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + PsiElement innerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class, PsiLambdaExpression.class); + while (innerClass != containingClass && innerClass != null) { + final PsiClass parentPsiClass = PsiTreeUtil.getParentOfType(innerClass, PsiClass.class, true); + if (parentPsiClass == containingClass) { + if (innerClass instanceof PsiLambdaExpression) { + if (PsiTreeUtil.isAncestor(innerClass, local, false)) { + innerClassesWithUsages.add(element); + innerClass = parentPsiClass; + continue; } - innerClassesWithUsages.add(innerClass); - innerClassUsages.add(element); } - innerClass = parentPsiClass; + innerClassesWithUsages.add(innerClass); + innerClassUsages.add(element); } - return true; + innerClass = parentPsiClass; } + return true; }); final PsiCodeBlock containerBlock = PsiTreeUtil.getParentOfType(local, PsiCodeBlock.class); @@ -230,65 +228,55 @@ public class InlineLocalHandler extends JavaInlineActionHandler { return; } - final Runnable runnable = new Runnable() { - public void run() { - final String refactoringId = "refactoring.inline.local.variable"; - try{ - SmartPsiElementPointer[] exprs = new SmartPsiElementPointer[refsToInline.length]; + final Runnable runnable = () -> { + final String refactoringId = "refactoring.inline.local.variable"; + try{ + SmartPsiElementPointer[] exprs = new SmartPsiElementPointer[refsToInline.length]; - RefactoringEventData beforeData = new RefactoringEventData(); - beforeData.addElements(refsToInline); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData); + RefactoringEventData beforeData = new RefactoringEventData(); + beforeData.addElements(refsToInline); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData); - final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); - for(int idx = 0; idx < refsToInline.length; idx++){ - PsiJavaCodeReferenceElement refElement = (PsiJavaCodeReferenceElement)refsToInline[idx]; - exprs[idx] = pointerManager.createSmartPsiElementPointer(InlineUtil.inlineVariable(local, defToInline, refElement)); + final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); + for(int idx = 0; idx < refsToInline.length; idx++){ + PsiJavaCodeReferenceElement refElement = (PsiJavaCodeReferenceElement)refsToInline[idx]; + exprs[idx] = pointerManager.createSmartPsiElementPointer(InlineUtil.inlineVariable(local, defToInline, refElement)); + } + + if (inlineAll.get()) { + if (!isInliningVariableInitializer(defToInline)) { + defToInline.getParent().delete(); + } else { + defToInline.delete(); } - if (inlineAll.get()) { - if (!isInliningVariableInitializer(defToInline)) { - defToInline.getParent().delete(); - } else { - defToInline.delete(); - } - - if (ReferencesSearch.search(local).findFirst() == null) { - QuickFixFactory.getInstance().createRemoveUnusedVariableFix(local).invoke(project, editor, local.getContainingFile()); - } - } - - - if (editor != null && !ApplicationManager.getApplication().isUnitTestMode()) { - highlightManager.addOccurrenceHighlights(editor, ContainerUtil.convert(exprs, new PsiExpression[refsToInline.length], new Function, PsiExpression>() { - @Override - public PsiExpression fun(SmartPsiElementPointer pointer) { - return pointer.getElement(); - } - }), attributes, true, null); - WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting")); - } - - for (final SmartPsiElementPointer expr : exprs) { - InlineUtil.tryToInlineArrayCreationForVarargs(expr.getElement()); + if (ReferencesSearch.search(local).findFirst() == null) { + QuickFixFactory.getInstance().createRemoveUnusedVariableFix(local).invoke(project, editor, local.getContainingFile()); } } - catch (IncorrectOperationException e){ - LOG.error(e); + + + if (editor != null && !ApplicationManager.getApplication().isUnitTestMode()) { + highlightManager.addOccurrenceHighlights(editor, ContainerUtil.convert(exprs, new PsiExpression[refsToInline.length], + pointer -> pointer.getElement()), attributes, true, null); + WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting")); } - finally { - final RefactoringEventData afterData = new RefactoringEventData(); - afterData.addElement(containingClass); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData); + + for (final SmartPsiElementPointer expr : exprs) { + InlineUtil.tryToInlineArrayCreationForVarargs(expr.getElement()); } } + catch (IncorrectOperationException e){ + LOG.error(e); + } + finally { + final RefactoringEventData afterData = new RefactoringEventData(); + afterData.addElement(containingClass); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData); + } }; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(runnable); - } - }, RefactoringBundle.message("inline.command", localName), null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(runnable), RefactoringBundle.message("inline.command", localName), null); } @Nullable diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java index 596aa32d15dd..20ba4a534f08 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java @@ -321,10 +321,8 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor { final PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(expression, PsiMethodCallExpression.class); LOG.assertTrue(methodCallExpression != null); conflicts.putValue(expression, "Inlined method calls " + methodCallExpression.getText() + " which won't be accessed in " + - StringUtil.join(targetContainingClasses, new Function() { - public String fun(PsiClass psiClass) { - return RefactoringUIUtil.getDescription(psiClass, false); - } + StringUtil.join(targetContainingClasses, psiClass -> { + return RefactoringUIUtil.getDescription(psiClass, false); }, ",")); } } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java index 247f0e1f1db0..41cbc208c60e 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java @@ -87,37 +87,35 @@ public class InlineParameterHandler extends JavaInlineActionHandler { final List occurrences = Collections.synchronizedList(new ArrayList()); final Collection containingFiles = Collections.synchronizedSet(new HashSet()); containingFiles.add(psiParameter.getContainingFile()); - boolean result = ReferencesSearch.search(method).forEach(new Processor() { - public boolean process(final PsiReference psiReference) { - PsiElement element = psiReference.getElement(); - final PsiElement parent = element.getParent(); - if (parent instanceof PsiCallExpression) { - final PsiCallExpression methodCall = (PsiCallExpression)parent; - occurrences.add(psiReference); - containingFiles.add(element.getContainingFile()); - final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); - if (expressions.length <= index) return false; - PsiExpression argument = expressions[index]; - if (!refInitializer.isNull()) { - return argument != null - && PsiEquivalenceUtil.areElementsEquivalent(refInitializer.get(), argument) - && PsiEquivalenceUtil.areElementsEquivalent(refMethodCall.get(), methodCall); + boolean result = ReferencesSearch.search(method).forEach(psiReference -> { + PsiElement element = psiReference.getElement(); + final PsiElement parent = element.getParent(); + if (parent instanceof PsiCallExpression) { + final PsiCallExpression methodCall = (PsiCallExpression)parent; + occurrences.add(psiReference); + containingFiles.add(element.getContainingFile()); + final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); + if (expressions.length <= index) return false; + PsiExpression argument = expressions[index]; + if (!refInitializer.isNull()) { + return argument != null + && PsiEquivalenceUtil.areElementsEquivalent(refInitializer.get(), argument) + && PsiEquivalenceUtil.areElementsEquivalent(refMethodCall.get(), methodCall); + } + if (InlineToAnonymousConstructorProcessor.isConstant(argument) || getReferencedFinalField(argument) != null) { + if (refConstantInitializer.isNull()) { + refConstantInitializer.set(argument); } - if (InlineToAnonymousConstructorProcessor.isConstant(argument) || getReferencedFinalField(argument) != null) { - if (refConstantInitializer.isNull()) { - refConstantInitializer.set(argument); - } - else if (!isSameConstant(argument, refConstantInitializer.get())) { - return false; - } - } else if (!isRecursiveReferencedParameter(argument, psiParameter)) { - if (!refConstantInitializer.isNull()) return false; - refInitializer.set(argument); - refMethodCall.set(methodCall); + else if (!isSameConstant(argument, refConstantInitializer.get())) { + return false; } + } else if (!isRecursiveReferencedParameter(argument, psiParameter)) { + if (!refConstantInitializer.isNull()) return false; + refInitializer.set(argument); + refMethodCall.set(methodCall); } - return true; } + return true; }); final PsiReference reference = TargetElementUtil.findReference(editor); final PsiReferenceExpression refExpr = reference instanceof PsiReferenceExpression ? ((PsiReferenceExpression)reference) : null; @@ -223,13 +221,10 @@ public class InlineParameterHandler extends JavaInlineActionHandler { final RefactoringEventData data = new RefactoringEventData(); data.addElement(psiElement.copy()); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, data); - SameParameterValueInspection.InlineParameterValueFix.inlineSameParameterValue(method, psiParameter, constantExpression); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, null); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, data); + SameParameterValueInspection.InlineParameterValueFix.inlineSameParameterValue(method, psiParameter, constantExpression); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, null); }, REFACTORING_NAME, null); } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineToAnonymousClassHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineToAnonymousClassHandler.java index 09d597e0a05a..5ca46f314be4 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineToAnonymousClassHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineToAnonymousClassHandler.java @@ -73,25 +73,17 @@ public class InlineToAnonymousClassHandler extends JavaInlineActionHandler { private static boolean findClassInheritors(final PsiClass element) { final Collection inheritors = new ArrayList(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){ - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiClass inheritor = ClassInheritorsSearch.search(element).findFirst(); - if (inheritor != null) { - inheritors.add(inheritor); - } else { - final PsiFunctionalExpression functionalExpression = FunctionalExpressionSearch.search(element).findFirst(); - if (functionalExpression != null) { - inheritors.add(functionalExpression); - } - } - } - }); + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass inheritor = ClassInheritorsSearch.search(element).findFirst(); + if (inheritor != null) { + inheritors.add(inheritor); + } else { + final PsiFunctionalExpression functionalExpression = FunctionalExpressionSearch.search(element).findFirst(); + if (functionalExpression != null) { + inheritors.add(functionalExpression); + } } - }, "Searching for class \"" + element.getQualifiedName() + "\" inheritors ...", true, element.getProject())) return false; + }), "Searching for class \"" + element.getQualifiedName() + "\" inheritors ...", true, element.getProject())) return false; return inheritors.isEmpty(); } @@ -122,17 +114,9 @@ public class InlineToAnonymousClassHandler extends JavaInlineActionHandler { } final Ref errorMessage = new Ref(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){ - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - errorMessage.set(getCannotInlineMessage(psiClass)); - } - }); - } - }, "Check if inline is possible...", true, project)) return; + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + errorMessage.set(getCannotInlineMessage(psiClass)); + }), "Check if inline is possible...", true, project)) return; if (errorMessage.get() != null) { CommonRefactoringUtil.showErrorHint(project, editor, errorMessage.get(), RefactoringBundle.message("inline.to.anonymous.refactoring"), null); return; diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java index 01ddb3b4e007..1e8c0dd8f5a1 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java @@ -106,54 +106,52 @@ public class InlineSuperClassRefactoringProcessor extends FixableUsagesRefactori findUsagesInExtendsList(usages, myCurrentInheritor.getImplementsList()); } else { - ReferencesSearch.search(mySuperClass).forEach(new Processor() { - public boolean process(final PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element instanceof PsiJavaCodeReferenceElement) { - final PsiImportStaticStatement staticImportStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class); - if (staticImportStatement != null) { - usages.add(new ReplaceStaticImportUsageInfo(staticImportStatement, myTargetClasses)); - } else { - final PsiImportStatement importStatement = PsiTreeUtil.getParentOfType(element, PsiImportStatement.class); - if (importStatement != null) { - usages.add(new RemoveImportUsageInfo(importStatement)); - } - else { - final PsiElement parent = element.getParent(); - if (parent instanceof PsiReferenceList) { - final PsiElement pparent = parent.getParent(); - if (pparent instanceof PsiClass) { - final PsiClass inheritor = (PsiClass)pparent; - if (parent.equals(inheritor.getExtendsList()) || parent.equals(inheritor.getImplementsList())) { - usages.add(new ReplaceExtendsListUsageInfo((PsiJavaCodeReferenceElement)element, mySuperClass, inheritor)); - } + ReferencesSearch.search(mySuperClass).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element instanceof PsiJavaCodeReferenceElement) { + final PsiImportStaticStatement staticImportStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class); + if (staticImportStatement != null) { + usages.add(new ReplaceStaticImportUsageInfo(staticImportStatement, myTargetClasses)); + } else { + final PsiImportStatement importStatement = PsiTreeUtil.getParentOfType(element, PsiImportStatement.class); + if (importStatement != null) { + usages.add(new RemoveImportUsageInfo(importStatement)); + } + else { + final PsiElement parent = element.getParent(); + if (parent instanceof PsiReferenceList) { + final PsiElement pparent = parent.getParent(); + if (pparent instanceof PsiClass) { + final PsiClass inheritor = (PsiClass)pparent; + if (parent.equals(inheritor.getExtendsList()) || parent.equals(inheritor.getImplementsList())) { + usages.add(new ReplaceExtendsListUsageInfo((PsiJavaCodeReferenceElement)element, mySuperClass, inheritor)); } - } else { - final PsiClass targetClass = myTargetClasses[0]; - final PsiClassType targetClassType = elementFactory - .createType(targetClass, TypeConversionUtil.getSuperClassSubstitutor(mySuperClass, targetClass, PsiSubstitutor.EMPTY)); + } + } else { + final PsiClass targetClass = myTargetClasses[0]; + final PsiClassType targetClassType = elementFactory + .createType(targetClass, TypeConversionUtil.getSuperClassSubstitutor(mySuperClass, targetClass, PsiSubstitutor.EMPTY)); - if (parent instanceof PsiTypeElement) { - final PsiType superClassType = ((PsiTypeElement)parent).getType(); - PsiSubstitutor subst = getSuperClassSubstitutor(superClassType, targetClassType, resolveHelper, targetClass); - usages.add(new ReplaceWithSubtypeUsageInfo(((PsiTypeElement)parent), elementFactory.createType(targetClass, subst), myTargetClasses)); - } - else if (parent instanceof PsiNewExpression) { - final PsiClassType newType = elementFactory.createType(targetClass, - getSuperClassSubstitutor(((PsiNewExpression)parent).getType(), - targetClassType, resolveHelper, - targetClass)); - usages.add(new ReplaceConstructorUsageInfo(((PsiNewExpression)parent), newType, myTargetClasses)); - } - else if (parent instanceof PsiJavaCodeReferenceElement) { - usages.add(new ReplaceReferenceUsageInfo(((PsiJavaCodeReferenceElement)parent).getQualifier(), myTargetClasses)); - } + if (parent instanceof PsiTypeElement) { + final PsiType superClassType = ((PsiTypeElement)parent).getType(); + PsiSubstitutor subst = getSuperClassSubstitutor(superClassType, targetClassType, resolveHelper, targetClass); + usages.add(new ReplaceWithSubtypeUsageInfo(((PsiTypeElement)parent), elementFactory.createType(targetClass, subst), myTargetClasses)); + } + else if (parent instanceof PsiNewExpression) { + final PsiClassType newType = elementFactory.createType(targetClass, + getSuperClassSubstitutor(((PsiNewExpression)parent).getType(), + targetClassType, resolveHelper, + targetClass)); + usages.add(new ReplaceConstructorUsageInfo(((PsiNewExpression)parent), newType, myTargetClasses)); + } + else if (parent instanceof PsiJavaCodeReferenceElement) { + usages.add(new ReplaceReferenceUsageInfo(((PsiJavaCodeReferenceElement)parent).getQualifier(), myTargetClasses)); } } } } - return true; } + return true; }); } for (PsiClass targetClass : myTargetClasses) { @@ -250,22 +248,19 @@ public class InlineSuperClassRefactoringProcessor extends FixableUsagesRefactori } } if (myCurrentInheritor != null) { - ReferencesSearch.search(myCurrentInheritor).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element != null) { - final PsiElement parent = element.getParent(); - if (parent instanceof PsiNewExpression) { - final PsiClass aClass = PsiUtil.resolveClassInType(getPlaceExpectedType(parent)); - if (aClass == mySuperClass) { - conflicts.putValue(parent, "Instance of target type is passed to a place where super class is expected."); - return false; - } + ReferencesSearch.search(myCurrentInheritor).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element != null) { + final PsiElement parent = element.getParent(); + if (parent instanceof PsiNewExpression) { + final PsiClass aClass = PsiUtil.resolveClassInType(getPlaceExpectedType(parent)); + if (aClass == mySuperClass) { + conflicts.putValue(parent, "Instance of target type is passed to a place where super class is expected."); + return false; } } - return true; } + return true; }); } checkConflicts(refUsages, conflicts); diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceConstructorUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceConstructorUsageInfo.java index 96e8909051e0..8da43acc27f9 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceConstructorUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceConstructorUsageInfo.java @@ -80,11 +80,10 @@ public class ReplaceConstructorUsageInfo extends FixableUsageInfo{ } if (targetClasses.length > 1) { - final String conflict = "Constructor " + element.getText() + " can be replaced with any of " + StringUtil.join(targetClasses, new Function() { - public String fun(final PsiClass psiClass) { - return psiClass.getQualifiedName(); - } - }, ", "); + final String conflict = "Constructor " + element.getText() + " can be replaced with any of " + StringUtil.join(targetClasses, + psiClass -> { + return psiClass.getQualifiedName(); + }, ", "); appendConflict(conflict); } } @@ -117,10 +116,8 @@ public class ReplaceConstructorUsageInfo extends FixableUsageInfo{ final PsiExpression[] arrayDimensions = newExpression.getArrayDimensions(); if (arrayDimensions.length > 0) { buf.append("["); - buf.append(StringUtil.join(arrayDimensions, new Function() { - public String fun(PsiExpression psiExpression) { - return psiExpression.getText(); - } + buf.append(StringUtil.join(arrayDimensions, psiExpression -> { + return psiExpression.getText(); }, "][")); buf.append("]"); for (int i = 0; i < newExpressionType.getArrayDimensions() - arrayDimensions.length; i++) { diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java index b578a9518b53..06708f8bd0dc 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceReferenceUsageInfo.java @@ -35,11 +35,10 @@ public class ReplaceReferenceUsageInfo extends FixableUsageInfo { public ReplaceReferenceUsageInfo(PsiElement referenceExpression, PsiClass[] targetClasses) { super(referenceExpression); myTargetClass = targetClasses[0]; - myConflict = targetClasses.length > 1 ? referenceExpression.getText() + "can be replaced with any of " + StringUtil.join(targetClasses, new Function() { - public String fun(final PsiClass psiClass) { - return psiClass.getQualifiedName(); - } - }, ", ") : null; + myConflict = targetClasses.length > 1 ? referenceExpression.getText() + "can be replaced with any of " + StringUtil.join(targetClasses, + psiClass -> { + return psiClass.getQualifiedName(); + }, ", ") : null; } public void fixUsage() throws IncorrectOperationException { diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java index 501e26e3d900..cd31d188fa63 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceStaticImportUsageInfo.java @@ -47,10 +47,8 @@ public class ReplaceStaticImportUsageInfo extends FixableUsageInfo { @Override public String getConflictMessage() { if (myTargetClasses.length != 1) { - return "Static import can be replaced with any of " + StringUtil.join(myTargetClasses, new Function() { - public String fun(final PsiClass psiClass) { - return psiClass.getQualifiedName(); - } + return "Static import can be replaced with any of " + StringUtil.join(myTargetClasses, psiClass -> { + return psiClass.getQualifiedName(); }, ", "); } return super.getConflictMessage(); diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java index ec1e10df935b..b7ea731596eb 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceWithSubtypeUsageInfo.java @@ -42,10 +42,8 @@ public class ReplaceWithSubtypeUsageInfo extends FixableUsageInfo { myTargetClassType = classType; myOriginalType = myTypeElement.getType(); if (targetClasses.length > 1) { - myConflict = typeElement.getText() + " can be replaced with any of " + StringUtil.join(targetClasses, new Function() { - public String fun(final PsiClass psiClass) { - return psiClass.getQualifiedName(); - } + myConflict = typeElement.getText() + " can be replaced with any of " + StringUtil.join(targetClasses, psiClass -> { + return psiClass.getQualifiedName(); }, ", ") ; } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceConstantPopup.java b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceConstantPopup.java index 1ce19ec5b2f3..bdcac4579413 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceConstantPopup.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceConstantPopup.java @@ -192,30 +192,27 @@ public class InplaceIntroduceConstantPopup extends AbstractInplaceIntroduceField JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS = myMoveToAnotherClassCb.isSelected(); if (myMoveToAnotherClassCb.isSelected()) { myEditor.putUserData(INTRODUCE_RESTART, true); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myEditor.putUserData(ACTIVE_INTRODUCE, InplaceIntroduceConstantPopup.this); - try { - final IntroduceConstantHandler constantHandler = new IntroduceConstantHandler(); - final PsiLocalVariable localVariable = (PsiLocalVariable)getLocalVariable(); - if (localVariable != null) { - constantHandler.invokeImpl(myProject, localVariable, myEditor); - } - else { - constantHandler.invokeImpl(myProject, myExpr, myEditor); - } + ApplicationManager.getApplication().invokeLater(() -> { + myEditor.putUserData(ACTIVE_INTRODUCE, InplaceIntroduceConstantPopup.this); + try { + final IntroduceConstantHandler constantHandler = new IntroduceConstantHandler(); + final PsiLocalVariable localVariable = (PsiLocalVariable)getLocalVariable(); + if (localVariable != null) { + constantHandler.invokeImpl(myProject, localVariable, myEditor); } - finally { - myEditor.putUserData(INTRODUCE_RESTART, false); - myEditor.putUserData(ACTIVE_INTRODUCE, null); - releaseResources(); - if (myLocalMarker != null) { - myLocalMarker.dispose(); - } - if (myExprMarker != null) { - myExprMarker.dispose(); - } + else { + constantHandler.invokeImpl(myProject, myExpr, myEditor); + } + } + finally { + myEditor.putUserData(INTRODUCE_RESTART, false); + myEditor.putUserData(ACTIVE_INTRODUCE, null); + releaseResources(); + if (myLocalMarker != null) { + myLocalMarker.dispose(); + } + if (myExprMarker != null) { + myExprMarker.dispose(); } } }); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldCentralPanel.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldCentralPanel.java index cc9a8a6f6677..bd226b8c5d2a 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldCentralPanel.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldCentralPanel.java @@ -139,15 +139,12 @@ public abstract class IntroduceFieldCentralPanel { for (PsiField field : fields) { final PsiMethod setUpMethod = TestFrameworks.getInstance().findSetUpMethod((field).getContainingClass()); if (setUpMethod != null) { - final Processor initializerSearcher = new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement referenceElement = reference.getElement(); - if (referenceElement instanceof PsiExpression) { - return !PsiUtil.isAccessedForWriting((PsiExpression)referenceElement); - } - return true; + final Processor initializerSearcher = reference -> { + final PsiElement referenceElement = reference.getElement(); + if (referenceElement instanceof PsiExpression) { + return !PsiUtil.isAccessedForWriting((PsiExpression)referenceElement); } + return true; }; if (ReferencesSearch.search(field, new LocalSearchScope(setUpMethod)).forEach(initializerSearcher)) { return false; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java index 41fcf11be5c0..b8884ecdf437 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java @@ -131,11 +131,7 @@ public abstract class LocalToFieldHandler { final boolean rebindNeeded1 = rebindNeeded; final Runnable runnable = new IntroduceFieldRunnable(rebindNeeded1, local, aaClass, settings, isStatic, occurences); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(runnable); - } - }, REFACTORING_NAME, null); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(runnable), REFACTORING_NAME, null); return false; } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java index 951bc52d9b71..60dceff1dc56 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java @@ -204,28 +204,21 @@ public class InplaceIntroduceParameterPopup extends AbstractJavaInplaceIntroduce isGenerateDelegate(), getType(), parametersToRemove); - final Runnable runnable = new Runnable() { - public void run() { - final Runnable performRefactoring = new Runnable() { - public void run() { - processor.setPrepareSuccessfulSwingThreadCallback(new Runnable() { - @Override - public void run() { - } - }); - processor.run(); - normalizeParameterIdxAccordingToRemovedParams(parametersToRemove); - final PsiParameter parameter = getParameter(); - if (parameter != null) { - InplaceIntroduceParameterPopup.super.saveSettings(parameter); - } - } - }; - if (ApplicationManager.getApplication().isUnitTestMode()) { - performRefactoring.run(); - } else { - ApplicationManager.getApplication().invokeLater(performRefactoring); + final Runnable runnable = () -> { + final Runnable performRefactoring = () -> { + processor.setPrepareSuccessfulSwingThreadCallback(() -> { + }); + processor.run(); + normalizeParameterIdxAccordingToRemovedParams(parametersToRemove); + final PsiParameter parameter = getParameter(); + if (parameter != null) { + InplaceIntroduceParameterPopup.super.saveSettings(parameter); } + }; + if (ApplicationManager.getApplication().isUnitTestMode()) { + performRefactoring.run(); + } else { + ApplicationManager.getApplication().invokeLater(performRefactoring); } }; CommandProcessor.getInstance().executeCommand(myProject, runnable, getCommandName(), null); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterHandler.java index 8d311229d6fa..fb3da83bb7be 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterHandler.java @@ -208,12 +208,8 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase { return true; } - chooseMethodToIntroduceParameter(editor, validEnclosingMethods, new PairConsumer() { - @Override - public void consume(PsiMethod methodToSearchIn, PsiMethod methodToSearchFor) { - introducer.introduceParameter(methodToSearchIn, methodToSearchFor); - } - }); + chooseMethodToIntroduceParameter(editor, validEnclosingMethods, + (methodToSearchIn, methodToSearchFor) -> introducer.introduceParameter(methodToSearchIn, methodToSearchFor)); return true; } @@ -488,12 +484,9 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase { dialog.setReplaceAllOccurrences(replaceAllOccurrences); dialog.setGenerateDelegate(delegate); if (dialog.showAndGet()) { - final Runnable cleanSelectionRunnable = new Runnable() { - @Override - public void run() { - if (myEditor != null && !myEditor.isDisposed()) { - myEditor.getSelectionModel().removeSelection(); - } + final Runnable cleanSelectionRunnable = () -> { + if (myEditor != null && !myEditor.isDisposed()) { + myEditor.getSelectionModel().removeSelection(); } }; SwingUtilities.invokeLater(cleanSelectionRunnable); @@ -613,12 +606,8 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase { final Editor editor, final MyExtractMethodProcessor processor, final PsiElement[] elements) { - final PairConsumer consumer = new PairConsumer() { - @Override - public void consume(PsiMethod methodToIntroduceParameter, PsiMethod methodToSearchFor) { - introduceWrappedCodeBlockParameter(methodToIntroduceParameter, methodToSearchFor, editor, project, selectedType, processor, elements); - } - }; + final PairConsumer consumer = + (methodToIntroduceParameter, methodToSearchFor) -> introduceWrappedCodeBlockParameter(methodToIntroduceParameter, methodToSearchFor, editor, project, selectedType, processor, elements); chooseMethodToIntroduceParameter(editor, enclosingMethods, consumer); } @@ -650,37 +639,34 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase { final Ref suffixText = new Ref(); final Ref prefixText = new Ref(); final Ref methodText = new Ref(); - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(wrapperClass); - LOG.assertTrue(method != null); - final String interfaceMethodName = method.getName(); - processor.setMethodName(interfaceMethodName); + WriteCommandAction.runWriteCommandAction(project, () -> { + final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(wrapperClass); + LOG.assertTrue(method != null); + final String interfaceMethodName = method.getName(); + processor.setMethodName(interfaceMethodName); - if (copyElements.length == 1 && copyElements[0].getUserData(ElementToWorkOn.PARENT) == null) { - copyElements[0].putUserData(ElementToWorkOn.REPLACE_NON_PHYSICAL, true); - } - - processor.doExtract(); - - final PsiMethod extractedMethod = processor.getExtractedMethod(); - final PsiParameter[] parameters = extractedMethod.getParameterList().getParameters(); - final PsiParameter[] interfaceParameters = method.getParameterList().getParameters(); - final PsiSubstitutor substitutor = resolveResult.getSubstitutor(); - for (int i = 0; i < interfaceParameters.length; i++) { - final PsiTypeElement typeAfterInterface = factory.createTypeElement(substitutor.substitute(interfaceParameters[i].getType())); - final PsiTypeElement typeElement = parameters[i].getTypeElement(); - if (typeElement != null) { - typeElement.replace(typeAfterInterface); - } - } - methodText.set(extractedMethod.getText()); - - final PsiMethodCallExpression methodCall = processor.getMethodCall(); - prefixText.set(containerCopy.getText().substring(0, methodCall.getTextRange().getStartOffset() - containerCopy.getTextRange().getStartOffset())); - suffixText.set("." + methodCall.getText() + containerCopy.getText().substring(methodCall.getTextRange().getEndOffset() - containerCopy.getTextRange().getStartOffset())); + if (copyElements.length == 1 && copyElements[0].getUserData(ElementToWorkOn.PARENT) == null) { + copyElements[0].putUserData(ElementToWorkOn.REPLACE_NON_PHYSICAL, true); } + + processor.doExtract(); + + final PsiMethod extractedMethod = processor.getExtractedMethod(); + final PsiParameter[] parameters = extractedMethod.getParameterList().getParameters(); + final PsiParameter[] interfaceParameters = method.getParameterList().getParameters(); + final PsiSubstitutor substitutor = resolveResult.getSubstitutor(); + for (int i = 0; i < interfaceParameters.length; i++) { + final PsiTypeElement typeAfterInterface = factory.createTypeElement(substitutor.substitute(interfaceParameters[i].getType())); + final PsiTypeElement typeElement = parameters[i].getTypeElement(); + if (typeElement != null) { + typeElement.replace(typeAfterInterface); + } + } + methodText.set(extractedMethod.getText()); + + final PsiMethodCallExpression methodCall = processor.getMethodCall(); + prefixText.set(containerCopy.getText().substring(0, methodCall.getTextRange().getStartOffset() - containerCopy.getTextRange().getStartOffset())); + suffixText.set("." + methodCall.getText() + containerCopy.getText().substring(methodCall.getTextRange().getEndOffset() - containerCopy.getTextRange().getStartOffset())); }); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java index 6b2d3fa95559..24c1fac204f2 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java @@ -453,12 +453,7 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem } if (isReplaceDuplicates()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - processMethodsDuplicates(); - } - }, ModalityState.NON_MODAL, myProject.getDisposed()); + ApplicationManager.getApplication().invokeLater(() -> processMethodsDuplicates(), ModalityState.NON_MODAL, myProject.getDisposed()); } } @@ -467,19 +462,12 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem } private void processMethodsDuplicates() { - final Runnable runnable = new Runnable() { - public void run() { - if (!myMethodToReplaceIn.isValid()) return; - MethodDuplicatesHandler.invokeOnScope(myProject, Collections.singleton(myMethodToReplaceIn), - new AnalysisScope(myMethodToReplaceIn.getContainingFile()), true); - } + final Runnable runnable = () -> { + if (!myMethodToReplaceIn.isValid()) return; + MethodDuplicatesHandler.invokeOnScope(myProject, Collections.singleton(myMethodToReplaceIn), + new AnalysisScope(myMethodToReplaceIn.getContainingFile()), true); }; - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(runnable); - } - }, "Search method duplicates...", true, myProject); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(runnable), "Search method duplicates...", true, myProject); } private PsiMethod generateDelegate(final PsiMethod methodToReplaceIn) throws IncorrectOperationException { diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/OldReferenceResolver.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/OldReferenceResolver.java index 3d483ced014d..a97a918fb4e8 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/OldReferenceResolver.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/OldReferenceResolver.java @@ -138,12 +138,8 @@ public class OldReferenceResolver { final PsiType parameterType = parameter.getType(); if (parameter.isVarArgs() && parameterType instanceof PsiEllipsisType) { - final String varargsJoin = StringUtil.join(ContainerUtil.map2Array(myActualArgs, String.class, new Function() { - @Override - public String fun(PsiExpression expression) { - return expression != null ? expression.getText() : "null"; - } - }), index + 1, myActualArgs.length, ","); + final String varargsJoin = StringUtil.join(ContainerUtil.map2Array(myActualArgs, String.class, + expression -> expression != null ? expression.getText() : "null"), index + 1, myActualArgs.length, ","); String newArrayInitializer = "new " + ((PsiEllipsisType)parameterType).toArrayType().getCanonicalText() + " {" + varargsJoin + "}"; initializer = replaceInitializerWithVarargSubstitution(factory, parameter, initializer, newArrayInitializer); } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/Util.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/Util.java index 06747b66e0c4..52d492059e3c 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/Util.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/Util.java @@ -144,27 +144,25 @@ public class Util { PsiParameter[] psiParameters = psiMethod.getParameterList().getParameters(); if (paramNum >= psiParameters.length) continue; PsiParameter parameter = psiParameters[paramNum]; - if (!ReferencesSearch.search(parameter, parameter.getResolveScope(), false).forEach(new Processor() { - public boolean process(final PsiReference reference) { - PsiElement element = reference.getElement(); - boolean stillCanBeRemoved = false; - if (element != null) { - stillCanBeRemoved = isAncestor(expr, element, false) || PsiUtil.isInsideJavadocComment(getPhysical(element)); - if (!stillCanBeRemoved && occurences != null) { - for (PsiExpression occurence : occurences) { - if (isAncestor(occurence, element, false)) { - stillCanBeRemoved = true; - break; - } + if (!ReferencesSearch.search(parameter, parameter.getResolveScope(), false).forEach(reference -> { + PsiElement element = reference.getElement(); + boolean stillCanBeRemoved = false; + if (element != null) { + stillCanBeRemoved = isAncestor(expr, element, false) || PsiUtil.isInsideJavadocComment(getPhysical(element)); + if (!stillCanBeRemoved && occurences != null) { + for (PsiExpression occurence : occurences) { + if (isAncestor(occurence, element, false)) { + stillCanBeRemoved = true; + break; } } } - if (!stillCanBeRemoved) { - iterator.remove(); - return false; - } - return true; } + if (!stillCanBeRemoved) { + iterator.remove(); + return false; + } + return true; })) break; } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/VisibilityListener.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/VisibilityListener.java index 6b23111fee4c..a83b9bf407f2 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/VisibilityListener.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/VisibilityListener.java @@ -81,12 +81,7 @@ public abstract class VisibilityListener { final String finalVisibility = visibility + (wasPackageLocal ? " " : ""); - Runnable runnable = new Runnable() { - @Override - public void run() { - document.replaceString(startOffset, endOffset, finalVisibility); - } - }; + Runnable runnable = () -> document.replaceString(startOffset, endOffset, finalVisibility); final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); if (lookup != null) { diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/FinalListener.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/FinalListener.java index 5936a013c49e..4f8ae1f64b8f 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/FinalListener.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/FinalListener.java @@ -30,17 +30,15 @@ public class FinalListener { LOG.assertTrue(modifierList != null); final int textOffset = modifierList.getTextOffset(); - final Runnable runnable = new Runnable() { - public void run() { - if (generateFinal) { - final PsiTypeElement typeElement = variable.getTypeElement(); - final int typeOffset = typeElement != null ? typeElement.getTextOffset() : textOffset; - document.insertString(typeOffset, modifier + " "); - } - else { - final int idx = modifierList.getText().indexOf(modifier); - document.deleteString(textOffset + idx, textOffset + idx + modifier.length() + 1); - } + final Runnable runnable = () -> { + if (generateFinal) { + final PsiTypeElement typeElement = variable.getTypeElement(); + final int typeOffset = typeElement != null ? typeElement.getTextOffset() : textOffset; + document.insertString(typeOffset, modifier + " "); + } + else { + final int idx = modifierList.getText().indexOf(modifier); + document.deleteString(textOffset + idx, textOffset + idx + modifier.length() + 1); } }; final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java index cf7adbeb80fc..0c6b16e94a11 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java @@ -700,41 +700,39 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { CommandProcessor.getInstance().executeCommand( project, - new Runnable() { - public void run() { - final Editor topLevelEditor ; - if (!InjectedLanguageManager.getInstance(project).isInjectedFragment(anchorStatement.getContainingFile())) { - topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(editor); - } else { - topLevelEditor = editor; + () -> { + final Editor topLevelEditor ; + if (!InjectedLanguageManager.getInstance(project).isInjectedFragment(anchorStatement.getContainingFile())) { + topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(editor); + } else { + topLevelEditor = editor; + } + + PsiVariable variable = null; + try { + final IntroduceVariableSettings settings = + getSettings(project, topLevelEditor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, anchorStatement, choice); + if (!settings.isOK()) { + wasSucceed[0] = false; + return; } - PsiVariable variable = null; - try { - final IntroduceVariableSettings settings = - getSettings(project, topLevelEditor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, anchorStatement, choice); - if (!settings.isOK()) { - wasSucceed[0] = false; - return; - } + final RefactoringEventData beforeData = new RefactoringEventData(); + beforeData.addElement(expr); + project.getMessageBus() + .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, beforeData); - final RefactoringEventData beforeData = new RefactoringEventData(); - beforeData.addElement(expr); - project.getMessageBus() - .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, beforeData); + final PsiElement chosenAnchor = + chooseAnchor(settings.isReplaceAllOccurrences(), hasWriteAccess, nonWrite, anchorStatementIfAll, anchorStatement); - final PsiElement chosenAnchor = - chooseAnchor(settings.isReplaceAllOccurrences(), hasWriteAccess, nonWrite, anchorStatementIfAll, anchorStatement); - - variable = ApplicationManager.getApplication().runWriteAction( - introduce(project, expr, topLevelEditor, chosenAnchor, occurrences, settings)); - } - finally { - final RefactoringEventData afterData = new RefactoringEventData(); - afterData.addElement(variable); - project.getMessageBus() - .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, afterData); - } + variable = ApplicationManager.getApplication().runWriteAction( + introduce(project, expr, topLevelEditor, chosenAnchor, occurrences, settings)); + } + finally { + final RefactoringEventData afterData = new RefactoringEventData(); + afterData.addElement(variable); + project.getMessageBus() + .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, afterData); } }, REFACTORING_NAME, null); } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/JavaVariableInplaceIntroducer.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/JavaVariableInplaceIntroducer.java index 8762836574f7..da2362e4d463 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/JavaVariableInplaceIntroducer.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/JavaVariableInplaceIntroducer.java @@ -211,14 +211,12 @@ public class JavaVariableInplaceIntroducer extends AbstractJavaInplaceIntroducer myEditor.getCaretModel().moveToOffset(startOffset); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - if (psiVariable.getInitializer() != null) { - appendTypeCasts(getOccurrenceMarkers(), file, myProject, psiVariable); - } - if (myConflictResolver != null && myInsertedName != null && isIdentifier(myInsertedName, psiVariable.getLanguage())) { - myConflictResolver.apply(psiVariable.getName()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (psiVariable.getInitializer() != null) { + appendTypeCasts(getOccurrenceMarkers(), file, myProject, psiVariable); + } + if (myConflictResolver != null && myInsertedName != null && isIdentifier(myInsertedName, psiVariable.getLanguage())) { + myConflictResolver.apply(psiVariable.getName()); } }); } @@ -387,12 +385,9 @@ public class JavaVariableInplaceIntroducer extends AbstractJavaInplaceIntroducer final int modifierListOffset = psiVariable.getTextRange().getStartOffset(); final int varLineNumber = document.getLineNumber(modifierListOffset); - ApplicationManager.getApplication().runWriteAction(new Runnable() { //adjust line indent if final was inserted and then deleted - - public void run() { - PsiDocumentManager.getInstance(psiVariable.getProject()).doPostponedOperationsAndUnblockDocument(document); - CodeStyleManager.getInstance(psiVariable.getProject()).adjustLineIndent(document, document.getLineStartOffset(varLineNumber)); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(psiVariable.getProject()).doPostponedOperationsAndUnblockDocument(document); + CodeStyleManager.getInstance(psiVariable.getProject()).adjustLineIndent(document, document.getLineStartOffset(varLineNumber)); }); } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/ReassignVariableUtil.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/ReassignVariableUtil.java index c2e1d3e34247..a01443ed371a 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/ReassignVariableUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/ReassignVariableUtil.java @@ -72,15 +72,12 @@ public class ReassignVariableUtil { final PsiVariable variable = proc.getResult(i); PsiElement outerCodeBlock = PsiUtil.getVariableCodeBlock(variable, null); if (outerCodeBlock == null) continue; - if (ReferencesSearch.search(variable, new LocalSearchScope(outerCodeBlock)).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element != null) { - return HighlightControlFlowUtil.getInnerClassVariableReferencedFrom(variable, element) == null; - } - return true; + if (ReferencesSearch.search(variable, new LocalSearchScope(outerCodeBlock)).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element != null) { + return HighlightControlFlowUtil.getInnerClassVariableReferencedFrom(variable, element) == null; } + return true; })) { vars.add(variable); } @@ -116,11 +113,7 @@ public class ReassignVariableUtil { JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle("Choose variable to reassign") .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - public void run() { - replaceWithAssignment(declaration, (PsiVariable)list.getSelectedValue(), editor); - } - }).createPopup().show(new RelativePoint(editor.getContentComponent(), point)); + .setItemChoosenCallback(() -> replaceWithAssignment(declaration, (PsiVariable)list.getSelectedValue(), editor)).createPopup().show(new RelativePoint(editor.getContentComponent(), point)); } return true; diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java index 1b5eb84fe01a..906b809af879 100644 --- a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodStaticProcessor.java @@ -67,12 +67,8 @@ public class MakeMethodStaticProcessor extends MakeMethodOrClassStaticProcessor< } } else { - final JavaCallerChooser chooser = new MakeStaticJavaCallerChooser(myMember, myProject, new Consumer>() { - @Override - public void consume(Set methods) { - myAdditionalMethods.addAll(methods); - } - }) { + final JavaCallerChooser chooser = new MakeStaticJavaCallerChooser(myMember, myProject, + methods -> myAdditionalMethods.addAll(methods)) { @Override protected ArrayList getTopLevelItems() { return new ArrayList(toMakeStatic); diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticHandler.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticHandler.java index fde9098298e3..7b3a103a4e01 100644 --- a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticHandler.java @@ -101,18 +101,11 @@ public class MakeStaticHandler implements RefactoringActionHandler { final boolean[] hasMethodReferenceOnInstance = new boolean[] {false}; if (member instanceof PsiMethod) { - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - hasMethodReferenceOnInstance[0] = !MethodReferencesSearch.search((PsiMethod)member).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - return !(element instanceof PsiMethodReferenceExpression); - } - }); - } - }, "Search for method references", true, project)) return; + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously( + (Runnable)() -> hasMethodReferenceOnInstance[0] = !MethodReferencesSearch.search((PsiMethod)member).forEach(reference -> { + final PsiElement element = reference.getElement(); + return !(element instanceof PsiMethodReferenceExpression); + }), "Search for method references", true, project)) return; } if (classRefsInMember.length > 0 || hasMethodReferenceOnInstance[0]) { diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticJavaCallerChooser.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticJavaCallerChooser.java index 667b850432c3..25ba6abb9148 100644 --- a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticJavaCallerChooser.java +++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticJavaCallerChooser.java @@ -95,12 +95,7 @@ abstract class MakeStaticJavaCallerChooser extends JavaCallerChooser { protected List computeCallers() { if (getTopMethod().equals(getMethod())) { final ArrayList items = getTopLevelItems(); - return ContainerUtil.map(items, new Function() { - @Override - public PsiMethod fun(UsageInfo info) { - return (PsiMethod)info.getElement(); - } - }); + return ContainerUtil.map(items, info -> (PsiMethod)info.getElement()); } return super.computeCallers(); } diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticUtil.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticUtil.java index e5c966f60cc5..782f7e63db4e 100644 --- a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeStaticUtil.java @@ -158,11 +158,7 @@ public class MakeStaticUtil { } final ArrayList psiFields = new ArrayList(reported); - Collections.sort(psiFields, new Comparator() { - public int compare(PsiField psiField, PsiField psiField1) { - return psiField.getName().compareTo(psiField1.getName()); - } - }); + Collections.sort(psiFields, (psiField, psiField1) -> psiField.getName().compareTo(psiField1.getName())); for (final PsiField field : psiFields) { if (accessedForWriting.contains(field)) continue; VariableData data = new VariableData(field); diff --git a/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHandler.java b/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHandler.java index d24ffeeaf2ac..e6989a369497 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHandler.java @@ -146,21 +146,12 @@ public class JavaPullUpHandler implements RefactoringActionHandler, PullUpDialog final PsiClass superClass = dialog.getSuperClass(); if (!checkWritable(superClass, memberInfos)) return false; final MultiMap conflicts = new MultiMap(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiDirectory targetDirectory = superClass.getContainingFile().getContainingDirectory(); - final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; - conflicts - .putAllValues(PullUpConflictsUtil.checkConflicts(memberInfos, mySubclass, superClass, targetPackage, targetDirectory, dialog.getContainmentVerifier())); - } - }); - - } - }, RefactoringBundle.message("detecting.possible.conflicts"), true, myProject)) return false; + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + final PsiDirectory targetDirectory = superClass.getContainingFile().getContainingDirectory(); + final PsiPackage targetPackage = targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; + conflicts + .putAllValues(PullUpConflictsUtil.checkConflicts(memberInfos, mySubclass, superClass, targetPackage, targetDirectory, dialog.getContainmentVerifier())); + }), RefactoringBundle.message("detecting.possible.conflicts"), true, myProject)) return false; if (!conflicts.isEmpty()) { ConflictsDialog conflictsDialog = new ConflictsDialog(myProject, conflicts); conflictsDialog.show(); diff --git a/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java b/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java index b660567f2c55..d4a2e3bcdd5b 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java @@ -421,14 +421,12 @@ public class JavaPullUpHelper implements PullUpHelper { ArrayList initializedFields = new ArrayList(fieldsToInitializers.keySet()); - Collections.sort(initializedFields, new Comparator() { - public int compare(PsiField field1, PsiField field2) { - Initializer i1 = fieldsToInitializers.get(field1); - Initializer i2 = fieldsToInitializers.get(field2); - if(i1.movedFieldsUsed.contains(field2)) return 1; - if(i2.movedFieldsUsed.contains(field1)) return -1; - return 0; - } + Collections.sort(initializedFields, (field1, field2) -> { + Initializer i1 = fieldsToInitializers.get(field1); + Initializer i2 = fieldsToInitializers.get(field2); + if(i1.movedFieldsUsed.contains(field2)) return 1; + if(i2.movedFieldsUsed.contains(field1)) return -1; + return 0; }); for (final PsiField initializedField : initializedFields) { diff --git a/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java b/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java index cc4faae65b6f..e2354c3d3a2b 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java @@ -110,12 +110,7 @@ public class PullUpProcessor extends BaseRefactoringProcessor implements PullUpD protected RefactoringEventData getBeforeData() { RefactoringEventData data = new RefactoringEventData(); data.addElement(mySourceClass); - data.addMembers(myMembersToMove, new Function() { - @Override - public PsiElement fun(MemberInfo info) { - return info.getMember(); - } - }); + data.addMembers(myMembersToMove, info -> info.getMember()); return data; } @@ -140,45 +135,32 @@ public class PullUpProcessor extends BaseRefactoringProcessor implements PullUpD processor.updateUsage(element); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - processMethodsDuplicates(); - } - }, ModalityState.NON_MODAL, myProject.getDisposed()); + ApplicationManager.getApplication().invokeLater(() -> processMethodsDuplicates(), ModalityState.NON_MODAL, myProject.getDisposed()); } private void processMethodsDuplicates() { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (!myTargetSuperClass.isValid()) return; - final Query search = ClassInheritorsSearch.search(myTargetSuperClass); - final Set hierarchyFiles = new HashSet(); - for (PsiClass aClass : search) { - final PsiFile containingFile = aClass.getContainingFile(); - if (containingFile != null) { - final VirtualFile virtualFile = containingFile.getVirtualFile(); - if (virtualFile != null) { - hierarchyFiles.add(virtualFile); - } - } - } - final Set methodsToSearchDuplicates = new HashSet(); - for (PsiMember psiMember : myMembersAfterMove) { - if (psiMember instanceof PsiMethod && psiMember.isValid() && ((PsiMethod)psiMember).getBody() != null) { - methodsToSearchDuplicates.add(psiMember); - } - } - - MethodDuplicatesHandler.invokeOnScope(myProject, methodsToSearchDuplicates, new AnalysisScope(myProject, hierarchyFiles), true); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + if (!myTargetSuperClass.isValid()) return; + final Query search = ClassInheritorsSearch.search(myTargetSuperClass); + final Set hierarchyFiles = new HashSet(); + for (PsiClass aClass : search) { + final PsiFile containingFile = aClass.getContainingFile(); + if (containingFile != null) { + final VirtualFile virtualFile = containingFile.getVirtualFile(); + if (virtualFile != null) { + hierarchyFiles.add(virtualFile); } - }); + } } - }, MethodDuplicatesHandler.REFACTORING_NAME, true, myProject); + final Set methodsToSearchDuplicates = new HashSet(); + for (PsiMember psiMember : myMembersAfterMove) { + if (psiMember instanceof PsiMethod && psiMember.isValid() && ((PsiMethod)psiMember).getBody() != null) { + methodsToSearchDuplicates.add(psiMember); + } + } + + MethodDuplicatesHandler.invokeOnScope(myProject, methodsToSearchDuplicates, new AnalysisScope(myProject, hierarchyFiles), true); + }), MethodDuplicatesHandler.REFACTORING_NAME, true, myProject); } @Override @@ -341,12 +323,7 @@ public class PullUpProcessor extends BaseRefactoringProcessor implements PullUpD @Override @NotNull public PsiElement[] getElements() { - return ContainerUtil.map(myMembersToMove, new Function() { - @Override - public PsiElement fun(MemberInfo info) { - return info.getMember(); - } - }, PsiElement.EMPTY_ARRAY); + return ContainerUtil.map(myMembersToMove, info -> info.getMember(), PsiElement.EMPTY_ARRAY); } @Override diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/DestinationFolderComboBox.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/DestinationFolderComboBox.java index d94d8436bf92..64ab2a1d3298 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/DestinationFolderComboBox.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/DestinationFolderComboBox.java @@ -248,13 +248,10 @@ public abstract class DestinationFolderComboBox extends ComboboxWithBrowseButton } } updateErrorMessage(updateErrorMessage, fileIndex, selection); - Collections.sort(items, new Comparator() { - @Override - public int compare(DirectoryChooser.ItemWrapper o1, DirectoryChooser.ItemWrapper o2) { - if (o1 == NULL_WRAPPER) return -1; - if (o2 == NULL_WRAPPER) return 1; - return o1.getRelativeToProjectPath().compareToIgnoreCase(o2.getRelativeToProjectPath()); - } + Collections.sort(items, (o1, o2) -> { + if (o1 == NULL_WRAPPER) return -1; + if (o2 == NULL_WRAPPER) return 1; + return o1.getRelativeToProjectPath().compareToIgnoreCase(o2.getRelativeToProjectPath()); }); comboBox.setModel(new CollectionComboBoxModel(items, selection)); diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassToInnerHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassToInnerHandler.java index 6ffcce31e262..eddc406eb357 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassToInnerHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassToInnerHandler.java @@ -62,11 +62,7 @@ public class JavaMoveClassToInnerHandler implements MoveClassToInnerHandler { } else { //rebind imports first - Collections.sort(usageInfos, new Comparator() { - public int compare(UsageInfo o1, UsageInfo o2) { - return PsiUtil.BY_POSITION.compare(o1.getElement(), o2.getElement()); - } - }); + Collections.sort(usageInfos, (o1, o2) -> PsiUtil.BY_POSITION.compare(o1.getElement(), o2.getElement())); } return importStatements; } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java index 4ebb952fe299..d114f9687745 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java @@ -200,10 +200,7 @@ public class JavaMoveClassesOrPackagesHandler extends MoveHandlerDelegate { new MoveDirectoryWithClassesProcessor(project, directories, (PsiDirectory)targetContainer, refactoringSettings.RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE, refactoringSettings.RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE, true, callback); - processor.setPrepareSuccessfulSwingThreadCallback(new Runnable() { - @Override - public void run() { - } + processor.setPrepareSuccessfulSwingThreadCallback(() -> { }); processor.run(); } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java index 8474a7125e1f..561726754735 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassToInnerProcessor.java @@ -114,14 +114,12 @@ public class MoveClassToInnerProcessor extends BaseRefactoringProcessor { } protected void refreshElements(@NotNull final PsiElement[] elements) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final PsiClass[] classesToMove = new PsiClass[elements.length]; - for (int i = 0; i < classesToMove.length; i++) { - classesToMove[i] = (PsiClass)elements[i]; - } - setClassesToMove(classesToMove); + ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass[] classesToMove = new PsiClass[elements.length]; + for (int i = 0; i < classesToMove.length; i++) { + classesToMove[i] = (PsiClass)elements[i]; } + setClassesToMove(classesToMove); }); } @@ -235,10 +233,8 @@ public class MoveClassToInnerProcessor extends BaseRefactoringProcessor { protected String getCommandName() { return RefactoringBundle.message("move.class.to.inner.command.name", - (myClassesToMove.length > 1 ? "classes " : "class ") + StringUtil.join(myClassesToMove, new Function() { - public String fun(PsiClass psiClass) { - return psiClass.getName(); - } + (myClassesToMove.length > 1 ? "classes " : "class ") + StringUtil.join(myClassesToMove, psiClass -> { + return psiClass.getName(); }, ", "), myTargetClass.getQualifiedName()); } @@ -308,17 +304,15 @@ public class MoveClassToInnerProcessor extends BaseRefactoringProcessor { private void detectInaccessibleMemberUsages(final ConflictsCollector collector) { PsiElement[] members = collectPackageLocalMembers(collector.getClassToMove()); for(PsiElement member: members) { - ReferencesSearch.search(member).forEach(new Processor() { - public boolean process(final PsiReference psiReference) { - PsiElement element = psiReference.getElement(); - for (PsiClass psiClass : myClassesToMove) { - if (PsiTreeUtil.isAncestor(psiClass, element, false)) return true; - } - if (isInaccessibleFromTarget(element, PsiModifier.PACKAGE_LOCAL)) { - collector.addConflict(psiReference.resolve(), element); - } - return true; + ReferencesSearch.search(member).forEach(psiReference -> { + PsiElement element = psiReference.getElement(); + for (PsiClass psiClass : myClassesToMove) { + if (PsiTreeUtil.isAncestor(psiClass, element, false)) return true; } + if (isInaccessibleFromTarget(element, PsiModifier.PACKAGE_LOCAL)) { + collector.addConflict(psiReference.resolve(), element); + } + return true; }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesDialog.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesDialog.java index 7eb533e2ce3b..7566c589a853 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesDialog.java @@ -116,10 +116,8 @@ public class MoveClassesOrPackagesDialog extends MoveDialogBase { myInnerClassChooser.setText(((PsiClass)initialTargetElement).getQualifiedName()); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myInnerClassChooser.requestFocus(); - } + ApplicationManager.getApplication().invokeLater(() -> { + myInnerClassChooser.requestFocus(); }, ModalityState.stateForComponent(myMainPanel)); } else if (initialTargetElement instanceof PsiPackage) { diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java index b4fc0a915bb1..b6e02829a428 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java @@ -319,18 +319,10 @@ public class MoveClassesOrPackagesImpl { final PsiDirectory selectedTarget = chooser.getSelectedDirectory(); if (selectedTarget == null) return; final MultiMap conflicts = new MultiMap(); - final Runnable analyzeConflicts = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - RefactoringConflictsUtil - .analyzeModuleConflicts(project, Arrays.asList(directories), UsageInfo.EMPTY_ARRAY, selectedTarget, conflicts); - } - }); - } - }; + final Runnable analyzeConflicts = () -> ApplicationManager.getApplication().runReadAction(() -> { + RefactoringConflictsUtil + .analyzeModuleConflicts(project, Arrays.asList(directories), UsageInfo.EMPTY_ARRAY, selectedTarget, conflicts); + }); if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously(analyzeConflicts, "Analyze Module Conflicts...", true, project)) { return; @@ -348,26 +340,18 @@ public class MoveClassesOrPackagesImpl { } final Ref ex = Ref.create(null); final String commandDescription = RefactoringBundle.message("moving.directories.command"); - Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - LocalHistoryAction a = LocalHistory.getInstance().startAction(commandDescription); - try { - rearrangeDirectoriesToTarget(directories, selectedTarget); - } - catch (IncorrectOperationException e) { - ex.set(e); - } - finally { - a.finish(); - } - } - }); + Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> { + LocalHistoryAction a = LocalHistory.getInstance().startAction(commandDescription); + try { + rearrangeDirectoriesToTarget(directories, selectedTarget); } - }; + catch (IncorrectOperationException e) { + ex.set(e); + } + finally { + a.finish(); + } + }); CommandProcessor.getInstance().executeCommand(project, runnable, commandDescription, null); if (ex.get() != null) { RefactoringUIUtil.processIncorrectOperation(project, ex.get()); diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java index 5b508d4e728f..eeb7acb48cf6 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java @@ -90,22 +90,19 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor { } } myElementsToMove = PsiUtilCore.toPsiElementArray(toMove); - Arrays.sort(myElementsToMove, new Comparator() { - @Override - public int compare(PsiElement o1, PsiElement o2) { - if (o1 instanceof PsiClass && o2 instanceof PsiClass) { - final PsiFile containingFile = o1.getContainingFile(); - if (Comparing.equal(containingFile, o2.getContainingFile())) { - final VirtualFile virtualFile = containingFile.getVirtualFile(); - if (virtualFile != null) { - final String fileName = virtualFile.getNameWithoutExtension(); - if (Comparing.strEqual(fileName, ((PsiClass)o1).getName())) return -1; - if (Comparing.strEqual(fileName, ((PsiClass)o2).getName())) return 1; - } + Arrays.sort(myElementsToMove, (o1, o2) -> { + if (o1 instanceof PsiClass && o2 instanceof PsiClass) { + final PsiFile containingFile = o1.getContainingFile(); + if (Comparing.equal(containingFile, o2.getContainingFile())) { + final VirtualFile virtualFile = containingFile.getVirtualFile(); + if (virtualFile != null) { + final String fileName = virtualFile.getNameWithoutExtension(); + if (Comparing.strEqual(fileName, ((PsiClass)o1).getName())) return -1; + if (Comparing.strEqual(fileName, ((PsiClass)o2).getName())) return 1; } } - return 0; } + return 0; }); myMoveDestination = moveDestination; myTargetPackage = myMoveDestination.getTargetPackage(); @@ -395,27 +392,25 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor { final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(aClass.getContainingFile().getContainingDirectory()); final GlobalSearchScope packageScope = aPackage == null ? aClass.getResolveScope() : PackageScope.packageScopeWithoutLibraries(aPackage, false); for (final ClassMemberWrapper memberWrapper : members) { - ReferencesSearch.search(memberWrapper.getMember(), packageScope, false).forEach(new Processor() { - public boolean process(final PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element instanceof PsiReferenceExpression) { - final PsiReferenceExpression expression = (PsiReferenceExpression)element; - final PsiExpression qualifierExpression = expression.getQualifierExpression(); - if (qualifierExpression != null) { - final PsiType type = qualifierExpression.getType(); - if (type != null) { - final PsiClass resolvedTypeClass = PsiUtil.resolveClassInType(type); - if (isDescendantOf.value(resolvedTypeClass)) { - instanceReferenceVisitor.visitMemberReference(memberWrapper.getMember(), expression, isDescendantOf); - } + ReferencesSearch.search(memberWrapper.getMember(), packageScope, false).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element instanceof PsiReferenceExpression) { + final PsiReferenceExpression expression = (PsiReferenceExpression)element; + final PsiExpression qualifierExpression = expression.getQualifierExpression(); + if (qualifierExpression != null) { + final PsiType type = qualifierExpression.getType(); + if (type != null) { + final PsiClass resolvedTypeClass = PsiUtil.resolveClassInType(type); + if (isDescendantOf.value(resolvedTypeClass)) { + instanceReferenceVisitor.visitMemberReference(memberWrapper.getMember(), expression, isDescendantOf); } } - else { - instanceReferenceVisitor.visitMemberReference(memberWrapper.getMember(), expression, isDescendantOf); - } } - return true; + else { + instanceReferenceVisitor.visitMemberReference(memberWrapper.getMember(), expression, isDescendantOf); + } } + return true; }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java index 07969b60e542..73fbf9a1edc2 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java @@ -245,11 +245,8 @@ public class MoveClassesOrPackagesUtil { LOG.assertTrue(newClass != null, "name: " + aClassName + ", file: " + file + ", classes: " + StringUtil.join(((PsiClassOwner)file).getClasses(), - new Function() { - @Override - public String fun(PsiClass psiClass) { - return psiClass.getName(); - } + psiClass -> { + return psiClass.getName(); }, " ")); } } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java index 6dee66a833ff..0fb02b894306 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/JavaMoveFilesOrDirectoriesHandler.java @@ -84,33 +84,29 @@ public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHan return; } MoveFilesOrDirectoriesUtil - .doMove(project, elements, new PsiElement[]{targetContainer}, callback, new Function() { - @Override - public PsiElement[] fun(final PsiElement[] elements) { - return new WriteCommandAction(project, "Regrouping ...") { - @Override - protected void run(@NotNull Result result) throws Throwable { - final List adjustedElements = new ArrayList(); - for (int i = 0, length = elements.length; i < length; i++) { - PsiElement element = elements[i]; - if (element instanceof PsiClass) { - final PsiClass topLevelClass = PsiUtil.getTopLevelClass(element); - if (topLevelClass != null) { - elements[i] = topLevelClass; - final PsiFile containingFile = obtainContainingFile(topLevelClass, elements); - if (containingFile != null) { - adjustedElements.add(containingFile); - continue; + .doMove(project, elements, new PsiElement[]{targetContainer}, callback, + elements1 -> new WriteCommandAction(project, "Regrouping ...") { + @Override + protected void run(@NotNull Result result) throws Throwable { + final List adjustedElements = new ArrayList(); + for (int i = 0, length = elements1.length; i < length; i++) { + PsiElement element = elements1[i]; + if (element instanceof PsiClass) { + final PsiClass topLevelClass = PsiUtil.getTopLevelClass(element); + if (topLevelClass != null) { + elements1[i] = topLevelClass; + final PsiFile containingFile = obtainContainingFile(topLevelClass, elements1); + if (containingFile != null) { + adjustedElements.add(containingFile); + continue; + } + } } + adjustedElements.add(element); } + result.setResult(PsiUtilCore.toPsiElementArray(adjustedElements)); } - adjustedElements.add(element); - } - result.setResult(PsiUtilCore.toPsiElementArray(adjustedElements)); - } - }.execute().getResultObject(); - } - }); + }.execute().getResultObject()); } @Nullable diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java index 5f154132e3c2..32bd80d2156f 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java @@ -373,11 +373,8 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor { if (containerSet.size() == 1) { placesDescription = RefactoringUIUtil.getDescription(resolved, true); } else { - placesDescription = "
  1. " + StringUtil.join(containerSet, new Function() { - @Override - public String fun(PsiElement element) { - return RefactoringUIUtil.getDescription(element, true); - } + placesDescription = "
    1. " + StringUtil.join(containerSet, element -> { + return RefactoringUIUtil.getDescription(element, true); }, "
    2. ") + "
    "; } String message = RefactoringBundle.message("0.will.become.inaccessible.from.1", diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java index 43bcfcc7d455..77885bd27c0b 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java @@ -265,11 +265,7 @@ public class MoveJavaMemberHandler implements MoveMemberHandler { } if (!afterFields.isEmpty()) { - Collections.sort(afterFields, new Comparator() { - public int compare(final PsiField o1, final PsiField o2) { - return -PsiUtilCore.compareElementsByPosition(o1, o2); - } - }); + Collections.sort(afterFields, (o1, o2) -> -PsiUtilCore.compareElementsByPosition(o1, o2)); return afterFields.get(0); } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java index 261a907a6606..cd7001960972 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java @@ -282,20 +282,17 @@ public class MoveMembersDialog extends MoveDialogBase implements MoveMembersOpti else { RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, fqName); final PsiClass[] targetClass = new PsiClass[]{null}; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - try { - targetClass[0] = findOrCreateTargetClass(manager, fqName); - } - catch (IncorrectOperationException e) { - CommonRefactoringUtil.showErrorMessage( - MoveMembersImpl.REFACTORING_NAME, - e.getMessage(), - HelpID.MOVE_MEMBERS, - myProject); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + try { + targetClass[0] = findOrCreateTargetClass(manager, fqName); + } + catch (IncorrectOperationException e) { + CommonRefactoringUtil.showErrorMessage( + MoveMembersImpl.REFACTORING_NAME, + e.getMessage(), + HelpID.MOVE_MEMBERS, + myProject); } - }, RefactoringBundle.message("create.class.command", fqName), null); if (targetClass[0] == null) { diff --git a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaClassProcessor.java b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaClassProcessor.java index c7d6af0854bf..f54a2a57a9f2 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaClassProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaClassProcessor.java @@ -234,14 +234,12 @@ public class RenameJavaClassProcessor extends RenamePsiElementProcessor { PsiClass[] inners = superClass.getInnerClasses(); for (final PsiClass inner : inners) { if (newName.equals(inner.getName())) { - ReferencesSearch.search(inner).forEach(new Processor() { - public boolean process(final PsiReference reference) { - PsiElement refElement = reference.getElement(); - if (refElement instanceof PsiReferenceExpression && ((PsiReferenceExpression)refElement).isQualified()) return true; - MemberHidesOuterMemberUsageInfo info = new MemberHidesOuterMemberUsageInfo(refElement, aClass); - result.add(info); - return true; - } + ReferencesSearch.search(inner).forEach(reference -> { + PsiElement refElement = reference.getElement(); + if (refElement instanceof PsiReferenceExpression && ((PsiReferenceExpression)refElement).isQualified()) return true; + MemberHidesOuterMemberUsageInfo info = new MemberHidesOuterMemberUsageInfo(refElement, aClass); + result.add(info); + return true; }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMemberProcessor.java b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMemberProcessor.java index f0c8ec34d296..788108e465df 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMemberProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMemberProcessor.java @@ -128,16 +128,14 @@ public abstract class RenameJavaMemberProcessor extends RenamePsiElementProcesso conflict = aClass.findFieldByName(newName, false); } if (conflict == null) continue; - ReferencesSearch.search(conflict).forEach(new Processor() { - public boolean process(final PsiReference reference) { - PsiElement refElement = reference.getElement(); - if (refElement instanceof PsiReferenceExpression && ((PsiReferenceExpression)refElement).isQualified()) return true; - if (PsiTreeUtil.isAncestor(fieldClass, refElement, false)) { - MemberHidesOuterMemberUsageInfo info = new MemberHidesOuterMemberUsageInfo(refElement, member); - result.add(info); - } - return true; + ReferencesSearch.search(conflict).forEach(reference -> { + PsiElement refElement = reference.getElement(); + if (refElement instanceof PsiReferenceExpression && ((PsiReferenceExpression)refElement).isQualified()) return true; + if (PsiTreeUtil.isAncestor(fieldClass, refElement, false)) { + MemberHidesOuterMemberUsageInfo info = new MemberHidesOuterMemberUsageInfo(refElement, member); + result.add(info); } + return true; }); } } @@ -184,11 +182,9 @@ public abstract class RenameJavaMemberProcessor extends RenamePsiElementProcesso } for (PsiMember member : importedMembers) { - ReferencesSearch.search(member, new LocalSearchScope(containingFile), true).forEach(new Processor() { - public boolean process(final PsiReference psiReference) { - potentialConflicts.add(psiReference); - return true; - } + ReferencesSearch.search(member, new LocalSearchScope(containingFile), true).forEach(psiReference -> { + potentialConflicts.add(psiReference); + return true; }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMethodProcessor.java index ccda76179ae4..6d19758a7dd1 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMethodProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaMethodProcessor.java @@ -277,26 +277,24 @@ public class RenameJavaMethodProcessor extends RenameJavaMemberProcessor { @Override public void prepareRenaming(PsiElement element, final String newName, final Map allRenames, SearchScope scope) { final PsiMethod method = (PsiMethod) element; - OverridingMethodsSearch.search(method, scope, true).forEach(new Processor() { - public boolean process(PsiMethod overrider) { - if (overrider instanceof PsiMirrorElement) { - final PsiElement prototype = ((PsiMirrorElement)overrider).getPrototype(); - if (prototype instanceof PsiMethod) { - overrider = (PsiMethod)prototype; - } + OverridingMethodsSearch.search(method, scope, true).forEach(overrider -> { + if (overrider instanceof PsiMirrorElement) { + final PsiElement prototype = ((PsiMirrorElement)overrider).getPrototype(); + if (prototype instanceof PsiMethod) { + overrider = (PsiMethod)prototype; } - - if (overrider instanceof SyntheticElement) return true; - - final String overriderName = overrider.getName(); - final String baseName = method.getName(); - final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName); - if (newOverriderName != null) { - RenameProcessor.assertNonCompileElement(overrider); - allRenames.put(overrider, newOverriderName); - } - return true; } + + if (overrider instanceof SyntheticElement) return true; + + final String overriderName = overrider.getName(); + final String baseName = method.getName(); + final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName); + if (newOverriderName != null) { + RenameProcessor.assertNonCompileElement(overrider); + allRenames.put(overrider, newOverriderName); + } + return true; }); } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java index 056485e06c25..8c6e92b7a1dd 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/RenameJavaVariableProcessor.java @@ -260,12 +260,10 @@ public class RenameJavaVariableProcessor extends RenameJavaMemberProcessor { methods = new PsiMethod[] {methodPrototype}; } for (PsiMethod method : methods) { - OverridingMethodsSearch.search(method).forEach(new Processor() { - public boolean process(PsiMethod psiMethod) { - RenameProcessor.assertNonCompileElement(psiMethod); - addGetterOrSetterWithParameter(psiMethod, newName, newPropertyName, oldParameterName, manager, allRenames); - return true; - } + OverridingMethodsSearch.search(method).forEach(psiMethod -> { + RenameProcessor.assertNonCompileElement(psiMethod); + addGetterOrSetterWithParameter(psiMethod, newName, newPropertyName, oldParameterName, manager, allRenames); + return true; }); addGetterOrSetterWithParameter(method, newName, newPropertyName, oldParameterName, manager, allRenames); diff --git a/java/java-impl/src/com/intellij/refactoring/rename/RenamePsiPackageProcessor.java b/java/java-impl/src/com/intellij/refactoring/rename/RenamePsiPackageProcessor.java index b5338b90abe9..f7c00bbe389f 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/RenamePsiPackageProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/RenamePsiPackageProcessor.java @@ -175,14 +175,12 @@ public class RenamePsiPackageProcessor extends RenamePsiElementProcessor { final Project project = element.getProject(); final PsiPackage psiPackage = (PsiPackage)element; final String newQualifiedName = PsiUtilCore.getQualifiedNameAfterRename(psiPackage.getQualifiedName(), newName); - return new Runnable() { - public void run() { - final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(newQualifiedName); - if (aPackage == null) { - return; //rename failed e.g. when the dir is used by another app - } - listener.elementRenamed(aPackage); + return () -> { + final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(newQualifiedName); + if (aPackage == null) { + return; //rename failed e.g. when the dir is used by another app } + listener.elementRenamed(aPackage); }; } diff --git a/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java b/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java index 009230acd93b..b9700511d6cb 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java @@ -37,12 +37,10 @@ public abstract class AutomaticUsageRenamer { myOldName = oldName; myNewName = newName; List elements = new ArrayList(renamedElements); - Collections.sort(elements, new Comparator() { - public int compare(T o1, T o2) { - int i = StringUtil.compare(getSourceName(o1), getSourceName(o2), false); - if (i != 0) return i; - return getName(o1).compareTo(getName(o2)); - } + Collections.sort(elements, (o1, o2) -> { + int i = StringUtil.compare(getSourceName(o1), getSourceName(o2), false); + if (i != 0) return i; + return getName(o1).compareTo(getName(o2)); }); for (T element : elements) { String suggestedNewName = suggestName(element); diff --git a/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteDelegateImpl.java b/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteDelegateImpl.java index 0fb3425ef703..526417a06f0f 100644 --- a/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteDelegateImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteDelegateImpl.java @@ -74,11 +74,8 @@ public class JavaSafeDeleteDelegateImpl implements JavaSafeDeleteDelegate { newText.append("/** @see #").append(method.getName()).append('('); final List parameters = new ArrayList(Arrays.asList(method.getParameterList().getParameters())); parameters.remove(parameter); - newText.append(StringUtil.join(parameters, new Function() { - @Override - public String fun(PsiParameter psiParameter) { - return psiParameter.getType().getCanonicalText(); - } + newText.append(StringUtil.join(parameters, psiParameter -> { + return psiParameter.getType().getCanonicalText(); }, ",")); newText.append(")*/"); usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, parameter, true) { diff --git a/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java b/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java index 60ec2387c397..830ef80342c7 100644 --- a/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/safeDelete/JavaSafeDeleteProcessor.java @@ -137,11 +137,9 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { } for (PsiMethod superMethod : superMethods) { parametersToDelete.add(superMethod.getParameterList().getParameters()[parameterIndex]); - OverridingMethodsSearch.search(superMethod).forEach(new Processor() { - public boolean process(PsiMethod overrider) { - parametersToDelete.add(overrider.getParameterList().getParameters()[parameterIndex]); - return true; - } + OverridingMethodsSearch.search(superMethod).forEach(overrider -> { + parametersToDelete.add(overrider.getParameterList().getParameters()[parameterIndex]); + return true; }); } @@ -163,14 +161,12 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { if (index >= 0) { final ArrayList overriders = new ArrayList(); overriders.add((PsiTypeParameter)element); - OverridingMethodsSearch.search((PsiMethod)owner).forEach(new Processor() { - public boolean process(PsiMethod overrider) { - final PsiTypeParameter[] typeParameters = overrider.getTypeParameters(); - if (index < typeParameters.length) { - overriders.add(typeParameters[index]); - } - return true; + OverridingMethodsSearch.search((PsiMethod)owner).forEach(overrider -> { + final PsiTypeParameter[] typeParameters = overrider.getTypeParameters(); + if (index < typeParameters.length) { + overriders.add(typeParameters[index]); } + return true; }); if (overriders.size() > 1) { String message = RefactoringBundle.message("0.is.a.part.of.method.hierarchy.do.you.want.to.delete.multiple.type.parameters", UsageViewUtil.getLongName(owner)); @@ -352,11 +348,8 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { unselected.removeAll(selected); if (!unselected.isEmpty()) { - final List unselectedMethods = ContainerUtil.map(unselected, new Function() { - @Override - public PsiMethod fun(UsageInfo info) { - return ((SafeDeleteOverridingMethodUsageInfo)info).getOverridingMethod(); - } + final List unselectedMethods = ContainerUtil.map(unselected, info -> { + return ((SafeDeleteOverridingMethodUsageInfo)info).getOverridingMethod(); }); for (Iterator iterator = result.iterator(); iterator.hasNext(); ) { @@ -524,45 +517,43 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { final String qualifiedName = psiClass.getQualifiedName(); final boolean annotationType = psiClass.isAnnotationType() && qualifiedName != null; - ReferencesSearch.search(psiClass).forEach(new Processor() { - public boolean process(final PsiReference reference) { - final PsiElement element = reference.getElement(); + ReferencesSearch.search(psiClass).forEach(reference -> { + final PsiElement element = reference.getElement(); - if (!isInside(element, allElementsToDelete)) { - PsiElement parent = element.getParent(); - if (parent instanceof PsiReferenceList) { - final PsiElement pparent = parent.getParent(); - if (pparent instanceof PsiClass && element instanceof PsiJavaCodeReferenceElement) { - final PsiClass inheritor = (PsiClass) pparent; - //If psiClass contains only private members, then it is safe to remove it and change inheritor's extends/implements accordingly - if (justPrivates) { - if (parent.equals(inheritor.getExtendsList()) || parent.equals(inheritor.getImplementsList())) { - usages.add(new SafeDeleteExtendsClassUsageInfo((PsiJavaCodeReferenceElement)element, psiClass, inheritor)); - return true; - } + if (!isInside(element, allElementsToDelete)) { + PsiElement parent = element.getParent(); + if (parent instanceof PsiReferenceList) { + final PsiElement pparent = parent.getParent(); + if (pparent instanceof PsiClass && element instanceof PsiJavaCodeReferenceElement) { + final PsiClass inheritor = (PsiClass) pparent; + //If psiClass contains only private members, then it is safe to remove it and change inheritor's extends/implements accordingly + if (justPrivates) { + if (parent.equals(inheritor.getExtendsList()) || parent.equals(inheritor.getImplementsList())) { + usages.add(new SafeDeleteExtendsClassUsageInfo((PsiJavaCodeReferenceElement)element, psiClass, inheritor)); + return true; } } } - LOG.assertTrue(element.getTextRange() != null); - final PsiFile containingFile = psiClass.getContainingFile(); - boolean sameFileWithSingleClass = false; - if (containingFile instanceof PsiClassOwner) { - final PsiClass[] classes = ((PsiClassOwner)containingFile).getClasses(); - sameFileWithSingleClass = classes.length == 1 && - classes[0] == psiClass && - element.getContainingFile() == containingFile; - } - - final boolean safeDelete = sameFileWithSingleClass || isInNonStaticImport(element); - if (annotationType && parent instanceof PsiAnnotation) { - usages.add(new SafeDeleteAnnotation((PsiAnnotation)parent, psiClass, safeDelete)); - } - else { - usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, safeDelete)); - } } - return true; + LOG.assertTrue(element.getTextRange() != null); + final PsiFile containingFile = psiClass.getContainingFile(); + boolean sameFileWithSingleClass = false; + if (containingFile instanceof PsiClassOwner) { + final PsiClass[] classes = ((PsiClassOwner)containingFile).getClasses(); + sameFileWithSingleClass = classes.length == 1 && + classes[0] == psiClass && + element.getContainingFile() == containingFile; + } + + final boolean safeDelete = sameFileWithSingleClass || isInNonStaticImport(element); + if (annotationType && parent instanceof PsiAnnotation) { + usages.add(new SafeDeleteAnnotation((PsiAnnotation)parent, psiClass, safeDelete)); + } + else { + usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, safeDelete)); + } } + return true; }); } @@ -615,20 +606,18 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { final int paramsCount = parameterList.getTypeParameters().length; final int index = parameterList.getTypeParameterIndex(typeParameter); - ReferencesSearch.search(owner).forEach(new Processor() { - public boolean process(final PsiReference reference) { - if (reference instanceof PsiJavaCodeReferenceElement) { - final PsiReferenceParameterList parameterList = ((PsiJavaCodeReferenceElement)reference).getParameterList(); - if (parameterList != null) { - PsiTypeElement[] typeArgs = parameterList.getTypeParameterElements(); - if (typeArgs.length > index) { - if (typeArgs.length == 1 && paramsCount > 1 && typeArgs[0].getType() instanceof PsiDiamondType) return true; - usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(typeArgs[index], typeParameter, true)); - } + ReferencesSearch.search(owner).forEach(reference -> { + if (reference instanceof PsiJavaCodeReferenceElement) { + final PsiReferenceParameterList parameterList1 = ((PsiJavaCodeReferenceElement)reference).getParameterList(); + if (parameterList1 != null) { + PsiTypeElement[] typeArgs = parameterList1.getTypeParameterElements(); + if (typeArgs.length > index) { + if (typeArgs.length == 1 && paramsCount > 1 && typeArgs[0].getType() instanceof PsiDiamondType) return true; + usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(typeArgs[index], typeParameter, true)); } } - return true; } + return true; }); } } @@ -680,12 +669,9 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { private static void findFunctionalExpressions(final List usages, PsiMethod... methods) { for (PsiMethod method : methods) { final PsiClass containingClass = method.getContainingClass(); - FunctionalExpressionSearch.search(method).forEach(new Processor() { - @Override - public boolean process(PsiFunctionalExpression expression) { - usages.add(new SafeDeleteFunctionalExpressionUsageInfo(expression, containingClass)); - return true; - } + FunctionalExpressionSearch.search(method).forEach(expression -> { + usages.add(new SafeDeleteFunctionalExpressionUsageInfo(expression, containingClass)); + return true; }); } } @@ -878,23 +864,21 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { private static Condition findFieldUsages(final PsiField psiField, final List usages, final PsiElement[] allElementsToDelete) { final Condition isInsideDeleted = getUsageInsideDeletedFilter(allElementsToDelete); - ReferencesSearch.search(psiField).forEach(new Processor() { - public boolean process(final PsiReference reference) { - if (!isInsideDeleted.value(reference.getElement())) { - final PsiElement element = reference.getElement(); - final PsiElement parent = element.getParent(); - if (parent instanceof PsiAssignmentExpression && element == ((PsiAssignmentExpression)parent).getLExpression()) { - usages.add(new SafeDeleteFieldWriteReference((PsiAssignmentExpression)parent, psiField)); - } - else { - TextRange range = reference.getRangeInElement(); - usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(reference.getElement(), psiField, range.getStartOffset(), - range.getEndOffset(), false, PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class) != null)); - } + ReferencesSearch.search(psiField).forEach(reference -> { + if (!isInsideDeleted.value(reference.getElement())) { + final PsiElement element = reference.getElement(); + final PsiElement parent = element.getParent(); + if (parent instanceof PsiAssignmentExpression && element == ((PsiAssignmentExpression)parent).getLExpression()) { + usages.add(new SafeDeleteFieldWriteReference((PsiAssignmentExpression)parent, psiField)); + } + else { + TextRange range = reference.getRangeInElement(); + usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(reference.getElement(), psiField, range.getStartOffset(), + range.getEndOffset(), false, PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class) != null)); } - - return true; } + + return true; }); return isInsideDeleted; @@ -905,58 +889,54 @@ public class JavaSafeDeleteProcessor extends SafeDeleteProcessorDelegateBase { final PsiMethod method = (PsiMethod)parameter.getDeclarationScope(); final int parameterIndex = method.getParameterList().getParameterIndex(parameter); //search for refs to current method only, do not search for refs to overriding methods, they'll be searched separately - ReferencesSearch.search(method).forEach(new Processor() { - public boolean process(final PsiReference reference) { - PsiElement element = reference.getElement(); - if (element != null) { - final JavaSafeDeleteDelegate safeDeleteDelegate = JavaSafeDeleteDelegate.EP.forLanguage(element.getLanguage()); - if (safeDeleteDelegate != null) { - safeDeleteDelegate.createUsageInfoForParameter(reference, usages, parameter, method); - } - if (!parameter.isVarArgs() && !RefactoringChangeUtil.isSuperMethodCall(element.getParent())) { - final PsiParameter paramInCaller = SafeDeleteJavaCallerChooser.isTheOnlyOneParameterUsage(element.getParent(), parameterIndex, method); - if (paramInCaller != null) { - final PsiMethod callerMethod = (PsiMethod)paramInCaller.getDeclarationScope(); - if (ApplicationManager.getApplication().isUnitTestMode()) { - usages.add(new SafeDeleteParameterCallHierarchyUsageInfo(callerMethod, paramInCaller, callerMethod)); - } - else { - usages.add(new SafeDeleteParameterCallHierarchyUsageInfo(method, parameter, callerMethod)); - } + ReferencesSearch.search(method).forEach(reference -> { + PsiElement element = reference.getElement(); + if (element != null) { + final JavaSafeDeleteDelegate safeDeleteDelegate = JavaSafeDeleteDelegate.EP.forLanguage(element.getLanguage()); + if (safeDeleteDelegate != null) { + safeDeleteDelegate.createUsageInfoForParameter(reference, usages, parameter, method); + } + if (!parameter.isVarArgs() && !RefactoringChangeUtil.isSuperMethodCall(element.getParent())) { + final PsiParameter paramInCaller = SafeDeleteJavaCallerChooser.isTheOnlyOneParameterUsage(element.getParent(), parameterIndex, method); + if (paramInCaller != null) { + final PsiMethod callerMethod = (PsiMethod)paramInCaller.getDeclarationScope(); + if (ApplicationManager.getApplication().isUnitTestMode()) { + usages.add(new SafeDeleteParameterCallHierarchyUsageInfo(callerMethod, paramInCaller, callerMethod)); + } + else { + usages.add(new SafeDeleteParameterCallHierarchyUsageInfo(method, parameter, callerMethod)); } } } - return true; } + return true; }); - ReferencesSearch.search(parameter).forEach(new Processor() { - public boolean process(final PsiReference reference) { - PsiElement element = reference.getElement(); - final PsiDocTag docTag = PsiTreeUtil.getParentOfType(element, PsiDocTag.class); - if (docTag != null) { - usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(docTag, parameter, true)); - return true; - } - - boolean isSafeDelete = false; - if (element.getParent().getParent() instanceof PsiMethodCallExpression) { - PsiMethodCallExpression call = (PsiMethodCallExpression)element.getParent().getParent(); - PsiReferenceExpression methodExpression = call.getMethodExpression(); - if (methodExpression.getText().equals(PsiKeyword.SUPER)) { - isSafeDelete = true; - } - else if (methodExpression.getQualifierExpression() instanceof PsiSuperExpression) { - final PsiMethod superMethod = call.resolveMethod(); - if (superMethod != null && MethodSignatureUtil.isSuperMethod(superMethod, method)) { - isSafeDelete = true; - } - } - } - - usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, parameter, isSafeDelete)); + ReferencesSearch.search(parameter).forEach(reference -> { + PsiElement element = reference.getElement(); + final PsiDocTag docTag = PsiTreeUtil.getParentOfType(element, PsiDocTag.class); + if (docTag != null) { + usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(docTag, parameter, true)); return true; } + + boolean isSafeDelete = false; + if (element.getParent().getParent() instanceof PsiMethodCallExpression) { + PsiMethodCallExpression call = (PsiMethodCallExpression)element.getParent().getParent(); + PsiReferenceExpression methodExpression = call.getMethodExpression(); + if (methodExpression.getText().equals(PsiKeyword.SUPER)) { + isSafeDelete = true; + } + else if (methodExpression.getQualifierExpression() instanceof PsiSuperExpression) { + final PsiMethod superMethod = call.resolveMethod(); + if (superMethod != null && MethodSignatureUtil.isSuperMethod(superMethod, method)) { + isSafeDelete = true; + } + } + } + + usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, parameter, isSafeDelete)); + return true; }); findFunctionalExpressions(usages, method); diff --git a/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCalleeChooser.java b/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCalleeChooser.java index 6989cfaa1ed4..7a9db5119e70 100644 --- a/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCalleeChooser.java +++ b/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCalleeChooser.java @@ -38,17 +38,9 @@ abstract class SafeDeleteJavaCalleeChooser extends JavaCallerChooser { private final Project myProject; public SafeDeleteJavaCalleeChooser(final PsiMethod method, Project project, final ArrayList result) { - super(method, project, "Select Methods To Cascade Safe Delete", null, new Consumer>() { - @Override - public void consume(Set methods) { - result.addAll(ContainerUtil.map(methods, new Function() { - @Override - public SafeDeleteReferenceJavaDeleteUsageInfo fun(PsiMethod m) { - return new SafeDeleteReferenceJavaDeleteUsageInfo(m, m, true); - } - })); - } - }); + super(method, project, "Select Methods To Cascade Safe Delete", null, methods -> result.addAll(ContainerUtil.map(methods, m -> { + return new SafeDeleteReferenceJavaDeleteUsageInfo(m, m, true); + }))); myProject = project; } @@ -130,11 +122,8 @@ abstract class SafeDeleteJavaCalleeChooser extends JavaCallerChooser { @Override protected List computeCallers() { if (getTopMethod().equals(getMethod())) { - return ContainerUtil.map(getTopLevelItems(), new Function() { - @Override - public PsiMethod fun(SafeDeleteMethodCalleeUsageInfo info) { - return info.getCalledMethod(); - } + return ContainerUtil.map(getTopLevelItems(), info -> { + return info.getCalledMethod(); }); } diff --git a/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCallerChooser.java b/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCallerChooser.java index 25eb65843865..6fe82fe4cbd0 100644 --- a/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCallerChooser.java +++ b/java/java-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteJavaCallerChooser.java @@ -68,35 +68,26 @@ abstract class SafeDeleteJavaCallerChooser extends JavaCallerChooser { @Override protected void doOKAction() { final List foreignMethodUsages = new ArrayList(); - final Runnable runnable = new Runnable() { - public void run() { - final Set> nodes = getSelectedNodes(); - for (MethodNodeBase node : nodes) { - final SafeDeleteJavaMethodNode methodNode = (SafeDeleteJavaMethodNode)node; - final PsiMethod nodeMethod = methodNode.getMethod(); - if (nodeMethod.equals(myMethod)) continue; - final PsiParameter parameter = nodeMethod.getParameterList().getParameters()[methodNode.myParameterIdx]; - foreignMethodUsages.add(new SafeDeleteParameterCallHierarchyUsageInfo(nodeMethod, parameter, nodeMethod)); - ReferencesSearch.search(nodeMethod).forEach(new Processor() { - public boolean process(final PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element != null) { - JavaSafeDeleteDelegate.EP.forLanguage(element.getLanguage()) - .createUsageInfoForParameter(reference, foreignMethodUsages, parameter, nodeMethod); - } - return true; - } - }); - } + final Runnable runnable = () -> { + final Set> nodes = getSelectedNodes(); + for (MethodNodeBase node : nodes) { + final SafeDeleteJavaMethodNode methodNode = (SafeDeleteJavaMethodNode)node; + final PsiMethod nodeMethod = methodNode.getMethod(); + if (nodeMethod.equals(myMethod)) continue; + final PsiParameter parameter = nodeMethod.getParameterList().getParameters()[methodNode.myParameterIdx]; + foreignMethodUsages.add(new SafeDeleteParameterCallHierarchyUsageInfo(nodeMethod, parameter, nodeMethod)); + ReferencesSearch.search(nodeMethod).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element != null) { + JavaSafeDeleteDelegate.EP.forLanguage(element.getLanguage()) + .createUsageInfoForParameter(reference, foreignMethodUsages, parameter, nodeMethod); + } + return true; + }); } }; - if (ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(runnable); - } - }, "Search for Caller Method Usages...", true, myProject)) { + if (ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(runnable), "Search for Caller Method Usages...", true, myProject)) { myResult.addAll(foreignMethodUsages); } super.doOKAction(); @@ -205,11 +196,8 @@ abstract class SafeDeleteJavaCallerChooser extends JavaCallerChooser { protected List computeCallers() { if (getTopMethod().equals(getMethod())) { final ArrayList items = getTopLevelItems(); - return ContainerUtil.map(items, new Function() { - @Override - public PsiMethod fun(SafeDeleteParameterCallHierarchyUsageInfo info) { - return info.getCallerMethod(); - } + return ContainerUtil.map(items, info -> { + return info.getCallerMethod(); }); } final List methods = super.computeCallers(); @@ -236,19 +224,16 @@ abstract class SafeDeleteJavaCallerChooser extends JavaCallerChooser { //find first method call final Ref ref = new Ref(); - ReferencesSearch.search(myMethod, new LocalSearchScope(caller)).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element instanceof PsiReferenceExpression) { - final PsiElement elementParent = element.getParent(); - if (elementParent instanceof PsiCallExpression) { - ref.set(isTheOnlyOneParameterUsage(elementParent, myParameterIdx, myMethod)); - return false; - } + ReferencesSearch.search(myMethod, new LocalSearchScope(caller)).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element instanceof PsiReferenceExpression) { + final PsiElement elementParent = element.getParent(); + if (elementParent instanceof PsiCallExpression) { + ref.set(isTheOnlyOneParameterUsage(elementParent, myParameterIdx, myMethod)); + return false; } - return true; } + return true; }); return ref.get(); } diff --git a/java/java-impl/src/com/intellij/refactoring/tempWithQuery/TempWithQueryHandler.java b/java/java-impl/src/com/intellij/refactoring/tempWithQuery/TempWithQueryHandler.java index 49746f800ffd..9a3f209ed2dd 100644 --- a/java/java-impl/src/com/intellij/refactoring/tempWithQuery/TempWithQueryHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/tempWithQuery/TempWithQueryHandler.java @@ -130,42 +130,36 @@ public class TempWithQueryHandler implements RefactoringActionHandler { if (processor.showDialog()) { CommandProcessor.getInstance().executeCommand( - project, new Runnable() { - public void run() { - final Runnable action = new Runnable() { - public void run() { - try { - processor.doRefactoring(); + project, () -> { + final Runnable action = () -> { + try { + processor.doRefactoring(); - local.normalizeDeclaration(); + local.normalizeDeclaration(); - PsiExpression initializer = local.getInitializer(); + PsiExpression initializer1 = local.getInitializer(); - PsiExpression[] exprs = new PsiExpression[refs.length]; - for (int idx = 0; idx < refs.length; idx++) { - PsiElement ref = refs[idx].getElement(); - exprs[idx] = (PsiExpression) ref.replace(initializer); - } - PsiDeclarationStatement declaration = (PsiDeclarationStatement) local.getParent(); - declaration.delete(); + PsiExpression[] exprs = new PsiExpression[refs.length]; + for (int idx = 0; idx < refs.length; idx++) { + PsiElement ref = refs[idx].getElement(); + exprs[idx] = (PsiExpression) ref.replace(initializer1); + } + PsiDeclarationStatement declaration = (PsiDeclarationStatement) local.getParent(); + declaration.delete(); - highlightManager.addOccurrenceHighlights(editor, exprs, attributes, true, null); - } catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }; + highlightManager.addOccurrenceHighlights(editor, exprs, attributes, true, null); + } catch (IncorrectOperationException e) { + LOG.error(e); + } + }; - PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable () { - public void run() { - ApplicationManager.getApplication().runWriteAction(action); - DuplicatesImpl.processDuplicates(processor, project, editor); - } - }); - } - }, - REFACTORING_NAME, - null + PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(() -> { + ApplicationManager.getApplication().runWriteAction(action); + DuplicatesImpl.processDuplicates(processor, project, editor); + }); + }, + REFACTORING_NAME, + null ); } diff --git a/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperProcessorBase.java b/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperProcessorBase.java index 72efe792c13a..a672b5ebeb9d 100644 --- a/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperProcessorBase.java +++ b/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperProcessorBase.java @@ -96,17 +96,9 @@ public abstract class TurnRefsToSuperProcessorBase extends BaseRefactoringProces myVariablesRenames.put(pointer, variableRenamer.getNewName(variable)); } - Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - variableRenamer.findUsages(myVariablesUsages, false, false); - } - }); - } - }; + Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> { + variableRenamer.findUsages(myVariablesUsages, false, false); + }); if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) { @@ -369,45 +361,42 @@ public abstract class TurnRefsToSuperProcessorBase extends BaseRefactoringProces final PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(ownerClass, inheritingClass, PsiSubstitutor.EMPTY); if (substitutor == null) return; final LocalSearchScope baseScope = new LocalSearchScope(ownerClass); - ReferencesSearch.search(typeParameter, baseScope).forEach(new Processor() { - @Override - public boolean process(final PsiReference ref) { - final PsiElement element = ref.getElement(); - final PsiElement parent = element.getParent(); - if (parent instanceof PsiTypeElement) { - final PsiElement pparent = parent.getParent(); - if (pparent instanceof PsiMethod && parent.equals(((PsiMethod)pparent).getReturnTypeElement())) { - final PsiMethod method = (PsiMethod)pparent; + ReferencesSearch.search(typeParameter, baseScope).forEach(ref -> { + final PsiElement element = ref.getElement(); + final PsiElement parent = element.getParent(); + if (parent instanceof PsiTypeElement) { + final PsiElement pparent = parent.getParent(); + if (pparent instanceof PsiMethod && parent.equals(((PsiMethod)pparent).getReturnTypeElement())) { + final PsiMethod method = (PsiMethod)pparent; + final MethodSignature signature = method.getSignature(substitutor); + if (PsiUtil.isAccessible(method, inheritingClass, null)) { + final PsiMethod inInheritor = MethodSignatureUtil.findMethodBySignature(inheritingClass, signature, false); + if (inInheritor != null && inInheritor.getReturnTypeElement() != null) { + addLink(instantiation, method.getReturnTypeElement()); + addLink(method.getReturnTypeElement(), instantiation); + } + } + } else if (pparent instanceof PsiParameter) { + final PsiParameter parameter = (PsiParameter)pparent; + if (parameter.getDeclarationScope() instanceof PsiMethod) { + PsiMethod method = (PsiMethod)parameter.getDeclarationScope(); + final int index = ((PsiParameterList)parameter.getParent()).getParameterIndex(parameter); final MethodSignature signature = method.getSignature(substitutor); if (PsiUtil.isAccessible(method, inheritingClass, null)) { final PsiMethod inInheritor = MethodSignatureUtil.findMethodBySignature(inheritingClass, signature, false); - if (inInheritor != null && inInheritor.getReturnTypeElement() != null) { - addLink(instantiation, method.getReturnTypeElement()); - addLink(method.getReturnTypeElement(), instantiation); - } - } - } else if (pparent instanceof PsiParameter) { - final PsiParameter parameter = (PsiParameter)pparent; - if (parameter.getDeclarationScope() instanceof PsiMethod) { - PsiMethod method = (PsiMethod)parameter.getDeclarationScope(); - final int index = ((PsiParameterList)parameter.getParent()).getParameterIndex(parameter); - final MethodSignature signature = method.getSignature(substitutor); - if (PsiUtil.isAccessible(method, inheritingClass, null)) { - final PsiMethod inInheritor = MethodSignatureUtil.findMethodBySignature(inheritingClass, signature, false); - if (inInheritor != null) { - final PsiParameter[] inheritorParams = inInheritor.getParameterList().getParameters(); - LOG.assertTrue(inheritorParams.length > index); - final PsiTypeElement hisTypeElement = inheritorParams[index].getTypeElement(); - addLink(instantiation, hisTypeElement); - addLink(hisTypeElement, instantiation); - } + if (inInheritor != null) { + final PsiParameter[] inheritorParams = inInheritor.getParameterList().getParameters(); + LOG.assertTrue(inheritorParams.length > index); + final PsiTypeElement hisTypeElement = inheritorParams[index].getTypeElement(); + addLink(instantiation, hisTypeElement); + addLink(hisTypeElement, instantiation); } } } } - - return true; } + + return true; }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/builder/ReductionSystem.java b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/builder/ReductionSystem.java index a23d6d033c74..35ea8055ac1d 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/builder/ReductionSystem.java +++ b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/builder/ReductionSystem.java @@ -356,11 +356,7 @@ public class ReductionSystem { } Arrays.sort(data, - new Comparator() { - public int compare(String x, String y) { - return x.compareTo(y); - } - }); + (x, y) -> x.compareTo(y)); final StringBuffer repr = new StringBuffer(); @@ -473,11 +469,7 @@ public class ReductionSystem { } Arrays.sort(data, - new Comparator() { - public int compare(String x, String y) { - return x.compareTo(y); - } - }); + (x, y) -> x.compareTo(y)); final StringBuffer repr = new StringBuffer(); diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeEvaluator.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeEvaluator.java index 1f882cef4089..85f71f8ede7a 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeEvaluator.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeEvaluator.java @@ -360,10 +360,8 @@ public class TypeEvaluator { if (types != null) { b.append(info.getElement()).append(" : "); - b.append(StringUtil.join(types, new Function() { - public String fun(final PsiType psiType) { - return psiType.getCanonicalText(); - } + b.append(StringUtil.join(types, psiType -> { + return psiType.getCanonicalText(); }, " ")); b.append("\n"); diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java index fa1d972a4990..4a8cead18e43 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java @@ -128,12 +128,7 @@ public class TypeMigrationLabeler { public UsageInfo[] getFailedUsages(final TypeMigrationUsageInfo root) { return map2Usages(ContainerUtil.mapNotNull(myFailedConversions.entrySet(), - new Function, PsiType>, TypeMigrationUsageInfo>, Pair, PsiType>>() { - @Override - public Pair, PsiType> fun(Map.Entry, PsiType>, TypeMigrationUsageInfo> entry) { - return entry.getValue().equals(root) ? entry.getKey() : null; - } - })); + entry -> entry.getValue().equals(root) ? entry.getKey() : null)); } public UsageInfo[] getFailedUsages() { @@ -143,9 +138,7 @@ public class TypeMigrationLabeler { @NotNull private static UsageInfo[] map2Usages(Collection, PsiType>> usages) { return ContainerUtil - .map2Array(usages, new UsageInfo[usages.size()], new Function, PsiType>, UsageInfo>() { - @Override - public UsageInfo fun(final Pair, PsiType> pair) { + .map2Array(usages, new UsageInfo[usages.size()], pair -> { final PsiExpression expr = pair.getFirst().getElement(); LOG.assertTrue(expr != null); return new UsageInfo(expr) { @@ -157,8 +150,7 @@ public class TypeMigrationLabeler { type.getCanonicalText() + " to " + pair.getSecond().getCanonicalText(); } }; - } - }); + }); } public TypeMigrationUsageInfo[] getMigratedUsages() { @@ -216,11 +208,8 @@ public class TypeMigrationLabeler { final Set infos = new HashSet(); for (Map.Entry>> entry : myRootsTree.entrySet()) { infos.add(entry.getKey()); - infos.addAll(ContainerUtil.map(entry.getValue(), new Function, TypeMigrationUsageInfo>() { - @Override - public TypeMigrationUsageInfo fun(Pair pair) { - return pair.getFirst(); - } + infos.addAll(ContainerUtil.map(entry.getValue(), pair -> { + return pair.getFirst(); })); } return infos; @@ -233,49 +222,43 @@ public class TypeMigrationLabeler { return Collections.emptyList().iterator(); } final List in = - ContainerUtil.map(rawNodes, new Function, TypeMigrationUsageInfo>() { - @Override - public TypeMigrationUsageInfo fun(Pair pair) { - return pair.getFirst(); - } + ContainerUtil.map(rawNodes, pair -> { + return pair.getFirst(); }); return in.iterator(); } })); final Comparator cmp = builder.comparator(); - Arrays.sort(infos, new Comparator() { - @Override - public int compare(final TypeMigrationUsageInfo info1, final TypeMigrationUsageInfo info2) { - final TypeMigrationUsageInfo i1 = info1.getOwnerRoot(); - final TypeMigrationUsageInfo i2 = info2.getOwnerRoot(); - if (i1 == null && i2 == null) { - return 0; - } - if (i1 == null) { - return 1; - } - if (i2 == null) { - return -1; - } - final PsiElement element1 = info1.getElement(); - final PsiElement element2 = info2.getElement(); - LOG.assertTrue(element1 != null && element2 != null); - final TextRange range1 = element1.getTextRange(); - final TextRange range2 = element2.getTextRange(); - if (range1.contains(range2)) { - return 1; - } - if (range2.contains(range1)) { - return -1; - } - - final int res = cmp.compare(i1, i2); - if (res != 0) { - return res; - } - return range2.getStartOffset() - range1.getStartOffset(); + Arrays.sort(infos, (info1, info2) -> { + final TypeMigrationUsageInfo i1 = info1.getOwnerRoot(); + final TypeMigrationUsageInfo i2 = info2.getOwnerRoot(); + if (i1 == null && i2 == null) { + return 0; } + if (i1 == null) { + return 1; + } + if (i2 == null) { + return -1; + } + final PsiElement element1 = info1.getElement(); + final PsiElement element2 = info2.getElement(); + LOG.assertTrue(element1 != null && element2 != null); + final TextRange range1 = element1.getTextRange(); + final TextRange range2 = element2.getTextRange(); + if (range1.contains(range2)) { + return 1; + } + if (range2.contains(range1)) { + return -1; + } + + final int res = cmp.compare(i1, i2); + if (res != 0) { + return res; + } + return range2.getStartOffset() - range1.getStartOffset(); }); return infos; @@ -760,14 +743,12 @@ public class TypeMigrationLabeler { myShowWarning = false; myDialogSemaphore.down(); try { - final Runnable checkTimeToStopRunnable = new Runnable() { - public void run() { - if (Messages.showYesNoCancelDialog("Found more than 10 roots to migrate. Do you want to preview?", "Type Migration", - Messages.getWarningIcon()) == Messages.YES) { - myException = new MigrateException(); - } - myDialogSemaphore.up(); + final Runnable checkTimeToStopRunnable = () -> { + if (Messages.showYesNoCancelDialog("Found more than 10 roots to migrate. Do you want to preview?", "Type Migration", + Messages.getWarningIcon()) == Messages.YES) { + myException = new MigrateException(); } + myDialogSemaphore.up(); }; SwingUtilities.invokeLater(checkTimeToStopRunnable); } @@ -877,11 +858,7 @@ public class TypeMigrationLabeler { } } - Collections.sort(validReferences, new Comparator() { - public int compare(final PsiReference o1, final PsiReference o2) { - return o1.getElement().getTextOffset() - o2.getElement().getTextOffset(); - } - }); + Collections.sort(validReferences, (o1, o2) -> o1.getElement().getTextOffset() - o2.getElement().getTextOffset()); return validReferences.toArray(new PsiReference[validReferences.size()]); } @@ -1098,11 +1075,7 @@ public class TypeMigrationLabeler { } } - Arrays.sort(conversions, new Comparator() { - public int compare(String x, String y) { - return x.compareTo(y); - } - }); + Arrays.sort(conversions, (x, y) -> x.compareTo(y)); for (String conversion : conversions) { buffer.append(conversion); @@ -1118,11 +1091,7 @@ public class TypeMigrationLabeler { newChanges[k++] = (element != null ? element.getText() : entry.getKey()) + " -> " + entry.getValue().getCanonicalText() + "\n"; } - Arrays.sort(newChanges, new Comparator() { - public int compare(String x, String y) { - return x.compareTo(y); - } - }); + Arrays.sort(newChanges, (x, y) -> x.compareTo(y)); for (String change : newChanges) { buffer.append(change); @@ -1132,13 +1101,11 @@ public class TypeMigrationLabeler { final ArrayList, PsiType>> failsList = new ArrayList, PsiType>>(myFailedConversions.keySet()); - Collections.sort(failsList, new Comparator, PsiType>>() { - public int compare(final Pair, PsiType> o1, final Pair, PsiType> o2) { - final PsiElement element1 = o1.getFirst().getElement(); - final PsiElement element2 = o2.getFirst().getElement(); - if (element1 == null || element2 == null) return 0; - return element1.getText().compareTo(element2.getText()); - } + Collections.sort(failsList, (o1, o2) -> { + final PsiElement element1 = o1.getFirst().getElement(); + final PsiElement element2 = o2.getFirst().getElement(); + if (element1 == null || element2 == null) return 0; + return element1.getText().compareTo(element2.getText()); }); for (final Pair, PsiType> p : failsList) { diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationProcessor.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationProcessor.java index b5024b56862f..bfe09bba59e6 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationProcessor.java @@ -84,35 +84,30 @@ public class TypeMigrationProcessor extends BaseRefactoringProcessor { final PsiElement[] roots, final Function migrationTypeFunction, final boolean optimizeImports) { - final Set containingFiles = ContainerUtil.map2Set(roots, new Function() { - @Override - public PsiFile fun(PsiElement element) { - return element.getContainingFile(); - } + final Set containingFiles = ContainerUtil.map2Set(roots, element -> { + return element.getContainingFile(); }); final TypeMigrationProcessor processor = new TypeMigrationProcessor(project, roots, migrationTypeFunction, rules) { @Override public void performRefactoring(@NotNull final UsageInfo[] usages) { super.performRefactoring(usages); if (editor != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - final List result = new ArrayList(); - for (UsageInfo usage : usages) { - final PsiElement element = usage.getElement(); - if (element == null || !containingFiles.contains(element.getContainingFile())) continue; - if (element instanceof PsiMethod) { - result.add(((PsiMethod)element).getReturnTypeElement()); - } - else if (element instanceof PsiVariable) { - result.add(((PsiVariable)element).getTypeElement()); - } - else { - result.add(element); - } + ApplicationManager.getApplication().invokeLater(() -> { + final List result = new ArrayList(); + for (UsageInfo usage : usages) { + final PsiElement element = usage.getElement(); + if (element == null || !containingFiles.contains(element.getContainingFile())) continue; + if (element instanceof PsiMethod) { + result.add(((PsiMethod)element).getReturnTypeElement()); + } + else if (element instanceof PsiVariable) { + result.add(((PsiVariable)element).getTypeElement()); + } + else { + result.add(element); } - RefactoringUtil.highlightAllOccurrences(project, PsiUtilCore.toPsiElementArray(result), editor); } + RefactoringUtil.highlightAllOccurrences(project, PsiUtilCore.toPsiElementArray(result), editor); }); } if (optimizeImports) { diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/ui/MigrationPanel.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/ui/MigrationPanel.java index 4479fb65b444..d1d3add84435 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/ui/MigrationPanel.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/ui/MigrationPanel.java @@ -134,20 +134,14 @@ public class MigrationPanel extends JPanel implements Disposable { add(conflictsSplitter, BorderLayout.CENTER); Disposer.register(this, myConflictsPanel); - builder.addSubtreeToUpdate((DefaultMutableTreeNode)myRootsTree.getModel().getRoot(), new Runnable() { - public void run() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (builder.isDisposed()) return; - myRootsTree.expandPath(new TreePath(myRootsTree.getModel().getRoot())); - final Collection children = currentRoot.getChildren(); - if (!children.isEmpty()) { - builder.select(children.iterator().next()); - } - } - }); + builder.addSubtreeToUpdate((DefaultMutableTreeNode)myRootsTree.getModel().getRoot(), () -> SwingUtilities.invokeLater(() -> { + if (builder.isDisposed()) return; + myRootsTree.expandPath(new TreePath(myRootsTree.getModel().getRoot())); + final Collection children = currentRoot.getChildren(); + if (!children.isEmpty()) { + builder.select(children.iterator().next()); } - }); + })); Disposer.register(this, builder); } @@ -181,10 +175,8 @@ public class MigrationPanel extends JPanel implements Disposable { if (!migrationNode.getInfo().isExcluded() || migrationNode.areChildrenInitialized()) { //do not walk into excluded collapsed nodes: nothing to migrate can be found final Collection nodes = migrationNode.getChildren(); for (final AbstractTreeNode node : nodes) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - expandTree((MigrationNode)node); - } + ApplicationManager.getApplication().runReadAction(() -> { + expandTree((MigrationNode)node); }); } } @@ -195,45 +187,40 @@ public class MigrationPanel extends JPanel implements Disposable { if (root instanceof DefaultMutableTreeNode) { final Object userObject = ((DefaultMutableTreeNode)root).getUserObject(); if (userObject instanceof MigrationRootNode) { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - final HashSet files = new HashSet(); - final TypeMigrationUsageInfo[] usages = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public TypeMigrationUsageInfo[] compute() { - final Collection children = ((MigrationRootNode)userObject).getChildren(); - for (AbstractTreeNode child : children) { - expandTree((MigrationNode)child); - } - final TypeMigrationUsageInfo[] usages = myLabeler.getMigratedUsages(); - for (TypeMigrationUsageInfo usage : usages) { - if (!usage.isExcluded()) { - final PsiElement element = usage.getElement(); - if (element != null) { - files.add(element.getContainingFile().getVirtualFile()); - } + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final HashSet files = new HashSet(); + final TypeMigrationUsageInfo[] usages = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public TypeMigrationUsageInfo[] compute() { + final Collection children = ((MigrationRootNode)userObject).getChildren(); + for (AbstractTreeNode child : children) { + expandTree((MigrationNode)child); + } + final TypeMigrationUsageInfo[] usages = myLabeler.getMigratedUsages(); + for (TypeMigrationUsageInfo usage : usages) { + if (!usage.isExcluded()) { + final PsiElement element = usage.getElement(); + if (element != null) { + files.add(element.getContainingFile().getVirtualFile()); } } - return usages; } - }); + return usages; + } + }); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (ReadonlyStatusHandler.getInstance(myProject). - ensureFilesWritable(VfsUtilCore.toVirtualFileArray(files)).hasReadonlyFiles()) { - return; - } - new WriteCommandAction(myProject) { - protected void run(@NotNull Result result) throws Throwable { - TypeMigrationProcessor.change(usages, myLabeler, myProject); - } - }.execute(); + ApplicationManager.getApplication().invokeLater(() -> { + if (ReadonlyStatusHandler.getInstance(myProject). + ensureFilesWritable(VfsUtilCore.toVirtualFileArray(files)).hasReadonlyFiles()) { + return; + } + new WriteCommandAction(myProject) { + protected void run(@NotNull Result result) throws Throwable { + TypeMigrationProcessor.change(usages, myLabeler, myProject); } - }, myProject.getDisposed()); - } + }.execute(); + }, myProject.getDisposed()); }, "Type Migration", false, myProject); } } @@ -253,12 +240,10 @@ public class MigrationPanel extends JPanel implements Disposable { rerunButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { UsageViewManager.getInstance(myProject).closeContent(myContent); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final TypeMigrationDialog.MultipleElements dialog = - new TypeMigrationDialog.MultipleElements(myProject, myInitialRoots, myLabeler.getMigrationRootTypeFunction(), myLabeler.getRules()); - dialog.show(); - } + SwingUtilities.invokeLater(() -> { + final TypeMigrationDialog.MultipleElements dialog = + new TypeMigrationDialog.MultipleElements(myProject, myInitialRoots, myLabeler.getMigrationRootTypeFunction(), myLabeler.getRules()); + dialog.show(); }); } }); diff --git a/java/java-impl/src/com/intellij/refactoring/ui/ClassNameReferenceEditor.java b/java/java-impl/src/com/intellij/refactoring/ui/ClassNameReferenceEditor.java index 6622612b47b5..03929a2a6399 100644 --- a/java/java-impl/src/com/intellij/refactoring/ui/ClassNameReferenceEditor.java +++ b/java/java-impl/src/com/intellij/refactoring/ui/ClassNameReferenceEditor.java @@ -46,17 +46,15 @@ public class ClassNameReferenceEditor extends ReferenceEditorWithBrowseButton { public ClassNameReferenceEditor(@NotNull final Project project, @Nullable final PsiClass selectedClass, @Nullable final GlobalSearchScope resolveScope) { - super(null, project, new Function() { - public Document fun(final String s) { - PsiPackage defaultPackage = JavaPsiFacade.getInstance(project).findPackage(""); - final JavaCodeFragment fragment = JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment(s, defaultPackage, true, true); - fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE); - if (resolveScope != null) { - fragment.forceResolveScope(resolveScope); - } - fragment.putUserData(CLASS_NAME_REFERENCE_FRAGMENT, true); - return PsiDocumentManager.getInstance(project).getDocument(fragment); + super(null, project, s -> { + PsiPackage defaultPackage = JavaPsiFacade.getInstance(project).findPackage(""); + final JavaCodeFragment fragment = JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment(s, defaultPackage, true, true); + fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE); + if (resolveScope != null) { + fragment.forceResolveScope(resolveScope); } + fragment.putUserData(CLASS_NAME_REFERENCE_FRAGMENT, true); + return PsiDocumentManager.getInstance(project).getDocument(fragment); }, selectedClass != null ? selectedClass.getQualifiedName() : ""); myProject = project; diff --git a/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java b/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java index f475a46a64ec..a3b73c8c27a1 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java @@ -99,15 +99,13 @@ public class ConflictsUtil { } } if (aClass != null && prototype.hasModifierProperty(PsiModifier.PRIVATE)) { - ClassInheritorsSearch.search(aClass).forEach(new Processor() { - @Override - public boolean process(PsiClass aClass) { - final PsiMethod[] methods = aClass.findMethodsBySignature(prototype, false); - for (PsiMethod method : methods) { - conflicts.putValue(method, "Method " + RefactoringUIUtil.getDescription(method, true) + " will override method of the base class " + RefactoringUIUtil.getDescription(aClass, false)); - } - return true; + ClassInheritorsSearch.search(aClass).forEach(aClass1 -> { + final PsiMethod[] methods = aClass1.findMethodsBySignature(prototype, false); + for (PsiMethod method1 : methods) { + conflicts.putValue(method1, "Method " + RefactoringUIUtil.getDescription(method1, true) + " will override method of the base class " + RefactoringUIUtil.getDescription( + aClass1, false)); } + return true; }); } } diff --git a/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java b/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java index 6fad6197cf5d..eeffefa075f0 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java @@ -283,22 +283,15 @@ public class InlineUtil { public static boolean allUsagesAreTailCalls(final PsiMethod method) { final List nonTailCallUsages = Collections.synchronizedList(new ArrayList()); - boolean result = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ReferencesSearch.search(method).forEach(new Processor() { - @Override - public boolean process(final PsiReference psiReference) { - ProgressManager.checkCanceled(); - if (getTailCallType(psiReference) == TailCallType.None) { - nonTailCallUsages.add(psiReference); - return false; - } - return true; - } - }); - } - }, RefactoringBundle.message("inline.method.checking.tail.calls.progress"), true, method.getProject()); + boolean result = ProgressManager.getInstance().runProcessWithProgressSynchronously( + (Runnable)() -> ReferencesSearch.search(method).forEach(psiReference -> { + ProgressManager.checkCanceled(); + if (getTailCallType(psiReference) == TailCallType.None) { + nonTailCallUsages.add(psiReference); + return false; + } + return true; + }), RefactoringBundle.message("inline.method.checking.tail.calls.progress"), true, method.getProject()); return result && nonTailCallUsages.isEmpty(); } @@ -367,11 +360,8 @@ public class InlineUtil { ref = parent.replace(copy); if (!result.equals(inferenceResult)) { final String inferredTypeText = StringUtil.join(inferenceResult.getTypes(), - new Function() { - @Override - public String fun(PsiType psiType) { - return psiType.getCanonicalText(); - } + psiType -> { + return psiType.getCanonicalText(); }, ", "); final PsiExpressionList argumentList = ((PsiNewExpression)initializer).getArgumentList(); if (argumentList != null) { diff --git a/java/java-impl/src/com/intellij/refactoring/util/LambdaRefactoringUtil.java b/java/java-impl/src/com/intellij/refactoring/util/LambdaRefactoringUtil.java index fe5bd6e1b315..8a208c42023a 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/LambdaRefactoringUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/LambdaRefactoringUtil.java @@ -86,36 +86,33 @@ public class LambdaRefactoringUtil { final Map map = new HashMap(); final UniqueNameGenerator nameGenerator = new UniqueNameGenerator(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(referenceExpression.getProject()); - final String paramsString = StringUtil.join(parameters, new Function() { - @Override - public String fun(PsiParameter parameter) { - final int parameterIndex = parameterList.getParameterIndex(parameter); - String baseName; - if (isReceiver && parameterIndex == 0) { - final SuggestedNameInfo - nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType())); - baseName = nameInfo.names.length > 0 ? nameInfo.names[0] : parameter.getName(); + final String paramsString = StringUtil.join(parameters, parameter -> { + final int parameterIndex = parameterList.getParameterIndex(parameter); + String baseName; + if (isReceiver && parameterIndex == 0) { + final SuggestedNameInfo + nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType())); + baseName = nameInfo.names.length > 0 ? nameInfo.names[0] : parameter.getName(); + } + else { + final String initialName; + if (psiParameters != null) { + final int idx = parameterIndex - (isReceiver ? 1 : 0); + initialName = psiParameters.length > 0 ? psiParameters[idx < psiParameters.length ? idx : psiParameters.length - 1].getName() + : parameter.getName(); } else { - final String initialName; - if (psiParameters != null) { - final int idx = parameterIndex - (isReceiver ? 1 : 0); - initialName = psiParameters.length > 0 ? psiParameters[idx < psiParameters.length ? idx : psiParameters.length - 1].getName() - : parameter.getName(); - } - else { - initialName = parameter.getName(); - } - baseName = codeStyleManager.variableNameToPropertyName(initialName, VariableKind.PARAMETER); + initialName = parameter.getName(); } - - if (baseName != null) { - String parameterName = nameGenerator.generateUniqueName(codeStyleManager.suggestUniqueVariableName(baseName, referenceExpression, true)); - map.put(parameter, parameterName); - return parameterName; - } - return ""; + baseName = codeStyleManager.variableNameToPropertyName(initialName, VariableKind.PARAMETER); } + + if (baseName != null) { + String parameterName = nameGenerator.generateUniqueName(codeStyleManager.suggestUniqueVariableName(baseName, referenceExpression, true)); + map.put(parameter, parameterName); + return parameterName; + } + return ""; }, ", "); buf.append(paramsString); buf.append(") -> "); @@ -186,13 +183,10 @@ public class LambdaRefactoringUtil { LOG.assertTrue(containingClass != null); if (containingClass.hasTypeParameters() && !PsiUtil.isRawSubstitutor(containingClass, substitutor)) { - buf.append("<").append(StringUtil.join(containingClass.getTypeParameters(), new Function() { - @Override - public String fun(PsiTypeParameter parameter) { - final PsiType psiType = substitutor.substitute(parameter); - LOG.assertTrue(psiType != null); - return psiType.getCanonicalText(); - } + buf.append("<").append(StringUtil.join(containingClass.getTypeParameters(), parameter -> { + final PsiType psiType = substitutor.substitute(parameter); + LOG.assertTrue(psiType != null); + return psiType.getCanonicalText(); }, ", ")).append(">"); } } diff --git a/java/java-impl/src/com/intellij/refactoring/util/RefactoringHierarchyUtil.java b/java/java-impl/src/com/intellij/refactoring/util/RefactoringHierarchyUtil.java index 37fcc30d4471..769fd171995b 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/RefactoringHierarchyUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/RefactoringHierarchyUtil.java @@ -129,17 +129,15 @@ public class RefactoringHierarchyUtil { if (sortAlphabetically) { Collections.sort( - basesList, new Comparator() { - public int compare(PsiClass c1, PsiClass c2) { - final String fqn1 = c1.getQualifiedName(); - final String fqn2 = c2.getQualifiedName(); - if (fqn1 != null && fqn2 != null) return fqn1.compareTo(fqn2); - if (fqn1 == null && fqn2 == null) { - return Comparing.compare(c1.getName(), c2.getName()); - } - return fqn1 == null ? 1 : -1; - } + basesList, (c1, c2) -> { + final String fqn1 = c1.getQualifiedName(); + final String fqn2 = c2.getQualifiedName(); + if (fqn1 != null && fqn2 != null) return fqn1.compareTo(fqn2); + if (fqn1 == null && fqn2 == null) { + return Comparing.compare(c1.getName(), c2.getName()); } + return fqn1 == null ? 1 : -1; + } ); } diff --git a/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java b/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java index 447d1adee883..da8758a07c76 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java @@ -1321,11 +1321,7 @@ public class RefactoringUtil { PsiTypeParameter[] typeParameters = used.toArray(new PsiTypeParameter[used.size()]); - Arrays.sort(typeParameters, new Comparator() { - public int compare(final PsiTypeParameter tp1, final PsiTypeParameter tp2) { - return tp1.getTextRange().getStartOffset() - tp2.getTextRange().getStartOffset(); - } - }); + Arrays.sort(typeParameters, (tp1, tp2) -> tp1.getTextRange().getStartOffset() - tp2.getTextRange().getStartOffset()); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(elements[0].getProject()).getElementFactory(); try { diff --git a/java/java-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesImpl.java b/java/java-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesImpl.java index 54658db14ed1..ea6c5401639a 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesImpl.java @@ -178,12 +178,10 @@ public class DuplicatesImpl { } } if (anyCollapsed) { - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - public void run() { - for (final FoldRegion foldRegion : foldRegions) { - if (!foldRegion.isExpanded()) { - foldRegion.setExpanded(true); - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + for (final FoldRegion foldRegion : foldRegions) { + if (!foldRegion.isExpanded()) { + foldRegion.setExpanded(true); } } }); diff --git a/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java b/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java index 88c54b97c43e..09ed96caa0c6 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java @@ -151,10 +151,8 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler, Contex }); if (module != null) { final HashSet dependencies = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - ModuleUtilCore.collectModulesDependsOn(module, dependencies); - } + ApplicationManager.getApplication().runReadAction(() -> { + ModuleUtilCore.collectModulesDependsOn(module, dependencies); }); memberWithModulesMap.put(member, dependencies); } @@ -204,13 +202,10 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler, Contex }); if (duplicates.isEmpty()) { if (!silent) { - final Runnable nothingFoundRunnable = new Runnable() { - @Override - public void run() { - final String message = RefactoringBundle.message("idea.has.not.found.any.code.that.can.be.replaced.with.method.call", - ApplicationNamesInfo.getInstance().getProductName()); - Messages.showInfoMessage(project, message, REFACTORING_NAME); - } + final Runnable nothingFoundRunnable = () -> { + final String message = RefactoringBundle.message("idea.has.not.found.any.code.that.can.be.replaced.with.method.call", + ApplicationNamesInfo.getInstance().getProductName()); + Messages.showInfoMessage(project, message, REFACTORING_NAME); }; if (ApplicationManager.getApplication().isUnitTestMode()) { nothingFoundRunnable.run(); @@ -227,38 +222,28 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler, Contex final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (progressIndicator != null && progressIndicator.isCanceled()) return; - final Runnable replaceRunnable = new Runnable() { - @Override - public void run() { - LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME); - try { - for (final PsiMember member : methods) { - final List matches = duplicates.get(member); - if (matches == null) continue; - final int duplicatesNo = matches.size(); - WindowManager.getInstance().getStatusBar(project).setInfo(getStatusMessage(duplicatesNo)); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() { - @Override - public void run() { - final MatchProvider matchProvider = - member instanceof PsiMethod ? new MethodDuplicatesMatchProvider((PsiMethod)member, matches) - : new ConstantMatchProvider(member, project, matches); - DuplicatesImpl.invoke(project, matchProvider); - } - }); - } - }, REFACTORING_NAME, REFACTORING_NAME); - - WindowManager.getInstance().getStatusBar(project).setInfo(""); - } - } - finally { - a.finish(); + final Runnable replaceRunnable = () -> { + LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME); + try { + for (final PsiMember member : methods) { + final List matches = duplicates.get(member); + if (matches == null) continue; + final int duplicatesNo = matches.size(); + WindowManager.getInstance().getStatusBar(project).setInfo(getStatusMessage(duplicatesNo)); + CommandProcessor.getInstance().executeCommand(project, + () -> PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(() -> { + final MatchProvider matchProvider = + member instanceof PsiMethod ? new MethodDuplicatesMatchProvider((PsiMethod)member, matches) + : new ConstantMatchProvider(member, project, matches); + DuplicatesImpl.invoke(project, matchProvider); + }), REFACTORING_NAME, REFACTORING_NAME); + + WindowManager.getInstance().getStatusBar(project).setInfo(""); } } + finally { + a.finish(); + } }; ApplicationManager.getApplication().invokeLater(replaceRunnable, ModalityState.NON_MODAL); } diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java index 5e22926bae2c..f56cf80b6690 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueProcessor.java @@ -148,13 +148,10 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor final StringBuilder returnTypeBuffer = new StringBuilder(qualifiedName); if (!myTypeParameters.isEmpty()) { returnTypeBuffer.append('<'); - returnTypeBuffer.append(StringUtil.join(myTypeParameters, new Function() { - @Override - public String fun(final PsiTypeParameter typeParameter) { - final String paramName = typeParameter.getName(); - LOG.assertTrue(paramName != null); - return paramName; - } + returnTypeBuffer.append(StringUtil.join(myTypeParameters, typeParameter -> { + final String paramName = typeParameter.getName(); + LOG.assertTrue(paramName != null); + return paramName; }, ",")); returnTypeBuffer.append('>'); } diff --git a/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java b/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java index a4b8f3a8d250..03b646b628bc 100644 --- a/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java +++ b/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java @@ -48,17 +48,14 @@ public class SPIClassProviderReferenceElement extends SPIPackageOrClassReference final PsiClass superProvider = JavaPsiFacade.getInstance(getProject()).findClass(name, getResolveScope()); if (superProvider != null) { final List result = new ArrayList(); - ClassInheritorsSearch.search(superProvider).forEach(new Processor() { - @Override - public boolean process(PsiClass psiClass) { - if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) { - final String jvmClassName = ClassUtil.getJVMClassName(psiClass); - if (jvmClassName != null) { - result.add(LookupElementBuilder.create(psiClass, jvmClassName)); - } + ClassInheritorsSearch.search(superProvider).forEach(psiClass -> { + if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + final String jvmClassName = ClassUtil.getJVMClassName(psiClass); + if (jvmClassName != null) { + result.add(LookupElementBuilder.create(psiClass, jvmClassName)); } - return true; } + return true; }); return ArrayUtil.toObjectArray(result); } diff --git a/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java b/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java index 7e05c9691843..78e14aca38b3 100644 --- a/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java +++ b/java/java-impl/src/com/intellij/testIntegration/BaseGenerateTestSupportMethodAction.java @@ -72,16 +72,13 @@ public class BaseGenerateTestSupportMethodAction extends BaseGenerateAction { return new AnAction("Edit Template") { @Override public void actionPerformed(AnActionEvent e) { - chooseAndPerform(editor, frameworks, new Consumer() { - @Override - public void consume(TestFramework framework) { - final FileTemplateDescriptor descriptor = methodKind.getFileTemplateDescriptor(framework); - if (descriptor != null) { - final String fileName = descriptor.getFileName(); - AllFileTemplatesConfigurable.editCodeTemplate(FileUtil.getNameWithoutExtension(fileName), project); - } else { - HintManager.getInstance().showErrorHint(editor, "No template found for " + framework.getName() + ":" + BaseGenerateTestSupportMethodAction.this.getTemplatePresentation().getText()); - } + chooseAndPerform(editor, frameworks, framework -> { + final FileTemplateDescriptor descriptor = methodKind.getFileTemplateDescriptor(framework); + if (descriptor != null) { + final String fileName = descriptor.getFileName(); + AllFileTemplatesConfigurable.editCodeTemplate(FileUtil.getNameWithoutExtension(fileName), project); + } else { + HintManager.getInstance().showErrorHint(editor, "No template found for " + framework.getName() + ":" + BaseGenerateTestSupportMethodAction.this.getTemplatePresentation().getText()); } }); } @@ -152,21 +149,11 @@ public class BaseGenerateTestSupportMethodAction extends BaseGenerateAction { PopupChooserBuilder builder = new PopupChooserBuilder(list); - builder.setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return ((TestFramework)o).getName(); - } - }); + builder.setFilteringEnabled(o -> ((TestFramework)o).getName()); builder .setTitle("Choose Framework") - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - consumer.consume((TestFramework)list.getSelectedValue()); - } - }) + .setItemChoosenCallback(() -> consumer.consume((TestFramework)list.getSelectedValue())) .setMovable(true) .createPopup().showInBestPositionFor(editor); } @@ -187,12 +174,9 @@ public class BaseGenerateTestSupportMethodAction extends BaseGenerateAction { } } if (frameworks.isEmpty()) return; - final Consumer consumer = new Consumer() { - @Override - public void consume(TestFramework framework) { - if (framework == null) return; - doGenerate(editor, file, targetClass, framework); - } + final Consumer consumer = framework -> { + if (framework == null) return; + doGenerate(editor, file, targetClass, framework); }; chooseAndPerform(editor, frameworks, consumer); @@ -222,20 +206,17 @@ public class BaseGenerateTestSupportMethodAction extends BaseGenerateAction { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; - WriteCommandAction.runWriteCommandAction(file.getProject(), new Runnable() { - @Override - public void run() { - try { - PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); - PsiMethod method = generateDummyMethod(editor, file); - if (method == null) return; + WriteCommandAction.runWriteCommandAction(file.getProject(), () -> { + try { + PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); + PsiMethod method = generateDummyMethod(editor, file); + if (method == null) return; - TestIntegrationUtils.runTestMethodTemplate(myMethodKind, framework, editor, targetClass, method, "name", false, null); - } - catch (IncorrectOperationException e) { - HintManager.getInstance().showErrorHint(editor, "Cannot generate method: " + e.getMessage()); - LOG.warn(e); - } + TestIntegrationUtils.runTestMethodTemplate(myMethodKind, framework, editor, targetClass, method, "name", false, null); + } + catch (IncorrectOperationException e) { + HintManager.getInstance().showErrorHint(editor, "Cannot generate method: " + e.getMessage()); + LOG.warn(e); } }); } diff --git a/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java b/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java index 20ad32e3e368..33c39c23c83c 100644 --- a/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java +++ b/java/java-impl/src/com/intellij/testIntegration/TestIntegrationUtils.java @@ -180,20 +180,18 @@ public class TestIntegrationUtils { adapter = new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); - PsiFile psi = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); - PsiElement el = PsiTreeUtil.findElementOfClassAtOffset(psi, editor.getCaretModel().getOffset() - 1, PsiMethod.class, false); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + PsiFile psi = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); + PsiElement el = PsiTreeUtil.findElementOfClassAtOffset(psi, editor.getCaretModel().getOffset() - 1, PsiMethod.class, false); - if (el != null) { - PsiMethod method = PsiTreeUtil.getParentOfType(el, PsiMethod.class, false); - if (method != null) { - if (method.findDeepestSuperMethods().length > 0) { - GenerateMembersUtil.setupGeneratedMethod(method); - } - CreateFromUsageUtils.setupEditor(method, editor); + if (el != null) { + PsiMethod method1 = PsiTreeUtil.getParentOfType(el, PsiMethod.class, false); + if (method1 != null) { + if (method1.findDeepestSuperMethods().length > 0) { + GenerateMembersUtil.setupGeneratedMethod(method1); } + CreateFromUsageUtils.setupEditor(method1, editor); } } }); diff --git a/java/java-impl/src/com/intellij/testIntegration/TestRunLineMarkerProvider.java b/java/java-impl/src/com/intellij/testIntegration/TestRunLineMarkerProvider.java index 17e3feac0730..8c716edd3aaf 100644 --- a/java/java-impl/src/com/intellij/testIntegration/TestRunLineMarkerProvider.java +++ b/java/java-impl/src/com/intellij/testIntegration/TestRunLineMarkerProvider.java @@ -39,12 +39,7 @@ import javax.swing.*; */ public class TestRunLineMarkerProvider extends RunLineMarkerContributor { - private static final Function TOOLTIP_PROVIDER = new Function() { - @Override - public String fun(PsiElement element) { - return "Run Test"; - } - }; + private static final Function TOOLTIP_PROVIDER = element -> "Run Test"; @Nullable @Override diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestAction.java b/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestAction.java index 9bea740c758c..0ba44282e873 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestAction.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestAction.java @@ -128,18 +128,10 @@ public class CreateTestAction extends PsiElementBaseIntentionAction { return; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - TestFramework framework = d.getSelectedTestFrameworkDescriptor(); - final TestGenerator generator = TestGenerators.INSTANCE.forLanguage(framework.getLanguage()); - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - generator.generateTest(project, d); - } - }); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + TestFramework framework = d.getSelectedTestFrameworkDescriptor(); + final TestGenerator generator = TestGenerators.INSTANCE.forLanguage(framework.getLanguage()); + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> generator.generateTest(project, d)); }, CodeInsightBundle.message("intention.create.test"), this); } diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java b/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java index 5fc4acf1f7bd..deb5ac369e7a 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java @@ -393,20 +393,14 @@ public class CreateTestDialog extends DialogWrapper { myFixLibraryButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - if (mySelectedFramework instanceof JavaTestFramework) { - ((JavaTestFramework)mySelectedFramework).setupLibrary(myTargetModule); - } else { - OrderEntryFix.addJarToRoots(mySelectedFramework.getLibraryPath(), myTargetModule, null); - } - } - }); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + if (mySelectedFramework instanceof JavaTestFramework) { + ((JavaTestFramework)mySelectedFramework).setupLibrary(myTargetModule); + } else { + OrderEntryFix.addJarToRoots(mySelectedFramework.getLibraryPath(), myTargetModule, null); + } + })); myFixLibraryPanel.setVisible(false); } }); diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java b/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java index 1125b6a033f4..d64b6ec8c3a8 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/GenerateMissedTestsAction.java @@ -87,12 +87,7 @@ public class GenerateMissedTestsAction extends PsiElementBaseIntentionAction { final JBList list = new JBList(testClasses); list.setCellRenderer(new PsiClassListCellRenderer()); JBPopupFactory.getInstance().createListPopupBuilder(list) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - generateMissedTests((PsiClass)list.getSelectedValue(), srcClass, editor); - } - }) + .setItemChoosenCallback(() -> generateMissedTests((PsiClass)list.getSelectedValue(), srcClass, editor)) .setTitle("Choose Test") .createPopup().showInBestPositionFor(editor); } @@ -106,11 +101,8 @@ public class GenerateMissedTestsAction extends PsiElementBaseIntentionAction { if (!FileModificationService.getInstance().preparePsiElementsForWrite(testClass)) return; final MissedTestsDialog dialog = new MissedTestsDialog(project, srcClass, testClass, framework); if (dialog.showAndGet()) { - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - JavaTestGenerator.addTestMethods(editor, testClass, srcClass, framework, dialog.getSelectedMethods(), false, false); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + JavaTestGenerator.addTestMethods(editor, testClass, srcClass, framework, dialog.getSelectedMethods(), false, false); }); } } diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java b/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java index 6603e9b542a6..48fe391076a3 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java @@ -202,11 +202,8 @@ public class JavaTestGenerator implements TestGenerator { final Template template = TestIntegrationUtils.createTestMethodTemplate(TestIntegrationUtils.MethodKind.TEST, descriptor, targetClass, sourceClass, null, true, existingNames); final String prefix = JavaPsiFacade.getElementFactory(targetClass.getProject()).createMethodFromText(template.getTemplateText(), targetClass).getName(); - existingNames.addAll(ContainerUtil.map(targetClass.getMethods(), new Function() { - @Override - public String fun(PsiMethod method) { - return StringUtil.decapitalize(StringUtil.trimStart(method.getName(), prefix)); - } + existingNames.addAll(ContainerUtil.map(targetClass.getMethods(), method -> { + return StringUtil.decapitalize(StringUtil.trimStart(method.getName(), prefix)); })); for (MemberInfo m : methods) { @@ -215,13 +212,9 @@ public class JavaTestGenerator implements TestGenerator { } private static void showErrorLater(final Project project, final String targetClassName) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Messages.showErrorDialog(project, - CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName), - CodeInsightBundle.message("intention.error.cannot.create.class.title")); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project, + CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName), + CodeInsightBundle.message("intention.error.cannot.create.class.title"))); } private static PsiMethod generateMethod(@NotNull TestIntegrationUtils.MethodKind methodKind, diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java b/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java index 69023c7a98ce..3a70675195db 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/MissedTestsDialog.java @@ -88,11 +88,8 @@ public class MissedTestsDialog extends DialogWrapper { final Set existingNames = new HashSet(); final String prefix = getTestPrefix(existingNames); - existingNames.addAll(ContainerUtil.map(myTestClass.getMethods(), new Function() { - @Override - public String fun(PsiMethod method) { - return StringUtil.decapitalize(StringUtil.trimStart(method.getName(), prefix)); - } + existingNames.addAll(ContainerUtil.map(myTestClass.getMethods(), method -> { + return StringUtil.decapitalize(StringUtil.trimStart(method.getName(), prefix)); })); diff --git a/java/java-impl/src/com/intellij/ui/JavaReferenceEditorUtil.java b/java/java-impl/src/com/intellij/ui/JavaReferenceEditorUtil.java index b5323adc4199..e4e298bf8d2a 100644 --- a/java/java-impl/src/com/intellij/ui/JavaReferenceEditorUtil.java +++ b/java/java-impl/src/com/intellij/ui/JavaReferenceEditorUtil.java @@ -35,11 +35,7 @@ public class JavaReferenceEditorUtil { final Project project, final boolean toAcceptClasses) { return new ReferenceEditorWithBrowseButton(browseActionListener, project, - new NullableFunction() { - public Document fun(final String s) { - return createDocument(s, project, toAcceptClasses); - } - }, text); + (NullableFunction)s -> createDocument(s, project, toAcceptClasses), text); } @Nullable diff --git a/java/java-impl/src/com/intellij/unscramble/ThreadDumpPanel.java b/java/java-impl/src/com/intellij/unscramble/ThreadDumpPanel.java index 73183568b0b2..a49c40061548 100644 --- a/java/java-impl/src/com/intellij/unscramble/ThreadDumpPanel.java +++ b/java/java-impl/src/com/intellij/unscramble/ThreadDumpPanel.java @@ -303,25 +303,17 @@ public class ThreadDumpPanel extends JPanel implements DataProvider { } private class SortThreadsAction extends DumbAwareAction { - private final Comparator BY_TYPE = new Comparator() { - @Override - public int compare(ThreadState o1, ThreadState o2) { - final int s1 = getThreadStateCode(o1).ordinal(); - final int s2 = getThreadStateCode(o2).ordinal(); - if (s1 == s2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } else { - return s1 < s2 ? - 1 : 1; - } + private final Comparator BY_TYPE = (o1, o2) -> { + final int s1 = getThreadStateCode(o1).ordinal(); + final int s2 = getThreadStateCode(o2).ordinal(); + if (s1 == s2) { + return o1.getName().compareToIgnoreCase(o2.getName()); + } else { + return s1 < s2 ? - 1 : 1; } }; - private final Comparator BY_NAME = new Comparator() { - @Override - public int compare(ThreadState o1, ThreadState o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }; + private final Comparator BY_NAME = (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()); private Comparator COMPARATOR = BY_TYPE; private static final String TYPE_LABEL = "Sort threads by type"; private static final String NAME_LABEL = "Sort threads by name"; diff --git a/java/java-impl/src/com/intellij/unscramble/ThreadDumpParser.java b/java/java-impl/src/com/intellij/unscramble/ThreadDumpParser.java index b0bd10dc16ec..a46999ac73de 100644 --- a/java/java-impl/src/com/intellij/unscramble/ThreadDumpParser.java +++ b/java/java-impl/src/com/intellij/unscramble/ThreadDumpParser.java @@ -115,11 +115,7 @@ public class ThreadDumpParser { } public static void sortThreads(List result) { - Collections.sort(result, new Comparator() { - public int compare(final ThreadState o1, final ThreadState o2) { - return getInterestLevel(o2) - getInterestLevel(o1); - } - }); + Collections.sort(result, (o1, o2) -> getInterestLevel(o2) - getInterestLevel(o1)); } @Nullable diff --git a/java/java-impl/src/com/intellij/unscramble/UnscrambleDialog.java b/java/java-impl/src/com/intellij/unscramble/UnscrambleDialog.java index eea196d623fe..fa37621a256c 100644 --- a/java/java-impl/src/com/intellij/unscramble/UnscrambleDialog.java +++ b/java/java-impl/src/com/intellij/unscramble/UnscrambleDialog.java @@ -225,11 +225,8 @@ public class UnscrambleDialog extends DialogWrapper { @Override public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); - FileChooser.chooseFiles(descriptor, myProject, null, new Consumer>() { - @Override - public void consume(List files) { - myLogFile.setText(FileUtil.toSystemDependentName(files.get(files.size() - 1).getPath())); - } + FileChooser.chooseFiles(descriptor, myProject, null, files -> { + myLogFile.setText(FileUtil.toSystemDependentName(files.get(files.size() - 1).getPath())); }); } }); @@ -386,13 +383,10 @@ public class UnscrambleDialog extends DialogWrapper { return; } } - DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - if (performUnscramble()) { - myLogFile.addCurrentTextToHistory(); - close(OK_EXIT_CODE); - } + DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> { + if (performUnscramble()) { + myLogFile.addCurrentTextToHistory(); + close(OK_EXIT_CODE); } }); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java b/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java index c4b4d194b3bf..67332b1841d6 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java @@ -121,12 +121,9 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { if ((me1 = supers1Q.poll()) != null) { if (supers2.contains(me1)) return true; supers1.add(me1); - PsiSuperMethodImplUtil.processDirectSuperMethodsSmart(me1, new Processor() { - @Override - public boolean process(PsiMethod psiMethod) { - supers1Q.add(psiMethod); - return true; - } + PsiSuperMethodImplUtil.processDirectSuperMethodsSmart(me1, psiMethod -> { + supers1Q.add(psiMethod); + return true; }); } @@ -134,12 +131,9 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { if ((me2 = supers2Q.poll()) != null) { if (supers1.contains(me2)) return true; supers2.add(me2); - PsiSuperMethodImplUtil.processDirectSuperMethodsSmart(me2, new Processor() { - @Override - public boolean process(PsiMethod psiMethod) { - supers2Q.add(psiMethod); - return true; - } + PsiSuperMethodImplUtil.processDirectSuperMethodsSmart(me2, psiMethod -> { + supers2Q.add(psiMethod); + return true; }); } if (me1 == null && me2 == null) break; diff --git a/java/java-impl/src/com/intellij/util/xml/impl/JavaDomApplicationComponent.java b/java/java-impl/src/com/intellij/util/xml/impl/JavaDomApplicationComponent.java index 107095c4146d..5fbab905e29b 100644 --- a/java/java-impl/src/com/intellij/util/xml/impl/JavaDomApplicationComponent.java +++ b/java/java-impl/src/com/intellij/util/xml/impl/JavaDomApplicationComponent.java @@ -45,21 +45,10 @@ public class JavaDomApplicationComponent implements Consumer { @Override public void consume(DomUIFactory factory) { - factory.registerCustomControl(PsiClass.class, new Function, BaseControl>() { - public BaseControl fun(final DomWrapper wrapper) { - return new PsiClassControl(wrapper, false); - } - }); - factory.registerCustomControl(PsiType.class, new Function, BaseControl>() { - public BaseControl fun(final DomWrapper wrapper) { - return new PsiTypeControl(wrapper, false); - } - }); + factory.registerCustomControl(PsiClass.class, wrapper -> new PsiClassControl(wrapper, false)); + factory.registerCustomControl(PsiType.class, wrapper -> new PsiTypeControl(wrapper, false)); - factory.registerCustomCellEditor(PsiClass.class, new Function() { - public TableCellEditor fun(final DomElement element) { - return new PsiClassTableCellEditor(element.getManager().getProject(), element.getResolveScope()); - } - }); + factory.registerCustomCellEditor(PsiClass.class, + element -> new PsiClassTableCellEditor(element.getManager().getProject(), element.getResolveScope())); } } \ No newline at end of file diff --git a/java/java-impl/src/com/intellij/util/xml/ui/PsiTypeControl.java b/java/java-impl/src/com/intellij/util/xml/ui/PsiTypeControl.java index aac163f74d36..c4837892573d 100644 --- a/java/java-impl/src/com/intellij/util/xml/ui/PsiTypeControl.java +++ b/java/java-impl/src/com/intellij/util/xml/ui/PsiTypeControl.java @@ -75,11 +75,8 @@ public class PsiTypeControl extends EditorTextFieldControl { boundedComponent = new PsiTypePanel(); } return PsiClassControl.initReferenceEditorWithBrowseButton(boundedComponent, - new ReferenceEditorWithBrowseButton(null, project, new Function() { - public Document fun(final String s) { - return JavaReferenceEditorUtil.createTypeDocument(s, project); - } - }, ""), this); + new ReferenceEditorWithBrowseButton(null, project, + s -> JavaReferenceEditorUtil.createTypeDocument(s, project), ""), this); } diff --git a/java/java-indexing-api/src/com/intellij/psi/search/PsiShortNamesCache.java b/java/java-indexing-api/src/com/intellij/psi/search/PsiShortNamesCache.java index ad97f51f28ea..433e01b822ec 100644 --- a/java/java-indexing-api/src/com/intellij/psi/search/PsiShortNamesCache.java +++ b/java/java-indexing-api/src/com/intellij/psi/search/PsiShortNamesCache.java @@ -122,12 +122,7 @@ public abstract class PsiShortNamesCache { public boolean processMethodsWithName(@NonNls @NotNull String name, @NotNull final Processor processor, @NotNull GlobalSearchScope scope, @Nullable IdFilter filter) { - return processMethodsWithName(name, scope, new Processor() { - @Override - public boolean process(PsiMethod method) { - return processor.process(method); - } - }); + return processMethodsWithName(name, scope, method -> processor.process(method)); } public boolean processAllMethodNames(Processor processor, GlobalSearchScope scope, IdFilter filter) { diff --git a/java/java-indexing-api/src/com/intellij/psi/search/searches/MethodReferencesSearch.java b/java/java-indexing-api/src/com/intellij/psi/search/searches/MethodReferencesSearch.java index a6f8bb0c8d27..5f0186718e47 100644 --- a/java/java-indexing-api/src/com/intellij/psi/search/searches/MethodReferencesSearch.java +++ b/java/java-indexing-api/src/com/intellij/psi/search/searches/MethodReferencesSearch.java @@ -106,12 +106,7 @@ public class MethodReferencesSearch extends ExtensibleQueryFactory processor) { - searchOptimized(method, scope, strictSignatureSearch, collector, false, new PairProcessor() { - @Override - public boolean process(PsiReference psiReference, SearchRequestCollector collector) { - return processor.process(psiReference); - } - }); + searchOptimized(method, scope, strictSignatureSearch, collector, false, (psiReference, collector1) -> processor.process(psiReference)); } public static void searchOptimized(final PsiMethod method, SearchScope scope, final boolean strictSignatureSearch, diff --git a/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/ClassImplementationsSearch.java b/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/ClassImplementationsSearch.java index 98186495b4e0..4693b7f59fd0 100644 --- a/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/ClassImplementationsSearch.java +++ b/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/ClassImplementationsSearch.java @@ -37,11 +37,8 @@ public class ClassImplementationsSearch implements QueryExecutor processor, SearchScope scope) { - if (!FunctionalExpressionSearch.search(psiClass, scope).forEach(new Processor() { - @Override - public boolean process(PsiFunctionalExpression expression) { - return processor.process(expression); - } + if (!FunctionalExpressionSearch.search(psiClass, scope).forEach(expression -> { + return processor.process(expression); })) { return false; } diff --git a/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/MethodImplementationsSearch.java b/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/MethodImplementationsSearch.java index 9a5f5ac4ddc1..fd7c95baa038 100644 --- a/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/MethodImplementationsSearch.java +++ b/java/java-indexing-impl/src/com/intellij/codeInsight/navigation/MethodImplementationsSearch.java @@ -42,11 +42,8 @@ public class MethodImplementationsSearch implements QueryExecutor consumer, final SearchScope searchScope) { - if (!FunctionalExpressionSearch.search(psiMethod, searchScope).forEach(new Processor() { - @Override - public boolean process(PsiFunctionalExpression expression) { - return consumer.process(expression); - } + if (!FunctionalExpressionSearch.search(psiMethod, searchScope).forEach(expression -> { + return consumer.process(expression); })) { return false; } diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java index d90a814afe57..502637c81631 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java @@ -59,12 +59,9 @@ public class AllClassesSearchExecutor implements QueryExecutor processor) { final Set names = new THashSet(10000); - processClassNames(parameters.getProject(), scope, new Consumer() { - @Override - public void consume(String s) { - if (parameters.nameMatches(s)) { - names.add(s); - } + processClassNames(parameters.getProject(), scope, s -> { + if (parameters.nameMatches(s)) { + names.add(s); } }); @@ -155,11 +152,8 @@ public class AllClassesSearchExecutor implements QueryExecutor { + scopeRoot.accept(visitor); }); return !stopped[0]; diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java index 51565a81e5f4..d5d97b9ede83 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java @@ -105,25 +105,22 @@ public class AnnotatedPackagesSearcher implements QueryExecutor() { - @Override - public boolean process(final PsiFile psiFile) { - PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(psiFile, PsiPackageStatement.class); - if (stmt == null) return true; + helper.processAllFilesWithWord(annotationShortName, infoFiles, psiFile -> { + PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(psiFile, PsiPackageStatement.class); + if (stmt == null) return true; - final PsiModifierList annotations = stmt.getAnnotationList(); - if (annotations == null) return true; - final PsiAnnotation ann = annotations.findAnnotation(annotationFQN); - if (ann == null) return true; + final PsiModifierList annotations1 = stmt.getAnnotationList(); + if (annotations1 == null) return true; + final PsiAnnotation ann = annotations1.findAnnotation(annotationFQN); + if (ann == null) return true; - final PsiJavaCodeReferenceElement ref = ann.getNameReferenceElement(); - if (ref == null) return true; + final PsiJavaCodeReferenceElement ref = ann.getNameReferenceElement(); + if (ref == null) return true; - if (!psiManager.areElementsEquivalent(ref.resolve(), annClass)) return true; + if (!psiManager.areElementsEquivalent(ref.resolve(), annClass)) return true; - wantMore[0] = consumer.process(JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(stmt.getPackageName())); - return wantMore[0]; - } + wantMore[0] = consumer.process(JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(stmt.getPackageName())); + return wantMore[0]; }, true); return wantMore[0]; diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/ClassesWithAnnotatedMembersSearcher.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/ClassesWithAnnotatedMembersSearcher.java index 2ca209dc043f..9d12558adf00 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/ClassesWithAnnotatedMembersSearcher.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/ClassesWithAnnotatedMembersSearcher.java @@ -46,24 +46,21 @@ public class ClassesWithAnnotatedMembersSearcher extends QueryExecutorBase processed = new HashSet(); - AnnotatedElementsSearch.searchPsiMembers(queryParameters.getAnnotationClass(), scope).forEach(new Processor() { - @Override - public boolean process(PsiMember member) { - PsiClass psiClass; - AccessToken token = ReadAction.start(); - try { - psiClass = member instanceof PsiClass ? (PsiClass)member : member.getContainingClass(); - } - finally { - token.finish(); - } - - if (psiClass != null && processed.add(psiClass)) { - consumer.process(psiClass); - } - - return true; + AnnotatedElementsSearch.searchPsiMembers(queryParameters.getAnnotationClass(), scope).forEach(member -> { + PsiClass psiClass; + AccessToken token = ReadAction.start(); + try { + psiClass = member instanceof PsiClass ? (PsiClass)member : member.getContainingClass(); } + finally { + token.finish(); + } + + if (psiClass != null && processed.add(psiClass)) { + consumer.process(psiClass); + } + + return true; }); } } diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/ConstructorReferencesSearchHelper.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/ConstructorReferencesSearchHelper.java index 199412e99615..908e3de08354 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/ConstructorReferencesSearchHelper.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/ConstructorReferencesSearchHelper.java @@ -74,30 +74,27 @@ public class ConstructorReferencesSearchHelper { } // search usages like "new XXX(..)" - PairProcessor processor1 = new PairProcessor() { - @Override - public boolean process(PsiReference reference, SearchRequestCollector collector) { - PsiElement parent = reference.getElement().getParent(); - if (parent instanceof PsiAnonymousClass) { - parent = parent.getParent(); - } - if (parent instanceof PsiNewExpression) { - PsiMethod constructor1 = ((PsiNewExpression)parent).resolveConstructor(); - if (constructor1 != null) { - if (isStrictSignatureSearch) { - if (myManager.areElementsEquivalent(constructor, constructor1)) { - return processor.process(reference); - } + PairProcessor processor1 = (reference, collector1) -> { + PsiElement parent = reference.getElement().getParent(); + if (parent instanceof PsiAnonymousClass) { + parent = parent.getParent(); + } + if (parent instanceof PsiNewExpression) { + PsiMethod constructor1 = ((PsiNewExpression)parent).resolveConstructor(); + if (constructor1 != null) { + if (isStrictSignatureSearch) { + if (myManager.areElementsEquivalent(constructor, constructor1)) { + return processor.process(reference); } - else { - if (myManager.areElementsEquivalent(containingClass, constructor1.getContainingClass())) { - return processor.process(reference); - } + } + else { + if (myManager.areElementsEquivalent(containingClass, constructor1.getContainingClass())) { + return processor.process(reference); } } } - return true; } + return true; }; ReferencesSearch.searchOptimized(containingClass, searchScope, ignoreAccessScope, collector, true, processor1); @@ -118,16 +115,13 @@ public class ConstructorReferencesSearchHelper { } // search usages like "super(..)" - Processor processor2 = new Processor() { - @Override - public boolean process(PsiClass inheritor) { - final PsiElement navigationElement = inheritor.getNavigationElement(); - if (navigationElement instanceof PsiClass) { - return processSuperOrThis((PsiClass)navigationElement, constructor, constructorCanBeCalledImplicitly[0], searchScope, project, - isStrictSignatureSearch, PsiKeyword.SUPER, processor); - } - return true; + Processor processor2 = inheritor -> { + final PsiElement navigationElement = inheritor.getNavigationElement(); + if (navigationElement instanceof PsiClass) { + return processSuperOrThis((PsiClass)navigationElement, constructor, constructorCanBeCalledImplicitly[0], searchScope, project, + isStrictSignatureSearch, PsiKeyword.SUPER, processor); } + return true; }; return ClassInheritorsSearch.search(containingClass, searchScope, false).forEach(processor2); @@ -159,27 +153,24 @@ public class ConstructorReferencesSearchHelper { @NotNull final PsiMethod constructor, @NotNull final Project project, @NotNull PsiClass aClass, SearchScope searchScope) { - return ReferencesSearch.search(aClass, searchScope).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element != null) { - return MethodUsagesSearcher.resolveInReadAction(project, new Computable() { - @Override - public Boolean compute() { - final PsiElement parent = element.getParent(); - if (parent instanceof PsiMethodReferenceExpression && - ((PsiMethodReferenceExpression)parent).getReferenceNameElement() instanceof PsiKeyword) { - if (((PsiMethodReferenceExpression)parent).isReferenceTo(constructor)) { - if (!processor.process((PsiReference)parent)) return false; - } + return ReferencesSearch.search(aClass, searchScope).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element != null) { + return MethodUsagesSearcher.resolveInReadAction(project, new Computable() { + @Override + public Boolean compute() { + final PsiElement parent = element.getParent(); + if (parent instanceof PsiMethodReferenceExpression && + ((PsiMethodReferenceExpression)parent).getReferenceNameElement() instanceof PsiKeyword) { + if (((PsiMethodReferenceExpression)parent).isReferenceTo(constructor)) { + if (!processor.process((PsiReference)parent)) return false; } - return true; } - }); - } - return true; + return true; + } + }); } + return true; }); } diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaFunctionalExpressionSearcher.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaFunctionalExpressionSearcher.java index ea0afc079863..7021ca3830ab 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaFunctionalExpressionSearcher.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaFunctionalExpressionSearcher.java @@ -101,23 +101,21 @@ public class JavaFunctionalExpressionSearcher extends QueryExecutorBase> holders = new LinkedHashMap>(); - //functional expressions checker: number and type of parameters at call site should correspond to candidate method currently check - final SuitableFilesProcessor processor = new SuitableFilesProcessor(holders, expectedFunExprParamsCount, parametersCount, varArgs, parameters); - fileBasedIndex.processValues(JavaFunctionalExpressionIndex.JAVA_FUNCTIONAL_EXPRESSION_INDEX_ID, psiMethod.getName(), null, processor, useScope.intersectWith(methodUseScope)); - for (Map.Entry> entry : holders.entrySet()) { - for (JavaFunctionalExpressionIndex.IndexHolder holder : entry.getValue()) { - if (processor.canBeFunctional(holder)) { - filesToProcess.add(entry.getKey()); - break; - } + ApplicationManager.getApplication().runReadAction(() -> { + if (!psiMethod.isValid()) return; + final int parametersCount = psiMethod.getParameterList().getParametersCount(); + final boolean varArgs = psiMethod.isVarArgs(); + final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); + final GlobalSearchScope methodUseScope = convertToGlobalScope(project, psiMethod.getUseScope()); + final LinkedHashMap> holders = new LinkedHashMap>(); + //functional expressions checker: number and type of parameters at call site should correspond to candidate method currently check + final SuitableFilesProcessor processor = new SuitableFilesProcessor(holders, expectedFunExprParamsCount, parametersCount, varArgs, parameters); + fileBasedIndex.processValues(JavaFunctionalExpressionIndex.JAVA_FUNCTIONAL_EXPRESSION_INDEX_ID, psiMethod.getName(), null, processor, useScope.intersectWith(methodUseScope)); + for (Map.Entry> entry : holders.entrySet()) { + for (JavaFunctionalExpressionIndex.IndexHolder holder : entry.getValue()) { + if (processor.canBeFunctional(holder)) { + filesToProcess.add(entry.getKey()); + break; } } } @@ -177,14 +175,11 @@ public class JavaFunctionalExpressionSearcher extends QueryExecutorBase methods = newLinkedHashSet(); - Processor methodProcessor = new Processor() { - @Override - public boolean process(PsiMethod method) { - if (usedMethodNames.contains(method.getName())) { - methods.add(method); - } - return true; + Processor methodProcessor = method -> { + if (usedMethodNames.contains(method.getName())) { + methods.add(method); } + return true; }; StubIndexKey key = JavaMethodParameterTypesIndex.getInstance().getKey(); @@ -225,11 +220,8 @@ public class JavaFunctionalExpressionSearcher extends QueryExecutorBase files = new HashSet(); - addAllNotNull(files, map(((LocalSearchScope)useScope).getScope(), new Function() { - @Override - public VirtualFile fun(PsiElement element) { - return PsiUtilCore.getVirtualFile(element); - } + addAllNotNull(files, map(((LocalSearchScope)useScope).getScope(), element -> { + return PsiUtilCore.getVirtualFile(element); })); scope = GlobalSearchScope.filesScope(project, files); } @@ -260,20 +252,17 @@ public class JavaFunctionalExpressionSearcher extends QueryExecutorBase usageFiles) { final Set fields = new LinkedHashSet(); for (final PsiReference reference : ReferencesSearch.search(aClass, filesScope)) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiElement element = reference.getElement(); - if (element != null) { - addIfNotNull(usageFiles, PsiUtilCore.getVirtualFile(element)); - final PsiElement parent = element.getParent(); - if (parent instanceof PsiTypeElement) { - final PsiElement gParent = parent.getParent(); - if (gParent instanceof PsiField && - !((PsiField)gParent).hasModifierProperty(PsiModifier.PRIVATE) && - !((PsiField)gParent).hasModifierProperty(PsiModifier.FINAL)) { - fields.add((PsiField)gParent); - } + ApplicationManager.getApplication().runReadAction(() -> { + final PsiElement element = reference.getElement(); + if (element != null) { + addIfNotNull(usageFiles, PsiUtilCore.getVirtualFile(element)); + final PsiElement parent = element.getParent(); + if (parent instanceof PsiTypeElement) { + final PsiElement gParent = parent.getParent(); + if (gParent instanceof PsiField && + !((PsiField)gParent).hasModifierProperty(PsiModifier.PRIVATE) && + !((PsiField)gParent).hasModifierProperty(PsiModifier.FINAL)) { + fields.add((PsiField)gParent); } } } diff --git a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/AnonymousClassesSorter.java b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/AnonymousClassesSorter.java index b18f9afe5716..0f833df7ab3a 100644 --- a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/AnonymousClassesSorter.java +++ b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/AnonymousClassesSorter.java @@ -28,19 +28,16 @@ import java.util.Comparator; public class AnonymousClassesSorter implements Sorter { public static Sorter INSTANCE = new AnonymousClassesSorter(); - private final Comparator myComparator = new Comparator() { - @Override - public int compare(Object o1, Object o2) { - String s1 = SorterUtil.getStringPresentation(o1); - String s2 = SorterUtil.getStringPresentation(o2); - if (s1.startsWith("$") && s2.startsWith("$")) { - try { - return Integer.parseInt(s1.substring(1)) - Integer.parseInt(s2.substring(1)); - } catch (NumberFormatException e) {// - } + private final Comparator myComparator = (o1, o2) -> { + String s1 = SorterUtil.getStringPresentation(o1); + String s2 = SorterUtil.getStringPresentation(o2); + if (s1.startsWith("$") && s2.startsWith("$")) { + try { + return Integer.parseInt(s1.substring(1)) - Integer.parseInt(s2.substring(1)); + } catch (NumberFormatException e) {// } - return 0; } + return 0; }; @NotNull diff --git a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java index 8a769377f9fc..7988268d1b65 100644 --- a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java +++ b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java @@ -135,12 +135,9 @@ public class PsiMethodTreeElement extends JavaClassTreeElementBase im public String getAlphaSortKey() { final PsiMethod method = getElement(); if (method != null) { - return method.getName() + " " + StringUtil.join(method.getParameterList().getParameters(), new Function() { - @Override - public String fun(PsiParameter psiParameter) { - PsiTypeElement typeElement = psiParameter.getTypeElement(); - return typeElement != null ? typeElement.getText() : ""; - } + return method.getName() + " " + StringUtil.join(method.getParameterList().getParameters(), psiParameter -> { + PsiTypeElement typeElement = psiParameter.getTypeElement(); + return typeElement != null ? typeElement.getText() : ""; }, " "); } return ""; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/ClsGenericsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/ClsGenericsHighlightingTest.java index fb0027867dc5..3f8ad0b4bdc8 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/ClsGenericsHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/ClsGenericsHighlightingTest.java @@ -75,14 +75,11 @@ public abstract class ClsGenericsHighlightingTest extends UsefulTestCase { } protected void addLibrary(@NotNull final String... libraryPath) { - ModuleRootModificationUtil.updateModel(myModule, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - commitLibraryModel(model, myFixture.getTestDataPath(), libraryPath); + ModuleRootModificationUtil.updateModel(myModule, model -> { + commitLibraryModel(model, myFixture.getTestDataPath(), libraryPath); - String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()); - model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); - } + String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()); + model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); }); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/ExternalJavadocUrlsTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/ExternalJavadocUrlsTest.java index 2f1eaeaeed3a..b868ae82e52f 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/ExternalJavadocUrlsTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/ExternalJavadocUrlsTest.java @@ -63,11 +63,8 @@ public class ExternalJavadocUrlsTest extends LightCodeInsightFixtureTestCase { assertNotNull(member); List urls = JavaDocumentationProvider.getExternalJavaDocUrl(member); assertNotNull(urls); - List actual = ContainerUtil.map(urls, new Function() { - @Override - public String fun(String url) { - return url.substring(url.indexOf('#') + 1); - } + List actual = ContainerUtil.map(urls, url -> { + return url.substring(url.indexOf('#') + 1); }); assertOrderedEquals(actual, expected); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEquals15Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEquals15Test.java index bc270b60c38c..384ff7148be4 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEquals15Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEquals15Test.java @@ -13,22 +13,14 @@ public class GenerateEquals15Test extends GenerateEqualsTestCase { } public void testDifferentTypes() throws Exception { - doTest(Function.ID, Function.ID, new Function() { - @Override - public PsiField[] fun(PsiField[] fields) { - return new PsiField[0]; - } - }, true + doTest(Function.ID, Function.ID, fields -> { + return new PsiField[0]; + }, true ); } public void testDifferentTypesGetters() throws Exception { - doTest(Function.ID, Function.ID, new Function() { - @Override - public PsiField[] fun(PsiField[] fields) { - return new PsiField[0]; - } - }, true, true); + doTest(Function.ID, Function.ID, fields -> new PsiField[0], true, true); } public void testDifferentTypesAllNotNull() throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEqualsTestCase.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEqualsTestCase.java index cb28ca2ef5a0..dab8c22abc89 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEqualsTestCase.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateEqualsTestCase.java @@ -21,21 +21,12 @@ public abstract class GenerateEqualsTestCase extends LightCodeInsightTestCase { final int[] hashCode, final int[] nonNull, boolean insertOverride) throws Exception { - doTest(new Function() { - @Override - public PsiField[] fun(PsiField[] fields) { - return getIndexed(fields, equals); - } - }, new Function() { - @Override - public PsiField[] fun(PsiField[] fields) { - return getIndexed(fields, hashCode); - } - }, new Function() { - @Override - public PsiField[] fun(PsiField[] fields) { - return getIndexed(fields, nonNull); - } + doTest(fields -> { + return getIndexed(fields, equals); + }, fields -> { + return getIndexed(fields, hashCode); + }, fields -> { + return getIndexed(fields, nonNull); }, insertOverride); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java index 9658830054d6..bc7b6b84025c 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java @@ -85,15 +85,12 @@ public class GenerateMembersUtilTest extends LightCodeInsightTestCase { PsiJavaFile file = (PsiJavaFile)PsiFileFactory.getInstance(getProject()) .createFileFromText(JavaLanguage.INSTANCE, "class A {void foo() {}}\n class B extends A {void foo() {}\n}"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiMethod newMethod = file.getClasses()[1].getMethods()[0]; - GenerateMembersUtil.setupGeneratedMethod(newMethod); - assertEquals("@Override void foo() {\n" + - " super.foo();\n" + - " }", newMethod.getText()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PsiMethod newMethod = file.getClasses()[1].getMethods()[0]; + GenerateMembersUtil.setupGeneratedMethod(newMethod); + assertEquals("@Override void foo() {\n" + + " super.foo();\n" + + " }", newMethod.getText()); }); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java index 2fa48e312e1b..6f2322d1ca92 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java @@ -59,11 +59,8 @@ public class GenerateSuperMethodCallTest extends LightCodeInsightTestCase { return super.getHandler(); } }.getHandler(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - handler.invoke(getProject(), getEditor(), getFile()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + handler.invoke(getProject(), getEditor(), getFile()); }); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/MultipleJdksHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/MultipleJdksHighlightingTest.java index 508d8d5e9931..874522ec38f7 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/MultipleJdksHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/MultipleJdksHighlightingTest.java @@ -72,28 +72,19 @@ public class MultipleJdksHighlightingTest extends UsefulTestCase { myJava3Module = builders[0].getFixture().getModule(); myJava7Module = builders[1].getFixture().getModule(); myJava8Module = builders[2].getFixture().getModule(); - ModuleRootModificationUtil.updateModel(myJava3Module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()) + "/java3"; - model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); - } + ModuleRootModificationUtil.updateModel(myJava3Module, model -> { + String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()) + "/java3"; + model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); }); - ModuleRootModificationUtil.updateModel(myJava7Module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()) + "/java7"; - model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); - } + ModuleRootModificationUtil.updateModel(myJava7Module, model -> { + String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()) + "/java7"; + model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); }); - ModuleRootModificationUtil.updateModel(myJava8Module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()) + "/java8"; - model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); - } + ModuleRootModificationUtil.updateModel(myJava8Module, model -> { + String contentUrl = VfsUtilCore.pathToUrl(myFixture.getTempDirPath()) + "/java8"; + model.addContentEntry(contentUrl).addSourceFolder(contentUrl, false); }); } @@ -111,12 +102,7 @@ public class MultipleJdksHighlightingTest extends UsefulTestCase { addDependencies_37_78(); final String name = getTestName(false); for (Module module : new Module[] {myJava7Module, myJava8Module}) { - ModuleRootModificationUtil.updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - ClsGenericsHighlightingTest.commitLibraryModel(model, myFixture.getTestDataPath(), name + ".jar"); - } - }); + ModuleRootModificationUtil.updateModel(module, model -> ClsGenericsHighlightingTest.commitLibraryModel(model, myFixture.getTestDataPath(), name + ".jar")); } myFixture.configureByFile("java8/p/" + name + ".java"); @@ -227,12 +213,7 @@ public class MultipleJdksHighlightingTest extends UsefulTestCase { private void doTest() { final String name = getTestName(false); for (Module module : new Module[] {myJava7Module, myJava8Module}) { - ModuleRootModificationUtil.updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - ClsGenericsHighlightingTest.commitLibraryModel(model, myFixture.getTestDataPath(), name + ".jar"); - } - }); + ModuleRootModificationUtil.updateModel(module, model -> ClsGenericsHighlightingTest.commitLibraryModel(model, myFixture.getTestDataPath(), name + ".jar")); } myFixture.configureByFiles("java7/p/" + name + ".java", "java8/p/" + name + ".java"); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java index 71e1a928c4e3..ddf462953065 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java @@ -164,24 +164,21 @@ public class OverrideImplement15Test extends LightCodeInsightTestCase { PsiElement context = getFile().findElementAt(offset); PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); assert psiClass != null; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (toImplement == null) { - PsiClassType[] implement = psiClass.getImplementsListTypes(); - final PsiClass superClass = implement.length == 0 ? psiClass.getSuperClass() : implement[0].resolve(); - assert superClass != null; - PsiMethod method = superClass.getMethods()[0]; - final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass, PsiSubstitutor.EMPTY); - final List candidates = Collections.singletonList(new PsiMethodMember(method, - OverrideImplementExploreUtil - .correctSubstitutor(method, - substitutor))); - OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true); - } - else { - OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (toImplement == null) { + PsiClassType[] implement = psiClass.getImplementsListTypes(); + final PsiClass superClass = implement.length == 0 ? psiClass.getSuperClass() : implement[0].resolve(); + assert superClass != null; + PsiMethod method = superClass.getMethods()[0]; + final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass, PsiSubstitutor.EMPTY); + final List candidates = Collections.singletonList(new PsiMethodMember(method, + OverrideImplementExploreUtil + .correctSubstitutor(method, + substitutor))); + OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true); + } + else { + OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); } }); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/SuppressExternalTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/SuppressExternalTest.java index da9b2615f423..45d766a8e132 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/SuppressExternalTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/SuppressExternalTest.java @@ -70,15 +70,12 @@ public class SuppressExternalTest extends UsefulTestCase { private void addAnnotationsModuleRoot() throws IOException { myFixture.copyDirectoryToProject("content/anno/suppressed", "content/anno/suppressed"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Module module = myFixture.getModule(); - final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); - final String url = VfsUtilCore.pathToUrl(myFixture.getTempDirPath() + "/content/anno"); - model.getModuleExtension(JavaModuleExternalPaths.class).setExternalAnnotationUrls(new String[]{url}); - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final Module module = myFixture.getModule(); + final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); + final String url = VfsUtilCore.pathToUrl(myFixture.getTempDirPath() + "/content/anno"); + model.getModuleExtension(JavaModuleExternalPaths.class).setExternalAnnotationUrls(new String[]{url}); + model.commit(); }); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImplementationsViewTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImplementationsViewTest.java index e7c8c8a79999..e3f5ffc3bb7b 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImplementationsViewTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImplementationsViewTest.java @@ -256,13 +256,8 @@ public class ImplementationsViewTest extends LightCodeInsightFixtureTestCase { all.addAll(methods); //make sure they are in predefined order - Collections.sort(all, new Comparator() { - @Override - public int compare(PsiMethod o1, PsiMethod o2) { - return o1.getContainingClass().getQualifiedName() - .compareTo(o2.getContainingClass().getQualifiedName()); - } - }); + Collections.sort(all, (o1, o2) -> o1.getContainingClass().getQualifiedName() + .compareTo(o2.getContainingClass().getQualifiedName())); final ImplementationViewComponent component = new ImplementationViewComponent(all.toArray(new PsiElement[all.size()]), 0); assertContent(component, new String[]{"a.java (AFoo)", "a.java (AFoo1 in AFoo)", "a.java (AFoo2 in AFoo)", "a.java (AFoo3 in AFoo)"}); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImportHelperTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImportHelperTest.java index 0a5a45eb1cad..15e5deb90b1d 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImportHelperTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/ImportHelperTest.java @@ -72,43 +72,35 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase { final PsiJavaFile file = (PsiJavaFile)configureByText(StdFileTypes.JAVA, text); assertEmpty(highlightErrors()); CommandProcessor.getInstance().executeCommand( - getProject(), new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - try { - checkAddImport(file, CommonClassNames.JAVA_UTIL_LIST, CommonClassNames.JAVA_UTIL_LIST); - checkAddImport(file, "java.util.ArrayList", "java.util.ArrayList", CommonClassNames.JAVA_UTIL_LIST); - checkAddImport(file, "java.util.HashMap", "java.util.ArrayList","java.util.HashMap", CommonClassNames.JAVA_UTIL_LIST); - checkAddImport(file, "java.util.SortedMap", "java.util.ArrayList","java.util.HashMap", CommonClassNames.JAVA_UTIL_LIST,"java.util.SortedMap"); - checkAddImport(file, CommonClassNames.JAVA_UTIL_MAP, "java.util.ArrayList","java.util.HashMap", - CommonClassNames.JAVA_UTIL_LIST, - CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap"); - checkAddImport(file, "java.util.AbstractList", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", - CommonClassNames.JAVA_UTIL_LIST, - CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap"); - checkAddImport(file, "java.util.AbstractList", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", - CommonClassNames.JAVA_UTIL_LIST, - CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap"); - checkAddImport(file, "java.util.TreeMap", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", - CommonClassNames.JAVA_UTIL_LIST, - CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap", "java.util.TreeMap"); - checkAddImport(file, "java.util.concurrent.atomic.AtomicBoolean", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", - CommonClassNames.JAVA_UTIL_LIST, - CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap", "java.util.TreeMap", "java.util.concurrent.atomic.AtomicBoolean"); - checkAddImport(file, "java.io.File", "java.io.File","java.util.AbstractList","java.util.ArrayList","java.util.HashMap", - CommonClassNames.JAVA_UTIL_LIST, - CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap", "java.util.TreeMap", "java.util.concurrent.atomic.AtomicBoolean"); - } - catch (Throwable e) { - LOG.error(e); - } - } - }); - } - }, "", ""); + getProject(), () -> WriteCommandAction.runWriteCommandAction(null, () -> { + try { + checkAddImport(file, CommonClassNames.JAVA_UTIL_LIST, CommonClassNames.JAVA_UTIL_LIST); + checkAddImport(file, "java.util.ArrayList", "java.util.ArrayList", CommonClassNames.JAVA_UTIL_LIST); + checkAddImport(file, "java.util.HashMap", "java.util.ArrayList","java.util.HashMap", CommonClassNames.JAVA_UTIL_LIST); + checkAddImport(file, "java.util.SortedMap", "java.util.ArrayList","java.util.HashMap", CommonClassNames.JAVA_UTIL_LIST,"java.util.SortedMap"); + checkAddImport(file, CommonClassNames.JAVA_UTIL_MAP, "java.util.ArrayList","java.util.HashMap", + CommonClassNames.JAVA_UTIL_LIST, + CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap"); + checkAddImport(file, "java.util.AbstractList", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", + CommonClassNames.JAVA_UTIL_LIST, + CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap"); + checkAddImport(file, "java.util.AbstractList", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", + CommonClassNames.JAVA_UTIL_LIST, + CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap"); + checkAddImport(file, "java.util.TreeMap", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", + CommonClassNames.JAVA_UTIL_LIST, + CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap", "java.util.TreeMap"); + checkAddImport(file, "java.util.concurrent.atomic.AtomicBoolean", "java.util.AbstractList","java.util.ArrayList","java.util.HashMap", + CommonClassNames.JAVA_UTIL_LIST, + CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap", "java.util.TreeMap", "java.util.concurrent.atomic.AtomicBoolean"); + checkAddImport(file, "java.io.File", "java.io.File","java.util.AbstractList","java.util.ArrayList","java.util.HashMap", + CommonClassNames.JAVA_UTIL_LIST, + CommonClassNames.JAVA_UTIL_MAP,"java.util.SortedMap", "java.util.TreeMap", "java.util.concurrent.atomic.AtomicBoolean"); + } + catch (Throwable e) { + LOG.error(e); + } + }), "", ""); } @WrapInCommand public void testStaticImportsGrouping() throws Throwable { @@ -127,45 +119,37 @@ public class ImportHelperTest extends DaemonAnalyzerTestCase { final PsiJavaFile file = (PsiJavaFile)configureByText(StdFileTypes.JAVA, text); assertEmpty(highlightErrors()); CommandProcessor.getInstance().executeCommand( - getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { + getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { - CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()).clone(); - settings.LAYOUT_STATIC_IMPORTS_SEPARATELY = true; - PackageEntryTable table = new PackageEntryTable(); - table.addEntry(PackageEntry.ALL_OTHER_IMPORTS_ENTRY); - table.addEntry(PackageEntry.BLANK_LINE_ENTRY); - table.addEntry(new PackageEntry(false, "javax", true)); - table.addEntry(new PackageEntry(false, "java", true)); - table.addEntry(PackageEntry.BLANK_LINE_ENTRY); - table.addEntry(new PackageEntry(true, "java", true)); - table.addEntry(PackageEntry.BLANK_LINE_ENTRY); - table.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY); + CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()).clone(); + settings.LAYOUT_STATIC_IMPORTS_SEPARATELY = true; + PackageEntryTable table = new PackageEntryTable(); + table.addEntry(PackageEntry.ALL_OTHER_IMPORTS_ENTRY); + table.addEntry(PackageEntry.BLANK_LINE_ENTRY); + table.addEntry(new PackageEntry(false, "javax", true)); + table.addEntry(new PackageEntry(false, "java", true)); + table.addEntry(PackageEntry.BLANK_LINE_ENTRY); + table.addEntry(new PackageEntry(true, "java", true)); + table.addEntry(PackageEntry.BLANK_LINE_ENTRY); + table.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY); - settings.IMPORT_LAYOUT_TABLE.copyFrom(table); - CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(settings); - try { - JavaCodeStyleManager.getInstance(getProject()).optimizeImports(file); - } - finally { - CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); - } + settings.IMPORT_LAYOUT_TABLE.copyFrom(table); + CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(settings); + try { + JavaCodeStyleManager.getInstance(getProject()).optimizeImports(file); + } + finally { + CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); + } - assertOrder(file, "java.awt.*", CommonClassNames.JAVA_UTIL_MAP, "static java.lang.Math.max", "static java.lang.Math.min", "static javax.swing.SwingConstants.CENTER"); + assertOrder(file, "java.awt.*", CommonClassNames.JAVA_UTIL_MAP, "static java.lang.Math.max", "static java.lang.Math.min", "static javax.swing.SwingConstants.CENTER"); - } - catch (Throwable e) { - LOG.error(e); - } - } - }); } - }, "", ""); + catch (Throwable e) { + LOG.error(e); + } + }), "", ""); } private void checkAddImport(PsiJavaFile file, String fqn, String... expectedOrder) { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java index 8dd0150e0721..1f2f0a821c11 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java @@ -102,14 +102,11 @@ public class LightAdvHighlightingPerformanceTest extends LightDaemonAnalyzerTest CodeInsightTestFixtureImpl.ensureIndexesUpToDate(getProject()); final List infos = new ArrayList(); - PlatformTestUtil.startPerformanceTest(getTestName(false), maxMillis, new ThrowableRunnable() { - @Override - public void run() throws Exception { - infos.clear(); - DaemonCodeAnalyzer.getInstance(getProject()).restart(); - List h = doHighlighting(); - infos.addAll(h); - } + PlatformTestUtil.startPerformanceTest(getTestName(false), maxMillis, () -> { + infos.clear(); + DaemonCodeAnalyzer.getInstance(getProject()).restart(); + List h = doHighlighting(); + infos.addAll(h); }).cpuBound().usesAllCPUCores().useLegacyScaling().assertTiming(); return highlightErrors(); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LossyEncodingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LossyEncodingTest.java index 5ef7fe870644..292c61aa02a5 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LossyEncodingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LossyEncodingTest.java @@ -139,12 +139,9 @@ public class LossyEncodingTest extends DaemonAnalyzerTestCase { configureByText(FileTypes.PLAIN_TEXT, threeNotoriousRussianLetters); VirtualFile virtualFile = getFile().getVirtualFile(); final Document document = FileDocumentManager.getInstance().getDocument(virtualFile); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - document.insertString(0, " "); - document.deleteString(0, 1); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + document.insertString(0, " "); + document.deleteString(0, 1); }); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/UnusedSymbolLocalTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/UnusedSymbolLocalTest.java index bd2fab9b3f42..8257d8f0d561 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/UnusedSymbolLocalTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/UnusedSymbolLocalTest.java @@ -48,11 +48,8 @@ public class UnusedSymbolLocalTest extends DaemonAnalyzerTestCase { assertEquals(0, collection.size()); final int offset = myEditor.getCaretModel().getOffset(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - document.insertString(offset, "//"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + document.insertString(offset, "//"); }); PsiDocumentManager.getInstance(getProject()).commitDocument(document); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java index 2b4832eda07a..1972624b2a71 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java @@ -62,13 +62,10 @@ public class I18nizeTest extends LightCodeInsightTestCase { if (afterFileExists) { PsiLiteralExpression literalExpression = I18nizeAction.getEnclosingStringLiteral(getFile(), getEditor()); assertNotNull(handler); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - handler.performI18nization(getFile(), getEditor(), literalExpression, Collections.emptyList(), "key1", "value1", - "i18nizedExpr", - PsiExpression.EMPTY_ARRAY, JavaI18nUtil.DEFAULT_PROPERTY_CREATION_HANDLER); - } + ApplicationManager.getApplication().runWriteAction(() -> { + handler.performI18nization(getFile(), getEditor(), literalExpression, Collections.emptyList(), "key1", "value1", + "i18nizedExpr", + PsiExpression.EMPTY_ARRAY, JavaI18nUtil.DEFAULT_PROPERTY_CREATION_HANDLER); }); checkResultByFile(afterFile); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/OrderEntryTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/OrderEntryTest.java index 18c9f577937e..2deb7970004a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/OrderEntryTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/OrderEntryTest.java @@ -91,11 +91,8 @@ public class OrderEntryTest extends DaemonAnalyzerTestCase { if (!actionShouldBeAvailable) { fail("Action '" + text + "' is available in test " + testFullPath); } - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - action.invoke(getProject(), getEditor(), getFile()); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + action.invoke(getProject(), getEditor(), getFile()); }); Collection infosAfter = highlightErrors(); @@ -155,22 +152,19 @@ public class OrderEntryTest extends DaemonAnalyzerTestCase { } private void removeLibs() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - for (Module module : ModuleManager.getInstance(getProject()).getModules()) { - ModuleRootManager rootManager = ModuleRootManager.getInstance(module); - ModifiableRootModel model = rootManager.getModifiableModel(); - for (OrderEntry orderEntry : model.getOrderEntries()) { - model.removeOrderEntry(orderEntry); - } - model.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + for (Module module : ModuleManager.getInstance(getProject()).getModules()) { + ModuleRootManager rootManager = ModuleRootManager.getInstance(module); + ModifiableRootModel model = rootManager.getModifiableModel(); + for (OrderEntry orderEntry : model.getOrderEntries()) { + model.removeOrderEntry(orderEntry); } + model.commit(); } - catch (Throwable e) { - e.printStackTrace(); // when running test from within IDEA it would fail because junit.jar cache is locked by host IDEA instance - } + } + catch (Throwable e) { + e.printStackTrace(); // when running test from within IDEA it would fail because junit.jar cache is locked by host IDEA instance } }); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java index e775ef7260cf..eed7a54f5991 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java @@ -217,11 +217,8 @@ public class JavaSurroundWithTest extends LightCodeInsightTestCase { PsiElement[] elements = item.getElementsToSurround(getFile(), selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()); assertTrue(surrounder.isApplicable(elements)); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); - } + ApplicationManager.getApplication().runWriteAction(() -> { + SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); }); checkResultByFile(BASE_PATH + fileName + "_after.java"); @@ -230,11 +227,8 @@ public class JavaSurroundWithTest extends LightCodeInsightTestCase { private void doTestWithTemplateFinish(@NotNull String fileName, Surrounder surrounder, @Nullable String textToType) { TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable()); configureByFile(BASE_PATH + fileName + ".java"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); - } + ApplicationManager.getApplication().runWriteAction(() -> { + SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); }); if (textToType != null) { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java index 6cef301c8b1c..8e38e0a20538 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java @@ -77,11 +77,8 @@ public class SplitIfActionTest extends LightCodeInsightTestCase { private void perform() throws Exception { SplitIfAction action = new SplitIfAction(); assertTrue(action.isAvailable(getProject(), getEditor(), getFile())); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - action.invoke(getProject(), getEditor(), getFile()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + action.invoke(getProject(), getEditor(), getFile()); }); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/navigation/RunLineMarkerTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/navigation/RunLineMarkerTest.java index 885de50fdc49..dca6d4ccd5dc 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/navigation/RunLineMarkerTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/navigation/RunLineMarkerTest.java @@ -77,11 +77,8 @@ public class RunLineMarkerTest extends LightCodeInsightFixtureTestCase { GutterIconsConfigurable configurable = new GutterIconsConfigurable(); configurable.createComponent(); List descriptors = configurable.getDescriptors(); - Set strings = ContainerUtil.map2Set(descriptors, new Function() { - @Override - public String fun(GutterIconDescriptor descriptor) { - return descriptor.getId(); - } + Set strings = ContainerUtil.map2Set(descriptors, descriptor -> { + return descriptor.getId(); }); assertEquals(descriptors.size(), strings.size()); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/psi/ControlFlowTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/psi/ControlFlowTest.java index 081cc6518753..4bc2ab2c16f1 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/psi/ControlFlowTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/psi/ControlFlowTest.java @@ -76,11 +76,8 @@ public class ControlFlowTest extends LightCodeInsightTestCase { private static void doAllTests() throws Exception { final String testDirPath = PathManagerEx.getTestDataPath().replace(File.separatorChar, '/') + BASE_PATH; File testDir = new File(testDirPath); - final File[] files = testDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".java"); - } + final File[] files = testDir.listFiles((dir, name) -> { + return name.endsWith(".java"); }); for (int i = 0; i < files.length; i++) { File file = files[i]; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/TemplateBuilderTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/TemplateBuilderTest.java index f88d4b8b9e29..70f68e8baf95 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/template/TemplateBuilderTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/TemplateBuilderTest.java @@ -11,11 +11,8 @@ public class TemplateBuilderTest extends LightCodeInsightFixtureTestCase { " public String test() {\n" + " }\n" + "}"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - TemplateBuilderFactory.getInstance().createTemplateBuilder(myFixture.getElementAtCaret()).run(myFixture.getEditor(), true); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + TemplateBuilderFactory.getInstance().createTemplateBuilder(myFixture.getElementAtCaret()).run(myFixture.getEditor(), true); }); myFixture.checkResult("class A {\n" + " public String test() {\n" + diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java index 6160c6338e52..09fd1f965be4 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java @@ -237,12 +237,7 @@ public class TemplatesCompletionTest extends CompletionAutoPopupTestCase { } private void configureByFile() { - edt(new Runnable() { - @Override - public void run() { - myFixture.configureByFile(getTestName(true) + ".java"); - } - }); + edt(() -> myFixture.configureByFile(getTestName(true) + ".java")); } private void checkResultByFile() { diff --git a/java/java-tests/testSrc/com/intellij/execution/filters/ExceptionWorkerTest.java b/java/java-tests/testSrc/com/intellij/execution/filters/ExceptionWorkerTest.java index f7c56c56b265..4c5fd19b17c6 100644 --- a/java/java-tests/testSrc/com/intellij/execution/filters/ExceptionWorkerTest.java +++ b/java/java-tests/testSrc/com/intellij/execution/filters/ExceptionWorkerTest.java @@ -55,12 +55,8 @@ public class ExceptionWorkerTest extends LightCodeInsightFixtureTestCase { final Document document = EditorFactory.getInstance().createDocument(testData); FilterMixin filter = (FilterMixin)new ExceptionExFilterFactory().create(GlobalSearchScope.projectScope(getProject())); final ArrayList result = new ArrayList(); - filter.applyHeavyFilter(document, 0, 0, new Consumer() { - @Override - public void consume(FilterMixin.AdditionalHighlight highlight) { - result.add(new TextRange(highlight.getStart(), highlight.getEnd()-1).substring(testData)); - } - }); + filter.applyHeavyFilter(document, 0, 0, + highlight -> result.add(new TextRange(highlight.getStart(), highlight.getEnd() - 1).substring(testData))); assertSameElements(result, "com.sample.RunningMain.func1", "com.sample.RunningMain.main"); } } diff --git a/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java b/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java index c987402b9574..04126192f4bb 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java @@ -92,12 +92,9 @@ public class FoldingProcessingOnDocumentModificationTest extends AbstractEditorT checkFoldingState("[FoldRegion -(0:37), placeholder='/.../', FoldRegion +(27:35), placeholder='{...}']"); WriteCommandAction.runWriteCommandAction(getProject(), - new Runnable() { - @Override - public void run() { - myEditor.getDocument().deleteString(0, 2); - } - }); + () -> { + myEditor.getDocument().deleteString(0, 2); + }); checkFoldingState("[FoldRegion +(25:33), placeholder='{...}']"); } diff --git a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java index 63eb149b4add..d69974a7c49b 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java @@ -68,103 +68,100 @@ public class DirectoryIndexTest extends IdeaTestCase { final File root = createTempDirectory(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - /* - root - lib - file.src - file.cls - module1 - src1 - pack1 - testSrc - pack2 - res - testRes - lib - src - exc - cls - exc - module2 - src2 - CVS - excluded - module3 - out - module1 - */ - myRootVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(root); - assertNotNull(myRootVFile); + ApplicationManager.getApplication().runWriteAction(() -> { + /* + root + lib + file.src + file.cls + module1 + src1 + pack1 + testSrc + pack2 + res + testRes + lib + src + exc + cls + exc + module2 + src2 + CVS + excluded + module3 + out + module1 + */ + myRootVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(root); + assertNotNull(myRootVFile); - myFileLibDir = createChildDirectory(myRootVFile, "lib"); - myFileLibSrc = createChildData(myFileLibDir, "file.src"); - myFileLibCls = createChildData(myFileLibDir, "file.cls"); - myModule1Dir = createChildDirectory(myRootVFile, "module1"); - mySrcDir1 = createChildDirectory(myModule1Dir, "src1"); - myPack1Dir = createChildDirectory(mySrcDir1, "pack1"); - myTestSrc1 = createChildDirectory(mySrcDir1, "testSrc"); - myPack2Dir = createChildDirectory(myTestSrc1, "pack2"); - myResDir = createChildDirectory(myModule1Dir, "res"); - myTestResDir = createChildDirectory(myModule1Dir, "testRes"); + myFileLibDir = createChildDirectory(myRootVFile, "lib"); + myFileLibSrc = createChildData(myFileLibDir, "file.src"); + myFileLibCls = createChildData(myFileLibDir, "file.cls"); + myModule1Dir = createChildDirectory(myRootVFile, "module1"); + mySrcDir1 = createChildDirectory(myModule1Dir, "src1"); + myPack1Dir = createChildDirectory(mySrcDir1, "pack1"); + myTestSrc1 = createChildDirectory(mySrcDir1, "testSrc"); + myPack2Dir = createChildDirectory(myTestSrc1, "pack2"); + myResDir = createChildDirectory(myModule1Dir, "res"); + myTestResDir = createChildDirectory(myModule1Dir, "testRes"); - myLibDir = createChildDirectory(myModule1Dir, "lib"); - myLibSrcDir = createChildDirectory(myLibDir, "src"); - myExcludedLibSrcDir = createChildDirectory(myLibSrcDir, "exc"); - myLibClsDir = createChildDirectory(myLibDir, "cls"); - myExcludedLibClsDir = createChildDirectory(myLibClsDir, "exc"); - myModule2Dir = createChildDirectory(myModule1Dir, "module2"); - mySrcDir2 = createChildDirectory(myModule2Dir, "src2"); - myCvsDir = createChildDirectory(mySrcDir2, "CVS"); - myExcludeDir = createChildDirectory(mySrcDir2, "excluded"); + myLibDir = createChildDirectory(myModule1Dir, "lib"); + myLibSrcDir = createChildDirectory(myLibDir, "src"); + myExcludedLibSrcDir = createChildDirectory(myLibSrcDir, "exc"); + myLibClsDir = createChildDirectory(myLibDir, "cls"); + myExcludedLibClsDir = createChildDirectory(myLibClsDir, "exc"); + myModule2Dir = createChildDirectory(myModule1Dir, "module2"); + mySrcDir2 = createChildDirectory(myModule2Dir, "src2"); + myCvsDir = createChildDirectory(mySrcDir2, "CVS"); + myExcludeDir = createChildDirectory(mySrcDir2, "excluded"); - myModule3Dir = createChildDirectory(myRootVFile, "module3"); + myModule3Dir = createChildDirectory(myRootVFile, "module3"); - myOutputDir = createChildDirectory(myRootVFile, "out"); - myModule1OutputDir = createChildDirectory(myOutputDir, "module1"); + myOutputDir = createChildDirectory(myRootVFile, "out"); + myModule1OutputDir = createChildDirectory(myOutputDir, "module1"); - getCompilerProjectExtension().setCompilerOutputUrl(myOutputDir.getUrl()); - ModuleManager moduleManager = ModuleManager.getInstance(myProject); + getCompilerProjectExtension().setCompilerOutputUrl(myOutputDir.getUrl()); + ModuleManager moduleManager = ModuleManager.getInstance(myProject); - // fill roots of module1 - { - ModuleRootModificationUtil.setModuleSdk(myModule, null); - PsiTestUtil.addContentRoot(myModule, myModule1Dir); - PsiTestUtil.addSourceRoot(myModule, mySrcDir1); - PsiTestUtil.addSourceRoot(myModule, myTestSrc1, true); - PsiTestUtil.addSourceRoot(myModule, myResDir, JavaResourceRootType.RESOURCE); - PsiTestUtil.addSourceRoot(myModule, myTestResDir, JavaResourceRootType.TEST_RESOURCE); + // fill roots of module1 + { + ModuleRootModificationUtil.setModuleSdk(myModule, null); + PsiTestUtil.addContentRoot(myModule, myModule1Dir); + PsiTestUtil.addSourceRoot(myModule, mySrcDir1); + PsiTestUtil.addSourceRoot(myModule, myTestSrc1, true); + PsiTestUtil.addSourceRoot(myModule, myResDir, JavaResourceRootType.RESOURCE); + PsiTestUtil.addSourceRoot(myModule, myTestResDir, JavaResourceRootType.TEST_RESOURCE); - ModuleRootModificationUtil.addModuleLibrary(myModule, "lib.js", - Collections.singletonList(myFileLibCls.getUrl()), Collections - .singletonList(myFileLibSrc.getUrl())); - PsiTestUtil.addExcludedRoot(myModule, myExcludedLibClsDir); - PsiTestUtil.addExcludedRoot(myModule, myExcludedLibSrcDir); - } + ModuleRootModificationUtil.addModuleLibrary(myModule, "lib.js", + Collections.singletonList(myFileLibCls.getUrl()), Collections + .singletonList(myFileLibSrc.getUrl())); + PsiTestUtil.addExcludedRoot(myModule, myExcludedLibClsDir); + PsiTestUtil.addExcludedRoot(myModule, myExcludedLibSrcDir); + } - // fill roots of module2 - { - VirtualFile moduleFile = createChildData(myModule2Dir, "module2.iml"); - myModule2 = moduleManager.newModule(moduleFile.getPath(), StdModuleTypes.JAVA.getId()); + // fill roots of module2 + { + VirtualFile moduleFile = createChildData(myModule2Dir, "module2.iml"); + myModule2 = moduleManager.newModule(moduleFile.getPath(), StdModuleTypes.JAVA.getId()); - PsiTestUtil.addContentRoot(myModule2, myModule2Dir); - PsiTestUtil.addSourceRoot(myModule2, mySrcDir2); - PsiTestUtil.addExcludedRoot(myModule2, myExcludeDir); - ModuleRootModificationUtil.addModuleLibrary(myModule2, "lib", - Collections.singletonList(myLibClsDir.getUrl()), Collections.singletonList(myLibSrcDir.getUrl()), - Arrays.asList(myExcludedLibClsDir.getUrl(), myExcludedLibSrcDir.getUrl()), DependencyScope.COMPILE, true); - } + PsiTestUtil.addContentRoot(myModule2, myModule2Dir); + PsiTestUtil.addSourceRoot(myModule2, mySrcDir2); + PsiTestUtil.addExcludedRoot(myModule2, myExcludeDir); + ModuleRootModificationUtil.addModuleLibrary(myModule2, "lib", + Collections.singletonList(myLibClsDir.getUrl()), Collections.singletonList(myLibSrcDir.getUrl()), + Arrays.asList(myExcludedLibClsDir.getUrl(), myExcludedLibSrcDir.getUrl()), DependencyScope.COMPILE, true); + } - // fill roots of module3 - { - VirtualFile moduleFile = createChildData(myModule3Dir, "module3.iml"); - myModule3 = moduleManager.newModule(moduleFile.getPath(), StdModuleTypes.JAVA.getId()); + // fill roots of module3 + { + VirtualFile moduleFile = createChildData(myModule3Dir, "module3.iml"); + myModule3 = moduleManager.newModule(moduleFile.getPath(), StdModuleTypes.JAVA.getId()); - PsiTestUtil.addContentRoot(myModule3, myModule3Dir); - ModuleRootModificationUtil.addDependency(myModule3, myModule2); - } + PsiTestUtil.addContentRoot(myModule3, myModule3Dir); + ModuleRootModificationUtil.addDependency(myModule3, myModule2); } }); @@ -239,13 +236,10 @@ public class DirectoryIndexTest extends IdeaTestCase { public void testDirectoriesWithPackagePrefix() { PsiTestUtil.addSourceRoot(myModule3, myModule3Dir); - WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { - @Override - public void run() { - final ModifiableRootModel model = ModuleRootManager.getInstance(myModule3).getModifiableModel(); - model.getContentEntries()[0].getSourceFolders()[0].setPackagePrefix("pack1"); - model.commit(); - } + WriteCommandAction.runWriteCommandAction(myProject, () -> { + final ModifiableRootModel model = ModuleRootManager.getInstance(myModule3).getModifiableModel(); + model.getContentEntries()[0].getSourceFolders()[0].setPackagePrefix("pack1"); + model.commit(); }); checkPackage("pack1", true, myPack1Dir, myModule3Dir); } @@ -320,20 +314,14 @@ public class DirectoryIndexTest extends IdeaTestCase { final String list = fileTypeManager.getIgnoredFilesList(); final String list1 = list + ";" + "newDir"; try { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - fileTypeManager.setIgnoredFilesList(list1); - } + ApplicationManager.getApplication().runWriteAction(() -> { + fileTypeManager.setIgnoredFilesList(list1); }); assertNotInProject(newDir); } finally { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - fileTypeManager.setIgnoredFilesList(list); - } + ApplicationManager.getApplication().runWriteAction(() -> { + fileTypeManager.setIgnoredFilesList(list); }); assertInProject(newDir); } @@ -441,11 +429,8 @@ public class DirectoryIndexTest extends IdeaTestCase { } private void fireRootsChanged() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true); }); } @@ -590,19 +575,16 @@ public class DirectoryIndexTest extends IdeaTestCase { public void testProcessingNestedContentRootsOfExcludedDirsOnCreation() { String rootPath = myModule1Dir.getPath(); final File f = new File(rootPath, "excludedDir/dir/anotherContentRoot"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel(); - rootModel.getContentEntries()[0] - .addExcludeFolder(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(f.getParentFile().getParent()))); - rootModel.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel(); + rootModel.getContentEntries()[0] + .addExcludeFolder(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(f.getParentFile().getParent()))); + rootModel.commit(); - ModuleRootModificationUtil.addContentRoot(myModule2, FileUtil.toSystemIndependentName(f.getPath())); + ModuleRootModificationUtil.addContentRoot(myModule2, FileUtil.toSystemIndependentName(f.getPath())); - assertTrue(f.getPath(), f.exists() || f.mkdirs()); - LocalFileSystem.getInstance().refresh(false); - } + assertTrue(f.getPath(), f.exists() || f.mkdirs()); + LocalFileSystem.getInstance().refresh(false); }); assertExcluded(LocalFileSystem.getInstance().findFileByIoFile(f.getParentFile().getParentFile()), myModule); diff --git a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/ProjectLibrariesTest.java b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/ProjectLibrariesTest.java index da25a5af0f0e..4511ea0a995b 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/ProjectLibrariesTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/ProjectLibrariesTest.java @@ -59,12 +59,9 @@ public class ProjectLibrariesTest extends IdeaTestCase { assertNull(getJavaFacade().findClass("pack.MyClass", GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(myModule))); final Library.ModifiableModel model = myLib.getModifiableModel(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - model.addRoot(myRoot, OrderRootType.CLASSES); - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + model.addRoot(myRoot, OrderRootType.CLASSES); + model.commit(); }); assertNotNull(getJavaFacade().findClass("pack.MyClass", GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(myModule))); @@ -78,23 +75,17 @@ public class ProjectLibrariesTest extends IdeaTestCase { assertNotNull(moduleModel.findLibraryOrderEntry(myLib)); final Library.ModifiableModel libModel = myLib.getModifiableModel(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - libModel.addRoot(myRoot, OrderRootType.CLASSES); - libModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + libModel.addRoot(myRoot, OrderRootType.CLASSES); + libModel.commit(); }); assertNotNull(getJavaFacade().findClass("pack.MyClass", GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(myModule))); assertTrue(Arrays.asList(moduleModel.orderEntries().librariesOnly().classes().getRoots()).contains(myRoot)); } finally { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - moduleModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + moduleModel.commit(); }); } diff --git a/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java b/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java index 8f95c73a6a11..fc7c41bd45a1 100644 --- a/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java +++ b/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java @@ -68,10 +68,8 @@ public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { final PsiClass[] classes = JavaDirectoryService.getInstance() .getPackage(getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1")).getClasses(); sortClassesByName(classes); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - classes[0].delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + classes[0].delete(); }); @@ -121,12 +119,8 @@ public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { getRootFiles() + " +External Libraries\n", true); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - new RenameProcessor(myProject, aClass, "Form1_renamed", false, false).run(); - } - }, null, null); + CommandProcessor.getInstance().executeCommand(myProject, + () -> new RenameProcessor(myProject, aClass, "Form1_renamed", false, false).run(), null, null); PlatformTestUtil.waitForAlarm(600); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + @@ -205,18 +199,11 @@ public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { final Document document = FileDocumentManager.getInstance().getDocument(containingFile.getVirtualFile()); final int caretPosition = document.getText().indexOf("public class InnerClass") - 1; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, - new Runnable() { - @Override - public void run() { - document.insertString(caretPosition, "\n"); - } - }, - "typing", - null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(myProject, + () -> document.insertString(caretPosition, "\n"), + "typing", + null); }); @@ -256,23 +243,15 @@ public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { getRootFiles() + " +External Libraries\n", true); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - assertEquals("myField2", lastField.getName()); - lastField.setName("_firstField"); - } - catch (IncorrectOperationException e) { - fail(e.getMessage()); - } - } - }); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + assertEquals("myField2", lastField.getName()); + lastField.setName("_firstField"); } - }, null, null); + catch (IncorrectOperationException e) { + fail(e.getMessage()); + } + }), null, null); PlatformTestUtil.waitForAlarm(600); @@ -384,15 +363,12 @@ public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { final JTree tree = pane.getTree(); - pane.getTreeBuilder().setNodeDescriptorComparator(new Comparator() { - @Override - public int compare(final NodeDescriptor o1, final NodeDescriptor o2) { - if (o1 instanceof NodeWrapper && o2 instanceof NodeWrapper) { - return ((NodeWrapper)o1).getName().compareTo(((NodeWrapper)o2).getName()); - } - else { - return 0; - } + pane.getTreeBuilder().setNodeDescriptorComparator((o1, o2) -> { + if (o1 instanceof NodeWrapper && o2 instanceof NodeWrapper) { + return ((NodeWrapper)o1).getName().compareTo(((NodeWrapper)o2).getName()); + } + else { + return 0; } }); diff --git a/java/java-tests/testSrc/com/intellij/projectView/StructureViewUpdatingTest.java b/java/java-tests/testSrc/com/intellij/projectView/StructureViewUpdatingTest.java index 89d8b15c9a9a..7fb096f94326 100644 --- a/java/java-tests/testSrc/com/intellij/projectView/StructureViewUpdatingTest.java +++ b/java/java-tests/testSrc/com/intellij/projectView/StructureViewUpdatingTest.java @@ -145,23 +145,14 @@ public class StructureViewUpdatingTest extends TestSourceBasedTestCase { " myField3: boolean\n" + " myField4: boolean\n"); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - try { - innerClassField.delete(); - } - catch (IncorrectOperationException e) { - fail(e.getLocalizedMessage()); - } - } - }); + CommandProcessor.getInstance().executeCommand(myProject, () -> WriteCommandAction.runWriteCommandAction(null, () -> { + try { + innerClassField.delete(); } - }, null, null); + catch (IncorrectOperationException e) { + fail(e.getLocalizedMessage()); + } + }), null, null); PlatformTestUtil.waitForAlarm(600); diff --git a/java/java-tests/testSrc/com/intellij/psi/AddClassToFileTest.java b/java/java-tests/testSrc/com/intellij/psi/AddClassToFileTest.java index c4bdd18441aa..dcfc87c48508 100644 --- a/java/java-tests/testSrc/com/intellij/psi/AddClassToFileTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/AddClassToFileTest.java @@ -39,11 +39,8 @@ public class AddClassToFileTest extends PsiTestCase{ } }); PsiClass aClass = myJavaFacade.getElementFactory().createClass("AAA"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - file.add(aClass); - } + ApplicationManager.getApplication().runWriteAction(() -> { + file.add(aClass); }); diff --git a/java/java-tests/testSrc/com/intellij/psi/AddRemoveInTypeParameterListTest.java b/java/java-tests/testSrc/com/intellij/psi/AddRemoveInTypeParameterListTest.java index 0c08c28b0092..712b91674194 100644 --- a/java/java-tests/testSrc/com/intellij/psi/AddRemoveInTypeParameterListTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/AddRemoveInTypeParameterListTest.java @@ -55,26 +55,23 @@ public class AddRemoveInTypeParameterListTest extends LightIdeaTestCase{ PsiReferenceParameterList list = ref.getParameterList(); final PsiTypeElement[] parms = list.getTypeParameterElements(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - parms[0].delete(); + WriteCommandAction.runWriteCommandAction(null, () -> { + parms[0].delete(); - assertEquals("class Test extends Type< B, C, D> {\n}", file.getText()); - PsiTestUtil.checkFileStructure(file); + assertEquals("class Test extends Type< B, C, D> {\n}", file.getText()); + PsiTestUtil.checkFileStructure(file); - parms[2].delete(); + parms[2].delete(); - assertEquals("class Test extends Type< B, D> {\n}", file.getText()); - PsiTestUtil.checkFileStructure(file); + assertEquals("class Test extends Type< B, D> {\n}", file.getText()); + PsiTestUtil.checkFileStructure(file); - parms[3].delete(); + parms[3].delete(); - assertEquals("class Test extends Type< B > {\n}", file.getText()); - PsiTestUtil.checkFileStructure(file); + assertEquals("class Test extends Type< B > {\n}", file.getText()); + PsiTestUtil.checkFileStructure(file); - parms[1].delete(); - } + parms[1].delete(); }); diff --git a/java/java-tests/testSrc/com/intellij/psi/ArrayIndexOutOfBoundsTest.java b/java/java-tests/testSrc/com/intellij/psi/ArrayIndexOutOfBoundsTest.java index 4c8ada5b23f5..4fe7dad7b6b0 100644 --- a/java/java-tests/testSrc/com/intellij/psi/ArrayIndexOutOfBoundsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/ArrayIndexOutOfBoundsTest.java @@ -77,51 +77,39 @@ public class ArrayIndexOutOfBoundsTest extends PsiTestCase { } private void restoreSources() { - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - FileUtil.copyDir(new File(JavaTestUtil.getJavaTestDataPath() + "/psi/arrayIndexOutOfBounds/src"), - VfsUtilCore.virtualToIoFile(myProjectRoot)); - } - catch (IOException e) { - LOG.error(e); - } - VirtualFileManager.getInstance().syncRefresh(); + Runnable runnable = () -> { + try { + FileUtil.copyDir(new File(JavaTestUtil.getJavaTestDataPath() + "/psi/arrayIndexOutOfBounds/src"), + VfsUtilCore.virtualToIoFile(myProjectRoot)); } + catch (IOException e) { + LOG.error(e); + } + VirtualFileManager.getInstance().syncRefresh(); }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", null); } private void deleteNewPackage() { - Runnable runnable = new Runnable() { - @Override - public void run() { - final PsiPackage aPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage("anotherBla"); - assertNotNull("Package anotherBla not found", aPackage); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - aPackage.getDirectories()[0].delete(); - } - }); - VirtualFileManager.getInstance().syncRefresh(); - } + Runnable runnable = () -> { + final PsiPackage aPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage("anotherBla"); + assertNotNull("Package anotherBla not found", aPackage); + WriteCommandAction.runWriteCommandAction(null, () -> { + aPackage.getDirectories()[0].delete(); + }); + VirtualFileManager.getInstance().syncRefresh(); }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", null); } private void renamePackage() { - Runnable runnable = new Runnable() { - @Override - public void run() { - PsiPackage aPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage("bla"); - assertNotNull("Package bla not found", aPackage); + Runnable runnable = () -> { + PsiPackage aPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage("bla"); + assertNotNull("Package bla not found", aPackage); - PsiDirectory dir = aPackage.getDirectories()[0]; - new RenameProcessor(myProject, dir, "anotherBla", true, true).run(); - FileDocumentManager.getInstance().saveAllDocuments(); - } + PsiDirectory dir = aPackage.getDirectories()[0]; + new RenameProcessor(myProject, dir, "anotherBla", true, true).run(); + FileDocumentManager.getInstance().saveAllDocuments(); }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", null); } diff --git a/java/java-tests/testSrc/com/intellij/psi/CodeFragmentsTest.java b/java/java-tests/testSrc/com/intellij/psi/CodeFragmentsTest.java index d9060d7fd40c..3f8aeb9324d1 100644 --- a/java/java-tests/testSrc/com/intellij/psi/CodeFragmentsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/CodeFragmentsTest.java @@ -32,11 +32,8 @@ public class CodeFragmentsTest extends PsiTestCase{ PsiCodeFragment fragment = JavaCodeFragmentFactory.getInstance(myProject).createExpressionCodeFragment("AAA.foo()", null, null, false); PsiClass arrayListClass = myJavaFacade.findClass("java.util.ArrayList", GlobalSearchScope.allScope(getProject())); PsiReference ref = fragment.findReferenceAt(0); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ref.bindToElement(arrayListClass); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ref.bindToElement(arrayListClass); }); assertEquals("ArrayList.foo()", fragment.getText()); @@ -44,18 +41,15 @@ public class CodeFragmentsTest extends PsiTestCase{ public void testDontLoseDocument() { PsiExpressionCodeFragment fragment = JavaCodeFragmentFactory.getInstance(myProject).createExpressionCodeFragment("a", null, null, true); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Document document = PsiDocumentManager.getInstance(myProject).getDocument(fragment); - document.insertString(1, "b"); - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - assertEquals("ab", fragment.getText()); - assertEquals("ab", fragment.getExpression().getText()); + ApplicationManager.getApplication().runWriteAction(() -> { + Document document = PsiDocumentManager.getInstance(myProject).getDocument(fragment); + document.insertString(1, "b"); + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + assertEquals("ab", fragment.getText()); + assertEquals("ab", fragment.getExpression().getText()); - //noinspection UnusedAssignment - document = null; - } + //noinspection UnusedAssignment + document = null; }); @@ -68,11 +62,8 @@ public class CodeFragmentsTest extends PsiTestCase{ VirtualFile file = fragment.getViewProvider().getVirtualFile(); assertInstanceOf(file, LightVirtualFile.class); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManagerEx.getInstanceEx(getProject()).makeRootsChange(EmptyRunnable.getInstance(), false, true); }); diff --git a/java/java-tests/testSrc/com/intellij/psi/CoreJavaFileManagerTest.java b/java/java-tests/testSrc/com/intellij/psi/CoreJavaFileManagerTest.java index 5328e9594e8c..6600e8ebd4b4 100644 --- a/java/java-tests/testSrc/com/intellij/psi/CoreJavaFileManagerTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/CoreJavaFileManagerTest.java @@ -190,11 +190,8 @@ public class CoreJavaFileManagerTest extends PsiTestCase { VirtualFile pkg = createChildDirectory(root, "foo"); PsiDirectory dir = myPsiManager.findDirectory(pkg); assertNotNull(dir); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - dir.add(PsiFileFactory.getInstance(getProject()).createFileFromText(className + ".java", JavaFileType.INSTANCE, text)); - } + ApplicationManager.getApplication().runWriteAction(() -> { + dir.add(PsiFileFactory.getInstance(getProject()).createFileFromText(className + ".java", JavaFileType.INSTANCE, text)); }); CoreJavaFileManager manager = new CoreJavaFileManager(myPsiManager); diff --git a/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java b/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java index a9ca3405cb4b..243d0854fa54 100644 --- a/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java +++ b/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java @@ -39,11 +39,8 @@ public abstract class GenericsTestCase extends PsiTestCase { protected void setupGenericSampleClasses() { final String commonPath = PathManagerEx.getTestDataPath().replace(File.separatorChar, '/') + "/psi/types/src"; final VirtualFile[] commonRoot = { null }; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - commonRoot[0] = LocalFileSystem.getInstance().refreshAndFindFileByPath(commonPath); - } + ApplicationManager.getApplication().runWriteAction(() -> { + commonRoot[0] = LocalFileSystem.getInstance().refreshAndFindFileByPath(commonPath); }); PsiTestUtil.addSourceRoot(myModule, commonRoot[0]); diff --git a/java/java-tests/testSrc/com/intellij/psi/JavaSOEOnReparsePerformanceTest.java b/java/java-tests/testSrc/com/intellij/psi/JavaSOEOnReparsePerformanceTest.java index cf79fd890c69..1915886c928e 100644 --- a/java/java-tests/testSrc/com/intellij/psi/JavaSOEOnReparsePerformanceTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/JavaSOEOnReparsePerformanceTest.java @@ -54,37 +54,31 @@ public class JavaSOEOnReparsePerformanceTest extends LightDaemonAnalyzerTestCase final int pos = getEditor().getDocument().getText().indexOf("\"\""); // replace small expression with huge binary one - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - getEditor().getDocument().replaceString(pos, pos + 2, myHugeExpr); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + getEditor().getDocument().replaceString(pos, pos + 2, myHugeExpr); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); }); doTestConfiguredFile(false, false, null); // modify huge binary expression (1) - ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { getEditor().getDocument().insertString(pos, "\".\"+"); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - }}); + }); doTestConfiguredFile(false, false, null); // modify huge binary expression (2) - ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { getEditor().getDocument().replaceString(pos, pos + 4, ""); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - }}); + }); doTestConfiguredFile(false, false, null); // replace huge binary expression with small one - ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { getEditor().getDocument().replaceString(pos, pos + myHugeExpr.length(), "\".\""); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - }}); + }); doTestConfiguredFile(false, false, null); } } diff --git a/java/java-tests/testSrc/com/intellij/psi/LibraryOrderTest.java b/java/java-tests/testSrc/com/intellij/psi/LibraryOrderTest.java index 6a5218b6519d..ade6a706f905 100644 --- a/java/java-tests/testSrc/com/intellij/psi/LibraryOrderTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/LibraryOrderTest.java @@ -50,11 +50,8 @@ public class LibraryOrderTest extends PsiTestCase { order[length - 2] = lib2; rootModel.rearrangeOrderEntries(order); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - rootModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + rootModel.commit(); } ); diff --git a/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java b/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java index 3f5890b366dd..0d432fb0d736 100644 --- a/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java @@ -128,10 +128,8 @@ public class MiscPsiTest extends LightCodeInsightFixtureTestCase { final PsiClass aClass = getJavaFacade().getElementFactory().createClassFromText("public int i, j;", null); final PsiField aField = aClass.getFields()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - aField.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + aField.delete(); }); assertEquals("public int j;", aClass.getFields()[0].getText()); @@ -185,10 +183,8 @@ public class MiscPsiTest extends LightCodeInsightFixtureTestCase { public void testDeleteAnnotationAttribute() throws Exception { final PsiAnnotation annotation = getJavaFacade().getElementFactory().createAnnotationFromText("@A(b,c)", null); final PsiNameValuePair secondAttribute = annotation.getParameterList().getAttributes()[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - secondAttribute.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + secondAttribute.delete(); }); assertEquals("@A(b )", annotation.getText()); @@ -199,10 +195,8 @@ public class MiscPsiTest extends LightCodeInsightFixtureTestCase { final PsiNameValuePair firstAttribute = annotation.getParameterList().getAttributes()[0]; assertTrue(firstAttribute.getValue() instanceof PsiArrayInitializerMemberValue); final PsiAnnotationMemberValue firstInitializer = ((PsiArrayInitializerMemberValue)firstAttribute.getValue()).getInitializers()[0]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - firstInitializer.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + firstInitializer.delete(); }); assertEquals("@A({ c})", annotation.getText()); diff --git a/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java b/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java index a2fbbf3e65df..e9d03cf7b4b6 100644 --- a/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java @@ -50,22 +50,14 @@ public class ModifyAnnotationsTest extends PsiTestCase { final PsiAnnotation newAnnotation = myJavaFacade.getElementFactory().createAnnotationFromText("@B", null); //here the tree is going to be loaded PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - try { - annotations[0].replace(newAnnotation); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + CommandProcessor.getInstance().executeCommand(myProject, () -> WriteCommandAction.runWriteCommandAction(null, () -> { + try { + annotations[0].replace(newAnnotation); } - }, null, null); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), null, null); assertEquals("@B", aClass.getModifierList().getText()); } diff --git a/java/java-tests/testSrc/com/intellij/psi/NormalizeDeclarationTest.java b/java/java-tests/testSrc/com/intellij/psi/NormalizeDeclarationTest.java index be74702c925b..94208c070b28 100644 --- a/java/java-tests/testSrc/com/intellij/psi/NormalizeDeclarationTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/NormalizeDeclarationTest.java @@ -43,20 +43,14 @@ public class NormalizeDeclarationTest extends PsiTestCase{ assertTrue(element instanceof PsiIdentifier); assertTrue(element.getParent() instanceof PsiVariable); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ((PsiVariable)element.getParent()).normalizeDeclaration(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ((PsiVariable)element.getParent()).normalizeDeclaration(); }); String textAfter = loadFile(getTestName(false) + "_after.java"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); }); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); diff --git a/java/java-tests/testSrc/com/intellij/psi/OptimizeImportsTestCase.java b/java/java-tests/testSrc/com/intellij/psi/OptimizeImportsTestCase.java index 5c03989d6144..3d2fddc87e00 100644 --- a/java/java-tests/testSrc/com/intellij/psi/OptimizeImportsTestCase.java +++ b/java/java-tests/testSrc/com/intellij/psi/OptimizeImportsTestCase.java @@ -27,31 +27,23 @@ import com.intellij.testFramework.PsiTestCase; public abstract class OptimizeImportsTestCase extends PsiTestCase { protected void doTest(final String extension) throws Exception { CommandProcessor.getInstance().executeCommand( - getProject(), new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - String fileName = getTestName(false) + extension; - try { - String text = loadFile(fileName); - PsiFile file = createFile(fileName, text); + getProject(), () -> WriteCommandAction.runWriteCommandAction(null, () -> { + String fileName = getTestName(false) + extension; + try { + String text = loadFile(fileName); + PsiFile file = createFile(fileName, text); - JavaCodeStyleManager.getInstance(myProject).optimizeImports(file); - PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - String textAfter = loadFile(getTestName(false) + "_after" + extension); - String fileText = file.getText(); - assertEquals(textAfter, fileText); - } - catch (Exception e) { - LOG.error(e); - } - } - }); - } - }, "", ""); + JavaCodeStyleManager.getInstance(myProject).optimizeImports(file); + PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + String textAfter = loadFile(getTestName(false) + "_after" + extension); + String fileText = file.getText(); + assertEquals(textAfter, fileText); + } + catch (Exception e) { + LOG.error(e); + } + }), "", ""); } } diff --git a/java/java-tests/testSrc/com/intellij/psi/OverlappingSourceRootsTest.java b/java/java-tests/testSrc/com/intellij/psi/OverlappingSourceRootsTest.java index 0fdf0bff6107..286e16fd5c16 100644 --- a/java/java-tests/testSrc/com/intellij/psi/OverlappingSourceRootsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/OverlappingSourceRootsTest.java @@ -45,35 +45,32 @@ public class OverlappingSourceRootsTest extends PsiTestCase { super.setUp(); ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { + () -> { - try { - File dir = createTempDirectory(); + try { + File dir = createTempDirectory(); - myProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/')); + myProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/')); - mySourceRoot1 = createChildDirectory(myProjectRoot, "root1"); - mySourceRoot2 = createChildDirectory(myProjectRoot, "root2"); - mySourceRoot11 = createChildDirectory(mySourceRoot1, "root11"); - mySourceRoot21 = createChildDirectory(mySourceRoot2, "root21"); + mySourceRoot1 = createChildDirectory(myProjectRoot, "root1"); + mySourceRoot2 = createChildDirectory(myProjectRoot, "root2"); + mySourceRoot11 = createChildDirectory(mySourceRoot1, "root11"); + mySourceRoot21 = createChildDirectory(mySourceRoot2, "root21"); - PsiTestUtil.addContentRoot(myModule, myProjectRoot); - PsiTestUtil.addSourceRoot(myModule, mySourceRoot21); - PsiTestUtil.addSourceRoot(myModule, mySourceRoot1); - PsiTestUtil.addSourceRoot(myModule, mySourceRoot2); - PsiTestUtil.addSourceRoot(myModule, mySourceRoot11); + PsiTestUtil.addContentRoot(myModule, myProjectRoot); + PsiTestUtil.addSourceRoot(myModule, mySourceRoot21); + PsiTestUtil.addSourceRoot(myModule, mySourceRoot1); + PsiTestUtil.addSourceRoot(myModule, mySourceRoot2); + PsiTestUtil.addSourceRoot(myModule, mySourceRoot11); - myFile1 = createChildData(mySourceRoot1, "File1.java"); - myFile2 = createChildData(mySourceRoot2, "File2.java"); - myFile11 = createChildData(mySourceRoot11, "File11.java"); - myFile21 = createChildData(mySourceRoot21, "File21.java"); - } catch (IOException e) { - LOG.error(e); - } - } - } + myFile1 = createChildData(mySourceRoot1, "File1.java"); + myFile2 = createChildData(mySourceRoot2, "File2.java"); + myFile11 = createChildData(mySourceRoot11, "File11.java"); + myFile21 = createChildData(mySourceRoot21, "File21.java"); + } catch (IOException e) { + LOG.error(e); + } + } ); } diff --git a/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java index 0627b13693ff..8c10148da186 100644 --- a/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java @@ -629,11 +629,8 @@ public class SrcRepositoryUseTest extends PsiTestCase{ PsiClass aClass = myJavaFacade.findClass("pack.MyClass2", GlobalSearchScope.allScope(myProject)); assertNotNull(aClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - aClass.getNameIdentifier().replace(myJavaFacade.getElementFactory().createIdentifier("NewName")); - } + ApplicationManager.getApplication().runWriteAction(() -> { + aClass.getNameIdentifier().replace(myJavaFacade.getElementFactory().createIdentifier("NewName")); }); assertEquals("pack.NewName", aClass.getQualifiedName()); @@ -644,11 +641,8 @@ public class SrcRepositoryUseTest extends PsiTestCase{ assertNotNull(aClass); PsiField field = aClass.getFields()[0]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - aClass.getNameIdentifier().replace(myJavaFacade.getElementFactory().createIdentifier("NewName")); - } + ApplicationManager.getApplication().runWriteAction(() -> { + aClass.getNameIdentifier().replace(myJavaFacade.getElementFactory().createIdentifier("NewName")); }); assertTrue(field.isValid()); @@ -656,11 +650,8 @@ public class SrcRepositoryUseTest extends PsiTestCase{ public void testModification2() throws Exception { PsiClass aClass = myJavaFacade.findClass("pack.MyClass2", GlobalSearchScope.allScope(myProject)); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiUtil.setModifierProperty(aClass, PsiModifier.FINAL, true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PsiUtil.setModifierProperty(aClass, PsiModifier.FINAL, true); }); @@ -675,19 +666,13 @@ public class SrcRepositoryUseTest extends PsiTestCase{ BlockSupport blockSupport = ServiceManager.getService(myProject, BlockSupport.class); final PsiFile psiFile = aClass.getContainingFile(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - blockSupport.reparseRange(psiFile, classRange.getStartOffset(), classRange.getEndOffset(), ""); - } + ApplicationManager.getApplication().runWriteAction(() -> { + blockSupport.reparseRange(psiFile, classRange.getStartOffset(), classRange.getEndOffset(), ""); }); LOG.assertTrue(!aClass.isValid()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - blockSupport.reparseRange(psiFile, classRange.getStartOffset(), classRange.getStartOffset(), text); - } + ApplicationManager.getApplication().runWriteAction(() -> { + blockSupport.reparseRange(psiFile, classRange.getStartOffset(), classRange.getStartOffset(), text); }); @@ -748,27 +733,24 @@ public class SrcRepositoryUseTest extends PsiTestCase{ private void replaceSourceRoot(final VirtualFile newSourceRoot) { ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - final ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel(); - final ContentEntry[] content = rootModel.getContentEntries(); - boolean contentToChangeFound = false; - for (ContentEntry contentEntry : content) { - final SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); - for (SourceFolder sourceFolder : sourceFolders) { - contentEntry.removeSourceFolder(sourceFolder); - } - final VirtualFile contentRoot = contentEntry.getFile(); - if (contentRoot != null && VfsUtilCore.isAncestor(contentRoot, newSourceRoot, false)) { - contentEntry.addSourceFolder(newSourceRoot, false); - contentToChangeFound = true; - } - } - assertTrue(contentToChangeFound); - rootModel.commit(); + () -> { + final ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel(); + final ContentEntry[] content = rootModel.getContentEntries(); + boolean contentToChangeFound = false; + for (ContentEntry contentEntry : content) { + final SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); + for (SourceFolder sourceFolder : sourceFolders) { + contentEntry.removeSourceFolder(sourceFolder); + } + final VirtualFile contentRoot = contentEntry.getFile(); + if (contentRoot != null && VfsUtilCore.isAncestor(contentRoot, newSourceRoot, false)) { + contentEntry.addSourceFolder(newSourceRoot, false); + contentToChangeFound = true; } } + assertTrue(contentToChangeFound); + rootModel.commit(); + } ); } @@ -782,11 +764,8 @@ public class SrcRepositoryUseTest extends PsiTestCase{ PsiMethod[] methods = nonAnonClass.getMethods(); assertEquals(1, methods.length); PsiTypeElement newType = myJavaFacade.getElementFactory().createTypeElement(PsiType.FLOAT); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - methods[0].getReturnTypeElement().replace(newType); - } + ApplicationManager.getApplication().runWriteAction(() -> { + methods[0].getReturnTypeElement().replace(newType); }); } diff --git a/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java b/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java index c959ac753f4f..0659375acabb 100644 --- a/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java @@ -1101,11 +1101,8 @@ public class TreeIsCorrectAfterDiffReparseTest extends LightCodeInsightTestCase final PsiDocumentManager docManager = PsiDocumentManager.getInstance(ourProject); final Document doc = docManager.getDocument(myFile); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - doc.insertString(part1.length(), "/**"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + doc.insertString(part1.length(), "/**"); }); diff --git a/java/java-tests/testSrc/com/intellij/psi/TypesTest.java b/java/java-tests/testSrc/com/intellij/psi/TypesTest.java index 1613f6344e08..e21e7450bf8f 100644 --- a/java/java-tests/testSrc/com/intellij/psi/TypesTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/TypesTest.java @@ -38,11 +38,8 @@ public class TypesTest extends GenericsTestCase { final String testPath = PathManagerEx.getTestDataPath().replace(File.separatorChar, '/') + "/psi/types/" + getTestName(true); final VirtualFile[] testRoot = { null }; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - testRoot[0] = LocalFileSystem.getInstance().refreshAndFindFileByPath(testPath); - } + ApplicationManager.getApplication().runWriteAction(() -> { + testRoot[0] = LocalFileSystem.getInstance().refreshAndFindFileByPath(testPath); }); if (testRoot[0] != null) { PsiTestUtil.addSourceRoot(myModule, testRoot[0]); diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java index d5a126627202..fb227eef4e0e 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/AbstractJavaFormatterTest.java @@ -202,28 +202,20 @@ public abstract class AbstractJavaFormatterTest extends LightIdeaTestCase { new TextRange(doc.getLineStartOffset(myLineRange.getStartOffset()), doc.getLineEndOffset(myLineRange.getEndOffset())); } final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject()); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(0, document.getTextLength(), text); - manager.commitDocument(document); - try { - TextRange rangeToUse = myTextRange; - if (rangeToUse == null) { - rangeToUse = file.getTextRange(); - } - ACTIONS.get(action).run(file, rangeToUse.getStartOffset(), rangeToUse.getEndOffset()); - } - catch (IncorrectOperationException e) { - assertTrue(e.getLocalizedMessage(), false); - } - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(0, document.getTextLength(), text); + manager.commitDocument(document); + try { + TextRange rangeToUse = myTextRange; + if (rangeToUse == null) { + rangeToUse = file.getTextRange(); + } + ACTIONS.get(action).run(file, rangeToUse.getStartOffset(), rangeToUse.getEndOffset()); } - }, action == Action.REFORMAT ? ReformatCodeProcessor.COMMAND_NAME : "", ""); + catch (IncorrectOperationException e) { + assertTrue(e.getLocalizedMessage(), false); + } + }), action == Action.REFORMAT ? ReformatCodeProcessor.COMMAND_NAME : "", ""); return document.getText(); } diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/IndentTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/IndentTest.java index f5266d02c9bf..b60a275055d7 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/IndentTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/IndentTest.java @@ -133,22 +133,14 @@ public class IndentTest extends LightIdeaTestCase { private void doTest(String fileNameBefore, String fileNameAfter) throws Exception { String text = loadFile(fileNameBefore); final PsiFile file = createFile(fileNameBefore, text); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - CodeStyleManager.getInstance(getProject()).reformat(file); - } - catch (IncorrectOperationException e) { - assertTrue(false); - } - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + CodeStyleManager.getInstance(getProject()).reformat(file); } - }, null, null); + catch (IncorrectOperationException e) { + assertTrue(false); + } + }), null, null); String textAfter = loadFile(fileNameAfter); diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java index bb907f068e78..0b51b5e0fd22 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java @@ -169,11 +169,8 @@ public class JavaFormatterInEditorTest extends LightPlatformCodeInsightTestCase public void doTest(@NotNull String before, @NotNull String after) throws IOException { configureFromFileText(getTestName(false) + ".java", before); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(getProject()).reformatText(getFile(), 0, getEditor().getDocument().getTextLength()); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + CodeStyleManager.getInstance(getProject()).reformatText(getFile(), 0, getEditor().getDocument().getTextLength()); }); checkResultByText(after); diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java index c48058cdc988..d6f4cb219f07 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java @@ -1203,22 +1203,14 @@ public class JavaFormatterTest extends AbstractJavaFormatterTest { final PsiCodeFragment fragment = factory.createCodeBlockCodeFragment("a=1;int b=2;", null, true); final PsiElement[] result = new PsiElement[1]; - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - try { - result[0] = CodeStyleManager.getInstance(getProject()).reformat(fragment); - } - catch (IncorrectOperationException e) { - fail(e.getLocalizedMessage()); - } - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> WriteCommandAction.runWriteCommandAction(null, () -> { + try { + result[0] = CodeStyleManager.getInstance(getProject()).reformat(fragment); } - }, null, null); + catch (IncorrectOperationException e) { + fail(e.getLocalizedMessage()); + } + }), null, null); assertEquals("a = 1;\n" + "int b = 2;", result[0].getText()); } diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/TabIndentingTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/TabIndentingTest.java index 03ea132fa4ee..3d0f00fb2fb8 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/TabIndentingTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/TabIndentingTest.java @@ -131,22 +131,14 @@ public class TabIndentingTest extends LightIdeaTestCase { private void doTest(String fileNameBefore, String fileNameAfter) throws Exception { String text = loadFile(fileNameBefore); final PsiFile file = createFile(fileNameBefore, text); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - CodeStyleManager.getInstance(getProject()).reformat(file); - } - catch (IncorrectOperationException e) { - assertTrue(false); - } - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + CodeStyleManager.getInstance(getProject()).reformat(file); } - }, null, null); + catch (IncorrectOperationException e) { + assertTrue(false); + } + }), null, null); String textAfter = loadFile(fileNameAfter); diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/ClassFileUnderSourceRootTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/ClassFileUnderSourceRootTest.java index a197d480318b..55182d6c0a38 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/ClassFileUnderSourceRootTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/ClassFileUnderSourceRootTest.java @@ -42,12 +42,9 @@ public class ClassFileUnderSourceRootTest extends IdeaTestCase { FileUtil.writeToFile(new File(dir, "p/A.java"), "package p;\npublic class A { }"); FileUtil.copy(new File(PathManagerEx.getTestDataPath() + "/psi/cls/repo/pack/MyClass.class"), new File(dir, "pack/MyClass.class")); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiTestUtil.addSourceRoot(myModule, root); - ModuleRootModificationUtil.addModuleLibrary(myModule, root.getUrl()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PsiTestUtil.addSourceRoot(myModule, root); + ModuleRootModificationUtil.addModuleLibrary(myModule, root.getUrl()); }); } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/FindClassTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/FindClassTest.java index f1fb852999f3..016c5ab7fa60 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/FindClassTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/FindClassTest.java @@ -57,27 +57,24 @@ public class FindClassTest extends PsiTestCase { super.setUp(); final File root = createTempDirectory(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - try { - VirtualFile rootVFile = - LocalFileSystem.getInstance().refreshAndFindFileByPath(root.getAbsolutePath().replace(File.separatorChar, '/')); + WriteCommandAction.runWriteCommandAction(null, () -> { + try { + VirtualFile rootVFile = + LocalFileSystem.getInstance().refreshAndFindFileByPath(root.getAbsolutePath().replace(File.separatorChar, '/')); - myPrjDir1 = createChildDirectory(rootVFile, "prj1"); - mySrcDir1 = createChildDirectory(myPrjDir1, "src1"); + myPrjDir1 = createChildDirectory(rootVFile, "prj1"); + mySrcDir1 = createChildDirectory(myPrjDir1, "src1"); - myPackDir = createChildDirectory(mySrcDir1, "p"); - VirtualFile file1 = createChildData(myPackDir, "A.java"); - setFileText(file1, "package p; public class A{ public void foo(); }"); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + myPackDir = createChildDirectory(mySrcDir1, "p"); + VirtualFile file1 = createChildData(myPackDir, "A.java"); + setFileText(file1, "package p; public class A{ public void foo(); }"); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - PsiTestUtil.addContentRoot(myModule, myPrjDir1); - PsiTestUtil.addSourceRoot(myModule, mySrcDir1); - } - catch (IOException e) { - LOG.error(e); - } + PsiTestUtil.addContentRoot(myModule, myPrjDir1); + PsiTestUtil.addSourceRoot(myModule, mySrcDir1); + } + catch (IOException e) { + LOG.error(e); } }); } @@ -88,64 +85,58 @@ public class FindClassTest extends PsiTestCase { } public void testClassUnderExcludedFolder() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiTestUtil.addExcludedRoot(myModule, myPackDir); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiTestUtil.addExcludedRoot(myModule, myPackDir); - PsiClass psiClass = myJavaFacade.findClass("p.A", GlobalSearchScope.allScope(myProject)); - assertNull(psiClass); + PsiClass psiClass = myJavaFacade.findClass("p.A", GlobalSearchScope.allScope(myProject)); + assertNull(psiClass); - ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel(); - final ContentEntry content = rootModel.getContentEntries()[0]; - content.removeExcludeFolder(content.getExcludeFolders()[0]); - rootModel.commit(); + ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel(); + final ContentEntry content = rootModel.getContentEntries()[0]; + content.removeExcludeFolder(content.getExcludeFolders()[0]); + rootModel.commit(); - psiClass = myJavaFacade.findClass("p.A", GlobalSearchScope.allScope(myProject)); - assertEquals("p.A", psiClass.getQualifiedName()); - } + psiClass = myJavaFacade.findClass("p.A", GlobalSearchScope.allScope(myProject)); + assertEquals("p.A", psiClass.getQualifiedName()); }); } public void testClassUnderIgnoredFolder() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiClass psiClass = myJavaFacade.findClass("p.A", GlobalSearchScope.allScope(myProject)); - assertEquals("p.A", psiClass.getQualifiedName()); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiClass psiClass = myJavaFacade.findClass("p.A", GlobalSearchScope.allScope(myProject)); + assertEquals("p.A", psiClass.getQualifiedName()); - assertTrue(psiClass.isValid()); + assertTrue(psiClass.isValid()); - FileTypeManager fileTypeManager = FileTypeManager.getInstance(); - String ignoredFilesList = fileTypeManager.getIgnoredFilesList(); - fileTypeManager.setIgnoredFilesList(ignoredFilesList + ";p"); - try { - assertFalse(psiClass.isValid()); - } - finally { - fileTypeManager.setIgnoredFilesList(ignoredFilesList); - } - - psiClass = myJavaFacade.findClass("p.A"); - assertTrue(psiClass.isValid()); + FileTypeManager fileTypeManager = FileTypeManager.getInstance(); + String ignoredFilesList = fileTypeManager.getIgnoredFilesList(); + fileTypeManager.setIgnoredFilesList(ignoredFilesList + ";p"); + try { + assertFalse(psiClass.isValid()); } + finally { + fileTypeManager.setIgnoredFilesList(ignoredFilesList); + } + + psiClass = myJavaFacade.findClass("p.A"); + assertTrue(psiClass.isValid()); }); } public void testSynchronizationAfterChange() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - FileDocumentManager.getInstance().saveAllDocuments(); - PsiClass psiClass = myJavaFacade.findClass("p.A"); - final VirtualFile vFile = psiClass.getContainingFile().getVirtualFile(); - File ioFile = VfsUtil.virtualToIoFile(vFile); - ioFile.setLastModified(5); + ApplicationManager.getApplication().runWriteAction(() -> { + FileDocumentManager.getInstance().saveAllDocuments(); + PsiClass psiClass = myJavaFacade.findClass("p.A"); + final VirtualFile vFile = psiClass.getContainingFile().getVirtualFile(); + File ioFile = VfsUtil.virtualToIoFile(vFile); + ioFile.setLastModified(5); - LocalFileSystem.getInstance().refresh(false); + LocalFileSystem.getInstance().refresh(false); - ModuleRootModificationUtil.setModuleSdk(myModule, null); + ModuleRootModificationUtil.setModuleSdk(myModule, null); - psiClass = myJavaFacade.findClass("p.A"); - assertNotNull(psiClass); - } + psiClass = myJavaFacade.findClass("p.A"); + assertNotNull(psiClass); }); } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/SameSourceRootInTwoModulesTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/SameSourceRootInTwoModulesTest.java index c8e701bc68c2..d2bb0bff9f40 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/SameSourceRootInTwoModulesTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/cache/impl/SameSourceRootInTwoModulesTest.java @@ -42,51 +42,46 @@ public class SameSourceRootInTwoModulesTest extends PsiTestCase { super.setUp(); final File root = createTempDirectory(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - VirtualFile rootVFile = - LocalFileSystem.getInstance().refreshAndFindFileByPath(root.getAbsolutePath().replace(File.separatorChar, '/')); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + VirtualFile rootVFile = + LocalFileSystem.getInstance().refreshAndFindFileByPath(root.getAbsolutePath().replace(File.separatorChar, '/')); - myPrjDir1 = createChildDirectory(rootVFile, "prj1"); - mySrcDir1 = createChildDirectory(myPrjDir1, "src1"); + myPrjDir1 = createChildDirectory(rootVFile, "prj1"); + mySrcDir1 = createChildDirectory(myPrjDir1, "src1"); - myPackDir = createChildDirectory(mySrcDir1, "p"); - VirtualFile file1 = createChildData(myPackDir, "A.java"); - setFileText(file1, "package p; public class A{ public void foo(); }"); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + myPackDir = createChildDirectory(mySrcDir1, "p"); + VirtualFile file1 = createChildData(myPackDir, "A.java"); + setFileText(file1, "package p; public class A{ public void foo(); }"); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - PsiTestUtil.addContentRoot(myModule, myPrjDir1); - PsiTestUtil.addSourceRoot(myModule, mySrcDir1); - } - catch (IOException e) { - LOG.error(e); - } + PsiTestUtil.addContentRoot(myModule, myPrjDir1); + PsiTestUtil.addSourceRoot(myModule, mySrcDir1); + } + catch (IOException e) { + LOG.error(e); } }); } public void testBug() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiClass psiClass = myJavaFacade.findClass("p.A"); - assertEquals("p.A", psiClass.getQualifiedName()); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiClass psiClass = myJavaFacade.findClass("p.A"); + assertEquals("p.A", psiClass.getQualifiedName()); - final PsiFile psiFile = myPsiManager.findFile(myPackDir.findChild("A.java")); - psiFile.getChildren(); - assertEquals(psiFile, psiClass.getContainingFile()); + final PsiFile psiFile = myPsiManager.findFile(myPackDir.findChild("A.java")); + psiFile.getChildren(); + assertEquals(psiFile, psiClass.getContainingFile()); - VirtualFile file = psiFile.getVirtualFile(); - assertEquals(myModule, ModuleUtil.findModuleForFile(file, myProject)); + VirtualFile file = psiFile.getVirtualFile(); + assertEquals(myModule, ModuleUtil.findModuleForFile(file, myProject)); - Module anotherModule = createModule("another"); - myFilesToDelete.add(new File(anotherModule.getModuleFilePath())); + Module anotherModule = createModule("another"); + myFilesToDelete.add(new File(anotherModule.getModuleFilePath())); - PsiTestUtil.addSourceRoot(anotherModule, mySrcDir1); + PsiTestUtil.addSourceRoot(anotherModule, mySrcDir1); - assertEquals(anotherModule, ModuleUtil.findModuleForFile(file, myProject)); - } + assertEquals(anotherModule, ModuleUtil.findModuleForFile(file, myProject)); }); } } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java index 6b9455940da9..0812eb4cc76f 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java @@ -59,30 +59,27 @@ public class PsiEventsTest extends PsiTestCase { root.mkdir(); myFilesToDelete.add(root); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - VirtualFile rootVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(root); + ApplicationManager.getApplication().runWriteAction(() -> { + VirtualFile rootVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(root); - myPrjDir1 = createChildDirectory(rootVFile, "prj1"); - mySrcDir1 = createChildDirectory(myPrjDir1, "src1"); - mySrcDir2 = createChildDirectory(myPrjDir1, "src2"); + myPrjDir1 = createChildDirectory(rootVFile, "prj1"); + mySrcDir1 = createChildDirectory(myPrjDir1, "src1"); + mySrcDir2 = createChildDirectory(myPrjDir1, "src2"); - myPrjDir2 = createChildDirectory(rootVFile, "prj2"); - mySrcDir3 = myPrjDir2; + myPrjDir2 = createChildDirectory(rootVFile, "prj2"); + mySrcDir3 = myPrjDir2; - myClsDir1 = createChildDirectory(myPrjDir1, "cls1"); + myClsDir1 = createChildDirectory(myPrjDir1, "cls1"); - myIgnoredDir = createChildDirectory(mySrcDir1, "CVS"); + myIgnoredDir = createChildDirectory(mySrcDir1, "CVS"); - PsiTestUtil.addContentRoot(myModule, myPrjDir1); - PsiTestUtil.addSourceRoot(myModule, mySrcDir1); - PsiTestUtil.addSourceRoot(myModule, mySrcDir2); - PsiTestUtil.addContentRoot(myModule, myPrjDir2); - ModuleRootModificationUtil.addModuleLibrary(myModule, myClsDir1.getUrl()); - PsiTestUtil.addSourceRoot(myModule, mySrcDir3); - } + PsiTestUtil.addContentRoot(myModule, myPrjDir1); + PsiTestUtil.addSourceRoot(myModule, mySrcDir1); + PsiTestUtil.addSourceRoot(myModule, mySrcDir2); + PsiTestUtil.addContentRoot(myModule, myPrjDir2); + ModuleRootModificationUtil.addModuleLibrary(myModule, myClsDir1.getUrl()); + PsiTestUtil.addSourceRoot(myModule, mySrcDir3); }); } @@ -181,12 +178,7 @@ public class PsiEventsTest extends PsiTestCase { if (((FileManagerImpl)fileManager).getCachedDirectory(myPrjDir1) != null) { - Processor isReallyLeak = new Processor() { - @Override - public boolean process(PsiDirectory directory) { - return directory.getVirtualFile().equals(myPrjDir1); - } - }; + Processor isReallyLeak = directory -> directory.getVirtualFile().equals(myPrjDir1); LeakHunter.checkLeak(LeakHunter.allRoots(), PsiDirectory.class, isReallyLeak); String dumpPath = FileUtil.createTempFile( @@ -563,12 +555,9 @@ public class PsiEventsTest extends PsiTestCase { EventsTestListener listener = new EventsTestListener(); myPsiManager.addPsiTreeChangeListener(listener,getTestRootDisposable()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ((FileTypeManagerEx)FileTypeManager.getInstance()).fireBeforeFileTypesChanged(); - ((FileTypeManagerEx)FileTypeManager.getInstance()).fireFileTypesChanged(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ((FileTypeManagerEx)FileTypeManager.getInstance()).fireBeforeFileTypesChanged(); + ((FileTypeManagerEx)FileTypeManager.getInstance()).fireFileTypesChanged(); }); @@ -707,20 +696,14 @@ public class PsiEventsTest extends PsiTestCase { this.newText = newText; original = getFile().getText(); Document document = PsiDocumentManager.getInstance(getProject()).getDocument(getFile()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.setText(newText); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.setText(newText); }); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.setText(original); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.setText(original); }); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); @@ -804,11 +787,8 @@ public class PsiEventsTest extends PsiTestCase { Document document = documentManager.getDocument(getFile()); assertTrue(documentManager.isCommitted(document)); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.setText(""); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.setText(""); }); documentManager.commitAllDocuments(); diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/TempFileSystemTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/TempFileSystemTest.java index 7b3780a8cd16..35fa956d2fad 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/TempFileSystemTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/TempFileSystemTest.java @@ -45,11 +45,8 @@ public class TempFileSystemTest extends LightPlatformCodeInsightFixtureTestCase }); PlatformTestCase.move(psiFile.getVirtualFile(), subdirectory.getVirtualFile()); assertTrue(psiFile.isValid()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - psiFile.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + psiFile.delete(); }); assertFalse(psiFile.isValid()); diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java index 65df10d061ab..feaca3d2afa9 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/smartPointers/SmartPsiElementPointersTest.java @@ -96,11 +96,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { } private static void insertString(Document document, int offset, String s) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.insertString(offset, s); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.insertString(offset, s); }); } @@ -166,26 +163,23 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { } public void testRetrieveOnUncommittedDocument() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiClass aClass = myJavaFacade.findClass("AClass", GlobalSearchScope.allScope(getProject())); - assertNotNull(aClass); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiClass aClass = myJavaFacade.findClass("AClass", GlobalSearchScope.allScope(getProject())); + assertNotNull(aClass); - PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); - Document document = documentManager.getDocument(aClass.getContainingFile()); - document.insertString(0, "/******/"); + PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); + Document document = documentManager.getDocument(aClass.getContainingFile()); + document.insertString(0, "/******/"); - SmartPointerEx pointer = (SmartPointerEx)createPointer(aClass.getNameIdentifier()); + SmartPointerEx pointer = (SmartPointerEx)createPointer(aClass.getNameIdentifier()); - document.insertString(0, "/**/"); - documentManager.commitAllDocuments(); + document.insertString(0, "/**/"); + documentManager.commitAllDocuments(); - PsiElement element = pointer.getElement(); - assertNotNull(element); - assertTrue(element.getParent() instanceof PsiClass); - assertTrue(element.isValid()); - } + PsiElement element = pointer.getElement(); + assertNotNull(element); + assertTrue(element.getParent() instanceof PsiClass); + assertTrue(element.isValid()); }); } @@ -217,11 +211,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { assertEquals(myFile.getFirstChild(), pointer.getElement()); Document document = myFile.getViewProvider().getDocument(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.deleteString(0, document.getTextLength()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.deleteString(0, document.getTextLength()); }); @@ -258,11 +249,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { createPointer(aClass.getNameIdentifier()); final PsiComment javadoc = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory().createCommentFromText("/** javadoc */", aClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - aClass.getParent().addBefore(javadoc, aClass); - } + ApplicationManager.getApplication().runWriteAction(() -> { + aClass.getParent().addBefore(javadoc, aClass); }); @@ -558,11 +546,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { } assertNull(FileDocumentManager.getInstance().getCachedDocument(vfile)); assertEquals(pointer1.getRange(), range1); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - insertString(FileDocumentManager.getInstance().getDocument(vfile), 0, " "); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + insertString(FileDocumentManager.getInstance().getDocument(vfile), 0, " "); }); assertEquals(range1.shiftRight(1), pointer1.getRange()); assertEquals(range2.shiftRight(1), pointer2.getRange()); @@ -643,11 +628,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { PsiClass aClass = ((PsiJavaFile)file).getClasses()[0]; - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - insertString(getEditor().getDocument(), 0, "import java.util.Map;\n"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + insertString(getEditor().getDocument(), 0, "import java.util.Map;\n"); }); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); @@ -700,18 +682,15 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { final Document document = file.getViewProvider().getDocument(); assertNotNull(document); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PlatformTestUtil.startPerformanceTest("smart pointer range update", 10000, () -> { - document.setText(StringUtil.repeat("foo foo \n", 50000)); - for (int i = 0; i < 10000; i++) { - document.insertString(i * 20 + 100, "x\n"); - assertFalse(PsiDocumentManager.getInstance(myProject).isCommitted(document)); - assertEquals(range, pointer.getRange()); - } - }).cpuBound().useLegacyScaling().assertTiming(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PlatformTestUtil.startPerformanceTest("smart pointer range update", 10000, () -> { + document.setText(StringUtil.repeat("foo foo \n", 50000)); + for (int i = 0; i < 10000; i++) { + document.insertString(i * 20 + 100, "x\n"); + assertFalse(PsiDocumentManager.getInstance(myProject).isCommitted(document)); + assertEquals(range, pointer.getRange()); + } + }).cpuBound().useLegacyScaling().assertTiming(); }); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); @@ -726,12 +705,9 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { SmartPsiFileRange range1 = getPointerManager().createSmartPsiFileRangePointer(myFile, TextRange.create(0, 2)); SmartPsiFileRange range2 = getPointerManager().createSmartPsiFileRangePointer(myFile, TextRange.create(1, 3)); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.deleteString(0, 1); - document.deleteString(1, 2); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.deleteString(0, 1); + document.deleteString(1, 2); }); assertEquals(TextRange.create(0, 1), range1.getRange()); @@ -766,11 +742,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { assertNull(((SmartPointerEx) pointer2).getCachedElement()); TextRange range = file.getClasses()[1].getTextRange(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.moveText(range.getStartOffset(), range.getEndOffset(), 0); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.moveText(range.getStartOffset(), range.getEndOffset(), 0); }); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); @@ -799,12 +772,9 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { TextRange originalRange = method.getTextRange(); SmartPsiElementPointer pointer = createPointer(method); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - EditorModificationUtil.insertStringAtCaret(myEditor, " void m() {\n" + - " }\n"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + EditorModificationUtil.insertStringAtCaret(myEditor, " void m() {\n" + + " }\n"); }); PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); @@ -822,11 +792,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { PlatformTestUtil.tryGcSoftlyReachableObjects(); assertNull(((SmartPointerEx) pointer).getCachedElement()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - file.getClasses()[1].delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + file.getClasses()[1].delete(); }); @@ -875,11 +842,8 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { ref = PsiTreeUtil.findElementOfClassAtOffset(file, file.getText().indexOf("Bar"), PsiJavaCodeReferenceElement.class, false); final PsiJavaCodeReferenceElement finalRef = ref; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - finalRef.handleElementRename("BarImpl"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + finalRef.handleElementRename("BarImpl"); }); assertNotNull(pointer.getElement()); @@ -911,23 +875,20 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase { List tags = ContainerUtil.newArrayList(PsiTreeUtil.findChildrenOfType(file.getDocument(), XmlTag.class)); List pointers = tags.stream().map(this::createPointer).collect(Collectors.toList()); Random random = new Random(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PlatformTestUtil.startPerformanceTest("smart pointer range update after PSI change", 21000, () -> { - for (int i = 0; i < tags.size(); i++) { - XmlTag tag = tags.get(i); - SmartPsiElementPointer pointer = pointers.get(i); - assertEquals(tag.getName().length(), TextRange.create(pointer.getRange()).getLength()); - assertEquals(tag.getName().length(), TextRange.create(pointer.getPsiRange()).getLength()); + ApplicationManager.getApplication().runWriteAction(() -> { + PlatformTestUtil.startPerformanceTest("smart pointer range update after PSI change", 21000, () -> { + for (int i = 0; i < tags.size(); i++) { + XmlTag tag = tags.get(i); + SmartPsiElementPointer pointer = pointers.get(i); + assertEquals(tag.getName().length(), TextRange.create(pointer.getRange()).getLength()); + assertEquals(tag.getName().length(), TextRange.create(pointer.getPsiRange()).getLength()); - tag.setName("bar" + random.nextInt(20)); - assertEquals(tag.getName().length(), TextRange.create(pointer.getRange()).getLength()); - assertEquals(tag.getName().length(), TextRange.create(pointer.getPsiRange()).getLength()); - } - PostprocessReformattingAspect.getInstance(myProject).doPostponedFormatting(); - }).cpuBound().useLegacyScaling().assertTiming(); - } + tag.setName("bar" + random.nextInt(20)); + assertEquals(tag.getName().length(), TextRange.create(pointer.getRange()).getLength()); + assertEquals(tag.getName().length(), TextRange.create(pointer.getPsiRange()).getLength()); + } + PostprocessReformattingAspect.getInstance(myProject).doPostponedFormatting(); + }).cpuBound().useLegacyScaling().assertTiming(); }); } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/BindToElementTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/BindToElementTest.java index 73e0e9828ae2..4e1a5271500b 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/BindToElementTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/BindToElementTest.java @@ -54,50 +54,38 @@ public class BindToElementTest extends CodeInsightTestCase { } public void testSingleClassImport() throws Exception { - doTest(new Runnable() { - @Override - public void run() { - PsiElement element = myFile.findElementAt(myEditor.getCaretModel().getOffset()); - final PsiJavaCodeReferenceElement referenceElement = PsiTreeUtil.getParentOfType(element, PsiJavaCodeReferenceElement.class); - final PsiClass aClassA = JavaPsiFacade.getInstance(myProject).findClass("p2.A", GlobalSearchScope.moduleScope(myModule)); - assertNotNull(aClassA); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - referenceElement.bindToElement(aClassA); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); - } + doTest(() -> { + PsiElement element = myFile.findElementAt(myEditor.getCaretModel().getOffset()); + final PsiJavaCodeReferenceElement referenceElement = PsiTreeUtil.getParentOfType(element, PsiJavaCodeReferenceElement.class); + final PsiClass aClassA = JavaPsiFacade.getInstance(myProject).findClass("p2.A", GlobalSearchScope.moduleScope(myModule)); + assertNotNull(aClassA); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + referenceElement.bindToElement(aClassA); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }); }); } public void testReplacingType() throws Exception { - doTest(new Runnable() { - @Override - public void run() { - final PsiElement elementAt = myFile.findElementAt(myEditor.getCaretModel().getOffset()); - final PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(elementAt, PsiTypeElement.class); - final PsiClass aClassA = JavaPsiFacade.getInstance(myProject).findClass("p2.A", GlobalSearchScope.moduleScope(myModule)); - assertNotNull(aClassA); - final PsiElementFactory factory = myJavaFacade.getElementFactory(); - final PsiClassType type = factory.createType(aClassA); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - typeElement.replace(factory.createTypeElement(type)); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); - } + doTest(() -> { + final PsiElement elementAt = myFile.findElementAt(myEditor.getCaretModel().getOffset()); + final PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(elementAt, PsiTypeElement.class); + final PsiClass aClassA = JavaPsiFacade.getInstance(myProject).findClass("p2.A", GlobalSearchScope.moduleScope(myModule)); + assertNotNull(aClassA); + final PsiElementFactory factory = myJavaFacade.getElementFactory(); + final PsiClassType type = factory.createType(aClassA); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + typeElement.replace(factory.createTypeElement(type)); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }); }); } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java index 275da0cfea86..01e599e40fb1 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java @@ -26,11 +26,8 @@ import com.intellij.testFramework.LightCodeInsightTestCase; public class ExtendsBoundListTest extends LightCodeInsightTestCase { public void testRemoveBoundFromFront() throws Exception { final PsiTypeParameter typeParameter = getTypeParameter(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - typeParameter.getExtendsList().getReferenceElements()[0].delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + typeParameter.getExtendsList().getReferenceElements()[0].delete(); }); check(); @@ -38,11 +35,8 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { public void testRemoveBoundFromEnd() throws Exception { final PsiTypeParameter typeParameter = getTypeParameter(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - typeParameter.getExtendsList().getReferenceElements()[1].delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + typeParameter.getExtendsList().getReferenceElements()[1].delete(); }); check(); @@ -50,11 +44,8 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { public void testRemoveBoundFromMiddle() throws Exception { final PsiTypeParameter typeParameter = getTypeParameter(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - typeParameter.getExtendsList().getReferenceElements()[1].delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + typeParameter.getExtendsList().getReferenceElements()[1].delete(); }); check(); @@ -66,11 +57,8 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass("java.lang.Cloneable"); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - extendsList.addAfter(reference, extendsList.getReferenceElements()[0]); - } + ApplicationManager.getApplication().runWriteAction(() -> { + extendsList.addAfter(reference, extendsList.getReferenceElements()[0]); }); check(); @@ -82,11 +70,8 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass("java.lang.Cloneable"); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - extendsList.addBefore(reference, extendsList.getReferenceElements()[0]); - } + ApplicationManager.getApplication().runWriteAction(() -> { + extendsList.addBefore(reference, extendsList.getReferenceElements()[0]); }); check(); @@ -98,11 +83,8 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass("java.lang.Cloneable"); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - extendsList.addBefore(reference, null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + extendsList.addBefore(reference, null); }); check(); @@ -114,11 +96,8 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass(CommonClassNames.JAVA_LANG_RUNNABLE); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - extendsList.add(reference); - } + ApplicationManager.getApplication().runWriteAction(() -> { + extendsList.add(reference); }); check(); diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/JavadocParamTagsTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/JavadocParamTagsTest.java index 3c637f871482..0d33e7529c3f 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/JavadocParamTagsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/JavadocParamTagsTest.java @@ -41,11 +41,8 @@ public class JavadocParamTagsTest extends LightIdeaTestCase { final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - tags[0].delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tags[0].delete(); }); assertEquals("/**\n" + @@ -67,11 +64,8 @@ public class JavadocParamTagsTest extends LightIdeaTestCase { final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tags[1].delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tags[1].delete(); }); assertEquals("/**\n" + @@ -94,11 +88,8 @@ public class JavadocParamTagsTest extends LightIdeaTestCase { final PsiDocComment docComment = method.getDocComment(); assertNotNull(docComment); final PsiDocTag[] tags = docComment.getTags(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tags[1].delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tags[1].delete(); }); assertEquals("/**\n" + @@ -157,42 +148,34 @@ public class JavadocParamTagsTest extends LightIdeaTestCase { } public void testAddTag3() throws Exception { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable(){ - @Override - public void run() { - final PsiElementFactory factory = getFactory(); - final PsiJavaFile psiFile; - try { - psiFile = (PsiJavaFile)createFile("aaa.java", "class A {/**\n" + - " * Javadoc\n" + - " * @param p1\n" + - " * @param p3\n" + - " */\n" + - "void m();}"); - final PsiClass psiClass = psiFile.getClasses()[0]; - final PsiMethod method = psiClass.getMethods()[0]; - PsiDocComment docComment = method.getDocComment(); - assertNotNull(docComment); - final PsiDocTag[] tags = docComment.getTags(); - final PsiDocTag tag2 = factory.createParamTag("p2", ""); - docComment.addAfter(tag2, tags[0]); - docComment = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(docComment); - assertEquals( - "/**\n" + - " * Javadoc\n" + - " * @param p1\n" + - " * @param p2\n" + - " * @param p3\n" + - " */", docComment.getText()); - } - catch (IncorrectOperationException e) {} - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + final PsiElementFactory factory = getFactory(); + final PsiJavaFile psiFile; + try { + psiFile = (PsiJavaFile)createFile("aaa.java", "class A {/**\n" + + " * Javadoc\n" + + " * @param p1\n" + + " * @param p3\n" + + " */\n" + + "void m();}"); + final PsiClass psiClass = psiFile.getClasses()[0]; + final PsiMethod method = psiClass.getMethods()[0]; + PsiDocComment docComment = method.getDocComment(); + assertNotNull(docComment); + final PsiDocTag[] tags = docComment.getTags(); + final PsiDocTag tag2 = factory.createParamTag("p2", ""); + docComment.addAfter(tag2, tags[0]); + docComment = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(docComment); + assertEquals( + "/**\n" + + " * Javadoc\n" + + " * @param p1\n" + + " * @param p2\n" + + " * @param p3\n" + + " */", docComment.getText()); } - }, "", null); + catch (IncorrectOperationException e) {} + }), "", null); } public void testAddTag4() throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ReferenceParameterListTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ReferenceParameterListTest.java index 964474a521b3..2b6e7704cc1b 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ReferenceParameterListTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ReferenceParameterListTest.java @@ -56,15 +56,12 @@ public class ReferenceParameterListTest extends PsiTestCase { null); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - try { - classFromText.setName("Q"); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + try { + classFromText.setName("Q"); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); final PsiClass classX = classFromText.getInnerClasses()[3]; diff --git a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveClassTest.java b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveClassTest.java index 8a7bcb1d0e29..7cbc01bc9d8e 100644 --- a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveClassTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveClassTest.java @@ -242,22 +242,19 @@ public class ResolveClassTest extends ResolveTestCase { @SuppressWarnings({"ConstantConditions"}) private void configureDependency() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ModifiableModuleModel modifiableModel = ModuleManager.getInstance(getProject()).getModifiableModel(); - Module module = modifiableModel.newModule("a.iml", StdModuleTypes.JAVA.getId()); - modifiableModel.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + ModifiableModuleModel modifiableModel = ModuleManager.getInstance(getProject()).getModifiableModel(); + Module module = modifiableModel.newModule("a.iml", StdModuleTypes.JAVA.getId()); + modifiableModel.commit(); - VirtualFile root = LocalFileSystem.getInstance().refreshAndFindFileByPath(getTestDataPath() + "/class/dependentModule"); - assert root != null; + VirtualFile root = LocalFileSystem.getInstance().refreshAndFindFileByPath(getTestDataPath() + "/class/dependentModule"); + assert root != null; - PsiTestUtil.addContentRoot(module, root); - PsiTestUtil.addSourceRoot(module, root.findChild("src")); - PsiTestUtil.addSourceRoot(module, root.findChild("test"), true); + PsiTestUtil.addContentRoot(module, root); + PsiTestUtil.addSourceRoot(module, root.findChild("src")); + PsiTestUtil.addSourceRoot(module, root.findChild("test"), true); - ModuleRootModificationUtil.addDependency(getModule(), module); - } + ModuleRootModificationUtil.addDependency(getModule(), module); }); } diff --git a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolvePerformanceTest.java b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolvePerformanceTest.java index aba8c4dc4183..ef7b9e756670 100644 --- a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolvePerformanceTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolvePerformanceTest.java @@ -63,10 +63,8 @@ public class ResolvePerformanceTest extends ResolveTestCase { resolveAllReferences(references); System.out.println("Not cached resolve: " + (System.currentTimeMillis() - time)/(double)1000 + "s"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ResolveCache.getInstance(myProject).clearCache(true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ResolveCache.getInstance(myProject).clearCache(true); }); time = System.currentTimeMillis(); diff --git a/java/java-tests/testSrc/com/intellij/psi/search/FindUsagesTest.java b/java/java-tests/testSrc/com/intellij/psi/search/FindUsagesTest.java index 4928562f5356..01e32a57eab1 100644 --- a/java/java-tests/testSrc/com/intellij/psi/search/FindUsagesTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/search/FindUsagesTest.java @@ -154,18 +154,15 @@ public class FindUsagesTest extends PsiTestCase{ PsiClass bar = myJavaFacade.findClass("com.Foo.Bar", scope); final int[] count = {0}; - Processor processor = new Processor() { - @Override - public boolean process(UsageInfo usageInfo) { - int navigationOffset = usageInfo.getNavigationOffset(); - assertTrue(navigationOffset > 0); - String textAfter = usageInfo.getFile().getText().substring(navigationOffset); - assertTrue(textAfter, textAfter.startsWith("Foo") || textAfter.startsWith("Bar") || - textAfter.startsWith("com.Foo.Bar") // sorry, can't get references with dollar-dot mismatch to work now - ); - count[0]++; - return true; - } + Processor processor = usageInfo -> { + int navigationOffset = usageInfo.getNavigationOffset(); + assertTrue(navigationOffset > 0); + String textAfter = usageInfo.getFile().getText().substring(navigationOffset); + assertTrue(textAfter, textAfter.startsWith("Foo") || textAfter.startsWith("Bar") || + textAfter.startsWith("com.Foo.Bar") // sorry, can't get references with dollar-dot mismatch to work now + ); + count[0]++; + return true; }; JavaFindUsagesHandler handler = new JavaFindUsagesHandler(bar, JavaFindUsagesHandlerFactory.getInstance(getProject())); diff --git a/java/java-tests/testSrc/com/intellij/psi/search/UpdateCacheTest.java b/java/java-tests/testSrc/com/intellij/psi/search/UpdateCacheTest.java index 48b05f31cdb3..602d42e50bcb 100644 --- a/java/java-tests/testSrc/com/intellij/psi/search/UpdateCacheTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/search/UpdateCacheTest.java @@ -365,12 +365,7 @@ public class UpdateCacheTest extends PsiTestCase { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - PsiSearchHelper.SERVICE.getInstance(myProject).processAllFilesWithWord("aaa", GlobalSearchScope.allScope(myProject), new Processor() { - @Override - public boolean process(final PsiFile psiFile) { - return true; - } - }, true); // to initialize caches + PsiSearchHelper.SERVICE.getInstance(myProject).processAllFilesWithWord("aaa", GlobalSearchScope.allScope(myProject), psiFile -> true, true); // to initialize caches /* rootManager.startChange(); @@ -423,12 +418,7 @@ public class UpdateCacheTest extends PsiTestCase { assertEquals(expectedFiles.length, files.size()); - Collections.sort(files, new Comparator() { - @Override - public int compare(PsiFile file1, PsiFile file2) { - return file1.getName().compareTo(file2.getName()); - } - }); + Collections.sort(files, (file1, file2) -> file1.getName().compareTo(file2.getName())); Arrays.sort(expectedFiles); for(int i = 0; i < expectedFiles.length; i++){ @@ -445,12 +435,7 @@ public class UpdateCacheTest extends PsiTestCase { assertEquals(expectedFiles.length, files.length); - Arrays.sort(files, new Comparator() { - @Override - public int compare(PsiFile file1, PsiFile file2) { - return file1.getName().compareTo(file2.getName()); - } - }); + Arrays.sort(files, (file1, file2) -> file1.getName().compareTo(file2.getName())); Arrays.sort(expectedFiles); for(int i = 0; i < expectedFiles.length; i++){ diff --git a/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java index 8b2aa98a9b4a..77a63b76191d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/CopyClassTest.java @@ -119,21 +119,15 @@ public class CopyClassTest extends CodeInsightTestCase { } final VirtualFile targetVDir = rootDir.findChild("p2"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CopyClassesHandler.doCopyClasses(map, null, myPsiManager.findDirectory(targetVDir), myProject); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CopyClassesHandler.doCopyClasses(map, null, myPsiManager.findDirectory(targetVDir), myProject); }); String rootAfter = root + "/after"; VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/')); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); }); PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java index eb8a1492e366..f76572a58c83 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java @@ -962,11 +962,8 @@ public class ExtractMethodTest extends LightCodeInsightTestCase { for (final Match match : duplicates) { if (!match.getMatchStart().isValid() || !match.getMatchEnd().isValid()) continue; PsiDocumentManager.getInstance(project).commitAllDocuments(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - processor.processMatch(match); - } + ApplicationManager.getApplication().runWriteAction(() -> { + processor.processMatch(match); }); } } diff --git a/java/java-tests/testSrc/com/intellij/roots/MultiModuleEditingTest.java b/java/java-tests/testSrc/com/intellij/roots/MultiModuleEditingTest.java index 6d7205e93613..5540a82eb475 100644 --- a/java/java-tests/testSrc/com/intellij/roots/MultiModuleEditingTest.java +++ b/java/java-tests/testSrc/com/intellij/roots/MultiModuleEditingTest.java @@ -170,11 +170,8 @@ public class MultiModuleEditingTest extends ModuleTestCase { assertSame(moduleA, moduleManager.findModuleByName("a")); assertEquals("c", moduleModel.getNewName(moduleA)); assertSame(moduleA, moduleModel.getModuleToBeRenamed("c")); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - moduleModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + moduleModel.commit(); }); } diff --git a/java/java-tests/testSrc/com/intellij/roots/libraries/LibraryTest.java b/java/java-tests/testSrc/com/intellij/roots/libraries/LibraryTest.java index a201aa06bbc2..bfd33325bedc 100644 --- a/java/java-tests/testSrc/com/intellij/roots/libraries/LibraryTest.java +++ b/java/java-tests/testSrc/com/intellij/roots/libraries/LibraryTest.java @@ -112,11 +112,8 @@ public class LibraryTest extends ModuleRootManagerTestCase { } private static void commit(LibraryTable.ModifiableModel model) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + model.commit(); }); } diff --git a/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java b/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java index 674fe342fbcf..8a485e5a93b2 100644 --- a/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java +++ b/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java @@ -143,12 +143,7 @@ public abstract class JspSpiUtil { public static List buildUrls(@Nullable final VirtualFile virtualFile, @Nullable final Module module, boolean includeModuleOutput) { final List urls = new ArrayList(); - processClassPathItems(virtualFile, module, new Consumer() { - @Override - public void consume(final VirtualFile file) { - addUrl(urls, file); - } - }, includeModuleOutput); + processClassPathItems(virtualFile, module, file -> addUrl(urls, file), includeModuleOutput); return urls; } diff --git a/java/openapi/src/com/intellij/codeInsight/NullableNotNullDialog.java b/java/openapi/src/com/intellij/codeInsight/NullableNotNullDialog.java index cda46d106333..cbdb0f160752 100644 --- a/java/openapi/src/com/intellij/codeInsight/NullableNotNullDialog.java +++ b/java/openapi/src/com/intellij/codeInsight/NullableNotNullDialog.java @@ -162,12 +162,7 @@ public class NullableNotNullDialog extends DialogWrapper { if (e.getValueIsAdjusting()) return; final String selectedValue = (String)myList.getSelectedValue(); if (myDefaultAnnotations.contains(selectedValue)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - removeButton.setEnabled(false); - } - }); + SwingUtilities.invokeLater(() -> removeButton.setEnabled(false)); } } }); diff --git a/java/openapi/src/com/intellij/util/xml/converters/AbstractMethodResolveConverter.java b/java/openapi/src/com/intellij/util/xml/converters/AbstractMethodResolveConverter.java index b302858af972..9d2e7202e3c3 100644 --- a/java/openapi/src/com/intellij/util/xml/converters/AbstractMethodResolveConverter.java +++ b/java/openapi/src/com/intellij/util/xml/converters/AbstractMethodResolveConverter.java @@ -84,19 +84,13 @@ public abstract class AbstractMethodResolveConverter result = new Ref(Boolean.FALSE); - processMethods(context, new Processor() { - public boolean process(final PsiMethod method) { - if (method.equals(element)) { - result.set(Boolean.TRUE); - return false; - } - return true; + processMethods(context, method -> { + if (method.equals(element)) { + result.set(Boolean.TRUE); + return false; } - }, new Function() { - public PsiMethod[] fun(final PsiClass s) { - return s.findMethodsByName(stringValue, true); - } - }); + return true; + }, s -> s.findMethodsByName(stringValue, true)); return result.get(); } @@ -118,15 +112,13 @@ public abstract class AbstractMethodResolveConverter getVariants(final ConvertContext context) { Set methodList = new LinkedHashSet(); Processor processor = CommonProcessors.notNullProcessor(Processors.cancelableCollectProcessor(methodList)); - processMethods(context, processor, new Function() { - public PsiMethod[] fun(final PsiClass s) { - final List list = ContainerUtil.findAll(getVariants(s), new Condition() { - public boolean value(final PsiMethod object) { - return acceptMethod(object, context); - } - }); - return list.toArray(new PsiMethod[list.size()]); - } + processMethods(context, processor, s -> { + final List list = ContainerUtil.findAll(getVariants(s), new Condition() { + public boolean value(final PsiMethod object) { + return acceptMethod(object, context); + } + }); + return list.toArray(new PsiMethod[list.size()]); }); return methodList; } @@ -152,22 +144,16 @@ public abstract class AbstractMethodResolveConverter processor = new CommonProcessors.FindFirstProcessor(); - processMethods(context, processor, new Function() { - public PsiMethod[] fun(final PsiClass s) { - final PsiMethod method = findMethod(s, methodName, getMethodParams(getParent(context))); - if (method != null && acceptMethod(method, context)) { - return new PsiMethod[]{method}; - } - return PsiMethod.EMPTY_ARRAY; + processMethods(context, processor, s -> { + final PsiMethod method = findMethod(s, methodName, getMethodParams(getParent(context))); + if (method != null && acceptMethod(method, context)) { + return new PsiMethod[]{method}; } + return PsiMethod.EMPTY_ARRAY; }); if (processor.isFound()) return processor.getFoundValue(); - processMethods(context, processor, new Function() { - public PsiMethod[] fun(final PsiClass s) { - return s.findMethodsByName(methodName, true); - } - }); + processMethods(context, processor, s -> s.findMethodsByName(methodName, true)); return processor.getFoundValue(); } diff --git a/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudModuleWizardStep.java b/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudModuleWizardStep.java index 79b307b0658e..cd195a8514ca 100644 --- a/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudModuleWizardStep.java +++ b/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudModuleWizardStep.java @@ -60,13 +60,7 @@ public class CloudModuleWizardStep extends ModuleWizardStep { myAccountSelectionPanel = new CloudAccountSelectionEditor(cloudTypes); myAccountPanelPlaceHolder.add(myAccountSelectionPanel.getMainPanel()); - myAccountSelectionPanel.setAccountSelectionListener(new Runnable() { - - @Override - public void run() { - onAccountSelectionChanged(); - } - }); + myAccountSelectionPanel.setAccountSelectionListener(() -> onAccountSelectionChanged()); onAccountSelectionChanged(); } diff --git a/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudSourceApplicationConfigurable.java b/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudSourceApplicationConfigurable.java index b6e0dfc857b0..6532c3393c9d 100644 --- a/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudSourceApplicationConfigurable.java +++ b/java/remote-servers/impl/src/com/intellij/remoteServer/impl/module/CloudSourceApplicationConfigurable.java @@ -104,21 +104,14 @@ public abstract class CloudSourceApplicationConfigurable< @Override public void connected(@NotNull ServerRuntimeInstance serverRuntimeInstance) { - connection.computeDeployments(new Runnable() { - - @Override - public void run() { - result.set(connection.getDeployments()); - semaphore.up(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (!Disposer.isDisposed(myParentDisposable)) { - setupExistingApplications(result.get()); - } - } - }); - } + connection.computeDeployments(() -> { + result.set(connection.getDeployments()); + semaphore.up(); + UIUtil.invokeLaterIfNeeded(() -> { + if (!Disposer.isDisposed(myParentDisposable)) { + setupExistingApplications(result.get()); + } + }); }); } diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java index 871724bf9f3a..cc8d82bfa717 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/compiler/JavaCompilingVisitor.java @@ -522,12 +522,9 @@ public class JavaCompilingVisitor extends JavaRecursiveElementWalkingVisitor { final PsiClass[] classes = cache.getClassesByName(className, (GlobalSearchScope)scope); final List results = new ArrayList(); - final Processor processor = new Processor() { - @Override - public boolean process(PsiClass aClass) { - results.add(aClass); - return true; - } + final Processor processor = aClass -> { + results.add(aClass); + return true; }; for (PsiClass aClass : classes) { diff --git a/java/testFramework/src/com/intellij/JavaTestUtil.java b/java/testFramework/src/com/intellij/JavaTestUtil.java index 6e75f5193329..5f574e434694 100644 --- a/java/testFramework/src/com/intellij/JavaTestUtil.java +++ b/java/testFramework/src/com/intellij/JavaTestUtil.java @@ -41,18 +41,15 @@ public class JavaTestUtil { } public static void setupTestJDK() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectJdkTable jdkTable = ProjectJdkTable.getInstance(); + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectJdkTable jdkTable = ProjectJdkTable.getInstance(); - Sdk jdk = jdkTable.findJdk(TEST_JDK_NAME); - if (jdk != null) { - jdkTable.removeJdk(jdk); - } - - jdkTable.addJdk(getTestJdk()); + Sdk jdk = jdkTable.findJdk(TEST_JDK_NAME); + if (jdk != null) { + jdkTable.removeJdk(jdk); } + + jdkTable.addJdk(getTestJdk()); }); } diff --git a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java index 5c3060027f96..de32aa4da4d3 100644 --- a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java @@ -232,11 +232,8 @@ public abstract class CodeInsightTestCase extends PsiTestCase { FileUtil.copyDir(projectRoot, toDirIO); VirtualFile fromDir = getVirtualFile(projectRoot); editorInfos = - copyFilesFillingEditorInfos(fromDir, toDir, ContainerUtil.map2Array(reversed, String.class, new Function() { - @Override - public String fun(final VirtualFile s) { - return s.getPath().substring(projectRoot.getPath().length()); - } + copyFilesFillingEditorInfos(fromDir, toDir, ContainerUtil.map2Array(reversed, String.class, s -> { + return s.getPath().substring(projectRoot.getPath().length()); })); toDir.refresh(false, true); diff --git a/java/testFramework/src/com/intellij/codeInsight/completion/CompletionTestCase.java b/java/testFramework/src/com/intellij/codeInsight/completion/CompletionTestCase.java index f453d16d618b..32a922606dd4 100644 --- a/java/testFramework/src/com/intellij/codeInsight/completion/CompletionTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/completion/CompletionTestCase.java @@ -114,11 +114,8 @@ public abstract class CompletionTestCase extends DaemonAnalyzerTestCase { protected void assertStringItems(String... strings) { assertNotNull(myItems); - List actual = ContainerUtil.map(myItems, new Function() { - @Override - public String fun(LookupElement element) { - return element.getLookupString(); - } + List actual = ContainerUtil.map(myItems, element -> { + return element.getLookupString(); }); assertOrderedEquals(actual, strings); } diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java index e8a63d4eb1cb..ab439829ce9a 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java @@ -61,15 +61,12 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa @Override protected void runTest() throws Throwable { final Throwable[] throwable = {null}; - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - try { - doRunTest(); - } - catch (Throwable t) { - throwable[0] = t; - } + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + try { + doRunTest(); + } + catch (Throwable t) { + throwable[0] = t; } }, "", null); if (throwable[0] != null) { diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixParameterizedTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixParameterizedTestCase.java index b4cd26ef5ffd..dc4570379aec 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixParameterizedTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixParameterizedTestCase.java @@ -44,11 +44,6 @@ public abstract class LightQuickFixParameterizedTestCase extends LightQuickFixTe @SuppressWarnings("JUnit4AnnotatedMethodInJUnit3TestCase") @Test public void runSingle() throws Throwable { - runSingleTest(new Runnable() { - @Override - public void run() { - doSingleTest(myFileSuffix, myTestDataPath); - } - }); + runSingleTest(() -> doSingleTest(myFileSuffix, myTestDataPath)); } } diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java index d7572b343209..9d685e9f0e50 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/quickFix/LightQuickFixTestCase.java @@ -69,37 +69,33 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase final String relativePath = notNull(quickFixTestCase.getBasePath(), "") + "/" + BEFORE_PREFIX + testName; final String testFullPath = quickFixTestCase.getTestDataPath().replace(File.separatorChar, '/') + relativePath; final File testFile = new File(testFullPath); - CommandProcessor.getInstance().executeCommand(quickFixTestCase.getProject(), new Runnable() { - @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod", "CallToPrintStackTrace"}) - @Override - public void run() { + CommandProcessor.getInstance().executeCommand(quickFixTestCase.getProject(), () -> { + try { + String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET)); + quickFixTestCase.configureFromFileText(testFile.getName(), contents); + quickFixTestCase.bringRealEditorBack(); + final Pair pair = quickFixTestCase.parseActionHintImpl(quickFixTestCase.getFile(), contents); + final String text = pair.getFirst(); + final boolean actionShouldBeAvailable = pair.getSecond().booleanValue(); + + quickFixTestCase.beforeActionStarted(testName, contents); + try { - String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET)); - quickFixTestCase.configureFromFileText(testFile.getName(), contents); - quickFixTestCase.bringRealEditorBack(); - final Pair pair = quickFixTestCase.parseActionHintImpl(quickFixTestCase.getFile(), contents); - final String text = pair.getFirst(); - final boolean actionShouldBeAvailable = pair.getSecond().booleanValue(); - - quickFixTestCase.beforeActionStarted(testName, contents); - - try { - myWrapper = quickFixTestCase; - quickFixTestCase.doAction(text, actionShouldBeAvailable, testFullPath, testName); - } - finally { - myWrapper = null; - quickFixTestCase.afterActionCompleted(testName, contents); - } + myWrapper = quickFixTestCase; + quickFixTestCase.doAction(text, actionShouldBeAvailable, testFullPath, testName); } - catch (FileComparisonFailure e){ - throw e; - } - catch (Throwable e) { - e.printStackTrace(); - fail(testName); + finally { + myWrapper = null; + quickFixTestCase.afterActionCompleted(testName, contents); } } + catch (FileComparisonFailure e){ + throw e; + } + catch (Throwable e) { + e.printStackTrace(); + fail(testName); + } }, "", ""); } @@ -224,11 +220,8 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase final String testDirPath = testCase.getTestDataPath().replace(File.separatorChar, '/') + testCase.getBasePath(); File testDir = new File(testDirPath); - final File[] files = testDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, @NonNls String name) { - return name.startsWith(BEFORE_PREFIX); - } + final File[] files = testDir.listFiles((dir, name) -> { + return name.startsWith(BEFORE_PREFIX); }); if (files == null || files.length == 0) { diff --git a/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java b/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java index 95d71bc9bec5..668e78270b64 100644 --- a/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java +++ b/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java @@ -101,30 +101,27 @@ public class CompilerTestUtil { @Override public void run() throws Throwable { final JavaAwareProjectJdkTableImpl table = JavaAwareProjectJdkTableImpl.getInstanceEx(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Sdk internalJdk = table.getInternalJdk(); - List modulesToRestore = new SmartList(); - for (Module module : ModuleManager.getInstance(project).getModules()) { - Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); - if (sdk != null && sdk.equals(internalJdk)) { - modulesToRestore.add(module); - } - } - table.removeJdk(internalJdk); - for (Module module : modulesToRestore) { - ModuleRootModificationUtil.setModuleSdk(module, internalJdk); - } - BuildManager.getInstance().clearState(project); - Future future = BuildManager.getInstance().stopListening(); - try { - future.get(100, TimeUnit.SECONDS); - } - catch (Exception e) { - throw new RuntimeException(e); + ApplicationManager.getApplication().runWriteAction(() -> { + Sdk internalJdk = table.getInternalJdk(); + List modulesToRestore = new SmartList(); + for (Module module : ModuleManager.getInstance(project).getModules()) { + Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); + if (sdk != null && sdk.equals(internalJdk)) { + modulesToRestore.add(module); } } + table.removeJdk(internalJdk); + for (Module module : modulesToRestore) { + ModuleRootModificationUtil.setModuleSdk(module, internalJdk); + } + BuildManager.getInstance().clearState(project); + Future future = BuildManager.getInstance().stopListening(); + try { + future.get(100, TimeUnit.SECONDS); + } + catch (Exception e) { + throw new RuntimeException(e); + } }); } }); diff --git a/java/testFramework/src/com/intellij/debugger/DebuggerTestCase.java b/java/testFramework/src/com/intellij/debugger/DebuggerTestCase.java index b711744a9a2a..35d549659770 100644 --- a/java/testFramework/src/com/intellij/debugger/DebuggerTestCase.java +++ b/java/testFramework/src/com/intellij/debugger/DebuggerTestCase.java @@ -156,26 +156,23 @@ public abstract class DebuggerTestCase extends ExecutionWithDebuggerToolsTestCas } }; - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - try { - myDebuggerSession = - DebuggerManagerEx.getInstanceEx(myProject) - .attachVirtualMachine(new DefaultDebugEnvironment(new ExecutionEnvironmentBuilder(myProject, DefaultDebugExecutor.getDebugExecutorInstance()) - .runProfile(new MockConfiguration()) - .build(), javaCommandLineState, debugParameters, false)); - XDebuggerManager.getInstance(myProject).startSession(javaCommandLineState.getEnvironment(), new XDebugProcessStarter() { - @Override - @NotNull - public XDebugProcess start(@NotNull XDebugSession session) { - return JavaDebugProcess.create(session, myDebuggerSession); - } - }); - } - catch (ExecutionException e) { - LOG.error(e); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + try { + myDebuggerSession = + DebuggerManagerEx.getInstanceEx(myProject) + .attachVirtualMachine(new DefaultDebugEnvironment(new ExecutionEnvironmentBuilder(myProject, DefaultDebugExecutor.getDebugExecutorInstance()) + .runProfile(new MockConfiguration()) + .build(), javaCommandLineState, debugParameters, false)); + XDebuggerManager.getInstance(myProject).startSession(javaCommandLineState.getEnvironment(), new XDebugProcessStarter() { + @Override + @NotNull + public XDebugProcess start(@NotNull XDebugSession session) { + return JavaDebugProcess.create(session, myDebuggerSession); + } + }); + } + catch (ExecutionException e) { + LOG.error(e); } }, ModalityState.defaultModalityState()); myDebugProcess = myDebuggerSession.getProcess(); @@ -366,14 +363,11 @@ public abstract class DebuggerTestCase extends ExecutionWithDebuggerToolsTestCas if(request.isDone()) { thread.interrupt(); } - waitFor(new Runnable() { - @Override - public void run() { - try { - thread.join(); - } - catch (InterruptedException ignored) { - } + waitFor(() -> { + try { + thread.join(); + } + catch (InterruptedException ignored) { } }); @@ -400,12 +394,7 @@ public abstract class DebuggerTestCase extends ExecutionWithDebuggerToolsTestCas } }); - waitFor(new Runnable() { - @Override - public void run() { - s.waitFor(); - } - }); + waitFor(() -> s.waitFor()); } public DebuggerContextImpl createDebuggerContext(final SuspendContextImpl suspendContext, StackFrameProxyImpl stackFrame) { @@ -443,15 +432,12 @@ public abstract class DebuggerTestCase extends ExecutionWithDebuggerToolsTestCas } protected void createBreakpointInHelloWorld() { - DebuggerInvocationUtil.invokeAndWait(myProject, new Runnable() { - @Override - public void run() { - BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager(); - PsiClass psiClass = JavaPsiFacade.getInstance(myProject).findClass("HelloWorld", GlobalSearchScope.allScope(myProject)); - assertNotNull(psiClass); - Document document = PsiDocumentManager.getInstance(myProject).getDocument(psiClass.getContainingFile()); - breakpointManager.addLineBreakpoint(document, 3); - } + DebuggerInvocationUtil.invokeAndWait(myProject, () -> { + BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager(); + PsiClass psiClass = JavaPsiFacade.getInstance(myProject).findClass("HelloWorld", GlobalSearchScope.allScope(myProject)); + assertNotNull(psiClass); + Document document = PsiDocumentManager.getInstance(myProject).getDocument(psiClass.getContainingFile()); + breakpointManager.addLineBreakpoint(document, 3); }, ApplicationManager.getApplication().getDefaultModalityState()); } diff --git a/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java b/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java index 285baf42e0e3..5c4c5c003704 100644 --- a/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java +++ b/java/testFramework/src/com/intellij/debugger/ExecutionWithDebuggerToolsTestCase.java @@ -104,12 +104,7 @@ public abstract class ExecutionWithDebuggerToolsTestCase extends ExecutionTestCa protected void waitBreakpoints() { myScriptRunnablesSema.down(); - waitFor(new Runnable() { - @Override - public void run() { - myScriptRunnablesSema.waitFor(); - } - }); + waitFor(() -> myScriptRunnablesSema.waitFor()); } @Override @@ -209,43 +204,37 @@ public abstract class ExecutionWithDebuggerToolsTestCase extends ExecutionTestCa } protected void printContext(final StackFrameContext context) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (context.getFrameProxy() != null) { - SourcePosition sourcePosition = PositionUtil.getSourcePosition(context); - println(sourcePosition.getFile().getVirtualFile().getName() + ":" + sourcePosition.getLine(), ProcessOutputTypes.SYSTEM); - } - else { - println("Context thread is null", ProcessOutputTypes.SYSTEM); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (context.getFrameProxy() != null) { + SourcePosition sourcePosition = PositionUtil.getSourcePosition(context); + println(sourcePosition.getFile().getVirtualFile().getName() + ":" + sourcePosition.getLine(), ProcessOutputTypes.SYSTEM); + } + else { + println("Context thread is null", ProcessOutputTypes.SYSTEM); } }); } protected void printContextWithText(final StackFrameContext context) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (context.getFrameProxy() != null) { - SourcePosition sourcePosition = PositionUtil.getSourcePosition(context); - int offset = sourcePosition.getOffset(); - Document document = PsiDocumentManager.getInstance(myProject).getDocument(sourcePosition.getFile()); - CharSequence text = document.getImmutableCharSequence(); - String positionText = ""; - if (offset > -1) { - positionText = StringUtil.escapeLineBreak(" [" + text.subSequence(Math.max(0, offset - 20), offset) + "<*>" - + text.subSequence(offset, Math.min(offset + 20, text.length())) + "]"); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (context.getFrameProxy() != null) { + SourcePosition sourcePosition = PositionUtil.getSourcePosition(context); + int offset = sourcePosition.getOffset(); + Document document = PsiDocumentManager.getInstance(myProject).getDocument(sourcePosition.getFile()); + CharSequence text = document.getImmutableCharSequence(); + String positionText = ""; + if (offset > -1) { + positionText = StringUtil.escapeLineBreak(" [" + text.subSequence(Math.max(0, offset - 20), offset) + "<*>" + + text.subSequence(offset, Math.min(offset + 20, text.length())) + "]"); + } - println(sourcePosition.getFile().getVirtualFile().getName() - + ":" + sourcePosition.getLine() - + positionText, - ProcessOutputTypes.SYSTEM); - } - else { - println("Context thread is null", ProcessOutputTypes.SYSTEM); - } + println(sourcePosition.getFile().getVirtualFile().getName() + + ":" + sourcePosition.getLine() + + positionText, + ProcessOutputTypes.SYSTEM); + } + else { + println("Context thread is null", ProcessOutputTypes.SYSTEM); } }); } @@ -313,25 +302,17 @@ public abstract class ExecutionWithDebuggerToolsTestCase extends ExecutionTestCa }); } else { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - pumpSwingThread(); - } - }); + SwingUtilities.invokeLater(() -> pumpSwingThread()); } } } protected void invokeRatherLater(final DebuggerCommandImpl command) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - InvokeRatherLaterRequest request = new InvokeRatherLaterRequest(command, getDebugProcess()); - myRatherLaterRequests.add(request); + UIUtil.invokeLaterIfNeeded(() -> { + InvokeRatherLaterRequest request = new InvokeRatherLaterRequest(command, getDebugProcess()); + myRatherLaterRequests.add(request); - if (myRatherLaterRequests.size() == 1) pumpSwingThread(); - } + if (myRatherLaterRequests.size() == 1) pumpSwingThread(); }); } @@ -346,84 +327,81 @@ public abstract class ExecutionWithDebuggerToolsTestCase extends ExecutionTestCa } public void createBreakpoints(final PsiFile file) { - Runnable runnable = new Runnable() { - @Override - public void run() { - BreakpointManager breakpointManager = DebuggerManagerImpl.getInstanceEx(myProject).getBreakpointManager(); - Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); - int offset = -1; - for (; ;) { - offset = document.getText().indexOf("Breakpoint!", offset + 1); - if (offset == -1) break; + Runnable runnable = () -> { + BreakpointManager breakpointManager = DebuggerManagerImpl.getInstanceEx(myProject).getBreakpointManager(); + Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); + int offset = -1; + for (; ;) { + offset = document.getText().indexOf("Breakpoint!", offset + 1); + if (offset == -1) break; - int commentLine = document.getLineNumber(offset); + int commentLine = document.getLineNumber(offset); - String comment = document.getText().substring(document.getLineStartOffset(commentLine), document.getLineEndOffset(commentLine)); + String comment = document.getText().substring(document.getLineStartOffset(commentLine), document.getLineEndOffset(commentLine)); - Breakpoint breakpoint; + Breakpoint breakpoint; - if (comment.indexOf("Method") != -1) { - breakpoint = breakpointManager.addMethodBreakpoint(document, commentLine + 1); - if (breakpoint != null) { - println("MethodBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), - ProcessOutputTypes.SYSTEM); - } + if (comment.indexOf("Method") != -1) { + breakpoint = breakpointManager.addMethodBreakpoint(document, commentLine + 1); + if (breakpoint != null) { + println("MethodBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), + ProcessOutputTypes.SYSTEM); } - else if (comment.indexOf("Field") != -1) { - breakpoint = breakpointManager.addFieldBreakpoint(document, commentLine + 1, readValue(comment, "Field")); - if (breakpoint != null) { - println("FieldBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), ProcessOutputTypes.SYSTEM); - } + } + else if (comment.indexOf("Field") != -1) { + breakpoint = breakpointManager.addFieldBreakpoint(document, commentLine + 1, readValue(comment, "Field")); + if (breakpoint != null) { + println("FieldBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), ProcessOutputTypes.SYSTEM); } - else if (comment.indexOf("Exception") != -1) { - breakpoint = breakpointManager.addExceptionBreakpoint(readValue(comment, "Exception"), ""); - if (breakpoint != null) { - println("ExceptionBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), - ProcessOutputTypes.SYSTEM); - } + } + else if (comment.indexOf("Exception") != -1) { + breakpoint = breakpointManager.addExceptionBreakpoint(readValue(comment, "Exception"), ""); + if (breakpoint != null) { + println("ExceptionBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), + ProcessOutputTypes.SYSTEM); } - else { - breakpoint = breakpointManager.addLineBreakpoint(document, commentLine + 1); - if (breakpoint != null) { - println("LineBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), ProcessOutputTypes.SYSTEM); - } + } + else { + breakpoint = breakpointManager.addLineBreakpoint(document, commentLine + 1); + if (breakpoint != null) { + println("LineBreakpoint created at " + file.getVirtualFile().getName() + ":" + (commentLine + 2), ProcessOutputTypes.SYSTEM); + } + } + + String suspendPolicy = readValue(comment, "suspendPolicy"); + if (suspendPolicy != null) { + //breakpoint.setSuspend(!DebuggerSettings.SUSPEND_NONE.equals(suspendPolicy)); + breakpoint.setSuspendPolicy(suspendPolicy); + println("SUSPEND_POLICY = " + suspendPolicy, ProcessOutputTypes.SYSTEM); + } + String condition = readValue(comment, "Condition"); + if (condition != null) { + //breakpoint.CONDITION_ENABLED = true; + breakpoint.setCondition(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition)); + println("Condition = " + condition, ProcessOutputTypes.SYSTEM); + } + String passCount = readValue(comment, "Pass count"); + if (passCount != null) { + breakpoint.setCountFilterEnabled(true); + breakpoint.setCountFilter(Integer.parseInt(passCount)); + println("Pass count = " + passCount, ProcessOutputTypes.SYSTEM); + } + + String classFilters = readValue(comment, "Class filters"); + if (classFilters != null) { + breakpoint.setClassFiltersEnabled(true); + StringTokenizer tokenizer = new StringTokenizer(classFilters, " ,"); + ArrayList lst = new ArrayList(); + + while (tokenizer.hasMoreTokens()) { + ClassFilter filter = new ClassFilter(); + filter.setEnabled(true); + filter.setPattern(tokenizer.nextToken()); + lst.add(filter); } - String suspendPolicy = readValue(comment, "suspendPolicy"); - if (suspendPolicy != null) { - //breakpoint.setSuspend(!DebuggerSettings.SUSPEND_NONE.equals(suspendPolicy)); - breakpoint.setSuspendPolicy(suspendPolicy); - println("SUSPEND_POLICY = " + suspendPolicy, ProcessOutputTypes.SYSTEM); - } - String condition = readValue(comment, "Condition"); - if (condition != null) { - //breakpoint.CONDITION_ENABLED = true; - breakpoint.setCondition(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition)); - println("Condition = " + condition, ProcessOutputTypes.SYSTEM); - } - String passCount = readValue(comment, "Pass count"); - if (passCount != null) { - breakpoint.setCountFilterEnabled(true); - breakpoint.setCountFilter(Integer.parseInt(passCount)); - println("Pass count = " + passCount, ProcessOutputTypes.SYSTEM); - } - - String classFilters = readValue(comment, "Class filters"); - if (classFilters != null) { - breakpoint.setClassFiltersEnabled(true); - StringTokenizer tokenizer = new StringTokenizer(classFilters, " ,"); - ArrayList lst = new ArrayList(); - - while (tokenizer.hasMoreTokens()) { - ClassFilter filter = new ClassFilter(); - filter.setEnabled(true); - filter.setPattern(tokenizer.nextToken()); - lst.add(filter); - } - - breakpoint.setClassFilters(lst.toArray(new ClassFilter[lst.size()])); - println("Class filters = " + classFilters, ProcessOutputTypes.SYSTEM); - } + breakpoint.setClassFilters(lst.toArray(new ClassFilter[lst.size()])); + println("Class filters = " + classFilters, ProcessOutputTypes.SYSTEM); } } }; diff --git a/java/testFramework/src/com/intellij/debugger/impl/DescriptorTestCase.java b/java/testFramework/src/com/intellij/debugger/impl/DescriptorTestCase.java index e045daff8b9d..cf6d91062c7e 100644 --- a/java/testFramework/src/com/intellij/debugger/impl/DescriptorTestCase.java +++ b/java/testFramework/src/com/intellij/debugger/impl/DescriptorTestCase.java @@ -181,41 +181,38 @@ public abstract class DescriptorTestCase extends DebuggerTestCase { final Set alreadyExpanded, final NodeFilter filter, final SuspendContextImpl context) { - invokeRatherLater(context, new Runnable() { - @Override - public void run() { - boolean anyCollapsed = false; - for(int i = 0; i < tree.getRowCount(); i++) { - final TreeNode treeNode = (TreeNode)tree.getPathForRow(i).getLastPathComponent(); - if(tree.isCollapsed(i) && !treeNode.isLeaf()) { - NodeDescriptor nodeDescriptor = null; - if (treeNode instanceof DebuggerTreeNodeImpl) { - nodeDescriptor = ((DebuggerTreeNodeImpl)treeNode).getDescriptor(); - } - boolean shouldExpand = filter == null || filter.shouldExpand(treeNode); - if (shouldExpand) { - // additional checks to prevent infinite expand - if (nodeDescriptor instanceof ValueDescriptor) { - final Value value = ((ValueDescriptor)nodeDescriptor).getValue(); - shouldExpand = !alreadyExpanded.contains(value); - if (shouldExpand) { - alreadyExpanded.add(value); - } + invokeRatherLater(context, () -> { + boolean anyCollapsed = false; + for(int i = 0; i < tree.getRowCount(); i++) { + final TreeNode treeNode = (TreeNode)tree.getPathForRow(i).getLastPathComponent(); + if(tree.isCollapsed(i) && !treeNode.isLeaf()) { + NodeDescriptor nodeDescriptor = null; + if (treeNode instanceof DebuggerTreeNodeImpl) { + nodeDescriptor = ((DebuggerTreeNodeImpl)treeNode).getDescriptor(); + } + boolean shouldExpand = filter == null || filter.shouldExpand(treeNode); + if (shouldExpand) { + // additional checks to prevent infinite expand + if (nodeDescriptor instanceof ValueDescriptor) { + final Value value = ((ValueDescriptor)nodeDescriptor).getValue(); + shouldExpand = !alreadyExpanded.contains(value); + if (shouldExpand) { + alreadyExpanded.add(value); } } - if (shouldExpand) { - anyCollapsed = true; - tree.expandRow(i); - } + } + if (shouldExpand) { + anyCollapsed = true; + tree.expandRow(i); } } + } - if (anyCollapsed) { - expandAll(tree, runnable, alreadyExpanded, filter, context); - } - else { - runnable.run(); - } + if (anyCollapsed) { + expandAll(tree, runnable, alreadyExpanded, filter, context); + } + else { + runnable.run(); } }); } diff --git a/java/testFramework/src/com/intellij/execution/ExecutionTestCase.java b/java/testFramework/src/com/intellij/execution/ExecutionTestCase.java index e02a9defa971..9d1dcffb4425 100644 --- a/java/testFramework/src/com/intellij/execution/ExecutionTestCase.java +++ b/java/testFramework/src/com/intellij/execution/ExecutionTestCase.java @@ -94,21 +94,18 @@ public abstract class ExecutionTestCase extends IdeaTestCase { @Override protected void setUpModule() { super.setUpModule(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final String modulePath = getTestAppPath(); - final String srcPath = modulePath + File.separator + "src"; - VirtualFile moduleDir = LocalFileSystem.getInstance().findFileByPath(modulePath.replace(File.separatorChar, '/')); - VirtualFile srcDir = LocalFileSystem.getInstance().findFileByPath(srcPath.replace(File.separatorChar, '/')); + ApplicationManager.getApplication().runWriteAction(() -> { + final String modulePath = getTestAppPath(); + final String srcPath = modulePath + File.separator + "src"; + VirtualFile moduleDir = LocalFileSystem.getInstance().findFileByPath(modulePath.replace(File.separatorChar, '/')); + VirtualFile srcDir = LocalFileSystem.getInstance().findFileByPath(srcPath.replace(File.separatorChar, '/')); - final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); - PsiTestUtil.removeAllRoots(myModule, rootManager.getSdk()); - PsiTestUtil.addContentRoot(myModule, moduleDir); - PsiTestUtil.addSourceRoot(myModule, srcDir); - IdeaTestUtil.setModuleLanguageLevel(myModule, LanguageLevel.JDK_1_8); - PsiTestUtil.setCompilerOutputPath(myModule, VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(myModuleOutputDir.getAbsolutePath())), false); - } + final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); + PsiTestUtil.removeAllRoots(myModule, rootManager.getSdk()); + PsiTestUtil.addContentRoot(myModule, moduleDir); + PsiTestUtil.addSourceRoot(myModule, srcDir); + IdeaTestUtil.setModuleLanguageLevel(myModule, LanguageLevel.JDK_1_8); + PsiTestUtil.setCompilerOutputPath(myModule, VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(myModuleOutputDir.getAbsolutePath())), false); }); } @@ -184,17 +181,14 @@ public abstract class ExecutionTestCase extends IdeaTestCase { Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD, getTestRootDisposable()); final boolean[] isRunning = {true}; - alarm.addRequest(new Runnable() { - @Override - public void run() { - boolean b; - synchronized (isRunning) { - b = isRunning[0]; - } - if (b) { - processHandler.destroyProcess(); - LOG.error("process was running over " + myTimeout / 1000 + " seconds. Interrupted. "); - } + alarm.addRequest(() -> { + boolean b; + synchronized (isRunning) { + b = isRunning[0]; + } + if (b) { + processHandler.destroyProcess(); + LOG.error("process was running over " + myTimeout / 1000 + " seconds. Interrupted. "); } }, myTimeout); processHandler.waitFor(); @@ -209,17 +203,14 @@ public abstract class ExecutionTestCase extends IdeaTestCase { final Thread thread = Thread.currentThread(); final boolean[] isRunning = {true}; - alarm.addRequest(new Runnable() { - @Override - public void run() { - boolean b; - synchronized (isRunning) { - b = isRunning[0]; - } - if (b) { - thread.interrupt(); - LOG.error("test was running over " + myTimeout / 1000 + " seconds. Interrupted. "); - } + alarm.addRequest(() -> { + boolean b; + synchronized (isRunning) { + b = isRunning[0]; + } + if (b) { + thread.interrupt(); + LOG.error("test was running over " + myTimeout / 1000 + " seconds. Interrupted. "); } }, myTimeout); r.run(); diff --git a/java/testFramework/src/com/intellij/ide/projectWizard/ProjectWizardTestCase.java b/java/testFramework/src/com/intellij/ide/projectWizard/ProjectWizardTestCase.java index 783d26fba100..6f064c3daaf3 100644 --- a/java/testFramework/src/com/intellij/ide/projectWizard/ProjectWizardTestCase.java +++ b/java/testFramework/src/com/intellij/ide/projectWizard/ProjectWizardTestCase.java @@ -101,15 +101,12 @@ public abstract class ProjectWizardTestCase ext throw new IllegalArgumentException(group + '/' + name + " template not found, available groups " + step.availableTemplateGroupsToString()); } - runWizard(new Consumer() { - @Override - public void consume(Step step) { - if (name != null && step instanceof ChooseTemplateStep) { - ((ChooseTemplateStep)step).setSelectedTemplate(name); - } - if (adjuster != null) { - adjuster.consume(step); - } + runWizard(step1 -> { + if (name != null && step1 instanceof ChooseTemplateStep) { + ((ChooseTemplateStep)step1).setSelectedTemplate(name); + } + if (adjuster != null) { + adjuster.consume(step1); } }); } @@ -156,36 +153,26 @@ public abstract class ProjectWizardTestCase ext Sdk projectSdk = ProjectRootManager.getInstance(getProject()).getProjectSdk(); for (final Sdk jdk : ProjectJdkTable.getInstance().getAllJdks()) { if (projectSdk != jdk) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectJdkTable.getInstance().removeJdk(jdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectJdkTable.getInstance().removeJdk(jdk); }); } } } protected void configureJdk() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @SuppressWarnings("UseOfSystemOutOrSystemErr") - @Override - public void run() { - addSdk(new SimpleJavaSdkType().createJdk(DEFAULT_SDK, SystemProperties.getJavaHome())); - addSdk(new SimpleJavaSdkType().createJdk("_other", SystemProperties.getJavaHome())); + ApplicationManager.getApplication().runWriteAction(() -> { + addSdk(new SimpleJavaSdkType().createJdk(DEFAULT_SDK, SystemProperties.getJavaHome())); + addSdk(new SimpleJavaSdkType().createJdk("_other", SystemProperties.getJavaHome())); - System.out.println("ProjectWizardTestCase.configureJdk:"); - System.out.println(Arrays.asList(ProjectJdkTable.getInstance().getAllJdks())); - } + System.out.println("ProjectWizardTestCase.configureJdk:"); + System.out.println(Arrays.asList(ProjectJdkTable.getInstance().getAllJdks())); }); } protected void addSdk(final Sdk sdk) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectJdkTable.getInstance().addJdk(sdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectJdkTable.getInstance().addJdk(sdk); }); mySdks.add(sdk); @@ -199,21 +186,15 @@ public abstract class ProjectWizardTestCase ext } if (myCreatedProject != null) { myProjectManager.closeProject(myCreatedProject); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Disposer.dispose(myCreatedProject); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Disposer.dispose(myCreatedProject); }); myCreatedProject = null; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectRootManager.getInstance(myProjectManager.getDefaultProject()).setProjectSdk(myOldDefaultProjectSdk); - for (Sdk sdk : mySdks) { - ProjectJdkTable.getInstance().removeJdk(sdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManager.getInstance(myProjectManager.getDefaultProject()).setProjectSdk(myOldDefaultProjectSdk); + for (Sdk sdk : mySdks) { + ProjectJdkTable.getInstance().removeJdk(sdk); } }); SelectTemplateSettings.getInstance().setLastTemplate(null, null); @@ -257,11 +238,8 @@ public abstract class ProjectWizardTestCase ext protected Sdk createSdk(String name, SdkTypeId sdkType) { final Sdk sdk = ProjectJdkTable.getInstance().createSdk(name, sdkType); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectJdkTable.getInstance().addJdk(sdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectJdkTable.getInstance().addJdk(sdk); }); mySdks.add(sdk); return sdk; diff --git a/java/testFramework/src/com/intellij/projectView/BaseProjectViewTestCase.java b/java/testFramework/src/com/intellij/projectView/BaseProjectViewTestCase.java index 5a8ac4917ef4..c578c7cffd8e 100644 --- a/java/testFramework/src/com/intellij/projectView/BaseProjectViewTestCase.java +++ b/java/testFramework/src/com/intellij/projectView/BaseProjectViewTestCase.java @@ -79,14 +79,11 @@ public abstract class BaseProjectViewTestCase extends TestSourceBasedTestCase { } public static void checkContainsMethod(final Object rootElement, final AbstractTreeStructure structure) { - ProjectViewTestUtil.checkContainsMethod(rootElement, structure, new Function() { - @Override - public VirtualFile[] fun(AbstractTreeNode kid) { - if (kid instanceof PackageElementNode) { - return ((PackageElementNode)kid).getVirtualFiles(); - } - return null; + ProjectViewTestUtil.checkContainsMethod(rootElement, structure, kid -> { + if (kid instanceof PackageElementNode) { + return ((PackageElementNode)kid).getVirtualFiles(); } + return null; }); } diff --git a/java/testFramework/src/com/intellij/psi/AbstractReparseTestCase.java b/java/testFramework/src/com/intellij/psi/AbstractReparseTestCase.java index d1ad8a4c4d33..d372c9a6d722 100644 --- a/java/testFramework/src/com/intellij/psi/AbstractReparseTestCase.java +++ b/java/testFramework/src/com/intellij/psi/AbstractReparseTestCase.java @@ -24,26 +24,18 @@ public abstract class AbstractReparseTestCase extends PsiTestCase { } protected void insert(@NonNls final String s) throws IncorrectOperationException { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - String oldText = myDummyFile.getText(); - String expectedNewText = oldText.substring(0, myInsertOffset) + s + oldText.substring(myInsertOffset); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + String oldText = myDummyFile.getText(); + String expectedNewText = oldText.substring(0, myInsertOffset) + s + oldText.substring(myInsertOffset); - try { - doReparseAndCheck(s, expectedNewText, 0); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - myInsertOffset += s.length(); - } - }); + try { + doReparseAndCheck(s, expectedNewText, 0); } - }, "asd", null); + catch (IncorrectOperationException e) { + LOG.error(e); + } + myInsertOffset += s.length(); + }), "asd", null); } protected void moveEditPointLeft(int count) { @@ -83,23 +75,15 @@ public abstract class AbstractReparseTestCase extends PsiTestCase { } protected void doReparse(final String s, final int length) { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - BlockSupport blockSupport = ServiceManager.getService(myProject, BlockSupport.class); - try { - blockSupport.reparseRange(myDummyFile, myInsertOffset - length, myInsertOffset, s); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + BlockSupport blockSupport = ServiceManager.getService(myProject, BlockSupport.class); + try { + blockSupport.reparseRange(myDummyFile, myInsertOffset - length, myInsertOffset, s); } - }, "asd", null); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), "asd", null); } protected void prepareFile(@NonNls String prefix, @NonNls String suffix) throws IncorrectOperationException { diff --git a/java/testFramework/src/com/intellij/refactoring/MultiFileTestCase.java b/java/testFramework/src/com/intellij/refactoring/MultiFileTestCase.java index dbefed374e42..0fd9eed809b4 100644 --- a/java/testFramework/src/com/intellij/refactoring/MultiFileTestCase.java +++ b/java/testFramework/src/com/intellij/refactoring/MultiFileTestCase.java @@ -56,10 +56,8 @@ public abstract class MultiFileTestCase extends CodeInsightTestCase { final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/')); performAction.performAction(rootDir, rootAfter); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - public void run() { - myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); }); FileDocumentManager.getInstance().saveAllDocuments(); diff --git a/java/testFramework/src/com/intellij/testFramework/CompilerTester.java b/java/testFramework/src/com/intellij/testFramework/CompilerTester.java index 95fc232f6a38..7cb72cd2f9c1 100644 --- a/java/testFramework/src/com/intellij/testFramework/CompilerTester.java +++ b/java/testFramework/src/com/intellij/testFramework/CompilerTester.java @@ -156,48 +156,23 @@ public class CompilerTester { } public List make() { - return runCompiler(new Consumer() { - @Override - public void consume(ErrorReportingCallback callback) { - CompilerManager.getInstance(getProject()).make(callback); - } - }); + return runCompiler(callback -> CompilerManager.getInstance(getProject()).make(callback)); } public List rebuild() { - return runCompiler(new Consumer() { - @Override - public void consume(ErrorReportingCallback callback) { - CompilerManager.getInstance(getProject()).rebuild(callback); - } - }); + return runCompiler(callback -> CompilerManager.getInstance(getProject()).rebuild(callback)); } public List compileModule(final Module module) { - return runCompiler(new Consumer() { - @Override - public void consume(ErrorReportingCallback callback) { - CompilerManager.getInstance(getProject()).compile(module, callback); - } - }); + return runCompiler(callback -> CompilerManager.getInstance(getProject()).compile(module, callback)); } public List make(final CompileScope scope) { - return runCompiler(new Consumer() { - @Override - public void consume(ErrorReportingCallback callback) { - CompilerManager.getInstance(getProject()).make(scope, callback); - } - }); + return runCompiler(callback -> CompilerManager.getInstance(getProject()).make(scope, callback)); } public List compileFiles(final VirtualFile... files) { - return runCompiler(new Consumer() { - @Override - public void consume(ErrorReportingCallback callback) { - CompilerManager.getInstance(getProject()).compile(files, callback); - } - }); + return runCompiler(callback -> CompilerManager.getInstance(getProject()).compile(files, callback)); } private List runCompiler(final Consumer runnable) { diff --git a/java/testFramework/src/com/intellij/testFramework/ResolveTestCase.java b/java/testFramework/src/com/intellij/testFramework/ResolveTestCase.java index fda285d09b8c..5615728f5d77 100644 --- a/java/testFramework/src/com/intellij/testFramework/ResolveTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/ResolveTestCase.java @@ -71,11 +71,8 @@ public abstract class ResolveTestCase extends PsiTestCase { myDocument = FileDocumentManager.getInstance().getDocument(existing); assertNotNull(myDocument); final String finalFileText = fileText; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myDocument.setText(finalFileText); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myDocument.setText(finalFileText); }); myFile = PsiManager.getInstance(getProject()).findFile(existing); diff --git a/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java b/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java index 774b9df5b96a..ad863e54448f 100644 --- a/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java @@ -44,12 +44,9 @@ import java.io.File; FileUtil.copyDir(currentTestRoot, new File(myTempDirectory, getTestDirectoryName())); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - setupContentRoot(); - } - }); + ApplicationManager.getApplication().runWriteAction(() -> { + setupContentRoot(); + }); ProjectViewTestUtil.setupImpl(getProject(), true); } diff --git a/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaModuleFixtureBuilderImpl.java b/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaModuleFixtureBuilderImpl.java index ba1ee39d6302..709f310106a4 100644 --- a/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaModuleFixtureBuilderImpl.java +++ b/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaModuleFixtureBuilderImpl.java @@ -118,57 +118,54 @@ abstract class JavaModuleFixtureBuilderImpl extends Mod protected void initModule(final Module module) { super.initModule(module); - ModuleRootModificationUtil.updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - LibraryTable libraryTable = model.getModuleLibraryTable(); - for (Lib lib : myLibraries) { - Library library = libraryTable.createLibrary(lib.getName()); - Library.ModifiableModel libraryModel = library.getModifiableModel(); - boolean success = false; - try { - for (OrderRootType rootType : OrderRootType.getAllTypes()) { - for (String root : lib.getRoots(rootType)) { - VirtualFile vRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(root); - if (vRoot != null && OrderRootType.CLASSES.equals(rootType) && !vRoot.isDirectory()) { - VirtualFile jar = JarFileSystem.getInstance().refreshAndFindFileByPath(root + "!/"); - if (jar != null) { - vRoot = jar; - } - } - if (vRoot != null) { - libraryModel.addRoot(vRoot, rootType); + ModuleRootModificationUtil.updateModel(module, model -> { + LibraryTable libraryTable = model.getModuleLibraryTable(); + for (Lib lib : myLibraries) { + Library library = libraryTable.createLibrary(lib.getName()); + Library.ModifiableModel libraryModel = library.getModifiableModel(); + boolean success = false; + try { + for (OrderRootType rootType : OrderRootType.getAllTypes()) { + for (String root : lib.getRoots(rootType)) { + VirtualFile vRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(root); + if (vRoot != null && OrderRootType.CLASSES.equals(rootType) && !vRoot.isDirectory()) { + VirtualFile jar = JarFileSystem.getInstance().refreshAndFindFileByPath(root + "!/"); + if (jar != null) { + vRoot = jar; } } - } - success = true; - } - finally { - if (!success) { - Disposer.dispose(libraryModel); + if (vRoot != null) { + libraryModel.addRoot(vRoot, rootType); + } } } - - libraryModel.commit(); + success = true; + } + finally { + if (!success) { + Disposer.dispose(libraryModel); + } } - final Sdk jdk; - if (myJdk != null) { - VfsRootAccess.allowRootAccess(module, myJdk); - jdk = JavaSdk.getInstance().createJdk(module.getName() + "_jdk", myJdk, false); - ((ProjectJdkImpl)jdk).setVersionString(StringUtil.notNullize(IdeaTestUtil.getMockJdkVersion(myJdk), "java 1.5")); - } - else { - jdk = IdeaTestUtil.getMockJdk17(); - } - model.setSdk(new MockJdkWrapper(CompilerConfigurationImpl.getTestsExternalCompilerHome(), jdk)); + libraryModel.commit(); + } - if (myLanguageLevel != null) { - model.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(myLanguageLevel); - } - else if (myMockJdkLevel == MockJdkLevel.jdk15) { - model.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(LanguageLevel.JDK_1_5); - } + final Sdk jdk; + if (myJdk != null) { + VfsRootAccess.allowRootAccess(module, myJdk); + jdk = JavaSdk.getInstance().createJdk(module.getName() + "_jdk", myJdk, false); + ((ProjectJdkImpl)jdk).setVersionString(StringUtil.notNullize(IdeaTestUtil.getMockJdkVersion(myJdk), "java 1.5")); + } + else { + jdk = IdeaTestUtil.getMockJdk17(); + } + model.setSdk(new MockJdkWrapper(CompilerConfigurationImpl.getTestsExternalCompilerHome(), jdk)); + + if (myLanguageLevel != null) { + model.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(myLanguageLevel); + } + else if (myMockJdkLevel == MockJdkLevel.jdk15) { + model.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(LanguageLevel.JDK_1_5); } }); diff --git a/java/typeMigration/src/com/intellij/refactoring/typeMigration/inspections/GuavaInspection.java b/java/typeMigration/src/com/intellij/refactoring/typeMigration/inspections/GuavaInspection.java index a5015e8c87e1..dee2204f1db7 100644 --- a/java/typeMigration/src/com/intellij/refactoring/typeMigration/inspections/GuavaInspection.java +++ b/java/typeMigration/src/com/intellij/refactoring/typeMigration/inspections/GuavaInspection.java @@ -400,12 +400,7 @@ public class GuavaInspection extends BaseJavaLocalInspectionTool { PsiType type = typeIterator.next(); mappings.put(element, type); } - return new Function() { - @Override - public PsiType fun(PsiElement element) { - return mappings.get(element); - } - }; + return element -> mappings.get(element); } } } \ No newline at end of file diff --git a/java/typeMigration/test/com/intellij/refactoring/TypeMigrationTestBase.java b/java/typeMigration/test/com/intellij/refactoring/TypeMigrationTestBase.java index b3e586f36434..d11c907271f1 100644 --- a/java/typeMigration/test/com/intellij/refactoring/TypeMigrationTestBase.java +++ b/java/typeMigration/test/com/intellij/refactoring/TypeMigrationTestBase.java @@ -168,10 +168,8 @@ public abstract class TypeMigrationTestBase extends MultiFileTestCase { final UsageInfo[] usages = pr.findUsages(); final String report = pr.getLabeler().getMigrationReport(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - pr.performRefactoring(usages); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + pr.performRefactoring(usages); }); diff --git a/json/src/com/intellij/json/formatter/JsonBlock.java b/json/src/com/intellij/json/formatter/JsonBlock.java index 0f12cce18790..d0c09fd790d1 100644 --- a/json/src/com/intellij/json/formatter/JsonBlock.java +++ b/json/src/com/intellij/json/formatter/JsonBlock.java @@ -94,14 +94,11 @@ public class JsonBlock implements ASTBlock { @Override public List getSubBlocks() { if (mySubBlocks == null) { - mySubBlocks = ContainerUtil.mapNotNull(myNode.getChildren(null), new Function() { - @Override - public Block fun(ASTNode node) { - if (isWhitespaceOrEmpty(node)) { - return null; - } - return makeSubBlock(node); + mySubBlocks = ContainerUtil.mapNotNull(myNode.getChildren(null), node -> { + if (isWhitespaceOrEmpty(node)) { + return null; } + return makeSubBlock(node); }); } return mySubBlocks; diff --git a/json/src/com/intellij/json/structureView/JsonStructureViewElement.java b/json/src/com/intellij/json/structureView/JsonStructureViewElement.java index f7a350ef9a7a..8d42758840c5 100644 --- a/json/src/com/intellij/json/structureView/JsonStructureViewElement.java +++ b/json/src/com/intellij/json/structureView/JsonStructureViewElement.java @@ -66,26 +66,20 @@ public class JsonStructureViewElement implements StructureViewTreeElement { } if (value instanceof JsonObject) { final JsonObject object = ((JsonObject)value); - return ContainerUtil.map2Array(object.getPropertyList(), TreeElement.class, new Function() { - @Override - public TreeElement fun(JsonProperty property) { - return new JsonStructureViewElement(property); - } + return ContainerUtil.map2Array(object.getPropertyList(), TreeElement.class, (Function)property -> { + return new JsonStructureViewElement(property); }); } else if (value instanceof JsonArray) { final JsonArray array = (JsonArray)value; - final List childObjects = ContainerUtil.mapNotNull(array.getValueList(), new Function() { - @Override - public TreeElement fun(JsonValue value) { - if (value instanceof JsonObject && !((JsonObject)value).getPropertyList().isEmpty()) { - return new JsonStructureViewElement(value); - } - else if (value instanceof JsonArray && PsiTreeUtil.findChildOfType(value, JsonProperty.class) != null) { - return new JsonStructureViewElement(value); - } - return null; + final List childObjects = ContainerUtil.mapNotNull(array.getValueList(), value1 -> { + if (value1 instanceof JsonObject && !((JsonObject)value1).getPropertyList().isEmpty()) { + return new JsonStructureViewElement(value1); } + else if (value1 instanceof JsonArray && PsiTreeUtil.findChildOfType(value1, JsonProperty.class) != null) { + return new JsonStructureViewElement(value1); + } + return null; }); return ArrayUtil.toObjectArray(childObjects, TreeElement.class); } diff --git a/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurable.java b/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurable.java index b490a58c1119..12c5c14109f7 100644 --- a/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurable.java +++ b/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurable.java @@ -43,14 +43,11 @@ public class JsonSchemaMappingsConfigurable extends MasterDetailsComponent imple @NonNls public static final String SETTINGS_JSON_SCHEMA = "settings.json.schema"; public static final String JSON_SCHEMA_MAPPINGS = "JSON Schema"; - private final static Comparator COMPARATOR = new Comparator() { - @Override - public int compare(JsonSchemaMappingsConfigurationBase.SchemaInfo o1, JsonSchemaMappingsConfigurationBase.SchemaInfo o2) { - if (o1.isApplicationLevel() != o2.isApplicationLevel()) { - return o1.isApplicationLevel() ? -1 : 1; - } - return o1.getName().compareToIgnoreCase(o2.getName()); + private final static Comparator COMPARATOR = (o1, o2) -> { + if (o1.isApplicationLevel() != o2.isApplicationLevel()) { + return o1.isApplicationLevel() ? -1 : 1; } + return o1.getName().compareToIgnoreCase(o2.getName()); }; public static final String READ_JSON_SCHEMA = "Read JSON Schema"; public static final String ADD_PROJECT_SCHEMA = "Add Project Schema"; @@ -58,12 +55,9 @@ public class JsonSchemaMappingsConfigurable extends MasterDetailsComponent imple @Nullable private Project myProject; - private Runnable myTreeUpdater = new Runnable() { - @Override - public void run() { - TREE_UPDATER.run(); - updateWarningText(); - } + private Runnable myTreeUpdater = () -> { + TREE_UPDATER.run(); + updateWarningText(); }; public JsonSchemaMappingsConfigurable(@Nullable final Project project) { @@ -282,14 +276,11 @@ public class JsonSchemaMappingsConfigurable extends MasterDetailsComponent imple @Override protected Comparator getNodeComparator() { - return new Comparator() { - @Override - public int compare(MyNode o1, MyNode o2) { - if (o1.getConfigurable() instanceof JsonSchemaConfigurable && o2.getConfigurable() instanceof JsonSchemaConfigurable) { - return COMPARATOR.compare(getSchemaInfo(o1), getSchemaInfo(o2)); - } - return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); + return (o1, o2) -> { + if (o1.getConfigurable() instanceof JsonSchemaConfigurable && o2.getConfigurable() instanceof JsonSchemaConfigurable) { + return COMPARATOR.compare(getSchemaInfo(o1), getSchemaInfo(o2)); } + return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); }; } diff --git a/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurationBase.java b/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurationBase.java index 486ab1dd97d9..8ce039d38756 100644 --- a/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurationBase.java +++ b/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsConfigurationBase.java @@ -22,13 +22,10 @@ import java.util.*; * @author Irina.Chernushina on 2/2/2016. */ public class JsonSchemaMappingsConfigurationBase implements PersistentStateComponent { - private final static Comparator COMPARATOR = new Comparator() { - @Override - public int compare(Item o1, Item o2) { - if (o1.isPattern() != o2.isPattern()) return o1.isPattern() ? -1 : 1; - if (o1.isDirectory() != o2.isDirectory()) return o1.isDirectory() ? -1 : 1; - return o1.getPath().compareToIgnoreCase(o2.getPath()); - } + private final static Comparator COMPARATOR = (o1, o2) -> { + if (o1.isPattern() != o2.isPattern()) return o1.isPattern() ? -1 : 1; + if (o1.isDirectory() != o2.isDirectory()) return o1.isDirectory() ? -1 : 1; + return o1.getPath().compareToIgnoreCase(o2.getPath()); }; @Tag("state") @AbstractCollection(surroundWithTag = false) protected final Map myState = new TreeMap(); diff --git a/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsView.java b/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsView.java index 3037c91957fc..dc20f85fc5b0 100644 --- a/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsView.java +++ b/json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsView.java @@ -93,16 +93,13 @@ public class JsonSchemaMappingsView implements Disposable { SwingHelper.installFileCompletionAndBrowseDialog(myProject, mySchemaField, JsonBundle.message("json.schema.add.schema.chooser.title"), FileChooserDescriptorFactory.createSingleFileDescriptor()); attachNavigateToSchema(); - myError = SwingHelper.createHtmlLabel("Warning: conflicting mappings. Show details", null, new Consumer() { - @Override - public void consume(String s) { - final BalloonBuilder builder = JBPopupFactory.getInstance(). - createHtmlTextBalloonBuilder(myErrorText, UIUtil.getBalloonWarningIcon(), MessageType.WARNING.getPopupBackground(), null); - builder.setDisposable(JsonSchemaMappingsView.this); - builder.setHideOnClickOutside(true); - builder.setCloseButtonEnabled(true); - builder.createBalloon().showInCenterOf(myError); - } + myError = SwingHelper.createHtmlLabel("Warning: conflicting mappings. Show details", null, s -> { + final BalloonBuilder builder = JBPopupFactory.getInstance(). + createHtmlTextBalloonBuilder(myErrorText, UIUtil.getBalloonWarningIcon(), MessageType.WARNING.getPopupBackground(), null); + builder.setDisposable(JsonSchemaMappingsView.this); + builder.setHideOnClickOutside(true); + builder.setCloseButtonEnabled(true); + builder.createBalloon().showInCenterOf(myError); }); final FormBuilder builder = FormBuilder.createFormBuilder(); diff --git a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java index 79728a6ab629..0fef56318897 100644 --- a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java +++ b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java @@ -94,19 +94,9 @@ public class JsonSchemaImportedProviderFactory implements JsonSchemaProviderFact } if (pattern.isDirectory()) { - myPatterns.add(new Processor() { - @Override - public boolean process(VirtualFile file) { - return VfsUtil.isAncestor(relativeFile, file, true); - } - }); + myPatterns.add(file12 -> VfsUtil.isAncestor(relativeFile, file12, true)); } else { - myPatterns.add(new Processor() { - @Override - public boolean process(VirtualFile file) { - return relativeFile.equals(file); - } - }); + myPatterns.add(file1 -> relativeFile.equals(file1)); } } } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java b/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java index b56d003a1764..9564ab69c04a 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java @@ -251,11 +251,8 @@ class JsonBySchemaObjectAnnotator implements Annotator { for (Object object : objects) { if (object.toString().equalsIgnoreCase(text)) return true; } - error("Value should be one of: [" + StringUtil.join(objects, new Function() { - @Override - public String fun(Object o) { - return o.toString(); - } + error("Value should be one of: [" + StringUtil.join(objects, o -> { + return o.toString(); }, ", ") + "]", value); return false; } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectCompletionContributor.java b/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectCompletionContributor.java index d3109afb2f57..2164713d4721 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectCompletionContributor.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectCompletionContributor.java @@ -61,12 +61,7 @@ class JsonBySchemaObjectCompletionContributor extends CompletionContributor { public static List getCompletionVariants(@NotNull final JsonSchemaObject schema, @NotNull final PsiElement position) { final List result = new ArrayList(); - new Worker(schema, position, new Consumer() { - @Override - public void consume(LookupElement element) { - result.add(element); - } - }).work(); + new Worker(schema, position, element -> result.add(element)).work(); return result; } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaConflictNotificationProvider.java b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaConflictNotificationProvider.java index fb0da093362f..b41ad2fad000 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaConflictNotificationProvider.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaConflictNotificationProvider.java @@ -74,12 +74,9 @@ public class JsonSchemaConflictNotificationProvider extends EditorNotifications. } }; panel.setText(message); - panel.createActionLabel("Edit JSON Schema Mappings", new Runnable() { - @Override - public void run() { - ShowSettingsUtil.getInstance().editConfigurable(myProject, new JsonSchemaMappingsConfigurable(myProject)); - EditorNotifications.getInstance(myProject).updateNotifications(file); - } + panel.createActionLabel("Edit JSON Schema Mappings", () -> { + ShowSettingsUtil.getInstance().editConfigurable(myProject, new JsonSchemaMappingsConfigurable(myProject)); + EditorNotifications.getInstance(myProject).updateNotifications(file); }); return panel; } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaExportedDefinitions.java b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaExportedDefinitions.java index 89d3bcee9cb8..d36ef084f86f 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaExportedDefinitions.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaExportedDefinitions.java @@ -75,14 +75,11 @@ public class JsonSchemaExportedDefinitions { private void ensureInitialized() { synchronized (myLock) { if (myInitialized && !myDirty) return; - mySchemasIterator.consume(new PairConsumer>() { - @Override - public void consume(VirtualFile key, NullableLazyValue value) { - if (!myInitialized || !myId2Key.containsValue(key)) { - final JsonSchemaObject object = value.getValue(); - if (object != null) { - JsonSchemaReader.registerObjectsExportedDefinitions(key, JsonSchemaExportedDefinitions.this, object); - } + mySchemasIterator.consume((key, value) -> { + if (!myInitialized || !myId2Key.containsValue(key)) { + final JsonSchemaObject object = value.getValue(); + if (object != null) { + JsonSchemaReader.registerObjectsExportedDefinitions(key, JsonSchemaExportedDefinitions.this, object); } } }); diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java index b6c441ede44e..c77bfde24ea3 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java @@ -82,18 +82,15 @@ public class JsonSchemaReader { if (!StringUtil.isEmptyOrSpaces(id)) { id = id.endsWith("#") ? id.substring(0, id.length() - 1) : id; final PairConvertor, Map> convertor = - new PairConvertor,Map>() { - @Override - public Map convert(String s, Map map) { - final Map converted = new HashMap<>(); - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - key = key.startsWith("/") ? key.substring(1) : key; - converted.put(s + key, entry.getValue()); - } - return converted; + (s, map) -> { + final Map converted = new HashMap<>(); + for (Map.Entry entry : map.entrySet()) { + String key1 = entry.getKey(); + key1 = key1.startsWith("/") ? key1.substring(1) : key1; + converted.put(s + key1, entry.getValue()); } - }; + return converted; + }; final HashMap map = new HashMap<>(); final Map definitions = object.getDefinitions(); @@ -306,19 +303,16 @@ public class JsonSchemaReader { } private ThrowablePairConsumer createDefault() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() == JsonToken.BEGIN_OBJECT) { - object.setDefault(readInnerObject(in)); - } else if (in.peek() == JsonToken.NUMBER) { - object.setDefault(in.nextDouble()); - } else if (in.peek() == JsonToken.STRING) { - object.setDefault(in.nextString()); - } else if (in.peek() == JsonToken.BOOLEAN) { - object.setDefault(in.nextBoolean()); - } else in.skipValue(); - } + return (in, object) -> { + if (in.peek() == JsonToken.BEGIN_OBJECT) { + object.setDefault(readInnerObject(in)); + } else if (in.peek() == JsonToken.NUMBER) { + object.setDefault(in.nextDouble()); + } else if (in.peek() == JsonToken.STRING) { + object.setDefault(in.nextString()); + } else if (in.peek() == JsonToken.BOOLEAN) { + object.setDefault(in.nextBoolean()); + } else in.skipValue(); }; } @@ -332,13 +326,10 @@ public class JsonSchemaReader { } private ThrowablePairConsumer createNot() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() == JsonToken.BEGIN_OBJECT) { - object.setNot(readInnerObject(in)); - } else in.skipValue(); - } + return (in, object) -> { + if (in.peek() == JsonToken.BEGIN_OBJECT) { + object.setNot(readInnerObject(in)); + } else in.skipValue(); }; } @@ -392,127 +383,112 @@ public class JsonSchemaReader { } private ThrowablePairConsumer createEnum() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() != JsonToken.BEGIN_ARRAY) { - in.skipValue(); - return; - } - final ArrayList objects = new ArrayList(); - in.beginArray(); - while (in.peek() != JsonToken.END_ARRAY) { - if (in.peek() == JsonToken.STRING) objects.add("\"" + in.nextString() + "\""); - else if (in.peek() == JsonToken.NUMBER) objects.add(in.nextInt()); // parse as integer here makes much more sense - else if (in.peek() == JsonToken.BOOLEAN) objects.add(in.nextBoolean()); - else in.skipValue(); - } - in.endArray(); - object.setEnum(objects); + return (in, object) -> { + if (in.peek() != JsonToken.BEGIN_ARRAY) { + in.skipValue(); + return; } + final ArrayList objects = new ArrayList(); + in.beginArray(); + while (in.peek() != JsonToken.END_ARRAY) { + if (in.peek() == JsonToken.STRING) objects.add("\"" + in.nextString() + "\""); + else if (in.peek() == JsonToken.NUMBER) objects.add(in.nextInt()); // parse as integer here makes much more sense + else if (in.peek() == JsonToken.BOOLEAN) objects.add(in.nextBoolean()); + else in.skipValue(); + } + in.endArray(); + object.setEnum(objects); }; } private ThrowablePairConsumer createDependencies() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() != JsonToken.BEGIN_OBJECT) { + return (in, object) -> { + if (in.peek() != JsonToken.BEGIN_OBJECT) { + in.skipValue(); + return; + } + final HashMap> propertyDependencies = new HashMap>(); + final HashMap schemaDependencies = new HashMap(); + in.beginObject(); + while (in.peek() != JsonToken.END_OBJECT) { + if (in.peek() != JsonToken.NAME) { in.skipValue(); - return; + continue; } - final HashMap> propertyDependencies = new HashMap>(); - final HashMap schemaDependencies = new HashMap(); - in.beginObject(); - while (in.peek() != JsonToken.END_OBJECT) { - if (in.peek() != JsonToken.NAME) { - in.skipValue(); - continue; + final String name = in.nextName(); + if (in.peek() == JsonToken.BEGIN_ARRAY) { + final List members = new ArrayList(); + in.beginArray(); + while (in.peek() != JsonToken.END_ARRAY) { + if (in.peek() == JsonToken.STRING) { + members.add(in.nextString()); + } else in.skipValue(); } - final String name = in.nextName(); - if (in.peek() == JsonToken.BEGIN_ARRAY) { - final List members = new ArrayList(); - in.beginArray(); - while (in.peek() != JsonToken.END_ARRAY) { - if (in.peek() == JsonToken.STRING) { - members.add(in.nextString()); - } else in.skipValue(); - } - in.endArray(); - propertyDependencies.put(name, members); - } else if (in.peek() == JsonToken.BEGIN_OBJECT) { - schemaDependencies.put(name, readInnerObject(in)); - } else in.skipValue(); - } - in.endObject(); - if (! propertyDependencies.isEmpty()) { - object.setPropertyDependencies(propertyDependencies); - } - if (! schemaDependencies.isEmpty()) { - object.setSchemaDependencies(schemaDependencies); - } + in.endArray(); + propertyDependencies.put(name, members); + } else if (in.peek() == JsonToken.BEGIN_OBJECT) { + schemaDependencies.put(name, readInnerObject(in)); + } else in.skipValue(); + } + in.endObject(); + if (! propertyDependencies.isEmpty()) { + object.setPropertyDependencies(propertyDependencies); + } + if (! schemaDependencies.isEmpty()) { + object.setSchemaDependencies(schemaDependencies); } }; } private ThrowablePairConsumer createPatternProperties() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() != JsonToken.BEGIN_OBJECT) { - in.skipValue(); - return; - } - in.beginObject(); - final HashMap properties = new HashMap(); - while (in.peek() != JsonToken.END_OBJECT) { - if (in.peek() == JsonToken.NAME) { - final String name = in.nextName(); - if (in.peek() == JsonToken.BEGIN_OBJECT) { - properties.put(name, readInnerObject(in)); - } else in.skipValue(); - } else in.skipValue(); - } - object.setPatternProperties(properties); - in.endObject(); + return (in, object) -> { + if (in.peek() != JsonToken.BEGIN_OBJECT) { + in.skipValue(); + return; } + in.beginObject(); + final HashMap properties = new HashMap(); + while (in.peek() != JsonToken.END_OBJECT) { + if (in.peek() == JsonToken.NAME) { + final String name = in.nextName(); + if (in.peek() == JsonToken.BEGIN_OBJECT) { + properties.put(name, readInnerObject(in)); + } else in.skipValue(); + } else in.skipValue(); + } + object.setPatternProperties(properties); + in.endObject(); }; } private ThrowablePairConsumer createAdditionalProperties() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() == JsonToken.BOOLEAN) { - object.setAdditionalPropertiesAllowed(in.nextBoolean()); - } else if (in.peek() == JsonToken.BEGIN_OBJECT) { - object.setAdditionalPropertiesSchema(readInnerObject(in)); - } else { - in.skipValue(); - } + return (in, object) -> { + if (in.peek() == JsonToken.BOOLEAN) { + object.setAdditionalPropertiesAllowed(in.nextBoolean()); + } else if (in.peek() == JsonToken.BEGIN_OBJECT) { + object.setAdditionalPropertiesSchema(readInnerObject(in)); + } else { + in.skipValue(); } }; } private ThrowablePairConsumer createRequired() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() == JsonToken.BEGIN_ARRAY) { - final ArrayList required = new ArrayList(); - in.beginArray(); - while (in.peek() != JsonToken.END_ARRAY) { - if (in.peek() == JsonToken.STRING) { - required.add(in.nextString()); - } else { - in.skipValue(); - } + return (in, object) -> { + if (in.peek() == JsonToken.BEGIN_ARRAY) { + final ArrayList required = new ArrayList(); + in.beginArray(); + while (in.peek() != JsonToken.END_ARRAY) { + if (in.peek() == JsonToken.STRING) { + required.add(in.nextString()); + } else { + in.skipValue(); } - in.endArray(); - object.setRequired(required); - } else { - in.skipValue(); } + in.endArray(); + object.setRequired(required); + } else { + in.skipValue(); } }; } @@ -563,37 +539,31 @@ public class JsonSchemaReader { } private ThrowablePairConsumer createItems() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() == JsonToken.BEGIN_OBJECT) { - object.setItemsSchema(readInnerObject(in)); - } else if (in.peek() == JsonToken.BEGIN_ARRAY) { - in.beginArray(); - final List list = new ArrayList(); - while (in.peek() != JsonToken.END_ARRAY) { - if (in.peek() == JsonToken.BEGIN_OBJECT) { - list.add(readInnerObject(in)); - } else in.skipValue(); - } - in.endArray(); - object.setItemsSchemaList(list); + return (in, object) -> { + if (in.peek() == JsonToken.BEGIN_OBJECT) { + object.setItemsSchema(readInnerObject(in)); + } else if (in.peek() == JsonToken.BEGIN_ARRAY) { + in.beginArray(); + final List list = new ArrayList(); + while (in.peek() != JsonToken.END_ARRAY) { + if (in.peek() == JsonToken.BEGIN_OBJECT) { + list.add(readInnerObject(in)); + } else in.skipValue(); } + in.endArray(); + object.setItemsSchemaList(list); } }; } private ThrowablePairConsumer createAdditionalItems() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - if (in.peek() == JsonToken.BOOLEAN) { - object.setAdditionalItemsAllowed(in.nextBoolean()); - } else if (in.peek() == JsonToken.BEGIN_OBJECT) { - object.setAdditionalItemsSchema(readInnerObject(in)); - } else { - in.skipValue(); - } + return (in, object) -> { + if (in.peek() == JsonToken.BOOLEAN) { + object.setAdditionalItemsAllowed(in.nextBoolean()); + } else if (in.peek() == JsonToken.BEGIN_OBJECT) { + object.setAdditionalItemsSchema(readInnerObject(in)); + } else { + in.skipValue(); } }; } @@ -714,34 +684,28 @@ public class JsonSchemaReader { } private ThrowablePairConsumer createPropertiesConsumer() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - in.beginObject(); - while (in.peek() == JsonToken.NAME) { - final String name = in.nextName(); - object.getProperties().put(name, readInnerObject(in)); - } - in.endObject(); + return (in, object) -> { + in.beginObject(); + while (in.peek() == JsonToken.NAME) { + final String name = in.nextName(); + object.getProperties().put(name, readInnerObject(in)); } + in.endObject(); }; } @NotNull private ThrowablePairConsumer createDefinitionsConsumer() { - return new ThrowablePairConsumer() { - @Override - public void consume(JsonReader in, JsonSchemaObject object) throws IOException { - final Map map = new HashMap(); - in.beginObject(); - while (in.peek() == JsonToken.NAME) { - final String name = in.nextName(); - map.put(name, readInnerObject(in)); - } - in.endObject(); - if (! map.isEmpty()) { - object.setDefinitions(map); - } + return (in, object) -> { + final Map map = new HashMap(); + in.beginObject(); + while (in.peek() == JsonToken.NAME) { + final String name = in.nextName(); + map.put(name, readInnerObject(in)); + } + in.endObject(); + if (! map.isEmpty()) { + object.setDefinitions(map); } }; } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java index 25afa6561dda..23731a4816aa 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java @@ -54,12 +54,7 @@ public class JsonSchemaServiceImpl implements JsonSchemaServiceEx { myLock = new Object(); myProject = project; myDefinitions = new JsonSchemaExportedDefinitions( - new Consumer>>() { - @Override - public void consume(PairConsumer> consumer) { - iterateSchemas(consumer); - } - }); + consumer -> iterateSchemas(consumer)); ApplicationManager .getApplication().getMessageBus().connect(project).subscribe(VirtualFileManager.VFS_CHANGES, new JsonSchemaVfsListener(project, this)); ensureSchemaFiles(project); @@ -159,12 +154,8 @@ public class JsonSchemaServiceImpl implements JsonSchemaServiceEx { public List> getMatchingSchemaDescriptors(@Nullable VirtualFile file) { final List wrappers = getWrappers(file); if (wrappers == null || wrappers.isEmpty()) return null; - return ContainerUtil.map(wrappers, new NotNullFunction>() { - @NotNull - @Override - public Pair fun(JsonSchemaObjectCodeInsightWrapper wrapper) { - return Pair.create(wrapper.isUserSchema(), wrapper.getName()); - } + return ContainerUtil.map(wrappers, (NotNullFunction>)wrapper -> { + return Pair.create(wrapper.isUserSchema(), wrapper.getName()); }); } diff --git a/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaCrossReferencesTest.java b/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaCrossReferencesTest.java index d37f76a83e71..3d0299d77121 100644 --- a/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaCrossReferencesTest.java +++ b/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaCrossReferencesTest.java @@ -168,13 +168,10 @@ public class JsonSchemaCrossReferencesTest extends CompletionTestCase { int start = document.getText().indexOf(str); Assert.assertTrue(start > 0); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(start, start + str.length(), "\"enum\": [\"one1\", \"two1\"]"); + ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(start, start + str.length(), "\"enum\": [\"one1\", \"two1\"]"); - fileDocumentManager.saveAllDocuments(); - } + fileDocumentManager.saveAllDocuments(); }); LookupImpl lookup = getActiveLookup(); if (lookup != null) lookup.hide(); @@ -220,11 +217,8 @@ public class JsonSchemaCrossReferencesTest extends CompletionTestCase { instance.addSchema(inherited); try { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myFileTypeManager.associatePattern(JsonSchemaFileType.INSTANCE, "*Schema.json"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myFileTypeManager.associatePattern(JsonSchemaFileType.INSTANCE, "*Schema.json"); }); int offset = myEditor.getCaretModel().getPrimaryCaret().getOffset(); final PsiReference referenceAt = myFile.findReferenceAt(offset); @@ -233,11 +227,8 @@ public class JsonSchemaCrossReferencesTest extends CompletionTestCase { Assert.assertNotNull(resolve); Assert.assertEquals("\"baseEnum\"", resolve.getText()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myFileTypeManager.removeAssociatedExtension(JsonSchemaFileType.INSTANCE, "*Schema.json"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myFileTypeManager.removeAssociatedExtension(JsonSchemaFileType.INSTANCE, "*Schema.json"); }); } finally { container.unregisterComponent(key); @@ -275,11 +266,8 @@ public class JsonSchemaCrossReferencesTest extends CompletionTestCase { instance.addSchema(inherited); try { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myFileTypeManager.associatePattern(JsonSchemaFileType.INSTANCE, "*Schema.json"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myFileTypeManager.associatePattern(JsonSchemaFileType.INSTANCE, "*Schema.json"); }); int offset = myEditor.getCaretModel().getPrimaryCaret().getOffset(); final PsiReference referenceAt = myFile.findReferenceAt(offset); @@ -288,11 +276,8 @@ public class JsonSchemaCrossReferencesTest extends CompletionTestCase { Assert.assertNotNull(resolve); Assert.assertEquals("\"enum\"", resolve.getText()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myFileTypeManager.removeAssociatedExtension(JsonSchemaFileType.INSTANCE, "*Schema.json"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myFileTypeManager.removeAssociatedExtension(JsonSchemaFileType.INSTANCE, "*Schema.json"); }); } finally { container.unregisterComponent(key); diff --git a/json/tests/test/com/jetbrains/jsonSchema/impl/JsonBySchemaCompletionTest.java b/json/tests/test/com/jetbrains/jsonSchema/impl/JsonBySchemaCompletionTest.java index c9a2be951f0d..ad8271b78392 100644 --- a/json/tests/test/com/jetbrains/jsonSchema/impl/JsonBySchemaCompletionTest.java +++ b/json/tests/test/com/jetbrains/jsonSchema/impl/JsonBySchemaCompletionTest.java @@ -113,12 +113,7 @@ public class JsonBySchemaCompletionTest extends CompletionTestCase { Assert.assertNotNull(schemaObject); final List foundVariants = JsonBySchemaObjectCompletionContributor.getCompletionVariants(schemaObject, element); - Collections.sort(foundVariants, new Comparator() { - @Override - public int compare(LookupElement o1, LookupElement o2) { - return o1.getLookupString().compareTo(o2.getLookupString()); - } - }); + Collections.sort(foundVariants, (o1, o2) -> o1.getLookupString().compareTo(o2.getLookupString())); myItems = foundVariants.toArray(new LookupElement[foundVariants.size()]); assertStringItems(variants); } diff --git a/json/tests/test/com/jetbrains/jsonSchema/impl/JsonSchemaReadTest.java b/json/tests/test/com/jetbrains/jsonSchema/impl/JsonSchemaReadTest.java index 220077fea6b5..73a6313a45db 100644 --- a/json/tests/test/com/jetbrains/jsonSchema/impl/JsonSchemaReadTest.java +++ b/json/tests/test/com/jetbrains/jsonSchema/impl/JsonSchemaReadTest.java @@ -86,20 +86,17 @@ public class JsonSchemaReadTest { final AtomicReference error = new AtomicReference<>(); final Semaphore semaphore = new Semaphore(); semaphore.down(); - final Thread thread = new Thread(new Runnable() { - @Override - public void run() { - final JsonSchemaReader reader = new JsonSchemaReader(null); - try { - reader.read(new FileReader(file), null); - done.set(true); - } - catch (IOException e) { - error.set(e); - } - finally { - semaphore.up(); - } + final Thread thread = new Thread(() -> { + final JsonSchemaReader reader = new JsonSchemaReader(null); + try { + reader.read(new FileReader(file), null); + done.set(true); + } + catch (IOException e) { + error.set(e); + } + finally { + semaphore.up(); } }, getClass().getName() + ": read test json schema " + file.getName()); thread.setDaemon(true); diff --git a/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java b/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java index 44e5509f315e..3d1892d4d058 100644 --- a/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java +++ b/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java @@ -277,17 +277,14 @@ public class AnalysisScope { final boolean needReadAction = !ApplicationManager.getApplication().isReadAccessAllowed(); final PsiManager psiManager = PsiManager.getInstance(myProject); final FileIndex fileIndex = getFileIndex(); - accept(new Processor() { - @Override - public boolean process(VirtualFile file) { - if (file.isDirectory()) return true; - if (ProjectCoreUtil.isProjectOrWorkspaceFile(file)) return true; - if (fileIndex.isInContent(file) && !isFiltered(file, fileIndex) - && !GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, myProject)) { - return processFile(file, visitor, psiManager, needReadAction, clearResolveCache); - } - return true; + accept(file -> { + if (file.isDirectory()) return true; + if (ProjectCoreUtil.isProjectOrWorkspaceFile(file)) return true; + if (fileIndex.isInContent(file) && !isFiltered(file, fileIndex) + && !GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, myProject)) { + return processFile(file, visitor, psiManager, needReadAction, clearResolveCache); } + return true; }); } @@ -381,12 +378,7 @@ public class AnalysisScope { @NotNull final PsiManager psiManager, final boolean needReadAction, final boolean clearResolveCache) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - doProcessFile(visitor, psiManager, vFile, clearResolveCache); - } - }; + final Runnable runnable = () -> doProcessFile(visitor, psiManager, vFile, clearResolveCache); if (needReadAction && !ApplicationManager.getApplication().isDispatchThread()) { commitAndRunInSmartMode(runnable, psiManager.getProject()); } @@ -494,11 +486,8 @@ public class AnalysisScope { return AnalysisScopeBundle.message("scope.option.module", pathToName(myModule.getModuleFilePath())); case MODULES: - String modules = StringUtil.join(myModules, new Function() { - @Override - public String fun(@NotNull final Module module) { - return pathToName(module.getModuleFilePath()); - } + String modules = StringUtil.join(myModules, module -> { + return pathToName(module.getModuleFilePath()); }, ", "); return AnalysisScopeBundle.message("scope.module.list", modules, Integer.valueOf(myModules.size())); @@ -528,12 +517,8 @@ public class AnalysisScope { return AnalysisScopeBundle.message("scope.option.module", myModule.getName()); case MODULES: - String modules = StringUtil.join(myModules, new Function() { - @Override - @NotNull - public String fun(@NotNull final Module module) { - return module.getName(); - } + String modules = StringUtil.join(myModules, module -> { + return module.getName(); }, ", "); return AnalysisScopeBundle.message("scope.module.list", modules, Integer.valueOf(myModules.size())); diff --git a/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionActionBean.java b/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionActionBean.java index cbcabc3209de..1a32fbf13797 100644 --- a/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionActionBean.java +++ b/platform/analysis-api/src/com/intellij/codeInsight/intention/IntentionActionBean.java @@ -54,11 +54,8 @@ public class IntentionActionBean extends CustomLoadingExtensionPointBean { final String[] keys = categoryKey.split("/"); if (keys.length > 1) { - return ContainerUtil.map2Array(keys, String.class, new Function() { - @Override - public String fun(final String s) { - return CommonBundle.message(bundle, s); - } + return ContainerUtil.map2Array(keys, String.class, s -> { + return CommonBundle.message(bundle, s); }); } diff --git a/platform/analysis-api/src/com/intellij/codeInspection/CommonProblemDescriptor.java b/platform/analysis-api/src/com/intellij/codeInspection/CommonProblemDescriptor.java index da9f4989871a..9e51862f024d 100644 --- a/platform/analysis-api/src/com/intellij/codeInspection/CommonProblemDescriptor.java +++ b/platform/analysis-api/src/com/intellij/codeInspection/CommonProblemDescriptor.java @@ -28,13 +28,7 @@ import org.jetbrains.annotations.Nullable; */ public interface CommonProblemDescriptor { CommonProblemDescriptor[] EMPTY_ARRAY = new CommonProblemDescriptor[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public CommonProblemDescriptor[] create(final int count) { - return count == 0 ? EMPTY_ARRAY : new CommonProblemDescriptor[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new CommonProblemDescriptor[count]; /** * Returns the template from which the problem description is built. The template may diff --git a/platform/analysis-api/src/com/intellij/psi/search/GlobalSearchScopesCore.java b/platform/analysis-api/src/com/intellij/psi/search/GlobalSearchScopesCore.java index 82e13826f0ae..5a88cc4aa779 100644 --- a/platform/analysis-api/src/com/intellij/psi/search/GlobalSearchScopesCore.java +++ b/platform/analysis-api/src/com/intellij/psi/search/GlobalSearchScopesCore.java @@ -402,12 +402,7 @@ public class GlobalSearchScopesCore { VirtualFile root = myDirectories[0]; return "Directory '" + root.getName() + "'"; } - return "Directories " + StringUtil.join(myDirectories, new Function() { - @Override - public String fun(VirtualFile file) { - return "'" + file.getName() + "'"; - } - }, ", "); + return "Directories " + StringUtil.join(myDirectories, file -> "'" + file.getName() + "'", ", "); } } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/InspectionProfileConvertor.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/InspectionProfileConvertor.java index 9e264015df55..d604e648f5e8 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/InspectionProfileConvertor.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/InspectionProfileConvertor.java @@ -135,11 +135,8 @@ public class InspectionProfileConvertor { return; } - File[] files = profileDirectory.listFiles(new FileFilter() { - @Override - public boolean accept(@NotNull File pathname) { - return pathname.getPath().endsWith(File.separator + DEFAULT_XML); - } + File[] files = profileDirectory.listFiles(pathname -> { + return pathname.getPath().endsWith(File.separator + DEFAULT_XML); }); if (files == null || files.length != 1 || !files[0].isFile()) { return; diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerEx.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerEx.java index c61e857c4a71..814b19092bda 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerEx.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerEx.java @@ -50,16 +50,13 @@ public abstract class DaemonCodeAnalyzerEx extends DaemonCodeAnalyzer { final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project); MarkupModelEx model = (MarkupModelEx)DocumentMarkupModel.forDocument(document, project, true); - return model.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx marker) { - Object tt = marker.getErrorStripeTooltip(); - if (!(tt instanceof HighlightInfo)) return true; - HighlightInfo info = (HighlightInfo)tt; - return minSeverity != null && severityRegistrar.compare(info.getSeverity(), minSeverity) < 0 - || info.highlighter == null - || processor.process(info); - } + return model.processRangeHighlightersOverlappingWith(startOffset, endOffset, marker -> { + Object tt = marker.getErrorStripeTooltip(); + if (!(tt instanceof HighlightInfo)) return true; + HighlightInfo info = (HighlightInfo)tt; + return minSeverity != null && severityRegistrar.compare(info.getSeverity(), minSeverity) < 0 + || info.highlighter == null + || processor.process(info); }); } @@ -73,16 +70,13 @@ public abstract class DaemonCodeAnalyzerEx extends DaemonCodeAnalyzer { final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project); MarkupModelEx model = (MarkupModelEx)DocumentMarkupModel.forDocument(document, project, true); - return model.processRangeHighlightersOutside(startOffset, endOffset, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx marker) { - Object tt = marker.getErrorStripeTooltip(); - if (!(tt instanceof HighlightInfo)) return true; - HighlightInfo info = (HighlightInfo)tt; - return minSeverity != null && severityRegistrar.compare(info.getSeverity(), minSeverity) < 0 - || info.highlighter == null - || processor.process(info); - } + return model.processRangeHighlightersOutside(startOffset, endOffset, marker -> { + Object tt = marker.getErrorStripeTooltip(); + if (!(tt instanceof HighlightInfo)) return true; + HighlightInfo info = (HighlightInfo)tt; + return minSeverity != null && severityRegistrar.compare(info.getSeverity(), minSeverity) < 0 + || info.highlighter == null + || processor.process(info); }); } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitorBasedInspection.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitorBasedInspection.java index aab182e24a2d..ea00db069300 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitorBasedInspection.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitorBasedInspection.java @@ -168,16 +168,12 @@ public abstract class DefaultHighlightVisitorBasedInspection extends GlobalSimpl List passes = passRegistrarEx.instantiateMainPasses(file, document, HighlightInfoProcessor.getEmpty()); List gpasses = ContainerUtil.collect(passes.iterator(), FilteringIterator.instanceOf(GeneralHighlightingPass.class)); for (final GeneralHighlightingPass gpass : gpasses) { - gpass.setHighlightVisitorProducer(new NotNullProducer() { - @NotNull - @Override - public HighlightVisitor[] produce() { - gpass.incVisitorUsageCount(1); + gpass.setHighlightVisitorProducer(() -> { + gpass.incVisitorUsageCount(1); - HighlightVisitor visitor = new DefaultHighlightVisitor(project, highlightErrorElements, runAnnotators, true, - ServiceManager.getService(project, CachedAnnotators.class)); - return new HighlightVisitor[]{visitor}; - } + HighlightVisitor visitor = new DefaultHighlightVisitor(project, highlightErrorElements, runAnnotators, true, + ServiceManager.getService(project, CachedAnnotators.class)); + return new HighlightVisitor[]{visitor}; }); } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/GeneralHighlightingPass.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/GeneralHighlightingPass.java index cc4afae407eb..76c049b027f0 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/GeneralHighlightingPass.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/GeneralHighlightingPass.java @@ -80,13 +80,7 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP protected volatile boolean myHasErrorElement; private volatile boolean myErrorFound; protected final EditorColorsScheme myGlobalScheme; - private volatile NotNullProducer myHighlightVisitorProducer = new NotNullProducer() { - @NotNull - @Override - public HighlightVisitor[] produce() { - return cloneHighlightVisitors(); - } - }; + private volatile NotNullProducer myHighlightVisitorProducer = () -> cloneHighlightVisitors(); public GeneralHighlightingPass(@NotNull Project project, @NotNull PsiFile file, @@ -275,16 +269,13 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP final int chunkSize = Math.max(1, (elements1.size()+elements2.size()) / 100); // one percent precision is enough - boolean success = analyzeByVisitors(visitors, holder, 0, new Runnable() { - @Override - public void run() { - runVisitors(elements1, ranges1, chunkSize, progress, skipParentsSet, holder, insideResult, outsideResult, forceHighlightParents, visitors); - final TextRange priorityIntersection = myPriorityRange.intersection(myRestrictRange); - if ((!elements1.isEmpty() || !insideResult.isEmpty()) && priorityIntersection != null) { // do not apply when there were no elements to highlight - myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, insideResult, myPriorityRange, myRestrictRange, getId()); - } - runVisitors(elements2, ranges2, chunkSize, progress, skipParentsSet, holder, insideResult, outsideResult, forceHighlightParents, visitors); + boolean success = analyzeByVisitors(visitors, holder, 0, () -> { + runVisitors(elements1, ranges1, chunkSize, progress, skipParentsSet, holder, insideResult, outsideResult, forceHighlightParents, visitors); + final TextRange priorityIntersection = myPriorityRange.intersection(myRestrictRange); + if ((!elements1.isEmpty() || !insideResult.isEmpty()) && priorityIntersection != null) { // do not apply when there were no elements to highlight + myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, insideResult, myPriorityRange, myRestrictRange, getId()); } + runVisitors(elements2, ranges2, chunkSize, progress, skipParentsSet, holder, insideResult, outsideResult, forceHighlightParents, visitors); }); List postInfos = new ArrayList(holder.size()); // there can be extra highlights generated in PostHighlightVisitor @@ -306,12 +297,7 @@ public class GeneralHighlightingPass extends ProgressableTextEditorHighlightingP action.run(); } else { - if (!visitors[i].analyze(getFile(), myUpdateAll, holder, new Runnable() { - @Override - public void run() { - success[0] = analyzeByVisitors(visitors, holder, i + 1, action); - } - })) { + if (!visitors[i].analyze(getFile(), myUpdateAll, holder, () -> success[0] = analyzeByVisitors(visitors, holder, i + 1, action))) { success[0] = false; } } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java index e3a614952c4d..d6dea6ccb833 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java @@ -824,11 +824,8 @@ public class HighlightInfo implements Segment { else { SuppressQuickFix[] suppressFixes = wrappedTool.getBatchSuppressActions(element); if (suppressFixes.length > 0) { - ContainerUtil.addAll(newOptions, ContainerUtil.map(suppressFixes, new Function() { - @Override - public IntentionAction fun(SuppressQuickFix fix) { - return SuppressIntentionActionFromFix.convertBatchToSuppressIntentionAction(fix); - } + ContainerUtil.addAll(newOptions, ContainerUtil.map(suppressFixes, (Function)fix -> { + return SuppressIntentionActionFromFix.convertBatchToSuppressIntentionAction(fix); })); } } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java index 4a85f5157297..8d7cf622ce43 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java @@ -218,12 +218,7 @@ public class SeverityRegistrar implements Comparator { for (Object o : orderMap.keys()) { list.add((HighlightSeverity)o); } - Collections.sort(list, new Comparator() { - @Override - public int compare(HighlightSeverity o1, HighlightSeverity o2) { - return SeverityRegistrar.compare(o1, o2, orderMap); - } - }); + Collections.sort(list, (o1, o2) -> compare(o1, o2, orderMap)); return list; } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/InspectionEngine.java b/platform/analysis-impl/src/com/intellij/codeInspection/InspectionEngine.java index 6bf3fd4e15cd..fd954b668579 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/InspectionEngine.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/InspectionEngine.java @@ -143,28 +143,25 @@ public class InspectionEngine { Map> toolToSpecifiedDialectIds = getToolsToSpecifiedLanguages(toolWrappers); List>> entries = new ArrayList>>(toolToSpecifiedDialectIds.entrySet()); final Map> resultDescriptors = new ConcurrentHashMap>(); - Processor>> processor = new Processor>>() { - @Override - public boolean process(final Map.Entry> entry) { - ProblemsHolder holder = new ProblemsHolder(iManager, file, isOnTheFly); - final LocalInspectionTool tool = entry.getKey().getTool(); - Set dialectIdsSpecifiedForTool = entry.getValue(); - createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, elementDialectIds, dialectIdsSpecifiedForTool); + Processor>> processor = entry -> { + ProblemsHolder holder = new ProblemsHolder(iManager, file, isOnTheFly); + final LocalInspectionTool tool = entry.getKey().getTool(); + Set dialectIdsSpecifiedForTool = entry.getValue(); + createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, elementDialectIds, dialectIdsSpecifiedForTool); - tool.inspectionFinished(session, holder); + tool.inspectionFinished(session, holder); - if (holder.hasResults()) { - resultDescriptors.put(tool.getShortName(), ContainerUtil.filter(holder.getResults(), new Condition() { - @Override - public boolean value(ProblemDescriptor descriptor) { - PsiElement element = descriptor.getPsiElement(); - return element == null || !SuppressionUtil.inspectionResultSuppressed(element, tool); - } - })); - } - - return true; + if (holder.hasResults()) { + resultDescriptors.put(tool.getShortName(), ContainerUtil.filter(holder.getResults(), new Condition() { + @Override + public boolean value(ProblemDescriptor descriptor) { + PsiElement element = descriptor.getPsiElement(); + return element == null || !SuppressionUtil.inspectionResultSuppressed(element, tool); + } + })); } + + return true; }; JobLauncher.getInstance().invokeConcurrentlyUnderProgress(entries, indicator, failFastOnAcquireReadAction, processor); diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/SuppressIntentionActionFromFix.java b/platform/analysis-impl/src/com/intellij/codeInspection/SuppressIntentionActionFromFix.java index e3274879aab6..cc842a98258c 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/SuppressIntentionActionFromFix.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/SuppressIntentionActionFromFix.java @@ -38,11 +38,8 @@ public class SuppressIntentionActionFromFix extends SuppressIntentionAction { @NotNull public static SuppressIntentionAction[] convertBatchToSuppressIntentionActions(@NotNull SuppressQuickFix[] actions) { - return ContainerUtil.map2Array(actions, SuppressIntentionAction.class, new Function() { - @Override - public SuppressIntentionAction fun(SuppressQuickFix fix) { - return convertBatchToSuppressIntentionAction(fix); - } + return ContainerUtil.map2Array(actions, SuppressIntentionAction.class, fix -> { + return convertBatchToSuppressIntentionAction(fix); }); } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextBase.java b/platform/analysis-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextBase.java index 496aa8f55ac2..60abacf5f21c 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextBase.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextBase.java @@ -188,12 +188,9 @@ public class GlobalInspectionContextBase extends UserDataHolderBase implements G cleanup(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myCurrentScope = scope; - launchInspections(scope); - } + ApplicationManager.getApplication().invokeLater(() -> { + myCurrentScope = scope; + launchInspections(scope); }, ApplicationManager.getApplication().getDisposed()); } @@ -281,12 +278,7 @@ public class GlobalInspectionContextBase extends UserDataHolderBase implements G getStdJobDescriptors().LOCAL_ANALYSIS.setTotalAmount(scope.getFileCount()); getStdJobDescriptors().FIND_EXTERNAL_USAGES.setTotalAmount(0); //to override current progress in order to hide useless messages/% - ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { - @Override - public void run() { - runTools(scope, runGlobalToolsOnly, isOfflineInspections); - } - }, ProgressWrapper.wrap(myProgressIndicator)); + ProgressManager.getInstance().executeProcessUnderProgress(() -> runTools(scope, runGlobalToolsOnly, isOfflineInspections), ProgressWrapper.wrap(myProgressIndicator)); } catch (ProcessCanceledException e) { cleanup(); @@ -347,11 +339,8 @@ public class GlobalInspectionContextBase extends UserDataHolderBase implements G return tools; } Set set = new THashSet(tools, TOOLS_HASHING_STRATEGY); - set.addAll(ContainerUtil.map(dependentTools, new Function() { - @Override - public ToolsImpl fun(InspectionToolWrapper toolWrapper) { - return new ToolsImpl(toolWrapper, toolWrapper.getDefaultLevel(), true, true); - } + set.addAll(ContainerUtil.map(dependentTools, toolWrapper -> { + return new ToolsImpl(toolWrapper, toolWrapper.getDefaultLevel(), true, true); })); return new ArrayList(set); } @@ -418,24 +407,21 @@ public class GlobalInspectionContextBase extends UserDataHolderBase implements G public static void cleanupElements(@NotNull final Project project, @Nullable final Runnable runnable, final List> elements) { - Runnable cleanupRunnable = new Runnable() { - @Override - public void run() { - final List psiElements = new ArrayList(); - for (SmartPsiElementPointer element : elements) { - PsiElement psiElement = element.getElement(); - if (psiElement != null && psiElement.isPhysical()) { - psiElements.add(psiElement); - } + Runnable cleanupRunnable = () -> { + final List psiElements = new ArrayList(); + for (SmartPsiElementPointer 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).getInspectionProfile(); - AnalysisScope analysisScope = new AnalysisScope(new LocalSearchScope(psiElements.toArray(new PsiElement[psiElements.size()])), project); - globalContext.codeCleanup(project, analysisScope, profile, null, runnable, true); } + if (psiElements.isEmpty()) { + return; + } + GlobalInspectionContextBase globalContext = (GlobalInspectionContextBase)InspectionManager.getInstance(project).createNewGlobalContext(false); + final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); + AnalysisScope analysisScope = new AnalysisScope(new LocalSearchScope(psiElements.toArray(new PsiElement[psiElements.size()])), project); + globalContext.codeCleanup(project, analysisScope, profile, null, runnable, true); }; Application application = ApplicationManager.getApplication(); diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java index 8fe8d098f9c3..d03fcb4b2ebf 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java @@ -411,13 +411,10 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel, public void modifyToolSettings(@NotNull final Key shortNameKey, @NotNull final PsiElement psiElement, @NotNull final Consumer toolConsumer) { - modifyProfile(new Consumer() { - @Override - public void consume(@NotNull ModifiableModel model) { - InspectionProfileEntry tool = model.getUnwrappedTool(shortNameKey.toString(), psiElement); - //noinspection unchecked - toolConsumer.consume((T) tool); - } + modifyProfile(model -> { + InspectionProfileEntry tool = model.getUnwrappedTool(shortNameKey.toString(), psiElement); + //noinspection unchecked + toolConsumer.consume((T) tool); }); } @@ -659,12 +656,8 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel, @NotNull private List createTools(Project project) { if (mySource != null) { - return ContainerUtil.map(mySource.getDefaultStates(project), new Function() { - @NotNull - @Override - public InspectionToolWrapper fun(@NotNull ScopeToolState state) { - return state.getTool(); - } + return ContainerUtil.map(mySource.getDefaultStates(project), state -> { + return state.getTool(); }); } return myRegistrar.createTools(); diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefDirectoryImpl.java b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefDirectoryImpl.java index 842be68e4927..31153603397a 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefDirectoryImpl.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefDirectoryImpl.java @@ -51,11 +51,8 @@ public class RefDirectoryImpl extends RefElementImpl implements RefDirectory{ @Override public void accept(@NotNull final RefVisitor visitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - visitor.visitDirectory(RefDirectoryImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + visitor.visitDirectory(RefDirectoryImpl.this); }); } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefEntityImpl.java b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefEntityImpl.java index 02d622973332..8add49ea872a 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefEntityImpl.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefEntityImpl.java @@ -106,11 +106,8 @@ abstract class RefEntityImpl implements RefEntity { @Override public void accept(@NotNull final RefVisitor refVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - refVisitor.visitElement(RefEntityImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + refVisitor.visitElement(RefEntityImpl.this); }); } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefFileImpl.java b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefFileImpl.java index 444e69632114..769d59e58fe4 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefFileImpl.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefFileImpl.java @@ -49,11 +49,8 @@ public class RefFileImpl extends RefElementImpl implements RefFile { @Override public void accept(@NotNull final RefVisitor visitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - visitor.visitFile(RefFileImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + visitor.visitFile(RefFileImpl.this); }); } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefModuleImpl.java b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefModuleImpl.java index 39f3db32d548..0b168f2458b6 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefModuleImpl.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/reference/RefModuleImpl.java @@ -59,11 +59,8 @@ class RefModuleImpl extends RefEntityImpl implements RefModule { @Override public void accept(@NotNull final RefVisitor refVisitor) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - refVisitor.visitModule(RefModuleImpl.this); - } + ApplicationManager.getApplication().runReadAction(() -> { + refVisitor.visitModule(RefModuleImpl.this); }); } diff --git a/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java b/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java index 232c6aca645d..3f72c3fdc55f 100644 --- a/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java +++ b/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java @@ -89,48 +89,43 @@ public class BackwardDependenciesBuilder extends DependenciesBuilder { final int fileCount = getScope().getFileCount(); final boolean includeTestSource = getScope().isIncludeTestSource(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex(); - getScope().accept(new Processor() { - @Override - public boolean process(final VirtualFile virtualFile) { - if (!includeTestSource && fileIndex.isInTestSourceContent(virtualFile)) { - return true; - } - ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - if (indicator != null) { - if (indicator.isCanceled()) { - throw new ProcessCanceledException(); - } - indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text")); - indicator.setText2(getRelativeToProjectPath(virtualFile)); - if (fileCount > 0) { - indicator.setFraction(((double)++myFileCount) / myTotalFileCount); - } - } - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - PsiFile file = psiManager.findFile(virtualFile); - if (file != null) { - final PsiElement navigationElement = file.getNavigationElement(); - if (navigationElement instanceof PsiFile) { - file = (PsiFile)navigationElement; - } - final Map> dependencies = builder.getDependencies(); - for (final PsiFile psiFile : dependencies.keySet()) { - if (dependencies.get(psiFile).contains(file)) { - Set fileDeps = getDependencies().get(file); - if (fileDeps == null) { - fileDeps = new HashSet(); - getDependencies().put(file, fileDeps); - } - fileDeps.add(psiFile); - } - } - psiManager.dropResolveCaches(); - } - } - }); + getScope().accept(virtualFile -> { + if (!includeTestSource && fileIndex.isInTestSourceContent(virtualFile)) { return true; } + ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + if (indicator != null) { + if (indicator.isCanceled()) { + throw new ProcessCanceledException(); + } + indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text")); + indicator.setText2(getRelativeToProjectPath(virtualFile)); + if (fileCount > 0) { + indicator.setFraction(((double)++myFileCount) / myTotalFileCount); + } + } + ApplicationManager.getApplication().runReadAction(() -> { + PsiFile file = psiManager.findFile(virtualFile); + if (file != null) { + final PsiElement navigationElement = file.getNavigationElement(); + if (navigationElement instanceof PsiFile) { + file = (PsiFile)navigationElement; + } + final Map> dependencies = builder.getDependencies(); + for (final PsiFile psiFile : dependencies.keySet()) { + if (dependencies.get(psiFile).contains(file)) { + Set fileDeps = getDependencies().get(file); + if (fileDeps == null) { + fileDeps = new HashSet(); + getDependencies().put(file, fileDeps); + } + fileDeps.add(psiFile); + } + } + psiManager.dropResolveCaches(); + } + }); + return true; }); } finally { diff --git a/platform/analysis-impl/src/com/intellij/packageDependencies/DependencyValidationManagerImpl.java b/platform/analysis-impl/src/com/intellij/packageDependencies/DependencyValidationManagerImpl.java index 07e7e5cc382b..80cc84f862c0 100644 --- a/platform/analysis-impl/src/com/intellij/packageDependencies/DependencyValidationManagerImpl.java +++ b/platform/analysis-impl/src/com/intellij/packageDependencies/DependencyValidationManagerImpl.java @@ -211,19 +211,16 @@ public class DependencyValidationManagerImpl extends DependencyValidationManager super.loadState(element); final NamedScope[] scopes = getEditableScopes(); - Arrays.sort(scopes, new Comparator() { - @Override - public int compare(NamedScope s1, NamedScope s2) { - final String name1 = s1.getName(); - final String name2 = s2.getName(); - if (Comparing.equal(name1, name2)){ - return 0; - } - final List order = myNamedScopeManager.myOrderState.myOrder; - final int i1 = order.indexOf(name1); - final int i2 = order.indexOf(name2); - return i1 > i2 ? 1 : -1; + Arrays.sort(scopes, (s1, s2) -> { + final String name1 = s1.getName(); + final String name2 = s2.getName(); + if (Comparing.equal(name1, name2)){ + return 0; } + final List order = myNamedScopeManager.myOrderState.myOrder; + final int i1 = order.indexOf(name1); + final int i2 = order.indexOf(name2); + return i1 > i2 ? 1 : -1; }); super.setScopes(scopes); myUnnamedScopes.clear(); @@ -346,17 +343,14 @@ public class DependencyValidationManagerImpl extends DependencyValidationManager private final List> myScopePairs = ContainerUtil.createLockFreeCopyOnWriteList(); private void reloadScopes() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (getProject().isDisposed()) return; - List> scopeList = new ArrayList>(); - addScopesToList(scopeList, DependencyValidationManagerImpl.this); - addScopesToList(scopeList, myNamedScopeManager); - myScopePairs.clear(); - myScopePairs.addAll(scopeList); - reloadRules(); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (getProject().isDisposed()) return; + List> scopeList = new ArrayList>(); + addScopesToList(scopeList, DependencyValidationManagerImpl.this); + addScopesToList(scopeList, myNamedScopeManager); + myScopePairs.clear(); + myScopePairs.addAll(scopeList); + reloadRules(); }); } diff --git a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java index f1d90ce1417a..5a275782e8a9 100644 --- a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java +++ b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java @@ -128,14 +128,11 @@ public class InspectionProjectProfileManagerImpl extends InspectionProjectProfil profiles.addAll(getProfiles()); profiles.addAll(InspectionProfileManager.getInstance().getProfiles()); final Application app = ApplicationManager.getApplication(); - Runnable initInspectionProfilesRunnable = new Runnable() { - @Override - public void run() { - for (Profile profile : profiles) { - initProfileWrapper(profile); - } - fireProfilesInitialized(); + Runnable initInspectionProfilesRunnable = () -> { + for (Profile profile : profiles) { + initProfileWrapper(profile); } + fireProfilesInitialized(); }; if (app.isUnitTestMode() || app.isHeadlessEnvironment()) { initInspectionProfilesRunnable.run(); @@ -181,17 +178,14 @@ public class InspectionProjectProfileManagerImpl extends InspectionProjectProfil @Override public void projectClosed() { final Application app = ApplicationManager.getApplication(); - Runnable cleanupInspectionProfilesRunnable = new Runnable() { - @Override - public void run() { - for (InspectionProfileWrapper wrapper : myName2Profile.values()) { - wrapper.cleanup(myProject); - } - for (InspectionProfileWrapper wrapper : myAppName2Profile.values()) { - wrapper.cleanup(myProject); - } - fireProfilesShutdown(); + Runnable cleanupInspectionProfilesRunnable = () -> { + for (InspectionProfileWrapper wrapper : myName2Profile.values()) { + wrapper.cleanup(myProject); } + for (InspectionProfileWrapper wrapper : myAppName2Profile.values()) { + wrapper.cleanup(myProject); + } + fireProfilesShutdown(); }; if (app.isUnitTestMode() || app.isHeadlessEnvironment()) { cleanupInspectionProfilesRunnable.run(); diff --git a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java index 77a37d021147..122cd7362d19 100644 --- a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java +++ b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java @@ -49,13 +49,7 @@ public class FileReferenceSet { new CustomizableReferenceProvider.CustomizationKey>>( PsiBundle.message("default.path.evaluator.option")); public static final Function> ABSOLUTE_TOP_LEVEL = - new Function>() { - @Override - @Nullable - public Collection fun(final PsiFile file) { - return getAbsoluteTopLevelDirLocations(file); - } - }; + file -> getAbsoluteTopLevelDirLocations(file); public static final Condition FILE_FILTER = new Condition() { @Override @@ -464,12 +458,7 @@ public class FileReferenceSet { @NotNull protected Collection toFileSystemItems(@NotNull Collection files) { final PsiManager manager = getElement().getManager(); - return ContainerUtil.mapNotNull(files, new NullableFunction() { - @Override - public PsiFileSystemItem fun(VirtualFile file) { - return file != null ? manager.findDirectory(file) : null; - } - }); + return ContainerUtil.mapNotNull(files, (NullableFunction)file -> file != null ? manager.findDirectory(file) : null); } protected Condition getReferenceCompletionFilter() { diff --git a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/NullFileReferenceHelper.java b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/NullFileReferenceHelper.java index 3e18db1aff67..76ed9e09ad3e 100644 --- a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/NullFileReferenceHelper.java +++ b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/NullFileReferenceHelper.java @@ -45,11 +45,8 @@ public class NullFileReferenceHelper extends FileReferenceHelper { @Override @NotNull public Collection getRoots(@NotNull final Module module) { - return ContainerUtil.mapNotNull(ModuleRootManager.getInstance(module).getContentRoots(), new Function() { - @Override - public PsiFileSystemItem fun(VirtualFile virtualFile) { - return PsiManager.getInstance(module.getProject()).findDirectory(virtualFile); - } + return ContainerUtil.mapNotNull(ModuleRootManager.getInstance(module).getContentRoots(), virtualFile -> { + return PsiManager.getInstance(module.getProject()).findDirectory(virtualFile); }); } diff --git a/platform/built-in-server/src/org/jetbrains/builtInWebServer/ConsoleManager.java b/platform/built-in-server/src/org/jetbrains/builtInWebServer/ConsoleManager.java index 83793c18b6b2..09bd6f5ac93b 100644 --- a/platform/built-in-server/src/org/jetbrains/builtInWebServer/ConsoleManager.java +++ b/platform/built-in-server/src/org/jetbrains/builtInWebServer/ConsoleManager.java @@ -33,25 +33,22 @@ public final class ConsoleManager { netService.configureConsole(consoleBuilder); console = consoleBuilder.getConsole(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ActionGroup actionGroup = netService.getConsoleToolWindowActions(); - ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actionGroup, false); + ApplicationManager.getApplication().invokeLater(() -> { + ActionGroup actionGroup = netService.getConsoleToolWindowActions(); + ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actionGroup, false); - SimpleToolWindowPanel toolWindowPanel = new SimpleToolWindowPanel(false, true); - toolWindowPanel.setContent(console.getComponent()); - toolWindowPanel.setToolbar(toolbar.getComponent()); + SimpleToolWindowPanel toolWindowPanel = new SimpleToolWindowPanel(false, true); + toolWindowPanel.setContent(console.getComponent()); + toolWindowPanel.setToolbar(toolbar.getComponent()); - ToolWindow toolWindow = ToolWindowManager.getInstance(netService.getProject()) - .registerToolWindow(netService.getConsoleToolWindowId(), false, ToolWindowAnchor.BOTTOM, netService.getProject(), true); - toolWindow.setIcon(netService.getConsoleToolWindowIcon()); + ToolWindow toolWindow = ToolWindowManager.getInstance(netService.getProject()) + .registerToolWindow(netService.getConsoleToolWindowId(), false, ToolWindowAnchor.BOTTOM, netService.getProject(), true); + toolWindow.setIcon(netService.getConsoleToolWindowIcon()); - Content content = ContentFactory.SERVICE.getInstance().createContent(toolWindowPanel, "", false); - Disposer.register(content, console); + Content content = ContentFactory.SERVICE.getInstance().createContent(toolWindowPanel, "", false); + Disposer.register(content, console); - toolWindow.getContentManager().addContent(content); - } + toolWindow.getContentManager().addContent(content); }, netService.getProject().getDisposed()); } } \ No newline at end of file diff --git a/platform/built-in-server/src/org/jetbrains/ide/BuiltInServerManagerImpl.java b/platform/built-in-server/src/org/jetbrains/ide/BuiltInServerManagerImpl.java index 3580882d9bf1..6030acfc5e50 100644 --- a/platform/built-in-server/src/org/jetbrains/ide/BuiltInServerManagerImpl.java +++ b/platform/built-in-server/src/org/jetbrains/ide/BuiltInServerManagerImpl.java @@ -92,31 +92,28 @@ public class BuiltInServerManagerImpl extends BuiltInServerManager { return null; } - return ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - BuiltInServer mainServer = StartupUtil.getServer(); - if (mainServer == null || mainServer.getEventLoopGroup() instanceof OioEventLoopGroup) { - server = BuiltInServer.start(1, getDefaultPort(), PORTS_COUNT, false, null); - } - else { - server = BuiltInServer.start(mainServer.getEventLoopGroup(), false, getDefaultPort(), PORTS_COUNT, true, null); - } - bindCustomPorts(server); + return ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + BuiltInServer mainServer = StartupUtil.getServer(); + if (mainServer == null || mainServer.getEventLoopGroup() instanceof OioEventLoopGroup) { + server = BuiltInServer.start(1, getDefaultPort(), PORTS_COUNT, false, null); } - catch (Throwable e) { - LOG.info(e); - NOTIFICATION_GROUP.getValue().createNotification("Cannot start internal HTTP server. Git integration, JavaScript debugger and LiveEdit may operate with errors. " + - "Please check your firewall settings and restart " + ApplicationNamesInfo.getInstance().getFullProductName(), - NotificationType.ERROR).notify(null); - return; + else { + server = BuiltInServer.start(mainServer.getEventLoopGroup(), false, getDefaultPort(), PORTS_COUNT, true, null); } - - LOG.info("built-in server started, port " + server.getPort()); - - Disposer.register(ApplicationManager.getApplication(), server); + bindCustomPorts(server); } + catch (Throwable e) { + LOG.info(e); + NOTIFICATION_GROUP.getValue().createNotification("Cannot start internal HTTP server. Git integration, JavaScript debugger and LiveEdit may operate with errors. " + + "Please check your firewall settings and restart " + ApplicationNamesInfo.getInstance().getFullProductName(), + NotificationType.ERROR).notify(null); + return; + } + + LOG.info("built-in server started, port " + server.getPort()); + + Disposer.register(ApplicationManager.getApplication(), server); }); } diff --git a/platform/built-in-server/src/org/jetbrains/ide/DiffHttpService.java b/platform/built-in-server/src/org/jetbrains/ide/DiffHttpService.java index 061c32227831..03bc38aa7564 100644 --- a/platform/built-in-server/src/org/jetbrains/ide/DiffHttpService.java +++ b/platform/built-in-server/src/org/jetbrains/ide/DiffHttpService.java @@ -116,14 +116,11 @@ final class DiffHttpService extends RestService { final boolean finalFocused = focused; final String finalWindowTitle = windowTitle; final Project finalProject = project; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (finalFocused) { - ProjectUtil.focusProjectWindow(finalProject, true); - } - DiffManager.getInstance().showDiff(finalProject, new SimpleDiffRequest(StringUtil.notNullize(finalWindowTitle, "Diff Service"), contents, titles)); + ApplicationManager.getApplication().invokeLater(() -> { + if (finalFocused) { + ProjectUtil.focusProjectWindow(finalProject, true); } + DiffManager.getInstance().showDiff(finalProject, new SimpleDiffRequest(StringUtil.notNullize(finalWindowTitle, "Diff Service"), contents, titles)); }, project.getDisposed()); sendOk(request, context); diff --git a/platform/built-in-server/src/org/jetbrains/ide/ProjectSetRequestHandler.java b/platform/built-in-server/src/org/jetbrains/ide/ProjectSetRequestHandler.java index da22bb803530..a635fa3cd5c9 100644 --- a/platform/built-in-server/src/org/jetbrains/ide/ProjectSetRequestHandler.java +++ b/platform/built-in-server/src/org/jetbrains/ide/ProjectSetRequestHandler.java @@ -65,12 +65,9 @@ public class ProjectSetRequestHandler extends RestService { @Override public String execute(@NotNull QueryStringDecoder urlDecoder, @NotNull FullHttpRequest request, @NotNull ChannelHandlerContext context) throws IOException { final JsonObject descriptor = new JsonParser().parse(createJsonReader(request)).getAsJsonObject(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - new ProjectSetReader().readDescriptor(descriptor, null); - activateLastFocusedFrame(); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + new ProjectSetReader().readDescriptor(descriptor, null); + activateLastFocusedFrame(); }, ModalityState.defaultModalityState()); sendOk(request, context); return null; diff --git a/platform/built-in-server/src/org/jetbrains/notification/SingletonNotificationManager.java b/platform/built-in-server/src/org/jetbrains/notification/SingletonNotificationManager.java index be68b23ce5ed..c95dde9f3712 100644 --- a/platform/built-in-server/src/org/jetbrains/notification/SingletonNotificationManager.java +++ b/platform/built-in-server/src/org/jetbrains/notification/SingletonNotificationManager.java @@ -54,13 +54,10 @@ public final class SingletonNotificationManager { } if (expiredListener == null) { - expiredListener = new Runnable() { - @Override - public void run() { - Notification currentNotification = notification.get(); - if (currentNotification != null && currentNotification.isExpired()) { - notification.compareAndSet(currentNotification, null); - } + expiredListener = () -> { + Notification currentNotification = notification.get(); + if (currentNotification != null && currentNotification.isExpired()) { + notification.compareAndSet(currentNotification, null); } }; } diff --git a/platform/configuration-store-impl/src/com/intellij/ide/actions/ChooseComponentsToExportDialog.java b/platform/configuration-store-impl/src/com/intellij/ide/actions/ChooseComponentsToExportDialog.java index 69eb4cba1b46..6fe9b82e7ce8 100644 --- a/platform/configuration-store-impl/src/com/intellij/ide/actions/ChooseComponentsToExportDialog.java +++ b/platform/configuration-store-impl/src/com/intellij/ide/actions/ChooseComponentsToExportDialog.java @@ -82,23 +82,13 @@ public class ChooseComponentsToExportDialog extends DialogWrapper { for (ComponentElementProperties componentElementProperty : new LinkedHashSet<>(componentToContainingListElement.values())) { myChooser.addElement(componentElementProperty, true, componentElementProperty); } - myChooser.sort(new Comparator() { - @Override - public int compare(@NotNull ComponentElementProperties o1, @NotNull ComponentElementProperties o2) { - return o1.toString().compareTo(o2.toString()); - } - }); + myChooser.sort((o1, o2) -> o1.toString().compareTo(o2.toString())); final ActionListener browseAction = new ActionListener() { @Override public void actionPerformed(@NotNull ActionEvent e) { chooseSettingsFile(myPathPanel.getText(), getWindow(), IdeBundle.message("title.export.file.location"), IdeBundle.message("prompt.choose.export.settings.file.path")) - .done(new Consumer() { - @Override - public void consume(String path) { - myPathPanel.setText(FileUtil.toSystemDependentName(path)); - } - }); + .done(path -> myPathPanel.setText(FileUtil.toSystemDependentName(path))); } }; @@ -106,12 +96,7 @@ public class ChooseComponentsToExportDialog extends DialogWrapper { String exportPath = PropertiesComponent.getInstance().getValue("export.settings.path", DEFAULT_PATH); myPathPanel.setText(exportPath); - myPathPanel.setChangeListener(new Runnable() { - @Override - public void run() { - updateControls(); - } - }); + myPathPanel.setChangeListener(() -> updateControls()); updateControls(); setTitle(title); diff --git a/platform/duplicates-analysis/src/com/intellij/dupLocator/index/TracingData.java b/platform/duplicates-analysis/src/com/intellij/dupLocator/index/TracingData.java index 758e747b38c1..6e8997e56dcc 100644 --- a/platform/duplicates-analysis/src/com/intellij/dupLocator/index/TracingData.java +++ b/platform/duplicates-analysis/src/com/intellij/dupLocator/index/TracingData.java @@ -41,12 +41,7 @@ public class TracingData { } } }, 5, 5, TimeUnit.SECONDS); - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - flushingFuture.cancel(false); - } - }); + ShutDownTracker.getInstance().registerShutdownTask(() -> flushingFuture.cancel(false)); } catch (IOException ex) { ex.printStackTrace(); } @@ -87,12 +82,7 @@ public class TracingData { final TIntIntHashMap map = new TIntIntHashMap(mapping.size()); for(Integer i:mapping) map.put(i, lkeys.get(i)); - Collections.sort(mapping, new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return map.get(o2) - map.get(o1); - } - }); + Collections.sort(mapping, (o1, o2) -> map.get(o2) - map.get(o1)); for(int i = 0; i < 500; ++i) { //System.out.println(mapping.get(i) + ","); diff --git a/platform/duplicates-analysis/src/com/intellij/dupLocator/treeHash/DuplocatorHashCallback.java b/platform/duplicates-analysis/src/com/intellij/dupLocator/treeHash/DuplocatorHashCallback.java index ea1aefba5593..f49d4bad24b4 100644 --- a/platform/duplicates-analysis/src/com/intellij/dupLocator/treeHash/DuplocatorHashCallback.java +++ b/platform/duplicates-analysis/src/com/intellij/dupLocator/treeHash/DuplocatorHashCallback.java @@ -202,11 +202,7 @@ public class DuplocatorHashCallback implements FragmentsCollector { final Object[] duplicates = duplicateList.keys(); - Arrays.sort(duplicates, new Comparator() { - public int compare(Object x, Object y) { - return ((PsiFragment[])y)[0].getCost() - ((PsiFragment[])x)[0].getCost(); - } - }); + Arrays.sort(duplicates, (x, y) -> ((PsiFragment[])y)[0].getCost() - ((PsiFragment[])x)[0].getCost()); return new DupInfo() { private final TIntObjectHashMap myPattern2Description = new TIntObjectHashMap(); diff --git a/platform/editor-ui-api/src/com/intellij/ide/util/treeView/smartTree/Sorter.java b/platform/editor-ui-api/src/com/intellij/ide/util/treeView/smartTree/Sorter.java index 49589f850b35..d61672b6fe10 100644 --- a/platform/editor-ui-api/src/com/intellij/ide/util/treeView/smartTree/Sorter.java +++ b/platform/editor-ui-api/src/com/intellij/ide/util/treeView/smartTree/Sorter.java @@ -47,13 +47,10 @@ public interface Sorter extends TreeAction { Sorter ALPHA_SORTER = new Sorter() { @Override public Comparator getComparator() { - return new Comparator() { - @Override - public int compare(Object o1, Object o2) { - String s1 = SorterUtil.getStringPresentation(o1); - String s2 = SorterUtil.getStringPresentation(o2); - return s1.compareToIgnoreCase(s2); - } + return (o1, o2) -> { + String s1 = SorterUtil.getStringPresentation(o1); + String s2 = SorterUtil.getStringPresentation(o2); + return s1.compareToIgnoreCase(s2); }; } diff --git a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/CustomShortcutSet.java b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/CustomShortcutSet.java index 6511be92101f..cd9118850203 100644 --- a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/CustomShortcutSet.java +++ b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/CustomShortcutSet.java @@ -50,12 +50,7 @@ public final class CustomShortcutSet implements ShortcutSet { } public CustomShortcutSet(Integer... keyCodes) { - myShortcuts = ContainerUtil.map(keyCodes, new Function() { - @Override - public Shortcut fun(Integer integer) { - return new KeyboardShortcut(KeyStroke.getKeyStroke(integer, 0), null); - } - }, Shortcut.EMPTY_ARRAY); + myShortcuts = ContainerUtil.map(keyCodes, integer -> new KeyboardShortcut(KeyStroke.getKeyStroke(integer, 0), null), Shortcut.EMPTY_ARRAY); } @Override diff --git a/platform/editor-ui-ex/src/com/intellij/codeStyle/AbstractConvertLineSeparatorsAction.java b/platform/editor-ui-ex/src/com/intellij/codeStyle/AbstractConvertLineSeparatorsAction.java index d9872d2e56b4..99974e54b8bc 100644 --- a/platform/editor-ui-ex/src/com/intellij/codeStyle/AbstractConvertLineSeparatorsAction.java +++ b/platform/editor-ui-ex/src/com/intellij/codeStyle/AbstractConvertLineSeparatorsAction.java @@ -103,14 +103,11 @@ public abstract class AbstractConvertLineSeparatorsAction extends AnAction { for (VirtualFile file : virtualFiles) { VfsUtilCore.processFilesRecursively( file, - new Processor() { - @Override - public boolean process(VirtualFile file) { - if (shouldProcess(file, project)) { - changeLineSeparators(project, file, mySeparator); - } - return true; + file1 -> { + if (shouldProcess(file1, project)) { + changeLineSeparators(project, file1, mySeparator); } + return true; }, new Convertor() { @Override diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java index 47fa8fc58e24..15aa0fc0f85b 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java @@ -124,12 +124,7 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { protected AbstractColorsScheme(EditorColorsScheme parentScheme) { myParentScheme = parentScheme; - myFontPreferences.setChangeListener(new Runnable() { - @Override - public void run() { - initFonts(); - } - }); + myFontPreferences.setChangeListener(() -> initFonts()); } public AbstractColorsScheme() { diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/ex/RangeHighlighterEx.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/ex/RangeHighlighterEx.java index 06fcfcadcb23..f6f392e8e1df 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/ex/RangeHighlighterEx.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/ex/RangeHighlighterEx.java @@ -41,10 +41,5 @@ public interface RangeHighlighterEx extends RangeHighlighter, RangeMarkerEx { void setTextAttributes(@NotNull TextAttributes textAttributes); - Comparator BY_AFFECTED_START_OFFSET = new Comparator() { - @Override - public int compare(RangeHighlighterEx r1, RangeHighlighterEx r2) { - return r1.getAffectedAreaStartOffset() - r2.getAffectedAreaStartOffset(); - } - }; + Comparator BY_AFFECTED_START_OFFSET = (r1, r2) -> r1.getAffectedAreaStartOffset() - r2.getAffectedAreaStartOffset(); } diff --git a/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/IndexTodoCacheManagerImpl.java b/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/IndexTodoCacheManagerImpl.java index 1476a57233bc..8d996ddb3936 100644 --- a/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/IndexTodoCacheManagerImpl.java +++ b/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/IndexTodoCacheManagerImpl.java @@ -64,15 +64,12 @@ public class IndexTodoCacheManagerImpl implements TodoCacheManager { final Collection files = fileBasedIndex.getContainingFiles( TodoIndex.NAME, new TodoIndexEntry(indexPattern.getPatternString(), indexPattern.isCaseSensitive()), GlobalSearchScope.allScope(myProject)); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (VirtualFile file : files) { - if (projectFileIndex.isInContent(file)) { - final PsiFile psiFile = myPsiManager.findFile(file); - if (psiFile != null) { - allFiles.add(psiFile); - } + ApplicationManager.getApplication().runReadAction(() -> { + for (VirtualFile file : files) { + if (projectFileIndex.isInContent(file)) { + final PsiFile psiFile = myPsiManager.findFile(file); + if (psiFile != null) { + allFiles.add(psiFile); } } } diff --git a/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/todo/TodoIndex.java b/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/todo/TodoIndex.java index 61980a48d9ca..16c6a2acbc01 100644 --- a/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/todo/TodoIndex.java +++ b/platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/todo/TodoIndex.java @@ -136,12 +136,7 @@ public class TodoIndex extends FileBasedIndexExtension public int getVersion() { int version = 9; FileType[] types = myFileTypeManager.getRegisteredFileTypes(); - Arrays.sort(types, new Comparator() { - @Override - public int compare(FileType o1, FileType o2) { - return Comparing.compare(o1.getName(), o2.getName()); - } - }); + Arrays.sort(types, (o1, o2) -> Comparing.compare(o1.getName(), o2.getName())); for(FileType fileType:types) { DataIndexer indexer = TodoIndexers.INSTANCE.forFileType(fileType); diff --git a/platform/indexing-api/src/com/intellij/psi/search/QuerySearchRequest.java b/platform/indexing-api/src/com/intellij/psi/search/QuerySearchRequest.java index 08b8f12c1061..75039c659cdd 100644 --- a/platform/indexing-api/src/com/intellij/psi/search/QuerySearchRequest.java +++ b/platform/indexing-api/src/com/intellij/psi/search/QuerySearchRequest.java @@ -45,12 +45,7 @@ public class QuerySearchRequest { }; } else { - this.processor = new Processor() { - @Override - public boolean process(PsiReference psiReference) { - return processor.process(psiReference, collector); - } - }; + this.processor = psiReference -> processor.process(psiReference, collector); } } diff --git a/platform/indexing-api/src/com/intellij/psi/search/searches/ReferenceDescriptor.java b/platform/indexing-api/src/com/intellij/psi/search/searches/ReferenceDescriptor.java index 64fd476aaa16..19234af68876 100644 --- a/platform/indexing-api/src/com/intellij/psi/search/searches/ReferenceDescriptor.java +++ b/platform/indexing-api/src/com/intellij/psi/search/searches/ReferenceDescriptor.java @@ -27,13 +27,10 @@ import org.jetbrains.annotations.NotNull; */ public class ReferenceDescriptor { @NotNull - public static final Function MAPPER = new Function() { - @Override - public ReferenceDescriptor fun(PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - final PsiFile file = element.getContainingFile(); - return new ReferenceDescriptor(file.getViewProvider().getVirtualFile(), element.getTextRange().getStartOffset() + psiReference.getRangeInElement().getStartOffset()); - } + public static final Function MAPPER = psiReference -> { + final PsiElement element = psiReference.getElement(); + final PsiFile file1 = element.getContainingFile(); + return new ReferenceDescriptor(file1.getViewProvider().getVirtualFile(), element.getTextRange().getStartOffset() + psiReference.getRangeInElement().getStartOffset()); }; private final VirtualFile file; private final int offset; diff --git a/platform/indexing-api/src/com/intellij/psi/search/searches/ReferencesSearch.java b/platform/indexing-api/src/com/intellij/psi/search/searches/ReferencesSearch.java index 20ee72a87f87..fc7c7d1ccb0b 100644 --- a/platform/indexing-api/src/com/intellij/psi/search/searches/ReferencesSearch.java +++ b/platform/indexing-api/src/com/intellij/psi/search/searches/ReferencesSearch.java @@ -177,12 +177,8 @@ public class ReferencesSearch extends ExtensibleQueryFactory processor) { - searchOptimized(element, searchScope, ignoreAccessScope, collector, false, new PairProcessor() { - @Override - public boolean process(PsiReference psiReference, SearchRequestCollector collector) { - return processor.process(psiReference); - } - }); + searchOptimized(element, searchScope, ignoreAccessScope, collector, false, + (psiReference, collector1) -> processor.process(psiReference)); } public static void searchOptimized(@NotNull PsiElement element, diff --git a/platform/indexing-impl/src/com/intellij/openapi/module/impl/scopes/ModuleWithDependenciesScope.java b/platform/indexing-impl/src/com/intellij/openapi/module/impl/scopes/ModuleWithDependenciesScope.java index 9fbc050ecab5..d051c2561eed 100644 --- a/platform/indexing-impl/src/com/intellij/openapi/module/impl/scopes/ModuleWithDependenciesScope.java +++ b/platform/indexing-impl/src/com/intellij/openapi/module/impl/scopes/ModuleWithDependenciesScope.java @@ -73,13 +73,9 @@ public class ModuleWithDependenciesScope extends GlobalSearchScope { } else { OrderEnumerator en = getOrderEnumeratorForOptions(); - Collections.addAll(roots, en.roots(new NotNullFunction() { - @NotNull - @Override - public OrderRootType fun(OrderEntry entry) { - if (entry instanceof ModuleOrderEntry || entry instanceof ModuleSourceOrderEntry) return OrderRootType.SOURCES; - return OrderRootType.CLASSES; - } + Collections.addAll(roots, en.roots(entry -> { + if (entry instanceof ModuleOrderEntry || entry instanceof ModuleSourceOrderEntry) return OrderRootType.SOURCES; + return OrderRootType.CLASSES; }).getRoots()); } @@ -111,17 +107,14 @@ public class ModuleWithDependenciesScope extends GlobalSearchScope { // ordering the content roots, so use a LinkedHashSet final Set modules = ContainerUtil.newLinkedHashSet(); OrderEnumerator en = getOrderEnumeratorForOptions(); - en.forEach(new Processor() { - @Override - public boolean process(OrderEntry each) { - if (each instanceof ModuleOrderEntry) { - ContainerUtil.addIfNotNull(modules, ((ModuleOrderEntry)each).getModule()); - } - else if (each instanceof ModuleSourceOrderEntry) { - ContainerUtil.addIfNotNull(modules, each.getOwnerModule()); - } - return true; + en.forEach(each -> { + if (each instanceof ModuleOrderEntry) { + ContainerUtil.addIfNotNull(modules, ((ModuleOrderEntry)each).getModule()); } + else if (each instanceof ModuleSourceOrderEntry) { + ContainerUtil.addIfNotNull(modules, each.getOwnerModule()); + } + return true; }); return modules; } @@ -198,12 +191,7 @@ public class ModuleWithDependenciesScope extends GlobalSearchScope { public Collection getRoots() { //noinspection unchecked List result = (List)ContainerUtil.newArrayList(myRoots.keys()); - Collections.sort(result, new Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - return myRoots.get(o1) - myRoots.get(o2); - } - }); + Collections.sort(result, (o1, o2) -> myRoots.get(o1) - myRoots.get(o2)); return result; } diff --git a/platform/indexing-impl/src/com/intellij/openapi/roots/impl/LibraryScopeCache.java b/platform/indexing-impl/src/com/intellij/openapi/roots/impl/LibraryScopeCache.java index 518c8180af05..be430c0d0016 100644 --- a/platform/indexing-impl/src/com/intellij/openapi/roots/impl/LibraryScopeCache.java +++ b/platform/indexing-impl/src/com/intellij/openapi/roots/impl/LibraryScopeCache.java @@ -146,12 +146,7 @@ public class LibraryScopeCache { } } - Comparator comparator = new Comparator() { - @Override - public int compare(@NotNull Module o1, @NotNull Module o2) { - return o1.getName().compareTo(o2.getName()); - } - }; + Comparator comparator = (o1, o2) -> o1.getName().compareTo(o2.getName()); Collections.sort(modulesLibraryUsedIn, comparator); List uniquesList = ContainerUtil.removeDuplicatesFromSorted(modulesLibraryUsedIn, comparator); Module[] uniques = uniquesList.toArray(new Module[uniquesList.size()]); diff --git a/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java b/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java index c317bf525be8..829b353d4adb 100644 --- a/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java +++ b/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java @@ -69,12 +69,7 @@ public class ResolveScopeManagerImpl extends ResolveScopeManager { myManager = psiManager; myAdditionalIndexableFileSet = new AdditionalIndexableFileSet(project); - ((PsiManagerImpl) psiManager).registerRunnableToRunOnChange(new Runnable() { - @Override - public void run() { - myDefaultResolveScopesCache.clear(); - } - }); + ((PsiManagerImpl) psiManager).registerRunnableToRunOnChange(() -> myDefaultResolveScopesCache.clear()); } diff --git a/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java b/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java index 4954d461bf98..4a7bdb165ae7 100644 --- a/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java +++ b/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java @@ -307,18 +307,15 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { while (true) { List failedList = new SmartList(); final List failedFiles = Collections.synchronizedList(failedList); - final Processor processor = new Processor() { - @Override - public boolean process(final VirtualFile vfile) { - try { - TooManyUsagesStatus.getFrom(progress).pauseProcessingIfTooManyUsages(); - processVirtualFile(vfile, progress, localProcessor, canceled, counter, totalSize); - } - catch (ApplicationUtil.CannotRunReadActionException action) { - failedFiles.add(vfile); - } - return !canceled.get(); + final Processor processor = vfile -> { + try { + TooManyUsagesStatus.getFrom(progress).pauseProcessingIfTooManyUsages(); + processVirtualFile(vfile, progress, localProcessor, canceled, counter, totalSize); } + catch (ApplicationUtil.CannotRunReadActionException action) { + failedFiles.add(vfile); + } + return !canceled.get(); }; if (ApplicationManager.getApplication().isWriteAccessAllowed() || ((ApplicationEx)ApplicationManager.getApplication()).isWriteActionPending()) { // no point in processing in separate threads - they are doomed to fail to obtain read action anyway @@ -577,12 +574,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { if (request.equals(another.request)) { final Processor myProcessor = refProcessor; if (myProcessor != another.refProcessor) { - refProcessor = new Processor() { - @Override - public boolean process(PsiReference psiReference) { - return myProcessor.process(psiReference) && another.refProcessor.process(psiReference); - } - }; + refProcessor = psiReference -> myProcessor.process(psiReference) && another.refProcessor.process(psiReference); } return true; } @@ -711,18 +703,15 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { int alreadyProcessedFiles) { List files = new ArrayList(candidateFiles.keySet()); - return processPsiFileRoots(files, totalSize, alreadyProcessedFiles, progress, new Processor() { - @Override - public boolean process(final PsiFile psiRoot) { - final VirtualFile vfile = psiRoot.getVirtualFile(); - for (final RequestWithProcessor singleRequest : candidateFiles.get(vfile)) { - Processor localProcessor = localProcessors.get(singleRequest); - if (!localProcessor.process(psiRoot)) { - return false; - } + return processPsiFileRoots(files, totalSize, alreadyProcessedFiles, progress, psiRoot -> { + final VirtualFile vfile = psiRoot.getVirtualFile(); + for (final RequestWithProcessor singleRequest : candidateFiles.get(vfile)) { + Processor localProcessor = localProcessors.get(singleRequest); + if (!localProcessor.process(psiRoot)) { + return false; } - return true; } + return true; }); } @@ -795,26 +784,22 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { for (final VirtualFile file : result) { progress.checkCanceled(); for (final IdIndexEntry entry : keys) { - DumbService.getInstance(myManager.getProject()).runReadActionInSmartMode(new Runnable() { - @Override - public void run() { - FileBasedIndex.getInstance().processValues(IdIndex.NAME, entry, file, new FileBasedIndex.ValueProcessor() { - @Override - public boolean process(VirtualFile file, Integer value) { - int mask = value.intValue(); - for (RequestWithProcessor single : data) { - final PsiSearchRequest request = single.request; - if ((mask & request.searchContext) != 0 && ((GlobalSearchScope)request.searchScope).contains(file)) { - MultiMap result = - intersectionWithContainerNameFiles == null || !intersectionWithContainerNameFiles.contains(file) ? restResult : intersectionResult; - result.putValue(file, single); - } + DumbService.getInstance(myManager.getProject()).runReadActionInSmartMode( + (Runnable)() -> FileBasedIndex.getInstance().processValues(IdIndex.NAME, entry, file, new FileBasedIndex.ValueProcessor() { + @Override + public boolean process(VirtualFile file1, Integer value) { + int mask = value.intValue(); + for (RequestWithProcessor single : data) { + final PsiSearchRequest request = single.request; + if ((mask & request.searchContext) != 0 && ((GlobalSearchScope)request.searchScope).contains(file1)) { + MultiMap result1 = + intersectionWithContainerNameFiles == null || !intersectionWithContainerNameFiles.contains(file1) ? restResult : intersectionResult; + result1.putValue(file1, single); } - return true; } - }, commonScope); - } - }); + return true; + } + }, commonScope)); } } } @@ -872,12 +857,7 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { @NotNull private static GlobalSearchScope uniteScopes(@NotNull Collection requests) { - Set scopes = ContainerUtil.map2LinkedSet(requests, new Function() { - @Override - public GlobalSearchScope fun(RequestWithProcessor r) { - return (GlobalSearchScope)r.request.searchScope; - } - }); + Set scopes = ContainerUtil.map2LinkedSet(requests, r -> (GlobalSearchScope)r.request.searchScope); return GlobalSearchScope.union(scopes.toArray(new GlobalSearchScope[scopes.size()])); } @@ -985,12 +965,8 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { return DumbService.getInstance(project).runReadActionInSmartMode(new Computable() { @Override public Boolean compute() { - return FileBasedIndex.getInstance().processFilesContainingAllKeys(IdIndex.NAME, keys, scope, checker, new Processor() { - @Override - public boolean process(VirtualFile file) { - return !index.shouldBeFound(scope, file) || processor.process(file); - } - }); + return FileBasedIndex.getInstance().processFilesContainingAllKeys(IdIndex.NAME, keys, scope, checker, + file -> !index.shouldBeFound(scope, file) || processor.process(file)); } }); } @@ -1005,11 +981,8 @@ public class PsiSearchHelperImpl implements PsiSearchHelper { } } if (words.isEmpty()) return Collections.emptyList(); - return ContainerUtil.map2List(words, new Function() { - @Override - public IdIndexEntry fun(String word) { - return new IdIndexEntry(word, caseSensitively); - } + return ContainerUtil.map2List(words, word -> { + return new IdIndexEntry(word, caseSensitively); }); } diff --git a/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java b/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java index 68fbe3723fb3..c8719f91fde6 100644 --- a/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java +++ b/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java @@ -165,14 +165,11 @@ public class FilenameIndex extends ScalarIndexExtension { @Nullable final IdFilter idFilter) { final Set keys = new THashSet(); final FileBasedIndex index = FileBasedIndex.getInstance(); - index.processAllKeys(NAME, new Processor() { - @Override - public boolean process(String value) { - if (name.equalsIgnoreCase(value)) { - keys.add(value); - } - return true; + index.processAllKeys(NAME, value -> { + if (name.equalsIgnoreCase(value)) { + keys.add(value); } + return true; }, scope, idFilter); // values accessed outside of provessAllKeys diff --git a/platform/lang-api/src/com/intellij/codeInsight/actions/CodeInsightAction.java b/platform/lang-api/src/com/intellij/codeInsight/actions/CodeInsightAction.java index fc69be8d2e31..d32873f26133 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/actions/CodeInsightAction.java +++ b/platform/lang-api/src/com/intellij/codeInsight/actions/CodeInsightAction.java @@ -52,23 +52,17 @@ public abstract class CodeInsightAction extends AnAction { //final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); if (psiFile == null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - final CodeInsightActionHandler handler = getHandler(); - final Runnable action = new Runnable() { - @Override - public void run() { - if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return; - handler.invoke(project, editor, psiFile); - } - }; - if (handler.startInWriteAction()) { - ApplicationManager.getApplication().runWriteAction(action); - } - else { - action.run(); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + final CodeInsightActionHandler handler = getHandler(); + final Runnable action = () -> { + if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return; + handler.invoke(project, editor, psiFile); + }; + if (handler.startInWriteAction()) { + ApplicationManager.getApplication().runWriteAction(action); + } + else { + action.run(); } }, getCommandName(), DocCommandGroupId.noneGroupId(editor.getDocument())); } diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionResultSet.java b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionResultSet.java index 6cccc06dacf2..56952aee601e 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionResultSet.java +++ b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionResultSet.java @@ -112,14 +112,11 @@ public abstract class CompletionResultSet implements Consumer { public LinkedHashSet runRemainingContributors(CompletionParameters parameters, final boolean passResult) { final LinkedHashSet elements = new LinkedHashSet(); - runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(CompletionResult result) { - if (passResult) { - passResult(result); - } - elements.add(result); + runRemainingContributors(parameters, result -> { + if (passResult) { + passResult(result); } + elements.add(result); }); return elements; } diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java index d8f61a9535a7..e43f1dfe7889 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java +++ b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionService.java @@ -107,12 +107,9 @@ public abstract class CompletionService { public void performCompletion(final CompletionParameters parameters, final Consumer consumer) { final Set lookupSet = ContainerUtil.newConcurrentSet(); - getVariantsFromContributors(parameters, null, new Consumer() { - @Override - public void consume(final CompletionResult result) { - if (lookupSet.add(result.getLookupElement())) { - consumer.consume(result); - } + getVariantsFromContributors(parameters, null, result -> { + if (lookupSet.add(result.getLookupElement())) { + consumer.consume(result); } }); } diff --git a/platform/lang-api/src/com/intellij/codeInsight/daemon/MergeableLineMarkerInfo.java b/platform/lang-api/src/com/intellij/codeInsight/daemon/MergeableLineMarkerInfo.java index fbcd16197c6c..6e468e80d808 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/daemon/MergeableLineMarkerInfo.java +++ b/platform/lang-api/src/com/intellij/codeInsight/daemon/MergeableLineMarkerInfo.java @@ -132,51 +132,39 @@ public abstract class MergeableLineMarkerInfo extends Line @Override public void navigate(final MouseEvent e, PsiElement elt) { final List infos = new ArrayList(markers); - Collections.sort(infos, new Comparator() { - @Override - public int compare(LineMarkerInfo o1, LineMarkerInfo o2) { - return o1.startOffset - o2.startOffset; - } - }); + Collections.sort(infos, (o1, o2) -> o1.startOffset - o2.startOffset); final JBList list = new JBList(infos); list.setFixedCellHeight(UIUtil.LIST_FIXED_CELL_HEIGHT); PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list); if (!markers.get(0).configurePopupAndRenderer(builder, list, infos)) { - list.installCellRenderer(new NotNullFunction() { - @NotNull - @Override - public JComponent fun(Object dom) { - if (dom instanceof LineMarkerInfo) { - Icon icon = null; - final GutterIconRenderer renderer = ((LineMarkerInfo)dom).createGutterRenderer(); - if (renderer != null) { - icon = renderer.getIcon(); - } - PsiElement element = ((LineMarkerInfo)dom).getElement(); - assert element != null; - final String elementPresentation = - dom instanceof MergeableLineMarkerInfo ? ((MergeableLineMarkerInfo)dom).getElementPresentation(element) : element.getText(); - String text = StringUtil.first(elementPresentation, 100, true).replace('\n', ' '); - - final JBLabel label = new JBLabel(text, icon, SwingConstants.LEFT); - label.setBorder(IdeBorderFactory.createEmptyBorder(2)); - return label; + list.installCellRenderer(dom -> { + if (dom instanceof LineMarkerInfo) { + Icon icon = null; + final GutterIconRenderer renderer = ((LineMarkerInfo)dom).createGutterRenderer(); + if (renderer != null) { + icon = renderer.getIcon(); } + PsiElement element = ((LineMarkerInfo)dom).getElement(); + assert element != null; + final String elementPresentation = + dom instanceof MergeableLineMarkerInfo ? ((MergeableLineMarkerInfo)dom).getElementPresentation(element) : element.getText(); + String text = StringUtil.first(elementPresentation, 100, true).replace('\n', ' '); - return new JBLabel(); + final JBLabel label = new JBLabel(text, icon, SwingConstants.LEFT); + label.setBorder(IdeBorderFactory.createEmptyBorder(2)); + return label; } + + return new JBLabel(); }); } - builder.setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof LineMarkerInfo) { - final GutterIconNavigationHandler handler = ((LineMarkerInfo)value).getNavigationHandler(); - if (handler != null) { - //noinspection unchecked - handler.navigate(e, ((LineMarkerInfo)value).getElement()); - } + builder.setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof LineMarkerInfo) { + final GutterIconNavigationHandler handler = ((LineMarkerInfo)value).getNavigationHandler(); + if (handler != null) { + //noinspection unchecked + handler.navigate(e, ((LineMarkerInfo)value).getElement()); } } }).createPopup().show(new RelativePoint(e)); diff --git a/platform/lang-api/src/com/intellij/codeInsight/daemon/RelatedItemLineMarkerInfo.java b/platform/lang-api/src/com/intellij/codeInsight/daemon/RelatedItemLineMarkerInfo.java index 0735e4da50ec..7da9378d2ef8 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/daemon/RelatedItemLineMarkerInfo.java +++ b/platform/lang-api/src/com/intellij/codeInsight/daemon/RelatedItemLineMarkerInfo.java @@ -86,24 +86,18 @@ public class RelatedItemLineMarkerInfo extends MergeableLi @NotNull @Override public Function getCommonTooltip(@NotNull final List infos) { - return new Function() { - @Override - public String fun(PsiElement element) { - Set tooltips = new HashSet(ContainerUtil.mapNotNull(infos, new Function() { - @Override - public String fun(MergeableLineMarkerInfo info) { - return info.getLineMarkerTooltip(); - } - })); - StringBuilder tooltip = new StringBuilder(); - for (String info : tooltips) { - if (tooltip.length() > 0) { - tooltip.append(UIUtil.BORDER_LINE); - } - tooltip.append(UIUtil.getHtmlBody(info)); + return (Function)element -> { + Set tooltips = new HashSet(ContainerUtil.mapNotNull(infos, info -> { + return info.getLineMarkerTooltip(); + })); + StringBuilder tooltip = new StringBuilder(); + for (String info : tooltips) { + if (tooltip.length() > 0) { + tooltip.append(UIUtil.BORDER_LINE); } - return XmlStringUtil.wrapInHtml(tooltip); + tooltip.append(UIUtil.getHtmlBody(info)); } + return XmlStringUtil.wrapInHtml(tooltip); }; } diff --git a/platform/lang-api/src/com/intellij/codeInsight/lookup/LookupElementPresentation.java b/platform/lang-api/src/com/intellij/codeInsight/lookup/LookupElementPresentation.java index 5afceab2af5f..487a60110388 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/lookup/LookupElementPresentation.java +++ b/platform/lang-api/src/com/intellij/codeInsight/lookup/LookupElementPresentation.java @@ -133,12 +133,7 @@ public class LookupElementPresentation { @Nullable public String getTailText() { if (myTail == null) return null; - return StringUtil.join(myTail, new Function() { - @Override - public String fun(TextFragment fragment) { - return fragment.text; - } - }, ""); + return StringUtil.join(myTail, fragment -> fragment.text, ""); } @Nullable diff --git a/platform/lang-api/src/com/intellij/codeInspection/ui/ListEditForm.java b/platform/lang-api/src/com/intellij/codeInspection/ui/ListEditForm.java index 4b34c9d51de2..7ea93bb922c2 100644 --- a/platform/lang-api/src/com/intellij/codeInspection/ui/ListEditForm.java +++ b/platform/lang-api/src/com/intellij/codeInspection/ui/ListEditForm.java @@ -37,23 +37,20 @@ public class ListEditForm { public void run(AnActionButton button) { final ListWrappingTableModel tableModel = table.getModel(); tableModel.addRow(); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - final int lastRowIndex = tableModel.getRowCount() - 1; - final Rectangle rectangle = - table.getCellRect(lastRowIndex, 0, true); - table.scrollRectToVisible(rectangle); - table.editCellAt(lastRowIndex, 0); - final ListSelectionModel selectionModel = - table.getSelectionModel(); - selectionModel.setSelectionInterval(lastRowIndex, lastRowIndex); - final TableCellEditor editor = table.getCellEditor(); - final Component component = - editor.getTableCellEditorComponent(table, - null, true, lastRowIndex, 0); - component.requestFocus(); - } + EventQueue.invokeLater(() -> { + final int lastRowIndex = tableModel.getRowCount() - 1; + final Rectangle rectangle = + table.getCellRect(lastRowIndex, 0, true); + table.scrollRectToVisible(rectangle); + table.editCellAt(lastRowIndex, 0); + final ListSelectionModel selectionModel = + table.getSelectionModel(); + selectionModel.setSelectionInterval(lastRowIndex, lastRowIndex); + final TableCellEditor editor = table.getCellEditor(); + final Component component = + editor.getTableCellEditorComponent(table, + null, true, lastRowIndex, 0); + component.requestFocus(); }); } }).setRemoveAction(new AnActionButtonRunnable() { diff --git a/platform/lang-api/src/com/intellij/diagnostic/logging/LogConsolePreferences.java b/platform/lang-api/src/com/intellij/diagnostic/logging/LogConsolePreferences.java index c7b577c2e0f3..18c7a3658095 100644 --- a/platform/lang-api/src/com/intellij/diagnostic/logging/LogConsolePreferences.java +++ b/platform/lang-api/src/com/intellij/diagnostic/logging/LogConsolePreferences.java @@ -45,12 +45,7 @@ import java.util.regex.Pattern; @State(name = "LogFilters", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"}) public class LogConsolePreferences extends LogFilterRegistrar { - private final SortedMap myRegisteredLogFilters = new TreeMap(new Comparator() { - @Override - public int compare(final LogFilter o1, final LogFilter o2) { - return -1; - } - }); + private final SortedMap myRegisteredLogFilters = new TreeMap((o1, o2) -> -1); @NonNls private static final String FILTER = "filter"; @NonNls private static final String IS_ACTIVE = "is_active"; diff --git a/platform/lang-api/src/com/intellij/execution/RunManager.java b/platform/lang-api/src/com/intellij/execution/RunManager.java index 88553c0ed6a9..4239472bf26d 100644 --- a/platform/lang-api/src/com/intellij/execution/RunManager.java +++ b/platform/lang-api/src/com/intellij/execution/RunManager.java @@ -239,11 +239,8 @@ public abstract class RunManager { public String suggestUniqueName(@Nullable String name, @Nullable ConfigurationType type) { List settingsList = type != null ? getConfigurationSettingsList(type) : getAllSettings(); - List names = ContainerUtil.map(settingsList, new Function() { - @Override - public String fun(RunnerAndConfigurationSettings settings) { - return settings.getName(); - } + List names = ContainerUtil.map(settingsList, settings -> { + return settings.getName(); }); return suggestUniqueName(StringUtil.notNullize(name, UNNAMED), names); } diff --git a/platform/lang-api/src/com/intellij/execution/actions/ConfigurationFromContext.java b/platform/lang-api/src/com/intellij/execution/actions/ConfigurationFromContext.java index 754a943f6608..33925b14c40b 100644 --- a/platform/lang-api/src/com/intellij/execution/actions/ConfigurationFromContext.java +++ b/platform/lang-api/src/com/intellij/execution/actions/ConfigurationFromContext.java @@ -120,38 +120,31 @@ public abstract class ConfigurationFromContext { /** * Compares configurations according to precedence. */ - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(ConfigurationFromContext configuration1, ConfigurationFromContext configuration2) { - if (PsiTreeUtil.isAncestor(configuration1.getSourceElement(), configuration2.getSourceElement(), true)) { - return 1; - } - if (PsiTreeUtil.isAncestor(configuration2.getSourceElement(), configuration1.getSourceElement(), true)) { - return -1; - } - if (!configuration1.isPreferredTo(configuration2)) { - return 1; - } - if (configuration2.shouldReplace(configuration1)) { - return 1; - } - if (!configuration2.isPreferredTo(configuration1)) { - return -1; - } - if (configuration1.shouldReplace(configuration2)) { - return -1; - } - return 0; + public static final Comparator COMPARATOR = (configuration1, configuration2) -> { + if (PsiTreeUtil.isAncestor(configuration1.getSourceElement(), configuration2.getSourceElement(), true)) { + return 1; } + if (PsiTreeUtil.isAncestor(configuration2.getSourceElement(), configuration1.getSourceElement(), true)) { + return -1; + } + if (!configuration1.isPreferredTo(configuration2)) { + return 1; + } + if (configuration2.shouldReplace(configuration1)) { + return 1; + } + if (!configuration2.isPreferredTo(configuration1)) { + return -1; + } + if (configuration1.shouldReplace(configuration2)) { + return -1; + } + return 0; }; /** * Compares configurations according to configuration type name. */ - public static final Comparator NAME_COMPARATOR = new Comparator() { - @Override - public int compare(final ConfigurationFromContext p1, final ConfigurationFromContext p2) { - return p1.getConfigurationType().getDisplayName().compareTo(p2.getConfigurationType().getDisplayName()); - } - }; + public static final Comparator NAME_COMPARATOR = + (p1, p2) -> p1.getConfigurationType().getDisplayName().compareTo(p2.getConfigurationType().getDisplayName()); } diff --git a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java index b2593ef26de6..f80c40ac4811 100644 --- a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java +++ b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java @@ -139,12 +139,7 @@ public abstract class CommandLineState implements RunProfileState { @Override public void setSelected(final AnActionEvent event, final boolean flag) { myConsole.setOutputPaused(flag); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - update(event); - } - }); + ApplicationManager.getApplication().invokeLater(() -> update(event)); } @Override @@ -165,12 +160,7 @@ public abstract class CommandLineState implements RunProfileState { } else { presentation.setEnabled(true); - myConsole.performWhenNoDeferredOutput(new Runnable() { - @Override - public void run() { - update(event); - } - }); + myConsole.performWhenNoDeferredOutput(() -> update(event)); } } } diff --git a/platform/lang-api/src/com/intellij/execution/filters/OpenFileHyperlinkInfo.java b/platform/lang-api/src/com/intellij/execution/filters/OpenFileHyperlinkInfo.java index 14468ba5dcc2..005f7d2d066a 100644 --- a/platform/lang-api/src/com/intellij/execution/filters/OpenFileHyperlinkInfo.java +++ b/platform/lang-api/src/com/intellij/execution/filters/OpenFileHyperlinkInfo.java @@ -76,13 +76,10 @@ public final class OpenFileHyperlinkInfo implements FileHyperlinkInfo { @Override public void navigate(final Project project) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - OpenFileDescriptor descriptor = getDescriptor(); - if (descriptor != null) { - FileEditorManager.getInstance(project).openTextEditor(descriptor, true); - } + ApplicationManager.getApplication().runReadAction(() -> { + OpenFileDescriptor descriptor = getDescriptor(); + if (descriptor != null) { + FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } }); } diff --git a/platform/lang-api/src/com/intellij/execution/runners/ExecutionUtil.java b/platform/lang-api/src/com/intellij/execution/runners/ExecutionUtil.java index 5e794b77e044..3f9a109dd46a 100644 --- a/platform/lang-api/src/com/intellij/execution/runners/ExecutionUtil.java +++ b/platform/lang-api/src/com/intellij/execution/runners/ExecutionUtil.java @@ -115,29 +115,26 @@ public class ExecutionUtil { final HyperlinkListener finalListener = listener; final String finalDescription = description; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) { - return; - } - - ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); - if (toolWindowManager.canShowNotification(toolWindowId)) { - //noinspection SSBasedInspection - toolWindowManager.notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, finalListener); - } - else { - Messages.showErrorDialog(project, UIUtil.toHtml(fullMessage), ""); - } - NotificationListener notificationListener = finalListener == null ? null : new NotificationListener() { - @Override - public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { - finalListener.hyperlinkUpdate(event); - } - }; - ourNotificationGroup.createNotification(title, finalDescription, NotificationType.ERROR, notificationListener).notify(project); + UIUtil.invokeLaterIfNeeded(() -> { + if (project.isDisposed()) { + return; } + + ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); + if (toolWindowManager.canShowNotification(toolWindowId)) { + //noinspection SSBasedInspection + toolWindowManager.notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, finalListener); + } + else { + Messages.showErrorDialog(project, UIUtil.toHtml(fullMessage), ""); + } + NotificationListener notificationListener = finalListener == null ? null : new NotificationListener() { + @Override + public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { + finalListener.hyperlinkUpdate(event); + } + }; + ourNotificationGroup.createNotification(title, finalDescription, NotificationType.ERROR, notificationListener).notify(project); }); } diff --git a/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java b/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java index 1012a3380b0d..8b0ea86036af 100644 --- a/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java +++ b/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java @@ -39,12 +39,9 @@ public interface CellTransform { myRestoringNow = true; if (myActions.size() == 0) return ActionCallback.DONE; final ActionCallback topCallback = restore(0); - return topCallback.doWhenDone(new Runnable() { - @Override - public void run() { - myActions.clear(); - myRestoringNow = false; - } + return topCallback.doWhenDone(() -> { + myActions.clear(); + myRestoringNow = false; }); } @@ -52,14 +49,11 @@ public interface CellTransform { final ActionCallback result = new ActionCallback(); final Restore action = myActions.get(index); final ActionCallback actionCalback = action.restoreInGrid(); - actionCalback.doWhenDone(new Runnable() { - @Override - public void run() { - if (index < myActions.size() - 1) { - restore(index + 1).notifyWhenDone(result); - } else { - result.setDone(); - } + actionCalback.doWhenDone(() -> { + if (index < myActions.size() - 1) { + restore(index + 1).notifyWhenDone(result); + } else { + result.setDone(); } }); diff --git a/platform/lang-api/src/com/intellij/execution/util/EnvVariablesTable.java b/platform/lang-api/src/com/intellij/execution/util/EnvVariablesTable.java index 7c0b4296d52a..f07afdea7724 100644 --- a/platform/lang-api/src/com/intellij/execution/util/EnvVariablesTable.java +++ b/platform/lang-api/src/com/intellij/execution/util/EnvVariablesTable.java @@ -108,24 +108,20 @@ public class EnvVariablesTable extends ListTableWithButtons } public void editVariableName(final EnvironmentVariable environmentVariable) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - - @Override - public void run() { - final EnvironmentVariable actualEnvVar = ContainerUtil.find(getElements(), new Condition() { - @Override - public boolean value(EnvironmentVariable item) { - return StringUtil.equals(environmentVariable.getName(), item.getName()); - } - }); - if (actualEnvVar == null) { - return; + ApplicationManager.getApplication().invokeLater(() -> { + final EnvironmentVariable actualEnvVar = ContainerUtil.find(getElements(), new Condition() { + @Override + public boolean value(EnvironmentVariable item) { + return StringUtil.equals(environmentVariable.getName(), item.getName()); } + }); + if (actualEnvVar == null) { + return; + } - setSelection(actualEnvVar); - if (actualEnvVar.getNameIsWriteable()) { - editSelection(0); - } + setSelection(actualEnvVar); + if (actualEnvVar.getNameIsWriteable()) { + editSelection(0); } }); } diff --git a/platform/lang-api/src/com/intellij/execution/util/ListTableWithButtons.java b/platform/lang-api/src/com/intellij/execution/util/ListTableWithButtons.java index 36dea3914b29..d5be0fd2cc6e 100644 --- a/platform/lang-api/src/com/intellij/execution/util/ListTableWithButtons.java +++ b/platform/lang-api/src/com/intellij/execution/util/ListTableWithButtons.java @@ -60,24 +60,21 @@ public abstract class ListTableWithButtons extends Observable { final int row = myTableView.getEditingRow(); if (e.getModifiers() == 0 && (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_TAB)) { e.consume(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - stopEditing(); - int nextColumn = column < myTableView.getColumnCount() - 1 ? column + 1 : 0; - int nextRow = nextColumn == 0 ? row + 1 : row; - if (nextRow > myTableView.getRowCount() - 1) { - if (myElements.isEmpty() || !ListTableWithButtons.this.isEmpty(myElements.get(myElements.size() - 1))) { - ToolbarDecorator.findAddButton(myPanel).actionPerformed(null); - return; - } - else { - nextRow = 0; - } + SwingUtilities.invokeLater(() -> { + stopEditing(); + int nextColumn = column < myTableView.getColumnCount() - 1 ? column + 1 : 0; + int nextRow = nextColumn == 0 ? row + 1 : row; + if (nextRow > myTableView.getRowCount() - 1) { + if (myElements.isEmpty() || !ListTableWithButtons.this.isEmpty(myElements.get(myElements.size() - 1))) { + ToolbarDecorator.findAddButton(myPanel).actionPerformed(null); + return; + } + else { + nextRow = 0; } - myTableView.scrollRectToVisible(myTableView.getCellRect(nextRow, nextColumn, true)); - myTableView.editCellAt(nextRow, nextColumn); } + myTableView.scrollRectToVisible(myTableView.getCellRect(nextRow, nextColumn, true)); + myTableView.editCellAt(nextRow, nextColumn); }); } } @@ -97,16 +94,13 @@ public abstract class ListTableWithButtons extends Observable { public void run(AnActionButton button) { myTableView.stopEditing(); setModified(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myElements.isEmpty() || !isEmpty(myElements.get(myElements.size() - 1))) { - myElements.add(createElement()); - myTableView.getTableViewModel().setItems(myElements); - } - myTableView.scrollRectToVisible(myTableView.getCellRect(myElements.size() - 1, 0, true)); - myTableView.getComponent().editCellAt(myElements.size() - 1, 0); + SwingUtilities.invokeLater(() -> { + if (myElements.isEmpty() || !isEmpty(myElements.get(myElements.size() - 1))) { + myElements.add(createElement()); + myTableView.getTableViewModel().setItems(myElements); } + myTableView.scrollRectToVisible(myTableView.getCellRect(myElements.size() - 1, 0, true)); + myTableView.getComponent().editCellAt(myElements.size() - 1, 0); }); } }).setRemoveAction(new AnActionButtonRunnable() { diff --git a/platform/lang-api/src/com/intellij/facet/frameworks/LibrariesDownloadAssistant.java b/platform/lang-api/src/com/intellij/facet/frameworks/LibrariesDownloadAssistant.java index d9524e04affc..1231127800ac 100644 --- a/platform/lang-api/src/com/intellij/facet/frameworks/LibrariesDownloadAssistant.java +++ b/platform/lang-api/src/com/intellij/facet/frameworks/LibrariesDownloadAssistant.java @@ -136,20 +136,17 @@ public class LibrariesDownloadAssistant { @NotNull private static List convert(final String urlPrefix, @NotNull ArtifactItem[] jars) { - return ContainerUtil.mapNotNull(jars, new Function() { - @Override - public LibraryInfo fun(ArtifactItem artifactItem) { - String downloadUrl = artifactItem.getUrl(); - if (urlPrefix != null) { - if (downloadUrl == null) { - downloadUrl = artifactItem.getName(); - } - if (!downloadUrl.startsWith("http://")) { - downloadUrl = urlPrefix + downloadUrl; - } + return ContainerUtil.mapNotNull(jars, artifactItem -> { + String downloadUrl = artifactItem.getUrl(); + if (urlPrefix != null) { + if (downloadUrl == null) { + downloadUrl = artifactItem.getName(); + } + if (!downloadUrl.startsWith("http://")) { + downloadUrl = urlPrefix + downloadUrl; } - return new LibraryInfo(artifactItem.getName(), downloadUrl, downloadUrl, artifactItem.getMD5(), artifactItem.getRequiredClasses()); } + return new LibraryInfo(artifactItem.getName(), downloadUrl, downloadUrl, artifactItem.getMD5(), artifactItem.getRequiredClasses()); }); } } diff --git a/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java b/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java index 708d1eb28b39..409b367d1180 100644 --- a/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java +++ b/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java @@ -88,11 +88,8 @@ public class ArtifactItem { public String[] getRequiredClasses() { if (myRequiredClasses == null) return ArrayUtil.EMPTY_STRING_ARRAY; - final List classes = ContainerUtil.mapNotNull(myRequiredClasses, new Function() { - @Override - public String fun(RequiredClass requiredClass) { - return requiredClass.getFqn(); - } + final List classes = ContainerUtil.mapNotNull(myRequiredClasses, requiredClass -> { + return requiredClass.getFqn(); }); return ArrayUtil.toStringArray(classes); diff --git a/platform/lang-api/src/com/intellij/facet/frameworks/ui/LibrariesDownloadUiUtil.java b/platform/lang-api/src/com/intellij/facet/frameworks/ui/LibrariesDownloadUiUtil.java index 5d5e60d4caf0..3bbde2e86c23 100644 --- a/platform/lang-api/src/com/intellij/facet/frameworks/ui/LibrariesDownloadUiUtil.java +++ b/platform/lang-api/src/com/intellij/facet/frameworks/ui/LibrariesDownloadUiUtil.java @@ -72,26 +72,20 @@ public class LibrariesDownloadUiUtil { final String groupId, final URL... localUrls) { final ModalityState state = ModalityState.current(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final List newItems = new ArrayList(); - newItems.addAll(Arrays.asList(LibrariesDownloadAssistant.getVersions(groupId, localUrls))); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final List newItems = new ArrayList(); + newItems.addAll(Arrays.asList(LibrariesDownloadAssistant.getVersions(groupId, localUrls))); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - items.clear(); - if (!newItems.isEmpty()) { - items.addAll(newItems); - final CollectionComboBoxModel model = (CollectionComboBoxModel)jComboBox.getModel(); - model.update(); - jComboBox.setSelectedIndex(0); - } - jComboBox.setEnabled(true); - } - }, state); - } + ApplicationManager.getApplication().invokeLater(() -> { + items.clear(); + if (!newItems.isEmpty()) { + items.addAll(newItems); + final CollectionComboBoxModel model = (CollectionComboBoxModel)jComboBox.getModel(); + model.update(); + jComboBox.setSelectedIndex(0); + } + jComboBox.setEnabled(true); + }, state); } ); diff --git a/platform/lang-api/src/com/intellij/facet/ui/FacetDependentToolWindow.java b/platform/lang-api/src/com/intellij/facet/ui/FacetDependentToolWindow.java index 546ca636b0ee..a1b29bb604b3 100644 --- a/platform/lang-api/src/com/intellij/facet/ui/FacetDependentToolWindow.java +++ b/platform/lang-api/src/com/intellij/facet/ui/FacetDependentToolWindow.java @@ -26,11 +26,8 @@ public class FacetDependentToolWindow extends ToolWindowEP { } public List getFacetTypes() { - return ContainerUtil.mapNotNull(getFacetIds(), new NullableFunction() { - @Override - public FacetType fun(String facetId) { - return FacetTypeRegistry.getInstance().findFacetType(facetId); - } + return ContainerUtil.mapNotNull(getFacetIds(), (NullableFunction)facetId -> { + return FacetTypeRegistry.getInstance().findFacetType(facetId); }); } } diff --git a/platform/lang-api/src/com/intellij/ide/util/projectWizard/ModuleBuilder.java b/platform/lang-api/src/com/intellij/ide/util/projectWizard/ModuleBuilder.java index f7b00afd6fff..df2323204376 100644 --- a/platform/lang-api/src/com/intellij/ide/util/projectWizard/ModuleBuilder.java +++ b/platform/lang-api/src/com/intellij/ide/util/projectWizard/ModuleBuilder.java @@ -305,11 +305,8 @@ public abstract class ModuleBuilder extends AbstractModuleBuilder { StartupManager.getInstance(module.getProject()).runWhenProjectIsInitialized(new DumbAwareRunnable() { @Override public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - onModuleInitialized(module); - } + ApplicationManager.getApplication().runWriteAction(() -> { + onModuleInitialized(module); }); } }); diff --git a/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java b/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java index f3ee66225262..e74b7e726441 100644 --- a/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java +++ b/platform/lang-api/src/com/intellij/openapi/projectRoots/JdkUtil.java @@ -123,13 +123,10 @@ public class JdkUtil { File binPath = new File(homePath, "bin"); if (!binPath.exists()) return false; - FileFilter fileFilter = new FileFilter() { - @Override - public boolean accept(@NotNull File f) { - if (f.isDirectory()) return false; - String name = FileUtil.getNameWithoutExtension(f); - return "javac".equals(name) || "javah".equals(name); - } + FileFilter fileFilter = f -> { + if (f.isDirectory()) return false; + String name = FileUtil.getNameWithoutExtension(f); + return "javac".equals(name) || "javah".equals(name); }; File[] children = binPath.listFiles(fileFilter); @@ -145,12 +142,7 @@ public class JdkUtil { File binPath = new File(homePath, "bin"); if (!binPath.exists()) return false; - FileFilter fileFilter = new FileFilter() { - @Override - public boolean accept(@NotNull File f) { - return !f.isDirectory() && "java".equals(FileUtil.getNameWithoutExtension(f)); - } - }; + FileFilter fileFilter = f -> !f.isDirectory() && "java".equals(FileUtil.getNameWithoutExtension(f)); File[] children = binPath.listFiles(fileFilter); return children != null && children.length >= 1 && diff --git a/platform/lang-api/src/com/intellij/openapi/projectRoots/ui/PathEditor.java b/platform/lang-api/src/com/intellij/openapi/projectRoots/ui/PathEditor.java index 840b03b4eb50..58fc432bf738 100644 --- a/platform/lang-api/src/com/intellij/openapi/projectRoots/ui/PathEditor.java +++ b/platform/lang-api/src/com/intellij/openapi/projectRoots/ui/PathEditor.java @@ -297,12 +297,7 @@ public class PathEditor { final Object[] selectedItems = getSelectedRoots(); if (selectedItems != null) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setSelectedRoots(selectedItems); - } - }); + SwingUtilities.invokeLater(() -> setSelectedRoots(selectedItems)); } } diff --git a/platform/lang-api/src/com/intellij/openapi/vcs/checkin/HackSearch.java b/platform/lang-api/src/com/intellij/openapi/vcs/checkin/HackSearch.java index 51c15f50d3d5..e7e23ee9609d 100644 --- a/platform/lang-api/src/com/intellij/openapi/vcs/checkin/HackSearch.java +++ b/platform/lang-api/src/com/intellij/openapi/vcs/checkin/HackSearch.java @@ -41,9 +41,7 @@ public class HackSearch { myTZConvertor = TZConvertor; mySZConvertor = SZConvertor; myZComparator = zComparator; - myComparator = new Comparator() { - @Override - public int compare(S o1, S o2) { + myComparator = (o1, o2) -> { Z z1 = mySZConvertor.convert(o1); Z z2 = mySZConvertor.convert(o2); if (o1 == myFake) { @@ -52,8 +50,7 @@ public class HackSearch { z2 = myFakeConverted; } return myZComparator.compare(z1, z2); - } - }; + }; } public int search(final List list, final T item) { diff --git a/platform/lang-api/src/com/intellij/openapi/vcs/checkin/StepIntersection.java b/platform/lang-api/src/com/intellij/openapi/vcs/checkin/StepIntersection.java index a3e7df06038d..897dade15ec3 100644 --- a/platform/lang-api/src/com/intellij/openapi/vcs/checkin/StepIntersection.java +++ b/platform/lang-api/src/com/intellij/openapi/vcs/checkin/StepIntersection.java @@ -55,12 +55,7 @@ public class StepIntersection { myAreaIndex = 0; myDataConvertor = dataConvertor; myAreasConvertor = areasConvertor; - myHackSearch = new HackSearch(myDataConvertor, myAreasConvertor, new Comparator() { - @Override - public int compare(TextRange o1, TextRange o2) { - return o1.intersects(o2) ? 0 : o1.getStartOffset() < o2.getStartOffset() ? -1 : 1; - } - }); + myHackSearch = new HackSearch(myDataConvertor, myAreasConvertor, (o1, o2) -> o1.intersects(o2) ? 0 : o1.getStartOffset() < o2.getStartOffset() ? -1 : 1); } public void resetIndex() { @@ -69,12 +64,7 @@ public class StepIntersection { public List process(final Iterable data) { final List result = new ArrayList(); - process(data, new PairConsumer() { - @Override - public void consume(Data data, Area area) { - result.add(data); - } - }); + process(data, (data1, area) -> result.add(data1)); return result; } diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/DefaultArrangementEntryMatcherSerializer.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/DefaultArrangementEntryMatcherSerializer.java index 2584ec148ef1..e7652fb7a8c7 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/DefaultArrangementEntryMatcherSerializer.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/DefaultArrangementEntryMatcherSerializer.java @@ -40,27 +40,23 @@ import java.util.List; */ public class DefaultArrangementEntryMatcherSerializer { - private static final Comparator CONDITION_COMPARATOR = new Comparator() { - - @Override - public int compare(ArrangementMatchCondition c1, ArrangementMatchCondition c2) { - boolean isAtom1 = c1 instanceof ArrangementAtomMatchCondition; - boolean isAtom2 = c2 instanceof ArrangementAtomMatchCondition; - if (isAtom1 ^ isAtom2) { - return isAtom1 ? 1 : -1; // Composite conditions before atom conditions. - } - else if (!isAtom1) { - return 0; - } - - ArrangementAtomMatchCondition atom1 = (ArrangementAtomMatchCondition)c1; - ArrangementAtomMatchCondition atom2 = (ArrangementAtomMatchCondition)c2; - int cmp = atom1.getType().compareTo(atom2.getType()); - if (cmp == 0) { - cmp = atom1.getValue().toString().compareTo(atom2.getValue().toString()); - } - return cmp; + private static final Comparator CONDITION_COMPARATOR = (c1, c2) -> { + boolean isAtom1 = c1 instanceof ArrangementAtomMatchCondition; + boolean isAtom2 = c2 instanceof ArrangementAtomMatchCondition; + if (isAtom1 ^ isAtom2) { + return isAtom1 ? 1 : -1; // Composite conditions before atom conditions. } + else if (!isAtom1) { + return 0; + } + + ArrangementAtomMatchCondition atom1 = (ArrangementAtomMatchCondition)c1; + ArrangementAtomMatchCondition atom2 = (ArrangementAtomMatchCondition)c2; + int cmp = atom1.getType().compareTo(atom2.getType()); + if (cmp == 0) { + cmp = atom1.getValue().toString().compareTo(atom2.getValue().toString()); + } + return cmp; }; @NotNull private static final Logger LOG = Logger.getInstance("#" + DefaultArrangementEntryMatcherSerializer.class.getName()); diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/ArrangementStandardSettingsManager.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/ArrangementStandardSettingsManager.java index b30f21f160ac..8a5a88b74b1a 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/ArrangementStandardSettingsManager.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/ArrangementStandardSettingsManager.java @@ -40,24 +40,21 @@ public class ArrangementStandardSettingsManager { @NotNull private final TObjectIntHashMap myWidths = new TObjectIntHashMap(); @NotNull private final TObjectIntHashMap myWeights = new TObjectIntHashMap(); - @NotNull private final Comparator myComparator = new Comparator() { - @Override - public int compare(ArrangementSettingsToken t1, ArrangementSettingsToken t2) { - if (myWeights.containsKey(t1)) { - if (myWeights.containsKey(t2)) { - return myWeights.get(t1) - myWeights.get(t2); - } - else { - return -1; - } - } - else if (myWeights.containsKey(t2)) { - return 1; + @NotNull private final Comparator myComparator = (t1, t2) -> { + if (myWeights.containsKey(t1)) { + if (myWeights.containsKey(t2)) { + return myWeights.get(t1) - myWeights.get(t2); } else { - return t1.compareTo(t2); + return -1; } } + else if (myWeights.containsKey(t2)) { + return 1; + } + else { + return t1.compareTo(t2); + } }; @NotNull private final ArrangementStandardSettingsAware myDelegate; diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/CompositeArrangementSettingsToken.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/CompositeArrangementSettingsToken.java index 48287b4b9567..f39b34459632 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/CompositeArrangementSettingsToken.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/std/CompositeArrangementSettingsToken.java @@ -32,12 +32,7 @@ import java.util.List; public class CompositeArrangementSettingsToken { private static final Function WRAPPER = - new Function() { - @Override - public CompositeArrangementSettingsToken fun(ArrangementSettingsToken token) { - return new CompositeArrangementSettingsToken(token, deduceRole(token), Collections.emptyList()); - } - }; + token -> new CompositeArrangementSettingsToken(token, deduceRole(token), Collections.emptyList()); @NotNull private final List myChildren = ContainerUtilRt.newArrayList(); diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/extractor/values/Generation.java b/platform/lang-api/src/com/intellij/psi/codeStyle/extractor/values/Generation.java index d82476cf79d2..6ec6f7aff1ef 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/extractor/values/Generation.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/extractor/values/Generation.java @@ -102,12 +102,7 @@ public class Generation { } } - Collections.sort(ranges, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return o1.first - o2.first; - } - }); + Collections.sort(ranges, (o1, o2) -> o1.first - o2.first); final ArrayList gensPool = new ArrayList(newPoolSize); int count = 0; diff --git a/platform/lang-api/src/com/intellij/psi/util/PsiUtilBase.java b/platform/lang-api/src/com/intellij/psi/util/PsiUtilBase.java index a8e44fc20876..f2357e5024d0 100644 --- a/platform/lang-api/src/com/intellij/psi/util/PsiUtilBase.java +++ b/platform/lang-api/src/com/intellij/psi/util/PsiUtilBase.java @@ -45,12 +45,7 @@ import java.util.Comparator; public class PsiUtilBase extends PsiUtilCore implements PsiEditorUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.util.PsiUtilBase"); - public static final Comparator LANGUAGE_COMPARATOR = new Comparator() { - @Override - public int compare(@NotNull Language o1, @NotNull Language o2) { - return o1.getID().compareTo(o2.getID()); - } - }; + public static final Comparator LANGUAGE_COMPARATOR = (o1, o2) -> o1.getID().compareTo(o2.getID()); public static boolean isUnderPsiRoot(PsiFile root, PsiElement element) { PsiFile containingFile = element.getContainingFile(); diff --git a/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java b/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java index a03753d76590..9e85593b1906 100644 --- a/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java +++ b/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java @@ -60,17 +60,14 @@ public class RenameInputValidatorRegistry { } } - return acceptedValidators.isEmpty() ? null : new Function() { - @Override - public String fun(String newName) { - for (RenameInputValidatorEx validator : acceptedValidators.keySet()) { - final String message = validator.getErrorMessage(newName, element.getProject()); - if (message != null) { - return message; - } + return acceptedValidators.isEmpty() ? null : (Function)newName -> { + for (RenameInputValidatorEx validator : acceptedValidators.keySet()) { + final String message = validator.getErrorMessage(newName, element.getProject()); + if (message != null) { + return message; } - return null; } + return null; }; } } diff --git a/platform/lang-api/src/com/intellij/refactoring/util/CommonRefactoringUtil.java b/platform/lang-api/src/com/intellij/refactoring/util/CommonRefactoringUtil.java index 4c80f964cedc..7027e44580db 100644 --- a/platform/lang-api/src/com/intellij/refactoring/util/CommonRefactoringUtil.java +++ b/platform/lang-api/src/com/intellij/refactoring/util/CommonRefactoringUtil.java @@ -57,14 +57,12 @@ public class CommonRefactoringUtil { // order of usages across different files is irrelevant public static void sortDepthFirstRightLeftOrder(final UsageInfo[] usages) { - Arrays.sort(usages, new Comparator() { - public int compare(final UsageInfo usage1, final UsageInfo usage2) { - PsiElement element1 = usage1.getElement(), element2 = usage2.getElement(); - if (element1 == element2) return 0; - if (element1 == null) return 1; - if (element2 == null) return -1; - return element2.getTextRange().getStartOffset() - element1.getTextRange().getStartOffset(); - } + Arrays.sort(usages, (usage1, usage2) -> { + PsiElement element1 = usage1.getElement(), element2 = usage2.getElement(); + if (element1 == element2) return 0; + if (element1 == null) return 1; + if (element2 == null) return -1; + return element2.getTextRange().getStartOffset() - element1.getTextRange().getStartOffset(); }); } @@ -84,15 +82,12 @@ public class CommonRefactoringUtil { @Nullable final String helpId) { if (ApplicationManager.getApplication().isUnitTestMode()) throw new RefactoringErrorHintException(message); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (editor == null || editor.getComponent().getRootPane() == null) { - showErrorMessage(title, message, helpId, project); - } - else { - HintManager.getInstance().showErrorHint(editor, message); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (editor == null || editor.getComponent().getRootPane() == null) { + showErrorMessage(title, message, helpId, project); + } + else { + HintManager.getInstance().showErrorHint(editor, message); } }); } diff --git a/platform/lang-api/src/com/intellij/refactoring/util/MoveRenameUsageInfo.java b/platform/lang-api/src/com/intellij/refactoring/util/MoveRenameUsageInfo.java index 618931700adb..4208cba66d06 100644 --- a/platform/lang-api/src/com/intellij/refactoring/util/MoveRenameUsageInfo.java +++ b/platform/lang-api/src/com/intellij/refactoring/util/MoveRenameUsageInfo.java @@ -96,12 +96,7 @@ public class MoveRenameUsageInfo extends UsageInfo{ return myReference; } - final PsiReference reference = checkReferenceRange(element, new Function() { - @Override - public PsiReference fun(Integer start) { - return myReference; - } - }); + final PsiReference reference = checkReferenceRange(element, start -> myReference); if (reference != null) { return reference; @@ -114,12 +109,7 @@ public class MoveRenameUsageInfo extends UsageInfo{ if (element == null || !element.isValid()) { return null; } - return checkReferenceRange(element, new Function() { - @Override - public PsiReference fun(Integer start) { - return element.findReferenceAt(start); - } - }); + return checkReferenceRange(element, start -> element.findReferenceAt(start)); } @Nullable diff --git a/platform/lang-impl/src/com/intellij/application/options/CodeStyleAbstractPanel.java b/platform/lang-impl/src/com/intellij/application/options/CodeStyleAbstractPanel.java index 63a5ddc765d7..1cc364ea7c6b 100644 --- a/platform/lang-impl/src/com/intellij/application/options/CodeStyleAbstractPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/CodeStyleAbstractPanel.java @@ -186,12 +186,7 @@ public abstract class CodeStyleAbstractPanel implements Disposable { int currOffs = myEditor.getScrollingModel().getVerticalScrollOffset(); final Project finalProject = ProjectUtil.guessCurrentProject(getPanel()); - CommandProcessor.getInstance().executeCommand(finalProject, new Runnable() { - @Override - public void run() { - replaceText(finalProject); - } - }, null, null); + CommandProcessor.getInstance().executeCommand(finalProject, () -> replaceText(finalProject), null, null); myEditor.getSettings().setRightMargin(getAdjustedRightMargin()); myLastDocumentModificationStamp = myEditor.getDocument().getModificationStamp(); @@ -206,43 +201,40 @@ public abstract class CodeStyleAbstractPanel implements Disposable { protected abstract int getRightMargin(); private void replaceText(final Project project) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { + try { + Document beforeReformat = null; + beforeReformat = collectChangesBeforeCurrentSettingsAppliance(project); + + //important not mark as generated not to get the classes before setting language level + PsiFile psiFile = createFileFromText(project, myTextToReformat); + prepareForReformat(psiFile); + try { - Document beforeReformat = null; - beforeReformat = collectChangesBeforeCurrentSettingsAppliance(project); - - //important not mark as generated not to get the classes before setting language level - PsiFile psiFile = createFileFromText(project, myTextToReformat); - prepareForReformat(psiFile); - - try { - apply(mySettings); - } - catch (ConfigurationException ignore) { - } - CodeStyleSettings clone = mySettings.clone(); - clone.setRightMargin(getDefaultLanguage(), getAdjustedRightMargin()); - CodeStyleSettingsManager.getInstance(project).setTemporarySettings(clone); - PsiFile formatted; - try { - formatted = doReformat(project, psiFile); - } - finally { - CodeStyleSettingsManager.getInstance(project).dropTemporarySettings(); - } - - myEditor.getSettings().setTabSize(clone.getTabSize(getFileType())); - Document document = myEditor.getDocument(); - document.replaceString(0, document.getTextLength(), formatted.getText()); - if (document != null && beforeReformat != null) { - highlightChanges(beforeReformat); - } + apply(mySettings); } - catch (IncorrectOperationException e) { - LOG.error(e); + catch (ConfigurationException ignore) { } + CodeStyleSettings clone = mySettings.clone(); + clone.setRightMargin(getDefaultLanguage(), getAdjustedRightMargin()); + CodeStyleSettingsManager.getInstance(project).setTemporarySettings(clone); + PsiFile formatted; + try { + formatted = doReformat(project, psiFile); + } + finally { + CodeStyleSettingsManager.getInstance(project).dropTemporarySettings(); + } + + myEditor.getSettings().setTabSize(clone.getTabSize(getFileType())); + Document document = myEditor.getDocument(); + document.replaceString(0, document.getTextLength(), formatted.getText()); + if (document != null && beforeReformat != null) { + highlightChanges(beforeReformat); + } + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); } @@ -493,12 +485,7 @@ public abstract class CodeStyleAbstractPanel implements Disposable { updateEditor(true); } else { - UiNotifyConnector.doWhenFirstShown(myEditor.getComponent(), new Runnable() { - @Override - public void run() { - addUpdatePreviewRequest(); - } - }); + UiNotifyConnector.doWhenFirstShown(myEditor.getComponent(), () -> addUpdatePreviewRequest()); } } } diff --git a/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java b/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java index 6dcd4037f7f2..9f6e863d1f61 100644 --- a/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java @@ -206,18 +206,15 @@ public class CodeStyleSchemesConfigurable extends SearchableConfigurable.Parent. final List providers = Arrays.asList(Extensions.getExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME)); - Collections.sort(providers, new Comparator() { - @Override - public int compare(CodeStyleSettingsProvider p1, CodeStyleSettingsProvider p2) { - if (!p1.getPriority().equals(p2.getPriority())) { - return p1.getPriority().compareTo(p2.getPriority()); - } - String name1 = p1.getConfigurableDisplayName(); - if (name1 == null) name1 = ""; - String name2 = p2.getConfigurableDisplayName(); - if (name2 == null) name2 = ""; - return name1.compareToIgnoreCase(name2); + Collections.sort(providers, (p1, p2) -> { + if (!p1.getPriority().equals(p2.getPriority())) { + return p1.getPriority().compareTo(p2.getPriority()); } + String name1 = p1.getConfigurableDisplayName(); + if (name1 == null) name1 = ""; + String name2 = p2.getConfigurableDisplayName(); + if (name2 == null) name2 = ""; + return name1.compareToIgnoreCase(name2); }); for (final CodeStyleSettingsProvider provider : providers) { diff --git a/platform/lang-impl/src/com/intellij/application/options/CodeStyleSettingsUtilImpl.java b/platform/lang-impl/src/com/intellij/application/options/CodeStyleSettingsUtilImpl.java index 418cc3ccef6d..1a7cbdab9b4a 100644 --- a/platform/lang-impl/src/com/intellij/application/options/CodeStyleSettingsUtilImpl.java +++ b/platform/lang-impl/src/com/intellij/application/options/CodeStyleSettingsUtilImpl.java @@ -33,12 +33,9 @@ public class CodeStyleSettingsUtilImpl extends CodeStyleSettingsUtil { CodeStyleSettingsManager settingsManager = CodeStyleSettingsManager.getInstance(project); CodeStyleSettings savedSettings = settingsManager.getCurrentSettings().clone(); final CodeStyleSchemesConfigurable configurable = new CodeStyleSchemesConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - if (pageToSelect != null) { - configurable.selectPage(pageToSelect); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + if (pageToSelect != null) { + configurable.selectPage(pageToSelect); } }); diff --git a/platform/lang-impl/src/com/intellij/application/options/TabbedLanguageCodeStylePanel.java b/platform/lang-impl/src/com/intellij/application/options/TabbedLanguageCodeStylePanel.java index f6ffbb3aee27..8f9d261980c9 100644 --- a/platform/lang-impl/src/com/intellij/application/options/TabbedLanguageCodeStylePanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/TabbedLanguageCodeStylePanel.java @@ -327,12 +327,7 @@ public abstract class TabbedLanguageCodeStylePanel extends CodeStyleAbstractPane langItems.add(langItem); } } - Collections.sort(langItems, new Comparator() { - @Override - public int compare(JMenuItem item1, JMenuItem item2) { - return item1.getText().compareToIgnoreCase(item2.getText()); - } - }); + Collections.sort(langItems, (item1, item2) -> item1.getText().compareToIgnoreCase(item2.getText())); for (JMenuItem langItem : langItems) { parentMenu.add(langItem); } diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleMainPanel.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleMainPanel.java index bec159831858..e51f42a0d23f 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleMainPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleMainPanel.java @@ -137,27 +137,19 @@ public class CodeStyleMainPanel extends JPanel implements TabbedLanguageCodeStyl public void onCurrentSchemeChanged() { myLayout.show(mySettingsPanel, WAIT_CARD); - final Runnable replaceLayout = new Runnable() { - @Override - public void run() { - if (!myIsDisposed) { - ensureCurrentPanel().onSomethingChanged(); - String schemeName = myModel.getSelectedScheme().getName(); - updateSetFrom(); - myLayout.show(mySettingsPanel, schemeName); - } + final Runnable replaceLayout = () -> { + if (!myIsDisposed) { + ensureCurrentPanel().onSomethingChanged(); + String schemeName = myModel.getSelectedScheme().getName(); + updateSetFrom(); + myLayout.show(mySettingsPanel, schemeName); } }; if (ApplicationManager.getApplication().isHeadlessEnvironment()) { replaceLayout.run(); } else { myAlarm.cancelAllRequests(); - final Runnable request = new Runnable() { - @Override - public void run() { - SwingUtilities.invokeLater(replaceLayout); - } - }; + final Runnable request = () -> SwingUtilities.invokeLater(replaceLayout); myAlarm.addRequest(request, 200); } } diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java index 22b7c2bb7297..65a0bd334835 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemeExporterUI.java @@ -60,12 +60,7 @@ class CodeStyleSchemeExporterUI { new BaseListPopupStep(ApplicationBundle.message("scheme.exporter.ui.export.as.title"), enumExporters()) { @Override public PopupStep onChosen(final String selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - exportSchemeUsing(selectedValue); - } - }); + return doFinalStep(() -> exportSchemeUsing(selectedValue)); } }); popup.showInCenterOf(myParentComponent); diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesPanel.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesPanel.java index b4a2a2476a00..4969390f23e7 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesPanel.java @@ -50,12 +50,7 @@ public class CodeStyleSchemesPanel { @Override public void actionPerformed(@NotNull ActionEvent e) { if (!myIsReset) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - onCombo(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> onCombo()); } } }); diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CustomizableLanguageCodeStylePanel.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CustomizableLanguageCodeStylePanel.java index 46e919fdf2b8..da2963118547 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CustomizableLanguageCodeStylePanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CustomizableLanguageCodeStylePanel.java @@ -132,24 +132,16 @@ public abstract class CustomizableLanguageCodeStylePanel extends CodeStyleAbstra final String text = psiFile.getText(); final PsiDocumentManager manager = PsiDocumentManager.getInstance(project); final Document doc = manager.getDocument(psiFile); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - doc.replaceString(0, doc.getTextLength(), text); - manager.commitDocument(doc); - try { - CodeStyleManager.getInstance(project).reformat(psiFile); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); - } - }, "", ""); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + doc.replaceString(0, doc.getTextLength(), text); + manager.commitDocument(doc); + try { + CodeStyleManager.getInstance(project).reformat(psiFile); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), "", ""); if (doc != null) { manager.commitDocument(doc); } diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/OptionTreeWithPreviewPanel.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/OptionTreeWithPreviewPanel.java index 152aa711fb55..f105f64fcbec 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/OptionTreeWithPreviewPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/OptionTreeWithPreviewPanel.java @@ -232,22 +232,19 @@ public abstract class OptionTreeWithPreviewPanel extends CustomizableLanguageCod final List groupOrder = getGroupOrder(options); List result = new ArrayList(options.size()); result.addAll(options); - Collections.sort(result, new Comparator(){ - @Override - public int compare(BooleanOptionKey key1, BooleanOptionKey key2) { - String group1 = key1.groupName; - String group2 = key2.groupName; - if (group1 == null) { - return group2 == null ? 0 : 1; - } - if (group2 == null) { - return -1; - } - Integer index1 = groupOrder.indexOf(group1); - Integer index2 = groupOrder.indexOf(group2); - if (index1 == -1 || index2 == -1) return group1.compareToIgnoreCase(group2); - return index1.compareTo(index2); + Collections.sort(result, (key1, key2) -> { + String group1 = key1.groupName; + String group2 = key2.groupName; + if (group1 == null) { + return group2 == null ? 0 : 1; } + if (group2 == null) { + return -1; + } + Integer index1 = groupOrder.indexOf(group1); + Integer index2 = groupOrder.indexOf(group2); + if (index1 == -1 || index2 == -1) return group1.compareToIgnoreCase(group2); + return index1.compareTo(index2); }); return result; } diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/AbstractMoveArrangementRuleAction.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/AbstractMoveArrangementRuleAction.java index 7503a2cb8975..3729fc729cbb 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/AbstractMoveArrangementRuleAction.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/AbstractMoveArrangementRuleAction.java @@ -59,53 +59,50 @@ public abstract class AbstractMoveArrangementRuleAction extends AbstractArrangem final int editing = control.getEditingRow() - 1; - control.runOperationIgnoreSelectionChange(new Runnable() { - @Override - public void run() { - control.hideEditor(); - final List mappings = new ArrayList(); - fillMappings(control, mappings); + control.runOperationIgnoreSelectionChange(() -> { + control.hideEditor(); + final List mappings = new ArrayList(); + fillMappings(control, mappings); - if (mappings.isEmpty()) { - return; - } + if (mappings.isEmpty()) { + return; + } - int newRowToEdit = editing; - ArrangementMatchingRulesModel model = control.getModel(); - Object value; - int from; - int to; - for (int[] pair : mappings) { - from = pair[0]; - to = pair[1]; - if (from != to) { - value = model.getElementAt(from); - model.removeRow(from); - model.insert(to, value); - if (newRowToEdit == from) { - newRowToEdit = to; - } + int newRowToEdit = editing; + ArrangementMatchingRulesModel model = control.getModel(); + Object value; + int from; + int to; + for (int[] pair : mappings) { + from = pair[0]; + to = pair[1]; + if (from != to) { + value = model.getElementAt(from); + model.removeRow(from); + model.insert(to, value); + if (newRowToEdit == from) { + newRowToEdit = to; } } + } - ListSelectionModel selectionModel = control.getSelectionModel(); - for (int[] pair : mappings) { - selectionModel.addSelectionInterval(pair[1], pair[1]); - } + ListSelectionModel selectionModel = control.getSelectionModel(); + for (int[] pair : mappings) { + selectionModel.addSelectionInterval(pair[1], pair[1]); + } - int visibleRow = -1; - if (newRowToEdit >= 0) { - control.showEditor(newRowToEdit); - visibleRow = newRowToEdit; - } - else if (!mappings.isEmpty()) { - visibleRow = mappings.get(0)[1]; - } + int visibleRow = -1; + if (newRowToEdit >= 0) { + control.showEditor(newRowToEdit); + visibleRow = newRowToEdit; + } + else if (!mappings.isEmpty()) { + visibleRow = mappings.get(0)[1]; + } - if (visibleRow != -1) { - scrollRowToVisible(control, visibleRow); - } + if (visibleRow != -1) { + scrollRowToVisible(control, visibleRow); } }); control.repaintRows(0, control.getModel().getSize() - 1, true); diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/RemoveArrangementRuleAction.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/RemoveArrangementRuleAction.java index 5f03e2592c25..ae8210dbce80 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/RemoveArrangementRuleAction.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/action/RemoveArrangementRuleAction.java @@ -57,13 +57,10 @@ public class RemoveArrangementRuleAction extends AbstractArrangementRuleAction i } final ArrangementMatchingRulesModel model = control.getModel(); - control.runOperationIgnoreSelectionChange(new Runnable() { - @Override - public void run() { - for (int i = 0; i < rowsToRemove.size(); i++) { - int row = rowsToRemove.get(i); - model.removeRow(row); - } + control.runOperationIgnoreSelectionChange(() -> { + for (int i = 0; i < rowsToRemove.size(); i++) { + int row = rowsToRemove.get(i); + model.removeRow(row); } }); } diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementComboBoxUiComponent.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementComboBoxUiComponent.java index 9cfce2abc0ab..99665bbf2a54 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementComboBoxUiComponent.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementComboBoxUiComponent.java @@ -42,12 +42,7 @@ public class ArrangementComboBoxUiComponent extends AbstractArrangementUiCompone public ArrangementComboBoxUiComponent(@NotNull List tokens) { super(tokens); ArrangementSettingsToken[] tokensArray = tokens.toArray(new ArrangementSettingsToken[tokens.size()]); - Arrays.sort(tokensArray, new Comparator() { - @Override - public int compare(ArrangementSettingsToken t1, ArrangementSettingsToken t2) { - return t1.getRepresentationValue().compareTo(t2.getRepresentationValue()); - } - }); + Arrays.sort(tokensArray, (t1, t2) -> t1.getRepresentationValue().compareTo(t2.getRepresentationValue())); myComboBox = new JComboBox(tokensArray); myComboBox.setRenderer(new ListCellRendererWrapper() { @Override diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementTextFieldUiComponent.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementTextFieldUiComponent.java index 0e93b8a97ba1..ff95cf47e62f 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementTextFieldUiComponent.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/component/ArrangementTextFieldUiComponent.java @@ -62,12 +62,7 @@ public class ArrangementTextFieldUiComponent extends AbstractArrangementUiCompon private void scheduleUpdate() { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - fireStateChanged(); - } - }, ArrangementConstants.TEXT_UPDATE_DELAY_MILLIS); + myAlarm.addRequest(() -> fireStateChanged(), ArrangementConstants.TEXT_UPDATE_DELAY_MILLIS); } @NotNull diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java b/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java index 5d37da2c62de..281e7d446a99 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java @@ -165,14 +165,11 @@ public class ColorAndFontOptions extends SearchableConfigurable.Parent.Abstract @NotNull public String[] getSchemeNames() { List schemes = new ArrayList(mySchemes.values()); - Collections.sort(schemes, new Comparator() { - @Override - public int compare(@NotNull MyColorScheme o1, @NotNull MyColorScheme o2) { - if (isReadOnly(o1) && !isReadOnly(o2)) return -1; - if (!isReadOnly(o1) && isReadOnly(o2)) return 1; + Collections.sort(schemes, (o1, o2) -> { + if (isReadOnly(o1) && !isReadOnly(o2)) return -1; + if (!isReadOnly(o1) && isReadOnly(o2)) return 1; - return o1.getName().compareToIgnoreCase(o2.getName()); - } + return o1.getName().compareToIgnoreCase(o2.getName()); }); List names = new ArrayList(schemes.size()); @@ -375,23 +372,20 @@ public class ColorAndFontOptions extends SearchableConfigurable.Parent.Abstract }); } Collections.addAll(extensions, Extensions.getExtensions(ColorAndFontPanelFactory.EP_NAME)); - Collections.sort(extensions, new Comparator() { - @Override - public int compare(ColorAndFontPanelFactory f1, ColorAndFontPanelFactory f2) { - if (f1 instanceof DisplayPrioritySortable) { - if (f2 instanceof DisplayPrioritySortable) { - int result = ((DisplayPrioritySortable)f1).getPriority().compareTo(((DisplayPrioritySortable)f2).getPriority()); - if (result != 0) return result; - } - else { - return 1; - } + Collections.sort(extensions, (f1, f2) -> { + if (f1 instanceof DisplayPrioritySortable) { + if (f2 instanceof DisplayPrioritySortable) { + int result1 = ((DisplayPrioritySortable)f1).getPriority().compareTo(((DisplayPrioritySortable)f2).getPriority()); + if (result1 != 0) return result1; } - else if (f2 instanceof DisplayPrioritySortable) { - return -1; + else { + return 1; } - return f1.getPanelDisplayName().compareToIgnoreCase(f2.getPanelDisplayName()); } + else if (f2 instanceof DisplayPrioritySortable) { + return -1; + } + return f1.getPanelDisplayName().compareToIgnoreCase(f2.getPanelDisplayName()); }); result.addAll(extensions); @@ -535,12 +529,7 @@ public class ColorAndFontOptions extends SearchableConfigurable.Parent.Abstract List> list = new ArrayList>(namedScopes); - Collections.sort(list, new Comparator>() { - @Override - public int compare(@NotNull final Pair o1, @NotNull final Pair o2) { - return o1.getFirst().getName().compareToIgnoreCase(o2.getFirst().getName()); - } - }); + Collections.sort(list, (o1, o2) -> o1.getFirst().getName().compareToIgnoreCase(o2.getFirst().getName())); for (Pair pair : list) { NamedScope namedScope = pair.getFirst(); String name = namedScope.getName(); diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/ColorOptionsTree.java b/platform/lang-impl/src/com/intellij/application/options/colors/ColorOptionsTree.java index 0820737fdb47..3c431b189946 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/ColorOptionsTree.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/ColorOptionsTree.java @@ -35,12 +35,8 @@ public class ColorOptionsTree extends Tree { public final static String NAME_SEPARATOR = "//"; - private static final Comparator ATTR_COMPARATOR = new Comparator() { - @Override - public int compare(EditorSchemeAttributeDescriptor o1, EditorSchemeAttributeDescriptor o2) { - return StringUtil.naturalCompare(o1.toString(), o2.toString()); - } - }; + private static final Comparator ATTR_COMPARATOR = + (o1, o2) -> StringUtil.naturalCompare(o1.toString(), o2.toString()); public ColorOptionsTree(@NotNull String categoryName) { super(createTreeModel()); diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/OptionsPanelImpl.java b/platform/lang-impl/src/com/intellij/application/options/colors/OptionsPanelImpl.java index 1ac7b419e059..e46dd0023124 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/OptionsPanelImpl.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/OptionsPanelImpl.java @@ -159,12 +159,7 @@ public class OptionsPanelImpl extends JPanel implements OptionsPanel { @Override public Runnable showOption(final String attributeDisplayName) { - return new Runnable() { - @Override - public void run() { - myOptionsTree.selectOptionByName(attributeDisplayName); - } - }; + return () -> myOptionsTree.selectOptionByName(attributeDisplayName); } @Override diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java b/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java index c640cd996bc8..598eb0416c30 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java @@ -147,11 +147,8 @@ public class SchemesPanel extends JPanel implements SkipSelfSearchComponent { button.addActionListener(new ActionListener() { @Override public void actionPerformed(@NotNull ActionEvent e) { - importHandler.performImport(button, new Consumer() { - @Override - public void consume(EditorColorsScheme scheme) { - if (scheme != null) myOptions.addImportedScheme(scheme); - } + importHandler.performImport(button, scheme -> { + if (scheme != null) myOptions.addImportedScheme(scheme); }); } }); diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java b/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java index 22eca017d876..b1423acfa245 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java @@ -178,16 +178,13 @@ public class SimpleEditorPreview implements PreviewPanel{ } private void updateHighlighters() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myEditor.isDisposed()) return; - myEditor.getMarkupModel().removeAllHighlighters(); - HighlightData[] datum = myHighlightData; - final Map displayText = ColorSettingsUtil.keyToDisplayTextMap(myPage); - for (final HighlightData data : datum) { - data.addHighlToView(myEditor, myOptions.getSelectedScheme(), displayText); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myEditor.isDisposed()) return; + myEditor.getMarkupModel().removeAllHighlighters(); + HighlightData[] datum = myHighlightData; + final Map displayText = ColorSettingsUtil.keyToDisplayTextMap(myPage); + for (final HighlightData data : datum) { + data.addHighlToView(myEditor, myOptions.getSelectedScheme(), displayText); } }); } @@ -282,12 +279,7 @@ public class SimpleEditorPreview implements PreviewPanel{ final Map displayText = ColorSettingsUtil.keyToDisplayTextMap(page); // sort highlights to avoid overlappings - Collections.sort(highlights, new Comparator() { - @Override - public int compare(HighlightData highlightData1, HighlightData highlightData2) { - return highlightData1.getStartOffset() - highlightData2.getStartOffset(); - } - }); + Collections.sort(highlights, (highlightData1, highlightData2) -> highlightData1.getStartOffset() - highlightData2.getStartOffset()); for (int i = highlights.size() - 1; i >= 0; i--) { HighlightData highlightData = highlights.get(i); int startOffset = highlightData.getStartOffset(); @@ -302,12 +294,7 @@ public class SimpleEditorPreview implements PreviewPanel{ } } alarm.cancelAllRequests(); - alarm.addComponentRequest(new Runnable() { - @Override - public void run() { - startBlinkingHighlights(editor, highlightDatum, attrKey, highlighter, !show, alarm, count - 1, page); - } - }, 400); + alarm.addComponentRequest(() -> startBlinkingHighlights(editor, highlightDatum, attrKey, highlighter, !show, alarm, count - 1, page), 400); return matchingHighlights; } diff --git a/platform/lang-impl/src/com/intellij/application/options/editor/CodeFoldingConfigurable.java b/platform/lang-impl/src/com/intellij/application/options/editor/CodeFoldingConfigurable.java index 62203db42ae2..c674752ee3ac 100644 --- a/platform/lang-impl/src/com/intellij/application/options/editor/CodeFoldingConfigurable.java +++ b/platform/lang-impl/src/com/intellij/application/options/editor/CodeFoldingConfigurable.java @@ -85,20 +85,17 @@ public class CodeFoldingConfigurable extends CompositeConfigurable each : toUpdate) { - if (each.second == null || each.second.isDisposed()) { - continue; - } - final CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(each.second); - if (foldingManager != null) { - foldingManager.buildInitialFoldings(each.first); - } - } - EditorOptionsPanel.reinitAllEditors(); - } + ApplicationManager.getApplication().invokeLater(() -> { + for (Pair each : toUpdate) { + if (each.second == null || each.second.isDisposed()) { + continue; + } + final CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(each.second); + if (foldingManager != null) { + foldingManager.buildInitialFoldings(each.first); + } + } + EditorOptionsPanel.reinitAllEditors(); }, ModalityState.NON_MODAL); } diff --git a/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java b/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java index f9e1f683ba0d..93d6c610bc8b 100644 --- a/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java @@ -76,13 +76,9 @@ public class GutterIconsConfigurable implements Configurable, Configurable.NoScr @SuppressWarnings("unchecked") LanguageExtensionPoint[] extensions = (LanguageExtensionPoint[])point.getExtensions(); NullableFunction, PluginDescriptor> function = - new NullableFunction, PluginDescriptor>() { - @Nullable - @Override - public PluginDescriptor fun(LanguageExtensionPoint point) { - LineMarkerProvider instance = point.getInstance(); - return instance instanceof LineMarkerProviderDescriptor && ((LineMarkerProviderDescriptor)instance).getName() != null ? point.getPluginDescriptor() : null; - } + point1 -> { + LineMarkerProvider instance = point1.getInstance(); + return instance instanceof LineMarkerProviderDescriptor && ((LineMarkerProviderDescriptor)instance).getName() != null ? point1.getPluginDescriptor() : null; }; MultiMap> map = ContainerUtil.groupBy(Arrays.asList(extensions), function); Map pluginDescriptorMap = ContainerUtil.newHashMap(); @@ -119,12 +115,9 @@ public class GutterIconsConfigurable implements Configurable, Configurable.NoScr } myDescriptors.addAll(options); */ - myDescriptors.sort(new Comparator() { - @Override - public int compare(GutterIconDescriptor o1, GutterIconDescriptor o2) { - if (pluginDescriptorMap.get(o1) != pluginDescriptorMap.get(o2)) return 0; - return Comparing.compare(o1.getName(), o2.getName()); - } + myDescriptors.sort((o1, o2) -> { + if (pluginDescriptorMap.get(o1) != pluginDescriptorMap.get(o2)) return 0; + return Comparing.compare(o1.getName(), o2.getName()); }); PluginDescriptor current = null; for (GutterIconDescriptor descriptor : myDescriptors) { @@ -135,12 +128,7 @@ public class GutterIconsConfigurable implements Configurable, Configurable.NoScr } } - myList.setItems(myDescriptors, new Function() { - @Override - public String fun(GutterIconDescriptor descriptor) { - return descriptor.getName(); - } - }); + myList.setItems(myDescriptors, descriptor -> descriptor.getName()); myShowGutterIconsJBCheckBox.addChangeListener(e -> myList.setEnabled(myShowGutterIconsJBCheckBox.isSelected())); return myPanel; } diff --git a/platform/lang-impl/src/com/intellij/codeEditor/printing/ExportToHTMLManager.java b/platform/lang-impl/src/com/intellij/codeEditor/printing/ExportToHTMLManager.java index ac7b2d3a92b4..9da506c24d98 100644 --- a/platform/lang-impl/src/com/intellij/codeEditor/printing/ExportToHTMLManager.java +++ b/platform/lang-impl/src/com/intellij/codeEditor/printing/ExportToHTMLManager.java @@ -142,29 +142,26 @@ class ExportToHTMLManager { return true; } - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (!psiFile.isValid()) { - return; - } - TreeMap refMap = null; - for (PrintOption printOption : Extensions.getExtensions(PrintOption.EP_NAME)) { - final TreeMap map = printOption.collectReferences(psiFile, filesMap); - if (map != null) { - refMap = new TreeMap(); - refMap.putAll(map); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (!psiFile.isValid()) { + return; + } + TreeMap refMap = null; + for (PrintOption printOption : Extensions.getExtensions(PrintOption.EP_NAME)) { + final TreeMap map = printOption.collectReferences(psiFile, filesMap); + if (map != null) { + refMap = new TreeMap(); + refMap.putAll(map); } + } - String dirName = constructOutputDirectory(psiFile, outputDirectoryName); - HTMLTextPainter textPainter = new HTMLTextPainter(psiFile, project, dirName, exportToHTMLSettings.PRINT_LINE_NUMBERS); - try { - textPainter.paint(refMap, psiFile.getFileType()); - } - catch (FileNotFoundException e) { - myLastException = e; - } + String dirName = constructOutputDirectory(psiFile, outputDirectoryName); + HTMLTextPainter textPainter = new HTMLTextPainter(psiFile, project, dirName, exportToHTMLSettings.PRINT_LINE_NUMBERS); + try { + textPainter.paint(refMap, psiFile.getFileType()); + } + catch (FileNotFoundException e) { + myLastException = e; } }); return myLastException == null; @@ -254,15 +251,12 @@ class ExportToHTMLManager { final ArrayList filesList = new ArrayList(); final boolean isRecursive = myExportToHTMLSettings.isIncludeSubdirectories(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - try { - addToPsiFileList(myPsiDirectory, filesList, isRecursive, myOutputDirectoryName); - } - catch (FileNotFoundException e) { - myLastException = e; - } + ApplicationManager.getApplication().runReadAction(() -> { + try { + addToPsiFileList(myPsiDirectory, filesList, isRecursive, myOutputDirectoryName); + } + catch (FileNotFoundException e) { + myLastException = e; } }); if (myLastException != null) { diff --git a/platform/lang-impl/src/com/intellij/codeEditor/printing/FileSeparatorProvider.java b/platform/lang-impl/src/com/intellij/codeEditor/printing/FileSeparatorProvider.java index c4cadd3da7af..20bd37da2886 100644 --- a/platform/lang-impl/src/com/intellij/codeEditor/printing/FileSeparatorProvider.java +++ b/platform/lang-impl/src/com/intellij/codeEditor/printing/FileSeparatorProvider.java @@ -43,11 +43,7 @@ public class FileSeparatorProvider { } } - Collections.sort(result, new Comparator() { - public int compare(final LineMarkerInfo i1, final LineMarkerInfo i2) { - return getDisplayLine(i1, document) - getDisplayLine(i2, document); - } - }); + Collections.sort(result, (i1, i2) -> getDisplayLine(i1, document) - getDisplayLine(i2, document)); return result; } diff --git a/platform/lang-impl/src/com/intellij/codeEditor/printing/PrintManager.java b/platform/lang-impl/src/com/intellij/codeEditor/printing/PrintManager.java index c877970bc289..382a03a15ff6 100644 --- a/platform/lang-impl/src/com/intellij/codeEditor/printing/PrintManager.java +++ b/platform/lang-impl/src/com/intellij/codeEditor/printing/PrintManager.java @@ -221,11 +221,8 @@ class PrintManager { private static TextPainter initTextPainter(@NotNull final DocumentEx doc, final Project project) { final TextPainter[] res = new TextPainter[1]; ApplicationManager.getApplication().runReadAction( - new Runnable() { - @Override - public void run() { - res[0] = doInitTextPainter(doc, project); - } + () -> { + res[0] = doInitTextPainter(doc, project); } ); return res[0]; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java b/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java index 520b3cdc793b..429ce7aaf11d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java @@ -86,12 +86,7 @@ public class AutoPopupController implements Disposable { } }, this); - IdeEventQueue.getInstance().addActivityListener(new Runnable() { - @Override - public void run() { - cancelAllRequest(); - } - }, this); + IdeEventQueue.getInstance().addActivityListener(() -> cancelAllRequest(), this); } public void autoPopupMemberLookup(final Editor editor, @Nullable final Condition condition){ @@ -142,12 +137,7 @@ public class AutoPopupController implements Disposable { } private void addRequest(final Runnable request, final int delay) { - Runnable runnable = new Runnable() { - @Override - public void run() { - myAlarm.addRequest(request, delay); - } - }; + Runnable runnable = () -> myAlarm.addRequest(request, delay); if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightUtilBase.java b/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightUtilBase.java index 63dfe57da45a..192b448d5127 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightUtilBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/CodeInsightUtilBase.java @@ -52,13 +52,10 @@ public class CodeInsightUtilBase extends CodeInsightUtilCore { if (ReadonlyStatusHandler.ensureFilesWritable(project, file)) { return true; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), true); - if (editor != null && editor.getComponent().isDisplayable()) { - HintManager.getInstance().showErrorHint(editor, CodeInsightBundle.message("error.hint.file.is.readonly", file.getPresentableUrl())); - } + ApplicationManager.getApplication().invokeLater(() -> { + final Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), true); + if (editor != null && editor.getComponent().isDisplayable()) { + HintManager.getInstance().showErrorHint(editor, CodeInsightBundle.message("error.hint.file.is.readonly", file.getPresentableUrl())); } }, project.getDisposed()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/TargetElementUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/TargetElementUtil.java index c1371d346b26..ff809a603de0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/TargetElementUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/TargetElementUtil.java @@ -322,20 +322,17 @@ public class TargetElementUtil extends TargetElementUtilBase { if (element == null) return null; final List targets = ContainerUtil.newArrayList(); - final Consumer consumer = new Consumer() { - @Override - public void consume(PomTarget target) { - if (target instanceof PsiDeclaredTarget) { - final PsiDeclaredTarget declaredTarget = (PsiDeclaredTarget)target; - final PsiElement navigationElement = declaredTarget.getNavigationElement(); - final TextRange range = declaredTarget.getNameIdentifierRange(); - if (range != null && !range.shiftRight(navigationElement.getTextRange().getStartOffset()) - .contains(element.getTextRange().getStartOffset() + offsetInElement)) { - return; - } + final Consumer consumer = target -> { + if (target instanceof PsiDeclaredTarget) { + final PsiDeclaredTarget declaredTarget = (PsiDeclaredTarget)target; + final PsiElement navigationElement = declaredTarget.getNavigationElement(); + final TextRange range = declaredTarget.getNameIdentifierRange(); + if (range != null && !range.shiftRight(navigationElement.getTextRange().getStartOffset()) + .contains(element.getTextRange().getStartOffset() + offsetInElement)) { + return; } - targets.add(target); } + targets.add(target); }; PsiElement parent = element; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/AbstractLayoutCodeProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/AbstractLayoutCodeProcessor.java index 71c4bf725be2..5149924c39ff 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/AbstractLayoutCodeProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/AbstractLayoutCodeProcessor.java @@ -225,23 +225,17 @@ public abstract class AbstractLayoutCodeProcessor { final FutureTask previousTask = getPreviousProcessorTask(file, processChangedTextOnly); final FutureTask currentTask = prepareTask(file, processChangedTextOnly); - return new FutureTask(new Callable() { - @Override - public Boolean call() throws Exception { - if (previousTask != null) { - previousTask.run(); - if (!previousTask.get() || previousTask.isCancelled()) return false; - } - - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - currentTask.run(); - } - }); - - return currentTask.get() && !currentTask.isCancelled(); + return new FutureTask(() -> { + if (previousTask != null) { + previousTask.run(); + if (!previousTask.get() || previousTask.isCancelled()) return false; } + + ApplicationManager.getApplication().runWriteAction(() -> { + currentTask.run(); + }); + + return currentTask.get() && !currentTask.isCancelled(); }); } @@ -324,33 +318,27 @@ public abstract class AbstractLayoutCodeProcessor { } final Ref> writeActionRunnable = new Ref>(); - Runnable readAction = new Runnable() { - @Override - public void run() { - if (!checkFileWritable(file)) return; - try{ - FutureTask writeTask = preprocessFile(file, myProcessChangedTextOnly); - writeActionRunnable.set(writeTask); - } - catch(IncorrectOperationException e){ - LOG.error(e); - } + Runnable readAction = () -> { + if (!checkFileWritable(file)) return; + try{ + FutureTask writeTask = preprocessFile(file, myProcessChangedTextOnly); + writeActionRunnable.set(writeTask); + } + catch(IncorrectOperationException e){ + LOG.error(e); } }; - Runnable writeAction = new Runnable() { - @Override - public void run() { - if (writeActionRunnable.isNull()) return; - FutureTask task = writeActionRunnable.get(); - task.run(); - try { - task.get(); - } - catch (CancellationException ignored) { - } - catch (Exception e) { - LOG.error(e); - } + Runnable writeAction = () -> { + if (writeActionRunnable.isNull()) return; + FutureTask task = writeActionRunnable.get(); + task.run(); + try { + task.get(); + } + catch (CancellationException ignored) { + } + catch (Exception e) { + LOG.error(e); } }; runLayoutCodeProcess(readAction, writeAction, false ); @@ -401,53 +389,37 @@ public abstract class AbstractLayoutCodeProcessor { final ModalityState modalityState = ModalityState.current(); - final Runnable process = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(readAction); + final Runnable process = () -> ApplicationManager.getApplication().runReadAction(readAction); + + Runnable runnable = () -> { + try { + ProgressManager.getInstance().runProcess(process, progressWindow); + } + catch(ProcessCanceledException e) { + return; + } + catch(IndexNotReadyException e) { + return; } - }; - Runnable runnable = new Runnable() { - @Override - public void run() { + final Runnable writeRunnable = () -> CommandProcessor.getInstance().executeCommand(myProject, () -> { + if (globalAction) CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); try { - ProgressManager.getInstance().runProcess(process, progressWindow); - } - catch(ProcessCanceledException e) { - return; - } - catch(IndexNotReadyException e) { - return; - } + writeAction.run(); - final Runnable writeRunnable = new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - if (globalAction) CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); - try { - writeAction.run(); - - if (myPostRunnable != null) { - ApplicationManager.getApplication().invokeLater(myPostRunnable); - } - } - catch (IndexNotReadyException ignored) { - } - } - }, myCommandName, null); + if (myPostRunnable != null) { + ApplicationManager.getApplication().invokeLater(myPostRunnable); } - }; + } + catch (IndexNotReadyException ignored) { + } + }, myCommandName, null); - if (ApplicationManager.getApplication().isUnitTestMode()) { - writeRunnable.run(); - } - else { - ApplicationManager.getApplication().invokeLater(writeRunnable, modalityState, myProject.getDisposed()); - } + if (ApplicationManager.getApplication().isUnitTestMode()) { + writeRunnable.run(); + } + else { + ApplicationManager.getApplication().invokeLater(writeRunnable, modalityState, myProject.getDisposed()); } }; @@ -534,12 +506,7 @@ public abstract class AbstractLayoutCodeProcessor { if (shouldProcessFile(file)) { updateIndicatorText(ApplicationBundle.message("bulk.reformat.process.progress.text"), getPresentablePath(file)); - DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - performFileProcessing(file); - } - }); + DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> performFileProcessing(file)); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/FileInEditorProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/FileInEditorProcessor.java index 781a179a8d50..a7891541e2b0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/FileInEditorProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/FileInEditorProcessor.java @@ -96,24 +96,21 @@ class FileInEditorProcessor { if (shouldNotify()) { myProcessor.setCollectInfo(true); - myProcessor.setPostRunnable(new Runnable() { - @Override - public void run() { - String message = prepareMessage(); - if (!myEditor.isDisposed() && myEditor.getComponent().isShowing()) { - HyperlinkListener hyperlinkListener = new HyperlinkAdapter() { - @Override - protected void hyperlinkActivated(HyperlinkEvent e) { - AnAction action = ActionManager.getInstance().getAction("ShowReformatFileDialog"); - DataManager manager = DataManager.getInstance(); - if (manager != null) { - DataContext context = manager.getDataContext(myEditor.getContentComponent()); - action.actionPerformed(AnActionEvent.createFromAnAction(action, null, "", context)); - } + myProcessor.setPostRunnable(() -> { + String message = prepareMessage(); + if (!myEditor.isDisposed() && myEditor.getComponent().isShowing()) { + HyperlinkListener hyperlinkListener = new HyperlinkAdapter() { + @Override + protected void hyperlinkActivated(HyperlinkEvent e) { + AnAction action = ActionManager.getInstance().getAction("ShowReformatFileDialog"); + DataManager manager = DataManager.getInstance(); + if (manager != null) { + DataContext context = manager.getDataContext(myEditor.getContentComponent()); + action.actionPerformed(AnActionEvent.createFromAnAction(action, null, "", context)); } - }; - showHint(myEditor, message, hyperlinkListener); - } + } + }; + showHint(myEditor, message, hyperlinkListener); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/MultiCaretCodeInsightAction.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/MultiCaretCodeInsightAction.java index b91087dae459..b657138438fe 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/MultiCaretCodeInsightAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/MultiCaretCodeInsightAction.java @@ -60,23 +60,15 @@ public abstract class MultiCaretCodeInsightAction extends AnAction { } public void actionPerformedImpl(final Project project, final Editor hostEditor) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - MultiCaretCodeInsightActionHandler handler = getHandler(); - try { - iterateOverCarets(project, hostEditor, handler); - } - finally { - handler.postInvoke(); - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + MultiCaretCodeInsightActionHandler handler = getHandler(); + try { + iterateOverCarets(project, hostEditor, handler); } - }, getCommandName(), DocCommandGroupId.noneGroupId(hostEditor.getDocument())); + finally { + handler.postInvoke(); + } + }), getCommandName(), DocCommandGroupId.noneGroupId(hostEditor.getDocument())); hostEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsAction.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsAction.java index 40142e056b93..45cc643a3e34 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsAction.java @@ -138,16 +138,13 @@ public class OptimizeImportsAction extends AnAction { final OptimizeImportsProcessor optimizer = new OptimizeImportsProcessor(project, file); if (editor != null && EditorSettingsExternalizable.getInstance().getOptions().SHOW_NOTIFICATION_AFTER_OPTIMIZE_IMPORTS_ACTION) { optimizer.setCollectInfo(true); - optimizer.setPostRunnable(new Runnable() { - @Override - public void run() { - LayoutCodeInfoCollector collector = optimizer.getInfoCollector(); - if (collector != null) { - String info = collector.getOptimizeImportsNotification(); - if (!editor.isDisposed() && editor.getComponent().isShowing()) { - String message = info != null ? info : NO_IMPORTS_OPTIMIZED; - FileInEditorProcessor.showHint(editor, StringUtil.capitalize(message), null); - } + optimizer.setPostRunnable(() -> { + LayoutCodeInfoCollector collector = optimizer.getInfoCollector(); + if (collector != null) { + String info = collector.getOptimizeImportsNotification(); + if (!editor.isDisposed() && editor.getComponent().isShowing()) { + String message = info != null ? info : NO_IMPORTS_OPTIMIZED; + FileInEditorProcessor.showHint(editor, StringUtil.capitalize(message), null); } } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsProcessor.java index 1428605281ff..447cb3931877 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/OptimizeImportsProcessor.java @@ -87,20 +87,17 @@ public class OptimizeImportsProcessor extends AbstractLayoutCodeProcessor { } } - Runnable runnable = !runnables.isEmpty() ? new Runnable() { - @Override - public void run() { - CodeStyleManagerImpl.setSequentialProcessingAllowed(false); - try { - for (Runnable runnable : runnables) { - runnable.run(); - retrieveAndStoreNotificationInfo(runnable); - } - putNotificationInfoIntoCollector(); - } - finally { - CodeStyleManagerImpl.setSequentialProcessingAllowed(true); + Runnable runnable = !runnables.isEmpty() ? (Runnable)() -> { + CodeStyleManagerImpl.setSequentialProcessingAllowed(false); + try { + for (Runnable runnable1 : runnables) { + runnable1.run(); + retrieveAndStoreNotificationInfo(runnable1); } + putNotificationInfoIntoCollector(); + } + finally { + CodeStyleManagerImpl.setSequentialProcessingAllowed(true); } } : EmptyRunnable.getInstance(); return new FutureTask(runnable, true); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/RearrangeCodeProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/RearrangeCodeProcessor.java index a81322aeed94..765dbc64bd6a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/RearrangeCodeProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/RearrangeCodeProcessor.java @@ -72,31 +72,28 @@ public class RearrangeCodeProcessor extends AbstractLayoutCodeProcessor { @NotNull @Override protected FutureTask prepareTask(@NotNull final PsiFile file, final boolean processChangedTextOnly) { - return new FutureTask(new Callable() { - @Override - public Boolean call() throws Exception { - try { - Collection ranges = getRangesToFormat(file, processChangedTextOnly); - Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); + return new FutureTask(() -> { + try { + Collection ranges = getRangesToFormat(file, processChangedTextOnly); + Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); - if (document != null && Rearranger.EXTENSION.forLanguage(file.getLanguage()) != null) { - PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(document); - PsiDocumentManager.getInstance(myProject).commitDocument(document); - Runnable command = prepareRearrangeCommand(file, ranges); - try { - CommandProcessor.getInstance().executeCommand(myProject, command, COMMAND_NAME, null); - } - finally { - PsiDocumentManager.getInstance(myProject).commitDocument(document); - } + if (document != null && Rearranger.EXTENSION.forLanguage(file.getLanguage()) != null) { + PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(document); + PsiDocumentManager.getInstance(myProject).commitDocument(document); + Runnable command = prepareRearrangeCommand(file, ranges); + try { + CommandProcessor.getInstance().executeCommand(myProject, command, COMMAND_NAME, null); } + finally { + PsiDocumentManager.getInstance(myProject).commitDocument(document); + } + } - return true; - } - catch (FilesTooBigForDiffException e) { - handleFileTooBigException(LOG, e, file); - return false; - } + return true; + } + catch (FilesTooBigForDiffException e) { + handleFileTooBigException(LOG, e, file); + return false; } }); } @@ -104,14 +101,11 @@ public class RearrangeCodeProcessor extends AbstractLayoutCodeProcessor { @NotNull private Runnable prepareRearrangeCommand(@NotNull final PsiFile file, @NotNull final Collection ranges) { final ArrangementEngine engine = ServiceManager.getService(myProject, ArrangementEngine.class); - return new Runnable() { - @Override - public void run() { - engine.arrange(file, ranges); - if (getInfoCollector() != null) { - String info = engine.getUserNotificationInfo(); - getInfoCollector().setRearrangeCodeNotification(info); - } + return () -> { + engine.arrange(file, ranges); + if (getInfoCollector() != null) { + String info = engine.getUserNotificationInfo(); + getInfoCollector().setRearrangeCodeNotification(info); } }; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeProcessor.java index 8595c5c87d7d..758f129ee004 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeProcessor.java @@ -110,48 +110,45 @@ public class ReformatCodeProcessor extends AbstractLayoutCodeProcessor { protected FutureTask prepareTask(@NotNull final PsiFile file, final boolean processChangedTextOnly) throws IncorrectOperationException { - return new FutureTask(new Callable() { - @Override - public Boolean call() throws Exception { - FormattingProgressTask.FORMATTING_CANCELLED_FLAG.set(false); - try { - Collection ranges = getRangesToFormat(processChangedTextOnly, file); + return new FutureTask(() -> { + FormattingProgressTask.FORMATTING_CANCELLED_FLAG.set(false); + try { + Collection ranges = getRangesToFormat(processChangedTextOnly, file); - CharSequence before = null; - Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); - if (getInfoCollector() != null) { - LOG.assertTrue(document != null); - before = document.getImmutableCharSequence(); - } - - CaretVisualPositionKeeper caretPositionKeeper = new CaretVisualPositionKeeper(document); - - if (processChangedTextOnly) { - CodeStyleManager.getInstance(myProject).reformatTextWithContext(file, ranges); - } - else { - CodeStyleManager.getInstance(myProject).reformatText(file, ranges); - } - - caretPositionKeeper.restoreOriginalLocation(); - - if (before != null) { - prepareUserNotificationMessage(document, before); - } - - return !FormattingProgressTask.FORMATTING_CANCELLED_FLAG.get(); + CharSequence before = null; + Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); + if (getInfoCollector() != null) { + LOG.assertTrue(document != null); + before = document.getImmutableCharSequence(); } - catch (FilesTooBigForDiffException e) { - handleFileTooBigException(LOG, e, file); - return false; - } - catch (IncorrectOperationException e) { - LOG.error(e); - return false; + + CaretVisualPositionKeeper caretPositionKeeper = new CaretVisualPositionKeeper(document); + + if (processChangedTextOnly) { + CodeStyleManager.getInstance(myProject).reformatTextWithContext(file, ranges); } - finally { - myRanges.clear(); + else { + CodeStyleManager.getInstance(myProject).reformatText(file, ranges); } + + caretPositionKeeper.restoreOriginalLocation(); + + if (before != null) { + prepareUserNotificationMessage(document, before); + } + + return !FormattingProgressTask.FORMATTING_CANCELLED_FLAG.get(); + } + catch (FilesTooBigForDiffException e) { + handleFileTooBigException(LOG, e, file); + return false; + } + catch (IncorrectOperationException e) { + LOG.error(e); + return false; + } + finally { + myRanges.clear(); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index 439cf158aabb..34a67a149b82 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -158,26 +158,20 @@ public class CodeCompletionHandlerBase { final CompletionInitializationContext[] initializationContext = {null}; - Runnable initCmd = new Runnable() { - @Override - public void run() { - Runnable runnable = new Runnable() { - @Override - public void run() { - EditorUtil.fillVirtualSpaceUntilCaret(editor); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - CompletionAssertions.checkEditorValid(editor); + Runnable initCmd = () -> { + Runnable runnable = () -> { + EditorUtil.fillVirtualSpaceUntilCaret(editor); + PsiDocumentManager.getInstance(project).commitAllDocuments(); + CompletionAssertions.checkEditorValid(editor); - final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project); - assert psiFile != null : "no PSI file: " + FileDocumentManager.getInstance().getFile(editor.getDocument()); - psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE); - CompletionAssertions.assertCommitSuccessful(editor, psiFile); + final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project); + assert psiFile != null : "no PSI file: " + FileDocumentManager.getInstance().getFile(editor.getDocument()); + psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE); + CompletionAssertions.assertCommitSuccessful(editor, psiFile); - initializationContext[0] = runContributorsBeforeCompletion(editor, psiFile, invocationCount, caret); - } - }; - ApplicationManager.getApplication().runWriteAction(runnable); - } + initializationContext[0] = runContributorsBeforeCompletion(editor, psiFile, invocationCount, caret); + }; + ApplicationManager.getApplication().runWriteAction(runnable); }; if (autopopup) { CommandProcessor.getInstance().runUndoTransparentAction(initCmd); @@ -427,12 +421,9 @@ public class CodeCompletionHandlerBase { final Runnable restorePrefix = rememberDocumentState(indicator.getEditor()); final LookupElement item = ((AutoCompletionDecision.InsertItem)decision).getElement(); - CommandProcessor.getInstance().executeCommand(indicator.getProject(), new Runnable() { - @Override - public void run() { - indicator.setMergeCommand(); - indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, item); - } + CommandProcessor.getInstance().executeCommand(indicator.getProject(), () -> { + indicator.setMergeCommand(); + indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, item); }, "Autocompletion", null); // the insert handler may have started a live template with completion @@ -610,12 +601,9 @@ public class CodeCompletionHandlerBase { }); context = contexts.get(contexts.size() - 1); if (context.shouldAddCompletionChar() && context.getCompletionChar() != Lookup.COMPLETE_STATEMENT_SELECT_CHAR) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - DataContext dataContext = DataManager.getInstance().getDataContext(editor.getContentComponent()); - EditorActionManager.getInstance().getTypedAction().getHandler().execute(editor, completionChar, dataContext); - } + ApplicationManager.getApplication().runWriteAction(() -> { + DataContext dataContext = DataManager.getInstance().getDataContext(editor.getContentComponent()); + EditorActionManager.getInstance().getTypedAction().getHandler().execute(editor, completionChar, dataContext); }); } for (CompletionAssertions.WatchingInsertionContext insertionContext : contexts) { @@ -668,29 +656,26 @@ public class CodeCompletionHandlerBase { final CompletionAssertions.WatchingInsertionContext context = new CompletionAssertions.WatchingInsertionContext(offsetMap, psiFile, completionChar, items, editor); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (caretOffset < idEndOffset && completionChar == Lookup.REPLACE_SELECT_CHAR) { - editor.getDocument().deleteString(caretOffset, idEndOffset); - } - - assert context.getStartOffset() >= 0 : "stale startOffset: was " + initialStartOffset + "; selEnd=" + caretOffset + "; idEnd=" + idEndOffset + "; file=" + context.getFile(); - assert context.getTailOffset() >= 0 : "stale tail: was " + initialStartOffset + "; selEnd=" + caretOffset + "; idEnd=" + idEndOffset + "; file=" + context.getFile(); - - Project project = indicator.getProject(); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - item.handleInsert(context); - PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(); - - if (context.shouldAddCompletionChar()) { - addCompletionChar(project, context, item, editor, indicator, completionChar); - } - if (!editor.getCaretModel().supportsMultipleCarets()) { // done later, outside of this method - context.stopWatching(); - } - EditorModificationUtil.scrollToCaret(editor); + ApplicationManager.getApplication().runWriteAction(() -> { + if (caretOffset < idEndOffset && completionChar == Lookup.REPLACE_SELECT_CHAR) { + editor.getDocument().deleteString(caretOffset, idEndOffset); } + + assert context.getStartOffset() >= 0 : "stale startOffset: was " + initialStartOffset + "; selEnd=" + caretOffset + "; idEnd=" + idEndOffset + "; file=" + context.getFile(); + assert context.getTailOffset() >= 0 : "stale tail: was " + initialStartOffset + "; selEnd=" + caretOffset + "; idEnd=" + idEndOffset + "; file=" + context.getFile(); + + Project project = indicator.getProject(); + PsiDocumentManager.getInstance(project).commitAllDocuments(); + item.handleInsert(context); + PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(); + + if (context.shouldAddCompletionChar()) { + addCompletionChar(project, context, item, editor, indicator, completionChar); + } + if (!editor.getCaretModel().supportsMultipleCarets()) { // done later, outside of this method + context.stopWatching(); + } + EditorModificationUtil.scrollToCaret(editor); }); update.addSparedChars(indicator, item, context, completionChar); return context; @@ -784,18 +769,15 @@ public class CodeCompletionHandlerBase { final int vOffset = editor.getScrollingModel().getVerticalScrollOffset(); final int hOffset = editor.getScrollingModel().getHorizontalScrollOffset(); - return new Runnable() { - @Override - public void run() { - DocumentEx document = (DocumentEx) editor.getDocument(); + return () -> { + DocumentEx document = (DocumentEx) editor.getDocument(); - document.replaceString(0, document.getTextLength(), documentText); - editor.getCaretModel().moveToOffset(caret); - editor.getSelectionModel().setSelection(selStart, selEnd); + document.replaceString(0, document.getTextLength(), documentText); + editor.getCaretModel().moveToOffset(caret); + editor.getSelectionModel().setSelection(selStart, selEnd); - editor.getScrollingModel().scrollHorizontally(hOffset); - editor.getScrollingModel().scrollVertically(vOffset); - } + editor.getScrollingModel().scrollHorizontally(hOffset); + editor.getScrollingModel().scrollVertically(vOffset); }; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java index 90ac7feff7ec..16a3739b1be3 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java @@ -54,13 +54,10 @@ public class CompletionLookupArranger extends LookupArranger { private static final Alarm ourStatsAlarm = new Alarm(ApplicationManager.getApplication()); private static final Key GLOBAL_PRESENTATION_INVARIANT = Key.create("PRESENTATION_INVARIANT"); private final Key PRESENTATION_INVARIANT = Key.create("PRESENTATION_INVARIANT"); - private final Comparator BY_PRESENTATION_COMPARATOR = new Comparator() { - @Override - public int compare(LookupElement o1, LookupElement o2) { - String invariant = PRESENTATION_INVARIANT.get(o1); - assert invariant != null; - return StringUtil.naturalCompare(invariant, PRESENTATION_INVARIANT.get(o2)); - } + private final Comparator BY_PRESENTATION_COMPARATOR = (o1, o2) -> { + String invariant = PRESENTATION_INVARIANT.get(o1); + assert invariant != null; + return StringUtil.naturalCompare(invariant, PRESENTATION_INVARIANT.get(o2)); }; static final int MAX_PREFERRED_COUNT = 5; public static final Key WEIGHING_CONTEXT = Key.create("WEIGHING_CONTEXT"); @@ -502,12 +499,9 @@ public class CompletionLookupArranger extends LookupArranger { } }; - ourStatsAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (ourPendingUpdate == update) { - applyLastCompletionStatisticsUpdate(); - } + ourStatsAlarm.addRequest(() -> { + if (ourPendingUpdate == update) { + applyLastCompletionStatisticsUpdate(); } }, 20 * 1000); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionPhase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionPhase.java index bcaeeb0976b2..793e430c0b70 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionPhase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionPhase.java @@ -206,12 +206,7 @@ public abstract class CompletionPhase implements Disposable { @Override public int newCompletionStarted(int time, boolean repeated) { indicator.closeAndFinish(false); - indicator.restorePrefix(new Runnable() { - @Override - public void run() { - indicator.getLookup().restorePrefix(); - } - }); + indicator.restorePrefix(() -> indicator.getLookup().restorePrefix()); return indicator.nextInvocationCount(time, repeated); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionThreading.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionThreading.java index c8d5ae8ec265..941a91e5f344 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionThreading.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionThreading.java @@ -79,28 +79,17 @@ class AsyncCompletion implements CompletionThreading { public Future startThread(final ProgressIndicator progressIndicator, final Runnable runnable) { final Semaphore startSemaphore = new Semaphore(); startSemaphore.down(); - Future future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - try { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - startSemaphore.up(); - ProgressManager.checkCanceled(); - runnable.run(); - } - }); - } - catch (ProcessCanceledException ignored) { - } - } - }, progressIndicator); + Future future = ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> { + try { + ApplicationManager.getApplication().runReadAction(() -> { + startSemaphore.up(); + ProgressManager.checkCanceled(); + runnable.run(); + }); } - }); + catch (ProcessCanceledException ignored) { + } + }, progressIndicator)); startSemaphore.waitFor(); return future; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/LegacyCompletionContributor.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/LegacyCompletionContributor.java index 3a71bd4129c4..fed8941962f1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/LegacyCompletionContributor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/LegacyCompletionContributor.java @@ -66,20 +66,17 @@ public class LegacyCompletionContributor extends CompletionContributor { } final Ref hasVariants = Ref.create(false); - processReferences(parameters, result, new PairConsumer() { - @Override - public void consume(final PsiReference reference, final CompletionResultSet resultSet) { - final Set lookupSet = new LinkedHashSet(); - completionData.completeReference(reference, lookupSet, parameters.getPosition(), parameters.getOriginalFile()); - for (final LookupElement item : lookupSet) { - if (resultSet.getPrefixMatcher().prefixMatches(item)) { - if (!item.isValid()) { - LOG.error(completionData + " has returned an invalid lookup element " + item + " of " + item.getClass() + - " in " + parameters.getOriginalFile() + " of " + parameters.getOriginalFile().getClass()); - } - hasVariants.set(true); - resultSet.addElement(item); + processReferences(parameters, result, (reference, resultSet) -> { + final Set lookupSet = new LinkedHashSet(); + completionData.completeReference(reference, lookupSet, parameters.getPosition(), parameters.getOriginalFile()); + for (final LookupElement item : lookupSet) { + if (resultSet.getPrefixMatcher().prefixMatches(item)) { + if (!item.isValid()) { + LOG.error(completionData + " has returned an invalid lookup element " + item + " of " + item.getClass() + + " in " + parameters.getOriginalFile() + " of " + parameters.getOriginalFile().getClass()); } + hasVariants.set(true); + resultSet.addElement(item); } } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/StatisticsWeigher.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/StatisticsWeigher.java index f6ee7eeb9cb9..d648ab17c143 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/StatisticsWeigher.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/StatisticsWeigher.java @@ -159,11 +159,8 @@ public class StatisticsWeigher extends CompletionWeigher { @Override public List> getSortingWeights(@NotNull Iterable items, @NotNull final ProcessingContext context) { checkPrefixChanged(context); - return ContainerUtil.map(items, new Function>() { - @Override - public Pair fun(LookupElement lookupElement) { - return new Pair(lookupElement, getWeight(lookupElement, context.get(CompletionLookupArranger.WEIGHING_CONTEXT))); - } + return ContainerUtil.map(items, lookupElement -> { + return new Pair(lookupElement, getWeight(lookupElement, context.get(CompletionLookupArranger.WEIGHING_CONTEXT))); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java index 78fef5338633..26a0879dcf65 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java @@ -436,11 +436,8 @@ public class HippieWordCompletionHandler implements CodeInsightActionHandler { @NotNull private static List getCaretOffsets(Editor editor) { - return ContainerUtil.map(editor.getCaretModel().getAllCarets(), new Function() { - @Override - public Integer fun(Caret caret) { - return caret.getOffset(); - } + return ContainerUtil.map(editor.getCaretModel().getAllCarets(), caret -> { + return caret.getOffset(); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/LiftShorterItemsClassifier.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/LiftShorterItemsClassifier.java index ef1253b83b51..dd1517efcadf 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/LiftShorterItemsClassifier.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/LiftShorterItemsClassifier.java @@ -119,11 +119,8 @@ public class LiftShorterItemsClassifier extends Classifier { public List> getSortingWeights(@NotNull Iterable items, @NotNull ProcessingContext context) { final THashSet lifted = newIdentityTroveSet(); Iterable iterable = liftShorterElements(ContainerUtil.newArrayList(items), lifted, context); - return ContainerUtil.map(iterable, new Function>() { - @Override - public Pair fun(LookupElement element) { - return new Pair(element, lifted.contains(element)); - } + return ContainerUtil.map(iterable, element -> { + return new Pair(element, lifted.contains(element)); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java index c535e46761f9..a3706562a280 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java @@ -82,13 +82,10 @@ public class DaemonTooltipRendererProvider implements ErrorStripTooltipRendererP } if (!infos.isEmpty()) { // show errors first - ContainerUtil.quickSort(infos, new Comparator() { - @Override - public int compare(final HighlightInfo o1, final HighlightInfo o2) { - int i = SeverityRegistrar.getSeverityRegistrar(myProject).compare(o2.getSeverity(), o1.getSeverity()); - if (i != 0) return i; - return o1.getToolTip().compareTo(o2.getToolTip()); - } + ContainerUtil.quickSort(infos, (o1, o2) -> { + int i = SeverityRegistrar.getSeverityRegistrar(myProject).compare(o2.getSeverity(), o1.getSeverity()); + if (i != 0) return i; + return o1.getToolTip().compareTo(o2.getToolTip()); }); final HighlightInfoComposite composite = new HighlightInfoComposite(infos); if (bigRenderer == null) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightInfoProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightInfoProcessor.java index 10d387268e71..706582e1d4a1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightInfoProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightInfoProcessor.java @@ -55,25 +55,22 @@ public class DefaultHighlightInfoProcessor extends HighlightInfoProcessor { final TextRange priorityIntersection = priorityRange.intersection(restrictRange); final Editor editor = session.getEditor(); - TransactionGuard.submitTransaction(project, new Runnable() { - @Override - public void run() { - if (modificationStamp != document.getModificationStamp()) return; - if (priorityIntersection != null) { - MarkupModel markupModel = DocumentMarkupModel.forDocument(document, project, true); + TransactionGuard.submitTransaction(project, () -> { + if (modificationStamp != document.getModificationStamp()) return; + if (priorityIntersection != null) { + MarkupModel markupModel = DocumentMarkupModel.forDocument(document, project, true); - EditorColorsScheme scheme = session.getColorsScheme(); - UpdateHighlightersUtil.setHighlightersInRange(project, document, priorityIntersection, scheme, infos, - (MarkupModelEx)markupModel, groupId); + EditorColorsScheme scheme = session.getColorsScheme(); + UpdateHighlightersUtil.setHighlightersInRange(project, document, priorityIntersection, scheme, infos, + (MarkupModelEx)markupModel, groupId); + } + if (editor != null && !editor.isDisposed()) { + // usability: show auto import popup as soon as possible + if (!DumbService.isDumb(project)) { + new ShowAutoImportPass(project, psiFile, editor).addImports(); } - if (editor != null && !editor.isDisposed()) { - // usability: show auto import popup as soon as possible - if (!DumbService.isDumb(project)) { - new ShowAutoImportPass(project, psiFile, editor).addImports(); - } - DaemonListeners.repaintErrorStripeRenderer(editor, project); - } + DaemonListeners.repaintErrorStripeRenderer(editor, project); } }); } @@ -88,21 +85,18 @@ public class DefaultHighlightInfoProcessor extends HighlightInfoProcessor { final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (document == null) return; final long modificationStamp = document.getModificationStamp(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (project.isDisposed() || modificationStamp != document.getModificationStamp()) return; + UIUtil.invokeLaterIfNeeded(() -> { + if (project.isDisposed() || modificationStamp != document.getModificationStamp()) return; - EditorColorsScheme scheme = session.getColorsScheme(); + EditorColorsScheme scheme = session.getColorsScheme(); - UpdateHighlightersUtil.setHighlightersOutsideRange(project, document, psiFile, infos, scheme, - restrictedRange.getStartOffset(), restrictedRange.getEndOffset(), - ProperTextRange.create(priorityRange), - groupId); - Editor editor = session.getEditor(); - if (editor != null) { - DaemonListeners.repaintErrorStripeRenderer(editor, project); - } + UpdateHighlightersUtil.setHighlightersOutsideRange(project, document, psiFile, infos, scheme, + restrictedRange.getStartOffset(), restrictedRange.getEndOffset(), + ProperTextRange.create(priorityRange), + groupId); + Editor editor = session.getEditor(); + if (editor != null) { + DaemonListeners.repaintErrorStripeRenderer(editor, project); } }); @@ -124,23 +118,20 @@ public class DefaultHighlightInfoProcessor extends HighlightInfoProcessor { final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (document == null) return; DaemonCodeAnalyzerEx - .processHighlights(document, project, null, range.getStartOffset(), range.getEndOffset(), new Processor() { - @Override - public boolean process(final HighlightInfo existing) { - if (existing.isBijective() && - existing.getGroup() == Pass.UPDATE_ALL && - range.equalsToRange(existing.getActualStartOffset(), existing.getActualEndOffset())) { - if (infos != null) { - for (HighlightInfo created : infos) { - if (existing.equalsByActualOffset(created)) return true; - } + .processHighlights(document, project, null, range.getStartOffset(), range.getEndOffset(), existing -> { + if (existing.isBijective() && + existing.getGroup() == Pass.UPDATE_ALL && + range.equalsToRange(existing.getActualStartOffset(), existing.getActualEndOffset())) { + if (infos != null) { + for (HighlightInfo created : infos) { + if (existing.equalsByActualOffset(created)) return true; } - // seems that highlight info "existing" is going to disappear - // remove it earlier - ((HighlightingSessionImpl)highlightingSession).queueDisposeHighlighter(existing.highlighter); } - return true; + // seems that highlight info "existing" is going to disappear + // remove it earlier + ((HighlightingSessionImpl)highlightingSession).queueDisposeHighlighter(existing.highlighter); } + return true; }); } @@ -166,20 +157,17 @@ public class DefaultHighlightInfoProcessor extends HighlightInfoProcessor { if (ApplicationManager.getApplication().isCommandLine()) return; if (repaintIconAlarm.isEmpty() || progress >= 1) { - repaintIconAlarm.addRequest(new Runnable() { - @Override - public void run() { - Project myProject = file.getProject(); - if (myProject.isDisposed()) return; - Editor myeditor = editor; - if (myeditor == null) { - myeditor = PsiUtilBase.findEditor(file); - } - if (myeditor == null || myeditor.isDisposed()) return; - EditorMarkupModelImpl markup = (EditorMarkupModelImpl)myeditor.getMarkupModel(); - markup.repaintTrafficLightIcon(); - DaemonListeners.repaintErrorStripeRenderer(myeditor, myProject); + repaintIconAlarm.addRequest(() -> { + Project myProject = file.getProject(); + if (myProject.isDisposed()) return; + Editor myeditor = editor; + if (myeditor == null) { + myeditor = PsiUtilBase.findEditor(file); } + if (myeditor == null || myeditor.isDisposed()) return; + EditorMarkupModelImpl markup = (EditorMarkupModelImpl)myeditor.getMarkupModel(); + markup.repaintTrafficLightIcon(); + DaemonListeners.repaintErrorStripeRenderer(myeditor, myProject); }, 50, null); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/EditorTracker.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/EditorTracker.java index 951601a88ac2..d579b5ce1d98 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/EditorTracker.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/EditorTracker.java @@ -275,12 +275,9 @@ public class EditorTracker extends AbstractProjectComponent { }; contentComponent.addFocusListener(focusListener); - myExecuteOnEditorRelease.put(event.getEditor(), new Runnable() { - @Override - public void run() { - component.removeHierarchyListener(hierarchyListener); - contentComponent.removeFocusListener(focusListener); - } + myExecuteOnEditorRelease.put(event.getEditor(), () -> { + component.removeHierarchyListener(hierarchyListener); + contentComponent.removeFocusListener(focusListener); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java index c2e9d8fea749..041831ed8ffc 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java @@ -159,15 +159,12 @@ public class ExternalToolPass extends ProgressableTextEditorHighlightingPass { } doAnnotate(); - ApplicationManagerEx.getApplicationEx().tryRunReadAction(new Runnable() { - @Override - public void run() { - if (documentChanged(modificationStampBefore) || myProject.isDisposed()) { - return; - } - applyRelevant(); - doFinish(getHighlights(), modificationStampBefore); + ApplicationManagerEx.getApplicationEx().tryRunReadAction(() -> { + if (documentChanged(modificationStampBefore) || myProject.isDisposed()) { + return; } + applyRelevant(); + doFinish(getHighlights(), modificationStampBefore); }); } }; @@ -198,16 +195,13 @@ public class ExternalToolPass extends ProgressableTextEditorHighlightingPass { } private void doFinish(@NotNull final List highlights, final long modificationStampBefore) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (documentChanged(modificationStampBefore) || myProject.isDisposed()) { - return; - } - UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, myRestrictRange.getStartOffset(), myRestrictRange.getEndOffset(), highlights, getColorsScheme(), getId()); - DaemonCodeAnalyzerEx daemonCodeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject); - daemonCodeAnalyzer.getFileStatusMap().markFileUpToDate(myDocument, getId()); + ApplicationManager.getApplication().invokeLater(() -> { + if (documentChanged(modificationStampBefore) || myProject.isDisposed()) { + return; } + UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, myRestrictRange.getStartOffset(), myRestrictRange.getEndOffset(), highlights, getColorsScheme(), getId()); + DaemonCodeAnalyzerEx daemonCodeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject); + daemonCodeAnalyzer.getFileStatusMap().markFileUpToDate(myDocument, getId()); }, ModalityState.stateForComponent(getEditor().getComponent())); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java index 8da21f68ccd3..59bfa2dd7d60 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java @@ -71,18 +71,15 @@ public class GotoNextErrorHandler implements CodeInsightActionHandler { final HighlightInfo[][] infoToGo = new HighlightInfo[2][2]; //HighlightInfo[luck-noluck][skip-noskip] final int caretOffsetIfNoLuck = myGoForward ? -1 : document.getTextLength(); - DaemonCodeAnalyzerEx.processHighlights(document, project, minSeverity, 0, document.getTextLength(), new Processor() { - @Override - public boolean process(HighlightInfo info) { - int startOffset = getNavigationPositionFor(info, document); - if (SeverityRegistrar.isGotoBySeverityEnabled(info.getSeverity())) { - infoToGo[0][0] = getBetterInfoThan(infoToGo[0][0], caretOffset, startOffset, info); - infoToGo[1][0] = getBetterInfoThan(infoToGo[1][0], caretOffsetIfNoLuck, startOffset, info); - } - infoToGo[0][1] = getBetterInfoThan(infoToGo[0][1], caretOffset, startOffset, info); - infoToGo[1][1] = getBetterInfoThan(infoToGo[1][1], caretOffsetIfNoLuck, startOffset, info); - return true; + DaemonCodeAnalyzerEx.processHighlights(document, project, minSeverity, 0, document.getTextLength(), info -> { + int startOffset = getNavigationPositionFor(info, document); + if (SeverityRegistrar.isGotoBySeverityEnabled(info.getSeverity())) { + infoToGo[0][0] = getBetterInfoThan(infoToGo[0][0], caretOffset, startOffset, info); + infoToGo[1][0] = getBetterInfoThan(infoToGo[1][0], caretOffsetIfNoLuck, startOffset, info); } + infoToGo[0][1] = getBetterInfoThan(infoToGo[0][1], caretOffset, startOffset, info); + infoToGo[1][1] = getBetterInfoThan(infoToGo[1][1], caretOffsetIfNoLuck, startOffset, info); + return true; }); if (infoToGo[0][0] == null) infoToGo[0][0] = infoToGo[1][0]; if (infoToGo[0][1] == null) infoToGo[0][1] = infoToGo[1][1]; @@ -132,14 +129,11 @@ public class GotoNextErrorHandler implements CodeInsightActionHandler { } scrollingModel.runActionOnScrollingFinished( - new Runnable(){ - @Override - public void run() { - int maxOffset = editor.getDocument().getTextLength() - 1; - if (maxOffset == -1) return; - scrollingModel.scrollTo(editor.offsetToLogicalPosition(Math.min(maxOffset, endOffset)), ScrollType.MAKE_VISIBLE); - scrollingModel.scrollTo(editor.offsetToLogicalPosition(Math.min(maxOffset, offset)), ScrollType.MAKE_VISIBLE); - } + () -> { + int maxOffset = editor.getDocument().getTextLength() - 1; + if (maxOffset == -1) return; + scrollingModel.scrollTo(editor.offsetToLogicalPosition(Math.min(maxOffset, endOffset)), ScrollType.MAKE_VISIBLE); + scrollingModel.scrollTo(editor.offsetToLogicalPosition(Math.min(maxOffset, offset)), ScrollType.MAKE_VISIBLE); } ); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GutterIntentionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GutterIntentionAction.java index cc82f801a381..d3dc1e897ff1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GutterIntentionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GutterIntentionAction.java @@ -103,11 +103,8 @@ class GutterIntentionAction extends AbstractIntentionAction implements Comparabl else { HighlightInfo.IntentionActionDescriptor first = list.get(0); List options = ContainerUtil.map(list.subList(1, list.size()), - new Function() { - @Override - public IntentionAction fun(HighlightInfo.IntentionActionDescriptor descriptor) { - return descriptor.getAction(); - } + descriptor -> { + return descriptor.getAction(); }); descriptors.add(new HighlightInfo.IntentionActionDescriptor(first.getAction(), options, null, first.getIcon())); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IndentsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IndentsPass.java index 4fc6e6933428..9ba968b7ce69 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IndentsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/IndentsPass.java @@ -61,15 +61,12 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware private final EditorEx myEditor; private final PsiFile myFile; - public static final Comparator RANGE_COMPARATOR = new Comparator() { - @Override - public int compare(TextRange o1, TextRange o2) { - if (o1.getStartOffset() == o2.getStartOffset()) { - return o1.getEndOffset() - o2.getEndOffset(); - } - - return o1.getStartOffset() - o2.getStartOffset(); + public static final Comparator RANGE_COMPARATOR = (o1, o2) -> { + if (o1.getStartOffset() == o2.getStartOffset()) { + return o1.getEndOffset() - o2.getEndOffset(); } + + return o1.getStartOffset() - o2.getStartOffset(); }; private static final CustomHighlighterRenderer RENDERER = new CustomHighlighterRenderer() { @@ -278,12 +275,9 @@ public class IndentsPass extends TextEditorHighlightingPass implements DumbAware final int startRangeIndex = curRange; assert myDocument != null; - DocumentUtil.executeInBulk(myDocument, myRanges.size() > 10000, new Runnable() { - @Override - public void run() { - for (int i = startRangeIndex; i < myRanges.size(); i++) { - newHighlighters.add(createHighlighter(mm, myRanges.get(i))); - } + DocumentUtil.executeInBulk(myDocument, myRanges.size() > 10000, () -> { + for (int i = startRangeIndex; i < myRanges.size(); i++) { + newHighlighters.add(createHighlighter(mm, myRanges.get(i))); } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java index 988fe04afe80..9567e595513f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/InjectedGeneralHighlightingPass.java @@ -183,14 +183,11 @@ public class InjectedGeneralHighlightingPass extends GeneralHighlightingPass imp } }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList(hosts), progress, true, - new Processor() { - @Override - public boolean process(PsiElement element) { - ApplicationManager.getApplication().assertReadAccessAllowed(); - progress.checkCanceled(); - InjectedLanguageUtil.enumerate(element, myFile, false, visitor); - return true; - } + element -> { + ApplicationManager.getApplication().assertReadAccessAllowed(); + progress.checkCanceled(); + InjectedLanguageUtil.enumerate(element, myFile, false, visitor); + return true; })) { throw new ProcessCanceledException(); } @@ -209,12 +206,7 @@ public class InjectedGeneralHighlightingPass extends GeneralHighlightingPass imp return JobLauncher.getInstance() .invokeConcurrentlyUnderProgress(new ArrayList(injectedFiles), progress, isFailFastOnAcquireReadAction(), - new Processor() { - @Override - public boolean process(final PsiFile injectedPsi) { - return addInjectedPsiHighlights(injectedPsi, injectedAttributes, outInfos, progress, injectedLanguageManager); - } - }); + injectedPsi -> addInjectedPsiHighlights(injectedPsi, injectedAttributes, outInfos, progress, injectedLanguageManager)); } private boolean addInjectedPsiHighlights(@NotNull PsiFile injectedPsi, @@ -366,13 +358,10 @@ public class InjectedGeneralHighlightingPass extends GeneralHighlightingPass imp try { final List elements = CollectHighlightsUtil.getElementsInRange(injectedPsi, 0, injectedPsi.getTextLength()); for (final HighlightVisitor visitor : filtered) { - visitor.analyze(injectedPsi, true, holder, new Runnable() { - @Override - public void run() { - for (PsiElement element : elements) { - progress.checkCanceled(); - visitor.visit(element); - } + visitor.analyze(injectedPsi, true, holder, () -> { + for (PsiElement element : elements) { + progress.checkCanceled(); + visitor.visit(element); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersPass.java index e0c53467e8c8..e2ca901ffb58 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersPass.java @@ -212,12 +212,9 @@ public class LineMarkersPass extends TextEditorHighlightingPass implements LineM injectedFiles.add(injectedPsi); } }; - InjectedLanguageManagerImpl.getInstanceImpl(file.getProject()).processInjectableElements(elements, new Processor() { - @Override - public boolean process(PsiElement element) { - InjectedLanguageUtil.enumerate(element, file, false, collectingVisitor); - return true; - } + InjectedLanguageManagerImpl.getInstanceImpl(file.getProject()).processInjectableElements(elements, element -> { + InjectedLanguageUtil.enumerate(element, file, false, collectingVisitor); + return true; }); for (PsiFile injectedPsi : injectedFiles) { final Project project = injectedPsi.getProject(); @@ -235,12 +232,7 @@ public class LineMarkersPass extends TextEditorHighlightingPass implements LineM Icon icon = gutterRenderer == null ? null : gutterRenderer.getIcon(); LineMarkerInfo converted = new LineMarkerInfo(injectedMarker.getElement(), hostRange, icon, injectedMarker.updatePass, - new Function() { - @Override - public String fun(PsiElement element) { - return injectedMarker.getLineMarkerTooltip(); - } - }, injectedMarker.getNavigationHandler(), GutterIconRenderer.Alignment.RIGHT); + element -> injectedMarker.getLineMarkerTooltip(), injectedMarker.getNavigationHandler(), GutterIconRenderer.Alignment.RIGHT); result.add(converted); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java index f189ae1f2bfd..c22a03e8cd06 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LineMarkersUtil.java @@ -87,18 +87,15 @@ class LineMarkersUtil { final boolean lineSeparatorPlacementChanged = !Comparing.equal(marker.getLineSeparatorPlacement(), info.separatorPlacement); if (rendererChanged || lineSeparatorColorChanged || lineSeparatorPlacementChanged) { - ((MarkupModelEx)markupModel).changeAttributesInBatch((RangeHighlighterEx)marker, new Consumer() { - @Override - public void consume(RangeHighlighterEx markerEx) { - if (rendererChanged) { - markerEx.setGutterIconRenderer(newRenderer); - } - if (lineSeparatorColorChanged) { - markerEx.setLineSeparatorColor(info.separatorColor); - } - if (lineSeparatorPlacementChanged) { - markerEx.setLineSeparatorPlacement(info.separatorPlacement); - } + ((MarkupModelEx)markupModel).changeAttributesInBatch((RangeHighlighterEx)marker, markerEx -> { + if (rendererChanged) { + markerEx.setGutterIconRenderer(newRenderer); + } + if (lineSeparatorColorChanged) { + markerEx.setLineSeparatorColor(info.separatorColor); + } + if (lineSeparatorPlacementChanged) { + markerEx.setLineSeparatorPlacement(info.separatorPlacement); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java index fed52fe7933f..7cafcfe4e937 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java @@ -253,13 +253,10 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass List>> entries = new ArrayList>>(toolToSpecifiedLanguageIds.entrySet()); Processor>> processor = - new Processor>>() { - @Override - public boolean process(final Map.Entry> pair) { - LocalInspectionToolWrapper toolWrapper = pair.getKey(); - Set dialectIdsSpecifiedForTool = pair.getValue(); - return runToolOnElements(toolWrapper, dialectIdsSpecifiedForTool, iManager, isOnTheFly, indicator, elements, session, init, elementDialectIds); - } + pair -> { + LocalInspectionToolWrapper toolWrapper = pair.getKey(); + Set dialectIdsSpecifiedForTool = pair.getValue(); + return runToolOnElements(toolWrapper, dialectIdsSpecifiedForTool, iManager, isOnTheFly, indicator, elements, session, init, elementDialectIds); }; boolean result = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(entries, indicator, myFailFastOnAcquireReadAction, processor); if (!result) throw new ProcessCanceledException(); @@ -312,22 +309,19 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass @NotNull List init, @NotNull final Set elementDialectIds) { Processor processor = - new Processor() { - @Override - public boolean process(InspectionContext context) { - indicator.checkCanceled(); - ApplicationManager.getApplication().assertReadAccessAllowed(); - InspectionEngine.acceptElements(elements, context.visitor, elementDialectIds, context.dialectIdsSpecifiedForTool); - advanceProgress(1); - context.tool.getTool().inspectionFinished(session, context.holder); + context -> { + indicator.checkCanceled(); + ApplicationManager.getApplication().assertReadAccessAllowed(); + InspectionEngine.acceptElements(elements, context.visitor, elementDialectIds, context.dialectIdsSpecifiedForTool); + advanceProgress(1); + context.tool.getTool().inspectionFinished(session, context.holder); - if (context.holder.hasResults()) { - List allProblems = context.holder.getResults(); - List restProblems = allProblems.subList(context.problemsSize, allProblems.size()); - appendDescriptors(getFile(), restProblems, context.tool); - } - return true; + if (context.holder.hasResults()) { + List allProblems = context.holder.getResults(); + List restProblems = allProblems.subList(context.problemsSize, allProblems.size()); + appendDescriptors(getFile(), restProblems, context.tool); } + return true; }; boolean result = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(init, indicator, myFailFastOnAcquireReadAction, processor); if (!result) { @@ -351,12 +345,9 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass }); } if (injected.isEmpty()) return; - Processor processor = new Processor() { - @Override - public boolean process(final PsiFile injectedPsi) { - doInspectInjectedPsi(injectedPsi, onTheFly, indicator, iManager, inVisibleRange, wrappers); - return true; - } + Processor processor = injectedPsi -> { + doInspectInjectedPsi(injectedPsi, onTheFly, indicator, iManager, inVisibleRange, wrappers); + return true; }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList(injected), indicator, myFailFastOnAcquireReadAction, processor)) { throw new ProcessCanceledException(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java index 7d5ae036105f..32be03a1f5f3 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java @@ -362,22 +362,19 @@ class PassExecutorService implements Disposable { private void submit(@NotNull ScheduledPass pass) { if (!pass.myUpdateProgress.isCanceled()) { - Job job = JobLauncher.getInstance().submitToJobThread(pass, new Consumer() { - @Override - public void consume(Future future) { - try { - if (!future.isCancelled()) { // for canceled task .get() generates CancellationException which is expensive - future.get(); - } - } - catch (CancellationException ignored) { - } - catch (InterruptedException ignored) { - } - catch (ExecutionException e) { - LOG.error(e.getCause()); + Job job = JobLauncher.getInstance().submitToJobThread(pass, future -> { + try { + if (!future.isCancelled()) { // for canceled task .get() generates CancellationException which is expensive + future.get(); } } + catch (CancellationException ignored) { + } + catch (InterruptedException ignored) { + } + catch (ExecutionException e) { + LOG.error(e.getCause()); + } }); mySubmittedPasses.put(pass, job); } @@ -429,44 +426,38 @@ class PassExecutorService implements Disposable { } } - ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { - @Override - public void run() { - boolean success = ApplicationManagerEx.getApplicationEx().tryRunReadAction(new Runnable() { - @Override - public void run() { - try { - if (DumbService.getInstance(myProject).isDumb() && !DumbService.isDumbAware(myPass)) { - return; - } - - if (!myUpdateProgress.isCanceled() && !myProject.isDisposed()) { - myPass.collectInformation(myUpdateProgress); - } - } - catch (ProcessCanceledException e) { - log(myUpdateProgress, myPass, "Canceled "); - - if (!myUpdateProgress.isCanceled()) { - myUpdateProgress.cancel(e); //in case when some smart asses throw PCE just for fun - } - } - catch (RuntimeException e) { - myUpdateProgress.cancel(e); - LOG.error(e); - throw e; - } - catch (Error e) { - myUpdateProgress.cancel(e); - LOG.error(e); - throw e; - } + ProgressManager.getInstance().executeProcessUnderProgress(() -> { + boolean success = ApplicationManagerEx.getApplicationEx().tryRunReadAction(() -> { + try { + if (DumbService.getInstance(myProject).isDumb() && !DumbService.isDumbAware(myPass)) { + return; } - }); - if (!success) { - myUpdateProgress.cancel(); + if (!myUpdateProgress.isCanceled() && !myProject.isDisposed()) { + myPass.collectInformation(myUpdateProgress); + } } + catch (ProcessCanceledException e) { + log(myUpdateProgress, myPass, "Canceled "); + + if (!myUpdateProgress.isCanceled()) { + myUpdateProgress.cancel(e); //in case when some smart asses throw PCE just for fun + } + } + catch (RuntimeException e) { + myUpdateProgress.cancel(e); + LOG.error(e); + throw e; + } + catch (Error e) { + myUpdateProgress.cancel(e); + LOG.error(e); + throw e; + } + }); + + if (!success) { + myUpdateProgress.cancel(); } }, myUpdateProgress); @@ -552,12 +543,7 @@ class PassExecutorService implements Disposable { } private static void sortById(@NotNull List result) { - ContainerUtil.quickSort(result, new Comparator() { - @Override - public int compare(@NotNull TextEditorHighlightingPass o1, @NotNull TextEditorHighlightingPass o2) { - return o1.getId() - o2.getId(); - } - }); + ContainerUtil.quickSort(result, (o1, o2) -> o1.getId() - o2.getId()); } private static int getThreadNum() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PsiElementListNavigator.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PsiElementListNavigator.java index ba0163e0ac91..c893d43d2d18 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PsiElementListNavigator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PsiElementListNavigator.java @@ -77,14 +77,11 @@ public class PsiElementListNavigator { final String findUsagesTitle, final ListCellRenderer listRenderer, @Nullable final ListBackgroundUpdaterTask listUpdaterTask) { - return navigateOrCreatePopup(targets, title, findUsagesTitle, listRenderer, listUpdaterTask, new Consumer() { - @Override - public void consume(Object[] selectedElements) { - for (Object element : selectedElements) { - PsiElement selected = (PsiElement)element; - LOG.assertTrue(selected.isValid()); - ((NavigatablePsiElement)selected).navigate(true); - } + return navigateOrCreatePopup(targets, title, findUsagesTitle, listRenderer, listUpdaterTask, selectedElements -> { + for (Object element : selectedElements) { + PsiElement selected = (PsiElement)element; + LOG.assertTrue(selected.isValid()); + ((NavigatablePsiElement)selected).navigate(true); } }); } @@ -139,14 +136,11 @@ public class PsiElementListNavigator { setTitle(title). setMovable(true). setResizable(true). - setItemChoosenCallback(new Runnable() { - @Override - public void run() { - int[] ids = list.getSelectedIndices(); - if (ids == null || ids.length == 0) return; - Object[] selectedElements = list.getSelectedValues(); - consumer.consume(selectedElements); - } + setItemChoosenCallback(() -> { + int[] ids = list.getSelectedIndices(); + if (ids == null || ids.length == 0) return; + Object[] selectedElements = list.getSelectedValues(); + consumer.consume(selectedElements); }). setCancelCallback(new Computable() { @Override @@ -157,14 +151,11 @@ public class PsiElementListNavigator { }); final Ref usageView = new Ref(); if (findUsagesTitle != null) { - popupChooserBuilder = popupChooserBuilder.setCouldPin(new Processor() { - @Override - public boolean process(JBPopup popup) { - final List items = model.getItems(); - usageView.set(FindUtil.showInUsageView(null, items.toArray(new PsiElement[items.size()]), findUsagesTitle, targets[0].getProject())); - popup.cancel(); - return false; - } + popupChooserBuilder = popupChooserBuilder.setCouldPin(popup -> { + final List items = model.getItems(); + usageView.set(FindUtil.showInUsageView(null, items.toArray(new PsiElement[items.size()]), findUsagesTitle, targets[0].getProject())); + popup.cancel(); + return false; }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowAutoImportPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowAutoImportPass.java index 5db40f31ab5f..0516c13b9ae9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowAutoImportPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowAutoImportPass.java @@ -104,17 +104,14 @@ public class ShowAutoImportPass extends TextEditorHighlightingPass { Document document = getDocument(); final List infos = new ArrayList(); - DaemonCodeAnalyzerEx.processHighlights(document, myProject, null, 0, document.getTextLength(), new Processor() { - @Override - public boolean process(HighlightInfo info) { - if (!info.hasHint() || info.getSeverity() != HighlightSeverity.ERROR) { - return true; - } - PsiReference reference = myFile.findReferenceAt(info.getActualStartOffset()); - if (reference != null && reference.getElement().getTextRange().containsOffset(caretOffset)) return true; - infos.add(info); + DaemonCodeAnalyzerEx.processHighlights(document, myProject, null, 0, document.getTextLength(), info -> { + if (!info.hasHint() || info.getSeverity() != HighlightSeverity.ERROR) { return true; } + PsiReference reference = myFile.findReferenceAt(info.getActualStartOffset()); + if (reference != null && reference.getElement().getTextRange().containsOffset(caretOffset)) return true; + infos.add(info); + return true; }); ReferenceImporter[] importers = Extensions.getExtensions(ReferenceImporter.EP_NAME); @@ -128,14 +125,11 @@ public class ShowAutoImportPass extends TextEditorHighlightingPass { @NotNull private static List getVisibleHighlights(final int startOffset, final int endOffset, Project project, final Editor editor) { final List highlights = new ArrayList(); - DaemonCodeAnalyzerEx.processHighlights(editor.getDocument(), project, null, startOffset, endOffset, new Processor() { - @Override - public boolean process(HighlightInfo info) { - if (info.hasHint() && !editor.getFoldingModel().isOffsetCollapsed(info.startOffset)) { - highlights.add(info); - } - return true; + DaemonCodeAnalyzerEx.processHighlights(editor.getDocument(), project, null, startOffset, endOffset, info -> { + if (info.hasHint() && !editor.getFoldingModel().isOffsetCollapsed(info.startOffset)) { + highlights.add(info); } + return true; }); return highlights; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java index b1d452bbfec5..a0a12c2c9d27 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java @@ -80,12 +80,9 @@ public class ShowIntentionsPass extends TextEditorHighlightingPass { final Project project = file.getProject(); final List result = new ArrayList(); - DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true, new Processor() { - @Override - public boolean process(HighlightInfo info) { - addAvailableActionsForGroups(info, editor, file, result, passId, offset); - return true; - } + DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true, info -> { + addAvailableActionsForGroups(info, editor, file, result, passId, offset); + return true; }); return result; } @@ -301,12 +298,8 @@ public class ShowIntentionsPass extends TextEditorHighlightingPass { for (final IntentionAction action : IntentionManager.getInstance().getAvailableIntentionActions()) { Pair place = - ShowIntentionActionsHandler.chooseBetweenHostAndInjected(hostFile, hostEditor, new PairProcessor() { - @Override - public boolean process(PsiFile psiFile, Editor editor) { - return ShowIntentionActionsHandler.availableFor(psiFile, editor, action); - } - }); + ShowIntentionActionsHandler.chooseBetweenHostAndInjected(hostFile, hostEditor, + (psiFile, editor) -> ShowIntentionActionsHandler.availableFor(psiFile, editor, action)); if (place != null) { List enableDisableIntentionAction = new ArrayList(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java index 9dde14d31836..ac14e84e0dde 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java @@ -105,12 +105,9 @@ public class TrafficLightRenderer implements ErrorStripeRenderer, Disposable { incErrorCount(highlighter, -1); } }); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - for (RangeHighlighter rangeHighlighter : model.getAllHighlighters()) { - incErrorCount(rangeHighlighter, 1); - } + UIUtil.invokeLaterIfNeeded(() -> { + for (RangeHighlighter rangeHighlighter : model.getAllHighlighters()) { + incErrorCount(rangeHighlighter, 1); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DockablePopupManager.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DockablePopupManager.java index f7cd2ef0d1ee..b156ed27518d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DockablePopupManager.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DockablePopupManager.java @@ -174,19 +174,9 @@ public abstract class DockablePopupManager { protected void restartAutoUpdate(final boolean state) { if (state && myToolWindow != null) { if (myAutoUpdateRequest == null) { - myAutoUpdateRequest = new Runnable() { - @Override - public void run() { - updateComponent(); - } - }; + myAutoUpdateRequest = () -> updateComponent(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - IdeEventQueue.getInstance().addIdleListener(myAutoUpdateRequest, 500); - } - }); + UIUtil.invokeLaterIfNeeded(() -> IdeEventQueue.getInstance().addIdleListener(myAutoUpdateRequest, 500)); } } else { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index 727aaab6ee74..9e59cb2dd6d0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -622,13 +622,10 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr myText = text; //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myEditorPane.scrollRectToVisible(viewRect); // if ref is defined but is not found in document, this provides a default location - if (ref != null) { - myEditorPane.scrollToReference(ref); - } + SwingUtilities.invokeLater(() -> { + myEditorPane.scrollRectToVisible(viewRect); // if ref is defined but is not found in document, this provides a default location + if (ref != null) { + myEditorPane.scrollToReference(ref); } }); } @@ -648,12 +645,8 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr StyleConstants.setFontFamily(myFontSizeStyle, scheme.getEditorFontName()); } - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - styledDocument.setCharacterAttributes(0, styledDocument.getLength(), myFontSizeStyle, false); - } - }); + ApplicationManager.getApplication().executeOnPooledThread( + () -> styledDocument.setCharacterAttributes(0, styledDocument.getLength(), myFontSizeStyle, false)); } private void goBack() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java index 6816e27b662b..e3d0a648b674 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java @@ -451,24 +451,18 @@ public class DocumentationManager extends DockablePopupManager() { - @Override - public void consume(PsiElement psiElement) { - final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint(); - if (jbPopup != null) { - final String title = getTitle(psiElement, false); - jbPopup.setCaption(title); - } + component.setNavigateCallback(psiElement -> { + final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint(); + if (jbPopup != null) { + final String title = getTitle(psiElement, false); + jbPopup.setCaption(title); } }); - Processor pinCallback = new Processor() { - @Override - public boolean process(JBPopup popup) { - createToolWindow(element, originalElement); - myToolWindow.setAutoHide(false); - popup.cancel(); - return false; - } + Processor pinCallback = popup -> { + createToolWindow(element, originalElement); + myToolWindow.setAutoHide(false); + popup.cancel(); + return false; }; ActionListener actionListener = new ActionListener() { @@ -517,18 +511,15 @@ public class DocumentationManager extends DockablePopupManager() { - @Override - public boolean fun(KeyEvent e) { - if (myCloseOnSneeze) { - closeDocHint(); - } - if (AbstractPopup.isCloseRequest(e) && getDocInfoHint() != null) { - closeDocHint(); - return true; - } - return false; + .setKeyEventHandler(e -> { + if (myCloseOnSneeze) { + closeDocHint(); } + if (AbstractPopup.isCloseRequest(e) && getDocInfoHint() != null) { + closeDocHint(); + return true; + } + return false; }) .createPopup(); @@ -713,77 +704,71 @@ public class DocumentationManager extends DockablePopupManager { + if (myProject.isDisposed()) return; + LOG.debug("Started fetching documentation..."); + final Throwable[] ex = new Throwable[1]; + String text = null; + try { + text = provider.getDocumentation(); + } + catch (Throwable e) { + LOG.info(e); + ex[0] = e; + } - if (ex[0] != null) { - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - String message = ex[0] instanceof IndexNotReadyException - ? "Documentation is not available until indices are built." - : CodeInsightBundle.message("javadoc.external.fetch.error.message"); - component.setText(message, null, true); - callback.setDone(); - } - }); - return; - } - - LOG.debug("Documentation fetched successfully:\n", text); - - final PsiElement element = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - @Nullable - public PsiElement compute() { - return provider.getElement(); - } - }); - if (element == null) { - LOG.debug("Element for which documentation was requested is not available anymore"); - return; - } - final String documentationText = text; - PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() -> { - if (!element.isValid()) { - LOG.debug("Element for which documentation was requested is not valid"); - callback.setDone(); - return; - } - - if (documentationText == null) { - component.setText(CodeInsightBundle.message("no.documentation.found"), element, true, clearHistory); - } - else if (documentationText.isEmpty()) { - component.setText(component.getText(), element, true, clearHistory); - } - else { - component.setData(element, documentationText, clearHistory, provider.getEffectiveExternalUrl(), provider.getRef()); - } - - final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint(); - if(jbPopup==null){ - callback.setDone(); - return; - } - jbPopup.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE); - jbPopup.setCaption(getTitle(element, false)); + if (ex[0] != null) { + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + String message = ex[0] instanceof IndexNotReadyException + ? "Documentation is not available until indices are built." + : CodeInsightBundle.message("javadoc.external.fetch.error.message"); + component.setText(message, null, true); callback.setDone(); }); + return; } + + LOG.debug("Documentation fetched successfully:\n", text); + + final PsiElement element = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + @Nullable + public PsiElement compute() { + return provider.getElement(); + } + }); + if (element == null) { + LOG.debug("Element for which documentation was requested is not available anymore"); + return; + } + final String documentationText = text; + PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() -> { + if (!element.isValid()) { + LOG.debug("Element for which documentation was requested is not valid"); + callback.setDone(); + return; + } + + if (documentationText == null) { + component.setText(CodeInsightBundle.message("no.documentation.found"), element, true, clearHistory); + } + else if (documentationText.isEmpty()) { + component.setText(component.getText(), element, true, clearHistory); + } + else { + component.setData(element, documentationText, clearHistory, provider.getEffectiveExternalUrl(), provider.getRef()); + } + + final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint(); + if(jbPopup==null){ + callback.setDone(); + return; + } + jbPopup.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE); + jbPopup.setCaption(getTitle(element, false)); + callback.setDone(); + }); }, 10); return callback; } @@ -1150,14 +1135,11 @@ public class DocumentationManager extends DockablePopupManager result = new Ref(); - QuickDocUtil.runInReadActionWithWriteActionPriorityWithRetries(new Runnable() { - @Override - public void run() { - final SmartPsiElementPointer originalElement = myElement.getUserData(ORIGINAL_ELEMENT_KEY); - String doc = provider.generateDoc(myElement, originalElement != null ? originalElement.getElement() : null); - result.set(doc); - } - }, DOC_GENERATION_TIMEOUT_MILLISECONDS, DOC_GENERATION_PAUSE_MILLISECONDS, null); + QuickDocUtil.runInReadActionWithWriteActionPriorityWithRetries(() -> { + final SmartPsiElementPointer originalElement = myElement.getUserData(ORIGINAL_ELEMENT_KEY); + String doc = provider.generateDoc(myElement, originalElement != null ? originalElement.getElement() : null); + result.set(doc); + }, DOC_GENERATION_TIMEOUT_MILLISECONDS, DOC_GENERATION_PAUSE_MILLISECONDS, null); return result.get(); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java index cbd89ce27393..7a23e2f9b568 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java @@ -304,55 +304,49 @@ public class QuickDocOnMouseOverManager { public void run() { Ref targetElementRef = new Ref<>(); - QuickDocUtil.runInReadActionWithWriteActionPriorityWithRetries(new Runnable() { - @Override - public void run() { - if (originalElement.isValid()) { - targetElementRef.set(docManager.findTargetElement(editor, offset, originalElement.getContainingFile(), originalElement)); - } + QuickDocUtil.runInReadActionWithWriteActionPriorityWithRetries(() -> { + if (originalElement.isValid()) { + targetElementRef.set(docManager.findTargetElement(editor, offset, originalElement.getContainingFile(), originalElement)); } }, 5000, 100, myProgressIndicator); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myCurrentRequest = null; - - if (editor.isDisposed()) return; - - PsiElement targetElement = targetElementRef.get(); - if (targetElement == null) { - closeQuickDocIfPossible(); - return; - } - - myAlarm.cancelAllRequests(); + ApplicationManager.getApplication().invokeLater(() -> { + myCurrentRequest = null; - if (!originalElement.equals(SoftReference.dereference(myActiveElements.get(editor)))) { - return; - } + if (editor.isDisposed()) return; - // Skip the request if there is a control shown as a result of explicit 'show quick doc' (Ctrl + Q) invocation. - if (docManager.getDocInfoHint() != null && !docManager.isCloseOnSneeze()) { - return; - } + PsiElement targetElement = targetElementRef.get(); + if (targetElement == null) { + closeQuickDocIfPossible(); + return; + } - // We don't want to show a quick doc control if there is an active hint (e.g. the mouse is under an invalid element - // and corresponding error info is shown). - if (!docManager.hasActiveDockedDocWindow() && myHintManager.hasShownHintsThatWillHideByOtherHint(false)) { - myAlarm.addRequest(MyShowQuickDocRequest.this, EditorSettingsExternalizable.getInstance().getQuickDocOnMouseOverElementDelayMillis()); - return; - } + myAlarm.cancelAllRequests(); - editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, - editor.offsetToVisualPosition(originalElement.getTextRange().getStartOffset())); - try { - docManager.showJavaDocInfo(editor, targetElement, originalElement, myHintCloseCallback, true); - myDocumentationManager = new WeakReference(docManager); - } - finally { - editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, null); - } + if (!originalElement.equals(SoftReference.dereference(myActiveElements.get(editor)))) { + return; + } + + // Skip the request if there is a control shown as a result of explicit 'show quick doc' (Ctrl + Q) invocation. + if (docManager.getDocInfoHint() != null && !docManager.isCloseOnSneeze()) { + return; + } + + // We don't want to show a quick doc control if there is an active hint (e.g. the mouse is under an invalid element + // and corresponding error info is shown). + if (!docManager.hasActiveDockedDocWindow() && myHintManager.hasShownHintsThatWillHideByOtherHint(false)) { + myAlarm.addRequest(MyShowQuickDocRequest.this, EditorSettingsExternalizable.getInstance().getQuickDocOnMouseOverElementDelayMillis()); + return; + } + + editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, + editor.offsetToVisualPosition(originalElement.getTextRange().getStartOffset())); + try { + docManager.showJavaDocInfo(editor, targetElement, originalElement, myHintCloseCallback, true); + myDocumentationManager = new WeakReference(docManager); + } + finally { + editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, null); } }, ApplicationManager.getApplication().getNoneModalityState()); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocUtil.java index 91234427272e..fa53b46059f0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocUtil.java @@ -44,24 +44,16 @@ public class QuickDocUtil { public static void updateQuickDocAsync(@NotNull final PsiElement element, @NotNull final Producer docProducer) { final Project project = element.getProject(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - updateQuickDoc(project, element, docProducer.produce()); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> updateQuickDoc(project, element, docProducer.produce())); } public static void updateQuickDoc(@NotNull final Project project, @NotNull final PsiElement element, @Nullable final String documentation) { if (StringUtil.isEmpty(documentation)) return; // modal dialogs with fragment editors fix: can't guess proper modality state here - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - DocumentationComponent component = getActiveDocComponent(project); - if (component != null) { - component.replaceText(documentation, element); - } + UIUtil.invokeLaterIfNeeded(() -> { + DocumentationComponent component = getActiveDocComponent(project); + if (component != null) { + component.replaceText(documentation, element); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.java index 467a60fde882..1a0da3da1da3 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.java @@ -137,12 +137,7 @@ public class ShowQuickDocInfoAction extends BaseCodeInsightAction implements Hin } else if (project != null && element != null) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - DocumentationManager.getInstance(project).showJavaDocInfo(element, null); - } - }, getCommandName(), null); + CommandProcessor.getInstance().executeCommand(project, () -> DocumentationManager.getInstance(project).showJavaDocInfo(element, null), getCommandName(), null); } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CompletionAutoPopupHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CompletionAutoPopupHandler.java index 14294fc521c0..0a6a51e71106 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CompletionAutoPopupHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CompletionAutoPopupHandler.java @@ -54,12 +54,7 @@ public class CompletionAutoPopupHandler extends TypedHandlerDelegate { if (lookup != null) { if (editor.getSelectionModel().hasSelection()) { - lookup.performGuardedChange(new Runnable() { - @Override - public void run() { - EditorModificationUtil.deleteSelectedText(editor); - } - }); + lookup.performGuardedChange(() -> EditorModificationUtil.deleteSelectedText(editor)); } return Result.STOP; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java index 7e25790ea6c1..c85187d77ba2 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java @@ -89,12 +89,9 @@ public class CopyHandler extends EditorActionHandler { final List transferableDatas = new ArrayList(); - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - for (CopyPastePostProcessor processor : Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) { - transferableDatas.addAll(processor.collectTransferableData(file, editor, startOffsets, endOffsets)); - } + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { + for (CopyPastePostProcessor processor : Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) { + transferableDatas.addAll(processor.collectTransferableData(file, editor, startOffsets, endOffsets)); } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyPasteFoldingProcessor.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyPasteFoldingProcessor.java index 0bd390773f68..8e232ddf6ef9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyPasteFoldingProcessor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyPasteFoldingProcessor.java @@ -99,14 +99,11 @@ public class CopyPasteFoldingProcessor extends CopyPastePostProcessor { + for (FoldingData data : value.getData()) { + FoldRegion region = foldingManager.findFoldRegion(editor, data.startOffset + bounds.getStartOffset(), data.endOffset + bounds.getStartOffset()); + if (region != null) { + region.setExpanded(data.isExpanded); } } }; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java index 2de4acb6d6fe..c3be0f6351d9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java @@ -76,12 +76,8 @@ public class EnterHandler extends BaseEnterHandler { public void executeWriteAction(final Editor editor, final Caret caret, final DataContext dataContext) { final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null && !project.isDefault()) { - PostprocessReformattingAspect.getInstance(project).disablePostprocessFormattingInside(new Runnable() { - @Override - public void run() { - executeWriteActionInner(editor, caret, getExtendedContext(dataContext, project, caret), project); - } - }); + PostprocessReformattingAspect.getInstance(project).disablePostprocessFormattingInside( + () -> executeWriteActionInner(editor, caret, getExtendedContext(dataContext, project, caret), project)); } else { executeWriteActionInner(editor, caret, dataContext, project); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/FixDocCommentAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/FixDocCommentAction.java index c18ce1ba49b7..1b9f69b89925 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/FixDocCommentAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/FixDocCommentAction.java @@ -118,12 +118,7 @@ public class FixDocCommentAction extends EditorAction { final CodeDocumentationAwareCommenter commenter = (CodeDocumentationAwareCommenter)c; final Runnable task; if (pair.second == null || pair.second.getTextRange().isEmpty()) { - task = new Runnable() { - @Override - public void run() { - generateComment(pair.first, editor, docProvider, commenter, project); - } - }; + task = () -> generateComment(pair.first, editor, docProvider, commenter, project); } else { final DocCommentFixer fixer = DocCommentFixer.EXTENSION.forLanguage(language); @@ -131,20 +126,10 @@ public class FixDocCommentAction extends EditorAction { return; } else { - task = new Runnable() { - @Override - public void run() { - fixer.fixComment(project, editor, pair.second); - } - }; + task = () -> fixer.fixComment(project, editor, pair.second); } } - final Runnable command = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(task); - } - }; + final Runnable command = () -> ApplicationManager.getApplication().runWriteAction(task); CommandProcessor.getInstance().executeCommand(project, command, "Fix documentation", null); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java index 3d9340c9aad2..a88c6b2751b2 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java @@ -97,13 +97,7 @@ public class JoinLinesHandler extends EditorWriteActionHandler { } final int startReformatOffset = CharArrayUtil.shiftBackward(doc.getCharsSequence(), doc.getLineEndOffset(startLine), " \t"); - CodeEditUtil.setNodeReformatStrategy(new NotNullFunction() { - @NotNull - @Override - public Boolean fun(@NotNull ASTNode node) { - return node.getTextRange().getStartOffset() >= startReformatOffset; - } - }); + CodeEditUtil.setNodeReformatStrategy(node -> node.getTextRange().getStartOffset() >= startReformatOffset); try { doJob(editor, doc, caret, project, docManager, psiFile, startLine, endLine); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java index 3ba45f60dd24..622c39692a1d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java @@ -92,13 +92,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser DataContext context = new DataContext() { @Override public Object getData(@NonNls String dataId) { - return PasteAction.TRANSFERABLE_PROVIDER.is(dataId) ? new Producer() { - @Nullable - @Override - public Transferable produce() { - return transferable; - } - } : dataContext.getData(dataId); + return PasteAction.TRANSFERABLE_PROVIDER.is(dataId) ? (Producer)() -> transferable : dataContext.getData(dataId); } }; @@ -201,11 +195,8 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser final String _text = text; ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - EditorModificationUtil.insertStringAtCaret(editor, _text, false, true); - } + () -> { + EditorModificationUtil.insertStringAtCaret(editor, _text, false, true); } ); @@ -235,28 +226,25 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser final int indentOptions1 = indentOptions; ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document); - switch (indentOptions1) { - case CodeInsightSettings.INDENT_BLOCK: - if (!indented.get()) { - indentBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset(), blockIndentAnchorColumn); - } - break; + () -> { + PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document); + switch (indentOptions1) { + case CodeInsightSettings.INDENT_BLOCK: + if (!indented.get()) { + indentBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset(), blockIndentAnchorColumn); + } + break; - case CodeInsightSettings.INDENT_EACH_LINE: - if (!indented.get()) { - indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); - } - break; + case CodeInsightSettings.INDENT_EACH_LINE: + if (!indented.get()) { + indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); + } + break; - case CodeInsightSettings.REFORMAT_BLOCK: - indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); // this is needed for example when inserting a comment before method - reformatBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); - break; - } + case CodeInsightSettings.REFORMAT_BLOCK: + indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); // this is needed for example when inserting a comment before method + reformatBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); + break; } } ); @@ -327,16 +315,13 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) { PsiDocumentManager.getInstance(project).commitAllDocuments(); - Runnable task = new Runnable() { - @Override - public void run() { - PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); - try { - CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + Runnable task = () -> { + PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); + try { + CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }; @@ -524,15 +509,13 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser desiredSymbolsToRemove = -diff; } - Runnable deindentTask = new Runnable() { - public void run() { - for (int line = anchorLine + 1; line <= lastLine; line++) { - int currentLineStart = document.getLineStartOffset(line); - int currentLineIndentOffset = CharArrayUtil.shiftForward(chars, currentLineStart, " \t"); - int symbolsToRemove = Math.min(currentLineIndentOffset - currentLineStart, desiredSymbolsToRemove); - if (symbolsToRemove > 0) { - document.deleteString(currentLineStart, currentLineStart + symbolsToRemove); - } + Runnable deindentTask = () -> { + for (int line = anchorLine + 1; line <= lastLine; line++) { + int currentLineStart = document.getLineStartOffset(line); + int currentLineIndentOffset = CharArrayUtil.shiftForward(chars, currentLineStart, " \t"); + int symbolsToRemove = Math.min(currentLineIndentOffset - currentLineStart, desiredSymbolsToRemove); + if (symbolsToRemove > 0) { + document.deleteString(currentLineStart, currentLineStart + symbolsToRemove); } } }; @@ -549,12 +532,10 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser */ private static void indentLines(final @NotNull Document document, final int startLine, final int endLine, final @NotNull CharSequence indentString) { - Runnable indentTask = new Runnable() { - public void run() { - for (int line = startLine; line <= endLine; line++) { - int lineStartOffset = document.getLineStartOffset(line); - document.insertString(lineStartOffset, indentString); - } + Runnable indentTask = () -> { + for (int line = startLine; line <= endLine; line++) { + int lineStartOffset = document.getLineStartOffset(line); + document.insertString(lineStartOffset, indentString); } }; DocumentUtil.executeInBulk(document, endLine - startLine > LINE_LIMIT_FOR_BULK_CHANGE, indentTask); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java index 19db854d7be4..c8effc0c541c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java @@ -158,17 +158,14 @@ public class SelectWordHandler extends EditorActionHandler { final Ref minimumRange = new Ref(new TextRange(0, editor.getDocument().getTextLength())); - SelectWordUtil.processRanges(element, editor.getDocument().getCharsSequence(), caretOffset, editor, new Processor() { - @Override - public boolean process(@NotNull TextRange range) { - if (range.contains(selectionRange) && !range.equals(selectionRange)) { - if (minimumRange.get().contains(range)) { - minimumRange.set(range); - return true; - } + SelectWordUtil.processRanges(element, editor.getDocument().getCharsSequence(), caretOffset, editor, range -> { + if (range.contains(selectionRange) && !range.equals(selectionRange)) { + if (minimumRange.get().contains(range)) { + minimumRange.set(range); + return true; } - return false; } + return false; }); return minimumRange.get(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java index 62f912611e4c..7c3f5738a74b 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java @@ -229,14 +229,11 @@ public class SelectWordUtil { final CharSequence text, final int cursorOffset, final Editor editor) { - DumbService.getInstance(element.getProject()).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - PsiElement e = element; - while (e != null && !(e instanceof PsiFile)) { - if (processElement(e, consumer, text, cursorOffset, editor)) return; - e = e.getParent(); - } + DumbService.getInstance(element.getProject()).withAlternativeResolveEnabled(() -> { + PsiElement e = element; + while (e != null && !(e instanceof PsiFile)) { + if (processElement(e, consumer, text, cursorOffset, editor)) return; + e = e.getParent(); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java index 6e77521aa776..60227c34ad1f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java @@ -600,27 +600,24 @@ public class TypedHandler extends TypedActionHandlerBase { } if (element.getNode() != null && isBrace) { final int finalLBraceOffset = lBraceOffset; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run(){ - try{ - int newOffset; - if (finalLBraceOffset != -1) { - RangeMarker marker = document.createRangeMarker(offset, offset + 1); - CodeStyleManager.getInstance(project).reformatRange(file, finalLBraceOffset, offset, true); - newOffset = marker.getStartOffset(); - marker.dispose(); - } else { - newOffset = CodeStyleManager.getInstance(project).adjustLineIndent(file, offset); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try{ + int newOffset; + if (finalLBraceOffset != -1) { + RangeMarker marker = document.createRangeMarker(offset, offset + 1); + CodeStyleManager.getInstance(project).reformatRange(file, finalLBraceOffset, offset, true); + newOffset = marker.getStartOffset(); + marker.dispose(); + } else { + newOffset = CodeStyleManager.getInstance(project).adjustLineIndent(file, offset); + } - editor.getCaretModel().moveToOffset(newOffset + 1); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - editor.getSelectionModel().removeSelection(); - } - catch(IncorrectOperationException e){ - LOG.error(e); - } + editor.getCaretModel().moveToOffset(newOffset + 1); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + editor.getSelectionModel().removeSelection(); + } + catch(IncorrectOperationException e){ + LOG.error(e); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/ParagraphFillHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/ParagraphFillHandler.java index 930148b05e5c..2c2195716143 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/ParagraphFillHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/ParagraphFillHandler.java @@ -49,17 +49,14 @@ public class ParagraphFillHandler { final String replacementText = stringBuilder.toString(); - CommandProcessor.getInstance().executeCommand(element.getProject(), new Runnable() { - @Override - public void run() { - document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), - replacementText); - final CodeFormatterFacade codeFormatter = new CodeFormatterFacade( - CodeStyleSettingsManager.getSettings(element.getProject()), element.getLanguage()); - codeFormatter.doWrapLongLinesIfNecessary(editor, element.getProject(), document, - textRange.getStartOffset(), - textRange.getStartOffset() + replacementText.length() + 1); - } + CommandProcessor.getInstance().executeCommand(element.getProject(), () -> { + document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), + replacementText); + final CodeFormatterFacade codeFormatter = new CodeFormatterFacade( + CodeStyleSettingsManager.getSettings(element.getProject()), element.getLanguage()); + codeFormatter.doWrapLongLinesIfNecessary(editor, element.getProject(), document, + textRange.getStartOffset(), + textRange.getStartOffset() + replacementText.length() + 1); }, null, document); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/MoveElementLeftRightActionHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/MoveElementLeftRightActionHandler.java index d97ed36c462c..cacdb33499ea 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/MoveElementLeftRightActionHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveLeftRight/MoveElementLeftRightActionHandler.java @@ -41,12 +41,7 @@ import java.util.List; import java.util.Set; public class MoveElementLeftRightActionHandler extends EditorWriteActionHandler { - private static final Comparator BY_OFFSET = new Comparator() { - @Override - public int compare(PsiElement o1, PsiElement o2) { - return o1.getTextOffset() - o2.getTextOffset(); - } - }; + private static final Comparator BY_OFFSET = (o1, o2) -> o1.getTextOffset() - o2.getTextOffset(); private static final Set OUR_ACTIONS = new HashSet(Arrays.asList( IdeActions.MOVE_ELEMENT_LEFT, diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoverWrapper.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoverWrapper.java index c078ff41c973..bfdf5741407e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoverWrapper.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoverWrapper.java @@ -124,18 +124,15 @@ class MoverWrapper { // Swap fold regions status if necessary. if (topRegion != null && bottomRegion != null) { CodeFoldingManager.getInstance(project).updateFoldRegions(editor); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion newTopRegion = findTopLevelRegionInRange(editor, myInfo.range1); - if (newTopRegion != null) { - newTopRegion.setExpanded(bottomRegion.isExpanded()); - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + FoldRegion newTopRegion = findTopLevelRegionInRange(editor, myInfo.range1); + if (newTopRegion != null) { + newTopRegion.setExpanded(bottomRegion.isExpanded()); + } - FoldRegion newBottomRegion = findTopLevelRegionInRange(editor, myInfo.range2); - if (newBottomRegion != null) { - newBottomRegion.setExpanded(topRegion.isExpanded()); - } + FoldRegion newBottomRegion = findTopLevelRegionInRange(editor, myInfo.range2); + if (newBottomRegion != null) { + newBottomRegion.setExpanded(topRegion.isExpanded()); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/wordSelection/InjectedReferenceSelectioner.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/wordSelection/InjectedReferenceSelectioner.java index 04eb02fdfdba..07d7c1eef6d6 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/wordSelection/InjectedReferenceSelectioner.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/wordSelection/InjectedReferenceSelectioner.java @@ -41,13 +41,10 @@ public class InjectedReferenceSelectioner extends AbstractWordSelectioner { PsiReference ref = e.findReferenceAt(cursorOffset - e.getTextRange().getStartOffset()); if (ref == null) return Collections.emptyList(); JBIterable it = ref instanceof PsiMultiReference ? JBIterable.of(((PsiMultiReference)ref).getReferences()) : JBIterable.of(ref); - return it.transform(new Function() { - @Override - public TextRange fun(PsiReference ref) { - TextRange base = ref.getElement().getTextRange(); - TextRange r = ref.getRangeInElement().shiftRight(base.getStartOffset()); - return r.containsOffset(cursorOffset) ? r : null; - } + return it.transform(ref1 -> { + TextRange base = ref1.getElement().getTextRange(); + TextRange r = ref1.getRangeInElement().shiftRight(base.getStartOffset()); + return r.containsOffset(cursorOffset) ? r : null; }).filter(Conditions.notNull()).toList(); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java index 80ac45003bbe..9d8d62451cc8 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java @@ -249,21 +249,18 @@ public class CodeFoldingManagerImpl extends CodeFoldingManager implements Projec private void initFolding(@NotNull final Editor editor) { final Document document = editor.getDocument(); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - DocumentFoldingInfo documentFoldingInfo = getDocumentFoldingInfo(document); - Editor[] editors = EditorFactory.getInstance().getEditors(document, myProject); - for (Editor otherEditor : editors) { - if (otherEditor == editor || !isFoldingsInitializedInEditor(otherEditor)) continue; - documentFoldingInfo.loadFromEditor(otherEditor); - break; - } - documentFoldingInfo.setToEditor(editor); - documentFoldingInfo.clear(); - - editor.putUserData(FOLDING_STATE_KEY, Boolean.TRUE); + editor.getFoldingModel().runBatchFoldingOperation(() -> { + DocumentFoldingInfo documentFoldingInfo = getDocumentFoldingInfo(document); + Editor[] editors = EditorFactory.getInstance().getEditors(document, myProject); + for (Editor otherEditor : editors) { + if (otherEditor == editor || !isFoldingsInitializedInEditor(otherEditor)) continue; + documentFoldingInfo.loadFromEditor(otherEditor); + break; } + documentFoldingInfo.setToEditor(editor); + documentFoldingInfo.clear(); + + editor.putUserData(FOLDING_STATE_KEY, Boolean.TRUE); }); } @@ -305,15 +302,12 @@ public class CodeFoldingManagerImpl extends CodeFoldingManager implements Projec } final FoldRegion[] regions = editor.getFoldingModel().getAllFoldRegions(); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - EditorFoldingInfo foldingInfo = EditorFoldingInfo.get(editor); - for (FoldRegion region : regions) { - PsiElement element = foldingInfo.getPsiElement(region); - if (element != null) { - region.setExpanded(!FoldingPolicy.isCollapseByDefault(element)); - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + EditorFoldingInfo foldingInfo = EditorFoldingInfo.get(editor); + for (FoldRegion region : regions) { + PsiElement element = foldingInfo.getPsiElement(region); + if (element != null) { + region.setExpanded(!FoldingPolicy.isCollapseByDefault(element)); } } }); @@ -324,15 +318,12 @@ public class CodeFoldingManagerImpl extends CodeFoldingManager implements Projec public Runnable updateFoldRegionsAsync(@NotNull final Editor editor, final boolean firstTime) { if (!editor.getSettings().isAutoCodeFoldingEnabled()) return null; final Runnable runnable = updateFoldRegions(editor, firstTime, false); - return new Runnable() { - @Override - public void run() { - if (runnable != null) { - runnable.run(); - } - if (firstTime && !isFoldingsInitializedInEditor(editor)) { - initFolding(editor); - } + return () -> { + if (runnable != null) { + runnable.run(); + } + if (firstTime && !isFoldingsInitializedInEditor(editor)) { + initFolding(editor); } }; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseExpandDocCommentsHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseExpandDocCommentsHandler.java index 199acc9159bc..311771f6df5e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseExpandDocCommentsHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseExpandDocCommentsHandler.java @@ -40,14 +40,11 @@ public class CollapseExpandDocCommentsHandler implements CodeInsightActionHandle CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(project); foldingManager.updateFoldRegions(editor); final FoldRegion[] allFoldRegions = editor.getFoldingModel().getAllFoldRegions(); - Runnable processor = new Runnable() { - @Override - public void run() { - for (FoldRegion region : allFoldRegions) { - PsiElement element = EditorFoldingInfo.get(editor).getPsiElement(region); - if (element instanceof PsiDocCommentBase) { - region.setExpanded(myExpand); - } + Runnable processor = () -> { + for (FoldRegion region : allFoldRegions) { + PsiElement element = EditorFoldingInfo.get(editor).getPsiElement(region); + if (element instanceof PsiDocCommentBase) { + region.setExpanded(myExpand); } } }; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseSelectionHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseSelectionHandler.java index c9275429277b..f9d0dd460306 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseSelectionHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CollapseSelectionHandler.java @@ -36,46 +36,43 @@ public class CollapseSelectionHandler implements CodeInsightActionHandler { @Override public void invoke(@NotNull Project project, @NotNull final Editor editor, @NotNull PsiFile file) { editor.getFoldingModel().runBatchFoldingOperation( - new Runnable() { - @Override - public void run() { - final EditorFoldingInfo info = EditorFoldingInfo.get(editor); - FoldingModelEx foldingModel = (FoldingModelEx) editor.getFoldingModel(); - if (editor.getSelectionModel().hasSelection()) { - int start = editor.getSelectionModel().getSelectionStart(); - int end = editor.getSelectionModel().getSelectionEnd(); - if (start + 1 >= end) { - return; - } - Document doc = editor.getDocument(); - if (start < end && doc.getCharsSequence().charAt(end-1) == '\n') end--; - FoldRegion region; - if ((region = FoldingUtil.findFoldRegion(editor, start, end)) != null) { - if (info.getPsiElement(region) == null) { - editor.getFoldingModel().removeFoldRegion(region); - info.removeRegion(region); - } - } else if (!foldingModel.intersectsRegion(start, end)) { - region = foldingModel.addFoldRegion(start, end, ourPlaceHolderText); - LOG.assertTrue(region != null, "Fold region is not created. Folding model: " + foldingModel); - region.setExpanded(false); - int offset = Math.min(start + ourPlaceHolderText.length(), doc.getTextLength()); - editor.getCaretModel().moveToOffset(offset); - } - } else { - FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, editor.getCaretModel().getOffset()); - if (regions.length > 0) { - FoldRegion region = regions[0]; - if (info.getPsiElement(region) == null) { - editor.getFoldingModel().removeFoldRegion(region); - info.removeRegion(region); - } else { - region.setExpanded(!region.isExpanded()); - } - } - } - } + () -> { + final EditorFoldingInfo info = EditorFoldingInfo.get(editor); + FoldingModelEx foldingModel = (FoldingModelEx) editor.getFoldingModel(); + if (editor.getSelectionModel().hasSelection()) { + int start = editor.getSelectionModel().getSelectionStart(); + int end = editor.getSelectionModel().getSelectionEnd(); + if (start + 1 >= end) { + return; + } + Document doc = editor.getDocument(); + if (start < end && doc.getCharsSequence().charAt(end-1) == '\n') end--; + FoldRegion region; + if ((region = FoldingUtil.findFoldRegion(editor, start, end)) != null) { + if (info.getPsiElement(region) == null) { + editor.getFoldingModel().removeFoldRegion(region); + info.removeRegion(region); } + } else if (!foldingModel.intersectsRegion(start, end)) { + region = foldingModel.addFoldRegion(start, end, ourPlaceHolderText); + LOG.assertTrue(region != null, "Fold region is not created. Folding model: " + foldingModel); + region.setExpanded(false); + int offset = Math.min(start + ourPlaceHolderText.length(), doc.getTextLength()); + editor.getCaretModel().moveToOffset(offset); + } + } else { + FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, editor.getCaretModel().getOffset()); + if (regions.length > 0) { + FoldRegion region = regions[0]; + if (info.getPsiElement(region) == null) { + editor.getFoldingModel().removeFoldRegion(region); + info.removeRegion(region); + } else { + region.setExpanded(!region.isExpanded()); + } + } + } + } ); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java index b29f4c6a5366..77f97fac0467 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java @@ -280,70 +280,67 @@ class DocumentFoldingInfo implements JDOMExternalizable, CodeFoldingState { @Override public void readExternal(final Element element) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - clear(); + ApplicationManager.getApplication().runReadAction(() -> { + clear(); - if (!myFile.isValid()) return; + if (!myFile.isValid()) return; - final Document document = FileDocumentManager.getInstance().getDocument(myFile); - if (document == null) return; + final Document document = FileDocumentManager.getInstance().getDocument(myFile); + if (document == null) return; - PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); - if (psiFile == null || !psiFile.getViewProvider().isPhysical()) return; + PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); + if (psiFile == null || !psiFile.getViewProvider().isPhysical()) return; - String date = null; - boolean canRestoreElement = !DumbService.getInstance(myProject).isDumb() || FoldingUpdate.supportsDumbModeFolding(psiFile); - for (final Object o : element.getChildren()) { - Element e = (Element)o; - Boolean expanded = Boolean.valueOf(e.getAttributeValue(EXPANDED_ATT)); - if (ELEMENT_TAG.equals(e.getName())) { - String signature = e.getAttributeValue(SIGNATURE_ATT); - if (signature == null) { - continue; - } - FoldingInfo fi = new FoldingInfo(DEFAULT_PLACEHOLDER, expanded); - if (canRestoreElement) { - PsiElement restoredElement = FoldingPolicy.restoreBySignature(psiFile, signature); - if (restoredElement != null && restoredElement.isValid()) { - myPsiElements.add(SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(restoredElement)); - restoredElement.putUserData(FOLDING_INFO_KEY, fi); - } - } - else { - // Postponed initialization - mySerializedElements.add(new SerializedPsiElement(signature, fi)); - } + String date = null; + boolean canRestoreElement = !DumbService.getInstance(myProject).isDumb() || FoldingUpdate.supportsDumbModeFolding(psiFile); + for (final Object o : element.getChildren()) { + Element e = (Element)o; + Boolean expanded = Boolean.valueOf(e.getAttributeValue(EXPANDED_ATT)); + if (ELEMENT_TAG.equals(e.getName())) { + String signature = e.getAttributeValue(SIGNATURE_ATT); + if (signature == null) { + continue; } - else if (MARKER_TAG.equals(e.getName())) { - if (date == null) { - date = getTimeStamp(); - } - if (date.isEmpty()) continue; - - if (!date.equals(e.getAttributeValue(DATE_ATT)) || FileDocumentManager.getInstance().isDocumentUnsaved(document)) continue; - StringTokenizer tokenizer = new StringTokenizer(e.getAttributeValue(SIGNATURE_ATT), ":"); - try { - int start = Integer.valueOf(tokenizer.nextToken()).intValue(); - int end = Integer.valueOf(tokenizer.nextToken()).intValue(); - if (start < 0 || end >= document.getTextLength() || start > end) continue; - RangeMarker marker = document.createRangeMarker(start, end); - myRangeMarkers.add(marker); - String placeholderAttributeValue = e.getAttributeValue(PLACEHOLDER_ATT); - String placeHolderText = placeholderAttributeValue == null ? DEFAULT_PLACEHOLDER - : XmlStringUtil.unescapeIllegalXmlChars(placeholderAttributeValue); - FoldingInfo fi = new FoldingInfo(placeHolderText, expanded); - marker.putUserData(FOLDING_INFO_KEY, fi); - } - catch (NoSuchElementException exc) { - LOG.error(exc); + FoldingInfo fi = new FoldingInfo(DEFAULT_PLACEHOLDER, expanded); + if (canRestoreElement) { + PsiElement restoredElement = FoldingPolicy.restoreBySignature(psiFile, signature); + if (restoredElement != null && restoredElement.isValid()) { + myPsiElements.add(SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(restoredElement)); + restoredElement.putUserData(FOLDING_INFO_KEY, fi); } } else { - throw new IllegalStateException("unknown tag: " + e.getName()); + // Postponed initialization + mySerializedElements.add(new SerializedPsiElement(signature, fi)); } } + else if (MARKER_TAG.equals(e.getName())) { + if (date == null) { + date = getTimeStamp(); + } + if (date.isEmpty()) continue; + + if (!date.equals(e.getAttributeValue(DATE_ATT)) || FileDocumentManager.getInstance().isDocumentUnsaved(document)) continue; + StringTokenizer tokenizer = new StringTokenizer(e.getAttributeValue(SIGNATURE_ATT), ":"); + try { + int start = Integer.valueOf(tokenizer.nextToken()).intValue(); + int end = Integer.valueOf(tokenizer.nextToken()).intValue(); + if (start < 0 || end >= document.getTextLength() || start > end) continue; + RangeMarker marker = document.createRangeMarker(start, end); + myRangeMarkers.add(marker); + String placeholderAttributeValue = e.getAttributeValue(PLACEHOLDER_ATT); + String placeHolderText = placeholderAttributeValue == null ? DEFAULT_PLACEHOLDER + : XmlStringUtil.unescapeIllegalXmlChars(placeholderAttributeValue); + FoldingInfo fi = new FoldingInfo(placeHolderText, expanded); + marker.putUserData(FOLDING_INFO_KEY, fi); + } + catch (NoSuchElementException exc) { + LOG.error(exc); + } + } + else { + throw new IllegalStateException("unknown tag: " + e.getName()); + } } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java index 6f3b3b78d71c..310ff333b511 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java @@ -58,12 +58,9 @@ public class FoldingUpdate { private static final Key>> CODE_FOLDING_KEY = Key.create("code folding"); private static final Key CODE_FOLDING_FILE_EXTENSION_KEY = Key.create("code folding file extension"); - private static final Comparator COMPARE_BY_OFFSET_REVERSED = new Comparator() { - @Override - public int compare(PsiElement element, PsiElement element1) { - int startOffsetDiff = element1.getTextRange().getStartOffset() - element.getTextRange().getStartOffset(); - return startOffsetDiff == 0 ? element1.getTextRange().getEndOffset() - element.getTextRange().getEndOffset() : startOffsetDiff; - } + private static final Comparator COMPARE_BY_OFFSET_REVERSED = (element, element1) -> { + int startOffsetDiff = element1.getTextRange().getStartOffset() - element.getTextRange().getStartOffset(); + return startOffsetDiff == 0 ? element1.getTextRange().getEndOffset() - element.getTextRange().getEndOffset() : startOffsetDiff; }; private FoldingUpdate() { @@ -120,12 +117,7 @@ public class FoldingUpdate { final UpdateFoldRegionsOperation operation = new UpdateFoldRegionsOperation(project, editor, file, elementsToFoldMap, applyDefaultState ? EXCEPT_CARET_REGION : NO, !applyDefaultState, false); - Runnable runnable = new Runnable() { - @Override - public void run() { - editor.getFoldingModel().runBatchFoldingOperationDoNotCollapseCaret(operation); - } - }; + Runnable runnable = () -> editor.getFoldingModel().runBatchFoldingOperationDoNotCollapseCaret(operation); Set dependencies = new HashSet(); dependencies.add(document); dependencies.add(editor.getFoldingModel()); @@ -175,29 +167,23 @@ public class FoldingUpdate { }); } - return new Runnable() { - @Override - public void run() { - final ArrayList updateOperations = new ArrayList(injectedEditors.size()); - for (int i = 0; i < injectedEditors.size(); i++) { - EditorWindow injectedEditor = injectedEditors.get(i); - PsiFile injectedFile = injectedFiles.get(i); - if (!injectedEditor.getDocument().isValid()) continue; - FoldingMap map = maps.get(i); - updateOperations.add(new UpdateFoldRegionsOperation(project, injectedEditor, injectedFile, map, - applyDefaultState ? EXCEPT_CARET_REGION : NO, !applyDefaultState, true)); - } - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (Runnable operation : updateOperations) { - operation.run(); - } - } - }); - - editor.putUserData(LAST_UPDATE_INJECTED_STAMP_KEY, timeStamp); + return () -> { + final ArrayList updateOperations = new ArrayList(injectedEditors.size()); + for (int i = 0; i < injectedEditors.size(); i++) { + EditorWindow injectedEditor = injectedEditors.get(i); + PsiFile injectedFile = injectedFiles.get(i); + if (!injectedEditor.getDocument().isValid()) continue; + FoldingMap map = maps.get(i); + updateOperations.add(new UpdateFoldRegionsOperation(project, injectedEditor, injectedFile, map, + applyDefaultState ? EXCEPT_CARET_REGION : NO, !applyDefaultState, true)); } + foldingModel.runBatchFoldingOperation(() -> { + for (Runnable operation : updateOperations) { + operation.run(); + } + }); + + editor.putUserData(LAST_UPDATE_INJECTED_STAMP_KEY, timeStamp); }; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/BaseExpandToLevelAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/BaseExpandToLevelAction.java index 67a503dd5851..95b977d9b1e7 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/BaseExpandToLevelAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/BaseExpandToLevelAction.java @@ -58,33 +58,30 @@ public abstract class BaseExpandToLevelAction extends EditorAction { final FoldRegion root = rootRegion; final int[] rootLevel = new int[] {root == null ? 1 : -1}; - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - Iterator regionTreeIterator = FoldingUtil.createFoldTreeIterator(editor); - Deque currentStack = new LinkedList(); - while (regionTreeIterator.hasNext()) { - FoldRegion region = regionTreeIterator.next(); - while (!currentStack.isEmpty() && !isChild(currentStack.peek(), region)) { - if (currentStack.remove() == root) { - rootLevel[0] = -1; - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + Iterator regionTreeIterator = FoldingUtil.createFoldTreeIterator(editor); + Deque currentStack = new LinkedList(); + while (regionTreeIterator.hasNext()) { + FoldRegion region = regionTreeIterator.next(); + while (!currentStack.isEmpty() && !isChild(currentStack.peek(), region)) { + if (currentStack.remove() == root) { + rootLevel[0] = -1; } - currentStack.push(region); - int currentLevel = currentStack.size(); + } + currentStack.push(region); + int currentLevel = currentStack.size(); - if (region == root) { - rootLevel[0] = currentLevel; + if (region == root) { + rootLevel[0] = currentLevel; + } + if (rootLevel[0] >= 0) { + int relativeLevel = currentLevel - rootLevel[0]; + + if (relativeLevel < level) { + region.setExpanded(true); } - if (rootLevel[0] >= 0) { - int relativeLevel = currentLevel - rootLevel[0]; - - if (relativeLevel < level) { - region.setExpanded(true); - } - else if (relativeLevel == level) { - region.setExpanded(false); - } + else if (relativeLevel == level) { + region.setExpanded(false); } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseAllRegionsAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseAllRegionsAction.java index b3804be68202..ee23867112c2 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseAllRegionsAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseAllRegionsAction.java @@ -39,12 +39,9 @@ public class CollapseAllRegionsAction extends EditorAction { CodeFoldingManager.getInstance(project).updateFoldRegions(editor); final List regions = getFoldRegionsForSelection(editor, caret); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : regions) { - region.setExpanded(false); - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + for (FoldRegion region : regions) { + region.setExpanded(false); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionAction.java index c451a528d09e..b59c98108d1a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionAction.java @@ -35,21 +35,18 @@ public class CollapseRegionAction extends EditorAction { final int line = editor.getCaretModel().getLogicalPosition().line; - Runnable processor = new Runnable() { - @Override - public void run() { - FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line); - if (region != null && region.isExpanded()){ - region.setExpanded(false); - } - else { - int offset = editor.getCaretModel().getOffset(); - FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset); - for (FoldRegion region1 : regions) { - if (region1.isExpanded()) { - region1.setExpanded(false); - break; - } + Runnable processor = () -> { + FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line); + if (region != null && region.isExpanded()){ + region.setExpanded(false); + } + else { + int offset = editor.getCaretModel().getOffset(); + FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset); + for (FoldRegion region1 : regions) { + if (region1.isExpanded()) { + region1.setExpanded(false); + break; } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionRecursivelyAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionRecursivelyAction.java index 56ec6ece89de..ac9fef618b82 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionRecursivelyAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/CollapseRegionRecursivelyAction.java @@ -35,12 +35,9 @@ public class CollapseRegionRecursivelyAction extends EditorAction { foldingManager.updateFoldRegions(editor); final List regions = getFoldRegionsForCaret(editor, caret, true); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : regions) { - region.setExpanded(false); - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + for (FoldRegion region : regions) { + region.setExpanded(false); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandAllRegionsAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandAllRegionsAction.java index ccee7bd725ed..488f1255d1c0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandAllRegionsAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandAllRegionsAction.java @@ -42,26 +42,23 @@ public class ExpandAllRegionsAction extends EditorAction { CodeFoldingManager.getInstance(project).updateFoldRegions(editor); final List regions = getFoldRegionsForSelection(editor, caret); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - boolean anythingDone = false; - for (FoldRegion region : regions) { - // try to restore to default state at first - PsiElement element = EditorFoldingInfo.get(editor).getPsiElement(region); - if (!region.isExpanded() && (element == null || !FoldingPolicy.isCollapseByDefault(element))) { - region.setExpanded(true); - anythingDone = true; - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + boolean anythingDone = false; + for (FoldRegion region : regions) { + // try to restore to default state at first + PsiElement element = EditorFoldingInfo.get(editor).getPsiElement(region); + if (!region.isExpanded() && (element == null || !FoldingPolicy.isCollapseByDefault(element))) { + region.setExpanded(true); + anythingDone = true; } - - if (!anythingDone){ - for (FoldRegion region : regions) { - region.setExpanded(true); - } - } - } + + if (!anythingDone){ + for (FoldRegion region : regions) { + region.setExpanded(true); + } + } + }); } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionAction.java index 4a4afd297937..b5efe610eba6 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionAction.java @@ -48,21 +48,18 @@ public class ExpandRegionAction extends EditorAction { foldingManager.updateFoldRegions(editor); final int line = editor.getDocument().getLineNumber(offset); - Runnable processor = new Runnable() { - @Override - public void run() { - FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line); - if (region != null && !region.isExpanded()){ - region.setExpanded(true); - } - else{ - FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset); - for(int i = regions.length - 1; i >= 0; i--){ - region = regions[i]; - if (!region.isExpanded()){ - region.setExpanded(true); - break; - } + Runnable processor = () -> { + FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line); + if (region != null && !region.isExpanded()){ + region.setExpanded(true); + } + else{ + FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset); + for(int i = regions.length - 1; i >= 0; i--){ + region = regions[i]; + if (!region.isExpanded()){ + region.setExpanded(true); + break; } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionRecursivelyAction.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionRecursivelyAction.java index 9d87d2775a64..207d3fc38ade 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionRecursivelyAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/ExpandRegionRecursivelyAction.java @@ -35,12 +35,9 @@ public class ExpandRegionRecursivelyAction extends EditorAction { foldingManager.updateFoldRegions(editor); final List regions = getFoldRegionsForCaret(editor, caret, false); - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : regions) { - region.setExpanded(true); - } + editor.getFoldingModel().runBatchFoldingOperation(() -> { + for (FoldRegion region : regions) { + region.setExpanded(true); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByLineCommentHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByLineCommentHandler.java index 23c88695cd59..2c8d47e7d7f0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByLineCommentHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByLineCommentHandler.java @@ -435,15 +435,12 @@ public class CommentByLineCommentHandler extends MultiCaretCodeInsightActionHand public void doDefaultCommenting(final Block block) { final Document document = block.editor.getDocument(); DocumentUtil.executeInBulk( - document, block.endLine - block.startLine >= Registry.intValue("comment.by.line.bulk.lines.trigger"), new Runnable() { - @Override - public void run() { + document, block.endLine - block.startLine >= Registry.intValue("comment.by.line.bulk.lines.trigger"), () -> { for (int line = block.endLine; line >= block.startLine; line--) { int offset = document.getLineStartOffset(line); commentLine(block, line, offset); } - } - }); + }); } private void doIndentCommenting(final Block block) { @@ -453,29 +450,26 @@ public class CommentByLineCommentHandler extends MultiCaretCodeInsightActionHand final Indent minIndent = computeMinIndent(block.editor, block.psiFile, block.startLine, block.endLine, fileType); DocumentUtil.executeInBulk( - document, block.endLine - block.startLine > Registry.intValue("comment.by.line.bulk.lines.trigger"), new Runnable() { - @Override - public void run() { - for (int line = block.endLine; line >= block.startLine; line--) { - int lineStart = document.getLineStartOffset(line); - int offset = lineStart; - final StringBuilder buffer = new StringBuilder(); - while (true) { - String space = buffer.toString(); - Indent indent = myCodeStyleManager.getIndent(space, fileType); - if (indent.isGreaterThan(minIndent) || indent.equals(minIndent)) break; - char c = chars.charAt(offset); - if (c != ' ' && c != '\t') { - String newSpace = myCodeStyleManager.fillIndent(minIndent, fileType); - document.replaceString(lineStart, offset, newSpace); - offset = lineStart + newSpace.length(); - break; - } - buffer.append(c); - offset++; + document, block.endLine - block.startLine > Registry.intValue("comment.by.line.bulk.lines.trigger"), () -> { + for (int line = block.endLine; line >= block.startLine; line--) { + int lineStart = document.getLineStartOffset(line); + int offset = lineStart; + final StringBuilder buffer = new StringBuilder(); + while (true) { + String space = buffer.toString(); + Indent indent = myCodeStyleManager.getIndent(space, fileType); + if (indent.isGreaterThan(minIndent) || indent.equals(minIndent)) break; + char c = chars.charAt(offset); + if (c != ' ' && c != '\t') { + String newSpace = myCodeStyleManager.fillIndent(minIndent, fileType); + document.replaceString(lineStart, offset, newSpace); + offset = lineStart + newSpace.length(); + break; } - commentLine(block, line, offset); + buffer.append(c); + offset++; } + commentLine(block, line, offset); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlighter.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlighter.java index bb4ffba65d94..93b99adea60b 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlighter.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlighter.java @@ -124,22 +124,16 @@ public class BraceHighlighter implements StartupActivity { final Document document = editor.getDocument(); if (document instanceof DocumentEx && ((DocumentEx)document).isInBulkUpdate()) return; - BraceHighlightingHandler.lookForInjectedAndMatchBracesInOtherThread(editor, alarm, new Processor() { - @Override - public boolean process(final BraceHighlightingHandler handler) { - handler.updateBraces(); - return false; - } + BraceHighlightingHandler.lookForInjectedAndMatchBracesInOtherThread(editor, alarm, handler -> { + handler.updateBraces(); + return false; }); } private void clearBraces(@NotNull final Editor editor) { - BraceHighlightingHandler.lookForInjectedAndMatchBracesInOtherThread(editor, myAlarm, new Processor() { - @Override - public boolean process(final BraceHighlightingHandler handler) { - handler.clearBraceHighlighters(); - return false; - } + BraceHighlightingHandler.lookForInjectedAndMatchBracesInOtherThread(editor, myAlarm, handler -> { + handler.clearBraceHighlighters(); + return false; }); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java index d1b59e1df8e6..76f6c9420ee9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java @@ -122,63 +122,54 @@ public class BraceHighlightingHandler { final Project project = editor.getProject(); final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); if (!isValidFile(psiFile)) return; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(new Runnable() { - @Override - public void run() { - final PsiFile injected; - try { - if (psiFile instanceof PsiCompiledFile) { - injected = ((PsiCompiledFile)psiFile).getDecompiledPsiFile(); - } - else if (psiFile instanceof PsiCompiledElement || - psiFile instanceof PsiBinaryFile || - !isValidEditor(editor) || - !isValidFile(psiFile)) { - injected = null; - } - else { - injected = getInjectedFileIfAny(editor, project, offset, psiFile, alarm); - } - } - catch (RuntimeException e) { - // Reset processing flag in case of unexpected exception. - ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { - @Override - public void run() { - PROCESSED_EDITORS.remove(editor); - } - }); - throw e; - } - ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { - @Override - public void run() { - try { - if (isValidEditor(editor) && isValidFile(injected)) { - Editor newEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injected); - BraceHighlightingHandler handler = new BraceHighlightingHandler(project, newEditor, alarm, injected); - processor.process(handler); - } - } - finally { - PROCESSED_EDITORS.remove(editor); - } - } - }, ModalityState.stateForComponent(editor.getComponent())); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(() -> { + final PsiFile injected; + try { + if (psiFile instanceof PsiCompiledFile) { + injected = ((PsiCompiledFile)psiFile).getDecompiledPsiFile(); } - })) { - // write action is queued in AWT. restart after it's finished - ApplicationManager.getApplication().invokeLater(new Runnable() { + else if (psiFile instanceof PsiCompiledElement || + psiFile instanceof PsiBinaryFile || + !isValidEditor(editor) || + !isValidFile(psiFile)) { + injected = null; + } + else { + injected = getInjectedFileIfAny(editor, project, offset, psiFile, alarm); + } + } + catch (RuntimeException e) { + // Reset processing flag in case of unexpected exception. + ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { @Override public void run() { PROCESSED_EDITORS.remove(editor); - lookForInjectedAndMatchBracesInOtherThread(editor, alarm, processor); } - }, ModalityState.stateForComponent(editor.getComponent())); + }); + throw e; } + ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { + @Override + public void run() { + try { + if (isValidEditor(editor) && isValidFile(injected)) { + Editor newEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injected); + BraceHighlightingHandler handler = new BraceHighlightingHandler(project, newEditor, alarm, injected); + processor.process(handler); + } + } + finally { + PROCESSED_EDITORS.remove(editor); + } + } + }, ModalityState.stateForComponent(editor.getComponent())); + })) { + // write action is queued in AWT. restart after it's finished + ApplicationManager.getApplication().invokeLater(() -> { + PROCESSED_EDITORS.remove(editor); + lookForInjectedAndMatchBracesInOtherThread(editor, alarm, processor); + }, ModalityState.stateForComponent(editor.getComponent())); } }); } @@ -210,12 +201,9 @@ public class BraceHighlightingHandler { } } else { - PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() { - @Override - public void run() { - if (!project.isDisposed() && !editor.isDisposed()) { - BraceHighlighter.updateBraces(editor, alarm); - } + PsiDocumentManager.getInstance(project).performForCommittedDocument(document, () -> { + if (!project.isDisposed() && !editor.isDisposed()) { + BraceHighlighter.updateBraces(editor, alarm); } }); } @@ -364,12 +352,9 @@ public class BraceHighlightingHandler { final int _offset = offset; final FileType _fileType = fileType; - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed() && !myEditor.isDisposed()) { - highlightScope(_offset, _fileType); - } + myAlarm.addRequest(() -> { + if (!myProject.isDisposed() && !myEditor.isDisposed()) { + highlightScope(_offset, _fileType); } }, 300); } @@ -488,15 +473,12 @@ public class BraceHighlightingHandler { final int startLine = myEditor.offsetToLogicalPosition(lBrace.getStartOffset()).line; final int endLine = myEditor.offsetToLogicalPosition(rBrace.getEndOffset()).line; if (endLine - startLine > 0) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (myProject.isDisposed() || myEditor.isDisposed()) return; - Color color = attributes.getBackgroundColor(); - if (color == null) return; - color = ColorUtil.isDark(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()) ? ColorUtil.shift(color, 1.5d) : color.darker(); - lineMarkFragment(startLine, endLine, color); - } + final Runnable runnable = () -> { + if (myProject.isDisposed() || myEditor.isDisposed()) return; + Color color = attributes.getBackgroundColor(); + if (color == null) return; + color = ColorUtil.isDark(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()) ? ColorUtil.shift(color, 1.5d) : color.darker(); + lineMarkFragment(startLine, endLine, color); }; if (!scopeHighlighting) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/ChooseOneOrAllRunnable.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/ChooseOneOrAllRunnable.java index 304d147677ee..90b77e2e26ff 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/ChooseOneOrAllRunnable.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/ChooseOneOrAllRunnable.java @@ -69,30 +69,22 @@ public abstract class ChooseOneOrAllRunnable implements Ru final PopupChooserBuilder builder = new PopupChooserBuilder(myList); renderer.installSpeedSearch(builder); - final Runnable callback = new Runnable() { - @Override - public void run() { - int idx = myList.getSelectedIndex(); - if (idx < 0) return; - if (idx > 0) { - selected((T[])ArrayUtil.toObjectArray(myClasses[idx-1].getClass(), myClasses[idx-1])); - } - else { - selected(myClasses); - } + final Runnable callback = () -> { + int idx = myList.getSelectedIndex(); + if (idx < 0) return; + if (idx > 0) { + selected((T[])ArrayUtil.toObjectArray(myClasses[idx-1].getClass(), myClasses[idx-1])); + } + else { + selected(myClasses); } }; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - builder. - setTitle(myTitle). - setItemChoosenCallback(callback). - createPopup(). - showInBestPositionFor(myEditor); - } - }); + ApplicationManager.getApplication().invokeLater(() -> builder. + setTitle(myTitle). + setItemChoosenCallback(callback). + createPopup(). + showInBestPositionFor(myEditor)); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java index e16bac126f08..54f9792434de 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java @@ -85,19 +85,16 @@ public class HighlightUsagesHandler extends HighlightHandlerBase { return; } - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - UsageTarget[] usageTargets = getUsageTargets(editor, file); - if (usageTargets == null) { - handleNoUsageTargets(file, editor, selectionModel, project); - return; - } + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { + UsageTarget[] usageTargets = getUsageTargets(editor, file); + if (usageTargets == null) { + handleNoUsageTargets(file, editor, selectionModel, project); + return; + } - boolean clearHighlights = isClearHighlights(editor); - for (UsageTarget target : usageTargets) { - target.highlightUsages(file, editor, clearHighlights); - } + boolean clearHighlights = isClearHighlights(editor); + for (UsageTarget target : usageTargets) { + target.highlightUsages(file, editor, clearHighlights); } }); } @@ -125,12 +122,9 @@ public class HighlightUsagesHandler extends HighlightHandlerBase { ResolveResult[] results = ((PsiPolyVariantReference)ref).multiResolve(false); if (results.length > 0) { - usageTargets = ContainerUtil.mapNotNull(results, new Function() { - @Override - public UsageTarget fun(ResolveResult result) { - PsiElement element = result.getElement(); - return element == null ? null : new PsiElement2UsageTargetAdapter(element); - } + usageTargets = ContainerUtil.mapNotNull(results, result -> { + PsiElement element = result.getElement(); + return element == null ? null : new PsiElement2UsageTargetAdapter(element); }, UsageTarget.EMPTY_ARRAY); } } @@ -366,18 +360,8 @@ public class HighlightUsagesHandler extends HighlightHandlerBase { TextAttributes attributes) { if (editor instanceof EditorWindow) editor = ((EditorWindow)editor).getDelegate(); RangeHighlighter[] highlighters = ((HighlightManagerImpl)highlightManager).getHighlighters(editor); - Arrays.sort(highlighters, new Comparator() { - @Override - public int compare(RangeHighlighter o1, RangeHighlighter o2) { - return o1.getStartOffset() - o2.getStartOffset(); - } - }); - Collections.sort(rangesToHighlight, new Comparator() { - @Override - public int compare(TextRange o1, TextRange o2) { - return o1.getStartOffset() - o2.getStartOffset(); - } - }); + Arrays.sort(highlighters, (o1, o2) -> o1.getStartOffset() - o2.getStartOffset()); + Collections.sort(rangesToHighlight, (o1, o2) -> o1.getStartOffset() - o2.getStartOffset()); int i = 0; int j = 0; while (i < highlighters.length && j < rangesToHighlight.size()) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java index 13d1695cca77..3c7319d6cda3 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerBase.java @@ -56,12 +56,9 @@ public abstract class HighlightUsagesHandlerBase { if (targets == null) { return; } - selectTargets(targets, new Consumer>() { - @Override - public void consume(final List targets) { - computeUsages(targets); - performHighlighting(); - } + selectTargets(targets, targets1 -> { + computeUsages(targets1); + performHighlighting(); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/actions/HighlightUsagesAction.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/actions/HighlightUsagesAction.java index effeaa6f818f..f4c34742166d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/actions/HighlightUsagesAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/actions/HighlightUsagesAction.java @@ -50,16 +50,13 @@ public class HighlightUsagesAction extends AnAction implements DumbAware { CommandProcessor.getInstance().executeCommand( project, - new Runnable() { - @Override - public void run() { - PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); - try { - HighlightUsagesHandler.invoke(project, editor, psiFile); - } - catch (IndexNotReadyException ex) { - DumbService.getInstance(project).showDumbModeNotification(ActionsBundle.message("action.HighlightUsagesInFile.not.ready")); - } + () -> { + PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); + try { + HighlightUsagesHandler.invoke(project, editor, psiFile); + } + catch (IndexNotReadyException ex) { + DumbService.getInstance(project).showDumbModeNotification(ActionsBundle.message("action.HighlightUsagesInFile.not.ready")); } }, commandName, diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewComponent.java index a9ac6f35938a..eec13f568c3a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewComponent.java @@ -173,72 +173,69 @@ public class ImplementationViewComponent extends JPanel { setPreferredSize(JBUI.size(600, 400)); - update(elements, new PairFunction, Boolean>() { - @Override - public Boolean fun(final PsiElement[] psiElements, final List fileDescriptors) { - if (psiElements.length == 0) return false; - myElements = psiElements; + update(elements, (psiElements, fileDescriptors) -> { + if (psiElements.length == 0) return false; + myElements = psiElements; - myIndex = index < myElements.length ? index : 0; - PsiFile psiFile = getContainingFile(myElements[myIndex]); + myIndex = index < myElements.length ? index : 0; + PsiFile psiFile = getContainingFile(myElements[myIndex]); - VirtualFile virtualFile = psiFile.getVirtualFile(); - EditorHighlighter highlighter; - if (virtualFile != null) - highlighter = HighlighterFactory.createHighlighter(project, virtualFile); - else { - String fileName = psiFile.getName(); // some artificial psi file, lets do best we can - highlighter = HighlighterFactory.createHighlighter(project, fileName); - } - - ((EditorEx)myEditor).setHighlighter(highlighter); - - gc.fill = GridBagConstraints.HORIZONTAL; - gc.weightx = 1; - myLabel = new JLabel(); - myFileChooser = new ComboBox(fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]), 250); - myFileChooser.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int index = myFileChooser.getSelectedIndex(); - if (myIndex != index) { - myIndex = index; - updateControls(); - } - } - }); - toolbarPanel.add(myFileChooser, gc); - - if (myElements.length > 1) { - updateRenderer(project); - myLabel.setVisible(false); - } - else { - myFileChooser.setVisible(false); - myCountLabel.setVisible(false); - - VirtualFile file = psiFile.getVirtualFile(); - if (file != null) { - myLabel.setIcon(getIconForFile(psiFile)); - myLabel.setForeground(FileStatusManager.getInstance(project).getStatus(file).getColor()); - myLabel.setText(file.getPresentableName()); - myLabel.setBorder(new CompoundBorder(IdeBorderFactory.createRoundedBorder(), IdeBorderFactory.createEmptyBorder(0, 0, 0, 5))); - } - toolbarPanel.add(myLabel, gc); - } - - gc.fill = GridBagConstraints.NONE; - gc.weightx = 0; - toolbarPanel.add(myCountLabel, gc); - - header.add(toolbarPanel, BorderLayout.CENTER); - header.add(myLocationLabel, BorderLayout.EAST); - - add(header, BorderLayout.NORTH); - - updateControls(); - return true; + VirtualFile virtualFile = psiFile.getVirtualFile(); + EditorHighlighter highlighter; + if (virtualFile != null) + highlighter = HighlighterFactory.createHighlighter(project, virtualFile); + else { + String fileName = psiFile.getName(); // some artificial psi file, lets do best we can + highlighter = HighlighterFactory.createHighlighter(project, fileName); } + + ((EditorEx)myEditor).setHighlighter(highlighter); + + gc.fill = GridBagConstraints.HORIZONTAL; + gc.weightx = 1; + myLabel = new JLabel(); + myFileChooser = new ComboBox(fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]), 250); + myFileChooser.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int index1 = myFileChooser.getSelectedIndex(); + if (myIndex != index1) { + myIndex = index1; + updateControls(); + } + } + }); + toolbarPanel.add(myFileChooser, gc); + + if (myElements.length > 1) { + updateRenderer(project); + myLabel.setVisible(false); + } + else { + myFileChooser.setVisible(false); + myCountLabel.setVisible(false); + + VirtualFile file = psiFile.getVirtualFile(); + if (file != null) { + myLabel.setIcon(getIconForFile(psiFile)); + myLabel.setForeground(FileStatusManager.getInstance(project).getStatus(file).getColor()); + myLabel.setText(file.getPresentableName()); + myLabel.setBorder(new CompoundBorder(IdeBorderFactory.createRoundedBorder(), IdeBorderFactory.createEmptyBorder(0, 0, 0, 5))); + } + toolbarPanel.add(myLabel, gc); + } + + gc.fill = GridBagConstraints.NONE; + gc.weightx = 0; + toolbarPanel.add(myCountLabel, gc); + + header.add(toolbarPanel, BorderLayout.CENTER); + header.add(myLocationLabel, BorderLayout.EAST); + + add(header, BorderLayout.NORTH); + + updateControls(); + return true; }); } @@ -268,58 +265,55 @@ public class ImplementationViewComponent extends JPanel { } public void update(@NotNull final PsiElement[] elements, final int index) { - update(elements, new PairFunction, Boolean>() { - @Override - public Boolean fun(PsiElement[] psiElements, List fileDescriptors) { - if (myEditor.isDisposed()) return false; - if (psiElements.length == 0) return false; + update(elements, (psiElements, fileDescriptors) -> { + if (myEditor.isDisposed()) return false; + if (psiElements.length == 0) return false; - final Project project = psiElements[0].getProject(); - myElements = psiElements; + final Project project = psiElements[0].getProject(); + myElements = psiElements; - myIndex = index < myElements.length ? index : 0; - PsiFile psiFile = getContainingFile(myElements[myIndex]); + myIndex = index < myElements.length ? index : 0; + PsiFile psiFile = getContainingFile(myElements[myIndex]); - VirtualFile virtualFile = psiFile.getVirtualFile(); - EditorHighlighter highlighter; - if (virtualFile != null) - highlighter = HighlighterFactory.createHighlighter(project, virtualFile); - else { - String fileName = psiFile.getName(); // some artificial psi file, lets do best we can - highlighter = HighlighterFactory.createHighlighter(project, fileName); - } - - ((EditorEx)myEditor).setHighlighter(highlighter); - - if (myElements.length > 1) { - myFileChooser.setVisible(true); - myCountLabel.setVisible(true); - myLabel.setVisible(false); - - myFileChooser.setModel(new DefaultComboBoxModel(fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]))); - updateRenderer(project); - } - else { - myFileChooser.setVisible(false); - myCountLabel.setVisible(false); - - VirtualFile file = psiFile.getVirtualFile(); - if (file != null) { - myLabel.setIcon(getIconForFile(psiFile)); - myLabel.setForeground(FileStatusManager.getInstance(project).getStatus(file).getColor()); - myLabel.setText(file.getPresentableName()); - myLabel.setBorder(new CompoundBorder(IdeBorderFactory.createRoundedBorder(), IdeBorderFactory.createEmptyBorder(0, 0, 0, 5))); - myLabel.setVisible(true); - } - } - - updateControls(); - - revalidate(); - repaint(); - - return true; + VirtualFile virtualFile = psiFile.getVirtualFile(); + EditorHighlighter highlighter; + if (virtualFile != null) + highlighter = HighlighterFactory.createHighlighter(project, virtualFile); + else { + String fileName = psiFile.getName(); // some artificial psi file, lets do best we can + highlighter = HighlighterFactory.createHighlighter(project, fileName); } + + ((EditorEx)myEditor).setHighlighter(highlighter); + + if (myElements.length > 1) { + myFileChooser.setVisible(true); + myCountLabel.setVisible(true); + myLabel.setVisible(false); + + myFileChooser.setModel(new DefaultComboBoxModel(fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]))); + updateRenderer(project); + } + else { + myFileChooser.setVisible(false); + myCountLabel.setVisible(false); + + VirtualFile file = psiFile.getVirtualFile(); + if (file != null) { + myLabel.setIcon(getIconForFile(psiFile)); + myLabel.setForeground(FileStatusManager.getInstance(project).getStatus(file).getColor()); + myLabel.setText(file.getPresentableName()); + myLabel.setBorder(new CompoundBorder(IdeBorderFactory.createRoundedBorder(), IdeBorderFactory.createEmptyBorder(0, 0, 0, 5))); + myLabel.setVisible(true); + } + } + + updateControls(); + + revalidate(); + repaint(); + + return true; }); } @@ -418,17 +412,14 @@ public class ImplementationViewComponent extends JPanel { private void updateTextElement(final PsiElement elt) { final String newText = getNewText(elt); if (newText == null || Comparing.strEqual(newText, myEditor.getDocument().getText())) return; - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - Document fragmentDoc = myEditor.getDocument(); - fragmentDoc.setReadOnly(false); + DocumentUtil.writeInRunUndoTransparentAction(() -> { + Document fragmentDoc = myEditor.getDocument(); + fragmentDoc.setReadOnly(false); - fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), newText); - fragmentDoc.setReadOnly(true); - myEditor.getCaretModel().moveToOffset(0); - myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - } + fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), newText); + fragmentDoc.setReadOnly(true); + myEditor.getCaretModel().moveToOffset(0); + myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java index c95d26719453..bed57b73b472 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java @@ -63,16 +63,13 @@ public class ParameterInfoComponent extends JPanel { ImmutableMap.of(ParameterInfoUIContextEx.Flag.HIGHLIGHT, "b", ParameterInfoUIContextEx.Flag.DISABLE, "font color=gray", ParameterInfoUIContextEx.Flag.STRIKEOUT, "strike"); - private static final Comparator TEXT_RANGE_COMPARATOR = new Comparator() { - @Override - public int compare(TextRange o1, TextRange o2) { - if (o1.getStartOffset() == o2.getStartOffset()) { - return o1.getEndOffset() > o2.getEndOffset() ? 1 : -1; - } - if (o1.getStartOffset() > o2.getStartOffset()) return 1; - if (o1.getEndOffset() > o2.getEndOffset()) return 1; - return -1; + private static final Comparator TEXT_RANGE_COMPARATOR = (o1, o2) -> { + if (o1.getStartOffset() == o2.getStartOffset()) { + return o1.getEndOffset() > o2.getEndOffset() ? 1 : -1; } + if (o1.getStartOffset() > o2.getStartOffset()) return 1; + if (o1.getEndOffset() > o2.getEndOffset()) return 1; + return -1; }; private boolean myRequestFocus; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowContainerInfoHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowContainerInfoHandler.java index 5ccd71b866c7..0acca304c4af 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowContainerInfoHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowContainerInfoHandler.java @@ -100,14 +100,11 @@ public class ShowContainerInfoHandler implements CodeInsightActionHandler { return; } final PsiElement _container = container; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - LightweightHint hint = EditorFragmentComponent.showEditorFragmentHint(editor, range, true, true); - if (hint != null) { - hint.putUserData(CONTAINER_KEY, _container); - editor.putUserData(MY_LAST_HINT_KEY, new WeakReference(hint)); - } + ApplicationManager.getApplication().invokeLater(() -> { + LightweightHint hint1 = EditorFragmentComponent.showEditorFragmentHint(editor, range, true, true); + if (hint1 != null) { + hint1.putUserData(CONTAINER_KEY, _container); + editor.putUserData(MY_LAST_HINT_KEY, new WeakReference(hint1)); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowExpressionTypeHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowExpressionTypeHandler.java index b41cf29ca472..b83f36f4252d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowExpressionTypeHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowExpressionTypeHandler.java @@ -81,21 +81,13 @@ public class ShowExpressionTypeHandler implements CodeInsightActionHandler { final String informationHint = provider.getInformationHint(expression); TextRange range = expression.getTextRange(); editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - HintManager.getInstance().showInformationHint(editor, informationHint); - } - }); + ApplicationManager.getApplication().invokeLater(() -> HintManager.getInstance().showInformationHint(editor, informationHint)); } }; if (map.isEmpty()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String errorHint = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(handlers)).getErrorHint(); - HintManager.getInstance().showErrorHint(editor, errorHint); - } + ApplicationManager.getApplication().invokeLater(() -> { + String errorHint = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(handlers)).getErrorHint(); + HintManager.getInstance().showErrorHint(editor, errorHint); }); } else if (map.size() == 1) { @@ -104,12 +96,7 @@ public class ShowExpressionTypeHandler implements CodeInsightActionHandler { else { IntroduceTargetChooser.showChooser( editor, ContainerUtil.newArrayList(map.keySet()), callback, - new Function() { - @Override - public String fun(@NotNull PsiElement expression) { - return expression.getText(); - } - } + expression -> expression.getText() ); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java index c6282aef5e4c..b79485f1ea61 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java @@ -138,14 +138,11 @@ public class ShowParameterInfoHandler implements CodeInsightActionHandler { hint.setSelectingHint(true); final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); final Pair pos = ShowParameterInfoContext.chooseBestHintPosition(project, editor, -1, -1, hint, true, HintManager.DEFAULT); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!editor.getComponent().isShowing()) return; - hintManager.showEditorHint(hint, editor, pos.getFirst(), - HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_LOOKUP_ITEM_CHANGE | HintManager.UPDATE_BY_SCROLLING, - 0, false, pos.getSecond()); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!editor.getComponent().isShowing()) return; + hintManager.showEditorHint(hint, editor, pos.getFirst(), + HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_LOOKUP_ITEM_CHANGE | HintManager.UPDATE_BY_SCROLLING, + 0, false, pos.getSecond()); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java index 6ca9eb1a0632..3d63a1704464 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java @@ -71,12 +71,9 @@ public class FileLevelIntentionComponent extends EditorNotificationPanel { continue; } final String text = action.getText(); - createActionLabel(text, new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - ShowIntentionActionsHandler.chooseActionAndInvoke(psiFile, editor, action, text); - } + createActionLabel(text, () -> { + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + ShowIntentionActionsHandler.chooseActionAndInvoke(psiFile, editor, action, text); }); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java index d7bf2c6733c6..5ca0220dc85c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java @@ -158,12 +158,9 @@ public class IntentionHintComponent implements Disposable, ScrollAwareHint { component.showIntentionHintImpl(!showExpanded, position); Disposer.register(project, component); if (showExpanded) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!editor.isDisposed() && editor.getComponent().isShowing()) { - component.showPopup(false); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!editor.isDisposed() && editor.getComponent().isShowing()) { + component.showPopup(false); } }, project.getDisposed()); } @@ -571,12 +568,7 @@ public class IntentionHintComponent implements Disposable, ScrollAwareHint { myVisible = true; if (myShouldDelay) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - showImpl(parentComponent, x, y, focusBackComponent); - } - }, DELAY); + myAlarm.addRequest(() -> showImpl(parentComponent, x, y, focusBackComponent), DELAY); } else { showImpl(parentComponent, x, y, focusBackComponent); @@ -650,16 +642,8 @@ public class IntentionHintComponent implements Disposable, ScrollAwareHint { @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { final IntentionSettingsConfigurable configurable = new IntentionSettingsConfigurable(); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - configurable.selectIntention(myFamilyName); - } - }); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + SwingUtilities.invokeLater(() -> configurable.selectIntention(myFamilyName)); }); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionListStep.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionListStep.java index 91c0af3d2f39..3a613776b2af 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionListStep.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionListStep.java @@ -305,16 +305,13 @@ public class IntentionListStep implements ListPopupStep() { - @Override - public int compare(final IntentionActionWithTextCaching o1, final IntentionActionWithTextCaching o2) { - int weight1 = getWeight(o1); - int weight2 = getWeight(o2); - if (weight1 != weight2) { - return weight2 - weight1; - } - return o1.compareTo(o2); + Collections.sort(result, (o1, o2) -> { + int weight1 = getWeight(o1); + int weight2 = getWeight(o2); + if (weight1 != weight2) { + return weight2 - weight1; } + return o1.compareTo(o2); }); return result; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java index 941fe875db22..e5d970ac3878 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java @@ -231,24 +231,16 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { if (editor != null) { editor.putUserData(QuickEditAction.QUICK_EDIT_HANDLER, this); final FoldingModel foldingModel = editor.getFoldingModel(); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (RangeMarker o : ContainerUtil.reverse(((DocumentEx)myNewDocument).getGuardedBlocks())) { - String replacement = o.getUserData(REPLACEMENT_KEY); - if (StringUtil.isEmpty(replacement)) continue; - FoldRegion region = foldingModel.addFoldRegion(o.getStartOffset(), o.getEndOffset(), replacement); - if (region != null) region.setExpanded(false); - } + foldingModel.runBatchFoldingOperation(() -> { + for (RangeMarker o : ContainerUtil.reverse(((DocumentEx)myNewDocument).getGuardedBlocks())) { + String replacement = o.getUserData(REPLACEMENT_KEY); + if (StringUtil.isEmpty(replacement)) continue; + FoldRegion region = foldingModel.addFoldRegion(o.getStartOffset(), o.getEndOffset(), replacement); + if (region != null) region.setExpanded(false); } }); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); - } - }); + SwingUtilities.invokeLater(() -> myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE)); } } @@ -262,12 +254,9 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { // and check it after action is completed if (e.getDocument() == myOrigDocument) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) { - closeEditor(); - } + SwingUtilities.invokeLater(() -> { + if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) { + closeEditor(); } }); } @@ -275,21 +264,15 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { else if (e.getDocument() == myNewDocument) { commitToOriginal(e); if (!isValid()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - closeEditor(); - } + ApplicationManager.getApplication().invokeLater(() -> { + closeEditor(); }, myProject.getDisposed()); } } else if (e.getDocument() == myOrigDocument) { if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid()) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - closeEditor(); - } + ApplicationManager.getApplication().invokeLater(() -> { + closeEditor(); }, myProject.getDisposed()); } } @@ -365,15 +348,12 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { myCommittingToOriginal = true; try { if (origVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origVirtualFile).hasReadonlyFiles()) { - PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() { - @Override - public void run() { - if (myAltFullRange != null) { - altCommitToOriginal(e); - return; - } - commitToOriginalInner(); + PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(() -> { + if (myAltFullRange != null) { + altCommitToOriginal(e); + return; } + commitToOriginalInner(); }); PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myOrigDocument); } @@ -452,16 +432,13 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { // reformat PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument); - Runnable task = new Runnable() { - @Override - public void run() { - try { - CodeStyleManager.getInstance(myProject).reformatRange( - origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true); - } - catch (IncorrectOperationException e) { - //LOG.error(e); - } + Runnable task = () -> { + try { + CodeStyleManager.getInstance(myProject).reformatRange( + origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true); + } + catch (IncorrectOperationException e1) { + //LOG.error(e); } }; DocumentUtil.executeInBulk(myOrigDocument, true, task); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/ShowIntentionActionsHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/ShowIntentionActionsHandler.java index e33fec88984a..504dc3dff075 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/ShowIntentionActionsHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/ShowIntentionActionsHandler.java @@ -178,12 +178,8 @@ public class ShowIntentionActionsHandler implements CodeInsightActionHandler { FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.quickFix"); ((FeatureUsageTrackerImpl)FeatureUsageTracker.getInstance()).getFixesStats().registerInvocation(); - final Pair pair = hostEditor != null ? chooseBetweenHostAndInjected(hostFile, hostEditor, new PairProcessor() { - @Override - public boolean process(PsiFile psiFile, Editor editor) { - return availableFor(psiFile, editor, action); - } - }) : Pair.create(hostFile, null); + final Pair pair = hostEditor != null ? chooseBetweenHostAndInjected(hostFile, hostEditor, + (psiFile, editor) -> availableFor(psiFile, editor, action)) : Pair.create(hostFile, null); if (pair == null) return false; CommandProcessor.getInstance().executeCommand(project, () -> { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/ActionUsagePanel.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/ActionUsagePanel.java index 93fb332f475b..b800ce6b647a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/ActionUsagePanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/ActionUsagePanel.java @@ -79,17 +79,9 @@ public class ActionUsagePanel extends JPanel implements Disposable { public void reset(final String usageText, final FileType fileType) { reinitViews(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myEditor.isDisposed()) return; - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - configureByText(usageText, fileType); - } - }); - } + SwingUtilities.invokeLater(() -> { + if (myEditor.isDisposed()) return; + DocumentUtil.writeInRunUndoTransparentAction(() -> configureByText(usageText, fileType)); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java index 7de978eef4af..bd248a201556 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java @@ -109,12 +109,7 @@ public class IntentionDescriptionPanel { showUsages(myBeforePanel, myBeforeSeparator, myBeforeUsagePanels, actionMetaData.getExampleUsagesBefore()); showUsages(myAfterPanel, myAfterSeparator, myAfterUsagePanels, actionMetaData.getExampleUsagesAfter()); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPanel.revalidate(); - } - }); + SwingUtilities.invokeLater(() -> myPanel.revalidate()); } catch (IOException e) { @@ -138,11 +133,8 @@ public class IntentionDescriptionPanel { final ShowSettingsUtil util = ShowSettingsUtil.getInstance(); final PluginManagerConfigurable pluginConfigurable = new PluginManagerConfigurable(PluginManagerUISettings.getInstance()); final Project project = ProjectManager.getInstance().getDefaultProject(); - util.editConfigurable(project, pluginConfigurable, new Runnable(){ - @Override - public void run() { - pluginConfigurable.select(pluginDescriptor); - } + util.editConfigurable(project, pluginConfigurable, () -> { + pluginConfigurable.select(pluginDescriptor); }); } }); @@ -164,12 +156,7 @@ public class IntentionDescriptionPanel { URL afterURL = getClass().getClassLoader().getResource(getClass().getPackage().getName().replace('.','/') + "/" + AFTER_TEMPLATE); showUsages(myAfterPanel, myAfterSeparator, myAfterUsagePanels, new ResourceTextDescriptor[]{new ResourceTextDescriptor(afterURL)}); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPanel.revalidate(); - } - }); + SwingUtilities.invokeLater(() -> myPanel.revalidate()); } catch (IOException e) { LOG.error(e); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerImpl.java index fcb5c4843781..e135faaf0a27 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerImpl.java @@ -78,23 +78,20 @@ public class IntentionManagerImpl extends IntentionManager { } private void registerIntentionFromBean(@NotNull final IntentionActionBean extension) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - final String descriptionDirectoryName = extension.getDescriptionDirectoryName(); - final String[] categories = extension.getCategories(); - final IntentionAction instance = createIntentionActionWrapper(extension, categories); - if (categories == null) { + final Runnable runnable = () -> { + final String descriptionDirectoryName = extension.getDescriptionDirectoryName(); + final String[] categories = extension.getCategories(); + final IntentionAction instance = createIntentionActionWrapper(extension, categories); + if (categories == null) { + addAction(instance); + } + else { + if (descriptionDirectoryName != null) { addAction(instance); + mySettings.registerIntentionMetaData(instance, categories, descriptionDirectoryName, extension.getMetadataClassLoader()); } else { - if (descriptionDirectoryName != null) { - addAction(instance); - mySettings.registerIntentionMetaData(instance, categories, descriptionDirectoryName, extension.getMetadataClassLoader()); - } - else { - registerIntentionAndMetaData(instance, categories); - } + registerIntentionAndMetaData(instance, categories); } } }; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerSettings.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerSettings.java index fec1c2a09dfb..855824104000 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerSettings.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerSettings.java @@ -164,24 +164,21 @@ public class IntentionManagerSettings implements PersistentStateComponent words = registrar.getProcessedWordsWithoutStemming(descriptionText); - words.addAll(registrar.getProcessedWords(metaData.getFamily())); - for (String word : words) { - registrar.addOption(word, metaData.getFamily(), metaData.getFamily(), IntentionSettingsConfigurable.HELP_ID, IntentionSettingsConfigurable.DISPLAY_NAME); - } - } - catch (IOException e) { - LOG.error(e); + ourRegisterMetaDataAlarm.addRequest(() -> { + try { + SearchableOptionsRegistrar registrar = SearchableOptionsRegistrar.getInstance(); + if (registrar == null) return; + @NonNls String descriptionText = description.getText().toLowerCase(); + descriptionText = HTML_PATTERN.matcher(descriptionText).replaceAll(" "); + final Set words = registrar.getProcessedWordsWithoutStemming(descriptionText); + words.addAll(registrar.getProcessedWords(metaData.getFamily())); + for (String word : words) { + registrar.addOption(word, metaData.getFamily(), metaData.getFamily(), IntentionSettingsConfigurable.HELP_ID, IntentionSettingsConfigurable.DISPLAY_NAME); } } + catch (IOException e) { + LOG.error(e); + } }, 0); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java index bba8e743481c..5c8d702d3326 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java @@ -50,16 +50,13 @@ public class IntentionSettingsPanel implements MasterDetails { protected void selectionChanged(Object selected) { if (selected instanceof IntentionActionMetaData) { final IntentionActionMetaData actionMetaData = (IntentionActionMetaData)selected; - final Runnable runnable = new Runnable() { - @Override - public void run() { - intentionSelected(actionMetaData); - if (myDetailsComponent != null) { - String[] text = new String[actionMetaData.myCategory.length + 1]; - System.arraycopy(actionMetaData.myCategory, 0, text,0,actionMetaData.myCategory.length); - text[text.length - 1] = actionMetaData.getFamily(); - myDetailsComponent.setText(text); - } + final Runnable runnable = () -> { + intentionSelected(actionMetaData); + if (myDetailsComponent != null) { + String[] text = new String[actionMetaData.myCategory.length + 1]; + System.arraycopy(actionMetaData.myCategory, 0, text,0,actionMetaData.myCategory.length); + text[text.length - 1] = actionMetaData.getFamily(); + myDetailsComponent.setText(text); } }; myResetAlarm.cancelAllRequests(); @@ -113,12 +110,7 @@ public class IntentionSettingsPanel implements MasterDetails { public void reset() { myIntentionSettingsTree.reset(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myIntentionDescriptionPanel.init(myPanel.getWidth() / 2); - } - }); + SwingUtilities.invokeLater(() -> myIntentionDescriptionPanel.init(myPanel.getWidth() / 2)); } @Override @@ -212,12 +204,9 @@ public class IntentionSettingsPanel implements MasterDetails { } public Runnable showOption(final String option) { - return new Runnable() { - @Override - public void run() { - myIntentionSettingsTree.filter(myIntentionSettingsTree.filterModel(option, true)); - myIntentionSettingsTree.setFilter(option); - } + return () -> { + myIntentionSettingsTree.filter(myIntentionSettingsTree.filterModel(option, true)); + myIntentionSettingsTree.setFilter(option); }; } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java index cec29cf56516..6e66b7861528 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java @@ -173,17 +173,14 @@ public abstract class IntentionSettingsTree { private static List sort(final List intentionsToShow) { List copy = new ArrayList(intentionsToShow); - Collections.sort(copy, new Comparator() { - @Override - public int compare(final IntentionActionMetaData data1, final IntentionActionMetaData data2) { - String[] category1 = data1.myCategory; - String[] category2 = data2.myCategory; - int result = ArrayUtil.lexicographicCompare(category1, category2); - if (result!= 0) { - return result; - } - return data1.getFamily().compareTo(data2.getFamily()); + Collections.sort(copy, (data1, data2) -> { + String[] category1 = data1.myCategory; + String[] category2 = data2.myCategory; + int result = ArrayUtil.lexicographicCompare(category1, category2); + if (result!= 0) { + return result; } + return data1.getFamily().compareTo(data2.getFamily()); }); return copy; } @@ -372,12 +369,9 @@ public abstract class IntentionSettingsTree { ((DefaultTreeModel)myTree.getModel()).reload(); TreeUtil.restoreExpandedPaths(myTree, expandedPaths); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myTree.setSelectionRow(0); - myTree.requestFocus(); - } + SwingUtilities.invokeLater(() -> { + myTree.setSelectionRow(0); + myTree.requestFocus(); }); TreeUtil.expandAll(myTree); if (filter == null || filter.length() == 0) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/ComparingClassifier.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/ComparingClassifier.java index 96faa2fd8c31..70586d31ccf9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/ComparingClassifier.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/ComparingClassifier.java @@ -79,11 +79,8 @@ public abstract class ComparingClassifier extends Classifier { @NotNull @Override public List> getSortingWeights(@NotNull Iterable items, @NotNull final ProcessingContext context) { - return ContainerUtil.map(items, new Function>() { - @Override - public Pair fun(T t) { - return new Pair(t, getWeight(t, context)); - } + return ContainerUtil.map(items, t -> { + return new Pair(t, getWeight(t, context)); }); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/Advertiser.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/Advertiser.java index 456b4d06d1fd..27f38708c29e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/Advertiser.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/Advertiser.java @@ -149,11 +149,6 @@ public class Advertiser { } public List getAdvertisements() { - return ContainerUtil.map(myTexts, new Function, String>() { - @Override - public String fun(Pair pair) { - return pair.first; - } - }); + return ContainerUtil.map(myTexts, pair -> pair.first); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/BackspaceHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/BackspaceHandler.java index 470683227397..a50d6b35185a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/BackspaceHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/BackspaceHandler.java @@ -54,12 +54,7 @@ public class BackspaceHandler extends EditorActionHandler { final int hideOffset, final Caret caret) { final Editor editor = lookup.getEditor(); - if (!lookup.performGuardedChange(new Runnable() { - @Override - public void run() { - handler.execute(editor, caret, dataContext); - } - })) { + if (!lookup.performGuardedChange(() -> handler.execute(editor, caret, dataContext))) { return; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java index a267a66191cd..2e830e523320 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java @@ -194,12 +194,7 @@ public abstract class LookupActionHandler extends EditorActionHandler { return; } - if (!lookup.performGuardedChange(new Runnable() { - @Override - public void run() { - lookup.getEditor().getSelectionModel().removeSelection(); - } - })) { + if (!lookup.performGuardedChange(() -> lookup.getEditor().getSelectionModel().removeSelection())) { return; } @@ -229,25 +224,22 @@ public abstract class LookupActionHandler extends EditorActionHandler { return; } - if (!lookup.performGuardedChange(new Runnable() { - @Override - public void run() { - CaretAction action = new CaretAction() { - @Override - public void perform(Caret caret) { - caret.removeSelection(); - int caretOffset = caret.getOffset(); - if (caretOffset < seq.length()) { - caret.moveToOffset(caretOffset + 1); - } + if (!lookup.performGuardedChange(() -> { + CaretAction action = new CaretAction() { + @Override + public void perform(Caret caret1) { + caret1.removeSelection(); + int caretOffset = caret1.getOffset(); + if (caretOffset < seq.length()) { + caret1.moveToOffset(caretOffset + 1); } - }; - if (caret == null) { - editor.getCaretModel().runForEachCaret(action); - } - else { - action.perform(caret); } + }; + if (caret == null) { + editor.getCaretModel().runForEachCaret(action); + } + else { + action.perform(caret); } })) { return; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionsStep.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionsStep.java index ea435b1e2cf3..b4186ffbaeae 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionsStep.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionsStep.java @@ -64,12 +64,7 @@ public class LookupActionsStep extends BaseListPopupStep im myLookup.refreshUi(false, true); } else if (result instanceof LookupElementAction.Result.ChooseItem) { myLookup.setCurrentItem(((LookupElementAction.Result.ChooseItem)result).item); - CommandProcessor.getInstance().executeCommand(myLookup.getProject(), new Runnable() { - @Override - public void run() { - myLookup.finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR); - } - }, null, null); + CommandProcessor.getInstance().executeCommand(myLookup.getProject(), () -> myLookup.finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR), null, null); } return FINAL_CHOICE; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java index f312eae9003c..0cfa3083961e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java @@ -85,12 +85,8 @@ public class LookupImpl extends LightweightHint implements LookupEx, Disposable protected void processKeyEvent(@NotNull final KeyEvent e) { final char keyChar = e.getKeyChar(); if (keyChar == KeyEvent.VK_ENTER || keyChar == KeyEvent.VK_TAB) { - IdeFocusManager.getInstance(myProject).requestFocus(myEditor.getContentComponent(), true).doWhenDone(new Runnable() { - @Override - public void run() { - IdeEventQueue.getInstance().getKeyEventDispatcher().dispatchKeyEvent(e); - } - }); + IdeFocusManager.getInstance(myProject).requestFocus(myEditor.getContentComponent(), true).doWhenDone( + () -> IdeEventQueue.getInstance().getKeyEventDispatcher().dispatchKeyEvent(e)); return; } @@ -492,15 +488,13 @@ public class LookupImpl extends LightweightHint implements LookupEx, Disposable } myFinishing = true; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myEditor.getDocument().startGuardedBlockChecking(); - try { - insertLookupString(item, getPrefixLength(item)); - } - finally { - myEditor.getDocument().stopGuardedBlockChecking(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myEditor.getDocument().startGuardedBlockChecking(); + try { + insertLookupString(item, getPrefixLength(item)); + } + finally { + myEditor.getDocument().stopGuardedBlockChecking(); } }); @@ -749,12 +743,7 @@ public class LookupImpl extends LightweightHint implements LookupEx, Disposable markSelectionTouched(); if (clickCount == 2){ - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - finishLookup(NORMAL_SELECT_CHAR); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myProject, () -> finishLookup(NORMAL_SELECT_CHAR), "", null); } return true; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java index 11021728ee10..b5de05cb477f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java @@ -136,20 +136,17 @@ public class LookupManagerImpl extends LookupManager { final LookupImpl lookup = new LookupImpl(myProject, editor, arranger); final Alarm alarm = new Alarm(); - final Runnable request = new Runnable() { - @Override - public void run() { - if (myActiveLookup != lookup) return; - - LookupElement currentItem = lookup.getCurrentItem(); - if (currentItem != null && currentItem.isValid()) { - final CompletionProcess completion = CompletionService.getCompletionService().getCurrentCompletion(); - if (completion != null && !completion.isAutopopupCompletion()) { - try { - DocumentationManager.getInstance(myProject).showJavaDocInfo(editor, psiFile, false); - } - catch (IndexNotReadyException ignored) { - } + final Runnable request = () -> { + if (myActiveLookup != lookup) return; + + LookupElement currentItem = lookup.getCurrentItem(); + if (currentItem != null && currentItem.isValid()) { + final CompletionProcess completion = CompletionService.getCompletionService().getCurrentCompletion(); + if (completion != null && !completion.isAutopopupCompletion()) { + try { + DocumentationManager.getInstance(myProject).showJavaDocInfo(editor, psiFile, false); + } + catch (IndexNotReadyException ignored) { } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java index ea73cb30fee0..6588f9b1e69f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java @@ -114,12 +114,8 @@ public class LookupTypedHandler extends TypedActionHandlerBase { Document document = editor.getDocument(); long modificationStamp = document.getModificationStamp(); - if (!lookup.performGuardedChange(new Runnable() { - @Override - public void run() { - EditorModificationUtil.typeInStringAtCaretHonorMultipleCarets(originalEditor, String.valueOf(charTyped), true); - } - })) { + if (!lookup.performGuardedChange( + () -> EditorModificationUtil.typeInStringAtCaretHonorMultipleCarets(originalEditor, String.valueOf(charTyped), true))) { return true; } lookup.appendPrefix(charTyped); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java index 1a391dc99225..59eceb7d2b9c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java @@ -140,12 +140,7 @@ class LookupUi { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (myLookup.myUpdating || myLookup.isLookupDisposed()) return; - alarm.addRequest(new Runnable() { - @Override - public void run() { - myLookup.refreshUi(false, false); - } - }, 300, myModalityState); + alarm.addRequest(() -> myLookup.refreshUi(false, false), 300, myModalityState); } }); } @@ -173,17 +168,14 @@ class LookupUi { final Collection actions = myLookup.getActionsFor(item); if (!actions.isEmpty()) { - myHintAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!ShowHideIntentionIconLookupAction.shouldShowLookupHint() || - ((CompletionExtender)myList.getExpandableItemsHandler()).isShowing()) { - return; - } - myElementHint = new LookupHint(); - myLayeredPane.add(myElementHint, 20, 0); - myLayeredPane.layoutHint(); + myHintAlarm.addRequest(() -> { + if (!ShowHideIntentionIconLookupAction.shouldShowLookupHint() || + ((CompletionExtender)myList.getExpandableItemsHandler()).isShowing()) { + return; } + myElementHint = new LookupHint(); + myLayeredPane.add(myElementHint, 20, 0); + myLayeredPane.layoutHint(); }, 500, myModalityState); } } @@ -196,12 +188,9 @@ class LookupUi { public void focusGained(FocusEvent e) { final ActionCallback done = IdeFocusManager.getInstance(myProject).requestFocus(myLookup.getTopLevelEditor().getContentComponent(), true); IdeFocusManager.getInstance(myProject).typeAheadUntil(done); - new Alarm(myLookup).addRequest(new Runnable() { - @Override - public void run() { - if (!done.isDone()) { - done.setDone(); - } + new Alarm(myLookup).addRequest(() -> { + if (!done.isDone()) { + done.setDone(); } }, 300, myModalityState); } @@ -209,12 +198,7 @@ class LookupUi { } void setCalculating(final boolean calculating) { - Runnable setVisible = new Runnable() { - @Override - public void run() { - myIconPanel.setVisible(myLookup.isCalculating()); - } - }; + Runnable setVisible = () -> myIconPanel.setVisible(myLookup.isCalculating()); if (myLookup.isCalculating()) { new Alarm(myLookup).addRequest(setVisible, 100, myModalityState); } else { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java index 9070cd44d619..6e9e14874319 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java @@ -92,11 +92,8 @@ public abstract class BackgroundUpdaterTask extends Task.Backgroundable { public boolean updateComponent(final PsiElement element, @Nullable final Comparator comparator) { final UsageView view = myUsageView.get(); if (view != null && !((UsageViewImpl)view).isDisposed()) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - view.appendUsage(new UsageInfo2UsageAdapter(new UsageInfo(element))); - } + ApplicationManager.getApplication().runReadAction(() -> { + view.appendUsage(new UsageInfo2UsageAdapter(new UsageInfo(element))); }); return true; } @@ -110,23 +107,20 @@ public abstract class BackgroundUpdaterTask extends Task.Backgroundable { myData.add(element); } - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myAlarm.cancelAllRequests(); - if (myCanceled) return; - if (myPopup.isDisposed()) return; - ArrayList data = new ArrayList(); - synchronized (lock) { - if (comparator != null) { - Collections.sort(myData, comparator); - } - data.addAll(myData); + myAlarm.addRequest(() -> { + myAlarm.cancelAllRequests(); + if (myCanceled) return; + if (myPopup.isDisposed()) return; + ArrayList data = new ArrayList(); + synchronized (lock) { + if (comparator != null) { + Collections.sort(myData, comparator); } - replaceModel(data); - myPopup.setCaption(getCaption(getCurrentSize())); - myPopup.pack(true, true); + data.addAll(myData); } + replaceModel(data); + myPopup.setCaption(getCaption(getCurrentSize())); + myPopup.pack(true, true); }, 200, ModalityState.stateForComponent(content)); return true; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java index 7435ebebd87d..481f6e695c79 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java @@ -564,12 +564,9 @@ public class CtrlMouseHandler extends AbstractProjectComponent { @NotNull protected PsiElement[] searchDefinitions(final PsiElement element, Editor editor) { final List found = new ArrayList(2); - DefinitionsScopedSearch.search(element, getSearchScope(element, editor)).forEach(new Processor() { - @Override - public boolean process(final PsiElement psiElement) { - found.add(psiElement); - return found.size() != 2; - } + DefinitionsScopedSearch.search(element, getSearchScope(element, editor)).forEach(psiElement -> { + found.add(psiElement); + return found.size() != 2; }); return PsiUtilCore.toPsiElementArray(found); } @@ -663,103 +660,94 @@ public class CtrlMouseHandler extends AbstractProjectComponent { @NotNull final LightweightHint hint) { myDocAlarm.cancelAllRequests(); - myDocAlarm.addRequest(new Runnable() { - @Override - public void run() { - final Ref fullTextRef = new Ref(); - final Ref qualifiedNameRef = new Ref(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (anchorElement.isValid() && originalElement.isValid()) { - try { - fullTextRef.set(provider.generateDoc(anchorElement, originalElement)); - } - catch (IndexNotReadyException e) { - fullTextRef.set("Documentation is not available while indexing is in progress"); - } - if (anchorElement instanceof PsiQualifiedNamedElement) { - qualifiedNameRef.set(((PsiQualifiedNamedElement)anchorElement).getQualifiedName()); - } - } + myDocAlarm.addRequest(() -> { + final Ref fullTextRef = new Ref(); + final Ref qualifiedNameRef = new Ref(); + ApplicationManager.getApplication().runReadAction(() -> { + if (anchorElement.isValid() && originalElement.isValid()) { + try { + fullTextRef.set(provider.generateDoc(anchorElement, originalElement)); } - }); - String fullText = fullTextRef.get(); - if (fullText == null) { + catch (IndexNotReadyException e) { + fullTextRef.set("Documentation is not available while indexing is in progress"); + } + if (anchorElement instanceof PsiQualifiedNamedElement) { + qualifiedNameRef.set(((PsiQualifiedNamedElement)anchorElement).getQualifiedName()); + } + } + }); + String fullText = fullTextRef.get(); + if (fullText == null) { + return; + } + final String updatedText = DocPreviewUtil.buildPreview(header, qualifiedNameRef.get(), fullText); + final String newHtml = HintUtil.prepareHintText(updatedText, HintUtil.getInformationHint()); + UIUtil.invokeLaterIfNeeded(() -> { + + // There is a possible case that quick doc control width is changed, e.g. it contained text + // like 'public final class String implements java.io.Serializable, java.lang.Comparable' and + // new text replaces fully-qualified class names by hyperlinks with short name. + // That's why we might need to update the control size. We assume that the hint component is located at the + // layered pane, so, the algorithm is to find an ancestor layered pane and apply new size for the target component. + + JComponent component = hint.getComponent(); + Dimension oldSize = component.getPreferredSize(); + newTextConsumer.consume(newHtml); + + final int widthIncrease; + if (component instanceof QuickDocInfoPane) { + int buttonWidth = ((QuickDocInfoPane)component).getButtonWidth(); + widthIncrease = calculateWidthIncrease(buttonWidth, updatedText); + } + else { + widthIncrease = 0; + } + + if (oldSize == null) { return; } - final String updatedText = DocPreviewUtil.buildPreview(header, qualifiedNameRef.get(), fullText); - final String newHtml = HintUtil.prepareHintText(updatedText, HintUtil.getInformationHint()); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - // There is a possible case that quick doc control width is changed, e.g. it contained text - // like 'public final class String implements java.io.Serializable, java.lang.Comparable' and - // new text replaces fully-qualified class names by hyperlinks with short name. - // That's why we might need to update the control size. We assume that the hint component is located at the - // layered pane, so, the algorithm is to find an ancestor layered pane and apply new size for the target component. + Dimension newSize = component.getPreferredSize(); + if (newSize.width + widthIncrease == oldSize.width) { + return; + } + component.setPreferredSize(new Dimension(newSize.width + widthIncrease, newSize.height)); - JComponent component = hint.getComponent(); - Dimension oldSize = component.getPreferredSize(); - newTextConsumer.consume(newHtml); + // We're assuming here that there are two possible hint representation modes: popup and layered pane. + if (hint.isRealPopup()) { - final int widthIncrease; - if (component instanceof QuickDocInfoPane) { - int buttonWidth = ((QuickDocInfoPane)component).getButtonWidth(); - widthIncrease = calculateWidthIncrease(buttonWidth, updatedText); - } - else { - widthIncrease = 0; - } - - if (oldSize == null) { - return; - } - - Dimension newSize = component.getPreferredSize(); - if (newSize.width + widthIncrease == oldSize.width) { - return; - } - component.setPreferredSize(new Dimension(newSize.width + widthIncrease, newSize.height)); - - // We're assuming here that there are two possible hint representation modes: popup and layered pane. - if (hint.isRealPopup()) { - - TooltipProvider tooltipProvider = myTooltipProvider; - if (tooltipProvider != null) { - // There is a possible case that 'raw' control was rather wide but the 'rich' one is narrower. That's why we try to - // re-show the hint here. Benefits: there is a possible case that we'll be able to show nice layered pane-based balloon; - // the popup will be re-positioned according to the new width. - hint.hide(); - tooltipProvider.showHint(new LightweightHint(component)); - } - else { - component.setPreferredSize(new Dimension(newSize.width + widthIncrease, oldSize.height)); - hint.pack(); - } - return; - } - - Container topLevelLayeredPaneChild = null; - boolean adjustBounds = false; - for (Container current = component.getParent(); current != null; current = current.getParent()) { - if (current instanceof JLayeredPane) { - adjustBounds = true; - break; - } - else { - topLevelLayeredPaneChild = current; - } - } - - if (adjustBounds && topLevelLayeredPaneChild != null) { - Rectangle bounds = topLevelLayeredPaneChild.getBounds(); - topLevelLayeredPaneChild.setBounds(bounds.x, bounds.y, bounds.width + newSize.width + widthIncrease - oldSize.width, bounds.height); - } + TooltipProvider tooltipProvider = myTooltipProvider; + if (tooltipProvider != null) { + // There is a possible case that 'raw' control was rather wide but the 'rich' one is narrower. That's why we try to + // re-show the hint here. Benefits: there is a possible case that we'll be able to show nice layered pane-based balloon; + // the popup will be re-positioned according to the new width. + hint.hide(); + tooltipProvider.showHint(new LightweightHint(component)); } - }); - } + else { + component.setPreferredSize(new Dimension(newSize.width + widthIncrease, oldSize.height)); + hint.pack(); + } + return; + } + + Container topLevelLayeredPaneChild = null; + boolean adjustBounds = false; + for (Container current = component.getParent(); current != null; current = current.getParent()) { + if (current instanceof JLayeredPane) { + adjustBounds = true; + break; + } + else { + topLevelLayeredPaneChild = current; + } + } + + if (adjustBounds && topLevelLayeredPaneChild != null) { + Rectangle bounds = topLevelLayeredPaneChild.getBounds(); + topLevelLayeredPaneChild.setBounds(bounds.x, bounds.y, bounds.width + newSize.width + widthIncrease - oldSize.width, bounds.height); + } + }); }, 0); } @@ -863,12 +851,9 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } LOG.debug("Obtained info about element under cursor"); - return new ReadTask.Continuation(new Runnable() { - @Override - public void run() { - if (myDisposed || myEditor.isDisposed() || !myEditor.getComponent().isShowing()) return; - showHint(info, docInfo); - } + return new ReadTask.Continuation(() -> { + if (myDisposed || myEditor.isDisposed() || !myEditor.getComponent().isShowing()) return; + showHint(info, docInfo); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/GotoTargetHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/GotoTargetHandler.java index ad16abe2b1b4..393f56c95d06 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/GotoTargetHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/GotoTargetHandler.java @@ -147,40 +147,34 @@ public abstract class GotoTargetHandler implements CodeInsightActionHandler { } }); - final Runnable runnable = new Runnable() { - @Override - public void run() { - int[] ids = list.getSelectedIndices(); - if (ids == null || ids.length == 0) return; - Object[] selectedElements = list.getSelectedValues(); - for (Object element : selectedElements) { - if (element instanceof AdditionalAction) { - ((AdditionalAction)element).execute(); + final Runnable runnable = () -> { + int[] ids = list.getSelectedIndices(); + if (ids == null || ids.length == 0) return; + Object[] selectedElements = list.getSelectedValues(); + for (Object element : selectedElements) { + if (element instanceof AdditionalAction) { + ((AdditionalAction)element).execute(); + } + else { + Navigatable nav = element instanceof Navigatable ? (Navigatable)element : EditSourceUtil.getDescriptor((PsiElement)element); + try { + if (nav != null && nav.canNavigate()) { + navigateToElement(nav); + } } - else { - Navigatable nav = element instanceof Navigatable ? (Navigatable)element : EditSourceUtil.getDescriptor((PsiElement)element); - try { - if (nav != null && nav.canNavigate()) { - navigateToElement(nav); - } - } - catch (IndexNotReadyException e) { - DumbService.getInstance(project).showDumbModeNotification("Navigation is not available while indexing"); - } + catch (IndexNotReadyException e) { + DumbService.getInstance(project).showDumbModeNotification("Navigation is not available while indexing"); } } } }; final PopupChooserBuilder builder = new PopupChooserBuilder(list); - builder.setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - if (o instanceof AdditionalAction) { - return ((AdditionalAction)o).getText(); - } - return getRenderer(o, gotoData.renderers, gotoData).getElementText((PsiElement)o); + builder.setFilteringEnabled(o -> { + if (o instanceof AdditionalAction) { + return ((AdditionalAction)o).getText(); } + return getRenderer(o, gotoData.renderers, gotoData).getElementText((PsiElement)o); }); final Ref usageView = new Ref(); @@ -195,13 +189,10 @@ public abstract class GotoTargetHandler implements CodeInsightActionHandler { return true; } }). - setCouldPin(new Processor() { - @Override - public boolean process(JBPopup popup) { - usageView.set(FindUtil.showInUsageView(gotoData.source, gotoData.targets, getFindUsagesTitle(gotoData.source, name, gotoData.targets.length), project)); - popup.cancel(); - return false; - } + setCouldPin(popup1 -> { + usageView.set(FindUtil.showInUsageView(gotoData.source, gotoData.targets, getFindUsagesTitle(gotoData.source, name, gotoData.targets.length), project)); + popup1.cancel(); + return false; }). setAdText(getAdText(gotoData.source, targets.length)). createPopup(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/ListBackgroundUpdaterTask.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/ListBackgroundUpdaterTask.java index 013da38d6a71..d9115f7a8691 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/ListBackgroundUpdaterTask.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/ListBackgroundUpdaterTask.java @@ -35,12 +35,7 @@ public abstract class ListBackgroundUpdaterTask extends BackgroundUpdaterTask myComponent.setPaintBusy(paintBusy); //ensure start/end order SwingUtilities.invokeLater(runnable); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/NavigationUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/NavigationUtil.java index 3f1328328ed7..8bd7f9e68fad 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/NavigationUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/NavigationUtil.java @@ -122,15 +122,12 @@ public final class NavigationUtil { list.setSelectedValue(selection, true); } - final Runnable runnable = new Runnable() { - @Override - public void run() { - int[] ids = list.getSelectedIndices(); - if (ids == null || ids.length == 0) return; - for (Object element : list.getSelectedValues()) { - if (element != null) { - processor.execute((T)element); - } + final Runnable runnable = () -> { + int[] ids = list.getSelectedIndices(); + if (ids == null || ids.length == 0) return; + for (Object element : list.getSelectedValues()) { + if (element != null) { + processor.execute((T)element); } } }; @@ -229,19 +226,16 @@ public final class NavigationUtil { MarkupModel model = DocumentMarkupModel.forDocument(editor.getDocument(), editor.getProject(), false); if (model != null) { if (!((MarkupModelEx)model).processRangeHighlightersOverlappingWith(range.getStartOffset(), range.getEndOffset(), - new Processor() { - @Override - public boolean process(RangeHighlighterEx highlighter) { - if (highlighter.isValid() && highlighter.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) { - TextAttributes textAttributes = highlighter.getTextAttributes(); - if (textAttributes != null) { - Color color = textAttributes.getBackgroundColor(); - return !(color != null && color.getBlue() > 128 && color.getRed() < 128 && color.getGreen() < 128); - } - } - return true; - } - })) { + highlighter -> { + if (highlighter.isValid() && highlighter.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) { + TextAttributes textAttributes = highlighter.getTextAttributes(); + if (textAttributes != null) { + Color color = textAttributes.getBackgroundColor(); + return !(color != null && color.getBlue() > 128 && color.getRed() < 128 && color.getGreen() < 128); + } + } + return true; + })) { TextAttributes clone = attributes.clone(); clone.setForegroundColor(Color.orange); clone.setEffectColor(Color.orange); @@ -276,18 +270,15 @@ public final class NavigationUtil { itemsMap.put(item.getElement(), item); } - return getPsiElementPopup(elements, itemsMap, title, showContainingModules, new Processor() { - @Override - public boolean process(Object element) { - if (element instanceof PsiElement) { - //noinspection SuspiciousMethodCalls - itemsMap.get(element).navigate(); - } - else { - ((GotoRelatedItem)element).navigate(); - } - return true; + return getPsiElementPopup(elements, itemsMap, title, showContainingModules, element -> { + if (element instanceof PsiElement) { + //noinspection SuspiciousMethodCalls + itemsMap.get(element).navigate(); } + else { + ((GotoRelatedItem)element).navigate(); + } + return true; } ); } @@ -466,12 +457,7 @@ public final class NavigationUtil { public void actionPerformed(ActionEvent e) { for (final Object item : listPopup.getListStep().getValues()) { if (getMnemonic(item, itemsMap) == mnemonic) { - listPopup.setFinalRunnable(new Runnable() { - @Override - public void run() { - processor.process(item); - } - }); + listPopup.setFinalRunnable(() -> processor.process(item)); listPopup.closeOk(null); } } @@ -493,13 +479,10 @@ public final class NavigationUtil { } } GotoRelatedItem[] result = items.toArray(new GotoRelatedItem[items.size()]); - Arrays.sort(result, new Comparator() { - @Override - public int compare(GotoRelatedItem i1, GotoRelatedItem i2) { - String o1 = i1.getGroup(); - String o2 = i2.getGroup(); - return StringUtil.isEmpty(o1) ? 1 : StringUtil.isEmpty(o2) ? -1 : o1.compareTo(o2); - } + Arrays.sort(result, (i1, i2) -> { + String o1 = i1.getGroup(); + String o2 = i2.getGroup(); + return StringUtil.isEmpty(o1) ? 1 : StringUtil.isEmpty(o2) ? -1 : o1.compareTo(o2); }); return Arrays.asList(result); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoSuperAction.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoSuperAction.java index fd9db43d8ed1..4c705d45b2fd 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoSuperAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoSuperAction.java @@ -51,12 +51,7 @@ public class GotoSuperAction extends PresentableActionHandlerBasedAction impleme final CodeInsightActionHandler codeInsightActionHandler = CodeInsightActions.GOTO_SUPER.forLanguage(language); if (codeInsightActionHandler != null) { - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - codeInsightActionHandler.invoke(project, editor, file); - } - }); + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> codeInsightActionHandler.invoke(project, editor, file)); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/LiveTemplateBuilder.java b/platform/lang-impl/src/com/intellij/codeInsight/template/LiveTemplateBuilder.java index 9333eeafc232..473c4918bbc6 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/LiveTemplateBuilder.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/LiveTemplateBuilder.java @@ -133,17 +133,14 @@ public class LiveTemplateBuilder { } List variableOccurrences = getListWithLimit(myVariableOccurrences); - Collections.sort(variableOccurrences, new Comparator() { - @Override - public int compare(@NotNull VarOccurence o1, @NotNull VarOccurence o2) { - if (o1.myOffset < o2.myOffset) { - return -1; - } - if (o1.myOffset > o2.myOffset) { - return 1; - } - return 0; + Collections.sort(variableOccurrences, (o1, o2) -> { + if (o1.myOffset < o2.myOffset) { + return -1; } + if (o1.myOffset > o2.myOffset) { + return 1; + } + return 0; }); int last = 0; for (VarOccurence occurence : variableOccurrences) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java index ecebb1926ee9..d8807773b2ef 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java @@ -212,14 +212,11 @@ public class TemplateBuilderImpl implements TemplateBuilder { if (start > offset) { LOG.error("file: " + myFile + " container: " + myContainerElement + - " markers: " + StringUtil.join(myElements, new Function() { - @Override - public String fun(RangeMarker rangeMarker) { - final String docString = - myDocument.getText(new TextRange(rangeMarker.getStartOffset(), rangeMarker.getEndOffset())); - return "[[" + docString + "]" + rangeMarker.getStartOffset() + ", " + rangeMarker.getEndOffset() + "]"; - } - }, ", ")); + " markers: " + StringUtil.join(myElements, rangeMarker -> { + final String docString = + myDocument.getText(new TextRange(rangeMarker.getStartOffset(), rangeMarker.getEndOffset())); + return "[[" + docString + "]" + rangeMarker.getStartOffset() + ", " + rangeMarker.getEndOffset() + "]"; + }, ", ")); } template.addTextSegment(text.substring(start, offset)); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java b/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java index 0feed37aab89..542609dc4fcf 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java @@ -145,11 +145,8 @@ public class SaveAsTemplateAction extends AnAction { } final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable(); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - configurable.getTemplateListPanel().addTemplate(template); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + configurable.getTemplateListPanel().addTemplate(template); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/EditVariableDialog.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/EditVariableDialog.java index e33d8ea5b5cc..c386813135d4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/EditVariableDialog.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/EditVariableDialog.java @@ -175,19 +175,13 @@ class EditVariableDialog extends DialogWrapper { }*/ private void updateTemplateTextByVarNameChange(final Variable oldVar, final Variable newVar) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(null, new Runnable() { - @Override - public void run() { - Document document = myEditor.getDocument(); - String templateText = document.getText(); - templateText = templateText.replaceAll("\\$" + oldVar.getName() + "\\$", "\\$" + newVar.getName() + "\\$"); - document.replaceString(0, document.getTextLength(), templateText); - } - }, null, null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(null, () -> { + Document document = myEditor.getDocument(); + String templateText = document.getText(); + templateText = templateText.replaceAll("\\$" + oldVar.getName() + "\\$", "\\$" + newVar.getName() + "\\$"); + document.replaceString(0, document.getTextLength(), templateText); + }, null, null); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/InvokeTemplateAction.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/InvokeTemplateAction.java index 56f2f8e118d2..6567d8764006 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/InvokeTemplateAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/InvokeTemplateAction.java @@ -77,33 +77,29 @@ public class InvokeTemplateAction extends AnAction { ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(file); } - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - myEditor.getCaretModel().runForEachCaret(new CaretAction() { - public void perform(Caret caret) { - // adjust the selection so that it starts with a non-whitespace character (to make sure that the template is inserted - // at a meaningful position rather than at indent 0) - if (myEditor.getSelectionModel().hasSelection() && myTemplate.isToReformat()) { - int offset = myEditor.getSelectionModel().getSelectionStart(); - int selectionEnd = myEditor.getSelectionModel().getSelectionEnd(); - int lineEnd = document.getLineEndOffset(document.getLineNumber(offset)); - while (offset < lineEnd && offset < selectionEnd && - (document.getCharsSequence().charAt(offset) == ' ' || document.getCharsSequence().charAt(offset) == '\t')) { - offset++; - } - // avoid extra line break after $SELECTION$ in case when selection ends with a complete line - if (selectionEnd == document.getLineStartOffset(document.getLineNumber(selectionEnd))) { - selectionEnd--; - } - if (offset < lineEnd && offset < selectionEnd) { // found non-WS character in first line of selection - myEditor.getSelectionModel().setSelection(offset, selectionEnd); - } - } - String selectionString = myEditor.getSelectionModel().getSelectedText(); - TemplateManager.getInstance(myProject).startTemplate(myEditor, selectionString, myTemplate); + CommandProcessor.getInstance().executeCommand(myProject, () -> myEditor.getCaretModel().runForEachCaret(new CaretAction() { + public void perform(Caret caret) { + // adjust the selection so that it starts with a non-whitespace character (to make sure that the template is inserted + // at a meaningful position rather than at indent 0) + if (myEditor.getSelectionModel().hasSelection() && myTemplate.isToReformat()) { + int offset = myEditor.getSelectionModel().getSelectionStart(); + int selectionEnd = myEditor.getSelectionModel().getSelectionEnd(); + int lineEnd = document.getLineEndOffset(document.getLineNumber(offset)); + while (offset < lineEnd && offset < selectionEnd && + (document.getCharsSequence().charAt(offset) == ' ' || document.getCharsSequence().charAt(offset) == '\t')) { + offset++; } - }); + // avoid extra line break after $SELECTION$ in case when selection ends with a complete line + if (selectionEnd == document.getLineStartOffset(document.getLineNumber(selectionEnd))) { + selectionEnd--; + } + if (offset < lineEnd && offset < selectionEnd) { // found non-WS character in first line of selection + myEditor.getSelectionModel().setSelection(offset, selectionEnd); + } + } + String selectionString = myEditor.getSelectionModel().getSelectedText(); + TemplateManager.getInstance(myProject).startTemplate(myEditor, selectionString, myTemplate); } - }, "Wrap with template", "Wrap with template " + myTemplate.getKey()); + }), "Wrap with template", "Wrap with template " + myTemplate.getKey()); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java index 6c9a8a083615..594d4da1ff15 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java @@ -87,13 +87,10 @@ public class LiveTemplateCompletionContributor extends CompletionContributor { if (showAllTemplates()) { final AtomicBoolean templatesShown = new AtomicBoolean(false); final CompletionResultSet finalResult = result; - result.runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(CompletionResult completionResult) { - finalResult.passResult(completionResult); - if (completionResult.isStartMatch()) { - ensureTemplatesShown(templatesShown, templates, parameters, finalResult); - } + result.runRemainingContributors(parameters, completionResult -> { + finalResult.passResult(completionResult); + if (completionResult.isStartMatch()) { + ensureTemplatesShown(templatesShown, templates, parameters, finalResult); } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java index 6528f21c107d..1dae2d09525d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java @@ -41,19 +41,13 @@ public class LiveTemplateLookupActionProvider implements LookupActionProvider { @Override public Result performLookupAction() { final Project project = lookup.getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; - final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable(); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - configurable.getTemplateListPanel().editTemplate(template); - } - }); - } + final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable(); + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + configurable.getTemplateListPanel().editTemplate(template); + }); }); return Result.HIDE_LOOKUP; } @@ -63,12 +57,7 @@ public class LiveTemplateLookupActionProvider implements LookupActionProvider { consumer.consume(new LookupElementAction(AllIcons.Actions.Delete, String.format("Disable '%s' template", template.getKey())) { @Override public Result performLookupAction() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - templateFromSettings.setDeactivated(true); - } - }); + ApplicationManager.getApplication().invokeLater(() -> templateFromSettings.setDeactivated(true)); return Result.HIDE_LOOKUP; } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java index 3f1218c0ac70..54f9e2a57179 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java @@ -312,43 +312,40 @@ public class LiveTemplateSettingsEditor extends JPanel { panel.add(ctxLabel, BorderLayout.CENTER); panel.add(change, BorderLayout.EAST); - final Runnable updateLabel = new Runnable() { - @Override - public void run() { - myExpandByCombo.setEnabled(isExpandableFromEditor()); - updateHighlighter(); + final Runnable updateLabel = () -> { + myExpandByCombo.setEnabled(isExpandableFromEditor()); + updateHighlighter(); - StringBuilder sb = new StringBuilder(); - String oldPrefix = ""; - for (TemplateContextType type : getApplicableContexts()) { - final TemplateContextType base = type.getBaseContextType(); - String ownName = UIUtil.removeMnemonic(type.getPresentableName()); - String prefix = ""; - if (base != null && !(base instanceof EverywhereContextType)) { - prefix = UIUtil.removeMnemonic(base.getPresentableName()) + ": "; - ownName = StringUtil.decapitalize(ownName); - } - if (type instanceof EverywhereContextType) { - ownName = "Other"; - } - if (sb.length() > 0) { - sb.append(oldPrefix.equals(prefix) ? ", " : "; "); - } - if (!oldPrefix.equals(prefix)) { - sb.append(prefix); - oldPrefix = prefix; - } - sb.append(ownName); + StringBuilder sb = new StringBuilder(); + String oldPrefix = ""; + for (TemplateContextType type : getApplicableContexts()) { + final TemplateContextType base = type.getBaseContextType(); + String ownName = UIUtil.removeMnemonic(type.getPresentableName()); + String prefix = ""; + if (base != null && !(base instanceof EverywhereContextType)) { + prefix = UIUtil.removeMnemonic(base.getPresentableName()) + ": "; + ownName = StringUtil.decapitalize(ownName); } - final boolean noContexts = sb.length() == 0; - String contexts = (noContexts ? "No applicable contexts" + (allowNoContexts ? "" : " yet") : "Applicable in " + sb.toString()) + ". "; - ctxLabel.setText(StringUtil.first(contexts, 100, true)); - ctxLabel.setForeground(noContexts ? allowNoContexts ? JBColor.GRAY : JBColor.RED : UIUtil.getLabelForeground()); - change.setText(noContexts ? "Define" : "Change"); - - myTemplateOptionsPanel.removeAll(); - myTemplateOptionsPanel.add(createTemplateOptionsPanel()); + if (type instanceof EverywhereContextType) { + ownName = "Other"; + } + if (sb.length() > 0) { + sb.append(oldPrefix.equals(prefix) ? ", " : "; "); + } + if (!oldPrefix.equals(prefix)) { + sb.append(prefix); + oldPrefix = prefix; + } + sb.append(ownName); } + final boolean noContexts = sb.length() == 0; + String contexts = (noContexts ? "No applicable contexts" + (allowNoContexts ? "" : " yet") : "Applicable in " + sb.toString()) + ". "; + ctxLabel.setText(StringUtil.first(contexts, 100, true)); + ctxLabel.setForeground(noContexts ? allowNoContexts ? JBColor.GRAY : JBColor.RED : UIUtil.getLabelForeground()); + change.setText(noContexts ? "Define" : "Change"); + + myTemplateOptionsPanel.removeAll(); + myTemplateOptionsPanel.add(createTemplateOptionsPanel()); }; new ClickListener() { @@ -502,18 +499,10 @@ public class LiveTemplateSettingsEditor extends JPanel { } CommandProcessor.getInstance().executeCommand( - null, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Document document = myTemplateEditor.getDocument(); - document.replaceString(0, document.getTextLength(), myTemplate.getString()); - } - }); - } - }, + null, () -> ApplicationManager.getApplication().runWriteAction(() -> { + final Document document = myTemplateEditor.getDocument(); + document.replaceString(0, document.getTextLength(), myTemplate.getString()); + }), "", null ); @@ -545,11 +534,8 @@ public class LiveTemplateSettingsEditor extends JPanel { private ArrayList updateVariablesByTemplateText() { List oldVariables = getCurrentVariables(); - Set oldVariableNames = ContainerUtil.map2Set(oldVariables, new Function() { - @Override - public String fun(Variable variable) { - return variable.getName(); - } + Set oldVariableNames = ContainerUtil.map2Set(oldVariables, variable -> { + return variable.getName(); }); Map newVariableNames = parseVariables(); @@ -596,21 +582,12 @@ public class LiveTemplateSettingsEditor extends JPanel { //todo[peter,kirillk] without these invokeLaters this requestFocus conflicts with com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.MyDialog.MyWindowListener.windowOpened() IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true); final ModalityState modalityState = ModalityState.stateForComponent(myKeyField); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true); - } - }, modalityState); - } + ApplicationManager.getApplication().invokeLater(() -> { + ApplicationManager.getApplication().invokeLater(() -> { + ApplicationManager.getApplication().invokeLater(() -> { + IdeFocusManager.findInstanceByComponent(myKeyField).requestFocus(myKeyField, true); }, modalityState); - } + }, modalityState); }, modalityState); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplatesConfigurable.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplatesConfigurable.java index a0424580caf6..663e1477c29a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplatesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplatesConfigurable.java @@ -80,12 +80,7 @@ public class LiveTemplatesConfigurable extends BaseConfigurable implements Searc @Override @Nullable public Runnable enableSearch(final String option) { - return new Runnable() { - @Override - public void run() { - myPanel.selectNode(option); - } - }; + return () -> myPanel.selectNode(option); } public TemplateListPanel getTemplateListPanel() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateExpandShortcutPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateExpandShortcutPanel.java index b4553c24cfbc..659698ee11fe 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateExpandShortcutPanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateExpandShortcutPanel.java @@ -123,11 +123,7 @@ public class TemplateExpandShortcutPanel extends JPanel { final KeymapPanel keymapPanel = allSettings == null ? new KeymapPanel() : allSettings.find(KeymapPanel.class); if (keymapPanel == null) return; - Runnable selectAction = new Runnable() { - public void run() { - keymapPanel.selectAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_CUSTOM); - } - }; + Runnable selectAction = () -> keymapPanel.selectAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_CUSTOM); if (allSettings != null) { allSettings.select(keymapPanel).doWhenDone(selectAction); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java index f63c430742ff..096e9a8cc899 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java @@ -61,12 +61,9 @@ public class TemplateListPanel extends JPanel implements Disposable { private static final String TEMPLATE_SETTINGS = "TemplateSettings"; private static final TemplateImpl MOCK_TEMPLATE = new TemplateImpl("mockTemplate-xxx", "mockTemplateGroup-yyy"); public static final String ABBREVIATION = ""; - public static final Comparator TEMPLATE_COMPARATOR = new Comparator() { - @Override - public int compare(@NotNull final TemplateImpl o1, @NotNull final TemplateImpl o2) { - int compareKey = o1.getKey().compareToIgnoreCase(o2.getKey()); - return compareKey != 0 ? compareKey : o1.getGroupName().compareToIgnoreCase(o2.getGroupName()); - } + public static final Comparator TEMPLATE_COMPARATOR = (o1, o2) -> { + int compareKey = o1.getKey().compareToIgnoreCase(o2.getKey()); + return compareKey != 0 ? compareKey : o1.getGroupName().compareToIgnoreCase(o2.getGroupName()); }; static { @@ -125,12 +122,7 @@ public class TemplateListPanel extends JPanel implements Disposable { initTemplates(groups, templateSettings.getLastSelectedTemplateGroup(), templateSettings.getLastSelectedTemplateKey()); myExpandByDefaultPanel.setSelectedChar(templateSettings.getDefaultShortcutChar()); - UiNotifyConnector.doWhenFirstShown(this, new Runnable() { - @Override - public void run() { - updateTemplateDetails(false, false); - } - }); + UiNotifyConnector.doWhenFirstShown(this, () -> updateTemplateDetails(false, false)); myUpdateNeeded = true; } @@ -139,12 +131,7 @@ public class TemplateListPanel extends JPanel implements Disposable { private static List getSortedGroups(TemplateSettings templateSettings) { List groups = new ArrayList(templateSettings.getTemplateGroups()); - Collections.sort(groups, new Comparator() { - @Override - public int compare(@NotNull TemplateGroup o1, @NotNull TemplateGroup o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Collections.sort(groups, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); return groups; } @@ -231,15 +218,12 @@ public class TemplateListPanel extends JPanel implements Disposable { for (TemplateGroup group : groups) { result.addAll(group.getElements()); } - Collections.sort(result, new Comparator(){ - @Override - public int compare(@NotNull final TemplateImpl o1, @NotNull final TemplateImpl o2) { - final int groupsEqual = o1.getGroupName().compareToIgnoreCase(o2.getGroupName()); - if (groupsEqual != 0) { - return groupsEqual; - } - return o1.getKey().compareToIgnoreCase(o2.getKey()); + Collections.sort(result, (o1, o2) -> { + final int groupsEqual = o1.getGroupName().compareToIgnoreCase(o2.getGroupName()); + if (groupsEqual != 0) { + return groupsEqual; } + return o1.getKey().compareToIgnoreCase(o2.getKey()); }); return result; } @@ -290,14 +274,11 @@ public class TemplateListPanel extends JPanel implements Disposable { String shortcut, Map options, TemplateContext context) { - myCurrentTemplateEditor = new LiveTemplateSettingsEditor(template, shortcut, options, context, new Runnable() { - @Override - public void run() { - DefaultMutableTreeNode node = getNode(getSingleSelectedIndex()); - if (node != null) { - ((DefaultTreeModel)myTree.getModel()).nodeChanged(node); - TemplateSettings.getInstance().setLastSelectedTemplate(template.getGroupName(), template.getKey()); - } + myCurrentTemplateEditor = new LiveTemplateSettingsEditor(template, shortcut, options, context, () -> { + DefaultMutableTreeNode node = getNode(getSingleSelectedIndex()); + if (node != null) { + ((DefaultTreeModel)myTree.getModel()).nodeChanged(node); + TemplateSettings.getInstance().setLastSelectedTemplate(template.getGroupName(), template.getKey()); } }, TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName()) != null); for (Component component : myDetailsPanel.getComponents()) { @@ -503,12 +484,7 @@ public class TemplateListPanel extends JPanel implements Disposable { } if (myUpdateNeeded) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - updateTemplateDetails(false, false); - } - }, 100); + myAlarm.addRequest(() -> updateTemplateDetails(false, false), 100); } } }); @@ -524,16 +500,13 @@ public class TemplateListPanel extends JPanel implements Disposable { DnDSupport.createBuilder(myTree) - .setBeanProvider(new NullableFunction() { - @Override - public DnDDragStartBean fun(DnDActionInfo dnDActionInfo) { - Point point = dnDActionInfo.getPoint(); - if (myTree.getPathForLocation(point.x, point.y) == null) return null; + .setBeanProvider((NullableFunction)dnDActionInfo -> { + Point point = dnDActionInfo.getPoint(); + if (myTree.getPathForLocation(point.x, point.y) == null) return null; - Map templates = getSelectedTemplates(); + Map templates = getSelectedTemplates(); - return !templates.isEmpty() ? new DnDDragStartBean(templates) : null; - } + return !templates.isEmpty() ? new DnDDragStartBean(templates) : null; }). setDisposableParent(this) .setTargetChecker(new DnDTargetChecker() { @@ -554,13 +527,10 @@ public class TemplateListPanel extends JPanel implements Disposable { ObjectUtils.assertNotNull(getDropGroup(event)).getName()); } }) - .setImageProvider(new NullableFunction() { - @Override - public DnDImage fun(DnDActionInfo dnDActionInfo) { - Point point = dnDActionInfo.getPoint(); - TreePath path = myTree.getPathForLocation(point.x, point.y); - return path == null ? null : new DnDImage(DnDAwareTree.getDragImage(myTree, path, point).first); - } + .setImageProvider((NullableFunction)dnDActionInfo -> { + Point point = dnDActionInfo.getPoint(); + TreePath path = myTree.getPathForLocation(point.x, point.y); + return path == null ? null : new DnDImage(DnDAwareTree.getDragImage(myTree, path, point).first); }) .install(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java index 8a74213b7f3b..74cb53a869f5 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java @@ -174,22 +174,16 @@ public class TemplateManagerImpl extends TemplateManager implements Disposable { if (listener != null) { templateState.addTemplateStateListener(listener); } - Runnable r = new Runnable() { - @Override - public void run() { - if (selectionString != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - EditorModificationUtil.deleteSelectedText(editor); - } - }); - } - else { - editor.getSelectionModel().removeSelection(); - } - templateState.start((TemplateImpl)template, processor, predefinedVarValues); + Runnable r = () -> { + if (selectionString != null) { + ApplicationManager.getApplication().runWriteAction(() -> { + EditorModificationUtil.deleteSelectedText(editor); + }); } + else { + editor.getSelectionModel().removeSelection(); + } + templateState.start((TemplateImpl)template, processor, predefinedVarValues); }; if (inSeparateCommand) { CommandProcessor.getInstance().executeCommand(myProject, r, CodeInsightBundle.message("insert.code.template.command"), null); @@ -379,18 +373,15 @@ public class TemplateManagerImpl extends TemplateManager implements Disposable { return null; } - return new Runnable() { - @Override - public void run() { - if (template2argument.size() == 1) { - TemplateImpl template = template2argument.keySet().iterator().next(); - String argument = template2argument.get(template); - int templateStart = getTemplateStart(template, argument, caretOffset, text); - startTemplateWithPrefix(editor, template, templateStart, processor, argument); - } - else { - ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument); - } + return () -> { + if (template2argument.size() == 1) { + TemplateImpl template = template2argument.keySet().iterator().next(); + String argument = template2argument.get(template); + int templateStart = getTemplateStart(template, argument, caretOffset, text); + startTemplateWithPrefix(editor, template, templateStart, processor, argument); + } + else { + ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument); } }; } @@ -444,20 +435,17 @@ public class TemplateManagerImpl extends TemplateManager implements Disposable { final int caretOffset = editor.getCaretModel().getOffset(); final TemplateState templateState = initTemplateState(editor); CommandProcessor commandProcessor = CommandProcessor.getInstance(); - commandProcessor.executeCommand(myProject, new Runnable() { - @Override - public void run() { - editor.getDocument().deleteString(templateStart, caretOffset); - editor.getCaretModel().moveToOffset(templateStart); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - editor.getSelectionModel().removeSelection(); - Map predefinedVarValues = null; - if (argument != null) { - predefinedVarValues = new HashMap(); - predefinedVarValues.put(TemplateImpl.ARG, argument); - } - templateState.start(template, processor, predefinedVarValues); + commandProcessor.executeCommand(myProject, () -> { + editor.getDocument().deleteString(templateStart, caretOffset); + editor.getCaretModel().moveToOffset(templateStart); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + editor.getSelectionModel().removeSelection(); + Map predefinedVarValues = null; + if (argument != null) { + predefinedVarValues = new HashMap(); + predefinedVarValues.put(TemplateImpl.ARG, argument); } + templateState.start(template, processor, predefinedVarValues); }, CodeInsightBundle.message("insert.code.template.command"), null); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java index e3f443287e9e..cedae6ae90d0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java @@ -149,12 +149,7 @@ public class TemplateState implements Disposable { @Override public void beforeCommandFinished(CommandEvent event) { if (started && !isDisposed()) { - Runnable runnable = new Runnable() { - @Override - public void run() { - afterChangedUpdate(); - } - }; + Runnable runnable = () -> afterChangedUpdate(); final LookupImpl lookup = myEditor != null ? (LookupImpl)LookupManager.getActiveLookup(myEditor) : null; if (lookup != null) { lookup.performGuardedChange(runnable); @@ -410,41 +405,38 @@ public class TemplateState implements Disposable { } private void processAllExpressions(@NotNull final TemplateImpl template) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (!template.isInline()) myDocument.insertString(myTemplateRange.getStartOffset(), template.getTemplateText()); - for (int i = 0; i < template.getSegmentsCount(); i++) { - int segmentOffset = myTemplateRange.getStartOffset() + template.getSegmentOffset(i); - mySegments.addSegment(segmentOffset, segmentOffset); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (!template.isInline()) myDocument.insertString(myTemplateRange.getStartOffset(), template.getTemplateText()); + for (int i = 0; i < template.getSegmentsCount(); i++) { + int segmentOffset = myTemplateRange.getStartOffset() + template.getSegmentOffset(i); + mySegments.addSegment(segmentOffset, segmentOffset); + } - LOG.assertTrue(myTemplateRange.isValid(), getRangesDebugInfo()); - calcResults(false); - LOG.assertTrue(myTemplateRange.isValid(), getRangesDebugInfo()); - calcResults(false); //Fixed SCR #[vk500] : all variables should be recalced twice on start. - LOG.assertTrue(myTemplateRange.isValid(), getRangesDebugInfo()); - doReformat(null); + LOG.assertTrue(myTemplateRange.isValid(), getRangesDebugInfo()); + calcResults(false); + LOG.assertTrue(myTemplateRange.isValid(), getRangesDebugInfo()); + calcResults(false); //Fixed SCR #[vk500] : all variables should be recalced twice on start. + LOG.assertTrue(myTemplateRange.isValid(), getRangesDebugInfo()); + doReformat(null); - int nextVariableNumber = getNextVariableNumber(-1); + int nextVariableNumber = getNextVariableNumber(-1); - if (nextVariableNumber >= 0) { - fireWaitingForInput(); - } + if (nextVariableNumber >= 0) { + fireWaitingForInput(); + } - if (nextVariableNumber == -1) { + if (nextVariableNumber == -1) { + finishTemplateEditing(); + } + else { + setCurrentVariableNumber(nextVariableNumber); + initTabStopHighlighters(); + initListeners(); + focusCurrentExpression(); + currentVariableChanged(-1); + if (isMultiCaretMode()) { finishTemplateEditing(); } - else { - setCurrentVariableNumber(nextVariableNumber); - initTabStopHighlighters(); - initListeners(); - focusCurrentExpression(); - currentVariableChanged(-1); - if (isMultiCaretMode()) { - finishTemplateEditing(); - } - } } }); } @@ -462,19 +454,16 @@ public class TemplateState implements Disposable { rangeMarker.setGreedyToRight(true); } final RangeMarker finalRangeMarker = rangeMarker; - final Runnable action = new Runnable() { - @Override - public void run() { - IntArrayList indices = initEmptyVariables(); - mySegments.setSegmentsGreedy(false); - LOG.assertTrue(myTemplateRange.isValid(), - "template key: " + myTemplate.getKey() + "; " + - "template text" + myTemplate.getTemplateText() + "; " + - "variable number: " + getCurrentVariableNumber()); - reformat(finalRangeMarker); - mySegments.setSegmentsGreedy(true); - restoreEmptyVariables(indices); - } + final Runnable action = () -> { + IntArrayList indices = initEmptyVariables(); + mySegments.setSegmentsGreedy(false); + LOG.assertTrue(myTemplateRange.isValid(), + "template key: " + myTemplate.getKey() + "; " + + "template text" + myTemplate.getTemplateText() + "; " + + "variable number: " + getCurrentVariableNumber()); + reformat(finalRangeMarker); + mySegments.setSegmentsGreedy(true); + restoreEmptyVariables(indices); }; ApplicationManager.getApplication().runWriteAction(action); } @@ -491,19 +480,16 @@ public class TemplateState implements Disposable { } private void shortenReferences() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final PsiFile file = getPsiFile(); - if (file != null) { - IntArrayList indices = initEmptyVariables(); - mySegments.setSegmentsGreedy(false); - for (TemplateOptionalProcessor processor : Extensions.getExtensions(TemplateOptionalProcessor.EP_NAME)) { - processor.processText(myProject, myTemplate, myDocument, myTemplateRange, myEditor); - } - mySegments.setSegmentsGreedy(true); - restoreEmptyVariables(indices); + ApplicationManager.getApplication().runWriteAction(() -> { + final PsiFile file = getPsiFile(); + if (file != null) { + IntArrayList indices = initEmptyVariables(); + mySegments.setSegmentsGreedy(false); + for (TemplateOptionalProcessor processor : Extensions.getExtensions(TemplateOptionalProcessor.EP_NAME)) { + processor.processText(myProject, myTemplate, myDocument, myTemplateRange, myEditor); } + mySegments.setSegmentsGreedy(true); + restoreEmptyVariables(indices); } }); } @@ -581,41 +567,38 @@ public class TemplateState implements Disposable { myEditor.getSelectionModel().setSelection(start, end); } - DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - Expression expressionNode = getCurrentExpression(); - List lookupItems; - try { - lookupItems = getCurrentExpressionLookupItems(); - } - catch (IndexNotReadyException e) { - lookupItems = Collections.emptyList(); - } - final PsiFile psiFile = getPsiFile(); - if (!lookupItems.isEmpty()) { - if (((TemplateManagerImpl)TemplateManager.getInstance(myProject)).shouldSkipInTests()) { - insertSingleItem(lookupItems); - } - else { - for (LookupElement lookupItem : lookupItems) { - assert lookupItem != null : expressionNode; - } - - runLookup(lookupItems, expressionNode.getAdvertisingText()); - } + DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> { + Expression expressionNode = getCurrentExpression(); + List lookupItems; + try { + lookupItems = getCurrentExpressionLookupItems(); + } + catch (IndexNotReadyException e) { + lookupItems = Collections.emptyList(); + } + final PsiFile psiFile = getPsiFile(); + if (!lookupItems.isEmpty()) { + if (((TemplateManagerImpl)TemplateManager.getInstance(myProject)).shouldSkipInTests()) { + insertSingleItem(lookupItems); } else { - try { - Result result = expressionNode.calculateResult(getCurrentExpressionContext()); - if (result != null) { - result.handleFocused(psiFile, myDocument, mySegments.getSegmentStart(currentSegmentNumber), - mySegments.getSegmentEnd(currentSegmentNumber)); - } + for (LookupElement lookupItem : lookupItems) { + assert lookupItem != null : expressionNode; } - catch (IndexNotReadyException ignore) { + + runLookup(lookupItems, expressionNode.getAdvertisingText()); + } + } + else { + try { + Result result = expressionNode.calculateResult(getCurrentExpressionContext()); + if (result != null) { + result.handleFocused(psiFile, myDocument, mySegments.getSegmentStart(currentSegmentNumber), + mySegments.getSegmentEnd(currentSegmentNumber)); } } + catch (IndexNotReadyException ignore) { + } } }); focusCurrentHighlighter(true); @@ -709,64 +692,57 @@ public class TemplateState implements Disposable { fixOverlappedSegments(myCurrentSegmentNumber); - WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { - @Override - public void run() { - if (isDisposed()) { - return; - } - BitSet calcedSegments = new BitSet(); - int maxAttempts = (myTemplate.getVariableCount() + 1) * 3; - - do { - maxAttempts--; - calcedSegments.clear(); - for (int i = myCurrentVariableNumber + 1; i < myTemplate.getVariableCount(); i++) { - String variableName = myTemplate.getVariableNameAt(i); - final int segmentNumber = myTemplate.getVariableSegmentNumber(variableName); - if (segmentNumber < 0) continue; - final Expression expression = myTemplate.getExpressionAt(i); - final Expression defaultValue = myTemplate.getDefaultValueAt(i); - String oldValue = getVariableValueText(variableName); - DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - recalcSegment(segmentNumber, isQuick, expression, defaultValue); - } - }); - final TextResult value = getVariableValue(variableName); - assert value != null : "name=" + variableName + "\ntext=" + myTemplate.getTemplateText(); - String newValue = value.getText(); - if (!newValue.equals(oldValue)) { - calcedSegments.set(segmentNumber); - } - } - - List changes = ContainerUtil.newArrayList(); - boolean selectionCalculated = false; - for (int i = 0; i < myTemplate.getSegmentsCount(); i++) { - if (!calcedSegments.get(i)) { - String variableName = myTemplate.getSegmentName(i); - if (variableName.equals(TemplateImpl.SELECTION)) { - if (mySelectionCalculated) { - continue; - } - selectionCalculated = true; - } - if (TemplateImpl.END.equals(variableName)) continue; // No need to update end since it can be placed over some other variable - String newValue = getVariableValueText(variableName); - int start = mySegments.getSegmentStart(i); - int end = mySegments.getSegmentEnd(i); - changes.add(new TemplateDocumentChange(newValue, start, end, i)); - } - } - executeChanges(changes); - if (selectionCalculated) { - mySelectionCalculated = true; - } - } - while (!calcedSegments.isEmpty() && maxAttempts >= 0); + WriteCommandAction.runWriteCommandAction(myProject, () -> { + if (isDisposed()) { + return; } + BitSet calcedSegments = new BitSet(); + int maxAttempts = (myTemplate.getVariableCount() + 1) * 3; + + do { + maxAttempts--; + calcedSegments.clear(); + for (int i = myCurrentVariableNumber + 1; i < myTemplate.getVariableCount(); i++) { + String variableName = myTemplate.getVariableNameAt(i); + final int segmentNumber = myTemplate.getVariableSegmentNumber(variableName); + if (segmentNumber < 0) continue; + final Expression expression = myTemplate.getExpressionAt(i); + final Expression defaultValue = myTemplate.getDefaultValueAt(i); + String oldValue = getVariableValueText(variableName); + DumbService.getInstance(myProject).withAlternativeResolveEnabled( + () -> recalcSegment(segmentNumber, isQuick, expression, defaultValue)); + final TextResult value = getVariableValue(variableName); + assert value != null : "name=" + variableName + "\ntext=" + myTemplate.getTemplateText(); + String newValue = value.getText(); + if (!newValue.equals(oldValue)) { + calcedSegments.set(segmentNumber); + } + } + + List changes = ContainerUtil.newArrayList(); + boolean selectionCalculated = false; + for (int i = 0; i < myTemplate.getSegmentsCount(); i++) { + if (!calcedSegments.get(i)) { + String variableName = myTemplate.getSegmentName(i); + if (variableName.equals(TemplateImpl.SELECTION)) { + if (mySelectionCalculated) { + continue; + } + selectionCalculated = true; + } + if (TemplateImpl.END.equals(variableName)) continue; // No need to update end since it can be placed over some other variable + String newValue = getVariableValueText(variableName); + int start = mySegments.getSegmentStart(i); + int end = mySegments.getSegmentEnd(i); + changes.add(new TemplateDocumentChange(newValue, start, end, i)); + } + } + executeChanges(changes); + if (selectionCalculated) { + mySelectionCalculated = true; + } + } + while (!calcedSegments.isEmpty() && maxAttempts >= 0); }); } @@ -789,20 +765,14 @@ public class TemplateState implements Disposable { return; } if (changes.size() > 1) { - ContainerUtil.sort(changes, new Comparator() { - @Override - public int compare(TemplateDocumentChange o1, TemplateDocumentChange o2) { - int startDiff = o2.startOffset - o1.startOffset; - return startDiff != 0 ? startDiff : o2.endOffset - o1.endOffset; - } + ContainerUtil.sort(changes, (o1, o2) -> { + int startDiff = o2.startOffset - o1.startOffset; + return startDiff != 0 ? startDiff : o2.endOffset - o1.endOffset; }); } - DocumentUtil.executeInBulk(myDocument, true, new Runnable() { - @Override - public void run() { - for (TemplateDocumentChange change : changes) { - replaceString(change.newValue, change.startOffset, change.endOffset, change.segmentNumber); - } + DocumentUtil.executeInBulk(myDocument, true, () -> { + for (TemplateDocumentChange change : changes) { + replaceString(change.newValue, change.startOffset, change.endOffset, change.segmentNumber); } }); } @@ -935,11 +905,8 @@ public class TemplateState implements Disposable { int nextVariableNumber = getNextVariableNumber(oldVar); if (nextVariableNumber == -1) { calcResults(false); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - reformat(null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + reformat(null); }); finishTemplateEditing(); return; @@ -1174,12 +1141,9 @@ public class TemplateState implements Disposable { int index = indices.get(i); rangesToRemove.add(TextRange.create(mySegments.getSegmentStart(index), mySegments.getSegmentEnd(index))); } - Collections.sort(rangesToRemove, new Comparator() { - @Override - public int compare(TextRange o1, TextRange o2) { - int startDiff = o2.getStartOffset() - o1.getStartOffset(); - return startDiff != 0 ? startDiff : o2.getEndOffset() - o1.getEndOffset(); - } + Collections.sort(rangesToRemove, (o1, o2) -> { + int startDiff = o2.getStartOffset() - o1.getStartOffset(); + return startDiff != 0 ? startDiff : o2.getEndOffset() - o1.getEndOffset(); }); DocumentUtil.executeInBulk(myDocument, true, () -> { if (isDisposed()) { @@ -1245,12 +1209,9 @@ public class TemplateState implements Disposable { final PsiFile file = getPsiFile(); if (file != null) { CodeStyleManager style = CodeStyleManager.getInstance(myProject); - DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - for (TemplateOptionalProcessor optionalProcessor : Extensions.getExtensions(TemplateOptionalProcessor.EP_NAME)) { - optionalProcessor.processText(myProject, myTemplate, myDocument, myTemplateRange, myEditor); - } + DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> { + for (TemplateOptionalProcessor optionalProcessor : Extensions.getExtensions(TemplateOptionalProcessor.EP_NAME)) { + optionalProcessor.processText(myProject, myTemplate, myDocument, myTemplateRange, myEditor); } }); PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myDocument); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/macro/BaseCompleteMacro.java b/platform/lang-impl/src/com/intellij/codeInsight/template/macro/BaseCompleteMacro.java index dfa2342575ab..5dde4ea0e399 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/macro/BaseCompleteMacro.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/macro/BaseCompleteMacro.java @@ -61,12 +61,7 @@ public abstract class BaseCompleteMacro extends Macro { @Override public final Result calculateResult(@NotNull Expression[] params, final ExpressionContext context) { return new InvokeActionResult( - new Runnable() { - @Override - public void run() { - invokeCompletion(context); - } - } + () -> invokeCompletion(context) ); } @@ -75,29 +70,23 @@ public abstract class BaseCompleteMacro extends Macro { final Editor editor = context.getEditor(); final PsiFile psiFile = editor != null ? PsiUtilBase.getPsiFileInEditor(editor, project) : null; - Runnable runnable = new Runnable() { - @Override - public void run() { - if (project.isDisposed() || editor == null || editor.isDisposed() || psiFile == null || !psiFile.isValid()) return; + Runnable runnable = () -> { + if (project.isDisposed() || editor == null || editor.isDisposed() || psiFile == null || !psiFile.isValid()) return; - // it's invokeLater, so another completion could have started - if (CompletionServiceImpl.getCompletionService().getCurrentCompletion() != null) return; + // it's invokeLater, so another completion could have started + if (CompletionServiceImpl.getCompletionService().getCurrentCompletion() != null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - // if we're in some completion's insert handler, make sure our new completion isn't treated as the second invocation - CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); - - invokeCompletionHandler(project, editor); - Lookup lookup = LookupManager.getInstance(project).getActiveLookup(); + CommandProcessor.getInstance().executeCommand(project, () -> { + // if we're in some completion's insert handler, make sure our new completion isn't treated as the second invocation + CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); - if (lookup != null) { - lookup.addLookupListener(new MyLookupListener(context)); - } - } - }, "", null); - } + invokeCompletionHandler(project, editor); + Lookup lookup = LookupManager.getInstance(project).getActiveLookup(); + + if (lookup != null) { + lookup.addLookupListener(new MyLookupListener(context)); + } + }, "", null); }; ApplicationManager.getApplication().invokeLater(runnable); } @@ -148,20 +137,15 @@ public abstract class BaseCompleteMacro extends Macro { return; } - Runnable runnable = new Runnable() { + Runnable runnable = () -> new WriteCommandAction(project) { @Override - public void run() { - new WriteCommandAction(project) { - @Override - protected void run(@NotNull com.intellij.openapi.application.Result result) throws Throwable { - Editor editor = myContext.getEditor(); - if (editor != null) { - considerNextTab(editor); - } - } - }.execute(); + protected void run(@NotNull com.intellij.openapi.application.Result result) throws Throwable { + Editor editor = myContext.getEditor(); + if (editor != null) { + considerNextTab(editor); + } } - }; + }.execute(); if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupActionProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupActionProvider.java index 1fa73ed3316e..a605ba194010 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupActionProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupActionProvider.java @@ -42,23 +42,17 @@ public class PostfixTemplateLookupActionProvider implements LookupActionProvider @Override public Result performLookupAction() { final Project project = lookup.getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; - final PostfixTemplatesConfigurable configurable = new PostfixTemplatesConfigurable(); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - PostfixTemplatesCheckboxTree templatesTree = configurable.getTemplatesTree(); - if (templatesTree != null) { - templatesTree.selectTemplate(template, PostfixTemplatesUtils - .getLangForProvider(templateLookupElement.getProvider())); - } - } - }); - } + final PostfixTemplatesConfigurable configurable = new PostfixTemplatesConfigurable(); + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + PostfixTemplatesCheckboxTree templatesTree = configurable.getTemplatesTree(); + if (templatesTree != null) { + templatesTree.selectTemplate(template, PostfixTemplatesUtils + .getLangForProvider(templateLookupElement.getProvider())); + } + }); }); return Result.HIDE_LOOKUP; } @@ -69,12 +63,7 @@ public class PostfixTemplateLookupActionProvider implements LookupActionProvider consumer.consume(new LookupElementAction(AllIcons.Actions.Delete, String.format("Disable '%s' template", template.getKey())) { @Override public Result performLookupAction() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - settings.disableTemplate(template, templateLookupElement.getProvider()); - } - }); + ApplicationManager.getApplication().invokeLater(() -> settings.disableTemplate(template, templateLookupElement.getProvider())); return Result.HIDE_LOOKUP; } }); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java index 68d5e7417d2a..00e339c03b10 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java @@ -147,14 +147,11 @@ public class PostfixTemplatesCheckboxTree extends CheckboxTree { public Map> getState() { final Map> result = ContainerUtil.newHashMap(); - Consumer consumer = new Consumer() { - @Override - public void consume(PostfixTemplateCheckedTreeNode template) { - if (!template.isChecked()) { - Set templatesForLanguage = - ContainerUtil.getOrCreate(result, template.getLang(), PostfixTemplatesSettings.SET_FACTORY); - templatesForLanguage.add(template.getTemplate().getKey()); - } + Consumer consumer = template -> { + if (!template.isChecked()) { + Set templatesForLanguage = + ContainerUtil.getOrCreate(result, template.getLang(), PostfixTemplatesSettings.SET_FACTORY); + templatesForLanguage.add(template.getTemplate().getKey()); } }; visit(consumer); @@ -177,18 +174,15 @@ public class PostfixTemplatesCheckboxTree extends CheckboxTree { public void setState(@NotNull final Map> langToDisabledTemplates) { final TreeState treeState = TreeState.createOn(this, myRoot); - Consumer consumer = new Consumer() { - @Override - public void consume(PostfixTemplateCheckedTreeNode template) { - Set disabledTemplates = langToDisabledTemplates.get(template.getLang()); - String key = template.getTemplate().getKey(); - if (disabledTemplates != null && disabledTemplates.contains(key)) { - template.setChecked(false); - return; - } - - template.setChecked(true); + Consumer consumer = template -> { + Set disabledTemplates = langToDisabledTemplates.get(template.getLang()); + String key = template.getTemplate().getKey(); + if (disabledTemplates != null && disabledTemplates.contains(key)) { + template.setChecked(false); + return; } + + template.setChecked(true); }; visit(consumer); @@ -199,12 +193,9 @@ public class PostfixTemplatesCheckboxTree extends CheckboxTree { } public void selectTemplate(@NotNull final PostfixTemplate postfixTemplate, @NotNull final String lang) { - Consumer consumer = new Consumer() { - @Override - public void consume(PostfixTemplateCheckedTreeNode template) { - if (lang.equals(template.getLang()) && postfixTemplate.getKey().equals(template.getTemplate().getKey())) { - TreeUtil.selectInTree(template, true, PostfixTemplatesCheckboxTree.this, true); - } + Consumer consumer = template -> { + if (lang.equals(template.getLang()) && postfixTemplate.getKey().equals(template.getTemplate().getKey())) { + TreeUtil.selectInTree(template, true, PostfixTemplatesCheckboxTree.this, true); } }; visit(consumer); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java index a0dcbb429518..46593d885a5d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java @@ -47,12 +47,7 @@ import java.util.List; public class PostfixTemplatesConfigurable implements SearchableConfigurable, EditorOptionsProvider, Configurable.NoScroll { - public static final Comparator TEMPLATE_COMPARATOR = new Comparator() { - @Override - public int compare(PostfixTemplate o1, PostfixTemplate o2) { - return o1.getKey().compareTo(o2.getKey()); - } - }; + public static final Comparator TEMPLATE_COMPARATOR = (o1, o2) -> o1.getKey().compareTo(o2.getKey()); @Nullable private PostfixTemplatesCheckboxTree myCheckboxTree; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java index 61544faf2c81..d0d9c3b4a2cb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java @@ -220,15 +220,8 @@ public class PostfixLiveTemplate extends CustomLiveTemplateBase { private static void expandTemplate(@NotNull final PostfixTemplate template, @NotNull final Editor editor, @NotNull final PsiElement context) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(context.getProject(), new Runnable() { - public void run() { - template.expand(context, editor); - } - }, "Expand postfix template", POSTFIX_TEMPLATE_ID); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(context.getProject(), () -> template.expand(context, editor), "Expand postfix template", POSTFIX_TEMPLATE_ID); }); } @@ -238,18 +231,13 @@ public class PostfixLiveTemplate extends CustomLiveTemplateBase { final int currentOffset = editor.getCaretModel().getOffset(); final int newOffset = currentOffset - key.length(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - public void run() { - Document document = editor.getDocument(); - document.deleteString(newOffset, currentOffset); - editor.getCaretModel().moveToOffset(newOffset); - PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); - } - }); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().runUndoTransparentAction(() -> { + Document document = editor.getDocument(); + document.deleteString(newOffset, currentOffset); + editor.getCaretModel().moveToOffset(newOffset); + PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); + }); }); return newOffset; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateExpressionSelectorBase.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateExpressionSelectorBase.java index 648fdf5fedf5..9f9e0c544fcd 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateExpressionSelectorBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateExpressionSelectorBase.java @@ -72,12 +72,7 @@ public abstract class PostfixTemplateExpressionSelectorBase implements PostfixTe @NotNull public Function getRenderer() { - return new Function() { - @Override - public String fun(@NotNull PsiElement element) { - return element.getText(); - } - }; + return element -> element.getText(); } protected abstract List getNonFilteredExpressions(@NotNull PsiElement context, @NotNull Document document, int offset); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateWithExpressionSelector.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateWithExpressionSelector.java index 48f7b339f961..6c2c02b8678c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateWithExpressionSelector.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateWithExpressionSelector.java @@ -81,15 +81,8 @@ public abstract class PostfixTemplateWithExpressionSelector extends PostfixTempl editor, expressions, new Pass() { public void pass(@NotNull final PsiElement e) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(e.getProject(), new Runnable() { - public void run() { - expandForChooseExpression(e, editor); - } - }, "Expand postfix template", PostfixLiveTemplate.POSTFIX_TEMPLATE_ID); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(e.getProject(), () -> expandForChooseExpression(e, editor), "Expand postfix template", PostfixLiveTemplate.POSTFIX_TEMPLATE_ID); }); } }, diff --git a/platform/lang-impl/src/com/intellij/codeInsight/unwrap/ScopeHighlighter.java b/platform/lang-impl/src/com/intellij/codeInsight/unwrap/ScopeHighlighter.java index 39f70d4f22ea..e4ffd99b68f4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/unwrap/ScopeHighlighter.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/unwrap/ScopeHighlighter.java @@ -36,13 +36,7 @@ import java.util.ArrayList; import java.util.List; public class ScopeHighlighter { - public static final NotNullFunction NATURAL_RANGER = new NotNullFunction() { - @NotNull - @Override - public TextRange fun(PsiElement dom) { - return dom.getTextRange(); - } - }; + public static final NotNullFunction NATURAL_RANGER = dom -> dom.getTextRange(); private final Editor myEditor; private final List myActiveHighliters = new ArrayList(); private final NotNullFunction myRanger; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/unwrap/UnwrapHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/unwrap/UnwrapHandler.java index e70bbb81ff48..6e79f58a4520 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/unwrap/UnwrapHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/unwrap/UnwrapHandler.java @@ -128,12 +128,9 @@ public class UnwrapHandler implements CodeInsightActionHandler { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - MyUnwrapAction a = (MyUnwrapAction)options.get(list.getSelectedIndex()); - a.actionPerformed(null); - } + .setItemChoosenCallback(() -> { + MyUnwrapAction a = (MyUnwrapAction)options.get(list.getSelectedIndex()); + a.actionPerformed(null); }) .addListener(new JBPopupAdapter() { @Override @@ -172,31 +169,23 @@ public class UnwrapHandler implements CodeInsightActionHandler { final PsiFile file = myElement.getContainingFile(); if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - UnwrapDescriptor d = getUnwrapDescription(file); - if (d.shouldTryToRestoreCaretPosition()) saveCaretPosition(file); - int scrollOffset = myEditor.getScrollingModel().getVerticalScrollOffset(); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + UnwrapDescriptor d = getUnwrapDescription(file); + if (d.shouldTryToRestoreCaretPosition()) saveCaretPosition(file); + int scrollOffset = myEditor.getScrollingModel().getVerticalScrollOffset(); - List extractedElements = myUnwrapper.unwrap(myEditor, myElement); + List extractedElements = myUnwrapper.unwrap(myEditor, myElement); - if (d.shouldTryToRestoreCaretPosition()) restoreCaretPosition(file); - myEditor.getScrollingModel().scrollVertically(scrollOffset); + if (d.shouldTryToRestoreCaretPosition()) restoreCaretPosition(file); + myEditor.getScrollingModel().scrollVertically(scrollOffset); - highlightExtractedElements(extractedElements); - } - catch (IncorrectOperationException ex) { - throw new RuntimeException(ex); - } - } - }); + highlightExtractedElements(extractedElements); } - }, null, myEditor.getDocument()); + catch (IncorrectOperationException ex) { + throw new RuntimeException(ex); + } + }), null, myEditor.getDocument()); } private void saveCaretPosition(PsiFile file) { diff --git a/platform/lang-impl/src/com/intellij/codeInspection/InspectionApplication.java b/platform/lang-impl/src/com/intellij/codeInspection/InspectionApplication.java index 993f45736c68..7b425b52d666 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/InspectionApplication.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/InspectionApplication.java @@ -93,24 +93,21 @@ public class InspectionApplication { } final ApplicationEx application = ApplicationManagerEx.getApplicationEx(); - application.runReadAction(new Runnable() { - @Override - public void run() { - try { - final ApplicationInfoEx appInfo = (ApplicationInfoEx)ApplicationInfo.getInstance(); - logMessage(1, InspectionsBundle.message("inspection.application.starting.up", - appInfo.getFullApplicationName() + " (build " + appInfo.getBuild().asString() + ")")); - application.doNotSave(); - logMessageLn(1, InspectionsBundle.message("inspection.done")); + application.runReadAction(() -> { + try { + final ApplicationInfoEx appInfo = (ApplicationInfoEx)ApplicationInfo.getInstance(); + logMessage(1, InspectionsBundle.message("inspection.application.starting.up", + appInfo.getFullApplicationName() + " (build " + appInfo.getBuild().asString() + ")")); + application.doNotSave(); + logMessageLn(1, InspectionsBundle.message("inspection.done")); - InspectionApplication.this.run(); - } - catch (Exception e) { - LOG.error(e); - } - finally { - if (myErrorCodeRequired) application.exit(true, true); - } + InspectionApplication.this.run(); + } + catch (Exception e) { + LOG.error(e); + } + finally { + if (myErrorCodeRequired) application.exit(true, true); } }); } @@ -146,11 +143,8 @@ public class InspectionApplication { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run(){ - VirtualFileManager.getInstance().refreshWithoutFileWatcher(false); - } + ApplicationManager.getApplication().runWriteAction(() -> { + VirtualFileManager.getInstance().refreshWithoutFileWatcher(false); }); PatchProjectUtil.patchProject(myProject); @@ -218,18 +212,15 @@ public class InspectionApplication { } final List inspectionsResults = new ArrayList(); - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - if (!GlobalInspectionContextUtil.canRunInspections(myProject, false)) { - gracefulExit(); - return; - } - inspectionContext.launchInspectionsOffline(scope, resultsDataPath, myRunGlobalToolsOnly, inspectionsResults); - logMessageLn(1, "\n" + InspectionsBundle.message("inspection.capitalized.done") + "\n"); - if (!myErrorCodeRequired) { - closeProject(); - } + ProgressManager.getInstance().runProcess(() -> { + if (!GlobalInspectionContextUtil.canRunInspections(myProject, false)) { + gracefulExit(); + return; + } + inspectionContext.launchInspectionsOffline(scope, resultsDataPath, myRunGlobalToolsOnly, inspectionsResults); + logMessageLn(1, "\n" + InspectionsBundle.message("inspection.capitalized.done") + "\n"); + if (!myErrorCodeRequired) { + closeProject(); } }, new ProgressIndicatorBase() { private String lastPrefix = ""; diff --git a/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java b/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java index b6796085aed6..30f551c4b886 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java @@ -100,14 +100,11 @@ public class CleanupInspectionIntention implements IntentionAction, HighPriority new SequentialModalProgressTask(project, templatePresentationText, true); final boolean isBatch = BatchQuickFix.class.isAssignableFrom(myQuickfixClass); final AbstractPerformFixesTask fixesTask = createTask(project, descriptions.toArray(new ProblemDescriptor[descriptions.size()]), progressTask, isBatch); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); - progressTask.setMinIterationTime(200); - progressTask.setTask(fixesTask); - ProgressManager.getInstance().run(progressTask); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); + progressTask.setMinIterationTime(200); + progressTask.setTask(fixesTask); + ProgressManager.getInstance().run(progressTask); }, templatePresentationText, null); if (!fixesTask.isApplicableFixFound()) { diff --git a/platform/lang-impl/src/com/intellij/codeInspection/actions/RunInspectionAction.java b/platform/lang-impl/src/com/intellij/codeInspection/actions/RunInspectionAction.java index 60ac92cc3562..5a0e74b06359 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/actions/RunInspectionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/actions/RunInspectionAction.java @@ -86,12 +86,8 @@ public class RunInspectionAction extends GotoActionBase { @Override public void elementChosen(ChooseByNamePopup popup, final Object element) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - runInspection(project, ((InspectionToolWrapper)element).getShortName(), virtualFile, psiElement, psiFile); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> runInspection(project, ((InspectionToolWrapper)element).getShortName(), virtualFile, psiElement, psiFile)); } }, false); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java b/platform/lang-impl/src/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java index 196e8000f13c..4650c0a7ff92 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java @@ -105,63 +105,49 @@ public class ViewOfflineResultsAction extends AnAction { final Map>> resMap = new HashMap>>(); final String [] profileName = new String[1]; - final Runnable process = new Runnable() { - @Override - public void run() { - final VirtualFile[] files = virtualFile.getChildren(); - try { - for (final VirtualFile inspectionFile : files) { - if (inspectionFile.isDirectory()) continue; - final String shortName = inspectionFile.getNameWithoutExtension(); - final String extension = inspectionFile.getExtension(); - if (shortName.equals(InspectionApplication.DESCRIPTIONS)) { - profileName[0] = ApplicationManager.getApplication().runReadAction( - new Computable() { - @Override - @Nullable - public String compute() { - return OfflineViewParseUtil.parseProfileName(LoadTextUtil.loadText(inspectionFile).toString()); - } + final Runnable process = () -> { + final VirtualFile[] files = virtualFile.getChildren(); + try { + for (final VirtualFile inspectionFile : files) { + if (inspectionFile.isDirectory()) continue; + final String shortName = inspectionFile.getNameWithoutExtension(); + final String extension = inspectionFile.getExtension(); + if (shortName.equals(InspectionApplication.DESCRIPTIONS)) { + profileName[0] = ApplicationManager.getApplication().runReadAction( + new Computable() { + @Override + @Nullable + public String compute() { + return OfflineViewParseUtil.parseProfileName(LoadTextUtil.loadText(inspectionFile).toString()); } - ); - } - else if (XML_EXTENSION.equals(extension)) { - resMap.put(shortName, ApplicationManager.getApplication().runReadAction( - new Computable>>() { - @Override - public Map> compute() { - return OfflineViewParseUtil.parse(LoadTextUtil.loadText(inspectionFile).toString()); - } + } + ); + } + else if (XML_EXTENSION.equals(extension)) { + resMap.put(shortName, ApplicationManager.getApplication().runReadAction( + new Computable>>() { + @Override + public Map> compute() { + return OfflineViewParseUtil.parse(LoadTextUtil.loadText(inspectionFile).toString()); } - )); - } + } + )); } } - catch (final Exception e) { //all parse exceptions - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title")); - } - }); - throw new ProcessCanceledException(); //cancel process - } + } + catch (final Exception e) { //all parse exceptions + SwingUtilities.invokeLater( + () -> Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title"))); + throw new ProcessCanceledException(); //cancel process } }; - ProgressManager.getInstance().runProcessWithProgressAsynchronously(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), process, new Runnable() { - @Override - public void run() { - SwingUtilities.invokeLater(new Runnable(){ - @Override - public void run() { - final String name = profileName[0]; - showOfflineView(project, name, resMap, - InspectionsBundle.message("offline.view.title") + - " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) +")"); - } - }); - } - }, null, new PerformAnalysisInBackgroundOption(project)); + ProgressManager.getInstance().runProcessWithProgressAsynchronously(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), process, + () -> SwingUtilities.invokeLater(() -> { + final String name = profileName[0]; + showOfflineView(project, name, resMap, + InspectionsBundle.message("offline.view.title") + + " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) +")"); + }), null, new PerformAnalysisInBackgroundOption(project)); } @SuppressWarnings({"WeakerAccess", "UnusedReturnValue"}) //used in TeamCity diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/DisableInspectionToolAction.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/DisableInspectionToolAction.java index a3441c91b59c..bdc218f28050 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/DisableInspectionToolAction.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/DisableInspectionToolAction.java @@ -69,12 +69,7 @@ public class DisableInspectionToolAction extends IntentionAndQuickFixAction impl @Override public void applyFix(@NotNull Project project, final PsiFile file, @Nullable Editor editor) { - modifyAndCommitProjectProfile(new Consumer() { - @Override - public void consume(ModifiableModel modifiableModel) { - modifiableModel.disableTool(myToolId, file); - } - }, project); + modifyAndCommitProjectProfile(modifiableModel -> modifiableModel.disableTool(myToolId, file), project); DaemonCodeAnalyzer.getInstance(project).restart(); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/EditInspectionToolsSettingsAction.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/EditInspectionToolsSettingsAction.java index f30a394d39d7..a616ea41e953 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/EditInspectionToolsSettingsAction.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/EditInspectionToolsSettingsAction.java @@ -100,17 +100,9 @@ public class EditInspectionToolsSettingsAction implements IntentionAction, Icona else { errorsConfigurable = ErrorsConfigurable.SERVICE.createConfigurable(project); } - return settingsUtil.editConfigurable(project, errorsConfigurable, new Runnable() { - @Override - public void run() { - errorsConfigurable.selectProfile(inspectionProfile); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - errorsConfigurable.selectInspectionTool(selectedToolShortName); - } - }); - } + return settingsUtil.editConfigurable(project, errorsConfigurable, () -> { + errorsConfigurable.selectProfile(inspectionProfile); + SwingUtilities.invokeLater(() -> errorsConfigurable.selectInspectionTool(selectedToolShortName)); }); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/LocalDescriptorsUtil.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/LocalDescriptorsUtil.java index f3595dc19351..89c3c248902c 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/LocalDescriptorsUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/LocalDescriptorsUtil.java @@ -31,9 +31,8 @@ import java.util.List; import java.util.Map; public class LocalDescriptorsUtil { - private static final TripleFunction CONVERT = new TripleFunction() { - @Override - public RefElement fun(LocalInspectionTool tool, PsiElement element, GlobalInspectionContext context) { + private static final TripleFunction CONVERT = + (tool, element, context) -> { final PsiNamedElement problemElement = tool.getProblemElement(element); RefElement refElement = context.getRefManager().getReference(problemElement); @@ -41,8 +40,7 @@ public class LocalDescriptorsUtil { refElement = GlobalInspectionContextUtil.retrieveRefElement(element, context); } return refElement; - } - }; + }; static void addProblemDescriptors(@NotNull List descriptors, boolean filterSuppressed, diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/PerformFixesModalTask.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/PerformFixesModalTask.java index fc5b3964730e..023aa8625306 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/PerformFixesModalTask.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/PerformFixesModalTask.java @@ -86,21 +86,15 @@ public abstract class PerformFixesModalTask implements SequentialTask { } } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myDocumentManager.commitAllDocuments(); - if (!runInReadAction[0]) { - applyFix(myProject, descriptor); - } - } - }); - if (runInReadAction[0]) { + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> { + ApplicationManager.getApplication().runWriteAction(() -> { + myDocumentManager.commitAllDocuments(); + if (!runInReadAction[0]) { applyFix(myProject, descriptor); } + }); + if (runInReadAction[0]) { + applyFix(myProject, descriptor); } }); return isDone(); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/SequentialCleanupTask.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/SequentialCleanupTask.java index 3911b0da5a4b..7619367c554c 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/SequentialCleanupTask.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/SequentialCleanupTask.java @@ -46,12 +46,7 @@ class SequentialCleanupTask implements SequentialTask { PsiFile file = entry.getKey(); List infos = entry.getValue(); // sort from bottom to top - Collections.sort(infos, new Comparator() { - @Override - public int compare(HighlightInfo info1, HighlightInfo info2) { - return info2.getStartOffset() - info1.getStartOffset(); - } - }); + Collections.sort(infos, (info1, info2) -> info2.getStartOffset() - info1.getStartOffset()); for (HighlightInfo info : infos) { myResults.add(Pair.create(file, info)); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java index c39f2b35b040..43a7e4df55e7 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java @@ -243,13 +243,10 @@ public class SeverityEditorDialog extends DialogWrapper { assert colorAndFontOptions != null; final SearchableConfigurable javaPage = colorAndFontOptions.findSubConfigurable(InspectionColorSettingsPage.class); LOG.assertTrue(javaPage != null); - settings.select(javaPage).doWhenDone(new Runnable() { - @Override - public void run() { - final Runnable runnable = javaPage.enableSearch(toConfigure); - if (runnable != null) { - SwingUtilities.invokeLater(runnable); - } + settings.select(javaPage).doWhenDone(() -> { + final Runnable runnable = javaPage.enableSearch(toConfigure); + if (runnable != null) { + SwingUtilities.invokeLater(runnable); } }); } @@ -275,13 +272,8 @@ public class SeverityEditorDialog extends DialogWrapper { model.removeAllElements(); final List infoTypes = new ArrayList(); infoTypes.addAll(SeverityUtil.getRegisteredHighlightingInfoTypes(mySeverityRegistrar)); - Collections.sort(infoTypes, new Comparator() { - @Override - public int compare(SeverityBasedTextAttributes attributes1, - SeverityBasedTextAttributes attributes2) { - return -mySeverityRegistrar.compare(attributes1.getSeverity(), attributes2.getSeverity()); - } - }); + Collections.sort(infoTypes, + (attributes1, attributes2) -> -mySeverityRegistrar.compare(attributes1.getSeverity(), attributes2.getSeverity())); SeverityBasedTextAttributes preselection = null; for (SeverityBasedTextAttributes type : infoTypes) { model.addElement(type); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/export/HTMLExportUtil.java b/platform/lang-impl/src/com/intellij/codeInspection/export/HTMLExportUtil.java index b0979c9ea1e2..dac9f7f0e6f8 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/export/HTMLExportUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/export/HTMLExportUtil.java @@ -34,17 +34,14 @@ public class HTMLExportUtil { HTMLExporter.writeFileImpl(folder, fileName, buf); } catch (IOException e) { - Runnable showError = new Runnable() { - @Override - public void run() { - final String fullPath = folder + File.separator + fileName; - Messages.showMessageDialog( - project, - InspectionsBundle.message("inspection.export.error.writing.to", fullPath), - InspectionsBundle.message("inspection.export.results.error.title"), - Messages.getErrorIcon() - ); - } + Runnable showError = () -> { + final String fullPath = folder + File.separator + fileName; + Messages.showMessageDialog( + project, + InspectionsBundle.message("inspection.export.error.writing.to", fullPath), + InspectionsBundle.message("inspection.export.results.error.title"), + Messages.getErrorIcon() + ); }; ApplicationManager.getApplication().invokeLater(showError, ModalityState.NON_MODAL); throw new ProcessCanceledException(); @@ -56,17 +53,12 @@ public class HTMLExportUtil { runnable.run(); } catch (IOException e) { - Runnable showError = new Runnable() { - @Override - public void run() { - Messages.showMessageDialog( - project, - InspectionsBundle.message("inspection.export.error.writing.to", "export file"), - InspectionsBundle.message("inspection.export.results.error.title"), - Messages.getErrorIcon() - ); - } - }; + Runnable showError = () -> Messages.showMessageDialog( + project, + InspectionsBundle.message("inspection.export.error.writing.to", "export file"), + InspectionsBundle.message("inspection.export.results.error.title"), + Messages.getErrorIcon() + ); ApplicationManager.getApplication().invokeLater(showError, ModalityState.NON_MODAL); throw new ProcessCanceledException(); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java b/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java index 00f4ea65efde..830b93f6e259 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java @@ -115,12 +115,7 @@ public class OfflineInspectionRVContentProvider extends InspectionRVContentProvi final Map> filteredContent = getFilteredContent(context, toolWrapper); if (filteredContent != null && !filteredContent.values().isEmpty()) { final Function> computeContainer = - new Function>() { - @Override - public UserObjectContainer fun(final OfflineProblemDescriptor descriptor) { - return new OfflineProblemDescriptorContainer(descriptor); - } - }; + descriptor -> new OfflineProblemDescriptorContainer(descriptor); parentNode.add(toolNode); buildTree(context, filteredContent, false, toolWrapper, computeContainer, showStructure, toolNode::add); } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java index b87498a1b178..1624db025015 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java @@ -380,21 +380,18 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren final VirtualFile[] file = new VirtualFile[1]; final int[] offset = new int[1]; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiElement psiElement = refElement.getElement(); - if (psiElement != null) { - final PsiFile containingFile = psiElement.getContainingFile(); - if (containingFile != null) { - file[0] = containingFile.getVirtualFile(); - offset[0] = psiElement.getTextOffset(); - } - } - else { - file[0] = null; + ApplicationManager.getApplication().runReadAction(() -> { + PsiElement psiElement = refElement.getElement(); + if (psiElement != null) { + final PsiFile containingFile = psiElement.getContainingFile(); + if (containingFile != null) { + file[0] = containingFile.getVirtualFile(); + offset[0] = psiElement.getTextOffset(); } } + else { + file[0] = null; + } }); if (file[0] != null && file[0].isValid()) { diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionSequentialTask.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionSequentialTask.java index 9bcb3fee3c70..b063f5621d91 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionSequentialTask.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionSequentialTask.java @@ -71,17 +71,14 @@ public class SuppressActionSequentialTask implements SequentialTask { indicator.setFraction((double)myCount / myNodesToSuppress.length); } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - final Pair content = node.getSuppressContent(); - if (content.first != null) { - final PsiElement element = content.first; - RefEntity refEntity = node.getElement(); - LOG.assertTrue(refEntity != null); - if (suppress(element, content.second, mySuppressAction, refEntity, myWrapper)) { - node.markAsSuppressedFromView(); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> { + final Pair content = node.getSuppressContent(); + if (content.first != null) { + final PsiElement element = content.first; + RefEntity refEntity = node.getElement(); + LOG.assertTrue(refEntity != null); + if (suppress(element, content.second, mySuppressAction, refEntity, myWrapper)) { + node.markAsSuppressedFromView(); } } }); @@ -115,37 +112,34 @@ public class SuppressActionSequentialTask implements SequentialTask { } final Project project = element.getProject(); final PsiModificationTracker tracker = PsiManager.getInstance(project).getModificationTracker(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - try { - final long startModificationCount = tracker.getModificationCount(); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + try { + final long startModificationCount = tracker.getModificationCount(); - PsiElement container = null; - if (action instanceof SuppressIntentionActionFromFix) { - container = ((SuppressIntentionActionFromFix)action).getContainer(element); - } - if (container == null) { - container = element; - } + PsiElement container = null; + if (action instanceof SuppressIntentionActionFromFix) { + container = ((SuppressIntentionActionFromFix)action).getContainer(element); + } + if (container == null) { + container = element; + } - if (action.isAvailable(project, null, element)) { - action.invoke(project, null, element); - } - if (startModificationCount != tracker.getModificationCount()) { - final Set globalInspectionContexts = ((InspectionManagerEx)InspectionManager.getInstance(element.getProject())).getRunningContexts(); - for (GlobalInspectionContextImpl context : globalInspectionContexts) { - context.ignoreElement(wrapper.getTool(), container); - if (descriptor != null) { - context.getPresentation(wrapper).ignoreCurrentElementProblem(refEntity, descriptor); - } + if (action.isAvailable(project, null, element)) { + action.invoke(project, null, element); + } + if (startModificationCount != tracker.getModificationCount()) { + final Set globalInspectionContexts = ((InspectionManagerEx)InspectionManager.getInstance(element.getProject())).getRunningContexts(); + for (GlobalInspectionContextImpl context : globalInspectionContexts) { + context.ignoreElement(wrapper.getTool(), container); + if (descriptor != null) { + context.getPresentation(wrapper).ignoreCurrentElementProblem(refEntity, descriptor); } } } - catch (IncorrectOperationException e1) { - LOG.error(e1); - } + } + catch (IncorrectOperationException e1) { + LOG.error(e1); } }); return true; diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionWrapper.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionWrapper.java index 3a8233a775a5..16418c42be2d 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionWrapper.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/actions/suppress/SuppressActionWrapper.java @@ -102,35 +102,29 @@ public class SuppressActionWrapper extends ActionGroup implements CompactActionG @Override protected void actionPerformed(@NotNull InspectionResultsView view, @NotNull HighlightDisplayKey key) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Project project = view.getProject(); - final String templatePresentationText = getTemplatePresentation().getText(); - LOG.assertTrue(templatePresentationText != null); - final InspectionToolWrapper wrapper = view.getTree().getSelectedToolWrapper(); - LOG.assertTrue(wrapper != null); - final Set nodesAsSet = getNodesToSuppress(view); - final SuppressableInspectionTreeNode[] nodes = nodesAsSet.toArray(new SuppressableInspectionTreeNode[nodesAsSet.size()]); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); - final SequentialModalProgressTask progressTask = - new SequentialModalProgressTask(project, templatePresentationText, true); - progressTask.setMinIterationTime(200); - progressTask.setTask(new SuppressActionSequentialTask(nodes, mySuppressAction, wrapper, progressTask)); - ProgressManager.getInstance().run(progressTask); - } - }, templatePresentationText, null); + ApplicationManager.getApplication().invokeLater(() -> { + Project project = view.getProject(); + final String templatePresentationText = getTemplatePresentation().getText(); + LOG.assertTrue(templatePresentationText != null); + final InspectionToolWrapper wrapper = view.getTree().getSelectedToolWrapper(); + LOG.assertTrue(wrapper != null); + final Set nodesAsSet = getNodesToSuppress(view); + final SuppressableInspectionTreeNode[] nodes = nodesAsSet.toArray(new SuppressableInspectionTreeNode[nodesAsSet.size()]); + CommandProcessor.getInstance().executeCommand(project, () -> { + CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); + final SequentialModalProgressTask progressTask = + new SequentialModalProgressTask(project, templatePresentationText, true); + progressTask.setMinIterationTime(200); + progressTask.setTask(new SuppressActionSequentialTask(nodes, mySuppressAction, wrapper, progressTask)); + ProgressManager.getInstance().run(progressTask); + }, templatePresentationText, null); - final Set globalInspectionContexts = - ((InspectionManagerEx)InspectionManager.getInstance(project)).getRunningContexts(); - for (GlobalInspectionContextImpl context : globalInspectionContexts) { - context.refreshViews(); - } - view.syncRightPanel(); + final Set globalInspectionContexts = + ((InspectionManagerEx)InspectionManager.getInstance(project)).getRunningContexts(); + for (GlobalInspectionContextImpl context : globalInspectionContexts) { + context.refreshViews(); } + view.syncRightPanel(); }); } diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java index 6cb8a053d660..7774d5955078 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java @@ -384,12 +384,7 @@ public abstract class LogConsoleBase extends AdditionalTabComponent implements L } private void filterConsoleOutput() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - computeSelectedLineAndFilter(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> computeSelectedLineAndFilter()); } private synchronized void computeSelectedLineAndFilter() { @@ -417,12 +412,7 @@ public abstract class LogConsoleBase extends AdditionalTabComponent implements L } } } - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - doFilter(); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> doFilter()); } private synchronized void doFilter() { diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java index e01fc9bb01a6..c919a49aed5f 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java @@ -62,22 +62,19 @@ public class LogFilesManager { obsoletePaths.removeAll(newPaths); try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) { - return; - } + SwingUtilities.invokeAndWait(() -> { + if (project.isDisposed()) { + return; + } - addConfigurationConsoles(logFile.getOptions(), new Condition() { - @Override - public boolean value(final String file) { - return !oldPaths.contains(file); - } - }, newPaths, logFile.getConfiguration()); - for (String each : obsoletePaths) { - myManager.removeLogConsole(each); + addConfigurationConsoles(logFile.getOptions(), new Condition() { + @Override + public boolean value(final String file) { + return !oldPaths.contains(file); } + }, newPaths, logFile.getConfiguration()); + for (String each : obsoletePaths) { + myManager.removeLogConsole(each); } }); } diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java index 5c4f3ad9a3e3..9ba72931049f 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java @@ -129,11 +129,8 @@ public class OutputFileUtil { if (file != null) { file.refresh(false, false); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), true); - } + ApplicationManager.getApplication().runReadAction(() -> { + FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), true); }); } } diff --git a/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java b/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java index 94592406b54d..19ffb02c93a1 100644 --- a/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java +++ b/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java @@ -89,40 +89,37 @@ public class ExecutionHelper { if (ApplicationManager.getApplication().isUnitTestMode() && !errors.isEmpty()) { throw new RuntimeException(errors.get(0)); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - if (errors.isEmpty() && warnings.isEmpty()) { - removeContents(null, myProject, tabDisplayName); - return; - } - - final ErrorViewPanel errorTreeView = new ErrorViewPanel(myProject); - try { - openMessagesView(errorTreeView, myProject, tabDisplayName); - } - catch (NullPointerException e) { - final StringBuilder builder = new StringBuilder(); - builder.append("Exceptions occurred:"); - for (final Exception exception : errors) { - builder.append("\n"); - builder.append(exception.getMessage()); - } - builder.append("Warnings occurred:"); - for (final Exception exception : warnings) { - builder.append("\n"); - builder.append(exception.getMessage()); - } - Messages.showErrorDialog(builder.toString(), "Execution Error"); - return; - } - - addMessages(MessageCategory.ERROR, errors, errorTreeView, file, "Unknown Error"); - addMessages(MessageCategory.WARNING, warnings, errorTreeView, file, "Unknown Warning"); - - ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW).activate(null); + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; + if (errors.isEmpty() && warnings.isEmpty()) { + removeContents(null, myProject, tabDisplayName); + return; } + + final ErrorViewPanel errorTreeView = new ErrorViewPanel(myProject); + try { + openMessagesView(errorTreeView, myProject, tabDisplayName); + } + catch (NullPointerException e) { + final StringBuilder builder = new StringBuilder(); + builder.append("Exceptions occurred:"); + for (final Exception exception : errors) { + builder.append("\n"); + builder.append(exception.getMessage()); + } + builder.append("Warnings occurred:"); + for (final Exception exception : warnings) { + builder.append("\n"); + builder.append(exception.getMessage()); + } + Messages.showErrorDialog(builder.toString(), "Execution Error"); + return; + } + + addMessages(MessageCategory.ERROR, errors, errorTreeView, file, "Unknown Error"); + addMessages(MessageCategory.WARNING, warnings, errorTreeView, file, "Unknown Warning"); + + ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW).activate(null); }); } @@ -154,62 +151,59 @@ public class ExecutionHelper { throw new RuntimeException("STDOUT:\n" + stdout + "\nSTDERR:\n" + stderr); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; - final String stdOutTitle = "[Stdout]:"; - final String stderrTitle = "[Stderr]:"; - final ErrorViewPanel errorTreeView = new ErrorViewPanel(myProject); - try { - openMessagesView(errorTreeView, myProject, tabDisplayName); - } - catch (NullPointerException e) { - Messages.showErrorDialog(stdOutTitle + "\n" + (stdout != null ? stdout : "") + "\n" + stderrTitle + "\n" - + (stderr != null ? stderr : ""), "Process Output"); - return; - } + final String stdOutTitle = "[Stdout]:"; + final String stderrTitle = "[Stderr]:"; + final ErrorViewPanel errorTreeView = new ErrorViewPanel(myProject); + try { + openMessagesView(errorTreeView, myProject, tabDisplayName); + } + catch (NullPointerException e) { + Messages.showErrorDialog(stdOutTitle + "\n" + (stdout != null ? stdout : "") + "\n" + stderrTitle + "\n" + + (stderr != null ? stderr : ""), "Process Output"); + return; + } - if (!StringUtil.isEmpty(stdout)) { - final String[] stdoutLines = StringUtil.splitByLines(stdout); - if (stdoutLines.length > 0) { - if (StringUtil.isEmpty(stderr)) { - // Only stdout available + if (!StringUtil.isEmpty(stdout)) { + final String[] stdoutLines = StringUtil.splitByLines(stdout); + if (stdoutLines.length > 0) { + if (StringUtil.isEmpty(stderr)) { + // Only stdout available + errorTreeView.addMessage(MessageCategory.SIMPLE, stdoutLines, file, -1, -1, null); + } + else { + // both stdout and stderr available, show as groups + if (file == null) { + errorTreeView.addMessage(MessageCategory.SIMPLE, stdoutLines, stdOutTitle, NonNavigatable.INSTANCE, null, null, null); + } + else { + errorTreeView.addMessage(MessageCategory.SIMPLE, new String[]{stdOutTitle}, file, -1, -1, null); + errorTreeView.addMessage(MessageCategory.SIMPLE, new String[]{""}, file, -1, -1, null); errorTreeView.addMessage(MessageCategory.SIMPLE, stdoutLines, file, -1, -1, null); } - else { - // both stdout and stderr available, show as groups - if (file == null) { - errorTreeView.addMessage(MessageCategory.SIMPLE, stdoutLines, stdOutTitle, NonNavigatable.INSTANCE, null, null, null); - } - else { - errorTreeView.addMessage(MessageCategory.SIMPLE, new String[]{stdOutTitle}, file, -1, -1, null); - errorTreeView.addMessage(MessageCategory.SIMPLE, new String[]{""}, file, -1, -1, null); - errorTreeView.addMessage(MessageCategory.SIMPLE, stdoutLines, file, -1, -1, null); - } - } } } - if (!StringUtil.isEmpty(stderr)) { - final String[] stderrLines = StringUtil.splitByLines(stderr); - if (stderrLines.length > 0) { - if (file == null) { - errorTreeView.addMessage(MessageCategory.SIMPLE, stderrLines, stderrTitle, NonNavigatable.INSTANCE, null, null, null); - } - else { - errorTreeView.addMessage(MessageCategory.SIMPLE, new String[]{stderrTitle}, file, -1, -1, null); - errorTreeView.addMessage(MessageCategory.SIMPLE, ArrayUtil.EMPTY_STRING_ARRAY, file, -1, -1, null); - errorTreeView.addMessage(MessageCategory.SIMPLE, stderrLines, file, -1, -1, null); - } + } + if (!StringUtil.isEmpty(stderr)) { + final String[] stderrLines = StringUtil.splitByLines(stderr); + if (stderrLines.length > 0) { + if (file == null) { + errorTreeView.addMessage(MessageCategory.SIMPLE, stderrLines, stderrTitle, NonNavigatable.INSTANCE, null, null, null); + } + else { + errorTreeView.addMessage(MessageCategory.SIMPLE, new String[]{stderrTitle}, file, -1, -1, null); + errorTreeView.addMessage(MessageCategory.SIMPLE, ArrayUtil.EMPTY_STRING_ARRAY, file, -1, -1, null); + errorTreeView.addMessage(MessageCategory.SIMPLE, stderrLines, file, -1, -1, null); } } - errorTreeView - .addMessage(MessageCategory.SIMPLE, new String[]{"Process finished with exit code " + output.getExitCode()}, null, -1, -1, null); + } + errorTreeView + .addMessage(MessageCategory.SIMPLE, new String[]{"Process finished with exit code " + output.getExitCode()}, null, -1, -1, null); - if (activateWindow) { - ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW).activate(null); - } + if (activateWindow) { + ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW).activate(null); } }); } @@ -218,16 +212,13 @@ public class ExecutionHelper { @NotNull final Project myProject, @NotNull final String tabDisplayName) { CommandProcessor commandProcessor = CommandProcessor.getInstance(); - commandProcessor.executeCommand(myProject, new Runnable() { - @Override - public void run() { - final MessageView messageView = ServiceManager.getService(myProject, MessageView.class); - final Content content = ContentFactory.SERVICE.getInstance().createContent(errorTreeView, tabDisplayName, true); - messageView.getContentManager().addContent(content); - Disposer.register(content, errorTreeView); - messageView.getContentManager().setSelectedContent(content); - removeContents(content, myProject, tabDisplayName); - } + commandProcessor.executeCommand(myProject, () -> { + final MessageView messageView = ServiceManager.getService(myProject, MessageView.class); + final Content content = ContentFactory.SERVICE.getInstance().createContent(errorTreeView, tabDisplayName, true); + messageView.getContentManager().addContent(content); + Disposer.register(content, errorTreeView); + messageView.getContentManager().setSelectedContent(content); + removeContents(content, myProject, tabDisplayName); }, "Open message view", null); } @@ -252,13 +243,7 @@ public class ExecutionHelper { public static Collection findRunningConsoleByTitle(final Project project, @NotNull final NotNullFunction titleMatcher) { - return findRunningConsole(project, new NotNullFunction() { - @NotNull - @Override - public Boolean fun(RunContentDescriptor selectedContent) { - return titleMatcher.fun(selectedContent.getDisplayName()); - } - }); + return findRunningConsole(project, selectedContent -> titleMatcher.fun(selectedContent.getDisplayName())); } public static Collection findRunningConsole(@NotNull Project project, @@ -321,30 +306,24 @@ public class ExecutionHelper { final PopupChooserBuilder builder = new PopupChooserBuilder(list); builder.setTitle(selectDialogTitle); - builder.setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object selectedValue = list.getSelectedValue(); - if (selectedValue instanceof RunContentDescriptor) { - RunContentDescriptor descriptor = (RunContentDescriptor)selectedValue; - descriptorConsumer.consume(descriptor); - descriptorToFront(project, descriptor); - } + builder.setItemChoosenCallback(() -> { + final Object selectedValue = list.getSelectedValue(); + if (selectedValue instanceof RunContentDescriptor) { + RunContentDescriptor descriptor = (RunContentDescriptor)selectedValue; + descriptorConsumer.consume(descriptor); + descriptorToFront(project, descriptor); } }).createPopup().showInBestPositionFor(dataContext); } } private static void descriptorToFront(@NotNull final Project project, @NotNull final RunContentDescriptor descriptor) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ToolWindow toolWindow = ExecutionManager.getInstance(project).getContentManager().getToolWindowByDescriptor(descriptor); - if (toolWindow != null) { - toolWindow.show(null); - //noinspection ConstantConditions - toolWindow.getContentManager().setSelectedContent(descriptor.getAttachedContent()); - } + ApplicationManager.getApplication().invokeLater(() -> { + ToolWindow toolWindow = ExecutionManager.getInstance(project).getContentManager().getToolWindowByDescriptor(descriptor); + if (toolWindow != null) { + toolWindow.show(null); + //noinspection ConstantConditions + toolWindow.getContentManager().setSelectedContent(descriptor.getAttachedContent()); } }, project.getDisposed()); } @@ -379,12 +358,7 @@ public class ExecutionHelper { } else { if (mode.getTimeout() <= 0) { - process = new Runnable() { - @Override - public void run() { - processHandler.waitFor(); - } - }; + process = () -> processHandler.waitFor(); } else { process = createTimeLimitedExecutionProcess(processHandler, mode, presentableCmdline); @@ -419,15 +393,12 @@ public class ExecutionHelper { private ProgressIndicator myProgressIndicator; private final Semaphore mySemaphore = new Semaphore(); - private final Runnable myWaitThread = new Runnable() { - @Override - public void run() { - try { - processHandler.waitFor(); - } - finally { - mySemaphore.up(); - } + private final Runnable myWaitThread = () -> { + try { + processHandler.waitFor(); + } + finally { + mySemaphore.up(); } }; @@ -486,20 +457,17 @@ public class ExecutionHelper { return new Runnable() { private final Semaphore mySemaphore = new Semaphore(); - private final Runnable myProcessThread = new Runnable() { - @Override - public void run() { - try { - final boolean finished = processHandler.waitFor(1000 * mode.getTimeout()); - if (!finished) { - mode.getTimeoutCallback().consume(mode, presentableCmdline); - processHandler.destroyProcess(); - } - } - finally { - mySemaphore.up(); + private final Runnable myProcessThread = () -> { + try { + final boolean finished = processHandler.waitFor(1000 * mode.getTimeout()); + if (!finished) { + mode.getTimeoutCallback().consume(mode, presentableCmdline); + processHandler.destroyProcess(); } } + finally { + mySemaphore.up(); + } }; @Override diff --git a/platform/lang-impl/src/com/intellij/execution/ExecutionMode.java b/platform/lang-impl/src/com/intellij/execution/ExecutionMode.java index f58168aab2ad..331f822cef81 100644 --- a/platform/lang-impl/src/com/intellij/execution/ExecutionMode.java +++ b/platform/lang-impl/src/com/intellij/execution/ExecutionMode.java @@ -29,10 +29,7 @@ import java.util.List; * @author Roman.Chernyatchik */ public class ExecutionMode { - private static final PairConsumer NOOP_CONSUMER = new PairConsumer() { - @Override - public void consume(ExecutionMode mode, String s) { - } + private static final PairConsumer NOOP_CONSUMER = (mode, s) -> { }; private final boolean myCancelable; private final String myTitle; diff --git a/platform/lang-impl/src/com/intellij/execution/ExecutionModes.java b/platform/lang-impl/src/com/intellij/execution/ExecutionModes.java index 331cdf6eb084..92fcd0f62b23 100644 --- a/platform/lang-impl/src/com/intellij/execution/ExecutionModes.java +++ b/platform/lang-impl/src/com/intellij/execution/ExecutionModes.java @@ -27,12 +27,9 @@ import javax.swing.*; */ public class ExecutionModes { private static final Logger LOG = Logger.getInstance(ExecutionMode.class); - private static final PairConsumer DEFAULT_TIMEOUT_CALLBACK = new PairConsumer() { - @Override - public void consume(ExecutionMode mode, String presentableCmdLine) { - final String msg = "Timeout (" + mode.getTimeout() + " sec) on executing: " + presentableCmdLine; - LOG.error(msg); - } + private static final PairConsumer DEFAULT_TIMEOUT_CALLBACK = (mode, presentableCmdLine) -> { + final String msg = "Timeout (" + mode.getTimeout() + " sec) on executing: " + presentableCmdLine; + LOG.error(msg); }; /** diff --git a/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java b/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java index ecd3cfa9670e..f7ac13474afd 100644 --- a/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java +++ b/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java @@ -140,12 +140,8 @@ public class RunContentExecutor implements Disposable { } public void activateToolWindow() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.RUN).activate(null); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.RUN).activate(null)); } private static JComponent createConsolePanel(ConsoleView view, ActionGroup actions) { diff --git a/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java b/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java index 8c6fd2b08af1..1cf556a17d5e 100644 --- a/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java +++ b/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java @@ -79,12 +79,7 @@ public class TestStateStorage implements Disposable { } catch (IOException e) { LOG.error(e); } - myMapFlusher = FlushingDaemon.everyFiveSeconds(new Runnable() { - @Override - public void run() { - flushMap(); - } - }); + myMapFlusher = FlushingDaemon.everyFiveSeconds(() -> flushMap()); } diff --git a/platform/lang-impl/src/com/intellij/execution/actions/BaseRunConfigurationAction.java b/platform/lang-impl/src/com/intellij/execution/actions/BaseRunConfigurationAction.java index 3cc38f8d8a55..ab2dfbeaea5c 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/BaseRunConfigurationAction.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/BaseRunConfigurationAction.java @@ -174,12 +174,7 @@ public abstract class BaseRunConfigurationAction extends ActionGroup { private void perform(final ConfigurationFromContext configurationFromContext, final ConfigurationContext context) { RunnerAndConfigurationSettings configurationSettings = configurationFromContext.getConfigurationSettings(); context.setConfiguration(configurationSettings); - configurationFromContext.onFirstRun(context, new Runnable() { - @Override - public void run() { - perform(context); - } - }); + configurationFromContext.onFirstRun(context, () -> perform(context)); } protected abstract void perform(ConfigurationContext context); diff --git a/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java b/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java index 797a2afffa12..88165ad30104 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java @@ -475,25 +475,17 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { if (myAction.myEditConfiguration) { final Object o = wrapper.getValue(); if (o instanceof RunnerAndConfigurationSettingsImpl) { - return doFinalStep(new Runnable() { - @Override - public void run() { - myAction.editConfiguration(myProject, (RunnerAndConfigurationSettings)o); - } - }); + return doFinalStep(() -> myAction.editConfiguration(myProject, (RunnerAndConfigurationSettings)o)); } } if (finalChoice && wrapper.available(myAction.getExecutor())) { - return doFinalStep(new Runnable() { - @Override - public void run() { - if (myAction.getExecutor() == myAction.myAlternativeExecutor) { - PropertiesComponent.getInstance().setValue(myAction.myAddKey, Boolean.toString(true)); - } - - wrapper.perform(myProject, myAction.getExecutor(), DataManager.getInstance().getDataContext()); + return doFinalStep(() -> { + if (myAction.getExecutor() == myAction.myAlternativeExecutor) { + PropertiesComponent.getInstance().setValue(myAction.myAddKey, Boolean.toString(true)); } + + wrapper.perform(myProject, myAction.getExecutor(), DataManager.getInstance().getDataContext()); }); } else { @@ -620,12 +612,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { @Override public PopupStep onChosen(final ActionWrapper selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - selectedValue.perform(); - } - }); + return doFinalStep(() -> selectedValue.perform()); } @Override @@ -749,12 +736,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { return; for (final Object item : myListPopup.getListStep().getValues()) { if (item instanceof ItemWrapper && ((ItemWrapper)item).getMnemonic() == myNumber) { - myListPopup.setFinalRunnable(new Runnable() { - @Override - public void run() { - execute((ItemWrapper)item, myExecutor); - } - }); + myListPopup.setFinalRunnable(() -> execute((ItemWrapper)item, myExecutor)); myListPopup.closeOk(null); } } @@ -903,21 +885,13 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { if (finalChoice) { if (myPopup.myEditConfiguration) { final RunnerAndConfigurationSettings settings = selectedValue.getSettings(); - return doFinalStep(new Runnable() { - @Override - public void run() { - myPopup.editConfiguration(myProject, settings); - } - }); + return doFinalStep(() -> myPopup.editConfiguration(myProject, settings)); } - return doFinalStep(new Runnable() { - @Override - public void run() { - RunnerAndConfigurationSettings settings = selectedValue.getSettings(); - RunManagerEx.getInstanceEx(myProject).setSelectedConfiguration(settings); - ExecutionUtil.runConfiguration(settings, myExecutorProvider.getExecutor()); - } + return doFinalStep(() -> { + RunnerAndConfigurationSettings settings = selectedValue.getSettings(); + RunManagerEx.getInstanceEx(myProject).setSelectedConfiguration(settings); + ExecutionUtil.runConfiguration(settings, myExecutorProvider.getExecutor()); }); } else { return selectedValue; @@ -967,13 +941,10 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { super.init(); } }.showAndGet()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration(); - if (configuration != null) { - ExecutionUtil.runConfiguration(configuration, executor); - } + ApplicationManager.getApplication().invokeLater(() -> { + RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration(); + if (configuration != null) { + ExecutionUtil.runConfiguration(configuration, executor); } }, project.getDisposed()); } diff --git a/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java b/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java index d52448442ef2..349482ed9aea 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java @@ -162,18 +162,10 @@ class StopAction extends DumbAwareAction implements AnAction.TransparentUpdate { JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list) .setMovable(true) .setTitle(handlerItems.first.size() == 1 ? "Confirm process stop" : "Stop process") - .setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return ((HandlerItem)o).displayName; - } - }) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - HandlerItem item = (HandlerItem)list.getSelectedValue(); - if (item != null) item.stop(); - } + .setFilteringEnabled(o -> ((HandlerItem)o).displayName) + .setItemChoosenCallback(() -> { + HandlerItem item = (HandlerItem)list.getSelectedValue(); + if (item != null) item.stop(); }) .setRequestFocus(true) .createPopup(); diff --git a/platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfiguration.java b/platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfiguration.java index 8b503902d801..8b1e46c3152d 100644 --- a/platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfiguration.java +++ b/platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfiguration.java @@ -35,12 +35,9 @@ import org.jetbrains.annotations.Nullable; import java.util.*; public class CompoundRunConfiguration extends RunConfigurationBase implements WithoutOwnBeforeRunSteps, Cloneable { - static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(RunConfiguration o1, RunConfiguration o2) { - int i = o1.getType().getDisplayName().compareTo(o2.getType().getDisplayName()); - return (i != 0) ? i : o1.getName().compareTo(o2.getName()); - } + static final Comparator COMPARATOR = (o1, o2) -> { + int i = o1.getType().getDisplayName().compareTo(o2.getType().getDisplayName()); + return (i != 0) ? i : o1.getName().compareTo(o2.getName()); }; private Set> myPairs = new HashSet>(); private Set mySetToRun = new TreeSet(COMPARATOR); @@ -92,17 +89,14 @@ public class CompoundRunConfiguration extends RunConfigurationBase implements Wi @Nullable @Override public ExecutionResult execute(final Executor executor, @NotNull ProgramRunner runner) throws ExecutionException { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - RunManagerImpl manager = RunManagerImpl.getInstanceImpl(getProject()); - for (RunConfiguration configuration : getSetToRun()) { - RunnerAndConfigurationSettings settings = new RunnerAndConfigurationSettingsImpl(manager, configuration, false); - ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings); - if (builder != null) { - ExecutionManager.getInstance(getProject()) - .restartRunProfile(builder.activeTarget().dataContext(null).build()); - } + ApplicationManager.getApplication().invokeLater(() -> { + RunManagerImpl manager = RunManagerImpl.getInstanceImpl(getProject()); + for (RunConfiguration configuration : getSetToRun()) { + RunnerAndConfigurationSettings settings = new RunnerAndConfigurationSettingsImpl(manager, configuration, false); + ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings); + if (builder != null) { + ExecutionManager.getInstance(getProject()) + .restartRunProfile(builder.activeTarget().dataContext(null).build()); } } }); diff --git a/platform/lang-impl/src/com/intellij/execution/configuration/EnvironmentVariablesTextFieldWithBrowseButton.java b/platform/lang-impl/src/com/intellij/execution/configuration/EnvironmentVariablesTextFieldWithBrowseButton.java index bd68e978818a..e12b09309cc8 100644 --- a/platform/lang-impl/src/com/intellij/execution/configuration/EnvironmentVariablesTextFieldWithBrowseButton.java +++ b/platform/lang-impl/src/com/intellij/execution/configuration/EnvironmentVariablesTextFieldWithBrowseButton.java @@ -138,16 +138,13 @@ public class EnvironmentVariablesTextFieldWithBrowseButton extends TextFieldWith } private static List convertToVariables(Map map, final boolean readOnly) { - return ContainerUtil.map(map.entrySet(), new Function, EnvironmentVariable>() { - @Override - public EnvironmentVariable fun(Map.Entry entry) { - return new EnvironmentVariable(entry.getKey(), entry.getValue(), readOnly) { - @Override - public boolean getNameIsWriteable() { - return !readOnly; - } - }; - } + return ContainerUtil.map(map.entrySet(), entry -> { + return new EnvironmentVariable(entry.getKey(), entry.getValue(), readOnly) { + @Override + public boolean getNameIsWriteable() { + return !readOnly; + } + }; }); } diff --git a/platform/lang-impl/src/com/intellij/execution/console/ConsoleHistoryController.java b/platform/lang-impl/src/com/intellij/execution/console/ConsoleHistoryController.java index dc6040e4a300..20cf8683c6c5 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/ConsoleHistoryController.java +++ b/platform/lang-impl/src/com/intellij/execution/console/ConsoleHistoryController.java @@ -641,12 +641,9 @@ public class ConsoleHistoryController { } catch (final IOException e) { LOG.warn(e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String message = String.format("Unable to open '%s/%s'\nReason: %s", rootType.getId(), pathName, e.getLocalizedMessage()); - Messages.showErrorDialog(message, "Unable to Open File"); - } + ApplicationManager.getApplication().invokeLater(() -> { + String message = String.format("Unable to open '%s/%s'\nReason: %s", rootType.getId(), pathName, e.getLocalizedMessage()); + Messages.showErrorDialog(message, "Unable to Open File"); }); return null; } diff --git a/platform/lang-impl/src/com/intellij/execution/console/DuplexConsoleView.java b/platform/lang-impl/src/com/intellij/execution/console/DuplexConsoleView.java index 69b8fafdec69..d791d7838b82 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/DuplexConsoleView.java +++ b/platform/lang-impl/src/com/intellij/execution/console/DuplexConsoleView.java @@ -330,12 +330,7 @@ public class DuplexConsoleView ext public void setSelected(final AnActionEvent event, final boolean flag) { enableConsole(!flag); setStoredState(!flag); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - update(event); - } - }); + ApplicationManager.getApplication().invokeLater(() -> update(event)); } @Override diff --git a/platform/lang-impl/src/com/intellij/execution/console/FoldLinesLikeThis.java b/platform/lang-impl/src/com/intellij/execution/console/FoldLinesLikeThis.java index fdefc55da6b4..6d3854bbb1cd 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/FoldLinesLikeThis.java +++ b/platform/lang-impl/src/com/intellij/execution/console/FoldLinesLikeThis.java @@ -71,12 +71,7 @@ public class FoldLinesLikeThis extends DumbAwareAction { @Override public void reset() { super.reset(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - addRule(selection); - } - }); + UIUtil.invokeLaterIfNeeded(() -> addRule(selection)); } }); final ConsoleView consoleView = e.getData(LangDataKeys.CONSOLE_VIEW); diff --git a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java index 6327da951da4..f0eccd23db66 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java @@ -136,11 +136,8 @@ public class LanguageConsoleImpl extends ConsoleViewImpl implements LanguageCons myBusConnection = getProject().getMessageBus().connect(); // action shortcuts are not yet registered - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - installEditorFactoryListener(); - } + ApplicationManager.getApplication().invokeLater(() -> { + installEditorFactoryListener(); }, getProject().getDisposed()); } @@ -339,12 +336,8 @@ public class LanguageConsoleImpl extends ConsoleViewImpl implements LanguageCons String result = addTextRangeToHistory(textRange, editor, preserveMarkup); if (erase) { - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset()); - } - }); + DocumentUtil.writeInRunUndoTransparentAction( + () -> editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset())); } // always scroll to end on user input scrollToEnd(); @@ -521,12 +514,7 @@ public class LanguageConsoleImpl extends ConsoleViewImpl implements LanguageCons } public void setInputText(@NotNull final String query) { - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - myConsoleEditor.getDocument().setText(StringUtil.convertLineSeparators(query)); - } - }); + DocumentUtil.writeInRunUndoTransparentAction(() -> myConsoleEditor.getDocument().setText(StringUtil.convertLineSeparators(query))); } boolean isHistoryViewerForceAdditionalColumnsUsage() { diff --git a/platform/lang-impl/src/com/intellij/execution/console/RunIdeConsoleAction.java b/platform/lang-impl/src/com/intellij/execution/console/RunIdeConsoleAction.java index 577c0814f9bd..3dfd37fe5261 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/RunIdeConsoleAction.java +++ b/platform/lang-impl/src/com/intellij/execution/console/RunIdeConsoleAction.java @@ -86,17 +86,13 @@ public class RunIdeConsoleAction extends DumbAwareAction { } DefaultActionGroup actions = new DefaultActionGroup( - ContainerUtil.map(languages, new NotNullFunction() { - @NotNull - @Override - public AnAction fun(final String language) { - return new DumbAwareAction(language) { - @Override - public void actionPerformed(@NotNull AnActionEvent e) { - runConsole(e, language); - } - }; - } + ContainerUtil.map(languages, (NotNullFunction)language -> { + return new DumbAwareAction(language) { + @Override + public void actionPerformed(@NotNull AnActionEvent e1) { + runConsole(e1, language); + } + }; }) ); JBPopupFactory.getInstance().createActionGroupPopup("Script Engine", actions, e.getDataContext(), JBPopupFactory.ActionSelectionAid.NUMBERING, false). diff --git a/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java b/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java index 36dc51e15be9..cd73d9450621 100644 --- a/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java +++ b/platform/lang-impl/src/com/intellij/execution/filters/impl/MultipleFilesHyperlinkInfo.java @@ -88,12 +88,9 @@ class MultipleFilesHyperlinkInfo extends HyperlinkInfoBase implements FileHyperl list.setCellRenderer(new GotoFileCellRenderer(width)); JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle("Choose Target File") - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - VirtualFile file = ((PsiFile)list.getSelectedValue()).getVirtualFile(); - new OpenFileHyperlinkInfo(myProject, file, myLineNumber).navigate(project); - } + .setItemChoosenCallback(() -> { + VirtualFile file = ((PsiFile)list.getSelectedValue()).getVirtualFile(); + new OpenFileHyperlinkInfo(myProject, file, myLineNumber).navigate(project); }) .createPopup(); if (hyperlinkLocationPoint != null) { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java index f46811c0a2d1..c8efc8b6b79e 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java @@ -168,12 +168,9 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo myPendingFoldRegions.clear(); final FoldingModel model = myEditor.getFoldingModel(); - model.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : model.getAllFoldRegions()) { - model.removeFoldRegion(region); - } + model.runBatchFoldingOperation(() -> { + for (FoldRegion region : model.getAllFoldRegions()) { + model.removeFoldRegion(region); } }); myFolding.clear(); @@ -343,16 +340,13 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo @Override public void exitDumbMode() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myEditor == null || project.isDisposed() || DumbService.getInstance(project).isDumb()) return; - - DocumentEx document = myEditor.getDocument(); - if (myLastStamp != document.getModificationStamp()) { - clearHyperlinkAndFoldings(); - highlightHyperlinksAndFoldings(document.createRangeMarker(0, 0)); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myEditor == null || project.isDisposed() || DumbService.getInstance(project).isDumb()) return; + + DocumentEx document = myEditor.getDocument(); + if (myLastStamp != document.getModificationStamp()) { + clearHyperlinkAndFoldings(); + highlightHyperlinksAndFoldings(document.createRangeMarker(0, 0)); } }); } @@ -479,12 +473,7 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo private void performLaterWhenNoDeferredOutput(final Runnable runnable) { if (mySpareTimeAlarm.isDisposed()) return; mySpareTimeAlarm.addRequest( - new Runnable() { - @Override - public void run() { - performWhenNoDeferredOutput(runnable); - } - }, + () -> performWhenNoDeferredOutput(runnable), 100, ModalityState.stateForComponent(myJLayeredPane) ); @@ -703,20 +692,17 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo } final int documentTextLength = document.getTextLength(); if (documentTextLength > 0) { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - document.setInBulkUpdate(true); - try { - myInDocumentUpdate = true; - myDocumentClearing = true; - document.deleteString(0, documentTextLength); - } - finally { - document.setInBulkUpdate(false); - myDocumentClearing = false; - myInDocumentUpdate = false; - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + document.setInBulkUpdate(true); + try { + myInDocumentUpdate = true; + myDocumentClearing = true; + document.deleteString(0, documentTextLength); + } + finally { + document.setInBulkUpdate(false); + myDocumentClearing = false; + myInDocumentUpdate = false; } }, null, DocCommandGroupId.noneGroupId(document)); } @@ -745,38 +731,35 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo final Document document = myEditor.getDocument(); final RangeMarker lastProcessedOutput = document.createRangeMarker(document.getTextLength(), document.getTextLength()); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { + CommandProcessor.getInstance().executeCommand(myProject, () -> { + if (!shouldStickToEnd) { + myEditor.getScrollingModel().accumulateViewportChanges(); + } + try { + myInDocumentUpdate = true; + String[] strings = addedText.split("\\r", -1); // limit must be any negative number to avoid discarding of trailing empty strings + for (int i = 0; i < strings.length - 1; i++) { + document.insertString(document.getTextLength(), strings[i]); + int lastLine = document.getLineCount() - 1; + if (lastLine >= 0) { + ConsoleUtil.updateTokensOnTextRemoval(myTokens, document.getTextLength(), document.getTextLength() + 1); + document.deleteString(document.getLineStartOffset(lastLine), document.getTextLength()); + } + } + if (strings.length > 0) { + document.insertString(document.getTextLength(), strings[strings.length - 1]); + myContentSize -= strings.length - 1; + } + } + finally { + myInDocumentUpdate = false; if (!shouldStickToEnd) { - myEditor.getScrollingModel().accumulateViewportChanges(); + myEditor.getScrollingModel().flushViewportChanges(); } - try { - myInDocumentUpdate = true; - String[] strings = addedText.split("\\r", -1); // limit must be any negative number to avoid discarding of trailing empty strings - for (int i = 0; i < strings.length - 1; i++) { - document.insertString(document.getTextLength(), strings[i]); - int lastLine = document.getLineCount() - 1; - if (lastLine >= 0) { - ConsoleUtil.updateTokensOnTextRemoval(myTokens, document.getTextLength(), document.getTextLength() + 1); - document.deleteString(document.getLineStartOffset(lastLine), document.getTextLength()); - } - } - if (strings.length > 0) { - document.insertString(document.getTextLength(), strings[strings.length - 1]); - myContentSize -= strings.length - 1; - } - } - finally { - myInDocumentUpdate = false; - if (!shouldStickToEnd) { - myEditor.getScrollingModel().flushViewportChanges(); - } - } - if (!contentTypes.isEmpty()) { - for (ChangeListener each : myListeners) { - each.contentAdded(contentTypes); - } + } + if (!contentTypes.isEmpty()) { + for (ChangeListener each : myListeners) { + each.contentAdded(contentTypes); } } }, null, DocCommandGroupId.noneGroupId(document)); @@ -798,12 +781,7 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo new EditorNotificationPanel().text("Too much output to process").icon(AllIcons.General.ExclMark); final Alarm tooMuchOutputAlarm = new Alarm(); //show the notification with a delay to avoid blinking when "too much output" ceases quickly - tooMuchOutputAlarm.addRequest(new Runnable() { - @Override - public void run() { - add(comp, BorderLayout.NORTH); - } - }, 300); + tooMuchOutputAlarm.addRequest(() -> add(comp, BorderLayout.NORTH), 300); performWhenNoDeferredOutput(new Runnable() { @Override public void run() { @@ -852,12 +830,7 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo myPendingFoldRegions.clear(); myFolding.clear(); myFoldingAlarm.cancelAllRequests(); - myEditor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - myEditor.getFoldingModel().clearFoldRegions(); - } - }); + myEditor.getFoldingModel().runBatchFoldingOperation(() -> myEditor.getFoldingModel().clearFoldRegions()); cancelHeavyAlarm(); } @@ -874,16 +847,13 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo if (textToSend == null) { return; } - myFlushUserInputAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myState.isRunning()) { - try { - // this may block forever, see IDEA-54340 - myState.sendUserInput(textToSend); - } - catch (IOException ignored) { - } + myFlushUserInputAlarm.addRequest(() -> { + if (myState.isRunning()) { + try { + // this may block forever, see IDEA-54340 + myState.sendUserInput(textToSend); + } + catch (IOException ignored) { } } }, 0); @@ -1120,12 +1090,7 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo } finally { if (myHeavyAlarm.isEmpty()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myJLayeredPane.finishUpdating(); - } - }); + SwingUtilities.invokeLater(() -> myJLayeredPane.finishUpdating()); } } } @@ -1163,32 +1128,26 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo myPendingFoldRegions.addAll(toAdd); myFoldingAlarm.cancelAllRequests(); - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (myEditor == null || myEditor.isDisposed()) { - return; - } + final Runnable runnable = () -> { + if (myEditor == null || myEditor.isDisposed()) { + return; + } + assertIsDispatchThread(); + final FoldingModel model = myEditor.getFoldingModel(); + final Runnable operation = () -> { assertIsDispatchThread(); - final FoldingModel model = myEditor.getFoldingModel(); - final Runnable operation = new Runnable() { - @Override - public void run() { - assertIsDispatchThread(); - for (FoldRegion region : myPendingFoldRegions) { - region.setExpanded(false); - model.addFoldRegion(region); - } - myPendingFoldRegions.clear(); - } - }; - if (immediately) { - model.runBatchFoldingOperation(operation); - } - else { - model.runBatchFoldingOperationDoNotCollapseCaret(operation); + for (FoldRegion region : myPendingFoldRegions) { + region.setExpanded(false); + model.addFoldRegion(region); } + myPendingFoldRegions.clear(); + }; + if (immediately) { + model.runBatchFoldingOperation(operation); + } + else { + model.runBatchFoldingOperationDoNotCollapseCaret(operation); } }; if (immediately || myPendingFoldRegions.size() > 100) { @@ -1539,23 +1498,20 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo return null; } - return EditorHyperlinkSupport.getNextOccurrence(myEditor, delta, new Consumer() { - @Override - public void consume(RangeHighlighter next) { - int offset = next.getStartOffset(); - scrollTo(offset); - final HyperlinkInfo hyperlinkInfo = EditorHyperlinkSupport.getHyperlinkInfo(next); - if (hyperlinkInfo instanceof BrowserHyperlinkInfo) { - return; - } - if (hyperlinkInfo instanceof HyperlinkInfoBase) { - VisualPosition position = myEditor.offsetToVisualPosition(offset); - Point point = myEditor.visualPositionToXY(new VisualPosition(position.getLine() + 1, position.getColumn())); - ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(myEditor.getContentComponent(), point)); - } - else if (hyperlinkInfo != null) { - hyperlinkInfo.navigate(myProject); - } + return EditorHyperlinkSupport.getNextOccurrence(myEditor, delta, next -> { + int offset = next.getStartOffset(); + scrollTo(offset); + final HyperlinkInfo hyperlinkInfo = EditorHyperlinkSupport.getHyperlinkInfo(next); + if (hyperlinkInfo instanceof BrowserHyperlinkInfo) { + return; + } + if (hyperlinkInfo instanceof HyperlinkInfoBase) { + VisualPosition position = myEditor.offsetToVisualPosition(offset); + Point point = myEditor.visualPositionToXY(new VisualPosition(position.getLine() + 1, position.getColumn())); + ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(myEditor.getContentComponent(), point)); + } + else if (hyperlinkInfo != null) { + hyperlinkInfo.navigate(myProject); } }); } @@ -1622,18 +1578,15 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo final String placeholder = myCommandLineFolding.getPlaceholder(0); final FoldingModel foldingModel = myEditor.getFoldingModel(); final int firstLineEnd = myEditor.getDocument().getLineEndOffset(0); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion[] regions = foldingModel.getAllFoldRegions(); - if (regions.length > 0 && regions[0].getStartOffset() == 0 && regions[0].getEndOffset() == firstLineEnd) { - foldingModel.removeFoldRegion(regions[0]); - } - if (placeholder != null) { - FoldRegion foldRegion = foldingModel.addFoldRegion(0, firstLineEnd, placeholder); - if (foldRegion != null) { - foldRegion.setExpanded(false); - } + foldingModel.runBatchFoldingOperation(() -> { + FoldRegion[] regions = foldingModel.getAllFoldRegions(); + if (regions.length > 0 && regions[0].getStartOffset() == 0 && regions[0].getEndOffset() == firstLineEnd) { + foldingModel.removeFoldRegion(regions[0]); + } + if (placeholder != null) { + FoldRegion foldRegion = foldingModel.addFoldRegion(0, firstLineEnd, placeholder); + if (foldRegion != null) { + foldRegion.setExpanded(false); } } }); diff --git a/platform/lang-impl/src/com/intellij/execution/impl/EditConfigurationsDialog.java b/platform/lang-impl/src/com/intellij/execution/impl/EditConfigurationsDialog.java index cce960f33a50..a05f94438821 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/EditConfigurationsDialog.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/EditConfigurationsDialog.java @@ -51,12 +51,7 @@ public class EditConfigurationsDialog extends SingleConfigurableEditor implement public void show() { // run configurations don't support dumb mode yet, but some code inside them may trigger root change and start it // so let it be modal to prevent IndexNotReadyException from the configuration editors - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - EditConfigurationsDialog.super.show(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> EditConfigurationsDialog.super.show()); } public void addRunConfiguration(@NotNull final ConfigurationFactory factory) { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java index eccc9a9c9dd7..e673f0458300 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java @@ -583,13 +583,10 @@ public class ExecutionManagerImpl extends ExecutionManager implements Disposable @Override public void processTerminated(ProcessEvent event) { if (myProject.isDisposed()) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - RunnerLayoutUi ui = myDescriptor.getRunnerLayoutUi(); - if (ui != null && !ui.isDisposed()) { - ui.updateActionsNow(); - } + ApplicationManager.getApplication().invokeLater(() -> { + RunnerLayoutUi ui = myDescriptor.getRunnerLayoutUi(); + if (ui != null && !ui.isDisposed()) { + ui.updateActionsNow(); } }, ModalityState.any()); diff --git a/platform/lang-impl/src/com/intellij/execution/impl/NewRunConfigurationPopup.java b/platform/lang-impl/src/com/intellij/execution/impl/NewRunConfigurationPopup.java index 0fde711e03b0..cb5defd54987 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/NewRunConfigurationPopup.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/NewRunConfigurationPopup.java @@ -91,12 +91,7 @@ public class NewRunConfigurationPopup { private ListPopupStep getSupStep(final ConfigurationType type) { final ConfigurationFactory[] factories = type.getConfigurationFactories(); - Arrays.sort(factories, new Comparator() { - @Override - public int compare(final ConfigurationFactory factory1, final ConfigurationFactory factory2) { - return factory1.getName().compareToIgnoreCase(factory2.getName()); - } - }); + Arrays.sort(factories, (factory1, factory2) -> factory1.getName().compareToIgnoreCase(factory2.getName())); return new BaseListPopupStep( ExecutionBundle.message("add.new.run.configuration.action.name", type.getDisplayName()), factories) { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java index 94778ea7f7fb..796910616b68 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java @@ -297,24 +297,21 @@ class RunConfigurable extends BaseConfigurable { protected RunConfigurable selectConfigurableOnShow(final boolean option) { if (!option) return this; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isDisposed) return; + SwingUtilities.invokeLater(() -> { + if (isDisposed) return; - myTree.requestFocusInWindow(); - final RunnerAndConfigurationSettings settings = getRunManager().getSelectedConfiguration(); - if (settings != null) { - if (selectConfiguration(settings.getConfiguration())) { - return; - } + myTree.requestFocusInWindow(); + final RunnerAndConfigurationSettings settings = getRunManager().getSelectedConfiguration(); + if (settings != null) { + if (selectConfiguration(settings.getConfiguration())) { + return; } - else { - mySelectedConfigurable = null; - } - //TreeUtil.selectInTree(defaults, true, myTree); - drawPressAddButtonMessage(null); } + else { + mySelectedConfigurable = null; + } + //TreeUtil.selectInTree(defaults, true, myTree); + drawPressAddButtonMessage(null); }); return this; } @@ -401,12 +398,7 @@ class RunConfigurable extends BaseConfigurable { myRightPanel.add(BorderLayout.CENTER, configurableComponent); if (configurable instanceof SingleConfigurationConfigurable) { myRightPanel.add(((SingleConfigurationConfigurable)configurable).getValidationComponent(), BorderLayout.SOUTH); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ((SingleConfigurationConfigurable)configurable).updateWarning(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ((SingleConfigurationConfigurable)configurable).updateWarning()); if (configurableComponent != null) { DataProvider dataProvider = DataManager.getDataProvider(configurableComponent); if (dataProvider != null) { @@ -420,23 +412,20 @@ class RunConfigurable extends BaseConfigurable { private void sortTopLevelBranches() { List expandedPaths = TreeUtil.collectExpandedPaths(myTree); - TreeUtil.sort(myRoot, new Comparator() { - @Override - public int compare(final Object o1, final Object o2) { - final Object userObject1 = ((DefaultMutableTreeNode)o1).getUserObject(); - final Object userObject2 = ((DefaultMutableTreeNode)o2).getUserObject(); - if (userObject1 instanceof ConfigurationType && userObject2 instanceof ConfigurationType) { - return ((ConfigurationType)userObject1).getDisplayName().compareTo(((ConfigurationType)userObject2).getDisplayName()); - } - else if (userObject1 == DEFAULTS && userObject2 instanceof ConfigurationType) { - return 1; - } - else if (userObject2 == DEFAULTS && userObject1 instanceof ConfigurationType) { - return -1; - } - - return 0; + TreeUtil.sort(myRoot, (o1, o2) -> { + final Object userObject1 = ((DefaultMutableTreeNode)o1).getUserObject(); + final Object userObject2 = ((DefaultMutableTreeNode)o2).getUserObject(); + if (userObject1 instanceof ConfigurationType && userObject2 instanceof ConfigurationType) { + return ((ConfigurationType)userObject1).getDisplayName().compareTo(((ConfigurationType)userObject2).getDisplayName()); } + else if (userObject1 == DEFAULTS && userObject2 instanceof ConfigurationType) { + return 1; + } + else if (userObject2 == DEFAULTS && userObject1 instanceof ConfigurationType) { + return -1; + } + + return 0; }); TreeUtil.restoreExpandedPaths(myTree, expandedPaths); } @@ -938,12 +927,7 @@ class RunConfigurable extends BaseConfigurable { } private void setupDialogBounds() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - UIUtil.setupEnclosingDialogBounds(myWholePanel); - } - }); + SwingUtilities.invokeLater(() -> UIUtil.setupEnclosingDialogBounds(myWholePanel)); } @Nullable @@ -1139,29 +1123,14 @@ class RunConfigurable extends BaseConfigurable { private void showAddPopup(final boolean showApplicableTypesOnly) { ConfigurationType[] allTypes = getRunManager().getConfigurationFactories(false); final List configurationTypes = getTypesToShow(showApplicableTypesOnly, allTypes); - Collections.sort(configurationTypes, new Comparator() { - @Override - public int compare(final ConfigurationType type1, final ConfigurationType type2) { - return type1.getDisplayName().compareToIgnoreCase(type2.getDisplayName()); - } - }); + Collections.sort(configurationTypes, (type1, type2) -> type1.getDisplayName().compareToIgnoreCase(type2.getDisplayName())); final int hiddenCount = allTypes.length - configurationTypes.size(); if (hiddenCount > 0) { configurationTypes.add(null); } final ListPopup popup = NewRunConfigurationPopup.createAddPopup(configurationTypes, hiddenCount + " items more (irrelevant)...", - new Consumer() { - @Override - public void consume(ConfigurationFactory factory) { - createNewConfiguration(factory); - } - }, getSelectedConfigurationType(), new Runnable() { - @Override - public void run() { - showAddPopup(false); - } - }, true); + factory -> createNewConfiguration(factory), getSelectedConfigurationType(), () -> showAddPopup(false), true); //new TreeSpeedSearch(myTree); popup.showUnderneathOf(myToolbarDecorator.getActionsPanel()); } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java index 40193d51c528..444c29053026 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java @@ -239,16 +239,13 @@ extends BeforeRunTaskProvider { + try { + environment.getRunner().execute(environment); + } + catch (ExecutionException e) { + targetDone.up(); + LOG.error(e); } }, ModalityState.NON_MODAL); } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java index 03e7a51c96e1..dab3ff4b4122 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java @@ -42,15 +42,12 @@ public class RunnerAndConfigurationSettingsImpl implements JDOMExternalizable, C @NonNls private static final String RUNNER_ID = "RunnerId"; - private static final Comparator RUNNER_COMPARATOR = new Comparator() { - @Override - public int compare(@NotNull Element o1, @NotNull Element o2) { - String attributeValue1 = o1.getAttributeValue(RUNNER_ID); - if (attributeValue1 == null) { - return 1; - } - return StringUtil.compare(attributeValue1, o2.getAttributeValue(RUNNER_ID), false); + private static final Comparator RUNNER_COMPARATOR = (o1, o2) -> { + String attributeValue1 = o1.getAttributeValue(RUNNER_ID); + if (attributeValue1 == null) { + return 1; } + return StringUtil.compare(attributeValue1, o2.getAttributeValue(RUNNER_ID), false); }; @NonNls diff --git a/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java b/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java index 3136493baa63..d3e6ce8c4f40 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java @@ -175,13 +175,9 @@ public final class SingleConfigurationConfigurable { + quickFix.run(); + getEditor().resetFrom(fixedSettings); }; } else { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/statistics/AbstractRunConfigurationTypeUsagesCollector.java b/platform/lang-impl/src/com/intellij/execution/impl/statistics/AbstractRunConfigurationTypeUsagesCollector.java index f2d3193f7862..21e272f7a532 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/statistics/AbstractRunConfigurationTypeUsagesCollector.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/statistics/AbstractRunConfigurationTypeUsagesCollector.java @@ -62,11 +62,8 @@ public abstract class AbstractRunConfigurationTypeUsagesCollector extends Abstra } } }); - return ContainerUtil.map2Set(runConfigurationTypes, new Function() { - @Override - public UsageDescriptor fun(String runConfigurationType) { - return new UsageDescriptor(runConfigurationType, 1); - } + return ContainerUtil.map2Set(runConfigurationTypes, runConfigurationType -> { + return new UsageDescriptor(runConfigurationType, 1); }); } } diff --git a/platform/lang-impl/src/com/intellij/execution/lineMarker/ExecutorAction.java b/platform/lang-impl/src/com/intellij/execution/lineMarker/ExecutorAction.java index 4f2dd11333bf..eb79126656aa 100644 --- a/platform/lang-impl/src/com/intellij/execution/lineMarker/ExecutorAction.java +++ b/platform/lang-impl/src/com/intellij/execution/lineMarker/ExecutorAction.java @@ -39,12 +39,10 @@ import java.util.List; public class ExecutorAction extends AnAction { @NotNull public static AnAction[] getActions(final int order) { - return ContainerUtil.map2Array(ExecutorRegistry.getInstance().getRegisteredExecutors(), AnAction.class, new Function() { - @Override - public AnAction fun(Executor executor) { - return new ExecutorAction(ActionManager.getInstance().getAction(executor.getContextActionId()), executor, order); - } - }); + return ContainerUtil.map2Array(ExecutorRegistry.getInstance().getRegisteredExecutors(), AnAction.class, + (Function)executor -> { + return new ExecutorAction(ActionManager.getInstance().getAction(executor.getContextActionId()), executor, order); + }); } private final AnAction myOrigin; @@ -77,11 +75,8 @@ public class ExecutorAction extends AnAction { if (context.getLocation() == null) return null; List> producers = RunConfigurationProducer.getProducers(context.getProject()); List list = ContainerUtil.mapNotNull(producers, - new Function, ConfigurationFromContext>() { - @Override - public ConfigurationFromContext fun(RunConfigurationProducer producer) { - return createConfiguration(producer, context); - } + producer -> { + return createConfiguration(producer, context); } ); if (list.isEmpty()) return null; diff --git a/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerContributor.java b/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerContributor.java index ed6f66cb3ed5..7b80e96d944d 100644 --- a/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerContributor.java +++ b/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerContributor.java @@ -41,12 +41,7 @@ public abstract class RunLineMarkerContributor { } public Info(@NotNull final AnAction action) { - this(action.getTemplatePresentation().getIcon(), new Function() { - @Override - public String fun(PsiElement element) { - return getText(action, element); - } - }, action); + this(action.getTemplatePresentation().getIcon(), element -> getText(action, element), action); } } diff --git a/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerProvider.java b/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerProvider.java index 616d2942537d..2703fa8d3773 100644 --- a/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerProvider.java +++ b/platform/lang-impl/src/com/intellij/execution/lineMarker/RunLineMarkerProvider.java @@ -66,23 +66,20 @@ public class RunLineMarkerProvider extends LineMarkerProviderDescriptor { if (icon == null) return null; final DefaultActionGroup finalActionGroup = actionGroup; - Function tooltipProvider = new Function() { - @Override - public String fun(PsiElement element) { - final StringBuilder tooltip = new StringBuilder(); - for (RunLineMarkerContributor.Info info : infos) { - if (info.tooltipProvider != null) { - String string = info.tooltipProvider.fun(element); - if (string == null) continue; - if (tooltip.length() != 0) { - tooltip.append("\n"); - } - tooltip.append(string); + Function tooltipProvider = element1 -> { + final StringBuilder tooltip = new StringBuilder(); + for (RunLineMarkerContributor.Info info : infos) { + if (info.tooltipProvider != null) { + String string = info.tooltipProvider.fun(element1); + if (string == null) continue; + if (tooltip.length() != 0) { + tooltip.append("\n"); } + tooltip.append(string); } - - return tooltip.length() == 0 ? null : tooltip.toString(); } + + return tooltip.length() == 0 ? null : tooltip.toString(); }; return new LineMarkerInfo(element, element.getTextRange(), icon, Pass.UPDATE_ALL, tooltipProvider, null, diff --git a/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java b/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java index e843a82eb402..17d492252f03 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java @@ -78,12 +78,7 @@ public abstract class AbstractConsoleRunnerWithHistory initConsoleUI(process)); } private void initConsoleUI(Process process) { @@ -279,13 +274,7 @@ public abstract class AbstractConsoleRunnerWithHistory getActiveConsolesFromRunToolWindow(final String consoleTitle) { - List consoles = ExecutionHelper.collectConsolesByDisplayName(myProject, new NotNullFunction() { - @NotNull - @Override - public Boolean fun(String dom) { - return dom.contains(consoleTitle); - } - }); + List consoles = ExecutionHelper.collectConsolesByDisplayName(myProject, dom -> dom.contains(consoleTitle)); return FluentIterable.from(consoles).filter(new Predicate() { @Override diff --git a/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java b/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java index 13b7ca89ddd0..f5e3de0a97e0 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsNotification.java @@ -47,48 +47,35 @@ public class RerunTestsNotification { String lastActionId = ActionManagerEx.getInstanceEx().getPrevPreformedActionId(); boolean showNotification = !RerunTestsAction.ID.equals(lastActionId); if (showNotification && !PropertiesComponent.getInstance().isTrueValue(KEY)) { - UiNotifyConnector.doWhenFirstShown(executionConsole.getComponent(), new Runnable() { - @Override - public void run() { - doShow(executionConsole); - } - }); + UiNotifyConnector.doWhenFirstShown(executionConsole.getComponent(), () -> doShow(executionConsole)); } } private static void doShow(@NotNull final ExecutionConsole executionConsole) { final Alarm alarm = new Alarm(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - String shortcutText = KeymapUtil.getFirstKeyboardShortcutText( - ActionManager.getInstance().getAction(RerunTestsAction.ID) - ); - if (shortcutText.isEmpty()) { - return; - } - - GotItMessage message = GotItMessage.createMessage("Rerun tests with " + shortcutText, ""); - message.setDisposable(executionConsole); - message.setCallback(new Runnable() { - @Override - public void run() { - PropertiesComponent.getInstance().setValue(KEY, true); - } - }); - message.setShowCallout(false); - Dimension consoleSize = executionConsole.getComponent().getSize(); - - message.show( - new RelativePoint( - executionConsole.getComponent(), - new Point(consoleSize.width - 185, consoleSize.height - 60) - ), - Balloon.Position.below - ); - - Disposer.dispose(alarm); + alarm.addRequest(() -> { + String shortcutText = KeymapUtil.getFirstKeyboardShortcutText( + ActionManager.getInstance().getAction(RerunTestsAction.ID) + ); + if (shortcutText.isEmpty()) { + return; } + + GotItMessage message = GotItMessage.createMessage("Rerun tests with " + shortcutText, ""); + message.setDisposable(executionConsole); + message.setCallback(() -> PropertiesComponent.getInstance().setValue(KEY, true)); + message.setShowCallout(false); + Dimension consoleSize = executionConsole.getComponent().getSize(); + + message.show( + new RelativePoint( + executionConsole.getComponent(), + new Point(consoleSize.width - 185, consoleSize.height - 60) + ), + Balloon.Position.below + ); + + Disposer.dispose(alarm); }, 1000); } diff --git a/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurable.java b/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurable.java index d57f8d807d65..8d19621b3290 100644 --- a/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurable.java +++ b/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurable.java @@ -240,28 +240,18 @@ public class ProjectStartupConfigurable implements SearchableConfigurable, Confi } }; final List factoriesList = ContainerUtil.filter(Arrays.asList(factories), filter); - final ListPopup popup = NewRunConfigurationPopup.createAddPopup(factoriesList, "", new Consumer() { - @Override - public void consume(final ConfigurationFactory factory) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final EditConfigurationsDialog dialog = new EditConfigurationsDialog(project, factory); - if (dialog.showAndGet()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration(); - if (configuration != null) { - addConfiguration(configuration); - } - } - }, ModalityState.any(), project.getDisposed()); - } - } - }, ModalityState.any(), project.getDisposed()); - } - }, null, EmptyRunnable.getInstance(), false); + final ListPopup popup = NewRunConfigurationPopup.createAddPopup(factoriesList, "", + factory -> ApplicationManager.getApplication().invokeLater(() -> { + final EditConfigurationsDialog dialog = new EditConfigurationsDialog(project, factory); + if (dialog.showAndGet()) { + ApplicationManager.getApplication().invokeLater(() -> { + RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration(); + if (configuration != null) { + addConfiguration(configuration); + } + }, ModalityState.any(), project.getDisposed()); + } + }, ModalityState.any(), project.getDisposed()), null, EmptyRunnable.getInstance(), false); showPopup(button, popup); } @@ -322,18 +312,15 @@ public class ProjectStartupConfigurable implements SearchableConfigurable, Confi }); final JBPopup popup = JBPopupFactory.getInstance() .createListPopupBuilder(list) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final int index = list.getSelectedIndex(); - if (index < 0) return; - final ChooseRunConfigurationPopup.ItemWrapper at = (ChooseRunConfigurationPopup.ItemWrapper)list.getModel().getElementAt(index); - if (at.getValue() instanceof RunnerAndConfigurationSettings) { - final RunnerAndConfigurationSettings added = (RunnerAndConfigurationSettings)at.getValue(); - addConfiguration(added); - } else { - at.perform(myProject, executor, button.getDataContext()); - } + .setItemChoosenCallback(() -> { + final int index = list.getSelectedIndex(); + if (index < 0) return; + final ChooseRunConfigurationPopup.ItemWrapper at = (ChooseRunConfigurationPopup.ItemWrapper)list.getModel().getElementAt(index); + if (at.getValue() instanceof RunnerAndConfigurationSettings) { + final RunnerAndConfigurationSettings added = (RunnerAndConfigurationSettings)at.getValue(); + addConfiguration(added); + } else { + at.perform(myProject, executor, button.getDataContext()); } }) .createPopup(); diff --git a/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurationBase.java b/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurationBase.java index 8b2cc7e0ed4e..8736e42d6a8e 100644 --- a/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurationBase.java +++ b/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupConfigurationBase.java @@ -72,12 +72,9 @@ public class ProjectStartupConfigurationBase implements PersistentStateComponent public void setConfigurations(@NotNull Collection collection) { final List names = - ContainerUtil.map(collection, new Function() { - @Override - public ConfigurationDescriptor fun(RunnerAndConfigurationSettings settings) { + ContainerUtil.map(collection, settings -> { return new ConfigurationDescriptor(settings.getUniqueID(), settings.getName()); - } - }); + }); setList(names); } diff --git a/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupRunner.java b/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupRunner.java index cae3cd3dfe46..f9e42cbdd9a8 100644 --- a/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupRunner.java +++ b/platform/lang-impl/src/com/intellij/execution/startup/ProjectStartupRunner.java @@ -68,14 +68,11 @@ public class ProjectStartupRunner implements StartupActivity, DumbAware { } private static Runnable createRequest(final Project project, final Alarm alarm) { - return new Runnable() { - @Override - public void run() { - if (! ((StartupManagerEx) StartupManager.getInstance(project)).postStartupActivityPassed() && !Registry.is("dumb.aware.run.configurations")) { - alarm.addRequest(createRequest(project, alarm), DELAY_MILLIS); - } else { - runActivities(project); - } + return () -> { + if (! ((StartupManagerEx) StartupManager.getInstance(project)).postStartupActivityPassed() && !Registry.is("dumb.aware.run.configurations")) { + alarm.addRequest(createRequest(project, alarm), DELAY_MILLIS); + } else { + runActivities(project); } }; } @@ -88,21 +85,18 @@ public class ProjectStartupRunner implements StartupActivity, DumbAware { final Executor executor = DefaultRunExecutor.getRunExecutorInstance(); for (final RunnerAndConfigurationSettings configuration : configurations) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (! canBeRun(configuration)) { - ProjectStartupTaskManager.NOTIFICATION_GROUP - .createNotification(ProjectStartupTaskManager.PREFIX + " Run Configuration '" + configuration.getName() + - "' can not be started with 'Run' action.", MessageType.ERROR) - .notify(project); - return; - } - ProgramRunnerUtil.executeConfiguration(project, configuration, executor); + ApplicationManager.getApplication().invokeLater(() -> { + if (! canBeRun(configuration)) { ProjectStartupTaskManager.NOTIFICATION_GROUP - .createNotification(ProjectStartupTaskManager.PREFIX + " started '" + configuration.getName() + "'", MessageType.INFO) + .createNotification(ProjectStartupTaskManager.PREFIX + " Run Configuration '" + configuration.getName() + + "' can not be started with 'Run' action.", MessageType.ERROR) .notify(project); + return; } + ProgramRunnerUtil.executeConfiguration(project, configuration, executor); + ProjectStartupTaskManager.NOTIFICATION_GROUP + .createNotification(ProjectStartupTaskManager.PREFIX + " started '" + configuration.getName() + "'", MessageType.INFO) + .notify(project); }, ModalityState.any()); } } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/CommonProgramParametersPanel.java b/platform/lang-impl/src/com/intellij/execution/ui/CommonProgramParametersPanel.java index 2b2d7ff5827d..946d10de4963 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/CommonProgramParametersPanel.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/CommonProgramParametersPanel.java @@ -131,13 +131,10 @@ public class CommonProgramParametersPanel extends JPanel implements PanelWithAnc } final JList list = new JBList(ArrayUtil.toStringArray(macros)); - JBPopupFactory.getInstance().createListPopupBuilder(list).setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof String) { - textAccessor.setText('$' + ((String)value) + '$'); - } + JBPopupFactory.getInstance().createListPopupBuilder(list).setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof String) { + textAccessor.setText('$' + ((String)value) + '$'); } }).setMovable(false).setResizable(false).createPopup().showUnderneathOf(button); } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java index 4844342399f5..e70cd42ed271 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java @@ -76,12 +76,7 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { dockManager.register(DockableGridContainerFactory.TYPE, containerFactory); Disposer.register(myProject, containerFactory); - AppUIUtil.invokeOnEdt(new Runnable() { - @Override - public void run() { - init(); - } - }, myProject.getDisposed()); + AppUIUtil.invokeOnEdt(() -> init(), myProject.getDisposed()); } // must be called on EDT @@ -188,28 +183,22 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { @Override public void toFrontRunContent(final Executor requestor, final RunContentDescriptor descriptor) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ContentManager contentManager = getContentManagerForRunner(requestor); - Content content = getRunContentByDescriptor(contentManager, descriptor); - if (content != null) { - contentManager.setSelectedContent(content); - ToolWindowManager.getInstance(myProject).getToolWindow(requestor.getToolWindowId()).show(null); - } + ApplicationManager.getApplication().invokeLater(() -> { + ContentManager contentManager = getContentManagerForRunner(requestor); + Content content = getRunContentByDescriptor(contentManager, descriptor); + if (content != null) { + contentManager.setSelectedContent(content); + ToolWindowManager.getInstance(myProject).getToolWindow(requestor.getToolWindowId()).show(null); } }, myProject.getDisposed()); } @Override public void hideRunContent(@NotNull final Executor executor, final RunContentDescriptor descriptor) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(executor.getToolWindowId()); - if (toolWindow != null) { - toolWindow.hide(null); - } + ApplicationManager.getApplication().invokeLater(() -> { + ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(executor.getToolWindowId()); + if (toolWindow != null) { + toolWindow.hide(null); } }, myProject.getDisposed()); } @@ -290,40 +279,34 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { final ProcessAdapter processAdapter = new ProcessAdapter() { @Override public void startNotified(final ProcessEvent event) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - content.setIcon(ExecutionUtil.getLiveIndicator(descriptor.getIcon())); - toolWindow.setIcon(ExecutionUtil.getLiveIndicator(myToolwindowIdToBaseIconMap.get(executor.getToolWindowId()))); - } + UIUtil.invokeLaterIfNeeded(() -> { + content.setIcon(ExecutionUtil.getLiveIndicator(descriptor.getIcon())); + toolWindow.setIcon(ExecutionUtil.getLiveIndicator(myToolwindowIdToBaseIconMap.get(executor.getToolWindowId()))); }); } @Override public void processTerminated(final ProcessEvent event) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - boolean alive = false; - String toolWindowId = executor.getToolWindowId(); - ContentManager manager = myToolwindowIdToContentManagerMap.get(toolWindowId); - if (manager == null) return; - for (Content content : manager.getContents()) { - RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); - if (descriptor != null) { - ProcessHandler handler = descriptor.getProcessHandler(); - if (handler != null && !handler.isProcessTerminated()) { - alive = true; - break; - } + ApplicationManager.getApplication().invokeLater(() -> { + boolean alive = false; + String toolWindowId = executor.getToolWindowId(); + ContentManager manager = myToolwindowIdToContentManagerMap.get(toolWindowId); + if (manager == null) return; + for (Content content1 : manager.getContents()) { + RunContentDescriptor descriptor1 = getRunContentDescriptorByContent(content1); + if (descriptor1 != null) { + ProcessHandler handler = descriptor1.getProcessHandler(); + if (handler != null && !handler.isProcessTerminated()) { + alive = true; + break; } } - Icon base = myToolwindowIdToBaseIconMap.get(toolWindowId); - toolWindow.setIcon(alive ? ExecutionUtil.getLiveIndicator(base) : base); - - Icon icon = descriptor.getIcon(); - content.setIcon(icon == null ? executor.getDisabledIcon() : IconLoader.getTransparentIcon(icon)); } + Icon base = myToolwindowIdToBaseIconMap.get(toolWindowId); + toolWindow.setIcon(alive ? ExecutionUtil.getLiveIndicator(base) : base); + + Icon icon = descriptor.getIcon(); + content.setIcon(icon == null ? executor.getDisabledIcon() : IconLoader.getTransparentIcon(icon)); }); } }; @@ -346,19 +329,16 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ToolWindow window = ToolWindowManager.getInstance(myProject).getToolWindow(executor.getToolWindowId()); - // let's activate tool window, but don't move focus - // - // window.show() isn't valid here, because it will not - // mark the window as "last activated" windows and thus - // some action like navigation up/down in stacktrace wont - // work correctly - descriptor.getPreferredFocusComputable(); - window.activate(descriptor.getActivationCallback(), descriptor.isAutoFocusContent(), descriptor.isAutoFocusContent()); - } + ApplicationManager.getApplication().invokeLater(() -> { + ToolWindow window = ToolWindowManager.getInstance(myProject).getToolWindow(executor.getToolWindowId()); + // let's activate tool window, but don't move focus + // + // window.show() isn't valid here, because it will not + // mark the window as "last activated" windows and thus + // some action like navigation up/down in stacktrace wont + // work correctly + descriptor.getPreferredFocusComputable(); + window.activate(descriptor.getActivationCallback(), descriptor.isAutoFocusContent(), descriptor.isAutoFocusContent()); }, myProject.getDisposed()); } @@ -688,19 +668,16 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { final Semaphore semaphore = new Semaphore(); semaphore.down(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final ProcessHandler processHandler = descriptor.getProcessHandler(); - try { - if (processHandler != null) { - processHandler.waitFor(); - } - } - finally { - semaphore.up(); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final ProcessHandler processHandler1 = descriptor.getProcessHandler(); + try { + if (processHandler1 != null) { + processHandler1.waitFor(); } } + finally { + semaphore.up(); + } }); progressIndicator.setText(ExecutionBundle.message("waiting.for.vm.detach.progress.text")); diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java index e380cc918be5..55d37e2658c8 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java @@ -197,12 +197,7 @@ public class GridCellImpl implements GridCell { if (myContents.containsKey(content)) return; myContents.put(content, null); - revalidateCell(new Runnable() { - @Override - public void run() { - myTabs.addTab(createTabInfoFor(content)); - } - }); + revalidateCell(() -> myTabs.addTab(createTabInfoFor(content))); updateSelection(myTabs.getComponent().getRootPane() != null); } @@ -213,12 +208,7 @@ public class GridCellImpl implements GridCell { final TabInfo info = getTabFor(content); myContents.remove(content); - revalidateCell(new Runnable() { - @Override - public void run() { - myTabs.removeTab(info); - } - }); + revalidateCell(() -> myTabs.removeTab(info)); updateSelection(myTabs.getComponent().getRootPane() != null); } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java index be7cf867b1fe..6a0ca7c72eee 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java @@ -47,12 +47,8 @@ public class GridImpl extends Wrapper implements Grid, Disposable, DataProvider private final List myContents = new ArrayList(); private final Map myContent2Cell = new HashMap(); - private final Comparator myContentComparator = new Comparator() { - @Override - public int compare(final Content o1, final Content o2) { - return getCellFor(o1).getPlaceInGrid().compareTo(getCellFor(o2).getPlaceInGrid()); - } - }; + private final Comparator myContentComparator = + (o1, o2) -> getCellFor(o1).getPlaceInGrid().compareTo(getCellFor(o2).getPlaceInGrid()); private final ViewContextEx myViewContext; diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java index 7a2e7f8cdf07..ca7e58ab230d 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java @@ -97,16 +97,13 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac final MyDragOutDelegate myDragOutDelegate = new MyDragOutDelegate(); JBRunnerTabs myTabs; - private final Comparator myTabsComparator = new Comparator() { - @Override - public int compare(@NotNull final TabInfo o1, @NotNull final TabInfo o2) { - //noinspection ConstantConditions - TabImpl tab1 = getTabFor(o1); - TabImpl tab2 = getTabFor(o2); - int index1 = tab1 != null ? tab1.getIndex() : -1; - int index2 = tab2 != null ? tab2.getIndex() : -1; - return index1 - index2; - } + private final Comparator myTabsComparator = (o1, o2) -> { + //noinspection ConstantConditions + TabImpl tab1 = getTabFor(o1); + TabImpl tab2 = getTabFor(o2); + int index1 = tab1 != null ? tab1.getIndex() : -1; + int index2 = tab2 != null ? tab2.getIndex() : -1; + return index1 - index2; }; private final Project myProject; @@ -147,12 +144,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac private RunnerContentUi myOriginal; private final CopyOnWriteArraySet myDockingListeners = new CopyOnWriteArraySet(); - private final Set myChildren = new TreeSet(new Comparator() { - @Override - public int compare(@NotNull RunnerContentUi o1, @NotNull RunnerContentUi o2) { - return o1.myWindow - o2.myWindow; - } - }); + private final Set myChildren = new TreeSet((o1, o2) -> o1.myWindow - o2.myWindow); private int myWindow; private boolean myDisposing; @@ -942,13 +934,9 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac if (name != null && contents.size() > 1 && !usedNames.contains(name)) { title = name; } else { - title = StringUtil.join(contents, new NotNullFunction() { - @NotNull - @Override - public String fun(Content dom) { - return dom.getTabName(); - } - }, " | "); + title = StringUtil.join(contents, (NotNullFunction)dom -> { + return dom.getTabName(); + }, " | "); } } usedNames.add(title); @@ -1182,13 +1170,10 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac contents.add(content); } Content[] all = contents.toArray(new Content[contents.size()]); - Arrays.sort(all, new Comparator() { - @Override - public int compare(@NotNull Content content, @NotNull Content content1) { - final int i = getStateFor(content).getTab().getDefaultIndex(); - final int i1 = getStateFor(content1).getTab().getDefaultIndex(); - return i - i1; - } + Arrays.sort(all, (content, content1) -> { + final int i = getStateFor(content).getTab().getDefaultIndex(); + final int i1 = getStateFor(content1).getTab().getDefaultIndex(); + return i - i1; }); setStateIsBeingRestored(true, this); @@ -1454,21 +1439,13 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac // [kirillk] this is done later since restoreUiState doesn't work properly in the addNotify call chain //todo to investigate and to fix (may cause extra flickering) //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - restoreLastUiState().doWhenDone(new Runnable() { - @Override - public void run() { - if (!myWasEverAdded) { - myWasEverAdded = true; - attractOnStartup(); - myInitialized.setDone(); - } - } - }); + SwingUtilities.invokeLater(() -> restoreLastUiState().doWhenDone(() -> { + if (!myWasEverAdded) { + myWasEverAdded = true; + attractOnStartup(); + myInitialized.setDone(); } - }); + })); } } @@ -1488,12 +1465,9 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac // [kirillk] this is done later since "startup" attractions should be done gently, only if no explicit calls are done private void attractOnStartup() { final int currentCount = myAttractionCount; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (currentCount < myAttractionCount) return; - attractByCondition(LayoutViewOptions.STARTUP, false); - } + SwingUtilities.invokeLater(() -> { + if (currentCount < myAttractionCount) return; + attractByCondition(LayoutViewOptions.STARTUP, false); }); } @@ -1516,30 +1490,22 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac final LayoutAttractionPolicy defaultPolicy, final boolean afterInitialized, final boolean activate) { - IdeFocusManager.getInstance(getProject()).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - myInitialized.processOnDone(new Runnable() { - @Override - public void run() { - Content content = findContent(contentId); - if (content == null) return; + IdeFocusManager.getInstance(getProject()).doWhenFocusSettlesDown(() -> myInitialized.processOnDone(() -> { + Content content = findContent(contentId); + if (content == null) return; - final LayoutAttractionPolicy policy = getOrCreatePolicyFor(contentId, policyMap, defaultPolicy); - if (activate) { - // See IDEA-93683, bounce attraction should not disable further focus attraction - if (!(policy instanceof LayoutAttractionPolicy.Bounce)) { - myAttractionCount++; - } - policy.attract(content, myRunnerUi); - } - else { - policy.clearAttraction(content, myRunnerUi); - } - } - }, afterInitialized); + final LayoutAttractionPolicy policy = getOrCreatePolicyFor(contentId, policyMap, defaultPolicy); + if (activate) { + // See IDEA-93683, bounce attraction should not disable further focus attraction + if (!(policy instanceof LayoutAttractionPolicy.Bounce)) { + myAttractionCount++; + } + policy.attract(content, myRunnerUi); } - }); + else { + policy.clearAttraction(content, myRunnerUi); + } + }, afterInitialized)); } @@ -1640,12 +1606,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac final ActionCallback result = new ActionCallback(); - myTabs.select(info, false).doWhenDone(new Runnable() { - @Override - public void run() { - grid.select(content, requestFocus).notifyWhenDone(result); - } - }); + myTabs.select(info, false).doWhenDone(() -> grid.select(content, requestFocus).notifyWhenDone(result)); return result; @@ -1656,19 +1617,13 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac final TabInfo current = myTabs.getSelectedInfo(); myTabs.getPresentation().setPaintBlocked(true, true); - select(content, false).doWhenDone(new Runnable() { - @Override - public void run() { - myTabs.getComponent().validate(); - toRestore.run().doWhenDone(new Runnable() { - @Override - public void run() { - assert current != null; - myTabs.select(current, true); - myTabs.getPresentation().setPaintBlocked(false, true); - } - }); - } + select(content, false).doWhenDone(() -> { + myTabs.getComponent().validate(); + toRestore.run().doWhenDone(() -> { + assert current != null; + myTabs.select(current, true); + myTabs.getPresentation().setPaintBlocked(false, true); + }); }); } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayout.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayout.java index f3f14b02f3ee..1a5ed8dbd6ca 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayout.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayout.java @@ -43,12 +43,7 @@ public class RunnerLayout { protected Map myViews = new LinkedHashMap(); private final Map myDefaultViews = new HashMap(); - protected Set myTabs = new TreeSet(new Comparator() { - @Override - public int compare(final TabImpl o1, final TabImpl o2) { - return o1.getIndex() - o2.getIndex(); - } - }); + protected Set myTabs = new TreeSet((o1, o2) -> o1.getIndex() - o2.getIndex()); private final Map myDefaultTabs = new HashMap(); protected General myGeneral = new General(); diff --git a/platform/lang-impl/src/com/intellij/facet/impl/FacetTypeRegistryImpl.java b/platform/lang-impl/src/com/intellij/facet/impl/FacetTypeRegistryImpl.java index 3cee6a4ca430..3503e48f6618 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/FacetTypeRegistryImpl.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/FacetTypeRegistryImpl.java @@ -32,12 +32,8 @@ import java.util.*; */ public class FacetTypeRegistryImpl extends FacetTypeRegistry { private static final Logger LOG = Logger.getInstance("#com.intellij.facet.impl.FacetTypeRegistryImpl"); - private static final Comparator FACET_TYPE_COMPARATOR = new Comparator() { - @Override - public int compare(final FacetType o1, final FacetType o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }; + private static final Comparator FACET_TYPE_COMPARATOR = + (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); private final Map myTypeIds = new HashMap(); private final Map myFacetTypes = new HashMap(); private boolean myExtensionsLoaded = false; diff --git a/platform/lang-impl/src/com/intellij/facet/impl/FacetUtil.java b/platform/lang-impl/src/com/intellij/facet/impl/FacetUtil.java index 15936d608ebd..ec39f06c50a7 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/FacetUtil.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/FacetUtil.java @@ -42,12 +42,9 @@ public class FacetUtil { public static F addFacet(Module module, FacetType type) { final ModifiableFacetModel model = FacetManager.getInstance(module).createModifiableModel(); final F facet = createFacet(module, type); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - model.addFacet(facet); - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + model.addFacet(facet); + model.commit(); }); return facet; } diff --git a/platform/lang-impl/src/com/intellij/facet/impl/invalid/MultipleInvalidFacetEditor.java b/platform/lang-impl/src/com/intellij/facet/impl/invalid/MultipleInvalidFacetEditor.java index 8293d5a97b0a..28866ead53fa 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/invalid/MultipleInvalidFacetEditor.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/invalid/MultipleInvalidFacetEditor.java @@ -34,12 +34,8 @@ public class MultipleInvalidFacetEditor extends MultipleFacetSettingsEditor { public MultipleInvalidFacetEditor(FacetEditor[] editors) { myHelper = new MultipleFacetEditorHelperImpl(); - myHelper.bind(myIgnoreFacetsCheckBox, editors, new NotNullFunction() { - @NotNull - @Override - public JCheckBox fun(FacetEditor editor) { - return editor.getEditorTab(InvalidFacetEditor.class).getIgnoreCheckBox(); - } + myHelper.bind(myIgnoreFacetsCheckBox, editors, editor -> { + return editor.getEditorTab(InvalidFacetEditor.class).getIgnoreCheckBox(); }); } diff --git a/platform/lang-impl/src/com/intellij/facet/impl/statistics/FrameworkUsagesCollector.java b/platform/lang-impl/src/com/intellij/facet/impl/statistics/FrameworkUsagesCollector.java index 7a750c75a01f..6e52e637ac7f 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/statistics/FrameworkUsagesCollector.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/statistics/FrameworkUsagesCollector.java @@ -50,11 +50,8 @@ public class FrameworkUsagesCollector extends AbstractApplicationUsagesCollector } } - return ContainerUtil.map2Set(facets, new Function() { - @Override - public UsageDescriptor fun(String facet) { - return new UsageDescriptor(facet, 1); - } + return ContainerUtil.map2Set(facets, facet -> { + return new UsageDescriptor(facet, 1); }); } } diff --git a/platform/lang-impl/src/com/intellij/facet/impl/statistics/ModuleTypeUsagesCollector.java b/platform/lang-impl/src/com/intellij/facet/impl/statistics/ModuleTypeUsagesCollector.java index 3cb4c9c4b520..47acab1b82ca 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/statistics/ModuleTypeUsagesCollector.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/statistics/ModuleTypeUsagesCollector.java @@ -46,11 +46,8 @@ public class ModuleTypeUsagesCollector extends AbstractApplicationUsagesCollecto for (Module module : ModuleManager.getInstance(project).getModules()) { modulesTypes.add(ModuleType.get(module).getId()); } - return ContainerUtil.map2Set(modulesTypes, new Function() { - @Override - public UsageDescriptor fun(String moduleType) { - return new UsageDescriptor(moduleType, 1); - } + return ContainerUtil.map2Set(modulesTypes, moduleType -> { + return new UsageDescriptor(moduleType, 1); }); } } diff --git a/platform/lang-impl/src/com/intellij/find/EditorSearchSession.java b/platform/lang-impl/src/com/intellij/find/EditorSearchSession.java index b66616b06f35..b1d04cb10026 100644 --- a/platform/lang-impl/src/com/intellij/find/EditorSearchSession.java +++ b/platform/lang-impl/src/com/intellij/find/EditorSearchSession.java @@ -115,18 +115,8 @@ public class EditorSearchSession implements SearchSession, .addReplaceFieldActions(new PrevOccurrenceAction(false), new NextOccurrenceAction(false)) .withDataProvider(this) - .withCloseAction(new Runnable() { - @Override - public void run() { - close(); - } - }) - .withReplaceAction(new Runnable() { - @Override - public void run() { - replaceCurrent(); - } - }) + .withCloseAction(() -> close()) + .withReplaceAction(() -> replaceCurrent()) .withSecondarySearchActionsIsModifiedGetter(new BooleanGetter() { @Override public boolean get() { diff --git a/platform/lang-impl/src/com/intellij/find/SearchReplaceComponent.java b/platform/lang-impl/src/com/intellij/find/SearchReplaceComponent.java index 3285ed8189d9..6a79effed13e 100644 --- a/platform/lang-impl/src/com/intellij/find/SearchReplaceComponent.java +++ b/platform/lang-impl/src/com/intellij/find/SearchReplaceComponent.java @@ -315,12 +315,7 @@ public class SearchReplaceComponent extends EditorHeaderComponent implements Dat mySearchTextComponent.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - searchFieldDocumentChanged(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> searchFieldDocumentChanged()); } }); @@ -338,12 +333,8 @@ public class SearchReplaceComponent extends EditorHeaderComponent implements Dat }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, SystemInfo.isMac ? InputEvent.META_DOWN_MASK : InputEvent.CTRL_DOWN_MASK), JComponent.WHEN_FOCUSED); if (!wasNull) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - mySearchTextComponent.setCaretPosition(Math.min(oldCaretPosition, mySearchTextComponent.getText().length())); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> mySearchTextComponent.setCaretPosition(Math.min(oldCaretPosition, mySearchTextComponent.getText().length()))); } new VariantsCompletionAction(mySearchTextComponent); // It registers a shortcut set automatically on construction @@ -359,12 +350,7 @@ public class SearchReplaceComponent extends EditorHeaderComponent implements Dat myReplaceTextComponent.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - replaceFieldDocumentChanged(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> replaceFieldDocumentChanged()); } }); @@ -373,12 +359,7 @@ public class SearchReplaceComponent extends EditorHeaderComponent implements Dat } //myReplaceTextComponent.setText(myFindModel.getStringToReplace()); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myReplaceTextComponent.setCaretPosition(oldCaretPosition); - } - }); + ApplicationManager.getApplication().invokeLater(() -> myReplaceTextComponent.setCaretPosition(oldCaretPosition)); new VariantsCompletionAction(myReplaceTextComponent); myReplaceFieldWrapper.revalidate(); @@ -471,12 +452,7 @@ public class SearchReplaceComponent extends EditorHeaderComponent implements Dat public void actionPerformed(final ActionEvent e) { final String text = textComponent.getText(); setMultilineInternal(true); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ObjectUtils.assertNotNull(wrapper.getTextComponent()).setText(text + "\n"); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ObjectUtils.assertNotNull(wrapper.getTextComponent()).setText(text + "\n")); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_DOWN_MASK), JComponent.WHEN_FOCUSED); wrapper.setContent(searchTextField); diff --git a/platform/lang-impl/src/com/intellij/find/editorHeaderActions/Utils.java b/platform/lang-impl/src/com/intellij/find/editorHeaderActions/Utils.java index 648b9d3a8e9e..6bbe578fa6b8 100644 --- a/platform/lang-impl/src/com/intellij/find/editorHeaderActions/Utils.java +++ b/platform/lang-impl/src/com/intellij/find/editorHeaderActions/Utils.java @@ -27,13 +27,10 @@ public class Utils { final JTextComponent textField, String ad) { - final Runnable callback = new Runnable() { - @Override - public void run() { - String selectedValue = (String)list.getSelectedValue(); - if (selectedValue != null) { - textField.setText(selectedValue); - } + final Runnable callback = () -> { + String selectedValue = (String)list.getSelectedValue(); + if (selectedValue != null) { + textField.setText(selectedValue); } }; diff --git a/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java b/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java index abf70c2f1905..73737f9bd154 100644 --- a/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java +++ b/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java @@ -83,17 +83,13 @@ public class FindInProjectManager { findManager.showFindPopup(findModel, dataContext); return; } - findManager.showFindDialog(findModel, new Runnable() { - @Override - public void run() { - findModel.setOpenInNewTabVisible(false); - if (isOpenInNewTabEnabled) { - FindSettings.getInstance().setShowResultsInSeparateView(findModel.isOpenInNewTab()); - } - - startFindInProject(findModel); + findManager.showFindDialog(findModel, () -> { + findModel.setOpenInNewTabVisible(false); + if (isOpenInNewTabEnabled) { + FindSettings.getInstance().setShowResultsInSeparateView(findModel.isOpenInNewTab()); } + startFindInProject(findModel); }); findModel.setOpenInNewTabVisible(false); } @@ -127,13 +123,10 @@ public class FindInProjectManager { myIsFindInProgress = true; try { - Processor consumer = new Processor() { - @Override - public boolean process(UsageInfo info) { - Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); - usage.getPresentation().getIcon(); // cache icon - return processor.process(usage); - } + Processor consumer = info -> { + Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); + usage.getPresentation().getIcon(); // cache icon + return processor.process(usage); }; FindInProjectUtil.findUsages(findModelCopy, myProject, consumer, processPresentation); } diff --git a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java index e4a4d9180db3..4ddda5e83c56 100644 --- a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java +++ b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java @@ -129,12 +129,7 @@ public abstract class FindUsagesHandler { if (searchText) { if (options.fastTrack != null) { - options.fastTrack.searchCustom(new Processor>() { - @Override - public boolean process(Processor consumer) { - return processUsagesInText(element, processor, (GlobalSearchScope)scope); - } - }); + options.fastTrack.searchCustom(consumer -> processUsagesInText(element, processor, (GlobalSearchScope)scope)); } else { return processUsagesInText(element, processor, (GlobalSearchScope)scope); diff --git a/platform/lang-impl/src/com/intellij/find/findUsages/PsiElement2UsageTargetComposite.java b/platform/lang-impl/src/com/intellij/find/findUsages/PsiElement2UsageTargetComposite.java index a44208095e02..ea6d850e7c4a 100644 --- a/platform/lang-impl/src/com/intellij/find/findUsages/PsiElement2UsageTargetComposite.java +++ b/platform/lang-impl/src/com/intellij/find/findUsages/PsiElement2UsageTargetComposite.java @@ -50,11 +50,8 @@ public class PsiElement2UsageTargetComposite extends PsiElement2UsageTargetAdapt @Override public VirtualFile[] getFiles() { - Set files = ContainerUtil.map2Set(myDescriptor.getAllElements(), new Function() { - @Override - public VirtualFile fun(PsiElement element) { - return PsiUtilCore.getVirtualFile(element); - } + Set files = ContainerUtil.map2Set(myDescriptor.getAllElements(), element -> { + return PsiUtilCore.getVirtualFile(element); }); return VfsUtilCore.toVirtualFileArray(files); } diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java b/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java index 421170a50005..f9da77b3a5b9 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java @@ -161,11 +161,8 @@ public class FindDialog extends DialogWrapper { validateFindButton(); if (haveResultsPreview()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - scheduleResultsUpdate(); - } + ApplicationManager.getApplication().invokeLater(() -> { + scheduleResultsUpdate(); }, ModalityState.any()); } } @@ -350,13 +347,10 @@ public class FindDialog extends DialogWrapper { comboBox, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "choosePrevious", - new Runnable() { - @Override - public void run() { - int row = myResultsPreviewTable.getSelectedRow(); - if (row > 0) myResultsPreviewTable.setRowSelectionInterval(row - 1, row - 1); - TableUtil.scrollSelectionToVisible(myResultsPreviewTable); - } + () -> { + int row = myResultsPreviewTable.getSelectedRow(); + if (row > 0) myResultsPreviewTable.setRowSelectionInterval(row - 1, row - 1); + TableUtil.scrollSelectionToVisible(myResultsPreviewTable); } ); @@ -364,14 +358,11 @@ public class FindDialog extends DialogWrapper { comboBox, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "chooseNext", - new Runnable() { - @Override - public void run() { - int row = myResultsPreviewTable.getSelectedRow(); - if (row >= -1 && row + 1 < myResultsPreviewTable.getRowCount()) { - myResultsPreviewTable.setRowSelectionInterval(row + 1, row + 1); - TableUtil.scrollSelectionToVisible(myResultsPreviewTable); - } + () -> { + int row = myResultsPreviewTable.getSelectedRow(); + if (row >= -1 && row + 1 < myResultsPreviewTable.getRowCount()) { + myResultsPreviewTable.setRowSelectionInterval(row + 1, row + 1); + TableUtil.scrollSelectionToVisible(myResultsPreviewTable); } } ); @@ -502,33 +493,24 @@ public class FindDialog extends DialogWrapper { final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, showPanelIfOnlyOneUsage, presentation); - FindInProjectUtil.findUsages(findModel, myProject, new Processor() { - @Override - public boolean process(final UsageInfo info) { - final Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); - usage.getPresentation().getIcon(); // cache icon - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - model.addRow(new Object[]{usage}); - if (model.getRowCount() == 1 && myResultsPreviewTable.getModel() == model && isResultsPreviewTabActive()) { - myResultsPreviewTable.setRowSelectionInterval(0, 0); - } - } - }, state); - return resultsCount.incrementAndGet() < ShowUsagesAction.USAGES_PAGE_SIZE; - } + FindInProjectUtil.findUsages(findModel, myProject, info -> { + final Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); + usage.getPresentation().getIcon(); // cache icon + ApplicationManager.getApplication().invokeLater(() -> { + model.addRow(new Object[]{usage}); + if (model.getRowCount() == 1 && myResultsPreviewTable.getModel() == model && isResultsPreviewTabActive()) { + myResultsPreviewTable.setRowSelectionInterval(0, 0); + } + }, state); + return resultsCount.incrementAndGet() < ShowUsagesAction.USAGES_PAGE_SIZE; }, processPresentation, filesToScanInitially); boolean succeeded = !progressIndicatorWhenSearchStarted.isCanceled(); if (succeeded) { - return new Continuation(new Runnable() { - @Override - public void run() { - if (progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress && !myResultsPreviewSearchProgress.isCanceled()) { - int occurrences = resultsCount.get(); - if (occurrences == 0) myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow")); - myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE + " (" + (occurrences != ShowUsagesAction.USAGES_PAGE_SIZE ? Integer.valueOf(occurrences): occurrences + "+") +")"); - } + return new Continuation(() -> { + if (progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress && !myResultsPreviewSearchProgress.isCanceled()) { + int occurrences = resultsCount.get(); + if (occurrences == 0) myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow")); + myContent.setTitleAt(RESULTS_PREVIEW_TAB_INDEX, PREVIEW_TITLE + " (" + (occurrences != ShowUsagesAction.USAGES_PAGE_SIZE ? Integer.valueOf(occurrences): occurrences + "+") +")"); } }, state); } @@ -1322,11 +1304,8 @@ public class FindDialog extends DialogWrapper { @Override public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); - FileChooser.chooseFiles(descriptor, myProject, null, new Consumer>() { - @Override - public void consume(final List files) { - myDirectoryComboBox.setSelectedItem(files.get(0).getPresentableUrl()); - } + FileChooser.chooseFiles(descriptor, myProject, null, files -> { + myDirectoryComboBox.setSelectedItem(files.get(0).getPresentableUrl()); }); } }); diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java index eb77f2dd92d2..9eae587af88f 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java @@ -186,12 +186,7 @@ class FindInProjectTask { } List extensions = ContainerUtil.newArrayList(stats.elementSet()); - Collections.sort(extensions, new Comparator() { - @Override - public int compare(String o1, String o2) { - return stats.count(o2) - stats.count(o1); - } - }); + Collections.sort(extensions, (o1, o2) -> stats.count(o2) - stats.count(o1)); String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" + @@ -240,21 +235,13 @@ class FindInProjectTask { }); if (psiFile == null) continue; - int countInFile = FindInProjectUtil.processUsagesInFile(psiFile, myFindModel, new Processor() { - @Override - public boolean process(UsageInfo info) { - return skipProjectFile || consumer.process(info); - } - }); + int countInFile = FindInProjectUtil.processUsagesInFile(psiFile, myFindModel, info -> skipProjectFile || consumer.process(info)); if (countInFile > 0 && skipProjectFile) { - processPresentation.projectFileUsagesFound(new Runnable() { - @Override - public void run() { - FindModel model = myFindModel.clone(); - model.setSearchInProjectFiles(true); - FindInProjectManager.getInstance(myProject).startFindInProject(model); - } + processPresentation.projectFileUsagesFound(() -> { + FindModel model = myFindModel.clone(); + model.setSearchInProjectFiles(true); + FindInProjectManager.getInstance(myProject).startFindInProject(model); }); continue; } @@ -473,11 +460,8 @@ class FindInProjectTask { if (!keys.isEmpty()) { final List hits = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, Processors.cancelableCollectProcessor(hits), scope); - } + ApplicationManager.getApplication().runReadAction(() -> { + FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, Processors.cancelableCollectProcessor(hits), scope); }); for (VirtualFile hit : hits) { @@ -491,14 +475,11 @@ class FindInProjectTask { } PsiSearchHelperImpl helper = (PsiSearchHelperImpl)PsiSearchHelper.SERVICE.getInstance(myProject); - helper.processFilesWithText(scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, new Processor() { - @Override - public boolean process(VirtualFile file) { - if (myFileMask.value(file)) { - ContainerUtil.addIfNotNull(resultFiles, file); - } - return true; + helper.processFilesWithText(scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, file -> { + if (myFileMask.value(file)) { + ContainerUtil.addIfNotNull(resultFiles, file); } + return true; }); // in case our word splitting is incorrect diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java index 3eaf8ec7ab54..1d18dd214a57 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java @@ -158,12 +158,9 @@ public class FindManagerImpl extends FindManager { @Override public void showFindDialog(@NotNull final FindModel model, @NotNull final Runnable okHandler) { - final Consumer handler = new Consumer(){ - @Override - public void consume(FindModel findModel) { - changeGlobalSettings(findModel); - okHandler.run(); - } + final Consumer handler = findModel -> { + changeGlobalSettings(findModel); + okHandler.run(); }; if(myFindDialog==null || Disposer.isDisposed(myFindDialog.getDisposable())){ myFindDialog = new FindDialog(myProject, model, handler) { @@ -1061,16 +1058,13 @@ public class FindManagerImpl extends FindManager { if (regions == null) { return; } - int i = Arrays.binarySearch(regions, null, new Comparator() { - @Override - public int compare(FoldRegion o1, FoldRegion o2) { - // Find the first region that ends after the given start offset - if (o1 == null) { - return startOffset - o2.getEndOffset(); - } - else { - return o1.getEndOffset() - startOffset; - } + int i = Arrays.binarySearch(regions, null, (o1, o2) -> { + // Find the first region that ends after the given start offset + if (o1 == null) { + return startOffset - o2.getEndOffset(); + } + else { + return o1.getEndOffset() - startOffset; } }); if (i < 0) { @@ -1095,12 +1089,9 @@ public class FindManagerImpl extends FindManager { if (toExpand.isEmpty()) { return; } - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : toExpand) { - region.setExpanded(true); - } + foldingModel.runBatchFoldingOperation(() -> { + for (FoldRegion region : toExpand) { + region.setExpanded(true); } }); } diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindPopupPanel.java b/platform/lang-impl/src/com/intellij/find/impl/FindPopupPanel.java index d119d24db5e3..3671cf8f889a 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindPopupPanel.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindPopupPanel.java @@ -221,11 +221,8 @@ public class FindPopupPanel extends JBPanel { initByModel(); updateReplaceVisibility(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - FindPopupPanel.this.scheduleResultsUpdate(); - } + ApplicationManager.getApplication().invokeLater(() -> { + FindPopupPanel.this.scheduleResultsUpdate(); }, ModalityState.any()); } @@ -414,12 +411,8 @@ public class FindPopupPanel extends JBPanel { @Override public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); - FileChooser.chooseFiles(descriptor, myProject, FindPopupPanel.this, null, new Consumer>() { - @Override - public void consume(final java.util.List files) { - myDirectoryComboBox.setSelectedItem(files.get(0).getPresentableUrl()); - } - }); + FileChooser.chooseFiles(descriptor, myProject, FindPopupPanel.this, null, + files -> myDirectoryComboBox.setSelectedItem(files.get(0).getPresentableUrl())); } }); @@ -578,12 +571,7 @@ public class FindPopupPanel extends JBPanel { boolean later = myUpdateResultsPopupBoundsAlarm.getActiveRequestCount() > 0; myUpdateResultsPopupBoundsAlarm.cancelAllRequests(); - myUpdateResultsPopupBoundsAlarm.addRequest(new Runnable() { - @Override - public void run() { - updateResultsPopupBounds(); - } - }, later? 50 : 0); + myUpdateResultsPopupBoundsAlarm.addRequest(() -> updateResultsPopupBounds(), later ? 50 : 0); } private void updateResultsPopupBounds() { @@ -787,12 +775,7 @@ public class FindPopupPanel extends JBPanel { if (myFindBalloon == null || !myFindBalloon.isVisible()) return; if (mySearchRescheduleOnCancellationsAlarm == null || mySearchRescheduleOnCancellationsAlarm.isDisposed()) return; mySearchRescheduleOnCancellationsAlarm.cancelAllRequests(); - mySearchRescheduleOnCancellationsAlarm.addRequest(new Runnable() { - @Override - public void run() { - findSettingsChanged(); - } - }, 100); + mySearchRescheduleOnCancellationsAlarm.addRequest(() -> findSettingsChanged(), 100); } private void finishPreviousPreviewSearch() { @@ -853,45 +836,36 @@ public class FindPopupPanel extends JBPanel { final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, showPanelIfOnlyOneUsage, presentation); - FindInProjectUtil.findUsages(myModel.clone(), myProject, new Processor() { - @Override - public boolean process(final UsageInfo info) { - final Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); - usage.getPresentation().getIcon(); // cache icon - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - model.addRow(new Object[]{usage}); - myCodePreviewComponent.setVisible(true); - if (model.getRowCount() == 1 && myResultsPreviewTable.getModel() == model) { - myResultsPreviewTable.setRowSelectionInterval(0, 0); - } - scheduleUpdateResultsPopupBounds(); - } - }, state); - return resultsCount.incrementAndGet() < ShowUsagesAction.USAGES_PAGE_SIZE; - } + FindInProjectUtil.findUsages(myModel.clone(), myProject, info -> { + final Usage usage = UsageInfo2UsageAdapter.CONVERTER.fun(info); + usage.getPresentation().getIcon(); // cache icon + ApplicationManager.getApplication().invokeLater(() -> { + model.addRow(new Object[]{usage}); + myCodePreviewComponent.setVisible(true); + if (model.getRowCount() == 1 && myResultsPreviewTable.getModel() == model) { + myResultsPreviewTable.setRowSelectionInterval(0, 0); + } + scheduleUpdateResultsPopupBounds(); + }, state); + return resultsCount.incrementAndGet() < ShowUsagesAction.USAGES_PAGE_SIZE; }, processPresentation); boolean succeeded = !progressIndicatorWhenSearchStarted.isCanceled(); if (succeeded) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress && !myResultsPreviewSearchProgress.isCanceled()) { - int occurrences = resultsCount.get(); - if (occurrences == 0) myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow")); - myCodePreviewComponent.setVisible(occurrences > 0); - StringBuilder info = new StringBuilder(); - if (occurrences > 0) { - info.append(Math.min(ShowUsagesAction.USAGES_PAGE_SIZE, occurrences)); - if (occurrences >= ShowUsagesAction.USAGES_PAGE_SIZE) { - info.append("+"); - } - info.append(UIBundle.message("message.matches", occurrences)); + ApplicationManager.getApplication().invokeLater(() -> { + if (progressIndicatorWhenSearchStarted == myResultsPreviewSearchProgress && !myResultsPreviewSearchProgress.isCanceled()) { + int occurrences = resultsCount.get(); + if (occurrences == 0) myResultsPreviewTable.getEmptyText().setText(UIBundle.message("message.nothingToShow")); + myCodePreviewComponent.setVisible(occurrences > 0); + StringBuilder info = new StringBuilder(); + if (occurrences > 0) { + info.append(Math.min(ShowUsagesAction.USAGES_PAGE_SIZE, occurrences)); + if (occurrences >= ShowUsagesAction.USAGES_PAGE_SIZE) { + info.append("+"); } - mySearchTextArea.setInfoText(info.toString()); - scheduleUpdateResultsPopupBounds(); + info.append(UIBundle.message("message.matches", occurrences)); } + mySearchTextArea.setInfoText(info.toString()); + scheduleUpdateResultsPopupBounds(); } }, state); } @@ -958,31 +932,25 @@ public class FindPopupPanel extends JBPanel { if (activeWindow == balloonWindow || (activeWindow != null && activeWindow.getParent() == balloonWindow)) { return Boolean.FALSE; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myFindBalloon != null) { - Disposer.dispose(myFindBalloon); - myFindBalloon = null; - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myFindBalloon != null) { + Disposer.dispose(myFindBalloon); + myFindBalloon = null; } }); return Boolean.TRUE; } }) - .setKeyEventHandler(new BooleanFunction() { - @Override - public boolean fun(KeyEvent event) { - if (AbstractPopup.isCloseRequest(event)) { - canClose.set(true); - myResultsPopup.cancel(event); - if (myFindBalloon != null && myFindBalloon.isVisible()) { - myFindBalloon.cancel(); - } - return true; + .setKeyEventHandler(event -> { + if (AbstractPopup.isCloseRequest(event)) { + canClose.set(true); + myResultsPopup.cancel(event); + if (myFindBalloon != null && myFindBalloon.isVisible()) { + myFindBalloon.cancel(); } - return false; + return true; } + return false; }) .createPopup(); RelativePoint point = new RelativePoint(FindPopupPanel.this, new Point(0, FindPopupPanel.this.getHeight())); diff --git a/platform/lang-impl/src/com/intellij/find/impl/RevealingSpaceComboboxEditor.java b/platform/lang-impl/src/com/intellij/find/impl/RevealingSpaceComboboxEditor.java index 3298b66ab74b..cfd28c370312 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/RevealingSpaceComboboxEditor.java +++ b/platform/lang-impl/src/com/intellij/find/impl/RevealingSpaceComboboxEditor.java @@ -34,13 +34,10 @@ public class RevealingSpaceComboboxEditor extends StringComboboxEditor { public RevealingSpaceComboboxEditor(final Project project, ComboBox comboBox) { super(project, FileTypes.PLAIN_TEXT, comboBox); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Editor editor = getEditor(); - if (editor != null) { - editor.getSettings().setWhitespacesShown(true); - } + SwingUtilities.invokeLater(() -> { + Editor editor = getEditor(); + if (editor != null) { + editor.getSettings().setWhitespacesShown(true); } }); } diff --git a/platform/lang-impl/src/com/intellij/find/impl/ShowRecentFindUsagesAction.java b/platform/lang-impl/src/com/intellij/find/impl/ShowRecentFindUsagesAction.java index 4a72450b4287..4d39e0647ea3 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/ShowRecentFindUsagesAction.java +++ b/platform/lang-impl/src/com/intellij/find/impl/ShowRecentFindUsagesAction.java @@ -85,12 +85,9 @@ public class ShowRecentFindUsagesAction extends AnAction { @Override public PopupStep onChosen(final ConfigurableUsageTarget selectedValue, final boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - if (selectedValue != null) { - findUsagesManager.rerunAndRecallFromHistory(selectedValue); - } + return doFinalStep(() -> { + if (selectedValue != null) { + findUsagesManager.rerunAndRecallFromHistory(selectedValue); } }); } diff --git a/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java b/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java index ff81d7b67c64..fdb6b50d868b 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java +++ b/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreview.java @@ -151,24 +151,21 @@ public class LivePreview extends DocumentAdapter implements SearchResults.Search } ranges.add(new Pair(-1, '\n')); ranges.add(new Pair(editor.getDocument().getTextLength()+1, '\n')); - ContainerUtil.sort(ranges, new Comparator>() { - @Override - public int compare(@NotNull Pair pair, @NotNull Pair pair2) { - int res = pair.first - pair2.first; - if (res == 0) { + ContainerUtil.sort(ranges, (pair, pair2) -> { + int res = pair.first - pair2.first; + if (res == 0) { - Character c1 = pair.second; - Character c2 = pair2.second; - if (c1 == '<' && c2 == '[') { - return 1; - } - else if (c1 == '[' && c2 == '<') { - return -1; - } - return c1.compareTo(c2); + Character c1 = pair.second; + Character c2 = pair2.second; + if (c1 == '<' && c2 == '[') { + return 1; } - return res; + else if (c1 == '[' && c2 == '<') { + return -1; + } + return c1.compareTo(c2); } + return res; }); Document document = editor.getDocument(); @@ -238,12 +235,7 @@ public class LivePreview extends DocumentAdapter implements SearchResults.Search myCursorHighlighter = dummy.iterator().next(); } - editor.getScrollingModel().runActionOnScrollingFinished(new Runnable() { - @Override - public void run() { - showReplacementPreview(); - } - }); + editor.getScrollingModel().runActionOnScrollingFinished(() -> showReplacementPreview()); } } @@ -454,21 +446,18 @@ public class LivePreview extends DocumentAdapter implements SearchResults.Search boolean notFound = markupModel.processRangeHighlightersOverlappingWith( textRange.getStartOffset(), textRange.getEndOffset(), - new Processor() { - @Override - public boolean process(RangeHighlighterEx highlighter) { - TextAttributes textAttributes = - highlighter.getTextAttributes(); - if (highlighter.getUserData(SEARCH_MARKER) != null && - textAttributes != null && - textAttributes.equals(attributes) && - highlighter.getStartOffset() == textRange.getStartOffset() && - highlighter.getEndOffset() == textRange.getEndOffset()) { - candidate[0] = highlighter; - return false; - } - return true; + highlighter -> { + TextAttributes textAttributes = + highlighter.getTextAttributes(); + if (highlighter.getUserData(SEARCH_MARKER) != null && + textAttributes != null && + textAttributes.equals(attributes) && + highlighter.getStartOffset() == textRange.getStartOffset() && + highlighter.getEndOffset() == textRange.getEndOffset()) { + candidate[0] = highlighter; + return false; } + return true; }); if (!notFound && highlighters.contains(candidate[0])) { @@ -541,11 +530,6 @@ public class LivePreview extends DocumentAdapter implements SearchResults.Search } private static void requestBalloonHiding(final Balloon object) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - object.hide(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> object.hide()); } } diff --git a/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreviewController.java b/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreviewController.java index e16ef52639f7..0135245466e8 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreviewController.java +++ b/platform/lang-impl/src/com/intellij/find/impl/livePreview/LivePreviewController.java @@ -134,14 +134,11 @@ public class LivePreviewController implements LivePreview.Delegate, FindUtil.Rep final FindModel copy = new FindModel(); copy.copyFrom(findModel); - Runnable request = new Runnable() { - @Override - public void run() { - if (myDisposed) return; - Project project = mySearchResults.getProject(); - if (project != null && project.isDisposed()) return; - mySearchResults.updateThreadSafe(copy, allowedToChangedEditorSelection, null, stamp); - } + Runnable request = () -> { + if (myDisposed) return; + Project project = mySearchResults.getProject(); + if (project != null && project.isDisposed()) return; + mySearchResults.updateThreadSafe(copy, allowedToChangedEditorSelection, null, stamp); }; if (unitTestMode) { request.run(); diff --git a/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java b/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java index 41be88921ab3..3824a900ab75 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java +++ b/platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java @@ -206,44 +206,36 @@ public class SearchResults implements DocumentListener { final FutureResult endsRef = new FutureResult(); getSelection(editor, startsRef, endsRef); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - Project project = getProject(); - if (myDisposed || project != null && project.isDisposed()) return; - int[] starts = new int[0]; - int[] ends = new int[0]; - try { - starts = startsRef.get(); - ends = endsRef.get(); - } - catch (InterruptedException ignore) { - } - catch (ExecutionException ignore) { - } + ApplicationManager.getApplication().runReadAction(() -> { + Project project = getProject(); + if (myDisposed || project != null && project.isDisposed()) return; + int[] starts = new int[0]; + int[] ends = new int[0]; + try { + starts = startsRef.get(); + ends = endsRef.get(); + } + catch (InterruptedException ignore) { + } + catch (ExecutionException ignore) { + } - if (starts.length == 0 || findModel.isGlobal()) { - findInRange(new TextRange(0, Integer.MAX_VALUE), editor, findModel, results); - } - else { - for (int i = 0; i < starts.length; ++i) { - findInRange(new TextRange(starts[i], ends[i]), editor, findModel, results); - } + if (starts.length == 0 || findModel.isGlobal()) { + findInRange(new TextRange(0, Integer.MAX_VALUE), editor, findModel, results); + } + else { + for (int i = 0; i < starts.length; ++i) { + findInRange(new TextRange(starts[i], ends[i]), editor, findModel, results); } + } - final Runnable searchCompletedRunnable = new Runnable() { - @Override - public void run() { - searchCompleted(results, editor, findModel, toChangeSelection, next, stamp); - } - }; + final Runnable searchCompletedRunnable = () -> searchCompleted(results, editor, findModel, toChangeSelection, next, stamp); - if (!ApplicationManager.getApplication().isUnitTestMode()) { - UIUtil.invokeLaterIfNeeded(searchCompletedRunnable); - } - else { - searchCompletedRunnable.run(); - } + if (!ApplicationManager.getApplication().isUnitTestMode()) { + UIUtil.invokeLaterIfNeeded(searchCompletedRunnable); + } + else { + searchCompletedRunnable.run(); } }); } @@ -267,13 +259,10 @@ public class SearchResults implements DocumentListener { ends.set(selection.getBlockSelectionEnds()); } else { try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - SelectionModel selection = editor.getSelectionModel(); - starts.set(selection.getBlockSelectionStarts()); - ends.set(selection.getBlockSelectionEnds()); - } + SwingUtilities.invokeAndWait(() -> { + SelectionModel selection = editor.getSelectionModel(); + starts.set(selection.getBlockSelectionStarts()); + ends.set(selection.getBlockSelectionEnds()); }); } catch (InterruptedException ignore) { @@ -335,12 +324,7 @@ public class SearchResults implements DocumentListener { } myOccurrences = occurrences; final TextRange oldCursorRange = myCursor; - Collections.sort(myOccurrences, new Comparator() { - @Override - public int compare(FindResult findResult, FindResult findResult1) { - return findResult.getStartOffset() - findResult1.getStartOffset(); - } - }); + Collections.sort(myOccurrences, (findResult, findResult1) -> findResult.getStartOffset() - findResult1.getStartOffset()); myFindModel = findModel; updateCursor(oldCursorRange, next); diff --git a/platform/lang-impl/src/com/intellij/find/impl/livePreview/SelectionManager.java b/platform/lang-impl/src/com/intellij/find/impl/livePreview/SelectionManager.java index a0b9714c12f6..181cf1029743 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/livePreview/SelectionManager.java +++ b/platform/lang-impl/src/com/intellij/find/impl/livePreview/SelectionManager.java @@ -46,20 +46,17 @@ public class SelectionManager { FoldingModel foldingModel = editor.getFoldingModel(); final FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions(); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : myRegionsToRestore) { - if (region.isValid()) region.setExpanded(false); - } - myRegionsToRestore.clear(); - for (FoldRegion region : allRegions) { - if (!region.isValid()) continue; - if (cursor.intersects(TextRange.create(region))) { - if (!region.isExpanded()) { - region.setExpanded(true); - myRegionsToRestore.add(region); - } + foldingModel.runBatchFoldingOperation(() -> { + for (FoldRegion region : myRegionsToRestore) { + if (region.isValid()) region.setExpanded(false); + } + myRegionsToRestore.clear(); + for (FoldRegion region : allRegions) { + if (!region.isValid()) continue; + if (cursor.intersects(TextRange.create(region))) { + if (!region.isExpanded()) { + region.setExpanded(true); + myRegionsToRestore.add(region); } } } diff --git a/platform/lang-impl/src/com/intellij/find/replaceInProject/ReplaceInProjectManager.java b/platform/lang-impl/src/com/intellij/find/replaceInProject/ReplaceInProjectManager.java index 5faf9a315137..f75dfc0e5b51 100644 --- a/platform/lang-impl/src/com/intellij/find/replaceInProject/ReplaceInProjectManager.java +++ b/platform/lang-impl/src/com/intellij/find/replaceInProject/ReplaceInProjectManager.java @@ -138,28 +138,25 @@ public class ReplaceInProjectManager { Editor editor = CommonDataKeys.EDITOR.getData(dataContext); FindUtil.initStringToFindWithSelection(findModel, editor); - findManager.showFindDialog(findModel, new Runnable() { - @Override - public void run() { - if (!findModel.isProjectScope() && - FindInProjectUtil.getDirectory(findModel) == null && - findModel.getModuleName() == null && - findModel.getCustomScope() == null) { - return; - } - - UsageViewManager manager = UsageViewManager.getInstance(myProject); - - if (manager == null) return; - findManager.getFindInProjectModel().copyFrom(findModel); - final FindModel findModelCopy = findModel.clone(); - - final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(findModel.isOpenInNewTab(), findModelCopy); - final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, true, presentation); - - UsageSearcherFactory factory = new UsageSearcherFactory(findModelCopy, processPresentation); - searchAndShowUsages(manager, factory, findModelCopy, presentation, processPresentation, findManager); + findManager.showFindDialog(findModel, () -> { + if (!findModel.isProjectScope() && + FindInProjectUtil.getDirectory(findModel) == null && + findModel.getModuleName() == null && + findModel.getCustomScope() == null) { + return; } + + UsageViewManager manager = UsageViewManager.getInstance(myProject); + + if (manager == null) return; + findManager.getFindInProjectModel().copyFrom(findModel); + final FindModel findModelCopy = findModel.clone(); + + final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(findModel.isOpenInNewTab(), findModelCopy); + final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, true, presentation); + + UsageSearcherFactory factory = new UsageSearcherFactory(findModelCopy, processPresentation); + searchAndShowUsages(manager, factory, findModelCopy, presentation, processPresentation, findManager); }); } @@ -220,12 +217,9 @@ public class ReplaceInProjectManager { @Override public void findingUsagesFinished(final UsageView usageView) { if (context[0] != null && findManager.getFindInProjectModel().isPromptOnReplace()) { - TransactionGuard.submitTransaction(myProject, new Runnable() { - @Override - public void run() { - replaceWithPrompt(context[0]); - context[0].invalidateExcludedSetCache(); - } + TransactionGuard.submitTransaction(myProject, () -> { + replaceWithPrompt(context[0]); + context[0].invalidateExcludedSetCache(); }); } } @@ -255,20 +249,17 @@ public class ReplaceInProjectManager { final VirtualFile virtualFile = psiFile.getVirtualFile(); - Runnable selectOnEditorRunnable = new Runnable() { - @Override - public void run() { - if (virtualFile != null && ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - return virtualFile.isValid(); - } - }).booleanValue()) { + Runnable selectOnEditorRunnable = () -> { + if (virtualFile != null && ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public Boolean compute() { + return virtualFile.isValid(); + } + }).booleanValue()) { - if (usage.isValid()) { - usage.highlightInEditor(); - replaceContext.getUsageView().selectUsages(new Usage[]{usage}); - } + if (usage.isValid()) { + usage.highlightInEditor(); + replaceContext.getUsageView().selectUsages(new Usage[]{usage}); } } }; @@ -303,12 +294,7 @@ public class ReplaceInProjectManager { final int currentNumber = i; if (result == FindManager.PromptResult.OK) { final Ref success = Ref.create(); - Runnable runnable = new Runnable() { - @Override - public void run() { - success.set(replaceUsageAndRemoveFromView(usage, replaceContext)); - } - }; + Runnable runnable = () -> success.set(replaceUsageAndRemoveFromView(usage, replaceContext)); CommandProcessor.getInstance().executeCommand(myProject, runnable, FindBundle.message("find.replace.command"), null); if (closeUsageViewIfEmpty(replaceContext.getUsageView(), success.get())) { return; @@ -329,28 +315,25 @@ public class ReplaceInProjectManager { if (result == FindManager.PromptResult.ALL_IN_THIS_FILE) { final int[] nextNumber = new int[1]; - Runnable runnable = new Runnable() { - @Override - public void run() { - int j = currentNumber; - boolean success = true; - for (; j < usages.length; j++) { - final Usage usage = usages[j]; - final UsageInfo usageInfo = ((UsageInfo2UsageAdapter)usage).getUsageInfo(); + Runnable runnable = () -> { + int j = currentNumber; + boolean success = true; + for (; j < usages.length; j++) { + final Usage usage1 = usages[j]; + final UsageInfo usageInfo1 = ((UsageInfo2UsageAdapter)usage1).getUsageInfo(); - final PsiElement elt = usageInfo.getElement(); - if (elt == null) continue; - PsiFile otherPsiFile = elt.getContainingFile(); - if (!otherPsiFile.equals(psiFile)) { - break; - } - if (!replaceUsageAndRemoveFromView(usage, replaceContext)) { - success = false; - } + final PsiElement elt1 = usageInfo1.getElement(); + if (elt1 == null) continue; + PsiFile otherPsiFile = elt1.getContainingFile(); + if (!otherPsiFile.equals(psiFile)) { + break; + } + if (!replaceUsageAndRemoveFromView(usage1, replaceContext)) { + success = false; } - closeUsageViewIfEmpty(replaceContext.getUsageView(), success); - nextNumber[0] = j; } + closeUsageViewIfEmpty(replaceContext.getUsageView(), success); + nextNumber[0] = j; }; CommandProcessor.getInstance().executeCommand(myProject, runnable, FindBundle.message("find.replace.command"), null); @@ -360,12 +343,9 @@ public class ReplaceInProjectManager { } if (result == FindManager.PromptResult.ALL_FILES) { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final boolean success = replaceUsages(replaceContext, _usages); - closeUsageViewIfEmpty(replaceContext.getUsageView(), success); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final boolean success = replaceUsages(replaceContext, _usages); + closeUsageViewIfEmpty(replaceContext.getUsageView(), success); }, FindBundle.message("find.replace.command"), null); break; } @@ -386,20 +366,11 @@ public class ReplaceInProjectManager { } private void addReplaceActions(final ReplaceContext replaceContext) { - final Runnable replaceRunnable = new Runnable() { - @Override - public void run() { - replaceUsagesUnderCommand(replaceContext, replaceContext.getUsageView().getUsages()); - } - }; + final Runnable replaceRunnable = () -> replaceUsagesUnderCommand(replaceContext, replaceContext.getUsageView().getUsages()); replaceContext.getUsageView().addButtonToLowerPane(replaceRunnable, FindBundle.message("find.replace.all.action")); - final Runnable replaceSelectedRunnable = new Runnable() { - @Override - public void run() { - replaceUsagesUnderCommand(replaceContext, replaceContext.getUsageView().getSelectedUsages()); - } - }; + final Runnable replaceSelectedRunnable = + () -> replaceUsagesUnderCommand(replaceContext, replaceContext.getUsageView().getSelectedUsages()); replaceContext.getUsageView().addButtonToLowerPane(replaceSelectedRunnable, FindBundle.message("find.replace.selected.action")); } @@ -455,24 +426,21 @@ public class ReplaceInProjectManager { final Document document = ((UsageInfo2UsageAdapter)usage).getDocument(); if (!document.isWritable()) return false; - boolean result = ((UsageInfo2UsageAdapter)usage).processRangeMarkers(new Processor() { - @Override - public boolean process(Segment segment) { - final int textOffset = segment.getStartOffset(); - final int textEndOffset = segment.getEndOffset(); - final Ref stringToReplace = Ref.create(); - try { - if (!getStringToReplace(textOffset, textEndOffset, document, findModel, stringToReplace)) return true; - if (!stringToReplace.isNull() && !justCheck) { - document.replaceString(textOffset, textEndOffset, stringToReplace.get()); - } + boolean result = ((UsageInfo2UsageAdapter)usage).processRangeMarkers(segment -> { + final int textOffset = segment.getStartOffset(); + final int textEndOffset = segment.getEndOffset(); + final Ref stringToReplace = Ref.create(); + try { + if (!getStringToReplace(textOffset, textEndOffset, document, findModel, stringToReplace)) return true; + if (!stringToReplace.isNull() && !justCheck) { + document.replaceString(textOffset, textEndOffset, stringToReplace.get()); } - catch (FindManager.MalformedReplacementStringException e) { - exceptionResult.set(e); - return false; - } - return true; } + catch (FindManager.MalformedReplacementStringException e) { + exceptionResult.set(e); + return false; + } + return true; }); return result; } @@ -520,15 +488,12 @@ public class ReplaceInProjectManager { if (!ensureUsagesWritable(replaceContext, usages)) return; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final boolean success = replaceUsages(replaceContext, usages); - final UsageView usageView = replaceContext.getUsageView(); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final boolean success = replaceUsages(replaceContext, usages); + final UsageView usageView = replaceContext.getUsageView(); - if (closeUsageViewIfEmpty(usageView, success)) return; - usageView.getComponent().requestFocus(); - } + if (closeUsageViewIfEmpty(usageView, success)) return; + usageView.getComponent().requestFocus(); }, FindBundle.message("find.replace.command"), null); replaceContext.invalidateExcludedSetCache(); diff --git a/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java b/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java index e12d601549b5..fd153cfa9b80 100644 --- a/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java +++ b/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java @@ -322,12 +322,7 @@ public class FormatterImpl extends FormatterEx } else { progressTask.setTask(task); - Runnable callback = new Runnable() { - @Override - public void run() { - enableFormatting(); - } - }; + Runnable callback = () -> enableFormatting(); for (FormattingProgressCallback.EventType eventType : FormattingProgressCallback.EventType.values()) { progressTask.addCallback(eventType, callback); } diff --git a/platform/lang-impl/src/com/intellij/formatting/FormatterTagHandler.java b/platform/lang-impl/src/com/intellij/formatting/FormatterTagHandler.java index 1395f9aa0037..1bfca618803e 100644 --- a/platform/lang-impl/src/com/intellij/formatting/FormatterTagHandler.java +++ b/platform/lang-impl/src/com/intellij/formatting/FormatterTagHandler.java @@ -115,13 +115,7 @@ public class FormatterTagHandler { private List getRanges() { List enabledRanges = new ArrayList(); - Collections.sort(myTagInfoList, new Comparator() { - @Override - public int compare(FormatterTagInfo tagInfo1, - FormatterTagInfo tagInfo2) { - return tagInfo1.offset - tagInfo2.offset; - } - }); + Collections.sort(myTagInfoList, (tagInfo1, tagInfo2) -> tagInfo1.offset - tagInfo2.offset); int start = myInitialRange.getStartOffset(); boolean formatterEnabled = true; diff --git a/platform/lang-impl/src/com/intellij/formatting/WhiteSpace.java b/platform/lang-impl/src/com/intellij/formatting/WhiteSpace.java index 7bee50ca0ea3..86a6024f4e2a 100644 --- a/platform/lang-impl/src/com/intellij/formatting/WhiteSpace.java +++ b/platform/lang-impl/src/com/intellij/formatting/WhiteSpace.java @@ -293,13 +293,10 @@ public class WhiteSpace { * @param indent new value for the {@link #getIndentSpaces()} indentSpaces} property */ public void setSpaces(final int spaces, final int indent) { - performModification(new Runnable() { - @Override - public void run() { - if (!isKeepFirstColumn() || getFlag(CONTAINS_SPACES_INITIALLY_MASK)) { - mySpaces = spaces; - myIndentSpaces = indent; - } + performModification(() -> { + if (!isKeepFirstColumn() || getFlag(CONTAINS_SPACES_INITIALLY_MASK)) { + mySpaces = spaces; + myIndentSpaces = indent; } }); } @@ -373,17 +370,14 @@ public class WhiteSpace { * @param spaceProperty spacing settings holder */ public void arrangeSpaces(final SpacingImpl spaceProperty) { - performModification(new Runnable() { - @Override - public void run() { - if (spaceProperty != null) { - if (getLineFeeds() == 0) { - if (spaceProperty.getMinSpaces() >= 0 && getTotalSpaces() < spaceProperty.getMinSpaces()) { - setSpaces(spaceProperty.getMinSpaces(), 0); - } - if (spaceProperty.getMaxSpaces() >= 0 && getTotalSpaces() > spaceProperty.getMaxSpaces()) { - setSpaces(spaceProperty.getMaxSpaces(), 0); - } + performModification(() -> { + if (spaceProperty != null) { + if (getLineFeeds() == 0) { + if (spaceProperty.getMinSpaces() >= 0 && getTotalSpaces() < spaceProperty.getMinSpaces()) { + setSpaces(spaceProperty.getMinSpaces(), 0); + } + if (spaceProperty.getMaxSpaces() >= 0 && getTotalSpaces() > spaceProperty.getMaxSpaces()) { + setSpaces(spaceProperty.getMaxSpaces(), 0); } } } @@ -395,45 +389,42 @@ public class WhiteSpace { * defined at the given spacing property. */ public void arrangeLineFeeds(final SpacingImpl spaceProperty, final BlockRangesMap helper) { - performModification(new Runnable() { - @Override - public void run() { - if (spaceProperty != null) { - spaceProperty.refresh(helper); + performModification(() -> { + if (spaceProperty != null) { + spaceProperty.refresh(helper); - if (spaceProperty.getMinLineFeeds() >= 0 && getLineFeeds() < spaceProperty.getMinLineFeeds()) { - setLineFeeds(spaceProperty.getMinLineFeeds()); - } - if (getLineFeeds() > 0) { - if (spaceProperty.getKeepBlankLines() > 0) { - if (getLineFeeds() >= spaceProperty.getKeepBlankLines() + 1) { - setLineFeeds(spaceProperty.getKeepBlankLines() + 1); - } - } - else { - if (getLineFeeds() > spaceProperty.getMinLineFeeds()) { - if (spaceProperty.shouldKeepLineFeeds()) { - setLineFeeds(Math.max(spaceProperty.getMinLineFeeds(), 1)); - } - else { - setLineFeeds(spaceProperty.getMinLineFeeds()); - if (getLineFeeds() == 0) mySpaces = 0; - } - } - } - if (getLineFeeds() == 1 && !spaceProperty.shouldKeepLineFeeds() && spaceProperty.getMinLineFeeds() == 0) { - setLineFeeds(0); - mySpaces = 0; - } - - if (getLineFeeds() > 0 && getLineFeeds() < spaceProperty.getPrefLineFeeds()) { - setLineFeeds(spaceProperty.getPrefLineFeeds()); - } - } - } else if (isFirst()) { - setLineFeeds(0); - mySpaces = 0; + if (spaceProperty.getMinLineFeeds() >= 0 && getLineFeeds() < spaceProperty.getMinLineFeeds()) { + setLineFeeds(spaceProperty.getMinLineFeeds()); } + if (getLineFeeds() > 0) { + if (spaceProperty.getKeepBlankLines() > 0) { + if (getLineFeeds() >= spaceProperty.getKeepBlankLines() + 1) { + setLineFeeds(spaceProperty.getKeepBlankLines() + 1); + } + } + else { + if (getLineFeeds() > spaceProperty.getMinLineFeeds()) { + if (spaceProperty.shouldKeepLineFeeds()) { + setLineFeeds(Math.max(spaceProperty.getMinLineFeeds(), 1)); + } + else { + setLineFeeds(spaceProperty.getMinLineFeeds()); + if (getLineFeeds() == 0) mySpaces = 0; + } + } + } + if (getLineFeeds() == 1 && !spaceProperty.shouldKeepLineFeeds() && spaceProperty.getMinLineFeeds() == 0) { + setLineFeeds(0); + mySpaces = 0; + } + + if (getLineFeeds() > 0 && getLineFeeds() < spaceProperty.getPrefLineFeeds()) { + setLineFeeds(spaceProperty.getPrefLineFeeds()); + } + } + } else if (isFirst()) { + setLineFeeds(0); + mySpaces = 0; } }); @@ -480,13 +471,10 @@ public class WhiteSpace { * Tries to ensure that current {@link WhiteSpace} object contains at least one line feed. */ public void ensureLineFeed() { - performModification(new Runnable() { - @Override - public void run() { - if (!containsLineFeeds()) { - setLineFeeds(1); - mySpaces = 0; - } + performModification(() -> { + if (!containsLineFeeds()) { + setLineFeeds(1); + mySpaces = 0; } }); } @@ -541,13 +529,10 @@ public class WhiteSpace { * {@link #arrangeSpaces(SpacingImpl)}. */ public void removeLineFeeds(final SpacingImpl spacing, final BlockRangesMap helper) { - performModification(new Runnable() { - @Override - public void run() { - setLineFeeds(0); - mySpaces = 0; - myIndentSpaces = 0; - } + performModification(() -> { + setLineFeeds(0); + mySpaces = 0; + myIndentSpaces = 0; }); arrangeLineFeeds(spacing, helper); arrangeSpaces(spacing); diff --git a/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java b/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java index 24c2713a6434..ace1b24d9b74 100644 --- a/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java +++ b/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java @@ -117,12 +117,9 @@ public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction { myOKAction = new ApplyToSettings(); myOKAction.setEnabled(false); - myTabbedLanguagePanel.setOnSomethingChangedCallback(new Runnable() { - @Override - public void run() { - boolean isModified = myTabbedLanguagePanel.isModified(mySettings); - myOKAction.setEnabled(isModified); - } + myTabbedLanguagePanel.setOnSomethingChangedCallback(() -> { + boolean isModified = myTabbedLanguagePanel.isModified(mySettings); + myOKAction.setEnabled(isModified); }); myEditor = editor; diff --git a/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/SelectedTextFormatter.java b/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/SelectedTextFormatter.java index 0762289947ad..96d344717e39 100644 --- a/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/SelectedTextFormatter.java +++ b/platform/lang-impl/src/com/intellij/formatting/contextConfiguration/SelectedTextFormatter.java @@ -53,16 +53,8 @@ public class SelectedTextFormatter { final int start = myEditor.getSelectionModel().getSelectionStart(); final int end = myEditor.getSelectionModel().getSelectionEnd(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - document.replaceString(start, end, myTextBefore); - } - }, "Configure code style on selected fragment: restore text before", null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(myProject, () -> document.replaceString(start, end, myTextBefore), "Configure code style on selected fragment: restore text before", null); }); myEditor.getSelectionModel().setSelection(mySelectionStart, mySelectionEnd); @@ -87,17 +79,9 @@ public class SelectedTextFormatter { private static void reformatRange(final @NotNull PsiFile file, final @NotNull TextRange range) { final Project project = file.getProject(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(project).reformatText(file, range.getStartOffset(), range.getEndOffset()); - } - }); - } - }, "Reformat", null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + CodeStyleManager.getInstance(project).reformatText(file, range.getStartOffset(), range.getEndOffset()); + }), "Reformat", null); } @NotNull diff --git a/platform/lang-impl/src/com/intellij/formatting/engine/DependentSpacingEngine.java b/platform/lang-impl/src/com/intellij/formatting/engine/DependentSpacingEngine.java index c3e1d1ac39cc..17a20f1b6791 100644 --- a/platform/lang-impl/src/com/intellij/formatting/engine/DependentSpacingEngine.java +++ b/platform/lang-impl/src/com/intellij/formatting/engine/DependentSpacingEngine.java @@ -52,16 +52,13 @@ public class DependentSpacingEngine { private final BlockRangesMap myBlockRangesMap; private SortedMap myPreviousDependencies = - new TreeMap(new Comparator() { - @Override - public int compare(final TextRange o1, final TextRange o2) { - int offsetsDelta = o1.getEndOffset() - o2.getEndOffset(); + new TreeMap((o1, o2) -> { + int offsetsDelta = o1.getEndOffset() - o2.getEndOffset(); - if (offsetsDelta == 0) { - offsetsDelta = o2.getStartOffset() - o1.getStartOffset(); // starting earlier is greater - } - return offsetsDelta; + if (offsetsDelta == 0) { + offsetsDelta = o2.getStartOffset() - o1.getStartOffset(); // starting earlier is greater } + return offsetsDelta; }); public DependentSpacingEngine(BlockRangesMap helper) { diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/FrameworkDetectionManager.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/FrameworkDetectionManager.java index 81b7deb3ae5c..5cd4d383f065 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/FrameworkDetectionManager.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/FrameworkDetectionManager.java @@ -110,16 +110,13 @@ public class FrameworkDetectionManager extends AbstractProjectComponent implemen @Override public void projectOpened() { - StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - final Collection ids = FrameworkDetectorRegistry.getInstance().getAllDetectorIds(); - synchronized (myLock) { - myDetectorsToProcess.clear(); - myDetectorsToProcess.addAll(ids); - } - queueDetection(); + StartupManager.getInstance(myProject).registerPostStartupActivity(() -> { + final Collection ids = FrameworkDetectorRegistry.getInstance().getAllDetectorIds(); + synchronized (myLock) { + myDetectorsToProcess.clear(); + myDetectorsToProcess.addAll(ids); } + queueDetection(); }); } diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurable.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurable.java index e8fb0748a802..4e53316612f6 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurable.java @@ -126,12 +126,7 @@ public class DetectionExcludesConfigurable implements Configurable { types.add(type); } } - Collections.sort(types, new Comparator() { - @Override - public int compare(FrameworkType o1, FrameworkType o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }); + Collections.sort(types, (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName())); types.add(0, null); final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep("Framework to Exclude", types) { @Override @@ -153,12 +148,7 @@ public class DetectionExcludesConfigurable implements Configurable { @Override public PopupStep onChosen(final FrameworkType frameworkType, boolean finalChoice) { if (frameworkType == null) { - return doFinalStep(new Runnable() { - @Override - public void run() { - chooseDirectoryAndAdd(null); - } - }); + return doFinalStep(() -> chooseDirectoryAndAdd(null)); } else { return addExcludedFramework(frameworkType); @@ -193,12 +183,7 @@ public class DetectionExcludesConfigurable implements Configurable { return FINAL_CHOICE; } else { - return doFinalStep(new Runnable() { - @Override - public void run() { - chooseDirectoryAndAdd(frameworkType); - } - }); + return doFinalStep(() -> chooseDirectoryAndAdd(frameworkType)); } } }; diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurationImpl.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurationImpl.java index bd2cfde85a9f..16a765b5d54c 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurationImpl.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/DetectionExcludesConfigurationImpl.java @@ -190,12 +190,8 @@ public class DetectionExcludesConfigurationImpl extends DetectionExcludesConfigu state.getFiles().add(new ExcludedFileState(url, typeId)); } } - Collections.sort(state.getFiles(), new Comparator() { - @Override - public int compare(ExcludedFileState o1, ExcludedFileState o2) { - return StringUtil.comparePairs(o1.getFrameworkType(), o1.getUrl(), o2.getFrameworkType(), o2.getUrl(), true); - } - }); + Collections.sort(state.getFiles(), + (o1, o2) -> StringUtil.comparePairs(o1.getFrameworkType(), o1.getUrl(), o2.getFrameworkType(), o2.getUrl(), true)); return state; } diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/ExcludeListItem.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/ExcludeListItem.java index 170b8b203666..214a1dad7b9f 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/ExcludeListItem.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/ExcludeListItem.java @@ -25,12 +25,8 @@ import java.util.Comparator; * @author nik */ abstract class ExcludeListItem { - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(ExcludeListItem o1, ExcludeListItem o2) { - return StringUtil.comparePairs(o1.getPresentableFrameworkName(), o1.getFileUrl(), o2.getPresentableFrameworkName(), o2.getFileUrl(), true); - } - }; + public static final Comparator COMPARATOR = + (o1, o2) -> StringUtil.comparePairs(o1.getPresentableFrameworkName(), o1.getFileUrl(), o2.getPresentableFrameworkName(), o2.getFileUrl(), true); public abstract void renderItem(ColoredListCellRenderer renderer); diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionByTypeElement.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionByTypeElement.java index 13488f059ddb..2f4ee1771a4a 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionByTypeElement.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionByTypeElement.java @@ -34,12 +34,8 @@ import java.util.List; */ @Tag("facet-type") public class DisabledAutodetectionByTypeElement { - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(DisabledAutodetectionByTypeElement o1, DisabledAutodetectionByTypeElement o2) { - return StringUtil.compare(o1.getFacetTypeId(), o2.getFacetTypeId(), true); - } - }; + public static final Comparator COMPARATOR = + (o1, o2) -> StringUtil.compare(o1.getFacetTypeId(), o2.getFacetTypeId(), true); private String myFacetTypeId; private List myModuleElements = new SortedList(DisabledAutodetectionInModuleElement.COMPARATOR); diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionInModuleElement.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionInModuleElement.java index 45ad0e8cef92..81796acf2cb0 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionInModuleElement.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/exclude/old/DisabledAutodetectionInModuleElement.java @@ -30,12 +30,8 @@ import java.util.Set; */ @Tag("module") public class DisabledAutodetectionInModuleElement { - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(DisabledAutodetectionInModuleElement o1, DisabledAutodetectionInModuleElement o2) { - return StringUtil.compare(o1.getModuleName(), o2.getModuleName(), true); - } - }; + public static final Comparator COMPARATOR = + (o1, o2) -> StringUtil.compare(o1.getModuleName(), o2.getModuleName(), true); private String myModuleName; private Set myFiles = new LinkedHashSet(); private Set myDirectories = new LinkedHashSet(); diff --git a/platform/lang-impl/src/com/intellij/framework/detection/impl/ui/DetectedFrameworksComponent.java b/platform/lang-impl/src/com/intellij/framework/detection/impl/ui/DetectedFrameworksComponent.java index 0dc854a0d6bc..e938c32b9c17 100644 --- a/platform/lang-impl/src/com/intellij/framework/detection/impl/ui/DetectedFrameworksComponent.java +++ b/platform/lang-impl/src/com/intellij/framework/detection/impl/ui/DetectedFrameworksComponent.java @@ -98,12 +98,7 @@ public class DetectedFrameworksComponent { } public void processUncheckedNodes(final DetectionExcludesConfiguration excludesConfiguration) { - getTree().processUncheckedNodes(new Consumer() { - @Override - public void consume(DetectedFrameworkTreeNodeBase node) { - node.disableDetection(excludesConfiguration); - } - }); + getTree().processUncheckedNodes(node -> node.disableDetection(excludesConfiguration)); } public enum GroupByOption { TYPE, DIRECTORY } diff --git a/platform/lang-impl/src/com/intellij/ide/NativeIconProvider.java b/platform/lang-impl/src/com/intellij/ide/NativeIconProvider.java index ffe8464477c2..1b3990103144 100644 --- a/platform/lang-impl/src/com/intellij/ide/NativeIconProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/NativeIconProvider.java @@ -80,33 +80,30 @@ public class NativeIconProvider extends IconProvider implements DumbAware { if (icon != null) { return icon; } - return new DeferredIconImpl(ElementBase.ICON_PLACEHOLDER.getValue(), file, false, new Function() { - @Override - public Icon fun(VirtualFile virtualFile) { - final File f = new File(filePath); - if (!f.exists()) { - return null; - } - Icon icon; - try { // VM will ensure lock to init -static final field--, note we should have no read access here, to avoid deadlock with EDT needed to init component - assert SwingComponentHolder.ourFileChooser != null || !ApplicationManager.getApplication().isReadAccessAllowed(); - icon = getNativeIcon(f); - } - catch (Exception e) { // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4854174 - return null; - } - if (ext != null) { - synchronized (myIconCache) { - if (!myCustomIconExtensions.contains(ext)) { - myIconCache.put(ext, icon); - } - else if (filePath != null) { - myCustomIconCache.put(filePath, icon); - } + return new DeferredIconImpl(ElementBase.ICON_PLACEHOLDER.getValue(), file, false, virtualFile -> { + final File f = new File(filePath); + if (!f.exists()) { + return null; + } + Icon icon1; + try { // VM will ensure lock to init -static final field--, note we should have no read access here, to avoid deadlock with EDT needed to init component + assert SwingComponentHolder.ourFileChooser != null || !ApplicationManager.getApplication().isReadAccessAllowed(); + icon1 = getNativeIcon(f); + } + catch (Exception e) { // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4854174 + return null; + } + if (ext != null) { + synchronized (myIconCache) { + if (!myCustomIconExtensions.contains(ext)) { + myIconCache.put(ext, icon1); + } + else if (filePath != null) { + myCustomIconCache.put(filePath, icon1); } } - return icon; } + return icon1; }); } diff --git a/platform/lang-impl/src/com/intellij/ide/PsiCopyPasteManager.java b/platform/lang-impl/src/com/intellij/ide/PsiCopyPasteManager.java index af69bbe64074..f2b6e6ade587 100644 --- a/platform/lang-impl/src/com/intellij/ide/PsiCopyPasteManager.java +++ b/platform/lang-impl/src/com/intellij/ide/PsiCopyPasteManager.java @@ -162,27 +162,24 @@ public class PsiCopyPasteManager { public PsiElement[] getElements() { if (myElements == null) return PsiElement.EMPTY_ARRAY; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - int validElementsCount = 0; + ApplicationManager.getApplication().runReadAction(() -> { + int validElementsCount = 0; + for (PsiElement element : myElements) { + if (element.isValid()) { + validElementsCount++; + } + } + + if (validElementsCount != myElements.length) { + PsiElement[] validElements = new PsiElement[validElementsCount]; + int j = 0; for (PsiElement element : myElements) { if (element.isValid()) { - validElementsCount++; + validElements[j++] = element; } } - if (validElementsCount != myElements.length) { - PsiElement[] validElements = new PsiElement[validElementsCount]; - int j = 0; - for (PsiElement element : myElements) { - if (element.isValid()) { - validElements[j++] = element; - } - } - - myElements = validElements; - } + myElements = validElements; } }); diff --git a/platform/lang-impl/src/com/intellij/ide/actions/ApplyIntentionAction.java b/platform/lang-impl/src/com/intellij/ide/actions/ApplyIntentionAction.java index 0c92e0eb31e8..9c6297eea4f6 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/ApplyIntentionAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/ApplyIntentionAction.java @@ -66,11 +66,8 @@ public class ApplyIntentionAction extends AnAction { @Nullable public static ApplyIntentionAction[] getAvailableIntentions(final Editor editor, final PsiFile file) { final ShowIntentionsPass.IntentionsInfo info = new ShowIntentionsPass.IntentionsInfo(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ShowIntentionsPass.getActionsToShow(editor, file, info, -1); - } + ApplicationManager.getApplication().runReadAction(() -> { + ShowIntentionsPass.getActionsToShow(editor, file, info, -1); }); if (info.isEmpty()) return null; diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CopyElementAction.java b/platform/lang-impl/src/com/intellij/ide/actions/CopyElementAction.java index 0aed9b7ba727..fd4359ba2d90 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CopyElementAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CopyElementAction.java @@ -36,11 +36,7 @@ public class CopyElementAction extends AnAction { return; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - }}, "", null + CommandProcessor.getInstance().executeCommand(project, () -> PsiDocumentManager.getInstance(project).commitAllDocuments(), "", null ); final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); PsiElement[] elements; diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CopyReferenceAction.java b/platform/lang-impl/src/com/intellij/ide/actions/CopyReferenceAction.java index bf2ade88ec78..449751db4b65 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CopyReferenceAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CopyReferenceAction.java @@ -156,12 +156,7 @@ public class CopyReferenceAction extends DumbAwareAction { } } - return ContainerUtil.mapNotNull(elements, new Function() { - @Override - public PsiElement fun(PsiElement element) { - return element instanceof PsiFile && !((PsiFile)element).getViewProvider().isPhysical() ? null : adjustElement(element); - } - }); + return ContainerUtil.mapNotNull(elements, element -> element instanceof PsiFile && !((PsiFile)element).getViewProvider().isPhysical() ? null : adjustElement(element)); } private static PsiElement adjustElement(PsiElement element) { diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageAction.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageAction.java index cbf9b89c0e45..527f954d8e0b 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageAction.java @@ -50,15 +50,11 @@ public class CreateDirectoryOrPackageAction extends AnAction implements DumbAwar final CreateDirectoryOrPackageHandler validator = new CreateDirectoryOrPackageHandler(project, directory, isDirectory, isDirectory ? "\\/" : "."); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - public void run() { - Messages.showInputDialog(project, isDirectory - ? IdeBundle.message("prompt.enter.new.directory.name") - : IdeBundle.message("prompt.enter.new.package.name"), - isDirectory ? IdeBundle.message("title.new.directory") : IdeBundle.message("title.new.package"), - Messages.getQuestionIcon(), "", validator); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> Messages.showInputDialog(project, isDirectory + ? IdeBundle.message("prompt.enter.new.directory.name") + : IdeBundle.message("prompt.enter.new.package.name"), + isDirectory ? IdeBundle.message("title.new.directory") : IdeBundle.message("title.new.package"), + Messages.getQuestionIcon(), "", validator)); final PsiElement result = validator.getCreatedElement(); if (result != null) { diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java index 0c9e06567dbc..306b844a2fe9 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java @@ -194,38 +194,27 @@ public class CreateDirectoryOrPackageHandler implements InputValidatorEx { } private void doCreateElement(final String subDirName, final boolean createFile) { - Runnable command = new Runnable() { - @Override - public void run() { - final Runnable run = new Runnable() { - @Override - public void run() { - String dirPath = myDirectory.getVirtualFile().getPresentableUrl(); - String actionName = IdeBundle.message("progress.creating.directory", dirPath, File.separator, subDirName); - LocalHistoryAction action = LocalHistory.getInstance().startAction(actionName); - try { - if (createFile) { - CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(subDirName, myDirectory); - myCreatedElement = mkdirs.directory.createFile(mkdirs.newName); - } else { - createDirectories(subDirName); - } - } - catch (final IncorrectOperationException ex) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showErrorDialog(CreateElementActionBase.filterMessage(ex.getMessage())); - } - }); - } - finally { - action.finish(); - } + Runnable command = () -> { + final Runnable run = () -> { + String dirPath = myDirectory.getVirtualFile().getPresentableUrl(); + String actionName = IdeBundle.message("progress.creating.directory", dirPath, File.separator, subDirName); + LocalHistoryAction action = LocalHistory.getInstance().startAction(actionName); + try { + if (createFile) { + CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(subDirName, myDirectory); + myCreatedElement = mkdirs.directory.createFile(mkdirs.newName); + } else { + createDirectories(subDirName); } - }; - ApplicationManager.getApplication().runWriteAction(run); - } + } + catch (final IncorrectOperationException ex) { + ApplicationManager.getApplication().invokeLater(() -> showErrorDialog(CreateElementActionBase.filterMessage(ex.getMessage()))); + } + finally { + action.finish(); + } + }; + ApplicationManager.getApplication().runWriteAction(run); }; CommandProcessor.getInstance().executeCommand(myProject, command, createFile ? IdeBundle.message("command.create.file") : myIsDirectory diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateFileAction.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateFileAction.java index 35902ab3a850..617c9894bf4e 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateFileAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateFileAction.java @@ -231,12 +231,9 @@ public class CreateFileAction extends CreateElementActionBase implements DumbAwa final Project project = psiDirectory.getProject(); final boolean[] result = {false}; - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - final FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(psiDirectory.getVirtualFile(), getFileName(inputString), project); - result[0] = type != null && MyValidator.super.canClose(getFileName(inputString)); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + final FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(psiDirectory.getVirtualFile(), getFileName(inputString), project); + result[0] = type != null && MyValidator.super.canClose(getFileName(inputString)); }); return result[0]; } diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateAction.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateAction.java index cabbaeb8aed7..6872aa59936a 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateFileFromTemplateAction.java @@ -47,12 +47,8 @@ public abstract class CreateFileFromTemplateAction extends CreateFromTemplateAct protected PsiFile createFileFromTemplate(final String name, final FileTemplate template, final PsiDirectory dir) { final PsiFile[] file = new PsiFile[1]; - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - file[0] = createFileFromTemplate(name, template, dir, getDefaultTemplateProperty(), true); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> file[0] = createFileFromTemplate(name, template, dir, getDefaultTemplateProperty(), true)); return file[0]; } diff --git a/platform/lang-impl/src/com/intellij/ide/actions/NewElementToolbarAction.java b/platform/lang-impl/src/com/intellij/ide/actions/NewElementToolbarAction.java index 93a03da0b8cc..b900c70fe2ac 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/NewElementToolbarAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/NewElementToolbarAction.java @@ -38,12 +38,8 @@ public class NewElementToolbarAction extends NewElementAction { if (e.getData(LangDataKeys.IDE_VIEW) == null) { final Project project = e.getData(CommonDataKeys.PROJECT); final PsiFileSystemItem psiFile = e.getData(CommonDataKeys.PSI_FILE).getParent(); - ProjectViewImpl.getInstance(project).selectCB(psiFile, psiFile.getVirtualFile(), true).doWhenDone(new Runnable() { - @Override - public void run() { - showPopup(DataManager.getInstance().getDataContext()); - } - }); + ProjectViewImpl.getInstance(project).selectCB(psiFile, psiFile.getVirtualFile(), true).doWhenDone( + () -> showPopup(DataManager.getInstance().getDataContext())); } else { super.actionPerformed(e); diff --git a/platform/lang-impl/src/com/intellij/ide/actions/PasteReferenceProvider.java b/platform/lang-impl/src/com/intellij/ide/actions/PasteReferenceProvider.java index 00322d26b48c..c7b8c3a15c62 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/PasteReferenceProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/PasteReferenceProvider.java @@ -94,21 +94,13 @@ public class PasteReferenceProvider implements PasteProvider { final PsiFile file = documentManager.getPsiFile(editor.getDocument()); if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Document document = editor.getDocument(); - documentManager.doPostponedOperationsAndUnblockDocument(document); - documentManager.commitDocument(document); - EditorModificationUtil.deleteSelectedText(editor); - provider.insertQualifiedName(fqn, element, editor, project); - } - }); - } - }, IdeBundle.message("command.pasting.reference"), null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + Document document = editor.getDocument(); + documentManager.doPostponedOperationsAndUnblockDocument(document); + documentManager.commitDocument(document); + EditorModificationUtil.deleteSelectedText(editor); + provider.insertQualifiedName(fqn, element, editor, project); + }), IdeBundle.message("command.pasting.reference"), null); } @Nullable diff --git a/platform/lang-impl/src/com/intellij/ide/actions/ReloadFromDiskAction.java b/platform/lang-impl/src/com/intellij/ide/actions/ReloadFromDiskAction.java index 62be241074b6..063d6d1c5636 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/ReloadFromDiskAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/ReloadFromDiskAction.java @@ -42,22 +42,14 @@ public class ReloadFromDiskAction extends AnAction implements DumbAware { int res = Messages.showOkCancelDialog(project, message, IdeBundle.message("title.reload.file"), Messages.getWarningIcon()); if (res != Messages.OK) return; - Runnable command = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - file.getVirtualFile().refresh(false, false); - PsiManager.getInstance(project).reloadFromDisk(file); - } - } - } - ); + Runnable command = () -> ApplicationManager.getApplication().runWriteAction( + () -> { + if (!project.isDisposed()) { + file.getVirtualFile().refresh(false, false); + PsiManager.getInstance(project).reloadFromDisk(file); + } } - }; + ); CommandProcessor.getInstance().executeCommand(project, command, IdeBundle.message("command.reload.from.disk"), null); } diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchAgainAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchAgainAction.java index 531f3e52159f..65403b76b9a5 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/SearchAgainAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchAgainAction.java @@ -44,18 +44,15 @@ public class SearchAgainAction extends AnAction implements DumbAware { if (editor == null || project == null) return; CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - project, new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); - FindManager findManager = FindManager.getInstance(project); - if(!findManager.selectNextOccurrenceWasPerformed() && findManager.findNextUsageInEditor(editor)) { - return; - } - - FindUtil.searchAgain(project, editor, e.getDataContext()); + project, () -> { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); + FindManager findManager = FindManager.getInstance(project); + if(!findManager.selectNextOccurrenceWasPerformed() && findManager.findNextUsageInEditor(editor)) { + return; } + + FindUtil.searchAgain(project, editor, e.getDataContext()); }, IdeBundle.message("command.find.next"), null diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchBackAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchBackAction.java index 5f6e0d9959bd..978471cef90f 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/SearchBackAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchBackAction.java @@ -42,16 +42,13 @@ public class SearchBackAction extends AnAction implements DumbAware { final FileEditor editor = e.getData(PlatformDataKeys.FILE_EDITOR); CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - project, new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - FindManager findManager = FindManager.getInstance(project); - if(!findManager.selectNextOccurrenceWasPerformed() && findManager.findPreviousUsageInEditor(editor)) { - return; - } - FindUtil.searchBack(project, editor, e.getDataContext()); + project, () -> { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + FindManager findManager = FindManager.getInstance(project); + if(!findManager.selectNextOccurrenceWasPerformed() && findManager.findPreviousUsageInEditor(editor)) { + return; } + FindUtil.searchBack(project, editor, e.getDataContext()); }, IdeBundle.message("command.find.previous"), null diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java index 4c513a0f90ac..991989c08b55 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java @@ -257,11 +257,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA public SearchEverywhereAction() { updateComponents(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - onFocusLost(); - } - }); + SwingUtilities.invokeLater(() -> onFocusLost()); } @@ -304,12 +300,9 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA mySkipFocusGain = true; getField().requestFocus(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myList.setSelectedIndex(i); - doNavigate(i); - } + SwingUtilities.invokeLater(() -> { + myList.setSelectedIndex(i); + doNavigate(i); }); } } @@ -327,12 +320,9 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (editor != null) { final String pattern = editor.getText(); myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (editor.hasFocus()) { - rebuildList(pattern); - } + myAlarm.addRequest(() -> { + if (editor.hasFocus()) { + rebuildList(pattern); } }, 30); } @@ -399,13 +389,10 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA editor.setColumns(SEARCH_FIELD_COLUMNS); myFocusComponent = e.getOppositeComponent(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final JComponent parent = (JComponent)editor.getParent(); - parent.revalidate(); - parent.repaint(); - } + SwingUtilities.invokeLater(() -> { + final JComponent parent = (JComponent)editor.getParent(); + parent.revalidate(); + parent.repaint(); }); //if (myPopup != null && myPopup.isVisible()) { // myPopup.cancel(); @@ -452,31 +439,23 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA private ActionCallback onFocusLost() { final ActionCallback result = new ActionCallback(); //noinspection SSBasedInspection - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - try { - if (myCalcThread != null) { - myCalcThread.cancel(); - //myCalcThread = null; - } - myAlarm.cancelAllRequests(); - if (myBalloon != null && !myBalloon.isDisposed() && myPopup != null && !myPopup.isDisposed()) { - myBalloon.cancel(); - myPopup.cancel(); - } + UIUtil.invokeLaterIfNeeded(() -> { + try { + if (myCalcThread != null) { + myCalcThread.cancel(); + //myCalcThread = null; + } + myAlarm.cancelAllRequests(); + if (myBalloon != null && !myBalloon.isDisposed() && myPopup != null && !myPopup.isDisposed()) { + myBalloon.cancel(); + myPopup.cancel(); + } - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ActionToolbarImpl.updateAllToolbarsImmediately(); - } - }); - } - finally { - result.setDone(); - } + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> ActionToolbarImpl.updateAllToolbarsImmediately()); + } + finally { + result.setDone(); } }); return result; @@ -503,13 +482,10 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA else if (index == model.moreIndex.runConfigurations) wid = WidgetID.RUN_CONFIGURATIONS; if (wid != null) { final WidgetID widgetID = wid; - myCurrentWorker.doWhenProcessed(new Runnable() { - @Override - public void run() { - myCalcThread = new CalcThread(project, pattern, true); - myPopupActualWidth = 0; - myCurrentWorker = myCalcThread.insert(index, widgetID); - } + myCurrentWorker.doWhenProcessed(() -> { + myCalcThread = new CalcThread(project, pattern, true); + myPopupActualWidth = 0; + myCurrentWorker = myCalcThread.insert(index, widgetID); }); return; @@ -534,12 +510,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (value instanceof OptionsTopHitProvider) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - getField().setText("#" + ((OptionsTopHitProvider)value).getId() + " "); - } - }); + SwingUtilities.invokeLater(() -> getField().setText("#" + ((OptionsTopHitProvider)value).getId() + " ")); return; } Runnable onDone = null; @@ -547,57 +518,41 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA AccessToken token = ApplicationManager.getApplication().acquireReadActionLock(); try { if (value instanceof PsiElement) { - onDone = new Runnable() { - public void run() { - NavigationUtil.activateFileWithPsiElement((PsiElement)value, true); - } - }; + onDone = () -> NavigationUtil.activateFileWithPsiElement((PsiElement)value, true); return; } else if (isVirtualFile(value)) { - onDone = new Runnable() { - public void run() { - OpenSourceUtil.navigate(true, new OpenFileDescriptor(project, (VirtualFile)value)); - } - }; + onDone = () -> OpenSourceUtil.navigate(true, new OpenFileDescriptor(project, (VirtualFile)value)); return; } else if (isActionValue(value) || isSetting(value) || isRunConfiguration(value)) { focusManager.requestDefaultFocus(true); final Component comp = myContextComponent; final AnActionEvent event = myActionEvent; - IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - Component c = comp; - if (c == null) { - c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - } + IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> { + Component c = comp; + if (c == null) { + c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + } - if (isRunConfiguration(value)) { - ChooseRunConfigurationPopup.ItemWrapper itemWrapper = (ChooseRunConfigurationPopup.ItemWrapper)value; - RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(itemWrapper.getValue(), RunnerAndConfigurationSettings.class); - if (settings != null) { - Executor executor = findExecutor(settings); - if (executor != null) { - itemWrapper.perform(project, executor, dataManager.getDataContext(c)); - } + if (isRunConfiguration(value)) { + ChooseRunConfigurationPopup.ItemWrapper itemWrapper = (ChooseRunConfigurationPopup.ItemWrapper)value; + RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(itemWrapper.getValue(), RunnerAndConfigurationSettings.class); + if (settings != null) { + Executor executor = findExecutor(settings); + if (executor != null) { + itemWrapper.perform(project, executor, dataManager.getDataContext(c)); } - } else { - GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event); - if (isToolWindowAction(value)) return; } + } else { + GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event); + if (isToolWindowAction(value)) return; } }); return; } else if (value instanceof Navigatable) { - onDone = new Runnable() { - @Override - public void run() { - OpenSourceUtil.navigate(true, (Navigatable)value); - } - }; + onDone = () -> OpenSourceUtil.navigate(true, (Navigatable)value); return; } } @@ -633,13 +588,10 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA assert project != null; myRenderer.myProject = project; - final Runnable run = new Runnable() { - @Override - public void run() { - myCalcThread = new CalcThread(project, pattern, false); - myPopupActualWidth = 0; - myCurrentWorker = myCalcThread.start(); - } + final Runnable run = () -> { + myCalcThread = new CalcThread(project, pattern, false); + myPopupActualWidth = 0; + myCurrentWorker = myCalcThread.start(); }; if (myCurrentWorker.isDone()) { myCurrentWorker.doWhenDone(run); @@ -675,12 +627,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (project == null) return; //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - LookupManager.getInstance(project).hideActiveLookup(); - } - }); + SwingUtilities.invokeLater(() -> LookupManager.getInstance(project).hideActiveLookup()); updateComponents(); myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext()); @@ -780,12 +727,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA @Override public void exitDumbMode() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - rebuildList(myPopupField.getText()); - } - }); + ApplicationManager.getApplication().invokeLater(() -> rebuildList(myPopupField.getText())); } }); @@ -826,12 +768,9 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (myCalcThread != null && !myCalcThread.isCanceled()) { myCalcThread.cancel(); } - myCurrentWorker.doWhenProcessed(new Runnable() { - @Override - public void run() { - myList.setModel(model); - updatePopupBounds(); - } + myCurrentWorker.doWhenProcessed(() -> { + myList.setModel(model); + updatePopupBounds(); }); } @@ -1198,107 +1137,104 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA protected void customizeCellRenderer(@NotNull JList list, final Object value, int index, final boolean selected, boolean hasFocus) { setPaintFocusBorder(false); setIcon(EmptyIcon.ICON_16); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (value instanceof PsiElement) { - String name = myClassModel.getElementName(value); - assert name != null; - append(name); - } - else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) { - final ChooseRunConfigurationPopup.ItemWrapper wrapper = (ChooseRunConfigurationPopup.ItemWrapper)value; - append(wrapper.getText()); - setIcon(wrapper.getIcon()); - RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(wrapper.getValue(), RunnerAndConfigurationSettings.class); - if (settings != null) { - Executor executor = findExecutor(settings); - if (executor != null) { - setLocationString(executor.getId()); - myLocationIcon = executor.getToolWindowIcon(); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (value instanceof PsiElement) { + String name1 = myClassModel.getElementName(value); + assert name1 != null; + append(name1); + } + else if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) { + final ChooseRunConfigurationPopup.ItemWrapper wrapper = (ChooseRunConfigurationPopup.ItemWrapper)value; + append(wrapper.getText()); + setIcon(wrapper.getIcon()); + RunnerAndConfigurationSettings settings = ObjectUtils.tryCast(wrapper.getValue(), RunnerAndConfigurationSettings.class); + if (settings != null) { + Executor executor = findExecutor(settings); + if (executor != null) { + setLocationString(executor.getId()); + myLocationIcon = executor.getToolWindowIcon(); } } - else if (isVirtualFile(value)) { - final VirtualFile file = (VirtualFile)value; - if (file instanceof VirtualFilePathWrapper) { - append(((VirtualFilePathWrapper)file).getPresentablePath()); - } - else { - append(file.getName()); - } - setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); + } + else if (isVirtualFile(value)) { + final VirtualFile file = (VirtualFile)value; + if (file instanceof VirtualFilePathWrapper) { + append(((VirtualFilePathWrapper)file).getPresentablePath()); } - else if (isActionValue(value)) { - final GotoActionModel.ActionWrapper actionWithParentGroup = - value instanceof GotoActionModel.ActionWrapper ? (GotoActionModel.ActionWrapper)value : null; - final AnAction anAction = actionWithParentGroup == null ? (AnAction)value : actionWithParentGroup.getAction(); - final Presentation templatePresentation = anAction.getTemplatePresentation(); - Icon icon = templatePresentation.getIcon(); - if (anAction instanceof ActivateToolWindowAction) { - final String id = ((ActivateToolWindowAction)anAction).getToolWindowId(); - ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(id); - if (toolWindow != null) { - icon = toolWindow.getIcon(); - } + else { + append(file.getName()); + } + setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, myProject)); + } + else if (isActionValue(value)) { + final GotoActionModel.ActionWrapper actionWithParentGroup = + value instanceof GotoActionModel.ActionWrapper ? (GotoActionModel.ActionWrapper)value : null; + final AnAction anAction = actionWithParentGroup == null ? (AnAction)value : actionWithParentGroup.getAction(); + final Presentation templatePresentation = anAction.getTemplatePresentation(); + Icon icon = templatePresentation.getIcon(); + if (anAction instanceof ActivateToolWindowAction) { + final String id = ((ActivateToolWindowAction)anAction).getToolWindowId(); + ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(id); + if (toolWindow != null) { + icon = toolWindow.getIcon(); } + } - append(String.valueOf(templatePresentation.getText())); - if (actionWithParentGroup != null) { - final String groupName = actionWithParentGroup.getGroupName(); - if (!StringUtil.isEmpty(groupName)) { - setLocationString(groupName); - } - } - - final String groupName = actionWithParentGroup == null ? null : actionWithParentGroup.getGroupName(); + append(String.valueOf(templatePresentation.getText())); + if (actionWithParentGroup != null) { + final String groupName = actionWithParentGroup.getGroupName(); if (!StringUtil.isEmpty(groupName)) { setLocationString(groupName); } - if (icon != null && icon.getIconWidth() <= 16 && icon.getIconHeight() <= 16) { - setIcon(IconUtil.toSize(icon, 16, 16)); + } + + final String groupName = actionWithParentGroup == null ? null : actionWithParentGroup.getGroupName(); + if (!StringUtil.isEmpty(groupName)) { + setLocationString(groupName); + } + if (icon != null && icon.getIconWidth() <= 16 && icon.getIconHeight() <= 16) { + setIcon(IconUtil.toSize(icon, 16, 16)); + } + } + else if (isSetting(value)) { + String text = getSettingText((OptionDescription)value); + SimpleTextAttributes attrs = SimpleTextAttributes.REGULAR_ATTRIBUTES; + if (value instanceof Changeable && ((Changeable)value).hasChanged()) { + if (selected) { + attrs = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; + } + else { + SimpleTextAttributes base = SimpleTextAttributes.LINK_BOLD_ATTRIBUTES; + attrs = base.derive(SimpleTextAttributes.STYLE_BOLD, base.getFgColor(), null, null); } } - else if (isSetting(value)) { - String text = getSettingText((OptionDescription)value); - SimpleTextAttributes attrs = SimpleTextAttributes.REGULAR_ATTRIBUTES; - if (value instanceof Changeable && ((Changeable)value).hasChanged()) { - if (selected) { - attrs = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; - } - else { - SimpleTextAttributes base = SimpleTextAttributes.LINK_BOLD_ATTRIBUTES; - attrs = base.derive(SimpleTextAttributes.STYLE_BOLD, base.getFgColor(), null, null); - } - } - append(text, attrs); - final String id = ((OptionDescription)value).getConfigurableId(); - final String name = myConfigurables.get(id); - if (name != null) { - setLocationString(name); - } + append(text, attrs); + final String id = ((OptionDescription)value).getConfigurableId(); + final String name1 = myConfigurables.get(id); + if (name1 != null) { + setLocationString(name1); } - else if (value instanceof OptionsTopHitProvider) { - append("#" + ((OptionsTopHitProvider)value).getId()); + } + else if (value instanceof OptionsTopHitProvider) { + append("#" + ((OptionsTopHitProvider)value).getId()); + } + else { + ItemPresentation presentation = null; + if (value instanceof ItemPresentation) { + presentation = (ItemPresentation)value; } - else { - ItemPresentation presentation = null; - if (value instanceof ItemPresentation) { - presentation = (ItemPresentation)value; - } - else if (value instanceof NavigationItem) { - presentation = ((NavigationItem)value).getPresentation(); - } - if (presentation != null) { - final String text = presentation.getPresentableText(); - append(text == null ? value.toString() : text); - final String location = presentation.getLocationString(); - if (!StringUtil.isEmpty(location)) { - setLocationString(location); - } - Icon icon = presentation.getIcon(false); - if (icon != null) setIcon(icon); + else if (value instanceof NavigationItem) { + presentation = ((NavigationItem)value).getPresentation(); + } + if (presentation != null) { + final String text = presentation.getPresentableText(); + append(text == null ? value.toString() : text); + final String location = presentation.getLocationString(); + if (!StringUtil.isEmpty(location)) { + setLocationString(location); } + Icon icon = presentation.getIcon(false); + if (icon != null) setIcon(icon); } } }); @@ -1382,27 +1318,21 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA check(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - // this line must be called on EDT to avoid context switch at clear().append("text") Don't touch. Ask [kb] - myList.getEmptyText().setText("Searching..."); + SwingUtilities.invokeLater(() -> { + // this line must be called on EDT to avoid context switch at clear().append("text") Don't touch. Ask [kb] + myList.getEmptyText().setText("Searching..."); - if (myList.getModel() instanceof SearchListModel) { - //noinspection unchecked - myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!myDone.isRejected()) { - myList.setModel(myListModel); - updatePopup(); - } - } - }, 50); - } else { - myList.setModel(myListModel); - } + if (myList.getModel() instanceof SearchListModel) { + //noinspection unchecked + myAlarm.cancelAllRequests(); + myAlarm.addRequest(() -> { + if (!myDone.isRejected()) { + myList.setModel(myListModel); + updatePopup(); + } + }, 50); + } else { + myList.setModel(myListModel); } }); @@ -1418,11 +1348,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (!pattern.startsWith("#")) { buildRecentFiles(pattern); check(); - runReadAction(new Runnable() { - public void run() { - buildStructure(pattern); - } - }, true); + runReadAction(() -> buildStructure(pattern), true); updatePopup(); check(); buildToolWindows(pattern); @@ -1430,26 +1356,10 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA updatePopup(); check(); - runReadAction(new Runnable() { - public void run() { - buildRunConfigurations(pattern); - } - }, true); - runReadAction(new Runnable() { - public void run() { - buildClasses(pattern); - } - }, true); - runReadAction(new Runnable() { - public void run() { - buildFiles(pattern); - } - }, false); - runReadAction(new Runnable() { - public void run() { - buildSymbols(pattern); - } - }, true); + runReadAction(() -> buildRunConfigurations(pattern), true); + runReadAction(() -> buildClasses(pattern), true); + runReadAction(() -> buildFiles(pattern), false); + runReadAction(() -> buildSymbols(pattern), true); buildActionsAndSettings(pattern); @@ -1468,12 +1378,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA finally { if (!isCanceled()) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myList.getEmptyText().setText(StatusText.DEFAULT_EMPTY_TEXT); - } - }); + SwingUtilities.invokeLater(() -> myList.getEmptyText().setText(StatusText.DEFAULT_EMPTY_TEXT)); updatePopup(); } if (!myDone.isProcessed()) { @@ -1517,13 +1422,10 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA return; } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myListModel.titleIndex.toolWindows = myListModel.size(); - for (Object toolWindow : actions) { - myListModel.addElement(toolWindow); - } + SwingUtilities.invokeLater(() -> { + myListModel.titleIndex.toolWindows = myListModel.size(); + for (Object toolWindow : actions) { + myListModel.addElement(toolWindow); } }); } @@ -1538,31 +1440,28 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA myActionProvider = createActionProvider(); } - myActionProvider.filterElements(pattern, true, new Processor() { - @Override - public boolean process(GotoActionModel.MatchedValue matched) { - check(); - Object object = matched.value; - if (myListModel.contains(object)) return true; + myActionProvider.filterElements(pattern, true, matched -> { + check(); + Object object = matched.value; + if (myListModel.contains(object)) return true; - if (!actions && isSetting(object)) { - if (matcher.matches(getSettingText((OptionDescription)object))) { - result.add(object); - } + if (!actions && isSetting(object)) { + if (matcher.matches(getSettingText((OptionDescription)object))) { + result.add(object); } - else if (actions && !isToolWindowAction(object) && isActionValue(object)) { - AnAction action = object instanceof AnAction ? ((AnAction)object) : ((GotoActionModel.ActionWrapper)object).getAction(); - Object lock = myCalcThread; - if (lock != null) { - synchronized (lock) { - if (isEnabled(action)) { - result.add(object); - } + } + else if (actions && !isToolWindowAction(object) && isActionValue(object)) { + AnAction action = object instanceof AnAction ? ((AnAction)object) : ((GotoActionModel.ActionWrapper)object).getAction(); + Object lock = myCalcThread; + if (lock != null) { + synchronized (lock) { + if (isEnabled(action)) { + result.add(object); } } } - return result.size() <= max; } + return result.size() <= max; }); return result; @@ -1574,25 +1473,22 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA check(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - if (actions.size() > 0) { - myListModel.titleIndex.actions = myListModel.size(); - for (Object action : actions) { - myListModel.addElement(action); - } + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + if (actions.size() > 0) { + myListModel.titleIndex.actions = myListModel.size(); + for (Object action : actions) { + myListModel.addElement(action); } - myListModel.moreIndex.actions = actions.size() >= MAX_ACTIONS ? myListModel.size() - 1 : -1; - if (settings.size() > 0) { - myListModel.titleIndex.settings = myListModel.size(); - for (Object setting : settings) { - myListModel.addElement(setting); - } - } - myListModel.moreIndex.settings = settings.size() >= MAX_SETTINGS ? myListModel.size() - 1 : -1; } + myListModel.moreIndex.actions = actions.size() >= MAX_ACTIONS ? myListModel.size() - 1 : -1; + if (settings.size() > 0) { + myListModel.titleIndex.settings = myListModel.size(); + for (Object setting : settings) { + myListModel.addElement(setting); + } + } + myListModel.moreIndex.settings = settings.size() >= MAX_SETTINGS ? myListModel.size() - 1 : -1; }); } @@ -1602,16 +1498,13 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA check(); if (files.size() > 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - myListModel.titleIndex.files = myListModel.size(); - for (Object file : files) { - myListModel.addElement(file); - } - myListModel.moreIndex.files = files.needMore ? myListModel.size() - 1 : -1; + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + myListModel.titleIndex.files = myListModel.size(); + for (Object file : files) { + myListModel.addElement(file); } + myListModel.moreIndex.files = files.needMore ? myListModel.size() - 1 : -1; }); } } @@ -1622,16 +1515,13 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA final MinusculeMatcher matcher = NameUtil.buildMatcher("*" + pattern).build(); fillStructure(myStructureModel.getRoot(), elements, matcher); if (elements.size() > 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - myListModel.titleIndex.structure = myListModel.size(); - for (Object element : elements) { - myListModel.addElement(element); - } - myListModel.moreIndex.files = -1; + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + myListModel.titleIndex.structure = myListModel.size(); + for (Object element : elements) { + myListModel.addElement(element); } + myListModel.moreIndex.files = -1; }); } } @@ -1657,16 +1547,13 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA check(); if (symbols.size() > 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - myListModel.titleIndex.symbols = myListModel.size(); - for (Object file : symbols) { - myListModel.addElement(file); - } - myListModel.moreIndex.symbols = symbols.needMore ? myListModel.size() - 1 : -1; + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + myListModel.titleIndex.symbols = myListModel.size(); + for (Object file : symbols) { + myListModel.addElement(file); } + myListModel.moreIndex.symbols = symbols.needMore ? myListModel.size() - 1 : -1; }); } } @@ -1693,16 +1580,13 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA final SearchResult runConfigurations = getConfigurations(pattern, MAX_RUN_CONFIGURATION); if (runConfigurations.size() > 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - myListModel.titleIndex.runConfigurations = myListModel.size(); - for (Object runConfiguration : runConfigurations) { - myListModel.addElement(runConfiguration); - } - myListModel.moreIndex.runConfigurations = runConfigurations.needMore ? myListModel.getSize() - 1 : -1; + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + myListModel.titleIndex.runConfigurations = myListModel.size(); + for (Object runConfiguration : runConfigurations) { + myListModel.addElement(runConfiguration); } + myListModel.moreIndex.runConfigurations = runConfigurations.needMore ? myListModel.getSize() - 1 : -1; }); } } @@ -1741,18 +1625,15 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA check(); if (classes.size() > 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - myListModel.titleIndex.classes = myListModel.size(); - for (Object file : classes) { - myListModel.addElement(file); - } - myListModel.moreIndex.classes = -1; - if (classes.needMore) { - myListModel.moreIndex.classes = myListModel.size() - 1; - } + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + myListModel.titleIndex.classes = myListModel.size(); + for (Object file : classes) { + myListModel.addElement(file); + } + myListModel.moreIndex.classes = -1; + if (classes.needMore) { + myListModel.moreIndex.classes = myListModel.size() - 1; } }); } @@ -1767,29 +1648,26 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (chooseByNamePopup == null) return symbols; final ChooseByNameItemProvider provider = chooseByNamePopup.getProvider(); provider.filterElements(chooseByNamePopup, pattern, includeLibs, - myProgressIndicator, new Processor() { - @Override - public boolean process(Object o) { - if (SearchEverywhereClassifier.EP_Manager.isSymbol(o) && !myListModel.contains(o) && !symbols.contains(o)) { - PsiElement element = null; - if (o instanceof PsiElement) { - element = (PsiElement)o; - } - else if (o instanceof PsiElementNavigationItem) { - element = ((PsiElementNavigationItem)o).getTargetElement(); - } - VirtualFile virtualFile = SearchEverywhereClassifier.EP_Manager.getVirtualFile(o); - //some elements are non-physical like DB columns - boolean isElementWithoutFile = element != null && element.getContainingFile() == null; - boolean isFileInScope = virtualFile != null && (includeLibs || scope.accept(virtualFile)); - if (isElementWithoutFile || isFileInScope) { - symbols.add(o); - } - } - symbols.needMore = symbols.size() == max; - return !symbols.needMore; - } - }); + myProgressIndicator, o -> { + if (SearchEverywhereClassifier.EP_Manager.isSymbol(o) && !myListModel.contains(o) && !symbols.contains(o)) { + PsiElement element = null; + if (o instanceof PsiElement) { + element = (PsiElement)o; + } + else if (o instanceof PsiElementNavigationItem) { + element = ((PsiElementNavigationItem)o).getTargetElement(); + } + VirtualFile virtualFile = SearchEverywhereClassifier.EP_Manager.getVirtualFile(o); + //some elements are non-physical like DB columns + boolean isElementWithoutFile = element != null && element.getContainingFile() == null; + boolean isFileInScope = virtualFile != null && (includeLibs || scope.accept(virtualFile)); + if (isElementWithoutFile || isFileInScope) { + symbols.add(o); + } + } + symbols.needMore = symbols.size() == max; + return !symbols.needMore; + }); if (!includeLibs && symbols.isEmpty()) { return getSymbols(pattern, max, true, chooseByNamePopup); @@ -1804,37 +1682,34 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA return classes; } chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, includeLibs, - myProgressIndicator, new Processor() { - @Override - public boolean process(Object o) { - if (SearchEverywhereClassifier.EP_Manager.isClass(o) && !myListModel.contains(o) && !classes.contains(o)) { - if (classes.size() == max) { - classes.needMore = true; - return false; - } + myProgressIndicator, o -> { + if (SearchEverywhereClassifier.EP_Manager.isClass(o) && !myListModel.contains(o) && !classes.contains(o)) { + if (classes.size() == max) { + classes.needMore = true; + return false; + } - PsiElement element = null; - if (o instanceof PsiElement) { - element = (PsiElement)o; - } - else if (o instanceof PsiElementNavigationItem) { - element = ((PsiElementNavigationItem)o).getTargetElement(); - } - classes.add(o); + PsiElement element = null; + if (o instanceof PsiElement) { + element = (PsiElement)o; + } + else if (o instanceof PsiElementNavigationItem) { + element = ((PsiElementNavigationItem)o).getTargetElement(); + } + classes.add(o); - if (element instanceof PsiNamedElement) { - final String name = ((PsiNamedElement)element).getName(); - VirtualFile virtualFile = SearchEverywhereClassifier.EP_Manager.getVirtualFile(o); - if (virtualFile != null) { - if (StringUtil.equals(name, virtualFile.getNameWithoutExtension())) { - myAlreadyAddedFiles.add(virtualFile); - } - } - } - } - return true; - } - }); + if (element instanceof PsiNamedElement) { + final String name = ((PsiNamedElement)element).getName(); + VirtualFile virtualFile = SearchEverywhereClassifier.EP_Manager.getVirtualFile(o); + if (virtualFile != null) { + if (StringUtil.equals(name, virtualFile.getNameWithoutExtension())) { + myAlreadyAddedFiles.add(virtualFile); + } + } + } + } + return true; + }); if (!includeLibs && classes.isEmpty()) { return getClasses(pattern, true, max, chooseByNamePopup); } @@ -1848,32 +1723,29 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } final GlobalSearchScope scope = GlobalSearchScope.projectScope(project); chooseByNamePopup.getProvider().filterElements(chooseByNamePopup, pattern, true, - myProgressIndicator, new Processor() { - @Override - public boolean process(Object o) { - VirtualFile file = null; - if (o instanceof VirtualFile) { - file = (VirtualFile)o; - } else if (o instanceof PsiFile) { - file = ((PsiFile)o).getVirtualFile(); - } else if (o instanceof PsiDirectory) { - file = ((PsiDirectory)o).getVirtualFile(); - } - if (file != null - && !(pattern.indexOf(' ') != -1 && file.getName().indexOf(' ') == -1) - && (includeLibs || scope.accept(file) - && !myListModel.contains(file) - && !myAlreadyAddedFiles.contains(file)) - && !files.contains(file)) { - if (files.size() == max) { - files.needMore = true; - return false; - } - files.add(file); - } - return true; - } - }); + myProgressIndicator, o -> { + VirtualFile file = null; + if (o instanceof VirtualFile) { + file = (VirtualFile)o; + } else if (o instanceof PsiFile) { + file = ((PsiFile)o).getVirtualFile(); + } else if (o instanceof PsiDirectory) { + file = ((PsiDirectory)o).getVirtualFile(); + } + if (file != null + && !(pattern.indexOf(' ') != -1 && file.getName().indexOf(' ') == -1) + && (includeLibs || scope.accept(file) + && !myListModel.contains(file) + && !myAlreadyAddedFiles.contains(file)) + && !files.contains(file)) { + if (files.size() == max) { + files.needMore = true; + return false; + } + files.add(file); + } + return true; + }); if (!includeLibs && files.isEmpty()) { return getFiles(pattern, true, max, chooseByNamePopup); } @@ -1897,16 +1769,13 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (files.size() > 0) { myAlreadyAddedFiles.addAll(files); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; - myListModel.titleIndex.recentFiles = myListModel.size(); - for (Object file : files) { - myListModel.addElement(file); - } - updatePopup(); + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; + myListModel.titleIndex.recentFiles = myListModel.size(); + for (Object file : files) { + myListModel.addElement(file); } + updatePopup(); }); } } @@ -1924,25 +1793,23 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA switch (type){ case PSI: if (!DumbService.isDumb(project)) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { + ApplicationManager.getApplication().runReadAction(() -> { - final int i = history.fqn.indexOf("://"); - if (i != -1) { - final String langId = history.fqn.substring(0, i); - final Language language = Language.findLanguageByID(langId); - final String psiFqn = history.fqn.substring(i + 3); - if (language != null) { - final PsiElement psi = - LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).findByQualifiedName(project, psiFqn); - if (psi != null) { - elements.add(psi); - final PsiFile psiFile = psi.getContainingFile(); - if (psiFile != null) { - final VirtualFile file = psiFile.getVirtualFile(); - if (file != null) { - myAlreadyAddedFiles.add(file); - } + final int i = history.fqn.indexOf("://"); + if (i != -1) { + final String langId = history.fqn.substring(0, i); + final Language language = Language.findLanguageByID(langId); + final String psiFqn = history.fqn.substring(i + 3); + if (language != null) { + final PsiElement psi = + LanguagePsiElementExternalizer.INSTANCE.forLanguage(language).findByQualifiedName(project, psiFqn); + if (psi != null) { + elements.add(psi); + final PsiFile psiFile = psi.getContainingFile(); + if (psiFile != null) { + final VirtualFile file = psiFile.getVirtualFile(); + if (file != null) { + myAlreadyAddedFiles.add(file); } } } @@ -1968,12 +1835,10 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA break; case RUN_CONFIGURATION: if (!DumbService.isDumb(project)) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final ChooseRunConfigurationPopup.ItemWrapper runConfiguration = getRunConfigurationByName(history.fqn); - if (runConfiguration != null) { - elements.add(runConfiguration); - } + ApplicationManager.getApplication().runReadAction(() -> { + final ChooseRunConfigurationPopup.ItemWrapper runConfiguration = getRunConfigurationByName(history.fqn); + if (runConfiguration != null) { + elements.add(runConfiguration); } }); } @@ -1981,15 +1846,12 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } } } - final Consumer consumer = new Consumer() { - @Override - public void consume(Object o) { - if (isSetting(o) || isVirtualFile(o) || isActionValue(o) || o instanceof PsiElement || o instanceof OptionsTopHitProvider) { - if (o instanceof AnAction && myAlreadyAddedActions.contains(o)) { - return; - } - elements.add(o); + final Consumer consumer = o -> { + if (isSetting(o) || isVirtualFile(o) || isActionValue(o) || o instanceof PsiElement || o instanceof OptionsTopHitProvider) { + if (o instanceof AnAction && myAlreadyAddedActions.contains(o)) { + return; } + elements.add(o); } }; @@ -2022,24 +1884,21 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } } if (elements.size() > 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isCanceled()) return; + SwingUtilities.invokeLater(() -> { + if (isCanceled()) return; - for (Object element : new ArrayList(elements)) { - if (element instanceof AnAction) { - if (!isEnabled((AnAction)element)) { - elements.remove(element); - } - if (isCanceled()) return; + for (Object element : new ArrayList(elements)) { + if (element instanceof AnAction) { + if (!isEnabled((AnAction)element)) { + elements.remove(element); } + if (isCanceled()) return; } - if (isCanceled() || elements.isEmpty()) return; - myListModel.titleIndex.topHit = myListModel.size(); - for (Object element : ContainerUtil.getFirstItems(elements, MAX_TOP_HIT)) { - myListModel.addElement(element); - } + } + if (isCanceled() || elements.isEmpty()) return; + myListModel.titleIndex.topHit = myListModel.size(); + for (Object element : ContainerUtil.getFirstItems(elements, MAX_TOP_HIT)) { + myListModel.addElement(element); } }); } @@ -2082,13 +1941,11 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA fillConfigurablesIds(null, ShowSettingsUtilImpl.getConfigurables(project, true)); } if (myStructureModel == null && myFileEditor != null && Registry.is("search.everywhere.structure")) { - runReadAction(new Runnable() { - public void run() { - StructureViewBuilder structureViewBuilder = myFileEditor.getStructureViewBuilder(); - if (structureViewBuilder == null) return; - StructureView structureView = structureViewBuilder.createStructureView(myFileEditor, project); - myStructureModel = structureView.getTreeModel(); - } + runReadAction(() -> { + StructureViewBuilder structureViewBuilder = myFileEditor.getStructureViewBuilder(); + if (structureViewBuilder == null) return; + StructureView structureView = structureViewBuilder.createStructureView(myFileEditor, project); + myStructureModel = structureView.getTreeModel(); }, true); } } @@ -2178,32 +2035,21 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA Disposer.register(myPopup, new Disposable() { @Override public void dispose() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - resetFields(); - myNonProjectCheckBox.setSelected(false); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ActionToolbarImpl.updateAllToolbarsImmediately(); - } - }); - if (myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) { - final Component component = myActionEvent.getInputEvent().getComponent(); - if (component != null) { - final JLabel label = UIUtil.getParentOfType(JLabel.class, component); - if (label != null) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - label.setIcon(AllIcons.Actions.FindPlain); - } - }); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + resetFields(); + myNonProjectCheckBox.setSelected(false); + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> ActionToolbarImpl.updateAllToolbarsImmediately()); + if (myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) { + final Component component = myActionEvent.getInputEvent().getComponent(); + if (component != null) { + final JLabel label = UIUtil.getParentOfType(JLabel.class, component); + if (label != null) { + SwingUtilities.invokeLater(() -> label.setIcon(AllIcons.Actions.FindPlain)); } } - myActionEvent = null; } + myActionEvent = null; }); } }); @@ -2241,64 +2087,54 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } public ActionCallback insert(final int index, final WidgetID id) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - runReadAction(new Runnable() { - @Override - public void run() { - try { - final SearchResult result - = id == WidgetID.CLASSES ? getClasses(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myClassChooseByName) - : id == WidgetID.FILES ? getFiles(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myFileChooseByName) - : id == WidgetID.RUN_CONFIGURATIONS ? getConfigurations(pattern, DEFAULT_MORE_STEP_COUNT) - : id == WidgetID.SYMBOLS ? getSymbols(pattern, DEFAULT_MORE_STEP_COUNT, showAll.get(), mySymbolsChooseByName) - : id == WidgetID.ACTIONS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, true) - : id == WidgetID.SETTINGS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, false) - : new SearchResult(); + ApplicationManager.getApplication().executeOnPooledThread(() -> runReadAction(() -> { + try { + final SearchResult result + = id == WidgetID.CLASSES ? getClasses(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myClassChooseByName) + : id == WidgetID.FILES ? getFiles(pattern, showAll.get(), DEFAULT_MORE_STEP_COUNT, myFileChooseByName) + : id == WidgetID.RUN_CONFIGURATIONS ? getConfigurations(pattern, DEFAULT_MORE_STEP_COUNT) + : id == WidgetID.SYMBOLS ? getSymbols(pattern, DEFAULT_MORE_STEP_COUNT, showAll.get(), mySymbolsChooseByName) + : id == WidgetID.ACTIONS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, true) + : id == WidgetID.SETTINGS ? getActionsOrSettings(pattern, DEFAULT_MORE_STEP_COUNT, false) + : new SearchResult(); - check(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - int shift = 0; - int i = index+1; - for (Object o : result) { - //noinspection unchecked - myListModel.insertElementAt(o, i); - shift++; - i++; - } - MoreIndex moreIndex = myListModel.moreIndex; - myListModel.titleIndex.shift(index, shift); - moreIndex.shift(index, shift); + check(); + SwingUtilities.invokeLater(() -> { + try { + int shift = 0; + int i = index+1; + for (Object o : result) { + //noinspection unchecked + myListModel.insertElementAt(o, i); + shift++; + i++; + } + MoreIndex moreIndex = myListModel.moreIndex; + myListModel.titleIndex.shift(index, shift); + moreIndex.shift(index, shift); - if (!result.needMore) { - switch (id) { - case CLASSES: moreIndex.classes = -1; break; - case FILES: moreIndex.files = -1; break; - case ACTIONS: moreIndex.actions = -1; break; - case SETTINGS: moreIndex.settings = -1; break; - case SYMBOLS: moreIndex.symbols = -1; break; - case RUN_CONFIGURATIONS: moreIndex.runConfigurations = -1; break; - } - } - ScrollingUtil.selectItem(myList, index); - myDone.setDone(); - } - catch (Exception e) { - myDone.setRejected(); - } - } - }); - } - catch (Exception e) { - myDone.setRejected(); - } - } - }, true); - } - }); + if (!result.needMore) { + switch (id) { + case CLASSES: moreIndex.classes = -1; break; + case FILES: moreIndex.files = -1; break; + case ACTIONS: moreIndex.actions = -1; break; + case SETTINGS: moreIndex.settings = -1; break; + case SYMBOLS: moreIndex.symbols = -1; break; + case RUN_CONFIGURATIONS: moreIndex.runConfigurations = -1; break; + } + } + ScrollingUtil.selectItem(myList, index); + myDone.setDone(); + } + catch (Exception e) { + myDone.setRejected(); + } + }); + } + catch (Exception e) { + myDone.setRejected(); + } + }, true)); return myDone; } @@ -2316,52 +2152,44 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA if (myBalloon != null) { final JBPopup balloonToBeCanceled = myBalloon; //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - balloonToBeCanceled.cancel(); - } - }); + SwingUtilities.invokeLater(() -> balloonToBeCanceled.cancel()); myBalloon = null; } - myCurrentWorker.doWhenProcessed(new Runnable() { - @Override - public void run() { - myFileModel = null; - if (myFileChooseByName != null) { - myFileChooseByName.close(false); - myFileChooseByName = null; - } - if (myClassChooseByName != null) { - myClassChooseByName.close(false); - myClassChooseByName = null; - } - if (mySymbolsChooseByName != null) { - mySymbolsChooseByName.close(false); - mySymbolsChooseByName = null; - } - final Object lock = myCalcThread; - if (lock != null) { - synchronized (lock) { - myClassModel = null; - myActionProvider = null; - mySymbolsModel = null; - myConfigurables.clear(); - myFocusComponent = null; - myContextComponent = null; - myFocusOwner = null; - myRenderer.myProject = null; - myPopup = null; - myHistoryIndex = 0; - myPopupActualWidth = 0; - myCurrentWorker = ActionCallback.DONE; - showAll.set(false); - myCalcThread = null; - myEditor = null; - myFileEditor = null; - myStructureModel = null; - myDisabledActions.clear(); - } + myCurrentWorker.doWhenProcessed(() -> { + myFileModel = null; + if (myFileChooseByName != null) { + myFileChooseByName.close(false); + myFileChooseByName = null; + } + if (myClassChooseByName != null) { + myClassChooseByName.close(false); + myClassChooseByName = null; + } + if (mySymbolsChooseByName != null) { + mySymbolsChooseByName.close(false); + mySymbolsChooseByName = null; + } + final Object lock = myCalcThread; + if (lock != null) { + synchronized (lock) { + myClassModel = null; + myActionProvider = null; + mySymbolsModel = null; + myConfigurables.clear(); + myFocusComponent = null; + myContextComponent = null; + myFocusOwner = null; + myRenderer.myProject = null; + myPopup = null; + myHistoryIndex = 0; + myPopupActualWidth = 0; + myCurrentWorker = ActionCallback.DONE; + showAll.set(false); + myCalcThread = null; + myEditor = null; + myFileEditor = null; + myStructureModel = null; + myDisabledActions.clear(); } } }); diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java index ccbfc7922a85..4836d1265948 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java @@ -165,16 +165,13 @@ public class Bookmark implements Navigatable, Comparable { final int endOffset = markupDocument.getTextLength(); final Ref found = new Ref(); - markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(RangeHighlighterEx highlighter) { - GutterMark renderer = highlighter.getGutterIconRenderer(); - if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == Bookmark.this) { - found.set(highlighter); - return false; - } - return true; + markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> { + GutterMark renderer = highlighter.getGutterIconRenderer(); + if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == Bookmark.this) { + found.set(highlighter); + return false; } + return true; }); return found.get(); } @@ -336,13 +333,9 @@ public class Bookmark implements Navigatable, Comparable { @Override public void paintIcon(Component c, Graphics g, int x, int y) { - g.setColor(new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - //noinspection UseJBColor - return !darkBackground() ? new Color(0xffffcc) : new Color(0x675133); - } + g.setColor(new JBColor(() -> { + //noinspection UseJBColor + return !darkBackground() ? new Color(0xffffcc) : new Color(0x675133); })); g.fillRect(x, y, getIconWidth(), getIconHeight()); diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java index 510b7471a6bc..b55df6aa2e0f 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java @@ -101,12 +101,9 @@ public class BookmarkManager extends AbstractProjectComponent implements Persist if (file == null) return; for (final Bookmark bookmark : myBookmarks) { if (Comparing.equal(bookmark.getFile(), file)) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - bookmark.createHighlighter((MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true)); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myProject.isDisposed()) return; + bookmark.createHighlighter((MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true)); }); } } @@ -122,12 +119,7 @@ public class BookmarkManager extends AbstractProjectComponent implements Persist public void uiSettingsChanged(UISettings source) { if (mySortedState != UISettings.getInstance().SORT_BOOKMARKS) { mySortedState = UISettings.getInstance().SORT_BOOKMARKS; - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - myBus.syncPublisher(BookmarksListener.TOPIC).bookmarksOrderChanged(); - } - }); + EventQueue.invokeLater(() -> myBus.syncPublisher(BookmarksListener.TOPIC).bookmarksOrderChanged()); } } }, project); @@ -358,12 +350,9 @@ public class BookmarkManager extends AbstractProjectComponent implements Persist final int index = myBookmarks.indexOf(bookmark); if (index > 0) { Collections.swap(myBookmarks, index, index - 1); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index)); - myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index - 1)); - } + EventQueue.invokeLater(() -> { + myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index)); + myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index - 1)); }); } return myBookmarks; @@ -380,12 +369,9 @@ public class BookmarkManager extends AbstractProjectComponent implements Persist final int index = myBookmarks.indexOf(bookmark); if (index < myBookmarks.size() - 1) { Collections.swap(myBookmarks, index, index + 1); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index)); - myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index + 1)); - } + EventQueue.invokeLater(() -> { + myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index)); + myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(myBookmarks.get(index + 1)); }); } @@ -429,12 +415,7 @@ public class BookmarkManager extends AbstractProjectComponent implements Persist } Bookmark[] bookmarks = answer.toArray(new Bookmark[answer.size()]); - Arrays.sort(bookmarks, new Comparator() { - @Override - public int compare(final Bookmark o1, final Bookmark o2) { - return o1.getLine() - o2.getLine(); - } - }); + Arrays.sort(bookmarks, (o1, o2) -> o1.getLine() - o2.getLine()); return bookmarks; } diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java index acfa80c3feed..b322c4cd074d 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java @@ -90,18 +90,8 @@ public class BookmarksAction extends AnAction implements DumbAware, MasterDetail setDimensionServiceKey(DIMENSION_SERVICE_KEY). setAddDetailViewToEast(true). setActionsGroup(actions). - setPopupTuner(new Consumer() { - @Override - public void consume(PopupChooserBuilder builder) { - builder.setCloseOnEnter(false).setCancelOnClickOutside(false); - } - }). - setDoneRunnable(new Runnable() { - @Override - public void run() { - myPopup.cancel(); - } - }). + setPopupTuner(builder -> builder.setCloseOnEnter(false).setCancelOnClickOutside(false)). + setDoneRunnable(() -> myPopup.cancel()). createMasterDetailPopup(); new AnAction() { @@ -179,12 +169,7 @@ public class BookmarksAction extends AnAction implements DumbAware, MasterDetail final Bookmark bookmark = BookmarkManager.getInstance(project).findBookmarkForMnemonic(mnemonic); if (bookmark != null) { popup.cancel(); - IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - bookmark.navigate(true); - } - }); + IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> bookmark.navigate(true)); } } diff --git a/platform/lang-impl/src/com/intellij/ide/commander/AbstractListBuilder.java b/platform/lang-impl/src/com/intellij/ide/commander/AbstractListBuilder.java index 778734ca4d52..bfead6c1b49c 100644 --- a/platform/lang-impl/src/com/intellij/ide/commander/AbstractListBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/commander/AbstractListBuilder.java @@ -273,12 +273,7 @@ public abstract class AbstractListBuilder { myCurrentParent = parentElement; final Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); alarm.addRequest( - new Runnable() { - @Override - public void run() { - myList.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } - }, + () -> myList.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)), 200 ); @@ -302,12 +297,7 @@ public abstract class AbstractListBuilder { final int n = alarm.cancelAllRequests(); if (n == 0) { alarm.addRequest( - new Runnable() { - @Override - public void run() { - myList.setCursor(Cursor.getDefaultCursor()); - } - }, + () -> myList.setCursor(Cursor.getDefaultCursor()), 0 ); } diff --git a/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java b/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java index 42ae9836719f..c08a128dd483 100644 --- a/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java @@ -576,20 +576,14 @@ public class CommanderPanel extends JPanel { if (!isDirectory) { EditorHelper.openInEditor(element); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myBuilder.selectElement(element, PsiUtilCore.getVirtualFile(element)); - if (!isDirectory) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myMoveFocus) { - ToolWindowManager.getInstance(myProject).activateEditorComponent(); - } - } - }); - } + ApplicationManager.getApplication().invokeLater(() -> { + myBuilder.selectElement(element, PsiUtilCore.getVirtualFile(element)); + if (!isDirectory) { + ApplicationManager.getApplication().invokeLater(() -> { + if (myMoveFocus) { + ToolWindowManager.getInstance(myProject).activateEditorComponent(); + } + }); } }, ModalityState.NON_MODAL); } diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java index 12cb632c0ea4..5d00ea730bf5 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java @@ -205,11 +205,8 @@ public class FavoritesManager implements ProjectComponent, JDOMExternalizable { final Collection>> list = getFavoritesListRootUrls(name); final HashSet set = - new HashSet(ContainerUtil.map(list, new Function>, AbstractUrl>() { - @Override - public AbstractUrl fun(TreeItem> item) { - return item.getData().getFirst(); - } + new HashSet(ContainerUtil.map(list, item -> { + return item.getData().getFirst(); })); for (AbstractTreeNode node : nodes) { final Pair pair = createPairForNode(node); @@ -229,11 +226,8 @@ public class FavoritesManager implements ProjectComponent, JDOMExternalizable { final Collection>> list = getFavoritesListRootUrls(name); final HashSet set = - new HashSet(ContainerUtil.map(list, new Function>, AbstractUrl>() { - @Override - public AbstractUrl fun(TreeItem> item) { - return item.getData().getFirst(); - } + new HashSet(ContainerUtil.map(list, item -> { + return item.getData().getFirst(); })); for (AbstractTreeNode node : nodes) { final Pair pair = createPairForNode(node); @@ -690,22 +684,19 @@ public class FavoritesManager implements ProjectComponent, JDOMExternalizable { for (String listName : myName2FavoritesRoots.keySet()) { final List>> roots = myName2FavoritesRoots.get(listName); final AbstractUrl finalChildUrl = childUrl; - iterateTreeItems(roots, new Consumer>>() { - @Override - public void consume(TreeItem> item) { - final Pair root = item.getData(); - final Object[] path = root.first.createPath(myProject); - if (path == null || path.length < 1 || path[0] == null) { - return; - } - final Object element = path[path.length - 1]; - if (element == child && finalChildUrl != null) { - item.setData(Pair.create(finalChildUrl, root.second)); - } - else { - if (element == oldParent) { - item.setData(Pair.create(root.first.createUrlByElement(newParent), root.second)); - } + iterateTreeItems(roots, item -> { + final Pair root = item.getData(); + final Object[] path = root.first.createPath(myProject); + if (path == null || path.length < 1 || path[0] == null) { + return; + } + final Object element = path[path.length - 1]; + if (element == child && finalChildUrl != null) { + item.setData(Pair.create(finalChildUrl, root.second)); + } + else { + if (element == oldParent) { + item.setData(Pair.create(root.first.createUrlByElement(newParent), root.second)); } } }); @@ -726,21 +717,18 @@ public class FavoritesManager implements ProjectComponent, JDOMExternalizable { for (String listName : myName2FavoritesRoots.keySet()) { final List>> roots = myName2FavoritesRoots.get(listName); - iterateTreeItems(roots, new Consumer>>() { - @Override - public void consume(TreeItem> item) { - final Pair root = item.getData(); - final Object[] path = root.first.createPath(myProject); - if (path == null || path.length < 1 || path[0] == null) { - return; - } - final Object element = path[path.length - 1]; - if (element == psiElement && psiElement instanceof PsiFile) { - item.setData(Pair.create(childUrl, root.second)); - } - else { - item.setData(root); - } + iterateTreeItems(roots, item -> { + final Pair root = item.getData(); + final Object[] path = root.first.createPath(myProject); + if (path == null || path.length < 1 || path[0] == null) { + return; + } + final Object element = path[path.length - 1]; + if (element == psiElement && psiElement instanceof PsiFile) { + item.setData(Pair.create(childUrl, root.second)); + } + else { + item.setData(root); } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesPanel.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesPanel.java index 11eb9895973f..2ee4e3509a4f 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesPanel.java @@ -69,32 +69,29 @@ public class FavoritesPanel { private void setupDnD() { DnDSupport.createBuilder(myTree) - .setBeanProvider(new Function() { - @Override - public DnDDragStartBean fun(DnDActionInfo info) { - final TreePath path = myTree.getPathForLocation(info.getPoint().x, info.getPoint().y); - if (path != null && path.getPathCount() == 3) { - Object o = path.getLastPathComponent(); - if (o instanceof DefaultMutableTreeNode) { - o = ((DefaultMutableTreeNode)o).getUserObject(); - if (o instanceof FavoritesTreeNodeDescriptor) { - FavoritesTreeNodeDescriptor root = ((FavoritesTreeNodeDescriptor)o).getFavoritesRoot(); - if (root != null && root != o) { - o = root.getElement(); - if (o instanceof FavoritesListNode && ((FavoritesListNode)o).getProvider() == null) { - return new DnDDragStartBean(path); - } + .setBeanProvider(info -> { + final TreePath path = myTree.getPathForLocation(info.getPoint().x, info.getPoint().y); + if (path != null && path.getPathCount() == 3) { + Object o = path.getLastPathComponent(); + if (o instanceof DefaultMutableTreeNode) { + o = ((DefaultMutableTreeNode)o).getUserObject(); + if (o instanceof FavoritesTreeNodeDescriptor) { + FavoritesTreeNodeDescriptor root = ((FavoritesTreeNodeDescriptor)o).getFavoritesRoot(); + if (root != null && root != o) { + o = root.getElement(); + if (o instanceof FavoritesListNode && ((FavoritesListNode)o).getProvider() == null) { + return new DnDDragStartBean(path); } } } } - return new DnDDragStartBean("") { - @Override - public boolean isEmpty() { - return true; - } - }; } + return new DnDDragStartBean("") { + @Override + public boolean isEmpty() { + return true; + } + }; }) // todo process drag-and-drop here for tasks .setTargetChecker(new DnDTargetChecker() { @@ -159,12 +156,8 @@ public class FavoritesPanel { } } }) - .setImageProvider(new Function() { - @Override - public DnDImage fun(DnDActionInfo info) { - return new DnDImage(myFavoritesImage, new Point(-myFavoritesImage.getWidth(null) / 2, -myFavoritesImage.getHeight(null) / 2)); - } - }) + .setImageProvider( + info -> new DnDImage(myFavoritesImage, new Point(-myFavoritesImage.getWidth(null) / 2, -myFavoritesImage.getHeight(null) / 2))) .enableAsNativeTarget() .setDisposableParent(myProject) .install(); diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java index 223cc7efc275..ec2f2c292738 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java @@ -122,24 +122,21 @@ public class FavoritesTreeViewPanel extends JPanel implements DataProvider, Dock ToolTipManager.sharedInstance().registerComponent(myTree); final FavoritesComparator favoritesComparator = new FavoritesComparator(ProjectView.getInstance(project), FavoritesProjectViewPane.ID); - myBuilder.setNodeDescriptorComparator(new Comparator() { - @Override - public int compare(NodeDescriptor o1, NodeDescriptor o2) { - if (o1 instanceof FavoritesTreeNodeDescriptor && o2 instanceof FavoritesTreeNodeDescriptor) { - final FavoritesListNode listNode1 = FavoritesTreeUtil.extractParentList((FavoritesTreeNodeDescriptor)o1); - final FavoritesListNode listNode2 = FavoritesTreeUtil.extractParentList((FavoritesTreeNodeDescriptor)o2); - if (listNode1.equals(listNode2)) { - final Comparator comparator = myFavoritesManager.getCustomComparator(listNode1.getName()); - if (comparator != null) { - return comparator.compare((FavoritesTreeNodeDescriptor)o1, (FavoritesTreeNodeDescriptor)o2); - } - else { - return favoritesComparator.compare(o1, o2); - } + myBuilder.setNodeDescriptorComparator((o1, o2) -> { + if (o1 instanceof FavoritesTreeNodeDescriptor && o2 instanceof FavoritesTreeNodeDescriptor) { + final FavoritesListNode listNode1 = FavoritesTreeUtil.extractParentList((FavoritesTreeNodeDescriptor)o1); + final FavoritesListNode listNode2 = FavoritesTreeUtil.extractParentList((FavoritesTreeNodeDescriptor)o2); + if (listNode1.equals(listNode2)) { + final Comparator comparator = myFavoritesManager.getCustomComparator(listNode1.getName()); + if (comparator != null) { + return comparator.compare((FavoritesTreeNodeDescriptor)o1, (FavoritesTreeNodeDescriptor)o2); + } + else { + return favoritesComparator.compare(o1, o2); } } - return o1.getIndex() - o2.getIndex(); } + return o1.getIndex() - o2.getIndex(); }); myTree.setCellRenderer(new NodeRenderer() { @Override diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewSelectInTarget.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewSelectInTarget.java index 5a304044fdc0..4c6e72e68f83 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewSelectInTarget.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewSelectInTarget.java @@ -87,12 +87,9 @@ public class FavoritesViewSelectInTarget extends SelectInTargetPsiWrapper { final FavoritesTreeViewPanel panel = UIUtil.findComponentOfType(favoritesToolWindow.getComponent(), FavoritesTreeViewPanel.class); if (panel != null) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - panel.selectElement(toSelect, virtualFile, requestFocus); - result.setDone(); - } + final Runnable runnable = () -> { + panel.selectElement(toSelect, virtualFile, requestFocus); + result.setDone(); }; if (requestFocus) { diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/TaskDefaultFavoriteListProvider.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/TaskDefaultFavoriteListProvider.java index 9c917d65c211..a9d123b8dabd 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/TaskDefaultFavoriteListProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/TaskDefaultFavoriteListProvider.java @@ -207,12 +207,7 @@ public class TaskDefaultFavoriteListProvider extends AbstractFavoritesListProvid } }; action.registerCustomShortcutSet(CommonShortcuts.CTRL_ENTER, content); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - popup.showInCenterOf(tree); - } - }, ModalityState.NON_MODAL, project.getDisposed()); + ApplicationManager.getApplication().invokeLater(() -> popup.showInCenterOf(tree), ModalityState.NON_MODAL, project.getDisposed()); } //private Operation getCustomEditOperation() { diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageFavoriteNodeProvider.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageFavoriteNodeProvider.java index 521ff3e28a6c..8e0b4e0ca172 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageFavoriteNodeProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageFavoriteNodeProvider.java @@ -82,12 +82,9 @@ public class UsageFavoriteNodeProvider extends FavoriteNodeProvider { } private static TreeSet createSet() { - return new TreeSet(new Comparator() { - @Override - public int compare(WorkingSetSerializable o1, WorkingSetSerializable o2) { - assert o1.getId().equals(o1.getId()); - return Comparing.compare(o1.getVersion(), o2.getVersion()); - } + return new TreeSet((o1, o2) -> { + assert o1.getId().equals(o1.getId()); + return Comparing.compare(o1.getVersion(), o2.getVersion()); }); } diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageProjectTreeNode.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageProjectTreeNode.java index 279cea934cc0..3ecbaad34f0e 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageProjectTreeNode.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/UsageProjectTreeNode.java @@ -63,11 +63,8 @@ public class UsageProjectTreeNode extends ProjectViewNodeWithChildrenList() { - @Override - public String fun(TextChunk chunk) { - return chunk.getText(); - } + presentation.setPresentableText(StringUtil.join(text, chunk -> { + return chunk.getText(); }, "")); } diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java index 287811db17c0..22deec4e1895 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateUtil.java @@ -234,13 +234,8 @@ public class FileTemplateUtil{ LOG.error(e); } LOG.info("Error evaluating template:\n" + templateContent, e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), - IdeBundle.message("title.velocity.error")); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), + IdeBundle.message("title.velocity.error"))); } final String result = stringWriter.toString(); @@ -332,22 +327,14 @@ public class FileTemplateUtil{ final String templateText = StringUtil.convertLineSeparators(mergedText); final Exception[] commandException = new Exception[1]; final PsiElement[] result = new PsiElement[1]; - CommandProcessor.getInstance().executeCommand(project, new Runnable(){ - @Override - public void run(){ - ApplicationManager.getApplication().runWriteAction(new Runnable(){ - @Override - public void run(){ - try{ - result[0] = handler.createFromTemplate(project, directory, fileName_, template, templateText, props_); - } - catch (Exception ex){ - commandException[0] = ex; - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try{ + result[0] = handler.createFromTemplate(project, directory, fileName_, template, templateText, props_); } - }, template.isTemplateOfType(StdFileTypes.JAVA) && !"package-info".equals(template.getName()) + catch (Exception ex){ + commandException[0] = ex; + } + }), template.isTemplateOfType(StdFileTypes.JAVA) && !"package-info".equals(template.getName()) ? IdeBundle.message("command.create.class.from.template") : IdeBundle.message("command.create.file.from.template"), null); if(commandException[0] != null){ diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java index a69a5b5f437c..c909c189f055 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateActionBase.java @@ -99,11 +99,8 @@ public abstract class CreateFromTemplateActionBase extends AnAction { for (String variable : variables) { template.addVariable(variable, null, "\"" + variable + "\"", true); } - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - editor.getDocument().setText(template.getTemplateText()); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + editor.getDocument().setText(template.getTemplateText()); }); TemplateManager.getInstance(project).startTemplate(editor, template); } diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateGroup.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateGroup.java index dd22621680b3..5850e939c398 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateGroup.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/actions/CreateFromTemplateGroup.java @@ -74,26 +74,23 @@ public class CreateFromTemplateGroup extends ActionGroup implements DumbAware { } } - Arrays.sort(templates, new Comparator() { - @Override - public int compare(FileTemplate template1, FileTemplate template2) { - // java first - if (template1.isTemplateOfType(StdFileTypes.JAVA) && !template2.isTemplateOfType(StdFileTypes.JAVA)) { - return -1; - } - if (template2.isTemplateOfType(StdFileTypes.JAVA) && !template1.isTemplateOfType(StdFileTypes.JAVA)) { - return 1; - } - - // group by type - int i = template1.getExtension().compareTo(template2.getExtension()); - if (i != 0) { - return i; - } - - // group by name if same type - return template1.getName().compareTo(template2.getName()); + Arrays.sort(templates, (template1, template2) -> { + // java first + if (template1.isTemplateOfType(StdFileTypes.JAVA) && !template2.isTemplateOfType(StdFileTypes.JAVA)) { + return -1; } + if (template2.isTemplateOfType(StdFileTypes.JAVA) && !template1.isTemplateOfType(StdFileTypes.JAVA)) { + return 1; + } + + // group by type + int i = template1.getExtension().compareTo(template2.getExtension()); + if (i != 0) { + return i; + } + + // group by name if same type + return template1.getName().compareTo(template2.getName()); }); List result = new ArrayList(); diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java index 4e3534e6df4c..248c261cfae0 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java @@ -102,11 +102,8 @@ public class AllFileTemplatesConfigurable implements SearchableConfigurable, Con myProject = project; myManager = getInstance(project); myScheme = myManager.getCurrentScheme(); - myInternalTemplateNames = ContainerUtil.map2Set(myManager.getInternalTemplates(), new Function() { - @Override - public String fun(FileTemplate template) { - return template.getName(); - } + myInternalTemplateNames = ContainerUtil.map2Set(myManager.getInternalTemplates(), template -> { + return template.getName(); }); } @@ -228,11 +225,8 @@ public class AllFileTemplatesConfigurable implements SearchableConfigurable, Con @Override protected FileTemplateNode initModel() { SortedSet categories = - new TreeSet(new Comparator() { - @Override - public int compare(FileTemplateGroupDescriptor o1, FileTemplateGroupDescriptor o2) { - return o1.getTitle().compareTo(o2.getTitle()); - } + new TreeSet((o1, o2) -> { + return o1.getTitle().compareTo(o2.getTitle()); }); @@ -242,11 +236,8 @@ public class AllFileTemplatesConfigurable implements SearchableConfigurable, Con //noinspection HardCodedStringLiteral return new FileTemplateNode("ROOT", null, - ContainerUtil.map2List(categories, new Function() { - @Override - public FileTemplateNode fun(FileTemplateGroupDescriptor s) { - return new FileTemplateNode(s); - } + ContainerUtil.map2List(categories, s -> { + return new FileTemplateNode(s); })); } }; @@ -553,15 +544,12 @@ public class AllFileTemplatesConfigurable implements SearchableConfigurable, Con myTabbedPane.setSelectedIndex(Arrays.asList(myTabs).indexOf(list)); selectTemplate(itemWithError); list.selectTemplate(itemWithError); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (_errorInName) { - myEditor.focusToNameField(); - } - else { - myEditor.focusToExtensionField(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (_errorInName) { + myEditor.focusToNameField(); + } + else { + myEditor.focusToExtensionField(); } }); throw new ConfigurationException(errorString); @@ -681,15 +669,12 @@ public class AllFileTemplatesConfigurable implements SearchableConfigurable, Con public static void editCodeTemplate(@NotNull final String templateId, Project project) { final ShowSettingsUtil util = ShowSettingsUtil.getInstance(); final AllFileTemplatesConfigurable configurable = new AllFileTemplatesConfigurable(project); - util.editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - configurable.myTabbedPane.setSelectedIndex(ArrayUtil.indexOf(configurable.myTabs, configurable.myCodeTemplatesList)); - for (FileTemplate template : configurable.myCodeTemplatesList.getTemplates()) { - if (Comparing.equal(templateId, template.getName())) { - configurable.myCodeTemplatesList.selectTemplate(template); - break; - } + util.editConfigurable(project, configurable, () -> { + configurable.myTabbedPane.setSelectedIndex(ArrayUtil.indexOf(configurable.myTabs, configurable.myCodeTemplatesList)); + for (FileTemplate template : configurable.myCodeTemplatesList.getTemplates()) { + if (Comparing.equal(templateId, template.getName())) { + configurable.myCodeTemplatesList.selectTemplate(template); + break; } } }); diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java index 3fc7d3bdda24..106e72a79f8d 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FTManager.java @@ -87,12 +87,7 @@ class FTManager { List sorted = mySortedTemplates; if (sorted == null) { sorted = new ArrayList(getTemplates().values()); - Collections.sort(sorted, new Comparator() { - @Override - public int compare(FileTemplateBase t1, FileTemplateBase t2) { - return t1.getName().compareToIgnoreCase(t2.getName()); - } - }); + Collections.sort(sorted, (t1, t2) -> t1.getName().compareToIgnoreCase(t2.getName())); mySortedTemplates = sorted; } diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplateTabAsTree.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplateTabAsTree.java index 9081ce559112..7ce65a1d9681 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplateTabAsTree.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplateTabAsTree.java @@ -74,12 +74,10 @@ abstract class FileTemplateTabAsTree extends FileTemplateTab { FileTemplateNode(FileTemplateDescriptor descriptor) { this(descriptor.getDisplayName(), descriptor.getIcon(), - descriptor instanceof FileTemplateGroupDescriptor ? ContainerUtil.map2List(((FileTemplateGroupDescriptor)descriptor).getTemplates(), new Function() { - @Override - public FileTemplateNode fun(FileTemplateDescriptor s) { - return new FileTemplateNode(s); - } - }) : Collections.emptyList(), + descriptor instanceof FileTemplateGroupDescriptor ? ContainerUtil.map2List(((FileTemplateGroupDescriptor)descriptor).getTemplates(), + s -> { + return new FileTemplateNode(s); + }) : Collections.emptyList(), descriptor instanceof FileTemplateGroupDescriptor ? null : descriptor.getFileName()); } diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/CallHierarchyBrowserBase.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/CallHierarchyBrowserBase.java index 8561712d07e9..d95f99e17fe6 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/CallHierarchyBrowserBase.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/CallHierarchyBrowserBase.java @@ -99,12 +99,7 @@ public abstract class CallHierarchyBrowserBase extends HierarchyBrowserBaseEx { if (flag) { // setWaitCursor(); // invokeLater is called to update state of button before long tree building operation - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - changeView(myTypeName); - } - }); + ApplicationManager.getApplication().invokeLater(() -> changeView(myTypeName)); } } diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/ChangeViewTypeActionBase.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/ChangeViewTypeActionBase.java index 2da439e1dabc..eb580e341c10 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/ChangeViewTypeActionBase.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/ChangeViewTypeActionBase.java @@ -45,12 +45,9 @@ abstract class ChangeViewTypeActionBase extends ToggleAction { if (flag) { final TypeHierarchyBrowserBase browser = getTypeHierarchyBrowser(event.getDataContext()); // setWaitCursor(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (browser != null) { - browser.changeView(getTypeName()); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (browser != null) { + browser.changeView(getTypeName()); } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyBrowserBaseEx.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyBrowserBaseEx.java index a604be589ec3..dc5ce480eb60 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyBrowserBaseEx.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyBrowserBaseEx.java @@ -213,14 +213,11 @@ public abstract class HierarchyBrowserBaseEx extends HierarchyBrowserBase implem protected final JTree createTree(boolean dndAware) { final Tree tree; - final NullableFunction toPsiConverter = new NullableFunction() { - @Override - public PsiElement fun(Object o) { - if (o instanceof HierarchyNodeDescriptor) { - return ((HierarchyNodeDescriptor)o).getContainingFile(); - } - return null; + final NullableFunction toPsiConverter = o -> { + if (o instanceof HierarchyNodeDescriptor) { + return ((HierarchyNodeDescriptor)o).getContainingFile(); } + return null; }; if (dndAware) { @@ -322,12 +319,7 @@ public abstract class HierarchyBrowserBaseEx extends HierarchyBrowserBase implem } private void setWaitCursor() { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } - }, 100); + myAlarm.addRequest(() -> setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)), 100); } public final void changeView(@NotNull final String typeName) { @@ -373,12 +365,7 @@ public abstract class HierarchyBrowserBaseEx extends HierarchyBrowserBase implem }); final HierarchyNodeDescriptor descriptor = structure.getBaseDescriptor(); - builder.select(descriptor, new Runnable() { - @Override - public void run() { - builder.expand(descriptor, null); - } - }); + builder.select(descriptor, () -> builder.expand(descriptor, null)); } finally { restoreCursor(); @@ -515,13 +502,10 @@ public abstract class HierarchyBrowserBaseEx extends HierarchyBrowserBase implem } setHierarchyBase(element); validate(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - changeView(currentViewType); - final HierarchyTreeBuilder builder = getCurrentBuilder(); - builder.restoreExpandedAndSelectedInfo(storedInfo.get()); - } + ApplicationManager.getApplication().invokeLater(() -> { + changeView(currentViewType); + final HierarchyTreeBuilder builder = getCurrentBuilder(); + builder.restoreExpandedAndSelectedInfo(storedInfo.get()); }); } @@ -588,12 +572,8 @@ public abstract class HierarchyBrowserBaseEx extends HierarchyBrowserBase implem selectedElement.getContainingFile(), event.getDataContext()); final HierarchyBrowser newBrowser = BrowseHierarchyActionBase.createAndAddToPanel(selectedElement.getProject(), provider, selectedElement); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ((HierarchyBrowserBaseEx)newBrowser).changeView(correctViewType(browser, currentViewType)); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> ((HierarchyBrowserBaseEx)newBrowser).changeView(correctViewType(browser, currentViewType))); } protected String correctViewType(HierarchyBrowserBaseEx browser, String viewType) { @@ -705,11 +685,8 @@ public abstract class HierarchyBrowserBaseEx extends HierarchyBrowserBase implem HierarchyBrowserManager.getInstance(myProject).getState().SCOPE = scopeType; // invokeLater is called to update state of button before long tree building operation - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - doRefresh(true); // scope is kept per type so other builders doesn't need to be refreshed - } + ApplicationManager.getApplication().invokeLater(() -> { + doRefresh(true); // scope is kept per type so other builders doesn't need to be refreshed }); } diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/MethodHierarchyBrowserBase.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/MethodHierarchyBrowserBase.java index fa94b4d4e0f2..fcd3e76df055 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/MethodHierarchyBrowserBase.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/MethodHierarchyBrowserBase.java @@ -113,12 +113,7 @@ public abstract class MethodHierarchyBrowserBase extends HierarchyBrowserBaseEx HierarchyBrowserManager.getInstance(myProject).getState().HIDE_CLASSES_WHERE_METHOD_NOT_IMPLEMENTED = flag; // invokeLater is called to update state of button before long tree building operation - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - doRefresh(true); - } - }); + ApplicationManager.getApplication().invokeLater(() -> doRefresh(true)); } @Override diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java index 241b5a000043..f67fe3bebc3c 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java @@ -90,12 +90,7 @@ public abstract class BrowseHierarchyActionBase extends AnAction { contentManager.setSelectedContent(content); hierarchyBrowser.setContent(content); - final Runnable runnable = new Runnable() { - @Override - public void run() { - provider.browserActivated(hierarchyBrowser); - } - }; + final Runnable runnable = () -> provider.browserActivated(hierarchyBrowser); ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.HIERARCHY).activate(runnable); return hierarchyBrowser; } diff --git a/platform/lang-impl/src/com/intellij/ide/impl/PatchProjectUtil.java b/platform/lang-impl/src/com/intellij/ide/impl/PatchProjectUtil.java index 6c2be5072224..01d8decfb529 100644 --- a/platform/lang-impl/src/com/intellij/ide/impl/PatchProjectUtil.java +++ b/platform/lang-impl/src/com/intellij/ide/impl/PatchProjectUtil.java @@ -136,11 +136,8 @@ public class PatchProjectUtil { } } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ModifiableModelCommitter.multiCommit(models, modulesModel); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ModifiableModelCommitter.multiCommit(models, modulesModel); }); } diff --git a/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java b/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java index acb8a717b8d3..b05a10152c0e 100644 --- a/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java +++ b/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java @@ -75,21 +75,13 @@ public abstract class ProjectViewSelectInTarget extends SelectInTargetPsiWrapper ToolWindowManager windowManager = ToolWindowManager.getInstance(project); final ToolWindow projectViewToolWindow = windowManager.getToolWindow(ToolWindowId.PROJECT_VIEW); - final Runnable runnable = new Runnable() { - @Override - public void run() { - Runnable r = new Runnable() { - @Override - public void run() { - projectView.selectCB(toSelect, virtualFile, requestFocus).notify(result); - } - }; - if (requestFocus) { - projectView.changeViewCB(ObjectUtils.chooseNotNull(viewId, ProjectViewPane.ID), subviewId).doWhenProcessed(r); - } - else { - r.run(); - } + final Runnable runnable = () -> { + Runnable r = () -> projectView.selectCB(toSelect, virtualFile, requestFocus).notify(result); + if (requestFocus) { + projectView.changeViewCB(ObjectUtils.chooseNotNull(viewId, ProjectViewPane.ID), subviewId).doWhenProcessed(r); + } + else { + r.run(); } }; diff --git a/platform/lang-impl/src/com/intellij/ide/impl/StructureViewSelectInTarget.java b/platform/lang-impl/src/com/intellij/ide/impl/StructureViewSelectInTarget.java index ba704b9a4a83..d85040ea70b6 100644 --- a/platform/lang-impl/src/com/intellij/ide/impl/StructureViewSelectInTarget.java +++ b/platform/lang-impl/src/com/intellij/ide/impl/StructureViewSelectInTarget.java @@ -58,17 +58,8 @@ public class StructureViewSelectInTarget implements SelectInTarget { } ToolWindowManager windowManager = ToolWindowManager.getInstance(context.getProject()); - final Runnable runnable = new Runnable() { - @Override - public void run() { - StructureViewFactoryEx.getInstanceEx(myProject).runWhenInitialized(new Runnable() { - @Override - public void run() { - getStructureViewWrapper().selectCurrentElement(fileEditor, context.getVirtualFile(), requestFocus); - } - }); - } - }; + final Runnable runnable = () -> StructureViewFactoryEx.getInstanceEx(myProject).runWhenInitialized( + () -> getStructureViewWrapper().selectCurrentElement(fileEditor, context.getVirtualFile(), requestFocus)); if (requestFocus) { windowManager.getToolWindow(ToolWindowId.STRUCTURE_VIEW).activate(runnable); } diff --git a/platform/lang-impl/src/com/intellij/ide/impl/StructureViewWrapperImpl.java b/platform/lang-impl/src/com/intellij/ide/impl/StructureViewWrapperImpl.java index c4981bf40a67..2fc06cf9442f 100644 --- a/platform/lang-impl/src/com/intellij/ide/impl/StructureViewWrapperImpl.java +++ b/platform/lang-impl/src/com/intellij/ide/impl/StructureViewWrapperImpl.java @@ -220,16 +220,13 @@ public class StructureViewWrapperImpl implements StructureViewWrapper, Disposabl // this is dirty hack since some bright minds decided to used different TreeUi every time, so selection may be followed // by rebuild on completely different instance of TreeUi - Runnable runnable = new Runnable() { - @Override - public void run() { - if (!Comparing.equal(myFileEditor, fileEditor)) { - myFile = file; - rebuild(); - } - if (myStructureView != null) { - myStructureView.navigateToSelectedElement(requestFocus); - } + Runnable runnable = () -> { + if (!Comparing.equal(myFileEditor, fileEditor)) { + myFile = file; + rebuild(); + } + if (myStructureView != null) { + myStructureView.navigateToSelectedElement(requestFocus); } }; diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java index 572767e70ec9..29e5b23d2e60 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java @@ -185,12 +185,7 @@ public class NavBarListener extends WolfTheProblemSolver.ProblemListener // required invokeLater since in current call sequence KeyboardFocusManager is not initialized yet // but future focused component //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - processFocusLost(e); - } - }); + SwingUtilities.invokeLater(() -> processFocusLost(e)); } private void processFocusLost(FocusEvent e) { @@ -326,24 +321,21 @@ public class NavBarListener extends WolfTheProblemSolver.ProblemListener focusManager.typeAheadUntil(firstCharTyped); myPanel.moveDown(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - final Robot robot = new Robot(); - final boolean shiftOn = e.isShiftDown(); - final int code = e.getKeyCode(); - if (shiftOn) { - robot.keyPress(KeyEvent.VK_SHIFT); - } - robot.keyPress(code); - robot.keyRelease(code); + SwingUtilities.invokeLater(() -> { + try { + final Robot robot = new Robot(); + final boolean shiftOn = e.isShiftDown(); + final int code = e.getKeyCode(); + if (shiftOn) { + robot.keyPress(KeyEvent.VK_SHIFT); + } + robot.keyPress(code); + robot.keyRelease(code); - //don't release Shift - firstCharTyped.setDone(); - } - catch (AWTException ignored) { - } + //don't release Shift + firstCharTyped.setDone(); + } + catch (AWTException ignored) { } }); } @@ -351,12 +343,9 @@ public class NavBarListener extends WolfTheProblemSolver.ProblemListener @Override public void fileOpened(@NotNull final FileEditorManager manager, @NotNull final VirtualFile file) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myPanel.hasFocus()) { - manager.openFile(file, true); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myPanel.hasFocus()) { + manager.openFile(file, true); } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarModel.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarModel.java index ddaa4682e896..6dadc82439b0 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarModel.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarModel.java @@ -167,11 +167,8 @@ public class NavBarModel { final List updatedModel = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - traverseToRoot(psiElement, roots, updatedModel); - } + ApplicationManager.getApplication().runReadAction(() -> { + traverseToRoot(psiElement, roots, updatedModel); }); setModel(ContainerUtil.reverse(updatedModel)); @@ -300,12 +297,9 @@ public class NavBarModel { protected List getChildren(final Object object) { final List result = ContainerUtil.newArrayList(); - Processor processor = new Processor() { - @Override - public boolean process(Object o) { - ContainerUtil.addIfNotNull(result, o instanceof PsiElement ? normalize((PsiElement)o) : o); - return true; - } + Processor processor = o -> { + ContainerUtil.addIfNotNull(result, o instanceof PsiElement ? normalize((PsiElement)o) : o); + return true; }; processChildren(object, processor); diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java index f41b9f5705df..855a54533d60 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java @@ -175,12 +175,9 @@ public class NavBarPanel extends JPanel implements DataProvider, PopupOwner, Dis public void clearItems() { final NavBarItem[] toDispose = myList.toArray(new NavBarItem[myList.size()]); myList.clear(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - for (NavBarItem item : toDispose) { - Disposer.dispose(item); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + for (NavBarItem item : toDispose) { + Disposer.dispose(item); } }); @@ -285,14 +282,11 @@ public class NavBarPanel extends JPanel implements DataProvider, PopupOwner, Dis public void rebuildAndSelectTail(final boolean requestFocus) { myUpdateQueue.queueModelUpdateFromFocus(); myUpdateQueue.queueRebuildUi(); - myUpdateQueue.queueSelect(new Runnable() { - @Override - public void run() { - if (!myList.isEmpty()) { - myModel.setSelectedIndex(myList.size() - 1); - if (requestFocus) { - IdeFocusManager.getInstance(myProject).requestFocus(NavBarPanel.this, true); - } + myUpdateQueue.queueSelect(() -> { + if (!myList.isEmpty()) { + myModel.setSelectedIndex(myList.size() - 1); + if (requestFocus) { + IdeFocusManager.getInstance(myProject).requestFocus(NavBarPanel.this, true); } } }); @@ -340,12 +334,7 @@ public class NavBarPanel extends JPanel implements DataProvider, PopupOwner, Dis else { final NavBarItem item = new NavBarItem(this, null, 0, null); final Dimension size = item.getPreferredSize(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - Disposer.dispose(item); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> Disposer.dispose(item)); return size; } } @@ -435,35 +424,30 @@ public class NavBarPanel extends JPanel implements DataProvider, PopupOwner, Dis private void installDnD(final int index, NavBarItem component) { DnDSupport.createBuilder(component) - .setBeanProvider(new Function() { + .setBeanProvider(dnDActionInfo -> new DnDDragStartBean(new TransferableWrapper() { @Override - public DnDDragStartBean fun(DnDActionInfo dnDActionInfo) { - return new DnDDragStartBean(new TransferableWrapper() { - @Override - public List asFileList() { - final Object o = myModel.get(index); - if (o instanceof PsiElement) { - final VirtualFile vf = o instanceof PsiDirectory ? ((PsiDirectory)o).getVirtualFile() - : ((PsiElement)o).getContainingFile().getVirtualFile(); - if (vf != null) { - return Arrays.asList(new File(vf.getPath()).getAbsoluteFile()); - } - } - return Collections.emptyList(); + public List asFileList() { + final Object o = myModel.get(index); + if (o instanceof PsiElement) { + final VirtualFile vf = o instanceof PsiDirectory ? ((PsiDirectory)o).getVirtualFile() + : ((PsiElement)o).getContainingFile().getVirtualFile(); + if (vf != null) { + return Arrays.asList(new File(vf.getPath()).getAbsoluteFile()); } - - @Override - public TreeNode[] getTreeNodes() { - return null; - } - - @Override - public PsiElement[] getPsiElements() { - return null; - } - }); + } + return Collections.emptyList(); } - }) + + @Override + public TreeNode[] getTreeNodes() { + return null; + } + + @Override + public PsiElement[] getPsiElements() { + return null; + } + })) .setDisposableParent(component) .install(); } @@ -535,20 +519,17 @@ public class NavBarPanel extends JPanel implements DataProvider, PopupOwner, Dis } myUpdateQueue.queueRebuildUi(); - myUpdateQueue.queueAfterAll(new Runnable() { - @Override - public void run() { - int index = myModel.indexOf(obj); - if (index >= 0) { - myModel.setSelectedIndex(index); - } + myUpdateQueue.queueAfterAll(() -> { + int index = myModel.indexOf(obj); + if (index >= 0) { + myModel.setSelectedIndex(index); + } - if (myModel.hasChildren(obj)) { - restorePopup(); - } - else { - doubleClick(obj); - } + if (myModel.hasChildren(obj)) { + restorePopup(); + } + else { + doubleClick(obj); } }, NavBarUpdateQueue.ID.NAVIGATE_INSIDE); } diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java index 74417627abd1..a21e78ae53c0 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java @@ -112,18 +112,12 @@ public class NavBarPopup extends LightweightHint implements Disposable{ final Point p = point.getPoint(myPanel); if (p.x == 0 && p.y == 0 && checkRepaint) { // need repaint of nav bar panel //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPanel.getUpdateQueue().rebuildUi(); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - show(item, false); // end-less loop protection - } - }); - } + SwingUtilities.invokeLater(() -> { + myPanel.getUpdateQueue().rebuildUi(); + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + show(item, false); // end-less loop protection + }); }); } else { int offset = NavBarUIManager.getUI().getPopupOffset(item); @@ -165,26 +159,17 @@ public class NavBarPopup extends LightweightHint implements Disposable{ }); final List disposables = new ArrayList(); list.putClientProperty(DISPOSED_OBJECTS, disposables); - list.installCellRenderer(new NotNullFunction() { - @NotNull - @Override - public JComponent fun(Object obj) { - final NavBarItem navBarItem = new NavBarItem(panel, obj, null); - disposables.add(navBarItem); - return navBarItem; - } + list.installCellRenderer(obj -> { + final NavBarItem navBarItem = new NavBarItem(panel, obj, null); + disposables.add(navBarItem); + return navBarItem; }); list.setBorder(IdeBorderFactory.createEmptyBorder(5, 5, 5, 5)); installMoveAction(list, panel, -1, KeyEvent.VK_LEFT); installMoveAction(list, panel, 1, KeyEvent.VK_RIGHT); installEnterAction(list, panel, KeyEvent.VK_ENTER); installEscapeAction(list, panel, KeyEvent.VK_ESCAPE); - final JComponent component = ListWithFilter.wrap(list, new NavBarListWrapper(list), new Function() { - @Override - public String fun(Object o) { - return panel.getPresentation().getPresentableText(o); - } - }); + final JComponent component = ListWithFilter.wrap(list, new NavBarListWrapper(list), o -> panel.getPresentation().getPresentableText(o)); component.putClientProperty(JBLIST_KEY, list); return component; } diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarUpdateQueue.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarUpdateQueue.java index a599be5bdc1c..8902b2f260fe 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarUpdateQueue.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarUpdateQueue.java @@ -44,12 +44,7 @@ public class NavBarUpdateQueue extends MergingUpdateQueue { private AtomicBoolean myModelUpdating = new AtomicBoolean(Boolean.FALSE); private Alarm myUserActivityAlarm = new Alarm(this); private Runnable myRunWhenListRebuilt; - private Runnable myUserActivityAlarmRunnable = new Runnable() { - @Override - public void run() { - processUserActivity(); - } - }; + private Runnable myUserActivityAlarmRunnable = () -> processUserActivity(); private NavBarPanel myPanel; @@ -57,12 +52,7 @@ public class NavBarUpdateQueue extends MergingUpdateQueue { super("NavBar", Registry.intValue("navBar.updateMergeTime"), true, MergingUpdateQueue.ANY_COMPONENT, panel); myPanel = panel; setTrackUiActivity(true); - IdeEventQueue.getInstance().addActivityListener(new Runnable() { - @Override - public void run() { - restartRebuild(); - } - }, panel); + IdeEventQueue.getInstance().addActivityListener(() -> restartRebuild(), panel); } private void requestModelUpdate(@Nullable final DataContext context, final @Nullable Object object, boolean requeue) { @@ -128,39 +118,36 @@ public class NavBarUpdateQueue extends MergingUpdateQueue { } final Project project = myPanel.getProject(); - IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - Window wnd = SwingUtilities.windowForComponent(myPanel); - if (wnd == null) return; + IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> { + Window wnd = SwingUtilities.windowForComponent(myPanel); + if (wnd == null) return; - Component focus = null; + Component focus = null; - if (!wnd.isActive()) { - IdeFrame frame = UIUtil.getParentOfType(IdeFrame.class, myPanel); - if (frame != null) { - focus = IdeFocusManager.getInstance(project).getLastFocusedFor(frame); - } + if (!wnd.isActive()) { + IdeFrame frame = UIUtil.getParentOfType(IdeFrame.class, myPanel); + if (frame != null) { + focus = IdeFocusManager.getInstance(project).getLastFocusedFor(frame); } - else { - final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); - if (window instanceof Dialog) { - final Dialog dialog = (Dialog)window; - if (dialog.isModal() && !SwingUtilities.isDescendingFrom(myPanel, dialog)) { - return; - } + } + else { + final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); + if (window instanceof Dialog) { + final Dialog dialog = (Dialog)window; + if (dialog.isModal() && !SwingUtilities.isDescendingFrom(myPanel, dialog)) { + return; } } + } - if (focus != null && focus.isShowing()) { - if (!myPanel.hasFocus() && !myPanel.isNodePopupShowing()) { - requestModelUpdate(DataManager.getInstance().getDataContext(focus), null, false); - } - } - else if (wnd.isActive()) { - requestModelUpdate(null, myPanel.getContextObject(), false); + if (focus != null && focus.isShowing()) { + if (!myPanel.hasFocus() && !myPanel.isNodePopupShowing()) { + requestModelUpdate(DataManager.getInstance().getDataContext(focus), null, false); } } + else if (wnd.isActive()) { + requestModelUpdate(null, myPanel.getContextObject(), false); + } }); } @@ -224,12 +211,7 @@ public class NavBarUpdateQueue extends MergingUpdateQueue { myPanel.revalidate(); myPanel.repaint(); - queueAfterAll(new Runnable() { - @Override - public void run() { - myPanel.scrollSelectionToVisible(); - } - }, ID.SCROLL_TO_VISIBLE); + queueAfterAll(() -> myPanel.scrollSelectionToVisible(), ID.SCROLL_TO_VISIBLE); } private void queueRevalidate(@Nullable final Runnable after) { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java index dd46f6496c46..4b6ab4577807 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/BaseProjectTreeBuilder.java @@ -78,16 +78,8 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { public void run(@NotNull ProgressIndicator indicator) { final Ref target = new Ref(); _select(value, virtualFile, false, Conditions.alwaysTrue(), callback, indicator, target, focusRequestor, false); - callback.doWhenDone(new Runnable() { - @Override - public void run() { - result.setDone(target.get()); - } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected(); - } + callback.doWhenDone(() -> result.setDone(target.get())).doWhenRejected(() -> { + result.setRejected(); }); } }); @@ -173,18 +165,13 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { final FocusRequestor requestor = IdeFocusManager.getInstance(myProject).getFurtherRequestor(); UiActivityMonitor.getInstance().addActivity(myProject, new UiActivity.AsyncBgOperation("projectViewSelect"), getUpdater().getModalityState()); - cancelUpdate().doWhenDone(new Runnable() { + cancelUpdate().doWhenDone(() -> batch(new Progressive() { @Override - public void run() { - batch(new Progressive() { - @Override - public void run(@NotNull ProgressIndicator indicator) { - _select(element, file, requestFocus, nonStopCondition, result, indicator, null, requestor, false); - UiActivityMonitor.getInstance().removeActivity(myProject, new UiActivity.AsyncBgOperation("projectViewSelect")); - } - }); + public void run(@NotNull ProgressIndicator indicator) { + _select(element, file, requestFocus, nonStopCondition, result, indicator, null, requestor, false); + UiActivityMonitor.getInstance().removeActivity(myProject, new UiActivity.AsyncBgOperation("projectViewSelect")); } - }); + })); @@ -202,15 +189,12 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { final boolean isSecondAttempt) { final AbstractTreeNode alreadySelected = alreadySelectedNode(element); - final Runnable onDone = new Runnable() { - @Override - public void run() { - if (requestFocus && virtualSelectTarget == null && getUi().isReady()) { - focusRequestor.requestFocus(getTree(), true); - } - - result.setDone(); + final Runnable onDone = () -> { + if (requestFocus && virtualSelectTarget == null && getUi().isReady()) { + focusRequestor.requestFocus(getTree(), true); } + + result.setDone(); }; final Condition condition = new Condition() { @@ -232,16 +216,13 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { onDone.run(); } } - }).doWhenRejected(new Runnable() { - @Override - public void run() { + }).doWhenRejected(() -> { if (isSecondAttempt) { result.setRejected(); } else { _select(file, file, requestFocus, nonStopCondition, result, indicator, virtualSelectTarget, focusRequestor, true); } - } - }); + }); } else if (virtualSelectTarget == null && getTree().getSelectionPaths().length == 1) { select(alreadySelected, onDone); @@ -287,12 +268,7 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { if (root.canRepresent(element)) { if (target == null) { - expand(root, new Runnable() { - @Override - public void run() { - async.setDone(root); - } - }); + expand(root, () -> async.setDone(root)); } else { target.set(root); @@ -308,19 +284,16 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { if (target == null) { - expand(root, new Runnable() { - @Override - public void run() { - indicator.checkCanceled(); + expand(root, () -> { + indicator.checkCanceled(); - final DefaultMutableTreeNode rootNode = getNodeForElement(root); - if (rootNode != null) { - final List kids = collectChildren(rootNode); - expandChild(kids, 0, nonStopCondition, file, element, async, indicator, target); - } - else { - async.setRejected(); - } + final DefaultMutableTreeNode rootNode = getNodeForElement(root); + if (rootNode != null) { + final List kids = collectChildren(rootNode); + expandChild(kids, 0, nonStopCondition, file, element, async, indicator, target); + } + else { + async.setRejected(); } }); } @@ -341,12 +314,9 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { } } - yield(new Runnable() { - @Override - public void run() { - if (isDisposed()) return; - expandChild(kids, 0, nonStopCondition, file, element, async, indicator, target); - } + yield(() -> { + if (isDisposed()) return; + expandChild(kids, 0, nonStopCondition, file, element, async, indicator, target); }); } } @@ -382,16 +352,13 @@ public abstract class BaseProjectTreeBuilder extends AbstractTreeBuilder { if (!result.isProcessed()) { final int next = i + 1; - result.doWhenRejected(new Runnable() { - @Override - public void run() { - indicator.checkCanceled(); + result.doWhenRejected(() -> { + indicator.checkCanceled(); - if (nodeWasCollapsed[0] && virtualSelectTarget == null) { - collapseChildren(eachKid, null); - } - expandChild(kids, next, nonStopCondition, file, element, async, indicator, virtualSelectTarget); + if (nodeWasCollapsed[0] && virtualSelectTarget == null) { + collapseChildren(eachKid, null); } + expandChild(kids, next, nonStopCondition, file, element, async, indicator, virtualSelectTarget); }); return; } else { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkRootActionBase.java b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkRootActionBase.java index b22164a91b77..51161a0979af 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkRootActionBase.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkRootActionBase.java @@ -77,18 +77,11 @@ public abstract class MarkRootActionBase extends DumbAwareAction { modifyRoots(file, entry); } } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - model.commit(); - module.getProject().save(); - } - }); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + model.commit(); + module.getProject().save(); + })); } protected abstract void modifyRoots(VirtualFile file, ContentEntry entry); diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java index 77582269d90a..cbac211af1f3 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java @@ -205,15 +205,12 @@ public abstract class AbstractProjectViewPSIPane extends AbstractProjectViewPane final ActionCallback cb = new ActionCallback(); if (restoreExpandedPaths) { TreeBuilderUtil.storePaths(getTreeBuilder(), (DefaultMutableTreeNode)myTree.getModel().getRoot(), pathsToExpand, selectionPaths, true); - afterUpdate = new Runnable() { - @Override - public void run() { - if (myTree != null && getTreeBuilder() != null && !getTreeBuilder().isDisposed()) { - myTree.setSelectionPaths(new TreePath[0]); - TreeBuilderUtil.restorePaths(getTreeBuilder(), pathsToExpand, selectionPaths, true); - } - cb.setDone(); + afterUpdate = () -> { + if (myTree != null && getTreeBuilder() != null && !getTreeBuilder().isDisposed()) { + myTree.setSelectionPaths(new TreePath[0]); + TreeBuilderUtil.restorePaths(getTreeBuilder(), pathsToExpand, selectionPaths, true); } + cb.setDone(); }; } else { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java index ba2df7a215de..987bd86aea2f 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java @@ -217,20 +217,17 @@ public abstract class AbstractProjectViewPane implements DataProvider, Disposabl private void doSelectModuleOrGroup(final Object toSelect, final boolean requestFocus) { ToolWindowManager windowManager=ToolWindowManager.getInstance(myProject); - final Runnable runnable = new Runnable() { - @Override - public void run() { - ProjectView projectView = ProjectView.getInstance(myProject); - if (requestFocus) { - projectView.changeView(getId(), getSubId()); - } - ((BaseProjectTreeBuilder)getTreeBuilder()).selectInWidth(toSelect, requestFocus, new Condition(){ - @Override - public boolean value(final AbstractTreeNode node) { - return node instanceof AbstractModuleNode || node instanceof ModuleGroupNode || node instanceof AbstractProjectNode; - } - }); + final Runnable runnable = () -> { + ProjectView projectView = ProjectView.getInstance(myProject); + if (requestFocus) { + projectView.changeView(getId(), getSubId()); } + ((BaseProjectTreeBuilder)getTreeBuilder()).selectInWidth(toSelect, requestFocus, new Condition(){ + @Override + public boolean value(final AbstractTreeNode node) { + return node instanceof AbstractModuleNode || node instanceof ModuleGroupNode || node instanceof AbstractProjectNode; + } + }); }; if (requestFocus) { windowManager.getToolWindow(ToolWindowId.PROJECT_VIEW).activate(runnable); diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java index f385c35cf3f4..298cead52d7a 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java @@ -55,12 +55,9 @@ public class MoveModuleToGroup extends ActionGroup { if (e == null) return EMPTY_ARRAY; List children = new ArrayList(myModuleGroup.childGroups(e.getDataContext())); - Collections.sort ( children, new Comparator() { - @Override - public int compare(final ModuleGroup moduleGroup1, final ModuleGroup moduleGroup2) { - assert moduleGroup1.getGroupPath().length == moduleGroup2.getGroupPath().length; - return moduleGroup1.toString().compareToIgnoreCase(moduleGroup2.toString()); - } + Collections.sort (children, (moduleGroup1, moduleGroup2) -> { + assert moduleGroup1.getGroupPath().length == moduleGroup2.getGroupPath().length; + return moduleGroup1.toString().compareToIgnoreCase(moduleGroup2.toString()); }); List result = new ArrayList(); diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java index 1121a9c22bc3..30e6c909d738 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java @@ -179,21 +179,18 @@ public class ProjectTreeBuilder extends BaseProjectTreeBuilder { synchronized (myFilesToRefresh) { if (myFilesToRefresh.add(fileToRefresh)) { myUpdateProblemAlarm.cancelAllRequests(); - myUpdateProblemAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!myProject.isOpen()) return; - Set filesToRefresh; - synchronized (myFilesToRefresh) { - filesToRefresh = new THashSet(myFilesToRefresh); - } - final DefaultMutableTreeNode rootNode = getRootNode(); - if (rootNode != null) { - updateNodesContaining(filesToRefresh, rootNode); - } - synchronized (myFilesToRefresh) { - myFilesToRefresh.removeAll(filesToRefresh); - } + myUpdateProblemAlarm.addRequest(() -> { + if (!myProject.isOpen()) return; + Set filesToRefresh; + synchronized (myFilesToRefresh) { + filesToRefresh = new THashSet(myFilesToRefresh); + } + final DefaultMutableTreeNode rootNode = getRootNode(); + if (rootNode != null) { + updateNodesContaining(filesToRefresh, rootNode); + } + synchronized (myFilesToRefresh) { + myFilesToRefresh.removeAll(filesToRefresh); } }, 200, ModalityState.NON_MODAL); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java index 852fbc754e63..2bbdfc176468 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java @@ -180,12 +180,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private static final String ATTRIBUTE_ID = "id"; private JPanel myViewContentPanel; - private static final Comparator PANE_WEIGHT_COMPARATOR = new Comparator() { - @Override - public int compare(final AbstractProjectViewPane o1, final AbstractProjectViewPane o2) { - return o1.getWeight() - o2.getWeight(); - } - }; + private static final Comparator PANE_WEIGHT_COMPARATOR = (o1, o2) -> o1.getWeight() - o2.getWeight(); private final FileEditorManager myFileEditorManager; private final MyPanel myDataProvider; private final SplitterProportionsData splitterProportions = new SplitterProportionsDataImpl(); @@ -551,12 +546,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } GuiUtils.replaceJSplitPaneWithIDEASplitter(myPanel); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - splitterProportions.restoreSplitterProportions(myPanel); - } - }); + SwingUtilities.invokeLater(() -> splitterProportions.restoreSplitterProportions(myPanel)); if (loadPaneExtensions) { ensurePanesLoaded(); @@ -870,13 +860,10 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo if (!views.isEmpty()) { list.setSelectedValue(views.get(0), true); } - Runnable runnable = new Runnable() { - @Override - public void run() { - if (list.getSelectedIndex() < 0) return; - AbstractProjectViewPane pane = (AbstractProjectViewPane)list.getSelectedValue(); - changeView(pane.getId()); - } + Runnable runnable = () -> { + if (list.getSelectedIndex() < 0) return; + AbstractProjectViewPane pane = (AbstractProjectViewPane)list.getSelectedValue(); + changeView(pane.getId()); }; new PopupChooserBuilder(list). @@ -1154,27 +1141,21 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo String title = IdeBundle.message("detach.library"); int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon()); if (ret != Messages.OK) return; - CommandProcessor.getInstance().executeCommand(module.getProject(), new Runnable() { - @Override - public void run() { - final Runnable action = new Runnable() { - @Override - public void run() { - ModuleRootManager rootManager = ModuleRootManager.getInstance(module); - OrderEntry[] orderEntries = rootManager.getOrderEntries(); - ModifiableRootModel model = rootManager.getModifiableModel(); - OrderEntry[] modifiableEntries = model.getOrderEntries(); - for (int i = 0; i < orderEntries.length; i++) { - OrderEntry entry = orderEntries[i]; - if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) { - model.removeOrderEntry(modifiableEntries[i]); - } - } - model.commit(); + CommandProcessor.getInstance().executeCommand(module.getProject(), () -> { + final Runnable action = () -> { + ModuleRootManager rootManager = ModuleRootManager.getInstance(module); + OrderEntry[] orderEntries = rootManager.getOrderEntries(); + ModifiableRootModel model = rootManager.getModifiableModel(); + OrderEntry[] modifiableEntries = model.getOrderEntries(); + for (int i = 0; i < orderEntries.length; i++) { + OrderEntry entry = orderEntries[i]; + if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) { + model.removeOrderEntry(modifiableEntries[i]); } - }; - ApplicationManager.getApplication().runWriteAction(action); - } + } + model.commit(); + }; + ApplicationManager.getApplication().runWriteAction(action); }, title, null); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewTree.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewTree.java index 9341e52f00db..428331dac9a1 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewTree.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewTree.java @@ -110,17 +110,14 @@ public abstract class ProjectViewTree extends JBTreeWithHintProvider { @Nullable @Override public Color getFileColorFor(Object object) { - return getColorForObject(object, getProject(), new NullableFunction() { - @Override - public PsiElement fun(Object object) { - if (object instanceof AbstractTreeNode) { - final Object element = ((AbstractTreeNode)object).getValue(); - if (element instanceof PsiElement) { - return (PsiElement)element; - } + return getColorForObject(object, getProject(), (NullableFunction)object1 -> { + if (object1 instanceof AbstractTreeNode) { + final Object element = ((AbstractTreeNode)object1).getValue(); + if (element instanceof PsiElement) { + return (PsiElement)element; } - return null; } + return null; }); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/RenameModuleHandler.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/RenameModuleHandler.java index edeb03233d88..4839c846a9e0 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/RenameModuleHandler.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/RenameModuleHandler.java @@ -98,22 +98,10 @@ public class RenameModuleHandler implements RenameHandler, TitledHandler { final String oldName = myModule.getName(); final ModifiableModuleModel modifiableModel = renameModule(inputString); if (modifiableModel == null) return false; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifiableModel.commit(); - } - }); - } - }); - } - }, IdeBundle.message("command.renaming.module", oldName), null); + CommandProcessor.getInstance().executeCommand(myProject, () -> DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + modifiableModel.commit(); + })), IdeBundle.message("command.renaming.module", oldName), null); return true; } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java index 2f1720918c32..10e702ff6226 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java @@ -135,40 +135,37 @@ public abstract class AbstractPsiBasedNode extends ProjectViewNode @Override public void update(final PresentationData data) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (!validate()) { - return; - } + ApplicationManager.getApplication().runReadAction(() -> { + if (!validate()) { + return; + } - final PsiElement value = extractPsiFromValue(); - LOG.assertTrue(value.isValid()); + final PsiElement value = extractPsiFromValue(); + LOG.assertTrue(value.isValid()); - int flags = getIconableFlags(); + int flags = getIconableFlags(); - try { - Icon icon = value.getIcon(flags); - data.setIcon(icon); - } - catch (IndexNotReadyException ignored) { - } - data.setPresentableText(myName); + try { + Icon icon = value.getIcon(flags); + data.setIcon(icon); + } + catch (IndexNotReadyException ignored) { + } + data.setPresentableText(myName); - try { - if (isDeprecated()) { - data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES); - } - } - catch (IndexNotReadyException ignored) { - } - updateImpl(data); - data.setIcon(patchIcon(myProject, data.getIcon(true), getVirtualFile())); - - for (ProjectViewNodeDecorator decorator : Extensions.getExtensions(ProjectViewNodeDecorator.EP_NAME, myProject)) { - decorator.decorate(AbstractPsiBasedNode.this, data); + try { + if (isDeprecated()) { + data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES); } } + catch (IndexNotReadyException ignored) { + } + updateImpl(data); + data.setIcon(patchIcon(myProject, data.getIcon(true), getVirtualFile())); + + for (ProjectViewNodeDecorator decorator : Extensions.getExtensions(ProjectViewNodeDecorator.EP_NAME, myProject)) { + decorator.decorate(AbstractPsiBasedNode.this, data); + } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewProjectNode.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewProjectNode.java index 9f7cc2f7ac57..bde610af52f2 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewProjectNode.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/ProjectViewProjectNode.java @@ -98,12 +98,7 @@ public class ProjectViewProjectNode extends AbstractProjectNode { userHome = null; } - Collections.sort(roots, new java.util.Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - return o1.getPath().compareTo(o2.getPath()); - } - }); + Collections.sort(roots, (o1, o2) -> o1.getPath().compareTo(o2.getPath())); Iterator it = roots.iterator(); VirtualFile current = it.next(); diff --git a/platform/lang-impl/src/com/intellij/ide/scopeView/EditScopesAction.java b/platform/lang-impl/src/com/intellij/ide/scopeView/EditScopesAction.java index b7c8647d65c7..46a5a72d41ac 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/EditScopesAction.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/EditScopesAction.java @@ -45,11 +45,8 @@ public class EditScopesAction extends AnAction implements DumbAware { final String scopeName = ProjectView.getInstance(project).getCurrentProjectViewPane().getSubId(); LOG.assertTrue(scopeName != null); final ScopeChooserConfigurable scopeChooserConfigurable = new ScopeChooserConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, scopeChooserConfigurable, new Runnable(){ - @Override - public void run() { - scopeChooserConfigurable.selectNodeInTree(scopeName); - } + ShowSettingsUtil.getInstance().editConfigurable(project, scopeChooserConfigurable, () -> { + scopeChooserConfigurable.selectNodeInTree(scopeName); }); } diff --git a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java index b6b12247df07..8e1879187181 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java @@ -212,32 +212,27 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } public void selectNode(final PsiElement element, final PsiFileSystemItem file, final boolean requestFocus) { - final Runnable runnable = new Runnable() { + final Runnable runnable = () -> myUpdateQueue.queue(new Update("Select") { @Override public void run() { - myUpdateQueue.queue(new Update("Select") { - @Override - public void run() { - if (myProject.isDisposed()) return; - PackageDependenciesNode node = myBuilder.findNode(file, element); - if (node != null && node.getPsiElement() != element) { - final TreePath path = new TreePath(node.getPath()); - if (myTree.isCollapsed(path)) { - myTree.expandPath(path); - myTree.makeVisible(path); - } - } - node = myBuilder.findNode(file, element); - if (node != null) { - TreeUtil.selectPath(myTree, new TreePath(node.getPath())); - if (requestFocus) { - myTree.requestFocus(); - } - } + if (myProject.isDisposed()) return; + PackageDependenciesNode node = myBuilder.findNode(file, element); + if (node != null && node.getPsiElement() != element) { + final TreePath path = new TreePath(node.getPath()); + if (myTree.isCollapsed(path)) { + myTree.expandPath(path); + myTree.makeVisible(path); } - }); + } + node = myBuilder.findNode(file, element); + if (node != null) { + TreeUtil.selectPath(myTree, new TreePath(node.getPath())); + if (requestFocus) { + myTree.requestFocus(); + } + } } - }; + }); doWhenDone(runnable); } @@ -349,13 +344,10 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { myTree.getEmptyText().setText("Loading..."); myActionCallback = new ActionCallback(); myTree.putClientProperty(TreeState.CALLBACK, new WeakReference(myActionCallback)); - myTree.setModel(myBuilder.build(myProject, true, new Runnable(){ - @Override - public void run() { - myTree.setPaintBusy(false); - myTree.getEmptyText().setText(UIBundle.message("message.nothingToShow")); - myActionCallback.setDone(); - } + myTree.setModel(myBuilder.build(myProject, true, () -> { + myTree.setPaintBusy(false); + myTree.getEmptyText().setText(UIBundle.message("message.nothingToShow")); + myActionCallback.setDone(); })); ((PackageDependenciesNode)myTree.getModel().getRoot()).sortChildren(); ((DefaultTreeModel)myTree.getModel()).reload(); @@ -463,20 +455,17 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { final List selectionPaths = TreeUtil.collectSelectedPaths(myTree, new TreePath(rootToReload.getPath())); final TreePath path = new TreePath(rootToReload.getPath()); final boolean wasCollapsed = myTree.isCollapsed(path); - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (!isTreeShowing() || rootToReload.getParent() == null) return; - TreeUtil.sort(rootToReload, getNodeComparator()); - treeModel.reload(rootToReload); - if (!wasCollapsed) { - myTree.collapsePath(path); - for (TreePath treePath : treePaths) { - myTree.expandPath(treePath); - } - for (TreePath selectionPath : selectionPaths) { - TreeUtil.selectPath(myTree, selectionPath); - } + final Runnable runnable = () -> { + if (!isTreeShowing() || rootToReload.getParent() == null) return; + TreeUtil.sort(rootToReload, getNodeComparator()); + treeModel.reload(rootToReload); + if (!wasCollapsed) { + myTree.collapsePath(path); + for (TreePath treePath : treePaths) { + myTree.expandPath(treePath); + } + for (TreePath selectionPath : selectionPaths) { + TreeUtil.selectPath(myTree, selectionPath); } } }; @@ -582,12 +571,9 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { final PsiElement child = event.getChild(); if (child == null) return; if (element.getContainingFile() == null) { - queueUpdate(new Runnable() { - @Override - public void run() { - if (!child.isValid()) return; - processNodeCreation(child); - } + queueUpdate(() -> { + if (!child.isValid()) return; + processNodeCreation(child); }, false); } } @@ -617,13 +603,10 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { final PsiElement child = event.getChild(); final PsiElement parent = event.getParent(); if (parent instanceof PsiDirectory && (child instanceof PsiFile && !isInjected((PsiFile)child) || child instanceof PsiDirectory)) { - queueUpdate(new Runnable() { - @Override - public void run() { - final DefaultMutableTreeNode rootToReload = myBuilder.removeNode(child, (PsiDirectory)parent); - if (rootToReload != null) { - reload(rootToReload); - } + queueUpdate(() -> { + final DefaultMutableTreeNode rootToReload = myBuilder.removeNode(child, (PsiDirectory)parent); + if (rootToReload != null) { + reload(rootToReload); } }, true); } @@ -635,14 +618,11 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { final PsiElement child = event.getChild(); if (oldParent instanceof PsiDirectory) { if (child instanceof PsiFileSystemItem && (!(child instanceof PsiFile) || !isInjected((PsiFile)child))) { - queueUpdate(new Runnable() { - @Override - public void run() { - final DefaultMutableTreeNode rootToReload = - myBuilder.removeNode(child, child instanceof PsiDirectory ? (PsiDirectory)child : (PsiDirectory)oldParent); - if (rootToReload != null) { - reload(rootToReload); - } + queueUpdate(() -> { + final DefaultMutableTreeNode rootToReload = + myBuilder.removeNode(child, child instanceof PsiDirectory ? (PsiDirectory)child : (PsiDirectory)oldParent); + if (rootToReload != null) { + reload(rootToReload); } }, true); } @@ -656,20 +636,17 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { if (newParent instanceof PsiDirectory) { if (child instanceof PsiFileSystemItem && (!(child instanceof PsiFile) || !isInjected((PsiFile)child))) { final PsiFileSystemItem file = (PsiFileSystemItem)child; - queueUpdate(new Runnable() { - @Override - public void run() { - final VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile != null && virtualFile.isValid()) { - final PsiFileSystemItem newFile = file.isValid() ? file : - (file.isDirectory() ? PsiManager.getInstance(myProject).findDirectory(virtualFile) - : PsiManager.getInstance(myProject).findFile(virtualFile)); - if (newFile != null) { - final PackageDependenciesNode rootToReload = newFile.isDirectory() ? myBuilder.addDirNode((PsiDirectory)newFile) - : myBuilder.addFileNode((PsiFile)newFile); - if (rootToReload != null) { - reload(rootToReload); - } + queueUpdate(() -> { + final VirtualFile virtualFile = file.getVirtualFile(); + if (virtualFile != null && virtualFile.isValid()) { + final PsiFileSystemItem newFile = file.isValid() ? file : + (file.isDirectory() ? PsiManager.getInstance(myProject).findDirectory(virtualFile) + : PsiManager.getInstance(myProject).findFile(virtualFile)); + if (newFile != null) { + final PackageDependenciesNode rootToReload = newFile.isDirectory() ? myBuilder.addDirNode((PsiDirectory)newFile) + : myBuilder.addFileNode((PsiFile)newFile); + if (rootToReload != null) { + reload(rootToReload); } } } @@ -685,16 +662,13 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { final PsiFile file = parent.getContainingFile(); if (file != null && file.getFileType() == StdFileTypes.JAVA) { if (!file.getViewProvider().isPhysical() && !isInjected(file)) return; - queueUpdate(new Runnable() { - @Override - public void run() { - if (file.isValid() && file.getViewProvider().isPhysical()) { - final NamedScope scope = getCurrentScope(); - final PackageSet packageSet = scope.getValue(); - if (packageSet == null) return; //invalid scope selected - if (packageSet.contains(file, NamedScopesHolder.getHolder(myProject, scope.getName(), myDependencyValidationManager))){ - reload(myBuilder.getFileParentNode(file.getVirtualFile())); - } + queueUpdate(() -> { + if (file.isValid() && file.getViewProvider().isPhysical()) { + final NamedScope scope = getCurrentScope(); + final PackageSet packageSet = scope.getValue(); + if (packageSet == null) return; //invalid scope selected + if (packageSet.contains(file, NamedScopesHolder.getHolder(myProject, scope.getName(), myDependencyValidationManager))){ + reload(myBuilder.getFileParentNode(file.getVirtualFile())); } } }, false); @@ -708,12 +682,9 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { if (element != null) { final NamedScope scope = getCurrentScope(); if (propertyName.equals(PsiTreeChangeEvent.PROP_FILE_NAME) || propertyName.equals(PsiTreeChangeEvent.PROP_FILE_TYPES)) { - queueUpdate(new Runnable() { - @Override - public void run() { - if (element.isValid()) { - processRenamed(scope, element.getContainingFile()); - } + queueUpdate(() -> { + if (element.isValid()) { + processRenamed(scope, element.getContainingFile()); } }, false); } @@ -733,12 +704,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { final PsiFile psiFile = event.getFile(); if (psiFile != null && !isInjected(psiFile)) { if (psiFile.getLanguage() == psiFile.getViewProvider().getBaseLanguage()) { - queueUpdate(new Runnable() { - @Override - public void run() { - processRenamed(scope, psiFile); - } - }, false); + queueUpdate(() -> processRenamed(scope, psiFile), false); } } else if (element instanceof PsiDirectory && element.isValid()) { @@ -752,22 +718,16 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { private void queueRefreshScope(final NamedScope scope, final PsiDirectory dir) { myUpdateQueue.cancelAllUpdates(); - queueUpdate(new Runnable() { - @Override - public void run() { - myTreeExpansionMonitor.freeze(); - refreshScope(scope); - doWhenDone(new Runnable() { - @Override - public void run() { - myTreeExpansionMonitor.restore(); - final PackageDependenciesNode dirNode = myBuilder.findNode(dir, dir); - if (dirNode != null) { - TreeUtil.selectPath(myTree, new TreePath(dirNode.getPath())); - } - } - }); - } + queueUpdate(() -> { + myTreeExpansionMonitor.freeze(); + refreshScope(scope); + doWhenDone(() -> { + myTreeExpansionMonitor.restore(); + final PackageDependenciesNode dirNode = myBuilder.findNode(dir, dir); + if (dirNode != null) { + TreeUtil.selectPath(myTree, new TreePath(dirNode.getPath())); + } + }); }, false); } @@ -788,12 +748,9 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { //expand/collapse state should be restored in actual request if needed private void queueUpdate(final Runnable request, boolean updateImmediately) { - final Runnable wrapped = new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - request.run(); - } + final Runnable wrapped = () -> { + if (myProject.isDisposed()) return; + request.run(); }; if (updateImmediately && isTreeShowing()) { myUpdateQueue.run(new Update(request) { @@ -945,23 +902,11 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } private void addNode(VirtualFile file, final String scopeName) { - queueUpdate(file, new Function() { - @Override - @Nullable - public DefaultMutableTreeNode fun(final PsiFile psiFile) { - return myBuilder.addFileNode(psiFile); - } - }, scopeName); + queueUpdate(file, psiFile -> myBuilder.addFileNode(psiFile), scopeName); } private void removeNode(VirtualFile file, final String scopeName) { - queueUpdate(file, new Function() { - @Override - @Nullable - public DefaultMutableTreeNode fun(final PsiFile psiFile) { - return myBuilder.removeNode(psiFile, psiFile.getContainingDirectory()); - } - }, scopeName); + queueUpdate(file, psiFile -> myBuilder.removeNode(psiFile, psiFile.getContainingDirectory()), scopeName); } private void queueUpdate(final VirtualFile fileToRefresh, @@ -1018,11 +963,8 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { if (!list.getName().equals(subId) && (oldName == null || !oldName.equals(subId))) { return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myDependencyValidationManager.fireScopeListeners(); - } + ApplicationManager.getApplication().invokeLater(() -> { + myDependencyValidationManager.fireScopeListeners(); }, myProject.getDisposed()); } diff --git a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java index 4c19e69fc436..cf0cbda79196 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java @@ -72,28 +72,25 @@ public class ScopeViewPane extends AbstractProjectViewPane { public void scopesChanged() { // amortize batch scope changes refreshProjectViewAlarm.cancelAllRequests(); - refreshProjectViewAlarm.addRequest(new Runnable(){ - @Override - public void run() { - if (myProject.isDisposed()) { - return; - } + refreshProjectViewAlarm.addRequest(() -> { + if (myProject.isDisposed()) { + return; + } - final String subId = getSubId(); - ProjectView projectView = ProjectView.getInstance(myProject); - final String id = projectView.getCurrentViewId(); - projectView.removeProjectPane(ScopeViewPane.this); - projectView.addProjectPane(ScopeViewPane.this); - if (id != null) { - if (Comparing.strEqual(id, getId())) { - projectView.changeView(id, subId); - } - else { - projectView.changeView(id); - } + final String subId = getSubId(); + ProjectView projectView = ProjectView.getInstance(myProject); + final String id = projectView.getCurrentViewId(); + projectView.removeProjectPane(ScopeViewPane.this); + projectView.addProjectPane(ScopeViewPane.this); + if (id != null) { + if (Comparing.strEqual(id, getId())) { + projectView.changeView(id, subId); + } + else { + projectView.changeView(id); } } - },10); + }, 10); } }; myDependencyValidationManager.addScopeListener(myScopeListener); @@ -142,11 +139,8 @@ public class ScopeViewPane extends AbstractProjectViewPane { @Override @NotNull public String[] getSubIds() { - return ContainerUtil.map2Array(getShownScopes(), String.class, new Function() { - @Override - public String fun(NamedScope scope) { - return scope.getName(); - } + return ContainerUtil.map2Array(getShownScopes(), String.class, scope -> { + return scope.getName(); }); } diff --git a/platform/lang-impl/src/com/intellij/ide/scratch/LRUPopupBuilder.java b/platform/lang-impl/src/com/intellij/ide/scratch/LRUPopupBuilder.java index a938e48e1098..8f38e5bce218 100644 --- a/platform/lang-impl/src/com/intellij/ide/scratch/LRUPopupBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/scratch/LRUPopupBuilder.java @@ -69,22 +69,14 @@ public abstract class LRUPopupBuilder { @NotNull public static ListPopup forFileLanguages(@NotNull Project project, @NotNull Iterable files, @NotNull final PerFileMappings mappings) { final VirtualFile[] filesCopy = VfsUtilCore.toVirtualFileArray(JBIterable.from(files).toList()); - Arrays.sort(filesCopy, new Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - return StringUtil.compare(o1.getName(), o2.getName(), !o1.getFileSystem().isCaseSensitive()); - } - }); - return forFileLanguages(project, null, new Consumer() { - @Override - public void consume(final Language t) { - new WriteCommandAction(project, "Change Language") { - @Override - protected void run(@NotNull Result result) throws Throwable { - changeLanguageWithUndo(project, t, filesCopy, mappings); - } - }.execute(); - } + Arrays.sort(filesCopy, (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), !o1.getFileSystem().isCaseSensitive())); + return forFileLanguages(project, null, t -> { + new WriteCommandAction(project, "Change Language") { + @Override + protected void run(@NotNull Result result) throws Throwable { + changeLanguageWithUndo(project, t, filesCopy, mappings); + } + }.execute(); }); } @@ -169,12 +161,7 @@ public abstract class LRUPopupBuilder { Collections.sort(items, myComparator); } if (!lru.isEmpty()) { - Collections.sort(lru, new Comparator() { - @Override - public int compare(T o1, T o2) { - return ContainerUtil.indexOf(ids, getStorageId(o1)) - ContainerUtil.indexOf(ids, getStorageId(o2)); - } - }); + Collections.sort(lru, (o1, o2) -> ContainerUtil.indexOf(ids, getStorageId(o1)) - ContainerUtil.indexOf(ids, getStorageId(o2))); } final T separator1 = !lru.isEmpty() && !items.isEmpty()? items.get(0) : null; final T separator2 = !lru.isEmpty() || !items.isEmpty()? ContainerUtil.getFirstItem(extra) : null; diff --git a/platform/lang-impl/src/com/intellij/ide/scratch/LightDirectoryIndex.java b/platform/lang-impl/src/com/intellij/ide/scratch/LightDirectoryIndex.java index 525e2fb27498..9b965a02128b 100644 --- a/platform/lang-impl/src/com/intellij/ide/scratch/LightDirectoryIndex.java +++ b/platform/lang-impl/src/com/intellij/ide/scratch/LightDirectoryIndex.java @@ -70,12 +70,7 @@ abstract class LightDirectoryIndex { public void reinitRoots() { myInfoCache.clear(); - collectRoots(new PairConsumer() { - @Override - public void consume(VirtualFile file, T info) { - cacheInfo(file, info); - } - }); + collectRoots((file, info) -> cacheInfo(file, info)); } protected abstract void collectRoots(@NotNull PairConsumer consumer); diff --git a/platform/lang-impl/src/com/intellij/ide/scratch/ScratchFileActions.java b/platform/lang-impl/src/com/intellij/ide/scratch/ScratchFileActions.java index 7bf0e048ddd7..2a91c70a91d6 100644 --- a/platform/lang-impl/src/com/intellij/ide/scratch/ScratchFileActions.java +++ b/platform/lang-impl/src/com/intellij/ide/scratch/ScratchFileActions.java @@ -72,12 +72,7 @@ public class ScratchFileActions { final String text = StringUtil.notNullize(getSelectionText(editor)); Language language = text.isEmpty() ? null : detectLanguageFromSelection(project, editor, file, text); - Consumer consumer = new Consumer() { - @Override - public void consume(Language language) { - doCreateNewScratch(project, false, language, text); - } - }; + Consumer consumer = language1 -> doCreateNewScratch(project, false, language1, text); if (language != null) { consumer.consume(language); } diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java b/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java index c3f74727270e..005feb2fd669 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java @@ -65,23 +65,20 @@ public abstract class TemplateLanguageStructureViewBuilder implements StructureV private void updateAfterPsiChange() { if (myProject.isDisposed()) return; if (myBaseStructureViewDescriptor != null && ((StructureViewComponent)myBaseStructureViewDescriptor.structureView).getTree() == null) return; - ApplicationManager.getApplication().runReadAction(new Runnable(){ - @Override - public void run() { - if (!myVirtualFile.isValid() || getViewProvider() == null) return; + ApplicationManager.getApplication().runReadAction(() -> { + if (!myVirtualFile.isValid() || getViewProvider() == null) return; - StructureViewWrapper structureViewWrapper = StructureViewFactoryEx.getInstanceEx(myProject).getStructureViewWrapper(); - if (structureViewWrapper == null) return; + StructureViewWrapper structureViewWrapper = StructureViewFactoryEx.getInstanceEx(myProject).getStructureViewWrapper(); + if (structureViewWrapper == null) return; - Language baseLanguage = getTemplateDataLanguage(); - if (baseLanguage == myTemplateDataLanguage - && (myBaseStructureViewDescriptor == null || isPsiValid(myBaseStructureViewDescriptor))) { - updateBaseLanguageView(); - } - else { - myTemplateDataLanguage = baseLanguage; - ((StructureViewWrapperImpl)structureViewWrapper).rebuild(); - } + Language baseLanguage = getTemplateDataLanguage(); + if (baseLanguage == myTemplateDataLanguage + && (myBaseStructureViewDescriptor == null || isPsiValid(myBaseStructureViewDescriptor))) { + updateBaseLanguageView(); + } + else { + myTemplateDataLanguage = baseLanguage; + ((StructureViewWrapperImpl)structureViewWrapper).rebuild(); } }); } @@ -189,12 +186,7 @@ public abstract class TemplateLanguageStructureViewBuilder implements StructureV @Override public void modificationCountChanged() { alarm.cancelAllRequests(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - updateAfterPsiChange(); - } - }, 300, ModalityState.NON_MODAL); + alarm.addRequest(() -> updateAfterPsiChange(), 300, ModalityState.NON_MODAL); } }); return myStructureViewComposite; diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java index 65441460a689..3f2a1c7683a5 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java @@ -197,24 +197,18 @@ public class StructureTreeBuilder extends AbstractTreeBuilder { private void setupUpdateAlarm() { myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!isDisposed() && !myProject.isDisposed()) { - addRootToUpdate(); - } + myUpdateAlarm.addRequest(() -> { + if (!isDisposed() && !myProject.isDisposed()) { + addRootToUpdate(); } }, 300, ModalityState.stateForComponent(getTree())); } final void addRootToUpdate() { final AbstractTreeStructure structure = getTreeStructure(); - structure.asyncCommit().doWhenDone(new Runnable() { - @Override - public void run() { - ((SmartTreeStructure)structure).rebuildTree(); - getUpdater().addSubtreeToUpdate(getRootNode()); - } + structure.asyncCommit().doWhenDone(() -> { + ((SmartTreeStructure)structure).rebuildTree(); + getUpdater().addSubtreeToUpdate(getRootNode()); }); } diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureViewComponent.java b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureViewComponent.java index 0eec66ec6988..1da6c29a0c39 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureViewComponent.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureViewComponent.java @@ -465,35 +465,22 @@ public class StructureViewComponent extends SimpleToolWindowPanel implements Tre final AsyncResult result = new AsyncResult(); final AbstractTreeNode toExpand = pathToElement.get(pathToElement.size() - 1); - myAbstractTreeBuilder.expand(toExpand, new Runnable() { - @Override - public void run() { - result.setDone(toExpand); - } - }); + myAbstractTreeBuilder.expand(toExpand, () -> result.setDone(toExpand)); return result; } public boolean select(final Object element, final boolean requestFocus) { - myAbstractTreeBuilder.getReady(this).doWhenDone(new Runnable() { + myAbstractTreeBuilder.getReady(this).doWhenDone(() -> expandPathToElement(element).doWhenDone(new Consumer() { @Override - public void run() { - expandPathToElement(element).doWhenDone(new Consumer() { - @Override - public void consume(AbstractTreeNode abstractTreeNode) { - myAbstractTreeBuilder.select(abstractTreeNode, new Runnable() { - @Override - public void run() { - if (requestFocus) { - IdeFocusManager.getInstance(myProject).requestFocus(myAbstractTreeBuilder.getTree(), false); - } - } - }); + public void consume(AbstractTreeNode abstractTreeNode) { + myAbstractTreeBuilder.select(abstractTreeNode, () -> { + if (requestFocus) { + IdeFocusManager.getInstance(myProject).requestFocus(myAbstractTreeBuilder.getTree(), false); } }); } - }); + })); return true; } @@ -543,13 +530,10 @@ public class StructureViewComponent extends SimpleToolWindowPanel implements Tre myAutoscrollAlarm.cancelAllRequests(); myAutoscrollAlarm.addRequest( - new Runnable() { - @Override - public void run() { - if (myAbstractTreeBuilder == null) return; - if (UIUtil.isFocusAncestor(StructureViewComponent.this)) return; - scrollToSelectedElementInner(); - } + () -> { + if (myAbstractTreeBuilder == null) return; + if (UIUtil.isFocusAncestor(StructureViewComponent.this)) return; + scrollToSelectedElementInner(); }, 1000); } @@ -947,12 +931,7 @@ public class StructureViewComponent extends SimpleToolWindowPanel implements Tre _setRefSize(size); if (size != null) { - myAbstractTreeBuilder.getReady(this).doWhenDone(new Runnable() { - @Override - public void run() { - _setRefSize(null); - } - }); + myAbstractTreeBuilder.getReady(this).doWhenDone(() -> _setRefSize(null)); } } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosPanel.java b/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosPanel.java index 583c1eed1615..17de1db9e785 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosPanel.java @@ -55,22 +55,12 @@ public abstract class ChangeListTodosPanel extends TodoPanel{ @Override public void defaultListChanged(final ChangeList oldDefaultList, final ChangeList newDefaultList) { rebuildWithAlarm(myAlarm); - AppUIUtil.invokeOnEdt(new Runnable() { - @Override - public void run() { - setDisplayName(IdeBundle.message("changelist.todo.title", newDefaultList.getName())); - } - }); + AppUIUtil.invokeOnEdt(() -> setDisplayName(IdeBundle.message("changelist.todo.title", newDefaultList.getName()))); } @Override public void changeListRenamed(final ChangeList list, final String oldName) { - AppUIUtil.invokeOnEdt(new Runnable() { - @Override - public void run() { - setDisplayName(IdeBundle.message("changelist.todo.title", list.getName())); - } - }); + AppUIUtil.invokeOnEdt(() -> setDisplayName(IdeBundle.message("changelist.todo.title", list.getName()))); } @Override diff --git a/platform/lang-impl/src/com/intellij/ide/todo/CurrentFileTodosPanel.java b/platform/lang-impl/src/com/intellij/ide/todo/CurrentFileTodosPanel.java index 4c61743db0a1..cbaa89f24c1d 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/CurrentFileTodosPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/CurrentFileTodosPanel.java @@ -45,12 +45,7 @@ abstract class CurrentFileTodosPanel extends TodoPanel { final PsiFile psiFile = file != null && file.isValid() ? PsiManager.getInstance(myProject).findFile(file) : null; // This invokeLater is required. The problem is setFile does a commit to PSI, but setFile is // invoked inside PSI change event. It causes an Exception like "Changes to PSI are not allowed inside event processing" - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - @Override - public void run() { - setFile(psiFile); - } - }); + DumbService.getInstance(myProject).smartInvokeLater(() -> setFile(psiFile)); } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoPanel.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoPanel.java index 2c1eef8db44e..ed44289c6d5e 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoPanel.java @@ -158,12 +158,9 @@ abstract class TodoPanel extends SimpleToolWindowPanel implements OccurenceNavig myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(final TreeSelectionEvent e) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myUsagePreviewPanel.isVisible()) { - updatePreviewPanel(); - } + SwingUtilities.invokeLater(() -> { + if (myUsagePreviewPanel.isVisible()) { + updatePreviewPanel(); } }); } @@ -214,12 +211,7 @@ abstract class TodoPanel extends SimpleToolWindowPanel implements OccurenceNavig autoScrollToSourceHandler.install(myTree); rightGroup.add(autoScrollToSourceHandler.createToggleAction()); - SetTodoFilterAction setTodoFilterAction = new SetTodoFilterAction(myProject, mySettings, new Consumer() { - @Override - public void consume(TodoFilter todoFilter) { - setTodoFilter(todoFilter); - } - }); + SetTodoFilterAction setTodoFilterAction = new SetTodoFilterAction(myProject, mySettings, todoFilter -> setTodoFilter(todoFilter)); rightGroup.add(setTodoFilterAction); rightGroup.add(new MyPreviewAction()); toolBarPanel.add( @@ -422,35 +414,23 @@ abstract class TodoPanel extends SimpleToolWindowPanel implements OccurenceNavig protected void rebuildWithAlarm(final Alarm alarm) { alarm.cancelAllRequests(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - final Set files = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - try { - myTodoTreeBuilder.collectFiles(new Processor() { - @Override - public boolean process(VirtualFile virtualFile) { - files.add(virtualFile); - return true; - } - }); - } - catch (IndexNotReadyException ignore) { - } - } - }); - final Runnable runnable = new Runnable() { - @Override - public void run() { - myTodoTreeBuilder.rebuildCache(files); - updateTree(); - } - }; - ApplicationManager.getApplication().invokeLater(runnable); - } + alarm.addRequest(() -> { + final Set files = new HashSet(); + ApplicationManager.getApplication().runReadAction(() -> { + try { + myTodoTreeBuilder.collectFiles(virtualFile -> { + files.add(virtualFile); + return true; + }); + } + catch (IndexNotReadyException ignore) { + } + }); + final Runnable runnable = () -> { + myTodoTreeBuilder.rebuildCache(files); + updateTree(); + }; + ApplicationManager.getApplication().invokeLater(runnable); }, 300); } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java index 8a7ebd416e41..32f03b62f7cb 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java @@ -29,11 +29,6 @@ import org.jetbrains.annotations.NotNull; public class TodoToolWindowFactory implements ToolWindowFactory { @Override public void createToolWindowContent(@NotNull final Project project, @NotNull final ToolWindow toolWindow) { - DumbService.getInstance(project).runWhenSmart(new Runnable() { - @Override - public void run() { - ServiceManager.getService(project, TodoView.class).initToolWindow(toolWindow); - } - }); + DumbService.getInstance(project).runWhenSmart(() -> ServiceManager.getService(project, TodoView.class).initToolWindow(toolWindow)); } } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java index 9f6129dee7a0..b506732ed800 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java @@ -152,12 +152,7 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { if (myUpdatable != updatable) { myUpdatable = updatable; if (updatable) { - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - updateTree(false); - } - }); + DumbService.getInstance(myProject).runWhenSmart(() -> updateTree(false)); } } } @@ -188,16 +183,13 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { protected ActionCallback beforeUpdate(final TreeUpdatePass pass) { if (!myDirtyFileSet.isEmpty()) { // suppress redundant cache validations final AsyncResult callback = new AsyncResult(); - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - try { - validateCache(); - getTodoTreeStructure().validateCache(); - } - finally { - callback.setDone(); - } + DumbService.getInstance(myProject).runWhenSmart(() -> { + try { + validateCache(); + getTodoTreeStructure().validateCache(); + } + finally { + callback.setDone(); } }); return callback; @@ -362,12 +354,9 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { myDirtyFileSet.clear(); myFile2Highlighter.clear(); - collectFiles(new Processor() { - @Override - public boolean process(VirtualFile virtualFile) { - myFileTree.add(virtualFile); - return true; - } + collectFiles(virtualFile -> { + myFileTree.add(virtualFile); + return true; }); getTodoTreeStructure().validateCache(); } @@ -816,17 +805,7 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { String propertyName = e.getPropertyName(); if (propertyName.equals(PsiTreeChangeEvent.PROP_ROOTS)) { // rebuild all tree when source roots were changed getUpdater().runBeforeUpdate( - new Runnable() { - @Override - public void run() { - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - rebuildCache(); - } - }); - } - } + () -> DumbService.getInstance(myProject).runWhenSmart(() -> rebuildCache()) ); updateTree(true); } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoView.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoView.java index 9544cb889e9f..3ea15ce4fd46 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoView.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoView.java @@ -195,23 +195,20 @@ public class TodoView implements PersistentStateComponent, Dispo @Override public void directoryMappingChanged() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myContentManager == null || myProject.isDisposed()) { - // was not initialized yet - return; - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myContentManager == null || myProject.isDisposed()) { + // was not initialized yet + return; + } - boolean hasActiveVcss = ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss(); - if (myIsVisible && !hasActiveVcss) { - myContentManager.removeContent(myChangeListTodosContent, false); - myIsVisible = false; - } - else if (!myIsVisible && hasActiveVcss) { - myContentManager.addContent(myChangeListTodosContent); - myIsVisible = true; - } + boolean hasActiveVcss = ProjectLevelVcsManager.getInstance(myProject).hasActiveVcss(); + if (myIsVisible && !hasActiveVcss) { + myContentManager.removeContent(myChangeListTodosContent, false); + myIsVisible = false; + } + else if (!myIsVisible && hasActiveVcss) { + myContentManager.addContent(myChangeListTodosContent); + myIsVisible = true; } }, ModalityState.NON_MODAL); } @@ -230,12 +227,7 @@ public class TodoView implements PersistentStateComponent, Dispo updateFilters(); } catch (ProcessCanceledException e) { - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - @Override - public void run() { - _updateFilters(); - } - }, ModalityState.NON_MODAL); + DumbService.getInstance(myProject).smartInvokeLater(() -> _updateFilters(), ModalityState.NON_MODAL); } } @@ -251,37 +243,23 @@ public class TodoView implements PersistentStateComponent, Dispo public void fileTypesChanged(@NotNull FileTypeEvent e) { // this invokeLater guaranties that this code will be invoked after // PSI gets the same event. - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - if (myAllTodos == null) { - return; - } - - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (TodoPanel panel : myPanels) { - panel.rebuildCache(); - } - } - } - ); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - for (TodoPanel panel : myPanels) { - panel.updateTree(); - } - } - }, ModalityState.NON_MODAL); - } - }, IdeBundle.message("progress.looking.for.todos"), false, myProject); + DumbService.getInstance(myProject).smartInvokeLater(() -> ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + if (myAllTodos == null) { + return; } - }); + + ApplicationManager.getApplication().runReadAction(() -> { + for (TodoPanel panel : myPanels) { + panel.rebuildCache(); + } + } + ); + ApplicationManager.getApplication().invokeLater(() -> { + for (TodoPanel panel : myPanels) { + panel.updateTree(); + } + }, ModalityState.NON_MODAL); + }, IdeBundle.message("progress.looking.for.todos"), false, myProject)); } } diff --git a/platform/lang-impl/src/com/intellij/ide/util/AbstractTreeClassChooserDialog.java b/platform/lang-impl/src/com/intellij/ide/util/AbstractTreeClassChooserDialog.java index b270acf5efdd..b10951e99e34 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/AbstractTreeClassChooserDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/util/AbstractTreeClassChooserDialog.java @@ -386,13 +386,10 @@ public abstract class AbstractTreeClassChooserDialog private void selectElementInTree(@NotNull final PsiElement element) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myBuilder == null) return; - final VirtualFile vFile = PsiUtilBase.getVirtualFile(element); - myBuilder.select(element, vFile, false); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myBuilder == null) return; + final VirtualFile vFile = PsiUtilBase.getVirtualFile(element); + myBuilder.select(element, vFile, false); }, getModalityState()); } diff --git a/platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java b/platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java index af9bac9ac110..ecca89f35679 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java +++ b/platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java @@ -133,12 +133,9 @@ public class DeleteHandler { public void run(final SafeDeleteDialog dialog) { if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements), true)) return; - SafeDeleteProcessor processor = SafeDeleteProcessor.createInstance(project, new Runnable() { - @Override - public void run() { - exit.set(true); - dialog.close(DialogWrapper.OK_EXIT_CODE); - } + SafeDeleteProcessor processor = SafeDeleteProcessor.createInstance(project, () -> { + exit.set(true); + dialog.close(DialogWrapper.OK_EXIT_CODE); }, elements, dialog.isSearchInComments(), dialog.isSearchForTextOccurences(), true); DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, processor); @@ -192,112 +189,96 @@ public class DeleteHandler { } } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - Collection directories = ContainerUtil.newSmartList(); - for (PsiElement e : elements) { - if (e instanceof PsiFileSystemItem && e.getParent() != null) { - directories.add(e.getParent()); - } - } - if (!CommonRefactoringUtil.checkReadOnlyStatus(project, Arrays.asList(elements), directories, false)) { - return; + CommandProcessor.getInstance().executeCommand(project, () -> { + Collection directories = ContainerUtil.newSmartList(); + for (PsiElement e : elements) { + if (e instanceof PsiFileSystemItem && e.getParent() != null) { + directories.add(e.getParent()); } + } + if (!CommonRefactoringUtil.checkReadOnlyStatus(project, Arrays.asList(elements), directories, false)) { + return; + } - // deleted from project view or something like that. - if (CommonDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()) == null) { - CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); - } + // deleted from project view or something like that. + if (CommonDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()) == null) { + CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); + } - for (final PsiElement elementToDelete : elements) { - if (!elementToDelete.isValid()) continue; //was already deleted - if (elementToDelete instanceof PsiDirectory) { - VirtualFile virtualFile = ((PsiDirectory)elementToDelete).getVirtualFile(); - if (virtualFile.isInLocalFileSystem() && !virtualFile.is(VFileProperty.SYMLINK)) { - ArrayList readOnlyFiles = new ArrayList(); - CommonRefactoringUtil.collectReadOnlyFiles(virtualFile, readOnlyFiles); + for (final PsiElement elementToDelete : elements) { + if (!elementToDelete.isValid()) continue; //was already deleted + if (elementToDelete instanceof PsiDirectory) { + VirtualFile virtualFile = ((PsiDirectory)elementToDelete).getVirtualFile(); + if (virtualFile.isInLocalFileSystem() && !virtualFile.is(VFileProperty.SYMLINK)) { + ArrayList readOnlyFiles = new ArrayList(); + CommonRefactoringUtil.collectReadOnlyFiles(virtualFile, readOnlyFiles); - if (!readOnlyFiles.isEmpty()) { - String message = IdeBundle.message("prompt.directory.contains.read.only.files", virtualFile.getPresentableUrl()); - int _result = Messages.showYesNoDialog(project, message, IdeBundle.message("title.delete"), Messages.getQuestionIcon()); - if (_result != Messages.YES) continue; + if (!readOnlyFiles.isEmpty()) { + String message = IdeBundle.message("prompt.directory.contains.read.only.files", virtualFile.getPresentableUrl()); + int _result = Messages.showYesNoDialog(project, message, IdeBundle.message("title.delete"), Messages.getQuestionIcon()); + if (_result != Messages.YES) continue; - boolean success = true; - for (VirtualFile file : readOnlyFiles) { - success = clearReadOnlyFlag(file, project); - if (!success) break; - } - if (!success) continue; + boolean success = true; + for (VirtualFile file : readOnlyFiles) { + success = clearReadOnlyFlag(file, project); + if (!success) break; } + if (!success) continue; } } - else if (!elementToDelete.isWritable() && - !(elementToDelete instanceof PsiFileSystemItem && PsiUtilBase.isSymLink((PsiFileSystemItem)elementToDelete))) { - final PsiFile file = elementToDelete.getContainingFile(); - if (file != null) { - final VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile.isInLocalFileSystem()) { - int _result = MessagesEx.fileIsReadOnly(project, virtualFile) - .setTitle(IdeBundle.message("title.delete")) - .appendMessage(IdeBundle.message("prompt.delete.it.anyway")) - .askYesNo(); - if (_result != Messages.YES) continue; + } + else if (!elementToDelete.isWritable() && + !(elementToDelete instanceof PsiFileSystemItem && PsiUtilBase.isSymLink((PsiFileSystemItem)elementToDelete))) { + final PsiFile file = elementToDelete.getContainingFile(); + if (file != null) { + final VirtualFile virtualFile = file.getVirtualFile(); + if (virtualFile.isInLocalFileSystem()) { + int _result = MessagesEx.fileIsReadOnly(project, virtualFile) + .setTitle(IdeBundle.message("title.delete")) + .appendMessage(IdeBundle.message("prompt.delete.it.anyway")) + .askYesNo(); + if (_result != Messages.YES) continue; - boolean success = clearReadOnlyFlag(virtualFile, project); - if (!success) continue; - } + boolean success = clearReadOnlyFlag(virtualFile, project); + if (!success) continue; } } + } + try { + elementToDelete.checkDelete(); + } + catch (IncorrectOperationException ex) { + Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); + continue; + } + + ApplicationManager.getApplication().runWriteAction(() -> { try { - elementToDelete.checkDelete(); + elementToDelete.delete(); } - catch (IncorrectOperationException ex) { - Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - continue; + catch (final IncorrectOperationException ex) { + ApplicationManager.getApplication().invokeLater( + () -> Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon())); } - - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - elementToDelete.delete(); - } - catch (final IncorrectOperationException ex) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - } - }); - } - } - }); - } + }); } }, RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null); } private static boolean clearReadOnlyFlag(final VirtualFile virtualFile, final Project project) { final boolean[] success = new boolean[1]; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - Runnable action = new Runnable() { - @Override - public void run() { - try { - ReadOnlyAttributeUtil.setReadOnlyAttribute(virtualFile, false); - success[0] = true; - } - catch (IOException e1) { - Messages.showMessageDialog(project, e1.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - } - } - }; - ApplicationManager.getApplication().runWriteAction(action); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + Runnable action = () -> { + try { + ReadOnlyAttributeUtil.setReadOnlyAttribute(virtualFile, false); + success[0] = true; + } + catch (IOException e1) { + Messages.showMessageDialog(project, e1.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); + } + }; + ApplicationManager.getApplication().runWriteAction(action); }, "", null); return success[0]; } diff --git a/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooser.java b/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooser.java index 7d5c86e9f7a1..fd066a536dda 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooser.java +++ b/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooser.java @@ -134,12 +134,7 @@ public class DirectoryChooser extends DialogWrapper { toolbarComponent.setBorder(null); panel.add(toolbarComponent, BorderLayout.NORTH); - final Runnable runnable = new Runnable() { - @Override - public void run() { - enableButtons(); - } - }; + final Runnable runnable = () -> enableButtons(); myView.onSelectionChange(runnable); final JComponent component = myView.getComponent(); final JScrollPane jScrollPane = ScrollPaneFactory.createScrollPane(component); diff --git a/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooserModuleTreeView.java b/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooserModuleTreeView.java index dbb7f632f302..492762f9a113 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooserModuleTreeView.java +++ b/platform/lang-impl/src/com/intellij/ide/util/DirectoryChooserModuleTreeView.java @@ -160,18 +160,8 @@ public class DirectoryChooserModuleTreeView implements DirectoryChooserView { final DefaultMutableTreeNode parentNode = ModuleGroupUtil.buildModuleGroupPath(new ModuleGroup(groupPath), myRootNode, myModuleGroupNodes, - new Consumer>() { - @Override - public void consume(final ModuleGroupUtil.ParentChildRelation parentChildRelation) { - insertNode(parentChildRelation.getChild(), parentChildRelation.getParent()); - } - }, - new Function() { - @Override - public DefaultMutableTreeNode fun(final ModuleGroup moduleGroup) { - return new DefaultMutableTreeNode(moduleGroup, true); - } - }); + parentChildRelation -> insertNode(parentChildRelation.getChild(), parentChildRelation.getParent()), + moduleGroup -> new DefaultMutableTreeNode(moduleGroup, true)); insertNode(node, parentNode); } myModuleNodes.put(module, node); @@ -185,25 +175,22 @@ public class DirectoryChooserModuleTreeView implements DirectoryChooserView { private void insertNode(final DefaultMutableTreeNode nodeToInsert, DefaultMutableTreeNode rootNode) { final Enumeration enumeration = rootNode.children(); ArrayList children = Collections.list(enumeration); - final int index = Collections.binarySearch(children, nodeToInsert, new Comparator() { - @Override - public int compare(DefaultMutableTreeNode node1, DefaultMutableTreeNode node2) { - final Object o1 = node1.getUserObject(); - final Object o2 = node2.getUserObject(); - if (o1 instanceof Module && o2 instanceof Module) { - return ((Module)o1).getName().compareToIgnoreCase(((Module)o2).getName()); - } - if (o1 instanceof ModuleGroup && o2 instanceof ModuleGroup){ - return o1.toString().compareToIgnoreCase(o2.toString()); - } - if (o1 instanceof ModuleGroup) return -1; - if (o1 instanceof DirectoryChooser.ItemWrapper && o2 instanceof DirectoryChooser.ItemWrapper) { - final VirtualFile virtualFile1 = ((DirectoryChooser.ItemWrapper)o1).getDirectory().getVirtualFile(); - final VirtualFile virtualFile2 = ((DirectoryChooser.ItemWrapper)o2).getDirectory().getVirtualFile(); - return Comparing.compare(virtualFile1.getPath(), virtualFile2.getPath()); - } - return 1; + final int index = Collections.binarySearch(children, nodeToInsert, (node1, node2) -> { + final Object o1 = node1.getUserObject(); + final Object o2 = node2.getUserObject(); + if (o1 instanceof Module && o2 instanceof Module) { + return ((Module)o1).getName().compareToIgnoreCase(((Module)o2).getName()); } + if (o1 instanceof ModuleGroup && o2 instanceof ModuleGroup){ + return o1.toString().compareToIgnoreCase(o2.toString()); + } + if (o1 instanceof ModuleGroup) return -1; + if (o1 instanceof DirectoryChooser.ItemWrapper && o2 instanceof DirectoryChooser.ItemWrapper) { + final VirtualFile virtualFile1 = ((DirectoryChooser.ItemWrapper)o1).getDirectory().getVirtualFile(); + final VirtualFile virtualFile2 = ((DirectoryChooser.ItemWrapper)o2).getDirectory().getVirtualFile(); + return Comparing.compare(virtualFile1.getPath(), virtualFile2.getPath()); + } + return 1; }); final int insertionPoint = -(index+1); if (insertionPoint < 0 || insertionPoint > rootNode.getChildCount()) { diff --git a/platform/lang-impl/src/com/intellij/ide/util/FileStructureDialog.java b/platform/lang-impl/src/com/intellij/ide/util/FileStructureDialog.java index 250921f73b5a..7ea8f6b33e07 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/FileStructureDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/util/FileStructureDialog.java @@ -372,17 +372,14 @@ public class FileStructureDialog extends DialogWrapper { return; } builder.addUpdateRequest(hasPrefixShortened(evt)); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - int index = myList.getSelectedIndex(); - if (index != -1 && index < myList.getModel().getSize()) { - myList.clearSelection(); - ScrollingUtil.selectItem(myList, index); - } - else { - ScrollingUtil.ensureSelectionExists(myList); - } + ApplicationManager.getApplication().invokeLater(() -> { + int index = myList.getSelectedIndex(); + if (index != -1 && index < myList.getModel().getSize()) { + myList.clearSelection(); + ScrollingUtil.selectItem(myList, index); + } + else { + ScrollingUtil.ensureSelectionExists(myList); } }); } @@ -399,12 +396,9 @@ public class FileStructureDialog extends DialogWrapper { public boolean navigateSelectedElement() { final Ref succeeded = new Ref(); final CommandProcessor commandProcessor = CommandProcessor.getInstance(); - commandProcessor.executeCommand(myProject, new Runnable() { - @Override - public void run() { - succeeded.set(MyCommanderPanel.super.navigateSelectedElement()); - IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); - } + commandProcessor.executeCommand(myProject, () -> { + succeeded.set(MyCommanderPanel.super.navigateSelectedElement()); + IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); }, "Navigate", null); if (succeeded.get()) { close(CANCEL_EXIT_CODE); diff --git a/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java b/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java index 018618e08625..9044e5683a64 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java +++ b/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java @@ -219,17 +219,14 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner { final Set psiSelection = ContainerUtil.map2LinkedSet(result, Functions.pairSecond()); - String text = StringUtil.join(result, new Function, String>() { - @Override - public String fun(Pair pair) { - PsiElement psi = pair.second; - String defaultPresentation = pair.first.getPresentation().getPresentableText(); - if (psi == null) return defaultPresentation; - for (PsiElement p = psi.getParent(); p != null; p = p.getParent()) { - if (psiSelection.contains(p)) return null; - } - return ObjectUtils.chooseNotNull(psi.getText(), defaultPresentation); + String text = StringUtil.join(result, pair -> { + PsiElement psi = pair.second; + String defaultPresentation = pair.first.getPresentation().getPresentableText(); + if (psi == null) return defaultPresentation; + for (PsiElement p = psi.getParent(); p != null; p = p.getParent()) { + if (psiSelection.contains(p)) return null; } + return ObjectUtils.chooseNotNull(psi.getText(), defaultPresentation); }, "\n"); String htmlText = "\n" + text + "\n"; @@ -370,41 +367,26 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner { myPopup.cancel(); } }); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - myFilteringStructure.rebuild(); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + ApplicationManager.getApplication().runReadAction(() -> { + myFilteringStructure.rebuild(); + }); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myAbstractTreeBuilder.queueUpdate().doWhenDone(new Runnable() { - @Override - public void run() { - myTreeHasBuilt.setDone(); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myAbstractTreeBuilder.isDisposed()) return; - if (selectPsiElement(myInitialPsiElement) == null) { - TreeUtil.ensureSelection(myAbstractTreeBuilder.getTree()); - myAbstractTreeBuilder.revalidateTree(); - } - } - }); - } - }); - installUpdater(); - } + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + myAbstractTreeBuilder.queueUpdate().doWhenDone(() -> { + myTreeHasBuilt.setDone(); + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + if (myAbstractTreeBuilder.isDisposed()) return; + if (selectPsiElement(myInitialPsiElement) == null) { + TreeUtil.ensureSelection(myAbstractTreeBuilder.getTree()); + myAbstractTreeBuilder.revalidateTree(); + } + }); }); - } + installUpdater(); + }); }); } @@ -426,32 +408,26 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner { if (!filter.equals(prefix)) { final boolean isBackspace = prefix.length() < filter.length(); filter = prefix; - myAbstractTreeBuilder.refilter(null, false, false).doWhenProcessed(new Runnable() { - @Override - public void run() { - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myAbstractTreeBuilder.isDisposed()) return; - myTree.repaint(); - if (isBackspace && handleBackspace(filter)) { - return; - } - if (myFilteringStructure.getRootElement().getChildren().length == 0) { - for (JCheckBox box : myCheckBoxes.values()) { - if (!box.isSelected()) { - myAutoClicked.add(box); - myTriggeredCheckboxes.add(0, Pair.create(filter, box)); - box.doClick(); - filter = ""; - break; - } - } + myAbstractTreeBuilder.refilter(null, false, false).doWhenProcessed(() -> { + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + if (myAbstractTreeBuilder.isDisposed()) return; + myTree.repaint(); + if (isBackspace && handleBackspace(filter)) { + return; + } + if (myFilteringStructure.getRootElement().getChildren().length == 0) { + for (JCheckBox box : myCheckBoxes.values()) { + if (!box.isSelected()) { + myAutoClicked.add(box); + myTriggeredCheckboxes.add(0, Pair.create(filter, box)); + box.doClick(); + filter = ""; + break; } } - }); - } + } + }); }); } if (!alarm.isDisposed()) { @@ -816,25 +792,22 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner { final Ref succeeded = new Ref(); final CommandProcessor commandProcessor = CommandProcessor.getInstance(); - commandProcessor.executeCommand(myProject, new Runnable() { - @Override - public void run() { - if (selectedNode != null) { - if (selectedNode.canNavigateToSource()) { - myPopup.cancel(); - selectedNode.navigate(true); - succeeded.set(true); - } - else { - succeeded.set(false); - } + commandProcessor.executeCommand(myProject, () -> { + if (selectedNode != null) { + if (selectedNode.canNavigateToSource()) { + myPopup.cancel(); + selectedNode.navigate(true); + succeeded.set(true); } else { succeeded.set(false); } - - IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); } + else { + succeeded.set(false); + } + + IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); }, "Navigate", null); return succeeded.get(); } @@ -873,24 +846,13 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner { myFilteringStructure.rebuild(); final Object sel = selection; - final Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - myAbstractTreeBuilder.refilter(sel, true, false).doWhenProcessed(new Runnable() { - @Override - public void run() { - if (mySpeedSearch.isPopupActive()) { - mySpeedSearch.refreshSelection(); - } - } - }); - } - }); - } - }; + final Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> { + myAbstractTreeBuilder.refilter(sel, true, false).doWhenProcessed(() -> { + if (mySpeedSearch.isPopupActive()) { + mySpeedSearch.refreshSelection(); + } + }); + }); if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } @@ -1143,13 +1105,10 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner { } } - Collections.sort(cur, new Comparator() { - @Override - public int compare(SpeedSearchObjectWithWeight o1, SpeedSearchObjectWithWeight o2) { - final int i = o1.compareWith(o2); - return i != 0 ? i - : ((TreePath)o2.node).getPathCount() - ((TreePath)o1.node).getPathCount(); - } + Collections.sort(cur, (o1, o2) -> { + final int i = o1.compareWith(o2); + return i != 0 ? i + : ((TreePath)o2.node).getPathCount() - ((TreePath)o1.node).getPathCount(); }); return cur.isEmpty() ? null : cur.get(0).node; } diff --git a/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java b/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java index cff92f7903b2..a275503a490e 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java +++ b/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java @@ -158,11 +158,8 @@ public class MemberChooser extends DialogWrapper implemen myElementToNodeMap.clear(); myContainerNodes.clear(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - myTreeModel = buildModel(); - } + ApplicationManager.getApplication().runReadAction(() -> { + myTreeModel = buildModel(); }); myTree.setModel(myTreeModel); diff --git a/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java b/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java index 7fbde2d02ee4..09563ac689f4 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java +++ b/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java @@ -120,12 +120,8 @@ public class PlatformPackageUtil { final GlobalSearchScope scope_ = scope; List dirs = ContainerUtil - .mapNotNull(ProjectRootManager.getInstance(project).getContentSourceRoots(), new Function() { - @Override - public PsiDirectory fun(VirtualFile virtualFile) { - return scope_.contains(virtualFile) ? PsiManager.getInstance(project).findDirectory(virtualFile) : null; - } - }); + .mapNotNull(ProjectRootManager.getInstance(project).getContentSourceRoots(), + virtualFile -> scope_.contains(virtualFile) ? PsiManager.getInstance(project).findDirectory(virtualFile) : null); psiDirectory = DirectoryChooserUtil.selectDirectory(project, dirs.toArray(new PsiDirectory[dirs.size()]), baseDir, File.separatorChar + packageName.replace('.', File.separatorChar)); if (psiDirectory == null) return null; @@ -211,11 +207,8 @@ public class PlatformPackageUtil { } }); - List directories = ContainerUtil.mapNotNull(query.findAll(), new Function() { - @Override - public PsiDirectory fun(VirtualFile virtualFile) { - return manager.findDirectory(virtualFile); - } + List directories = ContainerUtil.mapNotNull(query.findAll(), virtualFile -> { + return manager.findDirectory(virtualFile); }); return directories.toArray(new PsiDirectory[directories.size()]); } diff --git a/platform/lang-impl/src/com/intellij/ide/util/PsiElementListCellRenderer.java b/platform/lang-impl/src/com/intellij/ide/util/PsiElementListCellRenderer.java index 8128542ba001..b53e7dcfdb93 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/PsiElementListCellRenderer.java +++ b/platform/lang-impl/src/com/intellij/ide/util/PsiElementListCellRenderer.java @@ -270,12 +270,7 @@ public abstract class PsiElementListCellRenderer extends J } public Comparator getComparator() { - return new Comparator() { - @Override - public int compare(T o1, T o2) { - return getComparingObject(o1).compareTo(getComparingObject(o2)); - } - }; + return (o1, o2) -> getComparingObject(o1).compareTo(getComparingObject(o2)); } @NotNull @@ -290,19 +285,16 @@ public abstract class PsiElementListCellRenderer extends J } public void installSpeedSearch(PopupChooserBuilder builder, final boolean includeContainerText) { - builder.setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - if (o instanceof PsiElement) { - final String elementText = getElementText((T)o); - if (includeContainerText) { - return elementText + " " + getContainerText((T)o, elementText); - } - return elementText; - } - else { - return o.toString(); + builder.setFilteringEnabled(o -> { + if (o instanceof PsiElement) { + final String elementText = getElementText((T)o); + if (includeContainerText) { + return elementText + " " + getContainerText((T)o, elementText); } + return elementText; + } + else { + return o.toString(); } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java b/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java index a414b0628a8f..85b156103e85 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java @@ -113,20 +113,10 @@ public final class TreeFileChooserDialog extends DialogWrapper implements TreeFi init(); if (initialFile != null) { // dialog does not exist yet - SwingUtilities.invokeLater(new Runnable(){ - @Override - public void run() { - selectFile(initialFile); - } - }); + SwingUtilities.invokeLater(() -> selectFile(initialFile)); } - SwingUtilities.invokeLater(new Runnable(){ - @Override - public void run() { - handleSelectionChanged(); - } - }); + SwingUtilities.invokeLater(() -> handleSelectionChanged()); } @Override @@ -264,12 +254,7 @@ public final class TreeFileChooserDialog extends DialogWrapper implements TreeFi myTabbedPane.addTab(IdeBundle.message("tab.chooser.project"), scrollPane); myTabbedPane.addTab(IdeBundle.message("tab.chooser.search.by.name"), dummyPanel); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myGotoByNamePanel.invoke(new MyCallback(), ModalityState.stateForComponent(getRootPane()), false); - } - }); + SwingUtilities.invokeLater(() -> myGotoByNamePanel.invoke(new MyCallback(), ModalityState.stateForComponent(getRootPane()), false)); myTabbedPane.addChangeListener( new ChangeListener() { @@ -313,12 +298,9 @@ public final class TreeFileChooserDialog extends DialogWrapper implements TreeFi @Override public void selectFile(@NotNull final PsiFile file) { // Select element in the tree - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myBuilder != null) { - myBuilder.select(file, file.getVirtualFile(), true); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myBuilder != null) { + myBuilder.select(file, file.getVirtualFile(), true); } }, ModalityState.stateForComponent(getWindow())); } @@ -424,11 +406,8 @@ public final class TreeFileChooserDialog extends DialogWrapper implements TreeFi if (myFileType != null && myProject != null) { GlobalSearchScope scope = myShowLibraryContents ? GlobalSearchScope.allScope(myProject) : GlobalSearchScope.projectScope(myProject); Collection virtualFiles = FileTypeIndex.getFiles(myFileType, scope); - fileNames = ContainerUtil.map2Array(virtualFiles, String.class, new Function() { - @Override - public String fun(VirtualFile file) { - return file.getName(); - } + fileNames = ContainerUtil.map2Array(virtualFiles, String.class, file -> { + return file.getName(); }); } else { diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java index 8aa3828065ff..12a3d4a556c7 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java @@ -525,39 +525,36 @@ public abstract class ChooseByNameBase { myFocusPoint = null; } cancelListUpdater(); // cancel thread as early as possible - myHideAlarm.addRequest(new Runnable() { - @Override - public void run() { - JBPopup popup = JBPopupFactory.getInstance().getChildFocusedPopup(e.getComponent()); - if (popup != null) { - popup.addListener(new JBPopupListener.Adapter() { - @Override - public void onClosed(@NotNull LightweightWindowEvent event) { - if (event.isOk()) { - hideHint(); - } + myHideAlarm.addRequest(() -> { + JBPopup popup = JBPopupFactory.getInstance().getChildFocusedPopup(e.getComponent()); + if (popup != null) { + popup.addListener(new JBPopupListener.Adapter() { + @Override + public void onClosed(@NotNull LightweightWindowEvent event) { + if (event.isOk()) { + hideHint(); } - }); + } + }); + } + else { + Component oppositeComponent = e.getOppositeComponent(); + if (oppositeComponent == myCheckBox) { + IdeFocusManager.getInstance(myProject).requestFocus(myTextField, true); + return; } - else { - Component oppositeComponent = e.getOppositeComponent(); - if (oppositeComponent == myCheckBox) { - IdeFocusManager.getInstance(myProject).requestFocus(myTextField, true); - return; - } - if (oppositeComponent != null && !(oppositeComponent instanceof JFrame) && - myList.isShowing() && - (oppositeComponent == myList || SwingUtilities.isDescendingFrom(myList, oppositeComponent))) { - IdeFocusManager.getInstance(myProject).requestFocus(myTextField, true);// Otherwise me may skip some KeyEvents - return; - } - - if (isDescendingFromTemporarilyFocusableToolWindow(oppositeComponent)) { - return; // Allow toolwindows to gain focus (used by QuickDoc shown in a toolwindow) - } - - hideHint(); + if (oppositeComponent != null && !(oppositeComponent instanceof JFrame) && + myList.isShowing() && + (oppositeComponent == myList || SwingUtilities.isDescendingFrom(myList, oppositeComponent))) { + IdeFocusManager.getInstance(myProject).requestFocus(myTextField, true);// Otherwise me may skip some KeyEvents + return; } + + if (isDescendingFromTemporarilyFocusableToolWindow(oppositeComponent)) { + return; // Allow toolwindows to gain focus (used by QuickDoc shown in a toolwindow) + } + + hideHint(); } }, 5); } @@ -901,22 +898,19 @@ public abstract class ChooseByNameBase { ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(myTextFieldPanel, myTextField); builder.setLocateWithinScreenBounds(false); - builder.setKeyEventHandler(new BooleanFunction() { - @Override - public boolean fun(KeyEvent event) { - if (myTextPopup == null || !AbstractPopup.isCloseRequest(event) || !myTextPopup.isCancelKeyEnabled()) { - return false; - } + builder.setKeyEventHandler(event -> { + if (myTextPopup == null || !AbstractPopup.isCloseRequest(event) || !myTextPopup.isCancelKeyEnabled()) { + return false; + } - IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); - if (isDescendingFromTemporarilyFocusableToolWindow(focusManager.getFocusOwner())) { - focusManager.requestFocus(myTextField, true); - return false; - } - else { - myTextPopup.cancel(event); - return true; - } + IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); + if (isDescendingFromTemporarilyFocusableToolWindow(focusManager.getFocusOwner())) { + focusManager.requestFocus(myTextField, true); + return false; + } + else { + myTextPopup.cancel(event); + return true; } }).setCancelCallback(new Computable() { @Override @@ -986,12 +980,7 @@ public abstract class ChooseByNameBase { myAlarm.cancelAllRequests(); if (delay > 0) { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - rebuildList(pos, 0, modalityState, postRunnable); - } - }, delay, ModalityState.stateForComponent(myTextField)); + myAlarm.addRequest(() -> rebuildList(pos, 0, modalityState, postRunnable), delay, ModalityState.stateForComponent(myTextField)); return; } @@ -1021,15 +1010,12 @@ public abstract class ChooseByNameBase { ((MatcherHolder)cellRenderer).setPatternMatcher(matcher); } - scheduleCalcElements(text, myCheckBox.isSelected(), modalityState, new Consumer>() { - @Override - public void consume(Set elements) { - ApplicationManager.getApplication().assertIsDispatchThread(); - backgroundCalculationFinished(elements, pos); + scheduleCalcElements(text, myCheckBox.isSelected(), modalityState, elements -> { + ApplicationManager.getApplication().assertIsDispatchThread(); + backgroundCalculationFinished(elements, pos); - if (postRunnable != null) { - postRunnable.run(); - } + if (postRunnable != null) { + postRunnable.run(); } }); } @@ -1336,12 +1322,7 @@ public abstract class ChooseByNameBase { final String pattern = getTrimmedText(); final int oldPos = myList.getSelectedIndex(); myHistory.add(Pair.create(pattern, oldPos)); - final Runnable postRunnable = new Runnable() { - @Override - public void run() { - fillInCommonPrefix(pattern); - } - }; + final Runnable postRunnable = () -> fillInCommonPrefix(pattern); rebuildList(0, 0, ModalityState.current(), postRunnable); return; } @@ -1468,13 +1449,10 @@ public abstract class ChooseByNameBase { if (!myInitIsDone) return; if (myModel instanceof GotoClassModel2 && isFileName(str)) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - GotoFileAction gotoFile = new GotoFileAction(); - DataContext context = DataManager.getInstance().getDataContext(myTextField); - gotoFile.actionPerformed(AnActionEvent.createFromAnAction(gotoFile, null, ActionPlaces.UNKNOWN, context)); - } + SwingUtilities.invokeLater(() -> { + GotoFileAction gotoFile = new GotoFileAction(); + DataContext context = DataManager.getInstance().getDataContext(myTextField); + gotoFile.actionPerformed(AnActionEvent.createFromAnAction(gotoFile, null, ActionPlaces.UNKNOWN, context)); }); } } @@ -1563,17 +1541,14 @@ public abstract class ChooseByNameBase { final boolean edt = myModel instanceof EdtSortingModel; final Set filtered = !edt ? filter(elements) : Collections.emptySet(); - return new Continuation(new Runnable() { - @Override - public void run() { - if (!checkDisposed() && !myProgress.isCanceled()) { - CalcElementsThread currentBgProcess = myCalcElementsThread; - LOG.assertTrue(currentBgProcess == CalcElementsThread.this, currentBgProcess); + return new Continuation(() -> { + if (!checkDisposed() && !myProgress.isCanceled()) { + CalcElementsThread currentBgProcess = myCalcElementsThread; + LOG.assertTrue(currentBgProcess == CalcElementsThread.this, currentBgProcess); - showCard(cardToShow, 0); + showCard(cardToShow, 0); - myCallback.consume(edt ? filter(elements) : filtered); - } + myCallback.consume(edt ? filter(elements) : filtered); } }, myModalityState); } @@ -1604,18 +1579,15 @@ public abstract class ChooseByNameBase { myProvider.filterElements( ChooseByNameBase.this, pattern, everywhere, indicator, - new Processor() { - @Override - public boolean process(Object o) { - if (indicator.isCanceled()) return false; - elements.add(o); + o -> { + if (indicator.isCanceled()) return false; + elements.add(o); - if (isOverflow(elements)) { - elements.add(EXTRA_ELEM); - return false; - } - return true; + if (isOverflow(elements)) { + elements.add(EXTRA_ELEM); + return false; } + return true; } ); if (myAlwaysHasMore) { @@ -1630,12 +1602,9 @@ public abstract class ChooseByNameBase { private void showCard(final String card, final int delay) { if (ApplicationManager.getApplication().isUnitTestMode()) return; myShowCardAlarm.cancelAllRequests(); - myShowCardAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!myProgress.isCanceled()) { - myCard.show(myCardContainer, card); - } + myShowCardAlarm.addRequest(() -> { + if (!myProgress.isCanceled()) { + myCard.show(myCardContainer, card); } }, delay, myModalityState); } @@ -1751,23 +1720,20 @@ public abstract class ChooseByNameBase { } }; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - boolean anyPlace = isSearchInAnyPlace(); - setSearchInAnyPlace(false); - myCalcUsagesThread.addElementsByPattern(text, prefixMatchElementsArray, indicator, everywhere); - setSearchInAnyPlace(anyPlace); + ApplicationManager.getApplication().runReadAction(() -> { + boolean anyPlace = isSearchInAnyPlace(); + setSearchInAnyPlace(false); + myCalcUsagesThread.addElementsByPattern(text, prefixMatchElementsArray, indicator, everywhere); + setSearchInAnyPlace(anyPlace); - if (anyPlace && !indicator.isCanceled()) { - myCalcUsagesThread.addElementsByPattern(text, nonPrefixMatchElementsArray, indicator, everywhere); - nonPrefixMatchElementsArray.removeAll(prefixMatchElementsArray); - } - - indicator.setText("Prepare..."); - fillUsages(prefixMatchElementsArray, usages, targets, false); - fillUsages(nonPrefixMatchElementsArray, usages, targets, true); + if (anyPlace && !indicator.isCanceled()) { + myCalcUsagesThread.addElementsByPattern(text, nonPrefixMatchElementsArray, indicator, everywhere); + nonPrefixMatchElementsArray.removeAll(prefixMatchElementsArray); } + + indicator.setText("Prepare..."); + fillUsages(prefixMatchElementsArray, usages, targets, false); + fillUsages(nonPrefixMatchElementsArray, usages, targets, true); }); } diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ContributorsBasedGotoByModel.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ContributorsBasedGotoByModel.java index 4b0bb2f5bd58..57304037bd77 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ContributorsBasedGotoByModel.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ContributorsBasedGotoByModel.java @@ -101,14 +101,11 @@ public abstract class ContributorsBasedGotoByModel implements ChooseByNameModelE final TIntHashSet filter = new TIntHashSet(1000); myContributorToItsSymbolsMap.put(contributor, filter); if (contributor instanceof ChooseByNameContributorEx) { - ((ChooseByNameContributorEx)contributor).processNames(new Processor() { - @Override - public boolean process(String s) { - if (nameProcessor.process(s)) { - filter.add(s.hashCode()); - } - return true; + ((ChooseByNameContributorEx)contributor).processNames(s -> { + if (nameProcessor.process(s)) { + filter.add(s.hashCode()); } + return true; }, FindSymbolParameters.searchScopeFor(myProject, checkBoxState), getIdFilter(checkBoxState)); } else { String[] names = contributor.getNames(myProject, checkBoxState); @@ -191,64 +188,58 @@ public abstract class ContributorsBasedGotoByModel implements ChooseByNameModelE long elementByNameStarted = System.currentTimeMillis(); final List items = Collections.synchronizedList(new ArrayList()); - Processor processor = new Processor() { - @Override - public boolean process(@NotNull ChooseByNameContributor contributor) { - if (myProject.isDisposed()) { - return true; - } - TIntHashSet filter = myContributorToItsSymbolsMap.get(contributor); - if (filter != null && !filter.contains(name.hashCode())) return true; - try { - boolean searchInLibraries = parameters.getSearchScope().isSearchInLibraries(); - long contributorStarted = System.currentTimeMillis(); - - if (contributor instanceof ChooseByNameContributorEx) { - ((ChooseByNameContributorEx)contributor).processElementsWithName(name, new Processor() { - @Override - public boolean process(NavigationItem item) { - canceled.checkCanceled(); - if (acceptItem(item)) items.add(item); - return true; - } - }, parameters); - - if (LOG.isDebugEnabled()) { - LOG.debug(System.currentTimeMillis() - contributorStarted + "," + contributor + ","); - } - } else { - NavigationItem[] itemsByName = contributor.getItemsByName(name, parameters.getLocalPatternName(), myProject, searchInLibraries); - for (NavigationItem item : itemsByName) { - canceled.checkCanceled(); - if (item == null) { - PluginId pluginId = PluginManager.getPluginByClassName(contributor.getClass().getName()); - if (pluginId != null) { - LOG.error(new PluginException("null item from contributor " + contributor + " for name " + name, pluginId)); - } - else { - LOG.error("null item from contributor " + contributor + " for name " + name); - } - continue; - } - - if (acceptItem(item)) { - items.add(item); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug(System.currentTimeMillis() - contributorStarted + "," + contributor + "," + itemsByName.length); - } - } - } - catch (ProcessCanceledException ex) { - // index corruption detected, ignore - } - catch (Exception ex) { - LOG.error(ex); - } + Processor processor = contributor -> { + if (myProject.isDisposed()) { return true; } + TIntHashSet filter = myContributorToItsSymbolsMap.get(contributor); + if (filter != null && !filter.contains(name.hashCode())) return true; + try { + boolean searchInLibraries = parameters.getSearchScope().isSearchInLibraries(); + long contributorStarted = System.currentTimeMillis(); + + if (contributor instanceof ChooseByNameContributorEx) { + ((ChooseByNameContributorEx)contributor).processElementsWithName(name, item -> { + canceled.checkCanceled(); + if (acceptItem(item)) items.add(item); + return true; + }, parameters); + + if (LOG.isDebugEnabled()) { + LOG.debug(System.currentTimeMillis() - contributorStarted + "," + contributor + ","); + } + } else { + NavigationItem[] itemsByName = contributor.getItemsByName(name, parameters.getLocalPatternName(), myProject, searchInLibraries); + for (NavigationItem item : itemsByName) { + canceled.checkCanceled(); + if (item == null) { + PluginId pluginId = PluginManager.getPluginByClassName(contributor.getClass().getName()); + if (pluginId != null) { + LOG.error(new PluginException("null item from contributor " + contributor + " for name " + name, pluginId)); + } + else { + LOG.error("null item from contributor " + contributor + " for name " + name); + } + continue; + } + + if (acceptItem(item)) { + items.add(item); + } + } + + if (LOG.isDebugEnabled()) { + LOG.debug(System.currentTimeMillis() - contributorStarted + "," + contributor + "," + itemsByName.length); + } + } + } + catch (ProcessCanceledException ex) { + // index corruption detected, ignore + } + catch (Exception ex) { + LOG.error(ex); + } + return true; }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(filterDumb(myContributors), canceled, true, processor)) { canceled.cancel(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java index 56488e842254..1f95ff3e2ff3 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java @@ -74,17 +74,14 @@ public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider indicator.checkCanceled(); started = System.currentTimeMillis(); final MinusculeMatcher matcher = buildPatternMatcher(matchingPattern, NameUtil.MatchingCaseSensitivity.NONE); - ((ChooseByNameModelEx)model).processNames(new Processor() { - @Override - public boolean process(String sequence) { - indicator.checkCanceled(); - MatchResult result = matches(base, pattern, matcher, sequence); - if (result != null) { - collect.consume(result); - return true; - } - return false; + ((ChooseByNameModelEx)model).processNames(sequence -> { + indicator.checkCanceled(); + MatchResult result = matches(base, pattern, matcher, sequence); + if (result != null) { + collect.consume(result); + return true; } + return false; }, everywhere); if (LOG.isDebugEnabled()) { LOG.debug("loaded + matched:"+ (System.currentTimeMillis() - started)+ "," + collect.getResult().size()); @@ -285,13 +282,9 @@ public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider @NotNull private static List> getPatternsAndMatchers(@NotNull String qualifierPattern, @NotNull final ChooseByNameBase base) { - return ContainerUtil.map2List(split(qualifierPattern, base), new Function>() { - @NotNull - @Override - public Pair fun(String s) { - String namePattern = addSearchAnywherePatternDecorationIfNeeded(base, getNamePattern(base, s)); - return Pair.create(namePattern, buildPatternMatcher(namePattern, NameUtil.MatchingCaseSensitivity.NONE)); - } + return ContainerUtil.map2List(split(qualifierPattern, base), s -> { + String namePattern = addSearchAnywherePatternDecorationIfNeeded(base, getNamePattern(base, s)); + return Pair.create(namePattern, buildPatternMatcher(namePattern, NameUtil.MatchingCaseSensitivity.NONE)); }); } @@ -302,12 +295,9 @@ public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider if (pattern == null) return Collections.emptyList(); final List filtered = new ArrayList(); - processNamesByPattern(base, names, pattern, ProgressIndicatorProvider.getGlobalProgressIndicator(), new Consumer() { - @Override - public void consume(MatchResult result) { - synchronized (filtered) { - filtered.add(result.elementName); - } + processNamesByPattern(base, names, pattern, ProgressIndicatorProvider.getGlobalProgressIndicator(), result -> { + synchronized (filtered) { + filtered.add(result.elementName); } }); synchronized (filtered) { @@ -321,16 +311,13 @@ public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider final ProgressIndicator indicator, @NotNull final Consumer consumer) { final MinusculeMatcher matcher = buildPatternMatcher(pattern, NameUtil.MatchingCaseSensitivity.NONE); - Processor processor = new Processor() { - @Override - public boolean process(String name) { - ProgressManager.checkCanceled(); - MatchResult result = matches(base, pattern, matcher, name); - if (result != null) { - consumer.consume(result); - } - return true; + Processor processor = name -> { + ProgressManager.checkCanceled(); + MatchResult result = matches(base, pattern, matcher, name); + if (result != null) { + consumer.consume(result); } + return true; }; if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Arrays.asList(names), indicator, false, true, processor)) { throw new ProcessCanceledException(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultFileNavigationContributor.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultFileNavigationContributor.java index 81a52499ede8..8d74c9fba450 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultFileNavigationContributor.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultFileNavigationContributor.java @@ -43,12 +43,9 @@ public class DefaultFileNavigationContributor implements ChooseByNameContributor if (FileBasedIndex.ourEnableTracingOfKeyHashToVirtualFileMapping) { final THashSet names = new THashSet(1000); IdFilter filter = IdFilter.getProjectIdFilter(project, includeNonProjectItems); - processNames(new Processor() { - @Override - public boolean process(String s) { - names.add(s); - return true; - } + processNames(s -> { + names.add(s); + return true; }, FindSymbolParameters.searchScopeFor(project, includeNonProjectItems), filter); if (IdFilter.LOG.isDebugEnabled()) { IdFilter.LOG.debug("All names retrieved2:" + names.size()); @@ -72,12 +69,7 @@ public class DefaultFileNavigationContributor implements ChooseByNameContributor @Override public void processNames(@NotNull final Processor processor, @NotNull GlobalSearchScope scope, IdFilter filter) { long started = System.currentTimeMillis(); - FileBasedIndex.getInstance().processAllKeys(FilenameIndex.NAME, new Processor() { - @Override - public boolean process(String s) { - return processor.process(s); - } - }, scope, filter); + FileBasedIndex.getInstance().processAllKeys(FilenameIndex.NAME, s -> processor.process(s), scope, filter); if (IdFilter.LOG.isDebugEnabled()) { IdFilter.LOG.debug("All names retrieved:" + (System.currentTimeMillis() - started)); } @@ -88,14 +80,11 @@ public class DefaultFileNavigationContributor implements ChooseByNameContributor @NotNull final Processor _processor, @NotNull FindSymbolParameters parameters) { final boolean globalSearch = parameters.getSearchScope().isSearchInLibraries(); - final Processor processor = new Processor() { - @Override - public boolean process(PsiFileSystemItem item) { - if (!globalSearch && ProjectUtil.isProjectOrWorkspaceFile(item.getVirtualFile())) { - return true; - } - return _processor.process(item); + final Processor processor = item -> { + if (!globalSearch && ProjectUtil.isProjectOrWorkspaceFile(item.getVirtualFile())) { + return true; } + return _processor.process(item); }; String completePattern = parameters.getCompletePattern(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionItemProvider.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionItemProvider.java index 5f99add8f480..b1d6b491f82e 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionItemProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionItemProvider.java @@ -65,12 +65,7 @@ public class GotoActionItemProvider implements ChooseByNameItemProvider { boolean everywhere, @NotNull ProgressIndicator cancelled, @NotNull final Processor consumer) { - return filterElements(pattern, everywhere, new Processor() { - @Override - public boolean process(MatchedValue value) { - return consumer.process(value); - } - }); + return filterElements(pattern, everywhere, value -> consumer.process(value)); } public boolean filterElements(String pattern, boolean everywhere, Processor consumer) { @@ -93,17 +88,14 @@ public class GotoActionItemProvider implements ChooseByNameItemProvider { AnAction action = myActionManager.getAction(actionId); wrappers.add(new ActionWrapper(action, myModel.myActionGroups.get(action), MatchMode.NAME, context)); } - return ContainerUtil.process(ContainerUtil.map(wrappers, new Function() { - @Override - public MatchedValue fun(@NotNull ActionWrapper w) { - return new MatchedValue(w, pattern) { - @Nullable - @Override - public String getValueText() { - return pattern; - } - }; - } + return ContainerUtil.process(ContainerUtil.map(wrappers, (Function)w -> { + return new MatchedValue(w, pattern) { + @Nullable + @Override + public String getValueText() { + return pattern; + } + }; }), consumer); } diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java index b97e4d80bb05..6d2333a941ea 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java @@ -235,13 +235,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C @Override public ListCellRenderer getListCellRenderer() { - return new GotoActionListCellRenderer(new Function() { - @NotNull - @Override - public String fun(@NotNull OptionDescription description) { - return getGroupName(description); - } - }); + return new GotoActionListCellRenderer(description -> getGroupName(description)); } protected String getActionId(@NotNull AnAction anAction) { diff --git a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectDialog.java b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectDialog.java index 6b14ab36d092..a705cd062f3a 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectDialog.java @@ -67,12 +67,7 @@ public abstract class AbstractNewProjectDialog extends DialogWrapper { } }.registerCustomShortcutSet(KeyEvent.VK_ESCAPE, 0, component); myList = panel.second; - UiNotifyConnector.doWhenFirstShown(myList, new Runnable() { - @Override - public void run() { - ScrollingUtil.ensureSelectionExists(myList); - } - }); + UiNotifyConnector.doWhenFirstShown(myList, () -> ScrollingUtil.ensureSelectionExists(myList)); return component; } @@ -108,11 +103,6 @@ public abstract class AbstractNewProjectDialog extends DialogWrapper { @Override public void show() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - AbstractNewProjectDialog.super.show(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> AbstractNewProjectDialog.super.show()); } } diff --git a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectStep.java b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectStep.java index c733709d9439..1385e8a01185 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectStep.java +++ b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/AbstractNewProjectStep.java @@ -160,12 +160,7 @@ public class AbstractNewProjectStep extends DefaultActionGroup implements DumbAw final Project project = ProjectManager.getInstance().getDefaultProject(); final DirectoryProjectGenerator generator = settings.getProjectGenerator(); doGenerateProject(project, settings.getProjectLocation(), generator, - new Function() { - @Override - public Object fun(VirtualFile file) { - return getProjectSettings(generator); - } - }); + file -> getProjectSettings(generator)); } @Nullable diff --git a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/ProjectSettingsStepBase.java b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/ProjectSettingsStepBase.java index d1cf97653056..07dae9aeff14 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/ProjectSettingsStepBase.java +++ b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/ProjectSettingsStepBase.java @@ -124,12 +124,8 @@ public class ProjectSettingsStepBase extends AbstractActionWithPanel implements if (dialog != null) { dialog.close(DialogWrapper.OK_EXIT_CODE); } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - myCallback.consume(ProjectSettingsStepBase.this); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> myCallback.consume(ProjectSettingsStepBase.this)); } } }; diff --git a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/WebProjectSettingsStepWrapper.java b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/WebProjectSettingsStepWrapper.java index 460507dde64a..9a27e95f67d4 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/projectWizard/WebProjectSettingsStepWrapper.java +++ b/platform/lang-impl/src/com/intellij/ide/util/projectWizard/WebProjectSettingsStepWrapper.java @@ -27,12 +27,7 @@ import java.util.List; public class WebProjectSettingsStepWrapper implements SettingsStep { private static final Function, LabeledComponent> PAIR_LABELED_COMPONENT_FUNCTION = - new Function, LabeledComponent>() { - @Override - public LabeledComponent fun(Pair pair) { - return LabeledComponent.create(pair.getSecond(), pair.getFirst()); - } - }; + pair -> LabeledComponent.create(pair.getSecond(), pair.getFirst()); private final List> myFields = ContainerUtil.newArrayList(); private final List myComponents = ContainerUtil.newArrayList(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/PackageSetChooserCombo.java b/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/PackageSetChooserCombo.java index bb56e82d51b4..f8284bc92055 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/PackageSetChooserCombo.java +++ b/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/PackageSetChooserCombo.java @@ -108,9 +108,7 @@ public class PackageSetChooserCombo extends ComponentWithBrowseButton() { - @Override public String fun(Object o) { return o == null ? "" : ((NamedScope)o).getName(); } - }); + ((JBComboBoxTableCellEditorComponent)component).setToString(o -> o == null ? "" : ((NamedScope)o).getName()); } rebuild(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/ScopeEditorPanel.java b/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/ScopeEditorPanel.java index 014bd39fa7ca..b513b9189257 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/ScopeEditorPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/ScopeEditorPanel.java @@ -394,12 +394,7 @@ public class ScopeEditorPanel { private JComponent createTreeToolbar() { final DefaultActionGroup group = new DefaultActionGroup(); - final Runnable update = new Runnable() { - @Override - public void run() { - rebuild(true); - } - }; + final Runnable update = () -> rebuild(true); if (ProjectViewDirectoryHelper.getInstance(myProject).supportsFlattenPackages()) { group.add(new FlattenPackagesAction(update)); } @@ -427,43 +422,32 @@ public class ScopeEditorPanel { private void rebuild(final boolean updateText, @Nullable final Runnable runnable, final boolean requestFocus, final int delayMillis){ myUpdateAlarm.cancelAllRequests(); - final Runnable request = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - if (updateText) { - final String text = myCurrentScope != null ? myCurrentScope.getText() : null; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - myIsInUpdate = true; - myPatternField.setText(text); - } - finally { - myIsInUpdate = false; - } - } - }); - } - - try { - if (!myProject.isDisposed()) { - updateTreeModel(requestFocus); - } - } - catch (ProcessCanceledException e) { - return; - } - if (runnable != null) { - runnable.run(); - } + final Runnable request = () -> ApplicationManager.getApplication().executeOnPooledThread(() -> { + if (updateText) { + final String text = myCurrentScope != null ? myCurrentScope.getText() : null; + SwingUtilities.invokeLater(() -> { + try { + myIsInUpdate = true; + myPatternField.setText(text); + } + finally { + myIsInUpdate = false; } }); } - }; + + try { + if (!myProject.isDisposed()) { + updateTreeModel(requestFocus); + } + } + catch (ProcessCanceledException e) { + return; + } + if (runnable != null) { + runnable.run(); + } + }); myUpdateAlarm.addRequest(request, delayMillis); } @@ -543,50 +527,41 @@ public class ScopeEditorPanel { PanelProgressIndicator progress = createProgressIndicator(requestFocus); progress.setBordersVisible(false); myCurrentProgress = progress; - Runnable updateModel = new Runnable() { - @Override - public void run() { - final ProcessCanceledException [] ex = new ProcessCanceledException[1]; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - try { - myTreeExpansionMonitor.freeze(); - final TreeModel model = PatternDialectProvider.getInstance(DependencyUISettings.getInstance().SCOPE_TYPE).createTreeModel(myProject, myTreeMarker); - ((PackageDependenciesNode)model.getRoot()).sortChildren(); - if (myErrorMessage == null) { - String message = IdeBundle.message("label.scope.contains.files", model.getMarkedFileCount(), model.getTotalFileCount()); - if (FilePatternPackageSet.SCOPE_FILE.equals(DependencyUISettings.getInstance().SCOPE_TYPE)) { - message = UIUtil.toHtml(message + "
    (Non-project files are not shown)"); - } - myMatchingCountLabel.setText(message); - myMatchingCountLabel.setForeground(new JLabel().getForeground()); - } - else { - showErrorMessage(); - } - - SwingUtilities.invokeLater(new Runnable(){ - @Override - public void run() { //not under progress - myPackageTree.setModel(model); - myTreeExpansionMonitor.restore(); - } - }); - } catch (ProcessCanceledException e) { - ex[0] = e; - } - finally { - myCurrentProgress = null; - //update label - setToComponent(myMatchingCountLabel, requestFocus); + Runnable updateModel = () -> { + final ProcessCanceledException [] ex = new ProcessCanceledException[1]; + ApplicationManager.getApplication().runReadAction(() -> { + if (myProject.isDisposed()) return; + try { + myTreeExpansionMonitor.freeze(); + final TreeModel model = PatternDialectProvider.getInstance(DependencyUISettings.getInstance().SCOPE_TYPE).createTreeModel(myProject, myTreeMarker); + ((PackageDependenciesNode)model.getRoot()).sortChildren(); + if (myErrorMessage == null) { + String message = IdeBundle.message("label.scope.contains.files", model.getMarkedFileCount(), model.getTotalFileCount()); + if (FilePatternPackageSet.SCOPE_FILE.equals(DependencyUISettings.getInstance().SCOPE_TYPE)) { + message = UIUtil.toHtml(message + "
    (Non-project files are not shown)"); } + myMatchingCountLabel.setText(message); + myMatchingCountLabel.setForeground(new JLabel().getForeground()); } - }); - if (ex[0] != null) { - throw ex[0]; + else { + showErrorMessage(); + } + + SwingUtilities.invokeLater(() -> { //not under progress + myPackageTree.setModel(model); + myTreeExpansionMonitor.restore(); + }); + } catch (ProcessCanceledException e) { + ex[0] = e; } + finally { + myCurrentProgress = null; + //update label + setToComponent(myMatchingCountLabel, requestFocus); + } + }); + if (ex[0] != null) { + throw ex[0]; } }; ProgressManager.getInstance().runProcess(updateModel, progress); @@ -625,12 +600,7 @@ public class ScopeEditorPanel { myMatchingCountPanel.revalidate(); myMatchingCountPanel.repaint(); if (requestFocus) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPatternField.getTextField().requestFocusInWindow(); - } - }); + SwingUtilities.invokeLater(() -> myPatternField.getTextField().requestFocusInWindow()); } } diff --git a/platform/lang-impl/src/com/intellij/internal/ComputeVirtualFileNameStatAction.java b/platform/lang-impl/src/com/intellij/internal/ComputeVirtualFileNameStatAction.java index 3f5ede84b483..194956d2da3a 100644 --- a/platform/lang-impl/src/com/intellij/internal/ComputeVirtualFileNameStatAction.java +++ b/platform/lang-impl/src/com/intellij/internal/ComputeVirtualFileNameStatAction.java @@ -62,12 +62,7 @@ public class ComputeVirtualFileNameStatAction extends AnAction implements DumbAw return true; } }); - Collections.sort(names, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return o2.second - o1.second; - } - }); + Collections.sort(names, (o1, o2) -> o2.second - o1.second); System.out.println("Most frequent names ("+names.size()+" total):"); int saveByIntern = 0; @@ -122,11 +117,8 @@ public class ComputeVirtualFileNameStatAction extends AnAction implements DumbAw final String candidate = cp.first; picked.add(candidate); System.out.println("Candidate: '"+candidate+"', save = "+cp.second); - Collections.sort(picked, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o2.length() - o1.length(); // longer first - } + Collections.sort(picked, (o1, o2) -> { + return o2.length() - o1.length(); // longer first }); saveSorted.clear(); @@ -145,25 +137,12 @@ public class ComputeVirtualFileNameStatAction extends AnAction implements DumbAw return true; } }); - Collections.sort(saveSorted, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return o2.second.compareTo(o1.second); - } - }); + Collections.sort(saveSorted, (o1, o2) -> o2.second.compareTo(o1.second)); } - System.out.println("Picked: "+ StringUtil.join(picked, new Function() { - @Override - public String fun(String s) { - return "\""+s+"\""; - } - }, ",")); - Collections.sort(picked, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o2.length() - o1.length(); // longer first - } + System.out.println("Picked: "+ StringUtil.join(picked, s -> "\"" + s + "\"", ",")); + Collections.sort(picked, (o1, o2) -> { + return o2.length() - o1.length(); // longer first }); int saved = 0; @@ -192,12 +171,7 @@ public class ComputeVirtualFileNameStatAction extends AnAction implements DumbAw return true; } }); - Collections.sort(prefs, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return o2.second.compareTo(o1.second); - } - }); + Collections.sort(prefs, (o1, o2) -> o2.second.compareTo(o1.second)); int i =0; for (Pair pref : prefs) { Integer count = pref.second; diff --git a/platform/lang-impl/src/com/intellij/internal/DumpDirectoryInfoAction.java b/platform/lang-impl/src/com/intellij/internal/DumpDirectoryInfoAction.java index 2f278bb97919..906091fed7d5 100644 --- a/platform/lang-impl/src/com/intellij/internal/DumpDirectoryInfoAction.java +++ b/platform/lang-impl/src/com/intellij/internal/DumpDirectoryInfoAction.java @@ -43,23 +43,20 @@ public class DumpDirectoryInfoAction extends AnAction { final DirectoryIndex index = DirectoryIndex.getInstance(project); if (project != null) { final VirtualFile root = e.getData(CommonDataKeys.VIRTUAL_FILE); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - final ContentIterator contentIterator = new ContentIterator() { - @Override - public boolean processFile(VirtualFile fileOrDir) { - LOG.info(fileOrDir.getPath()); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final ContentIterator contentIterator = new ContentIterator() { + @Override + public boolean processFile(VirtualFile fileOrDir) { + LOG.info(fileOrDir.getPath()); - LOG.info(index.getInfoForFile(fileOrDir).toString()); - return true; - } - }; - if (root != null) { - ProjectRootManager.getInstance(project).getFileIndex().iterateContentUnderDirectory(root, contentIterator); - } else { - ProjectRootManager.getInstance(project).getFileIndex().iterateContent(contentIterator); + LOG.info(index.getInfoForFile(fileOrDir).toString()); + return true; } + }; + if (root != null) { + ProjectRootManager.getInstance(project).getFileIndex().iterateContentUnderDirectory(root, contentIterator); + } else { + ProjectRootManager.getInstance(project).getFileIndex().iterateContent(contentIterator); } }, "Dumping directory index", true, project); } diff --git a/platform/lang-impl/src/com/intellij/internal/DumpLookupElementWeights.java b/platform/lang-impl/src/com/intellij/internal/DumpLookupElementWeights.java index 49e355c0a586..7a6eafccdade 100644 --- a/platform/lang-impl/src/com/intellij/internal/DumpLookupElementWeights.java +++ b/platform/lang-impl/src/com/intellij/internal/DumpLookupElementWeights.java @@ -71,16 +71,6 @@ public class DumpLookupElementWeights extends AnAction implements DumbAware { public static List getLookupElementWeights(LookupImpl lookup, boolean hideSingleValued) { final Map>> weights = lookup.getRelevanceObjects(lookup.getItems(), hideSingleValued); - return ContainerUtil.map(weights.entrySet(), new Function>>, String>() { - @Override - public String fun(Map.Entry>> entry) { - return entry.getKey().getLookupString() + "\t" + StringUtil.join(entry.getValue(), new Function, String>() { - @Override - public String fun(Pair pair) { - return pair.first + "=" + pair.second; - } - }, ", "); - } - }); + return ContainerUtil.map(weights.entrySet(), entry -> entry.getKey().getLookupString() + "\t" + StringUtil.join(entry.getValue(), pair -> pair.first + "=" + pair.second, ", ")); } } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/internal/ImageDuplicateResultsDialog.java b/platform/lang-impl/src/com/intellij/internal/ImageDuplicateResultsDialog.java index 752545d1c979..86d14c5c1206 100644 --- a/platform/lang-impl/src/com/intellij/internal/ImageDuplicateResultsDialog.java +++ b/platform/lang-impl/src/com/intellij/internal/ImageDuplicateResultsDialog.java @@ -140,46 +140,28 @@ public class ImageDuplicateResultsDialog extends DialogWrapper { }); final JBList list = new JBList(new ResourceModules().getModuleNames()); - final NotNullFunction modulesRenderer = new NotNullFunction() { - @NotNull - @Override - public JComponent fun(Object dom) { - return new JLabel(dom instanceof Module ? ((Module)dom).getName() : dom.toString(), PlatformIcons.SOURCE_FOLDERS_ICON, SwingConstants.LEFT); - } - }; + final NotNullFunction modulesRenderer = + dom -> new JLabel(dom instanceof Module ? ((Module)dom).getName() : dom.toString(), PlatformIcons.SOURCE_FOLDERS_ICON, SwingConstants.LEFT); list.installCellRenderer(modulesRenderer); final JPanel modulesPanel = ToolbarDecorator.createDecorator(list) .setAddAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { final Module[] all = ModuleManager.getInstance(myProject).getModules(); - Arrays.sort(all, new Comparator() { - @Override - public int compare(Module o1, Module o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Arrays.sort(all, (o1, o2) -> o1.getName().compareTo(o2.getName())); final JBList modules = new JBList(all); modules.installCellRenderer(modulesRenderer); JBPopupFactory.getInstance().createListPopupBuilder(modules) .setTitle("Add Resource Module") - .setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return ((Module)o).getName(); - } - }) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = modules.getSelectedValue(); - if (value instanceof Module && !myResourceModules.contains((Module)value)) { - myResourceModules.add((Module)value); - ((DefaultListModel)list.getModel()).addElement(((Module)value).getName()); - } - ((DefaultTreeModel)myTree.getModel()).reload(); - TreeUtil.expandAll(myTree); + .setFilteringEnabled(o -> ((Module)o).getName()) + .setItemChoosenCallback(() -> { + final Object value = modules.getSelectedValue(); + if (value instanceof Module && !myResourceModules.contains((Module)value)) { + myResourceModules.add((Module)value); + ((DefaultListModel)list.getModel()).addElement(((Module)value).getName()); } + ((DefaultTreeModel)myTree.getModel()).reload(); + TreeUtil.expandAll(myTree); }).createPopup().show(button.getPreferredPopupPoint()); } }) diff --git a/platform/lang-impl/src/com/intellij/internal/LoadAllContentsAction.java b/platform/lang-impl/src/com/intellij/internal/LoadAllContentsAction.java index 87629e2e638c..1530faecb949 100644 --- a/platform/lang-impl/src/com/intellij/internal/LoadAllContentsAction.java +++ b/platform/lang-impl/src/com/intellij/internal/LoadAllContentsAction.java @@ -62,29 +62,25 @@ public class LoadAllContentsAction extends AnAction implements DumbAware { count.set(0); totalSize.set(0); - ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ProjectRootManager.getInstance(project).getFileIndex().iterateContent(new ContentIterator() { - @Override - public boolean processFile(VirtualFile fileOrDir) { - if (fileOrDir.isDirectory() || fileOrDir.is(VFileProperty.SPECIAL)) { - return true; - } - try { - count.incrementAndGet(); - byte[] bytes = FileUtil.loadFileBytes(new File(fileOrDir.getPath())); - totalSize.addAndGet(bytes.length); - ProgressManager.getInstance().getProgressIndicator().setText(fileOrDir.getPresentableUrl()); - } - catch (IOException e1) { - LOG.error(e1); - } + ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously( + () -> ProjectRootManager.getInstance(project).getFileIndex().iterateContent(new ContentIterator() { + @Override + public boolean processFile(VirtualFile fileOrDir) { + if (fileOrDir.isDirectory() || fileOrDir.is(VFileProperty.SPECIAL)) { return true; } - }); - } - }, "Loading", false, project); + try { + count.incrementAndGet(); + byte[] bytes = FileUtil.loadFileBytes(new File(fileOrDir.getPath())); + totalSize.addAndGet(bytes.length); + ProgressManager.getInstance().getProgressIndicator().setText(fileOrDir.getPresentableUrl()); + } + catch (IOException e1) { + LOG.error(e1); + } + return true; + } + }), "Loading", false, project); long end = System.currentTimeMillis(); String message = "Finished loading content of " + count + " files. " + diff --git a/platform/lang-impl/src/com/intellij/internal/LoadAllVfsStoredContentsAction.java b/platform/lang-impl/src/com/intellij/internal/LoadAllVfsStoredContentsAction.java index 3918f5df6188..a00e9c345a8a 100644 --- a/platform/lang-impl/src/com/intellij/internal/LoadAllVfsStoredContentsAction.java +++ b/platform/lang-impl/src/com/intellij/internal/LoadAllVfsStoredContentsAction.java @@ -65,14 +65,11 @@ public class LoadAllVfsStoredContentsAction extends AnAction implements DumbAwar count.set(0); totalSize.set(0); - ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - PersistentFS vfs = (PersistentFS)application.getComponent(ManagingFS.class); - VirtualFile[] roots = vfs.getRoots(); - for (VirtualFile root : roots) { - iterateCached(root); - } + ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(() -> { + PersistentFS vfs = (PersistentFS)application.getComponent(ManagingFS.class); + VirtualFile[] roots = vfs.getRoots(); + for (VirtualFile root : roots) { + iterateCached(root); } }, "Loading", false, null); diff --git a/platform/lang-impl/src/com/intellij/internal/SelectionBasedPsiElementInternalAction.java b/platform/lang-impl/src/com/intellij/internal/SelectionBasedPsiElementInternalAction.java index f669e52c69d0..b82a0d8c0b97 100644 --- a/platform/lang-impl/src/com/intellij/internal/SelectionBasedPsiElementInternalAction.java +++ b/platform/lang-impl/src/com/intellij/internal/SelectionBasedPsiElementInternalAction.java @@ -51,12 +51,7 @@ public abstract class SelectionBasedPsiElementInternalAction() { - @Override - public String fun(@NotNull T expression) { - return expression.getText(); - } - } + expression -> expression.getText() ); } else if (expressions.size() == 1 && first != null) { @@ -68,12 +63,9 @@ public abstract class SelectionBasedPsiElementInternalAction { + final String errorHint = "Cannot find element of class " + myClass.getSimpleName() + " at selection/offset"; + HintManager.getInstance().showErrorHint(editor, errorHint); }); } @@ -82,20 +74,10 @@ public abstract class SelectionBasedPsiElementInternalAction HintManager.getInstance().showInformationHint(editor, informationHint)); } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - HintManager.getInstance().showErrorHint(editor, getErrorHint()); - } - }); + ApplicationManager.getApplication().invokeLater(() -> HintManager.getInstance().showErrorHint(editor, getErrorHint())); } } diff --git a/platform/lang-impl/src/com/intellij/internal/ShowImageDuplicatesAction.java b/platform/lang-impl/src/com/intellij/internal/ShowImageDuplicatesAction.java index 6f0bc72d5305..9cdb0c678eaa 100644 --- a/platform/lang-impl/src/com/intellij/internal/ShowImageDuplicatesAction.java +++ b/platform/lang-impl/src/com/intellij/internal/ShowImageDuplicatesAction.java @@ -40,12 +40,7 @@ public class ShowImageDuplicatesAction extends AnAction { public void actionPerformed(AnActionEvent e) { final Project project = getEventProject(e); assert project != null; - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - collectAndShowDuplicates(project); - } - }, "Gathering images", true, project); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> collectAndShowDuplicates(project), "Gathering images", true, project); } private static void collectAndShowDuplicates(final Project project) { @@ -120,12 +115,7 @@ public class ShowImageDuplicatesAction extends AnAction { } } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - new ImageDuplicateResultsDialog(project, images, realDuplicates).show(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> new ImageDuplicateResultsDialog(project, images, realDuplicates).show()); } diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerDialog.java b/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerDialog.java index 93f16d74899f..05e931e78dc6 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerDialog.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerDialog.java @@ -232,12 +232,9 @@ public class PsiViewerDialog extends DialogWrapper implements DataProvider, Disp doOKAction(); if (!initOffset.isNull()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myEditor.getCaretModel().moveToOffset(initOffset.get()); - myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); - } + ApplicationManager.getApplication().invokeLater(() -> { + myEditor.getCaretModel().moveToOffset(initOffset.get()); + myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); }); } } @@ -912,13 +909,10 @@ public class PsiViewerDialog extends DialogWrapper implements DataProvider, Disp if (myBlockTreeBuilder == null) return; if (currentBlockNode != null) { myIgnoreBlockTreeSelectionMarker++; - myBlockTreeBuilder.select(currentBlockNode, new Runnable() { - @Override - public void run() { - // hope this is always called! - assert myIgnoreBlockTreeSelectionMarker > 0; - myIgnoreBlockTreeSelectionMarker--; - } + myBlockTreeBuilder.select(currentBlockNode, () -> { + // hope this is always called! + assert myIgnoreBlockTreeSelectionMarker > 0; + myIgnoreBlockTreeSelectionMarker--; }); } else { diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java index 5380bff0d4ad..e9b64238dede 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java @@ -71,57 +71,54 @@ public class ViewerTreeStructure extends AbstractTreeStructure { } final Object[][] children = new Object[1][]; children[0] = ArrayUtil.EMPTY_OBJECT_ARRAY; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final Object[] result; - if (myShowTreeNodes) { - final ArrayList list = new ArrayList(); - ASTNode root = element instanceof PsiElement? SourceTreeToPsiMap.psiElementToTree((PsiElement)element) : - element instanceof ASTNode? (ASTNode)element : null; - if (element instanceof Inject) { - root = SourceTreeToPsiMap.psiElementToTree(((Inject)element).getPsi()); - } + ApplicationManager.getApplication().runReadAction(() -> { + final Object[] result; + if (myShowTreeNodes) { + final ArrayList list = new ArrayList(); + ASTNode root = element instanceof PsiElement? SourceTreeToPsiMap.psiElementToTree((PsiElement)element) : + element instanceof ASTNode? (ASTNode)element : null; + if (element instanceof Inject) { + root = SourceTreeToPsiMap.psiElementToTree(((Inject)element).getPsi()); + } - if (root != null) { - ASTNode child = root.getFirstChildNode(); - while (child != null) { - if (myShowWhiteSpaces || child.getElementType() != TokenType.WHITE_SPACE) { - final PsiElement childElement = child.getPsi(); - list.add(childElement == null ? child : childElement); - } - child = child.getTreeNext(); - } - final PsiElement psi = root.getPsi(); - if (psi instanceof PsiLanguageInjectionHost) { - InjectedLanguageUtil.enumerate(psi, new PsiLanguageInjectionHost.InjectedPsiVisitor() { - @Override - public void visit(@NotNull PsiFile injectedPsi, @NotNull List places) { - list.add(new Inject(psi, injectedPsi)); - } - }); + if (root != null) { + ASTNode child = root.getFirstChildNode(); + while (child != null) { + if (myShowWhiteSpaces || child.getElementType() != TokenType.WHITE_SPACE) { + final PsiElement childElement = child.getPsi(); + list.add(childElement == null ? child : childElement); } + child = child.getTreeNext(); } - result = ArrayUtil.toObjectArray(list); + final PsiElement psi = root.getPsi(); + if (psi instanceof PsiLanguageInjectionHost) { + InjectedLanguageUtil.enumerate(psi, new PsiLanguageInjectionHost.InjectedPsiVisitor() { + @Override + public void visit(@NotNull PsiFile injectedPsi, @NotNull List places) { + list.add(new Inject(psi, injectedPsi)); + } + }); + } + } + result = ArrayUtil.toObjectArray(list); + } + else { + final PsiElement[] elementChildren = ((PsiElement)element).getChildren(); + if (!myShowWhiteSpaces) { + final List childrenList = new ArrayList(elementChildren.length); + for (PsiElement psiElement : elementChildren) { + if (!myShowWhiteSpaces && psiElement instanceof PsiWhiteSpace) { + continue; + } + childrenList.add(psiElement); + } + result = PsiUtilCore.toPsiElementArray(childrenList); } else { - final PsiElement[] elementChildren = ((PsiElement)element).getChildren(); - if (!myShowWhiteSpaces) { - final List childrenList = new ArrayList(elementChildren.length); - for (PsiElement psiElement : elementChildren) { - if (!myShowWhiteSpaces && psiElement instanceof PsiWhiteSpace) { - continue; - } - childrenList.add(psiElement); - } - result = PsiUtilCore.toPsiElementArray(childrenList); - } - else { - result = elementChildren; - } + result = elementChildren; } - children[0] = result; } + children[0] = result; }); return children[0]; } diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/formattingblocks/BlockTreeNode.java b/platform/lang-impl/src/com/intellij/internal/psiView/formattingblocks/BlockTreeNode.java index 87b0483ec979..bf7aa2471ee7 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/formattingblocks/BlockTreeNode.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/formattingblocks/BlockTreeNode.java @@ -42,11 +42,8 @@ public class BlockTreeNode extends SimpleNode { @Override public BlockTreeNode[] getChildren() { - return ContainerUtil.map2Array(myBlock.getSubBlocks(), BlockTreeNode.class, new Function() { - @Override - public BlockTreeNode fun(Block block) { - return new BlockTreeNode(block, BlockTreeNode.this); - } + return ContainerUtil.map2Array(myBlock.getSubBlocks(), BlockTreeNode.class, block -> { + return new BlockTreeNode(block, BlockTreeNode.this); }); } diff --git a/platform/lang-impl/src/com/intellij/lang/customFolding/CustomFoldingRegionsPopup.java b/platform/lang-impl/src/com/intellij/lang/customFolding/CustomFoldingRegionsPopup.java index 203179709dae..2d3770b553d0 100644 --- a/platform/lang-impl/src/com/intellij/lang/customFolding/CustomFoldingRegionsPopup.java +++ b/platform/lang-impl/src/com/intellij/lang/customFolding/CustomFoldingRegionsPopup.java @@ -54,14 +54,11 @@ public class CustomFoldingRegionsPopup { .setTitle(IdeBundle.message("goto.custom.region.command")) .setResizable(false) .setMovable(false) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - PsiElement navigationElement = getNavigationElement(); - if (navigationElement != null) { - navigateTo(editor, navigationElement); - IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); - } + .setItemChoosenCallback(() -> { + PsiElement navigationElement = getNavigationElement(); + if (navigationElement != null) { + navigateTo(editor, navigationElement); + IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); } }).createPopup(); } @@ -110,13 +107,10 @@ public class CustomFoldingRegionsPopup { private static Collection orderByPosition(Collection descriptors) { List sorted = new ArrayList(descriptors.size()); sorted.addAll(descriptors); - Collections.sort(sorted, new Comparator() { - @Override - public int compare(FoldingDescriptor descriptor1, FoldingDescriptor descriptor2) { - int pos1 = descriptor1.getElement().getTextRange().getStartOffset(); - int pos2 = descriptor2.getElement().getTextRange().getStartOffset(); - return pos1 - pos2; - } + Collections.sort(sorted, (descriptor1, descriptor2) -> { + int pos1 = descriptor1.getElement().getTextRange().getStartOffset(); + int pos2 = descriptor2.getElement().getTextRange().getStartOffset(); + return pos1 - pos2; }); return sorted; } diff --git a/platform/lang-impl/src/com/intellij/lang/customFolding/GotoCustomRegionAction.java b/platform/lang-impl/src/com/intellij/lang/customFolding/GotoCustomRegionAction.java index 333aa238940b..97c316041539 100644 --- a/platform/lang-impl/src/com/intellij/lang/customFolding/GotoCustomRegionAction.java +++ b/platform/lang-impl/src/com/intellij/lang/customFolding/GotoCustomRegionAction.java @@ -58,17 +58,14 @@ public class GotoCustomRegionAction extends AnAction implements DumbAware, Popup CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand( project, - new Runnable() { - @Override - public void run() { - Collection foldingDescriptors = getCustomFoldingDescriptors(editor, project); - if (foldingDescriptors.size() > 0) { - CustomFoldingRegionsPopup regionsPopup = new CustomFoldingRegionsPopup(foldingDescriptors, editor, project); - regionsPopup.show(); - } - else { - notifyCustomRegionsUnavailable(editor, project); - } + () -> { + Collection foldingDescriptors = getCustomFoldingDescriptors(editor, project); + if (foldingDescriptors.size() > 0) { + CustomFoldingRegionsPopup regionsPopup = new CustomFoldingRegionsPopup(foldingDescriptors, editor, project); + regionsPopup.show(); + } + else { + notifyCustomRegionsUnavailable(editor, project); } }, IdeBundle.message("goto.custom.region.command"), diff --git a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java index 936f2cc87cc6..5839bf4e84a9 100644 --- a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java +++ b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java @@ -76,11 +76,8 @@ public abstract class AbstractGithubTagDownloadedProjectGenerator extends WebPro catch (GeneratorException e) { showErrorMessage(project, e.getMessage()); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - baseDir.refresh(true, true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + baseDir.refresh(true, true); }); } diff --git a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubDownloadUtil.java b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubDownloadUtil.java index a9017a888f83..4fe7f03e7983 100644 --- a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubDownloadUtil.java +++ b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubDownloadUtil.java @@ -78,21 +78,15 @@ public class GithubDownloadUtil { project, progressTitle, "Downloading zip archive" + DownloadUtil.CONTENT_LENGTH_TEMPLATE + " ...", - new Callable() { - @Override - public File call() throws Exception { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - downloadAtomically(progress, url, outputFile, userName, repositoryName); - return outputFile; - } - }, new Producer() { - @Override - public Boolean produce() { - if (!retryOnError) { - return false; - } - return IOExceptionDialog.showErrorDialog("Download Error", "Can not download '" + url + "'"); + () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + downloadAtomically(progress, url, outputFile, userName, repositoryName); + return outputFile; + }, () -> { + if (!retryOnError) { + return false; } + return IOExceptionDialog.showErrorDialog("Download Error", "Can not download '" + url + "'"); } ); File out = outcome.get(); diff --git a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubProjectGeneratorPeer.java b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubProjectGeneratorPeer.java index f8d5957c2bd1..540b155b0cce 100644 --- a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubProjectGeneratorPeer.java +++ b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubProjectGeneratorPeer.java @@ -160,13 +160,10 @@ public class GithubProjectGeneratorPeer implements WebProjectGenerator.Generator @NotNull private static List createSortedTagList(@NotNull Collection tags) { List sortedTags = ContainerUtil.newArrayList(tags); - Collections.sort(sortedTags, new Comparator() { - @Override - public int compare(GithubTagInfo tag1, GithubTagInfo tag2) { - GithubTagInfo.Version v1 = tag1.getVersion(); - GithubTagInfo.Version v2 = tag2.getVersion(); - return v2.compareTo(v1); - } + Collections.sort(sortedTags, (tag1, tag2) -> { + GithubTagInfo.Version v1 = tag1.getVersion(); + GithubTagInfo.Version v2 = tag2.getVersion(); + return v2.compareTo(v1); }); for (GithubTagInfo tag : sortedTags) { tag.setRecentTag(false); diff --git a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubTagListProvider.java b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubTagListProvider.java index 3b68eeaacdaf..cceff485c1c1 100644 --- a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubTagListProvider.java +++ b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/GithubTagListProvider.java @@ -58,43 +58,35 @@ public class GithubTagListProvider { } private Runnable createUpdateTagListAction(@NotNull final GithubProjectGeneratorPeer peer) { - return new Runnable() { - @Override - public void run() { - if (ApplicationManager.getApplication().isUnitTestMode()) { - peer.onTagsUpdated(Collections.emptySet()); + return () -> { + if (ApplicationManager.getApplication().isUnitTestMode()) { + peer.onTagsUpdated(Collections.emptySet()); + return; + } + final String[] urls = formatTagListDownloadUrls(); + String firstErrorMessage = null; + for (String url : urls) { + String errorMessage; + try { + final ImmutableSet tags = fetchGithubTagsByUrl(url); + LOG.info(getGeneratorName() + "Cache has been successfully updated"); + UIUtil.invokeLaterIfNeeded(() -> peer.onTagsUpdated(tags)); return; } - final String[] urls = formatTagListDownloadUrls(); - String firstErrorMessage = null; - for (String url : urls) { - String errorMessage; - try { - final ImmutableSet tags = fetchGithubTagsByUrl(url); - LOG.info(getGeneratorName() + "Cache has been successfully updated"); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - peer.onTagsUpdated(tags); - } - }); - return; - } - catch (IOException e) { - errorMessage = "Can not fetch tags from " + url; - LOG.warn(getGeneratorName() + errorMessage, e); - } - catch (GeneratorException e) { - errorMessage = "Malformed JSON received from " + url; - LOG.warn(getGeneratorName() + errorMessage, e); - } - if (firstErrorMessage == null) { - firstErrorMessage = errorMessage; - } + catch (IOException e) { + errorMessage = "Can not fetch tags from " + url; + LOG.warn(getGeneratorName() + errorMessage, e); } - if (firstErrorMessage != null) { - peer.onTagsUpdateError(firstErrorMessage); + catch (GeneratorException e) { + errorMessage = "Malformed JSON received from " + url; + LOG.warn(getGeneratorName() + errorMessage, e); } + if (firstErrorMessage == null) { + firstErrorMessage = errorMessage; + } + } + if (firstErrorMessage != null) { + peer.onTagsUpdateError(firstErrorMessage); } }; } diff --git a/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java b/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java index 05e7cf8e8b09..f8c44ec37101 100644 --- a/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java +++ b/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java @@ -1149,29 +1149,26 @@ public class GeneratedParserUtilBase { final LinkedList> siblingList = new LinkedList>(); PsiBuilder.Marker marker = null; - final Runnable checkSiblingsRunnable = new Runnable() { - @Override - public void run() { - main: - while (!siblingList.isEmpty()) { - final Pair parenPair = parenList.peek(); - final int rating = siblingList.getFirst().second; - int count = 0; - for (Pair pair : siblingList) { - if (pair.second != rating || parenPair != null && pair.first == parenPair.second) break main; - if (++count >= MAX_CHILDREN_IN_TREE) { - PsiBuilder.Marker parentMarker = pair.first.precede(); - parentMarker.setCustomEdgeTokenBinders(WhitespacesBinders.GREEDY_LEFT_BINDER, null); - while (count-- > 0) { - siblingList.removeFirst(); - } - parentMarker.done(chunkType); - siblingList.addFirst(Pair.create(parentMarker, rating + 1)); - continue main; + final Runnable checkSiblingsRunnable = () -> { + main: + while (!siblingList.isEmpty()) { + final Pair parenPair = parenList.peek(); + final int rating = siblingList.getFirst().second; + int count = 0; + for (Pair pair : siblingList) { + if (pair.second != rating || parenPair != null && pair.first == parenPair.second) break main; + if (++count >= MAX_CHILDREN_IN_TREE) { + PsiBuilder.Marker parentMarker = pair.first.precede(); + parentMarker.setCustomEdgeTokenBinders(WhitespacesBinders.GREEDY_LEFT_BINDER, null); + while (count-- > 0) { + siblingList.removeFirst(); } + parentMarker.done(chunkType); + siblingList.addFirst(Pair.create(parentMarker, rating + 1)); + continue main; } - break; } + break; } }; boolean checkParens = state.braces != null && checkBraces; diff --git a/platform/lang-impl/src/com/intellij/moduleDependencies/DependenciesAnalyzeManager.java b/platform/lang-impl/src/com/intellij/moduleDependencies/DependenciesAnalyzeManager.java index 4bf336b33f64..b74fa78bbfbe 100644 --- a/platform/lang-impl/src/com/intellij/moduleDependencies/DependenciesAnalyzeManager.java +++ b/platform/lang-impl/src/com/intellij/moduleDependencies/DependenciesAnalyzeManager.java @@ -46,15 +46,12 @@ public class DependenciesAnalyzeManager implements PersistentStateComponent { + ToolWindowManager manager = ToolWindowManager.getInstance(myProject); + ToolWindow toolWindow = manager.registerToolWindow(ToolWindowId.MODULES_DEPENDENCIES, true, ToolWindowAnchor.RIGHT, project); + myContentManager = toolWindow.getContentManager(); + toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowModuleDependencies); + new ContentManagerWatcher(toolWindow, myContentManager); }); } diff --git a/platform/lang-impl/src/com/intellij/moduleDependencies/ModulesDependenciesPanel.java b/platform/lang-impl/src/com/intellij/moduleDependencies/ModulesDependenciesPanel.java index e93a527a38af..88f80da4c97d 100644 --- a/platform/lang-impl/src/com/intellij/moduleDependencies/ModulesDependenciesPanel.java +++ b/platform/lang-impl/src/com/intellij/moduleDependencies/ModulesDependenciesPanel.java @@ -72,13 +72,10 @@ import java.util.List; public class ModulesDependenciesPanel extends JPanel implements Disposable { private static final String HELP_ID = "module.dependencies.tool.window"; - private static final Comparator NODE_COMPARATOR = new Comparator() { - @Override - public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) { - if (!(o1.getUserObject() instanceof MyUserObject)) return 1; - if (!(o2.getUserObject() instanceof MyUserObject)) return -1; - return (o1.getUserObject().toString().compareToIgnoreCase(o2.getUserObject().toString())); - } + private static final Comparator NODE_COMPARATOR = (o1, o2) -> { + if (!(o1.getUserObject() instanceof MyUserObject)) return 1; + if (!(o2.getUserObject() instanceof MyUserObject)) return -1; + return (o1.getUserObject().toString().compareToIgnoreCase(o2.getUserObject().toString())); }; private static final ColoredTreeCellRenderer NODE_RENDERER = new ColoredTreeCellRenderer() { @@ -212,12 +209,9 @@ public class ModulesDependenciesPanel extends JPanel implements Disposable { public void valueChanged(TreeSelectionEvent e) { TreePath selectionPath = myLeftTree.getSelectionPath(); if (selectionPath != null) { - myPathField.setText(StringUtil.join(selectionPath.getPath(), new Function() { - @Override - public String fun(Object o) { - Object userObject = ((DefaultMutableTreeNode)o).getUserObject(); - return userObject instanceof MyUserObject ? ((MyUserObject)userObject).myModule.getName() : ""; - } + myPathField.setText(StringUtil.join(selectionPath.getPath(), o -> { + Object userObject = ((DefaultMutableTreeNode)o).getUserObject(); + return userObject instanceof MyUserObject ? ((MyUserObject)userObject).myModule.getName() : ""; }, " : ")); DefaultMutableTreeNode selection = (DefaultMutableTreeNode)selectionPath.getLastPathComponent(); @@ -336,18 +330,15 @@ public class ModulesDependenciesPanel extends JPanel implements Disposable { final DefaultMutableTreeNode root = (DefaultMutableTreeNode)myLeftTree.getModel().getRoot(); root.removeAllChildren(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - for (Module module : myModules) { - if (module.isDisposed()) continue; - ProgressManager.progress(AnalysisScopeBundle.message("update.module.tree.progress.text", module.getName())); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + for (Module module : myModules) { + if (module.isDisposed()) continue; + ProgressManager.progress(AnalysisScopeBundle.message("update.module.tree.progress.text", module.getName())); - DefaultMutableTreeNode moduleNode = new DefaultMutableTreeNode(new MyUserObject(isInCycle(module), module)); - root.add(moduleNode); - for (Module dependency : getModuleDependencies(module)) { - moduleNode.add(new DefaultMutableTreeNode(new MyUserObject(isInCycle(dependency), dependency))); - } + DefaultMutableTreeNode moduleNode = new DefaultMutableTreeNode(new MyUserObject(isInCycle(module), module)); + root.add(moduleNode); + for (Module dependency : getModuleDependencies(module)) { + moduleNode.add(new DefaultMutableTreeNode(new MyUserObject(isInCycle(dependency), dependency))); } } }, AnalysisScopeBundle.message("update.module.tree.progress.title"), true, myProject); diff --git a/platform/lang-impl/src/com/intellij/openapi/file/exclude/EnforcedPlainTextFileTypeManager.java b/platform/lang-impl/src/com/intellij/openapi/file/exclude/EnforcedPlainTextFileTypeManager.java index 7fd07d2e9d0c..fb58dfa56422 100644 --- a/platform/lang-impl/src/com/intellij/openapi/file/exclude/EnforcedPlainTextFileTypeManager.java +++ b/platform/lang-impl/src/com/intellij/openapi/file/exclude/EnforcedPlainTextFileTypeManager.java @@ -88,22 +88,19 @@ public class EnforcedPlainTextFileTypeManager implements ProjectManagerListener } private void setPlainTextStatus(@NotNull final Project project, final boolean isAdded, @NotNull final VirtualFile... files) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager = ProjectPlainTextFileTypeManager.getInstance(project); - for (VirtualFile file : files) { - if (projectPlainTextFileTypeManager.hasProjectContaining(file)) { - ensureProjectFileSetAdded(project, projectPlainTextFileTypeManager); - if (isAdded ? - projectPlainTextFileTypeManager.addFile(file) : - projectPlainTextFileTypeManager.removeFile(file)) { - FileBasedIndex.getInstance().requestReindex(file); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager = ProjectPlainTextFileTypeManager.getInstance(project); + for (VirtualFile file : files) { + if (projectPlainTextFileTypeManager.hasProjectContaining(file)) { + ensureProjectFileSetAdded(project, projectPlainTextFileTypeManager); + if (isAdded ? + projectPlainTextFileTypeManager.addFile(file) : + projectPlainTextFileTypeManager.removeFile(file)) { + FileBasedIndex.getInstance().requestReindex(file); } } - FileContentUtilCore.reparseFiles(files); } + FileContentUtilCore.reparseFiles(files); }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/file/exclude/PersistentFileSetManager.java b/platform/lang-impl/src/com/intellij/openapi/file/exclude/PersistentFileSetManager.java index 93ccdb77813b..050c9b0c81ff 100644 --- a/platform/lang-impl/src/com/intellij/openapi/file/exclude/PersistentFileSetManager.java +++ b/platform/lang-impl/src/com/intellij/openapi/file/exclude/PersistentFileSetManager.java @@ -61,12 +61,7 @@ class PersistentFileSetManager implements PersistentStateComponent { private Collection getSortedFiles() { List sortedFiles = new ArrayList(); sortedFiles.addAll(myFiles); - Collections.sort(sortedFiles, new Comparator() { - @Override - public int compare(final VirtualFile file1, final VirtualFile file2) { - return file1.getPath().toLowerCase().compareTo(file2.getPath().toLowerCase()); - } - }); + Collections.sort(sortedFiles, (file1, file2) -> file1.getPath().toLowerCase().compareTo(file2.getPath().toLowerCase())); return sortedFiles; } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileChooser/actions/GotoModuleDirectory.java b/platform/lang-impl/src/com/intellij/openapi/fileChooser/actions/GotoModuleDirectory.java index d99c5dfc66fe..104eab43757f 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileChooser/actions/GotoModuleDirectory.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileChooser/actions/GotoModuleDirectory.java @@ -29,11 +29,8 @@ public final class GotoModuleDirectory extends FileChooserAction { protected void actionPerformed(final FileSystemTree fileSystemTree, final AnActionEvent e) { final VirtualFile moduleDir = getModuleDir(e); if (moduleDir != null) { - fileSystemTree.select(moduleDir, new Runnable() { - @Override - public void run() { - fileSystemTree.expand(moduleDir, null); - } + fileSystemTree.select(moduleDir, () -> { + fileSystemTree.expand(moduleDir, null); }); } } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java index 783795f00540..26e5e7a4093a 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java @@ -80,12 +80,7 @@ final class TestEditorManagerImpl extends FileEditorManagerEx implements Disposa final boolean focusEditor, boolean searchForSplitter) { final Ref> result = new Ref>(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - result.set(openFileImpl3(file, focusEditor)); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myProject, () -> result.set(openFileImpl3(file, focusEditor)), "", null); return result.get(); } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java index 8deb3028d709..b77eda4ecd89 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java @@ -79,13 +79,10 @@ class JumpFromRemoteFileToLocalAction extends AnAction { new PopupChooserBuilder(list) .setTitle("Select Target File") .setMovable(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - //noinspection deprecation - for (Object value : list.getSelectedValues()) { - navigateToFile(myProject, (VirtualFile)value); - } + .setItemChoosenCallback(() -> { + //noinspection deprecation + for (Object value : list.getSelectedValues()) { + navigateToFile(myProject, (VirtualFile)value); } }).createPopup().showUnderneathOf(e.getInputEvent().getComponent()); } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java index f0032f4e343c..a61fe9ae91fc 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/PsiAwareTextEditorProvider.java @@ -93,12 +93,9 @@ public class PsiAwareTextEditorProvider extends TextEditorProvider implements As if (child != null) { if (document == null) { final Element detachedStateCopy = child.clone(); - state.setDelayedFoldState(new Producer() { - @Override - public CodeFoldingState produce() { - Document document = FileDocumentManager.getInstance().getCachedDocument(file); - return document == null ? null : CodeFoldingManager.getInstance(project).readFoldingState(detachedStateCopy, document); - } + state.setDelayedFoldState(() -> { + Document document1 = FileDocumentManager.getInstance().getCachedDocument(file); + return document1 == null ? null : CodeFoldingManager.getInstance(project).readFoldingState(detachedStateCopy, document1); }); } else { diff --git a/platform/lang-impl/src/com/intellij/openapi/fileTypes/FileTypeUsagesCollector.java b/platform/lang-impl/src/com/intellij/openapi/fileTypes/FileTypeUsagesCollector.java index 038bb5f143c8..5f5f38e407c3 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileTypes/FileTypeUsagesCollector.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileTypes/FileTypeUsagesCollector.java @@ -63,33 +63,26 @@ public class FileTypeUsagesCollector extends AbstractApplicationUsagesCollector throw new CollectUsagesException("Project is disposed"); } final String ideaDirPath = getIdeaDirPath(project); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - FileBasedIndex.getInstance().processValues( - FileTypeIndex.NAME, - fileType, - null, - new FileBasedIndex.ValueProcessor() { - @Override - public boolean process(VirtualFile file, Void value) { - //skip files from .idea directory otherwise 99% of projects would have XML and PLAIN_TEXT file types - if (ideaDirPath == null || FileUtil.isAncestorThreeState(ideaDirPath, file.getPath(), true) == ThreeState.NO) { - usedFileTypes.add(fileType); - return false; - } - return true; + ApplicationManager.getApplication().runReadAction(() -> { + FileBasedIndex.getInstance().processValues( + FileTypeIndex.NAME, + fileType, + null, + new FileBasedIndex.ValueProcessor() { + @Override + public boolean process(VirtualFile file, Void value) { + //skip files from .idea directory otherwise 99% of projects would have XML and PLAIN_TEXT file types + if (ideaDirPath == null || FileUtil.isAncestorThreeState(ideaDirPath, file.getPath(), true) == ThreeState.NO) { + usedFileTypes.add(fileType); + return false; } - }, GlobalSearchScope.projectScope(project)); - } + return true; + } + }, GlobalSearchScope.projectScope(project)); }); } - return ContainerUtil.map2Set(usedFileTypes, new NotNullFunction() { - @NotNull - @Override - public UsageDescriptor fun(FileType fileType) { - return new UsageDescriptor(fileType.getName(), 1); - } + return ContainerUtil.map2Set(usedFileTypes, (NotNullFunction)fileType -> { + return new UsageDescriptor(fileType.getName(), 1); }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeConfigurable.java b/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeConfigurable.java index 03edfea88c7c..ccf006c05378 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeConfigurable.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeConfigurable.java @@ -115,19 +115,16 @@ public class FileTypeConfigurable extends BaseConfigurable implements Searchable } myOriginalToEditedMap.clear(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (!myManager.isIgnoredFilesListEqualToCurrent(myFileTypePanel.myIgnoreFilesField.getText())) { - myManager.setIgnoredFilesList(myFileTypePanel.myIgnoreFilesField.getText()); - } - myManager.setPatternsTable(myTempFileTypes, myTempPatternsTable); - for (FileNameMatcher matcher : myReassigned.keySet()) { - myManager.getRemovedMappings().put(matcher, Pair.create(myReassigned.get(matcher), true)); - } - - TemplateDataLanguagePatterns.getInstance().setAssocTable(myTempTemplateDataLanguages); + ApplicationManager.getApplication().runWriteAction(() -> { + if (!myManager.isIgnoredFilesListEqualToCurrent(myFileTypePanel.myIgnoreFilesField.getText())) { + myManager.setIgnoredFilesList(myFileTypePanel.myIgnoreFilesField.getText()); } + myManager.setPatternsTable(myTempFileTypes, myTempPatternsTable); + for (FileNameMatcher matcher : myReassigned.keySet()) { + myManager.getRemovedMappings().put(matcher, Pair.create(myReassigned.get(matcher), true)); + } + + TemplateDataLanguagePatterns.getInstance().setAssocTable(myTempTemplateDataLanguages); }); } @@ -444,24 +441,18 @@ public class FileTypeConfigurable extends BaseConfigurable implements Searchable } private void initConvertors() { - final PairConvertor simpleConvertor = new PairConvertor() { - @Override - public Boolean convert(Object element, String s) { - String value = element.toString(); - if (element instanceof FileType) { - value = ((FileType)element).getDescription(); - } - return getComparator().matchingFragments(s, value) != null; + final PairConvertor simpleConvertor = (element, s) -> { + String value = element.toString(); + if (element instanceof FileType) { + value = ((FileType)element).getDescription(); } + return getComparator().matchingFragments(s, value) != null; }; - final PairConvertor byExtensionsConvertor = new PairConvertor() { - @Override - public Boolean convert(Object element, String s) { - if (element instanceof FileType && myCurrentType != null) { - return myCurrentType.equals(element); - } - return false; + final PairConvertor byExtensionsConvertor = (element, s) -> { + if (element instanceof FileType && myCurrentType != null) { + return myCurrentType.equals(element); } + return false; }; myOrderedConvertors.add(simpleConvertor); myOrderedConvertors.add(byExtensionsConvertor); diff --git a/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypePatternDialog.java b/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypePatternDialog.java index 9a7b2b6d59bd..fc5f97ae3094 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypePatternDialog.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileTypes/impl/FileTypePatternDialog.java @@ -43,12 +43,7 @@ public class FileTypePatternDialog { final DefaultComboBoxModel model = (DefaultComboBoxModel) myLanguageCombo.getModel(); model.addElement(null); final List languages = TemplateDataLanguageMappings.getTemplateableLanguages(); - Collections.sort(languages, new Comparator() { - @Override - public int compare(final Language o1, final Language o2) { - return o1.getID().compareTo(o2.getID()); - } - }); + Collections.sort(languages, (o1, o2) -> o1.getID().compareTo(o2.getID())); for (Language language : languages) { model.addElement(language); } diff --git a/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java b/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java index 694a45e34c25..aa70f47b79b3 100644 --- a/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java @@ -84,16 +84,13 @@ public class ModuleImpl extends PlatformComponentManagerImpl implements ModuleEx @Override public void init(@NotNull final String path, @Nullable final Runnable beforeComponentCreation) { - init(ProgressManager.getInstance().getProgressIndicator(), new Runnable() { - @Override - public void run() { - // create ServiceManagerImpl at first to force extension classes registration - getPicoContainer().getComponentInstance(ModuleServiceManagerImpl.class); - ServiceKt.getStateStore(ModuleImpl.this).setPath(path); + init(ProgressManager.getInstance().getProgressIndicator(), () -> { + // create ServiceManagerImpl at first to force extension classes registration + getPicoContainer().getComponentInstance(ModuleServiceManagerImpl.class); + ServiceKt.getStateStore(ModuleImpl.this).setPath(path); - if (beforeComponentCreation != null) { - beforeComponentCreation.run(); - } + if (beforeComponentCreation != null) { + beforeComponentCreation.run(); } }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/module/impl/ProjectLoadingErrorsNotifierImpl.java b/platform/lang-impl/src/com/intellij/openapi/module/impl/ProjectLoadingErrorsNotifierImpl.java index fc30e878708b..4d6ebbf6ee97 100644 --- a/platform/lang-impl/src/com/intellij/openapi/module/impl/ProjectLoadingErrorsNotifierImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/module/impl/ProjectLoadingErrorsNotifierImpl.java @@ -70,12 +70,7 @@ public class ProjectLoadingErrorsNotifierImpl extends ProjectLoadingErrorsNotifi fireNotifications(); } else if (first) { - StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - fireNotifications(); - } - }); + StartupManager.getInstance(myProject).registerPostStartupActivity(() -> fireNotifications()); } } diff --git a/platform/lang-impl/src/com/intellij/openapi/paths/PathReferenceManagerImpl.java b/platform/lang-impl/src/com/intellij/openapi/paths/PathReferenceManagerImpl.java index 23c4d1fdb3e2..b3be19b09fde 100644 --- a/platform/lang-impl/src/com/intellij/openapi/paths/PathReferenceManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/paths/PathReferenceManagerImpl.java @@ -34,12 +34,8 @@ import java.util.*; public class PathReferenceManagerImpl extends PathReferenceManager { private final StaticPathReferenceProvider myStaticProvider = new StaticPathReferenceProvider(null); private final PathReferenceProvider myGlobalPathsProvider = new GlobalPathReferenceProvider(); - private static final Comparator START_OFFSET_COMPARATOR = new Comparator() { - @Override - public int compare(final PsiReference o1, final PsiReference o2) { - return o1.getRangeInElement().getStartOffset() - o2.getRangeInElement().getStartOffset(); - } - }; + private static final Comparator START_OFFSET_COMPARATOR = + (o1, o2) -> o1.getRangeInElement().getStartOffset() - o2.getRangeInElement().getStartOffset(); @Override @Nullable diff --git a/platform/lang-impl/src/com/intellij/openapi/projectRoots/ex/PathUtilEx.java b/platform/lang-impl/src/com/intellij/openapi/projectRoots/ex/PathUtilEx.java index 4d68c57eb97c..7ff703c8aa74 100644 --- a/platform/lang-impl/src/com/intellij/openapi/projectRoots/ex/PathUtilEx.java +++ b/platform/lang-impl/src/com/intellij/openapi/projectRoots/ex/PathUtilEx.java @@ -42,12 +42,7 @@ import static com.intellij.util.containers.ContainerUtil.skipNulls; */ public class PathUtilEx { - private static final Function MODULE_JDK = new Function() { - @Override - public Sdk fun(Module module) { - return ModuleRootManager.getInstance(module).getSdk(); - } - }; + private static final Function MODULE_JDK = module -> ModuleRootManager.getInstance(module).getSdk(); private static final Convertor JDK_VERSION = new Convertor() { @Override public String convert(Sdk jdk) { diff --git a/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/DependentSdkType.java b/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/DependentSdkType.java index 0dd06d060f0e..ed584efec63a 100644 --- a/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/DependentSdkType.java +++ b/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/DependentSdkType.java @@ -84,16 +84,13 @@ public abstract class DependentSdkType extends SdkType { final SdkType sdkType, final Consumer sdkCreatedCallback) { final Ref result = new Ref(null); - SdkConfigurationUtil.selectSdkHome(sdkType, new Consumer() { - @Override - public void consume(final String home) { - String newSdkName = SdkConfigurationUtil.createUniqueSdkName(sdkType, home, Arrays.asList(sdkModel.getSdks())); - final ProjectJdkImpl newJdk = new ProjectJdkImpl(newSdkName, sdkType); - newJdk.setHomePath(home); + SdkConfigurationUtil.selectSdkHome(sdkType, home -> { + String newSdkName = SdkConfigurationUtil.createUniqueSdkName(sdkType, home, Arrays.asList(sdkModel.getSdks())); + final ProjectJdkImpl newJdk = new ProjectJdkImpl(newSdkName, sdkType); + newJdk.setHomePath(home); - sdkCreatedCallback.consume(newJdk); - result.set(newJdk); - } + sdkCreatedCallback.consume(newJdk); + result.set(newJdk); }); return result.get(); } diff --git a/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkConfigurationUtil.java b/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkConfigurationUtil.java index f78d871a7280..fc0d1e9112bc 100644 --- a/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkConfigurationUtil.java +++ b/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/SdkConfigurationUtil.java @@ -117,20 +117,14 @@ public class SdkConfigurationUtil { } public static void addSdk(@NotNull final Sdk sdk) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectJdkTable.getInstance().addJdk(sdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectJdkTable.getInstance().addJdk(sdk); }); } public static void removeSdk(final Sdk sdk) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectJdkTable.getInstance().removeJdk(sdk); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectJdkTable.getInstance().removeJdk(sdk); }); } @@ -176,14 +170,11 @@ public class SdkConfigurationUtil { } public static void setDirectoryProjectSdk(@NotNull final Project project, @Nullable final Sdk sdk) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectRootManager.getInstance(project).setProjectSdk(sdk); - final Module[] modules = ModuleManager.getInstance(project).getModules(); - if (modules.length > 0) { - ModuleRootModificationUtil.setSdkInherited(modules[0]); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManager.getInstance(project).setProjectSdk(sdk); + final Module[] modules = ModuleManager.getInstance(project).getModules(); + if (modules.length > 0) { + ModuleRootModificationUtil.setSdkInherited(modules[0]); } }); } @@ -284,19 +275,16 @@ public class SdkConfigurationUtil { consumer.consume(sdk.getHomePath()); return; } - FileChooser.chooseFiles(descriptor, null, getSuggestedSdkRoot(sdkType), new Consumer>() { - @Override - public void consume(final List chosen) { - final String path = chosen.get(0).getPath(); - if (sdkType.isValidSdkHome(path)) { - consumer.consume(path); - return; - } + FileChooser.chooseFiles(descriptor, null, getSuggestedSdkRoot(sdkType), chosen -> { + final String path = chosen.get(0).getPath(); + if (sdkType.isValidSdkHome(path)) { + consumer.consume(path); + return; + } - final String adjustedPath = sdkType.adjustSelectedSdkHome(path); - if (sdkType.isValidSdkHome(adjustedPath)) { - consumer.consume(adjustedPath); - } + final String adjustedPath = sdkType.adjustSelectedSdkHome(path); + if (sdkType.isValidSdkHome(adjustedPath)) { + consumer.consume(adjustedPath); } }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerComponent.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerComponent.java index 5acf72be1258..30d27fb0d620 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerComponent.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerComponent.java @@ -92,12 +92,7 @@ public class ProjectRootManagerComponent extends ProjectRootManagerImpl implemen } }, project); - startupManager.registerStartupActivity(new Runnable() { - @Override - public void run() { - myStartupActivityPerformed = true; - } - }); + startupManager.registerStartupActivity(() -> myStartupActivityPerformed = true); myHandler = new BatchUpdateListener() { @Override diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java index d9af7f6ef0bb..ef252a61efb3 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java @@ -80,19 +80,15 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater } }); - StartupManager.getInstance(project).registerPreStartupActivity(new Runnable() { - @Override - public void run() { - project.getMessageBus().connect().subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { - @Override - public void rootsChanged(final ModuleRootEvent event) { - for (FilePropertyPusher pusher : myPushers) { - pusher.afterRootsChanged(project); - } + StartupManager.getInstance(project).registerPreStartupActivity( + () -> project.getMessageBus().connect().subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { + @Override + public void rootsChanged(final ModuleRootEvent event) { + for (FilePropertyPusher pusher : myPushers) { + pusher.afterRootsChanged(project); } - }); - } - }); + } + })); } public void processAfterVfsChanges(@NotNull List events) { @@ -128,12 +124,7 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater queueTasks(delayedTasks); } if (pushedSomething) { - GuiUtils.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - scheduleDumbModeReindexingIfNeeded(); - } - }, ModalityState.defaultModalityState()); + GuiUtils.invokeLaterIfNeeded(() -> scheduleDumbModeReindexingIfNeeded(), ModalityState.defaultModalityState()); } } @@ -165,12 +156,7 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater if (pushers.length == 0) return null; final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); if (!fileIndex.isInContent(dir)) return null; - return new Runnable() { - @Override - public void run() { - doPushRecursively(dir, pushers, fileIndex); - } - }; + return () -> doPushRecursively(dir, pushers, fileIndex); } private void doPushRecursively(VirtualFile dir, final FilePropertyPusher[] pushers, ProjectFileIndex fileIndex) { @@ -256,12 +242,7 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater @Override public void pushAll(final FilePropertyPusher... pushers) { - queueTasks(Collections.singletonList(new Runnable() { - @Override - public void run() { - doPushAll(pushers); - } - })); + queueTasks(Collections.singletonList(() -> doPushAll(pushers))); } private void doPushAll(final FilePropertyPusher[] pushers) { @@ -287,18 +268,13 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater } final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex(); - return new Runnable() { + return () -> fileIndex.iterateContent(new ContentIterator() { @Override - public void run() { - fileIndex.iterateContent(new ContentIterator() { - @Override - public boolean processFile(final VirtualFile fileOrDir) { - applyPushersToFile(fileOrDir, pushers, moduleValues); - return true; - } - }); + public boolean processFile(final VirtualFile fileOrDir) { + applyPushersToFile(fileOrDir, pushers, moduleValues); + return true; } - }; + }); } }); tasks.add(iteration); @@ -323,17 +299,10 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater int numThreads = Math.max(Math.min(CacheUpdateRunner.indexingThreadCount() - 1, tasks.size() - 1), 1); for (int i = 0; i < numThreads; ++i) { - results.add(ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - Runnable runnable; - while ((runnable = tasksQueue.poll()) != null) runnable.run(); - } - }, ProgressWrapper.wrap(progress)); - }})); + results.add(ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> { + Runnable runnable; + while ((runnable = tasksQueue.poll()) != null) runnable.run(); + }, ProgressWrapper.wrap(progress)))); } } @@ -350,13 +319,10 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater } private void applyPushersToFile(final VirtualFile fileOrDir, final FilePropertyPusher[] pushers, final Object[] moduleValues) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - ProgressManager.checkCanceled(); - if (!fileOrDir.isValid()) return; - doApplyPushersToFile(fileOrDir, pushers, moduleValues); - } + ApplicationManager.getApplication().runReadAction(() -> { + ProgressManager.checkCanceled(); + if (!fileOrDir.isValid()) return; + doApplyPushersToFile(fileOrDir, pushers, moduleValues); }); } private void doApplyPushersToFile(VirtualFile fileOrDir, FilePropertyPusher[] pushers, Object[] moduleValues) { diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/libraries/RenameLibraryHandler.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/libraries/RenameLibraryHandler.java index 75d3443817b9..0e5f7a30ccbd 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/libraries/RenameLibraryHandler.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/libraries/RenameLibraryHandler.java @@ -96,34 +96,28 @@ public class RenameLibraryHandler implements RenameHandler, TitledHandler { final Library.ModifiableModel modifiableModel = renameLibrary(inputString); if (modifiableModel == null) return false; final Ref success = Ref.create(Boolean.TRUE); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - UndoableAction action = new BasicUndoableAction() { - @Override - public void undo() throws UnexpectedUndoException { - final Library.ModifiableModel modifiableModel = renameLibrary(oldName); - if (modifiableModel != null) { - modifiableModel.commit(); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + UndoableAction action = new BasicUndoableAction() { + @Override + public void undo() throws UnexpectedUndoException { + final Library.ModifiableModel modifiableModel1 = renameLibrary(oldName); + if (modifiableModel1 != null) { + modifiableModel1.commit(); } + } - @Override - public void redo() throws UnexpectedUndoException { - final Library.ModifiableModel modifiableModel = renameLibrary(inputString); - if (modifiableModel != null) { - modifiableModel.commit(); - } + @Override + public void redo() throws UnexpectedUndoException { + final Library.ModifiableModel modifiableModel1 = renameLibrary(inputString); + if (modifiableModel1 != null) { + modifiableModel1.commit(); } - }; - UndoManager.getInstance(myProject).undoableActionPerformed(action); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifiableModel.commit(); - } - }); - } + } + }; + UndoManager.getInstance(myProject).undoableActionPerformed(action); + ApplicationManager.getApplication().runWriteAction(() -> { + modifiableModel.commit(); + }); }, IdeBundle.message("command.renaming.module", oldName), null); return success.get().booleanValue(); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/FileTypeBasedRootFilter.java b/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/FileTypeBasedRootFilter.java index 64498607a58c..ad7ad88b460a 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/FileTypeBasedRootFilter.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/FileTypeBasedRootFilter.java @@ -61,16 +61,13 @@ public class FileTypeBasedRootFilter extends RootFilter { } private boolean containsFileOfType(VirtualFile rootCandidate, final ProgressIndicator progressIndicator) { - return !VfsUtil.processFilesRecursively(rootCandidate, new Processor() { - @Override - public boolean process(VirtualFile virtualFile) { - progressIndicator.checkCanceled(); - if (virtualFile.isDirectory()) { - progressIndicator.setText2(virtualFile.getPath()); - return true; - } - return !isFileAccepted(virtualFile); + return !VfsUtil.processFilesRecursively(rootCandidate, virtualFile -> { + progressIndicator.checkCanceled(); + if (virtualFile.isDirectory()) { + progressIndicator.setText2(virtualFile.getPath()); + return true; } + return !isFileAccepted(virtualFile); }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/impl/DetectedRootsChooserDialog.java b/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/impl/DetectedRootsChooserDialog.java index bf3d383aeebb..a9e7b79f4f91 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/impl/DetectedRootsChooserDialog.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/libraries/ui/impl/DetectedRootsChooserDialog.java @@ -204,12 +204,8 @@ public class DetectedRootsChooserDialog extends DialogWrapper { private static CheckedTreeNode createRoot(Collection suggestedRoots) { SuggestedChildRootInfo[] sortedRoots = suggestedRoots.toArray(new SuggestedChildRootInfo[suggestedRoots.size()]); - Arrays.sort(sortedRoots, new Comparator() { - @Override - public int compare(@NotNull SuggestedChildRootInfo o1, @NotNull SuggestedChildRootInfo o2) { - return o1.getDetectedRoot().getFile().getPresentableUrl().compareTo(o2.getDetectedRoot().getFile().getPresentableUrl()); - } - }); + Arrays.sort(sortedRoots, + (o1, o2) -> o1.getDetectedRoot().getFile().getPresentableUrl().compareTo(o2.getDetectedRoot().getFile().getPresentableUrl())); CheckedTreeNode root = new CheckedTreeNode(null); Map rootCandidateNodes = new HashMap(); diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/CommonContentEntriesEditor.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/CommonContentEntriesEditor.java index be24f390b959..047d0b83d285 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/CommonContentEntriesEditor.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/CommonContentEntriesEditor.java @@ -274,12 +274,7 @@ public class CommonContentEntriesEditor extends ModuleElementsEditor { editor.setSelected(true); final JComponent component = editor.getComponent(); final JComponent scroller = (JComponent)component.getParent(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - scroller.scrollRectToVisible(component.getBounds()); - } - }); + SwingUtilities.invokeLater(() -> scroller.scrollRectToVisible(component.getBounds())); myRootTreeEditor.setContentEntryEditor(editor); myRootTreeEditor.requestFocus(); } @@ -415,12 +410,9 @@ public class CommonContentEntriesEditor extends ModuleElementsEditor { @Override public void actionPerformed(AnActionEvent e) { - FileChooser.chooseFiles(myDescriptor, myProject, myLastSelectedDir, new Consumer>() { - @Override - public void consume(List files) { - myLastSelectedDir = files.get(0); - addContentEntries(VfsUtilCore.toVirtualFileArray(files)); - } + FileChooser.chooseFiles(myDescriptor, myProject, myLastSelectedDir, files -> { + myLastSelectedDir = files.get(0); + addContentEntries(VfsUtilCore.toVirtualFileArray(files)); }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeEditor.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeEditor.java index 908d695798e5..963e8aaf0a7a 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeEditor.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeEditor.java @@ -154,13 +154,10 @@ public class ContentEntryTreeEditor { myDescriptor.setTitle(FileUtil.toSystemDependentName(path)); } - final Runnable init = new Runnable() { - @Override - public void run() { - //noinspection ConstantConditions - myFileSystemTree.updateTree(); - myFileSystemTree.select(file, null); - } + final Runnable init = () -> { + //noinspection ConstantConditions + myFileSystemTree.updateTree(); + myFileSystemTree.select(file, null); }; myFileSystemTree = new FileSystemTreeImpl(myProject, myDescriptor, myTree, getContentEntryCellRenderer(), init, null) { diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java index 8bc63d157163..39b736d74667 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java @@ -61,22 +61,11 @@ import java.util.Map; */ public abstract class ContentRootPanel extends JPanel { private static final Color EXCLUDED_COLOR = new JBColor(new Color(0x992E00), DarculaColors.RED); - private static final Color SELECTED_HEADER_COLOR = new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - return UIUtil.isUnderDarcula() ? UIUtil.getPanelBackground().darker() : new Color(0xDEF2FF); - } - }); + private static final Color SELECTED_HEADER_COLOR = new JBColor( + () -> UIUtil.isUnderDarcula() ? UIUtil.getPanelBackground().darker() : new Color(0xDEF2FF)); private static final Color HEADER_COLOR = new JBColor(new Color(0xF5F5F5), Gray._82); private static final Color SELECTED_CONTENT_COLOR = new Color(0xF0F9FF); - private static final Color CONTENT_COLOR = new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - return UIUtil.isUnderDarcula() ? UIUtil.getPanelBackground() : Gray._255; - } - }); + private static final Color CONTENT_COLOR = new JBColor(() -> UIUtil.isUnderDarcula() ? UIUtil.getPanelBackground() : Gray._255); private static final Color UNSELECTED_TEXT_COLOR = Gray._51; protected final ActionCallback myCallback; @@ -159,12 +148,8 @@ public abstract class ContentRootPanel extends JPanel { } final IconActionComponent deleteIconComponent = new IconActionComponent(AllIcons.Modules.DeleteContentRoot, AllIcons.Modules.DeleteContentRootRollover, - ProjectBundle.message("module.paths.remove.content.tooltip"), new Runnable() { - @Override - public void run() { - myCallback.deleteContentEntry(); - } - }); + ProjectBundle.message("module.paths.remove.content.tooltip"), + () -> myCallback.deleteContentEntry()); final ResizingWrapper wrapper = new ResizingWrapper(headerLabel); panel.add(wrapper, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 0), 0, 0)); panel.add(deleteIconComponent, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 0.0, 1.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 0, 0)); @@ -264,12 +249,8 @@ public abstract class ContentRootPanel extends JPanel { else { tooltipText = ProjectBundle.message("module.paths.remove.tooltip"); } - return new IconActionComponent(AllIcons.Modules.DeleteContentFolder, AllIcons.Modules.DeleteContentFolderRollover, tooltipText, new Runnable() { - @Override - public void run() { - myCallback.deleteContentFolder(getContentEntry(), folder); - } - }); + return new IconActionComponent(AllIcons.Modules.DeleteContentFolder, AllIcons.Modules.DeleteContentFolderRollover, tooltipText, + () -> myCallback.deleteContentFolder(getContentEntry(), folder)); } public boolean isExcludedOrUnderExcludedDirectory(final VirtualFile file) { diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java index 96d591a7045d..aafae0f15694 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java @@ -69,17 +69,14 @@ public abstract class JavaSourceRootEditHandlerBase extends ModuleSourceRootEdit @NotNull final ContentRootPanel.ActionCallback callback) { final IconActionComponent iconComponent = new IconActionComponent(AllIcons.Modules.SetPackagePrefix, AllIcons.Modules.SetPackagePrefixRollover, - ProjectBundle.message("module.paths.edit.properties.tooltip"), new Runnable() { - @Override - public void run() { - JavaSourceRootProperties properties = folder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); - assert properties != null; - SourceRootPropertiesDialog dialog = new SourceRootPropertiesDialog(parentComponent, properties); - if (dialog.showAndGet()) { - callback.onSourceRootPropertiesChanged(folder); - } - } - }); + ProjectBundle.message("module.paths.edit.properties.tooltip"), () -> { + JavaSourceRootProperties properties = folder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); + assert properties != null; + SourceRootPropertiesDialog dialog = new SourceRootPropertiesDialog(parentComponent, properties); + if (dialog.showAndGet()) { + callback.onSourceRootPropertiesChanged(folder); + } + }); final JPanel panel = new JPanel(new BorderLayout()); panel.setOpaque(false); panel.add(iconComponent, BorderLayout.CENTER); diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/PlatformContentEntriesConfigurable.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/PlatformContentEntriesConfigurable.java index a818b4b94956..6bf5d35dc8d0 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/PlatformContentEntriesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/PlatformContentEntriesConfigurable.java @@ -94,11 +94,8 @@ public class PlatformContentEntriesConfigurable implements Configurable { public void apply() throws ConfigurationException { myEditor.apply(); if (myModifiableModel.isChanged()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myModifiableModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myModifiableModel.commit(); }); myEditor.disposeUIResources(); myTopPanel.remove(myEditor.getComponent()); diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/actions/ModuleDeleteProvider.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/actions/ModuleDeleteProvider.java index f5581650bf28..0c38b6bdd08b 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/actions/ModuleDeleteProvider.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/actions/ModuleDeleteProvider.java @@ -77,40 +77,29 @@ public class ModuleDeleteProvider implements DeleteProvider, TitledHandler { assert modules != null; final Project project = CommonDataKeys.PROJECT.getData(dataContext); assert project != null; - String names = StringUtil.join(Arrays.asList(modules), new Function() { - @Override - public String fun(final Module module) { - return "\'" + module.getName() + "\'"; - } - }, ", "); + String names = StringUtil.join(Arrays.asList(modules), module -> "\'" + module.getName() + "\'", ", "); int ret = Messages.showOkCancelDialog(getConfirmationText(modules, names), getActionTitle(), Messages.getQuestionIcon()); if (ret != Messages.OK) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - final Runnable action = new Runnable() { - @Override - public void run() { - final ModuleManager moduleManager = ModuleManager.getInstance(project); - final Module[] currentModules = moduleManager.getModules(); - final ModifiableModuleModel modifiableModuleModel = moduleManager.getModifiableModel(); - final Map otherModuleRootModels = new HashMap(); - for (final Module module : modules) { - final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel(); - for (final Module otherModule : currentModules) { - if (otherModule == module || ArrayUtilRt.find(modules, otherModule) != -1) continue; - if (!otherModuleRootModels.containsKey(otherModule)) { - otherModuleRootModels.put(otherModule, ModuleRootManager.getInstance(otherModule).getModifiableModel()); - } - } - removeModule(module, modifiableModel, otherModuleRootModels.values(), modifiableModuleModel); + CommandProcessor.getInstance().executeCommand(project, () -> { + final Runnable action = () -> { + final ModuleManager moduleManager = ModuleManager.getInstance(project); + final Module[] currentModules = moduleManager.getModules(); + final ModifiableModuleModel modifiableModuleModel = moduleManager.getModifiableModel(); + final Map otherModuleRootModels = new HashMap(); + for (final Module module : modules) { + final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel(); + for (final Module otherModule : currentModules) { + if (otherModule == module || ArrayUtilRt.find(modules, otherModule) != -1) continue; + if (!otherModuleRootModels.containsKey(otherModule)) { + otherModuleRootModels.put(otherModule, ModuleRootManager.getInstance(otherModule).getModifiableModel()); } - final ModifiableRootModel[] modifiableRootModels = otherModuleRootModels.values().toArray(new ModifiableRootModel[otherModuleRootModels.size()]); - ModifiableModelCommitter.multiCommit(modifiableRootModels, modifiableModuleModel); } - }; - ApplicationManager.getApplication().runWriteAction(action); - } + removeModule(module, modifiableModel, otherModuleRootModels.values(), modifiableModuleModel); + } + final ModifiableRootModel[] modifiableRootModels = otherModuleRootModels.values().toArray(new ModifiableRootModel[otherModuleRootModels.size()]); + ModifiableModelCommitter.multiCommit(modifiableRootModels, modifiableModuleModel); + }; + ApplicationManager.getApplication().runWriteAction(action); }, ProjectBundle.message("module.remove.command"), null); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ProjectSdksModel.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ProjectSdksModel.java index 350ed36a7220..a3ee8d32924b 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ProjectSdksModel.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/projectRoot/ProjectSdksModel.java @@ -130,48 +130,40 @@ public class ProjectSdksModel implements SdkModel { throw new ConfigurationException(errorString[0]); } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - doApply(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> doApply()); myModified = false; } private void doApply() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final ArrayList itemsInTable = new ArrayList(); - final ProjectJdkTable jdkTable = ProjectJdkTable.getInstance(); - final Sdk[] allFromTable = jdkTable.getAllJdks(); + ApplicationManager.getApplication().runWriteAction(() -> { + final ArrayList itemsInTable = new ArrayList(); + final ProjectJdkTable jdkTable = ProjectJdkTable.getInstance(); + final Sdk[] allFromTable = jdkTable.getAllJdks(); - // Delete removed and fill itemsInTable - for (final Sdk tableItem : allFromTable) { - if (myProjectSdks.containsKey(tableItem)) { - itemsInTable.add(tableItem); - } - else { - jdkTable.removeJdk(tableItem); - } + // Delete removed and fill itemsInTable + for (final Sdk tableItem : allFromTable) { + if (myProjectSdks.containsKey(tableItem)) { + itemsInTable.add(tableItem); } - - // Now all removed items are deleted from table, itemsInTable contains all items in table - for (Sdk originalJdk : itemsInTable) { - final Sdk modifiedJdk = myProjectSdks.get(originalJdk); - LOG.assertTrue(modifiedJdk != null); - LOG.assertTrue(originalJdk != modifiedJdk); - jdkTable.updateJdk(originalJdk, modifiedJdk); + else { + jdkTable.removeJdk(tableItem); } - // Add new items to table - final Sdk[] allJdks = jdkTable.getAllJdks(); - for (final Sdk projectJdk : myProjectSdks.keySet()) { - LOG.assertTrue(projectJdk != null); - if (ArrayUtilRt.find(allJdks, projectJdk) == -1) { - jdkTable.addJdk(projectJdk); - jdkTable.updateJdk(projectJdk, myProjectSdks.get(projectJdk)); - } + } + + // Now all removed items are deleted from table, itemsInTable contains all items in table + for (Sdk originalJdk : itemsInTable) { + final Sdk modifiedJdk = myProjectSdks.get(originalJdk); + LOG.assertTrue(modifiedJdk != null); + LOG.assertTrue(originalJdk != modifiedJdk); + jdkTable.updateJdk(originalJdk, modifiedJdk); + } + // Add new items to table + final Sdk[] allJdks = jdkTable.getAllJdks(); + for (final Sdk projectJdk : myProjectSdks.keySet()) { + LOG.assertTrue(projectJdk != null); + if (ArrayUtilRt.find(allJdks, projectJdk) == -1) { + jdkTable.addJdk(projectJdk); + jdkTable.updateJdk(projectJdk, myProjectSdks.get(projectJdk)); } } }); @@ -264,22 +256,14 @@ public class ProjectSdksModel implements SdkModel { public void doAdd(@NotNull JComponent parent, @NotNull final SdkType type, @NotNull final Consumer callback) { myModified = true; if (type.supportsCustomCreateUI()) { - type.showCustomCreateUI(this, parent, new Consumer() { - @Override - public void consume(Sdk sdk) { - setupSdk(sdk, callback); - } - }); + type.showCustomCreateUI(this, parent, sdk -> setupSdk(sdk, callback)); } else { - SdkConfigurationUtil.selectSdkHome(type, new Consumer() { - @Override - public void consume(final String home) { - String newSdkName = SdkConfigurationUtil.createUniqueSdkName(type, home, myProjectSdks.values()); - final ProjectJdkImpl newJdk = new ProjectJdkImpl(newSdkName, type); - newJdk.setHomePath(home); - setupSdk(newJdk, callback); - } + SdkConfigurationUtil.selectSdkHome(type, home -> { + String newSdkName = SdkConfigurationUtil.createUniqueSdkName(type, home, myProjectSdks.values()); + final ProjectJdkImpl newJdk = new ProjectJdkImpl(newSdkName, type); + newJdk.setHomePath(home); + setupSdk(newJdk, callback); }); } } diff --git a/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java b/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java index f2ec7bf398de..77c828faa59e 100644 --- a/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java +++ b/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java @@ -155,30 +155,27 @@ public class SwitchBootJdkAction extends AnAction implements DumbAware { } }; - FileChooser.chooseFiles(descriptor, null, null, new Consumer>() { - @Override - public void consume(final List files) { - if (files.size() > 0) { - final File jdkFile = new File(files.get(0).getPath()); - JdkBundle selectedJdk = pathsList.getBundle(jdkFile.getPath()); - if (selectedJdk == null) { - selectedJdk = JdkBundle.createBundle(jdkFile, false, false); - if (selectedJdk != null) { - pathsList.addBundle(selectedJdk, true); - if (model.getSize() > 0) { - model.insertElementAt(selectedJdk, model.getSize() - 1); - } - else { - model.addElement(selectedJdk); - } + FileChooser.chooseFiles(descriptor, null, null, files -> { + if (files.size() > 0) { + final File jdkFile = new File(files.get(0).getPath()); + JdkBundle selectedJdk = pathsList.getBundle(jdkFile.getPath()); + if (selectedJdk == null) { + selectedJdk = JdkBundle.createBundle(jdkFile, false, false); + if (selectedJdk != null) { + pathsList.addBundle(selectedJdk, true); + if (model.getSize() > 0) { + model.insertElementAt(selectedJdk, model.getSize() - 1); } else { - LOG.error("Cannot create bundle for path: " + jdkFile.getPath()); - return; + model.addElement(selectedJdk); } } - myComboBox.setSelectedItem(selectedJdk); + else { + LOG.error("Cannot create bundle for path: " + jdkFile.getPath()); + return; + } } + myComboBox.setSelectedItem(selectedJdk); } }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/util/objectTree/DisposerDebugger.java b/platform/lang-impl/src/com/intellij/openapi/util/objectTree/DisposerDebugger.java index c295cb087451..532f0e2db37a 100644 --- a/platform/lang-impl/src/com/intellij/openapi/util/objectTree/DisposerDebugger.java +++ b/platform/lang-impl/src/com/intellij/openapi/util/objectTree/DisposerDebugger.java @@ -267,12 +267,7 @@ public class DisposerDebugger implements UiDebuggerExtension, Disposable { } private void queueUpdate() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myTreeBuilder.refilter(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myTreeBuilder.refilter()); } @Override diff --git a/platform/lang-impl/src/com/intellij/openapi/util/registry/RegistryUi.java b/platform/lang-impl/src/com/intellij/openapi/util/registry/RegistryUi.java index 300109e226d0..5cf5db6b13ab 100644 --- a/platform/lang-impl/src/com/intellij/openapi/util/registry/RegistryUi.java +++ b/platform/lang-impl/src/com/intellij/openapi/util/registry/RegistryUi.java @@ -210,12 +210,9 @@ public class RegistryUi implements Disposable { private void startEditingAtSelection() { myTable.editCellAt(myTable.getSelectedRow(), 2); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myTable.isEditing()) { - myTable.getEditorComponent().requestFocus(); - } + SwingUtilities.invokeLater(() -> { + if (myTable.isEditing()) { + myTable.getEditorComponent().requestFocus(); } }); } @@ -228,20 +225,17 @@ public class RegistryUi implements Disposable { myAll = Registry.getAll(); final List recent = getRecent(); - Collections.sort(myAll, new Comparator() { - @Override - public int compare(@NotNull RegistryValue o1, @NotNull RegistryValue o2) { - final String key1 = o1.getKey(); - final String key2 = o2.getKey(); - final int i1 = recent.indexOf(key1); - final int i2 = recent.indexOf(key2); - final boolean c1 = i1 != -1; - final boolean c2 = i2 != -1; - if (c1 && !c2) return -1; - if (!c1 && c2) return 1; - if (c1 && c2) return i1 - i2; - return key1.compareToIgnoreCase(key2); - } + Collections.sort(myAll, (o1, o2) -> { + final String key1 = o1.getKey(); + final String key2 = o2.getKey(); + final int i1 = recent.indexOf(key1); + final int i2 = recent.indexOf(key2); + final boolean c1 = i1 != -1; + final boolean c2 = i2 != -1; + if (c1 && !c2) return -1; + if (!c1 && c2) return 1; + if (c1 && c2) return i1 - i2; + return key1.compareToIgnoreCase(key2); }); } @@ -387,11 +381,8 @@ public class RegistryUi implements Disposable { if (r == Messages.OK) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - app.restart(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + app.restart(true); }, ModalityState.NON_MODAL); } } diff --git a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/ConfigureFileDefaultEncodingAction.java b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/ConfigureFileDefaultEncodingAction.java index aa0acdf2090a..2918ff85b896 100644 --- a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/ConfigureFileDefaultEncodingAction.java +++ b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/ConfigureFileDefaultEncodingAction.java @@ -32,12 +32,9 @@ public class ConfigureFileDefaultEncodingAction extends AnAction { assert project != null; final FileEncodingConfigurable configurable = new FileEncodingConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable(){ - @Override - public void run() { - if (virtualFile != null) { - configurable.selectFile(virtualFile); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + if (virtualFile != null) { + configurable.selectFile(virtualFile); } }); } diff --git a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java index ce348e0d8070..db5140cc4452 100644 --- a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java +++ b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java @@ -108,12 +108,7 @@ public class FileEncodingConfigurable implements SearchableConfigurable, Configu @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { - return createCharsetsActionGroup("", selected.get(), new Function() { - @Override - public String fun(Charset charset) { - return "Choose encoding '" + charset + "'"; - } - }); + return createCharsetsActionGroup("", selected.get(), charset -> "Choose encoding '" + charset + "'"); } }; parentPanel.removeAll(); diff --git a/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java b/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java index a83f0b5703da..f428370610ca 100644 --- a/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java +++ b/platform/lang-impl/src/com/intellij/openapi/wm/impl/status/TogglePopupHintsPanel.java @@ -84,18 +84,15 @@ public class TogglePopupHintsPanel extends EditorBasedWidget implements StatusBa @Override public Consumer getClickConsumer() { - return new Consumer() { - @Override - public void consume(final MouseEvent e) { - Point point = new Point(0, 0); - final PsiFile file = getCurrentFile(); - if (file != null) { - if (!DaemonCodeAnalyzer.getInstance(file.getProject()).isHighlightingAvailable(file)) return; - final HectorComponent component = new HectorComponent(file); - final Dimension dimension = component.getPreferredSize(); - point = new Point(point.x - dimension.width, point.y - dimension.height); - component.showComponent(new RelativePoint(e.getComponent(), point)); - } + return e -> { + Point point = new Point(0, 0); + final PsiFile file = getCurrentFile(); + if (file != null) { + if (!DaemonCodeAnalyzer.getInstance(file.getProject()).isHighlightingAvailable(file)) return; + final HectorComponent component = new HectorComponent(file); + final Dimension dimension = component.getPreferredSize(); + point = new Point(point.x - dimension.width, point.y - dimension.height); + component.showComponent(new RelativePoint(e.getComponent(), point)); } }; } diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/DependenciesToolWindow.java b/platform/lang-impl/src/com/intellij/packageDependencies/DependenciesToolWindow.java index db7e94733a13..ab1f99d3e770 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/DependenciesToolWindow.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/DependenciesToolWindow.java @@ -41,31 +41,26 @@ public class DependenciesToolWindow { public DependenciesToolWindow(final Project project) { myProject = project; - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - @Override - public void run() { - final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); - if (toolWindowManager == null) return; - ToolWindow toolWindow = toolWindowManager.registerToolWindow(ToolWindowId.DEPENDENCIES, - true, - ToolWindowAnchor.BOTTOM, - project); - toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); - myContentManager = toolWindow.getContentManager(); + StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> { + final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); + if (toolWindowManager == null) return; + ToolWindow toolWindow = toolWindowManager.registerToolWindow(ToolWindowId.DEPENDENCIES, + true, + ToolWindowAnchor.BOTTOM, + project); + toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); + myContentManager = toolWindow.getContentManager(); - toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowInspection); - new ContentManagerWatcher(toolWindow, myContentManager); - } + toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowInspection); + new ContentManagerWatcher(toolWindow, myContentManager); }); } public void addContent(final Content content) { - final Runnable runnable = new Runnable() { - public void run() { - myContentManager.addContent(content); - myContentManager.setSelectedContent(content); - ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.DEPENDENCIES).activate(null); - } + final Runnable runnable = () -> { + myContentManager.addContent(content); + myContentManager.setSelectedContent(content); + ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.DEPENDENCIES).activate(null); }; StartupManager.getInstance(myProject).runWhenProjectIsInitialized(runnable); } diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/actions/DependenciesHandlerBase.java b/platform/lang-impl/src/com/intellij/packageDependencies/actions/DependenciesHandlerBase.java index 997cb49ce154..2c1a2c23e92b 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/actions/DependenciesHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/actions/DependenciesHandlerBase.java @@ -117,17 +117,14 @@ public abstract class DependenciesHandlerBase { private void onSuccess(final List builders) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (shouldShowDependenciesPanel(builders)) { - final String displayName = getPanelDisplayName(builders); - DependenciesPanel panel = new DependenciesPanel(myProject, builders, myExcluded); - Content content = ContentFactory.SERVICE.getInstance().createContent(panel, displayName, false); - content.setDisposer(panel); - panel.setContent(content); - DependenciesToolWindow.getInstance(myProject).addContent(content); - } + SwingUtilities.invokeLater(() -> { + if (shouldShowDependenciesPanel(builders)) { + final String displayName = getPanelDisplayName(builders); + DependenciesPanel panel = new DependenciesPanel(myProject, builders, myExcluded); + Content content = ContentFactory.SERVICE.getInstance().createContent(panel, displayName, false); + content.setDisposer(panel); + panel.setContent(content); + DependenciesToolWindow.getInstance(myProject).addContent(content); } }); } diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesPanel.java b/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesPanel.java index 96a5ab18c6f5..383fc65c80d9 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesPanel.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesPanel.java @@ -198,24 +198,18 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide myRightTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final Set searchIn = getSelectedScope(myLeftTree); - final Set searchFor = getSelectedScope(myRightTree); - if (searchIn.isEmpty() || searchFor.isEmpty()) { - myUsagesPanel.setToInitialPosition(); - processDependencies(searchIn, searchFor, new Processor>() { //todo do not show too many usages - @Override - public boolean process(final List path) { - searchFor.add(path.get(1)); - return true; - } - }); - } - else { - myUsagesPanel.findUsages(searchIn, searchFor); - } + SwingUtilities.invokeLater(() -> { + final Set searchIn = getSelectedScope(myLeftTree); + final Set searchFor = getSelectedScope(myRightTree); + if (searchIn.isEmpty() || searchFor.isEmpty()) { + myUsagesPanel.setToInitialPosition(); + processDependencies(searchIn, searchFor, path -> { + searchFor.add(path.get(1)); + return true; + }); + } + else { + myUsagesPanel.findUsages(searchIn, searchFor); } }); } @@ -253,12 +247,7 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide for (PsiFile from : searchIn) { for (PsiFile to : initialSearchFor) { final List> paths = builder.findPaths(from, to); - Collections.sort(paths, new Comparator>() { - @Override - public int compare(final List p1, final List p2) { - return p1.size() - p2.size(); - } - }); + Collections.sort(paths, (p1, p2) -> p1.size() - p2.size()); for (List path : paths) { if (!path.isEmpty()){ path.add(0, from); @@ -703,16 +692,13 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide final Element rootElement = new Element("root"); rootElement.setAttribute("isBackward", String.valueOf(!myForward)); final List files = new ArrayList(myDependencies.keySet()); - Collections.sort(files, new Comparator() { - @Override - public int compare(PsiFile f1, PsiFile f2) { - final VirtualFile virtualFile1 = f1.getVirtualFile(); - final VirtualFile virtualFile2 = f2.getVirtualFile(); - if (virtualFile1 != null && virtualFile2 != null) { - return virtualFile1.getPath().compareToIgnoreCase(virtualFile2.getPath()); - } - return 0; + Collections.sort(files, (f1, f2) -> { + final VirtualFile virtualFile1 = f1.getVirtualFile(); + final VirtualFile virtualFile2 = f2.getVirtualFile(); + if (virtualFile1 != null && virtualFile2 != null) { + return virtualFile1.getPath().compareToIgnoreCase(virtualFile2.getPath()); } + return 0; }); for (PsiFile file : files) { final Element fileElement = new Element("file"); @@ -764,21 +750,18 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide public void actionPerformed(AnActionEvent e) { DependenciesToolWindow.getInstance(myProject).closeContent(myContent); mySettings.copyToApplicationDependencySettings(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final List scopes = new ArrayList(); - for (DependenciesBuilder builder : myBuilders) { - final AnalysisScope scope = builder.getScope(); - scope.invalidate(); - scopes.add(scope); - } - if (!myForward) { - new BackwardDependenciesHandler(myProject, scopes, myScopeOfInterest, myExcluded).analyze(); - } - else { - new AnalyzeDependenciesHandler(myProject, scopes, myTransitiveBorder, myExcluded).analyze(); - } + SwingUtilities.invokeLater(() -> { + final List scopes = new ArrayList(); + for (DependenciesBuilder builder : myBuilders) { + final AnalysisScope scope = builder.getScope(); + scope.invalidate(); + scopes.add(scope); + } + if (!myForward) { + new BackwardDependenciesHandler(myProject, scopes, myScopeOfInterest, myExcluded).analyze(); + } + else { + new AnalyzeDependenciesHandler(myProject, scopes, myTransitiveBorder, myExcluded).analyze(); } }); } @@ -815,18 +798,12 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide public void actionPerformed(final AnActionEvent e) { @NonNls final String delim = " -> "; final StringBuffer buf = new StringBuffer(); - processDependencies(getSelectedScope(myLeftTree), getSelectedScope(myRightTree), new Processor>() { - @Override - public boolean process(final List path) { - if (buf.length() > 0) buf.append("
    "); - buf.append(StringUtil.join(path, new Function() { - @Override - public String fun(final PsiFile psiFile) { - return psiFile.getName(); - } - }, delim)); - return true; - } + processDependencies(getSelectedScope(myLeftTree), getSelectedScope(myRightTree), path -> { + if (buf.length() > 0) buf.append("
    "); + buf.append(StringUtil.join(path, psiFile -> { + return psiFile.getName(); + }, delim)); + return true; }); final JEditorPane pane = new JEditorPane(UIUtil.HTML_MIME, XmlStringUtil.wrapInHtml(buf)); pane.setForeground(JBColor.foreground()); @@ -843,12 +820,9 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide @Override public void update(final AnActionEvent e) { final boolean[] direct = new boolean[]{true}; - processDependencies(getSelectedScope(myLeftTree), getSelectedScope(myRightTree), new Processor>() { - @Override - public boolean process(final List path) { - direct [0] = false; - return false; - } + processDependencies(getSelectedScope(myLeftTree), getSelectedScope(myRightTree), path -> { + direct [0] = false; + return false; }); e.getPresentation().setEnabled(!direct[0]); } @@ -898,20 +872,13 @@ public class DependenciesPanel extends JPanel implements Disposable, DataProvide } else { builder = new ForwardDependenciesBuilder(myProject, scope, myTransitiveBorder); } - ProgressManager.getInstance().runProcessWithProgressAsynchronously(myProject, AnalysisScopeBundle.message("package.dependencies.progress.title"), new Runnable() { - @Override - public void run() { - builder.analyze(); - } - }, new Runnable() { - @Override - public void run() { - myBuilders.add(builder); - myDependencies.putAll(builder.getDependencies()); - putAllDependencies(builder); - exclude(myExcluded); - rebuild(); - } + ProgressManager.getInstance().runProcessWithProgressAsynchronously(myProject, AnalysisScopeBundle.message("package.dependencies.progress.title"), + () -> builder.analyze(), () -> { + myBuilders.add(builder); + myDependencies.putAll(builder.getDependencies()); + putAllDependencies(builder); + exclude(myExcluded); + rebuild(); }, null, new PerformAnalysisInBackgroundOption(myProject)); } diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesUsagesPanel.java b/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesUsagesPanel.java index 2d73d8b18bad..91e0ab22b327 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesUsagesPanel.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/ui/DependenciesUsagesPanel.java @@ -63,65 +63,43 @@ public class DependenciesUsagesPanel extends UsagesPanel { cancelCurrentFindRequest(); myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final ProgressIndicator progress = new PanelProgressIndicator(new Consumer() { - @Override - public void consume(final JComponent component) { - setToComponent(component); - } - }); - myCurrentProgress = progress; - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - UsageInfo[] usages = new UsageInfo[0]; - Set elementsToSearch = null; + myAlarm.addRequest(() -> ApplicationManager.getApplication().executeOnPooledThread(() -> { + final ProgressIndicator progress = new PanelProgressIndicator(component -> setToComponent(component)); + myCurrentProgress = progress; + ProgressManager.getInstance().runProcess(() -> { + ApplicationManager.getApplication().runReadAction(() -> { + UsageInfo[] usages = new UsageInfo[0]; + Set elementsToSearch = null; - try { - if (myBuilders.get(0).isBackward()){ - elementsToSearch = searchIn; - usages = FindDependencyUtil.findBackwardDependencies(myBuilders, searchFor, searchIn); - } - else { - elementsToSearch = searchFor; - usages = FindDependencyUtil.findDependencies(myBuilders, searchIn, searchFor); - } - assert !new HashSet(elementsToSearch).contains(null); - } - catch (ProcessCanceledException e) { - } - catch (Exception e) { - LOG.error(e); - } + try { + if (myBuilders.get(0).isBackward()){ + elementsToSearch = searchIn; + usages = FindDependencyUtil.findBackwardDependencies(myBuilders, searchFor, searchIn); + } + else { + elementsToSearch = searchFor; + usages = FindDependencyUtil.findDependencies(myBuilders, searchIn, searchFor); + } + assert !new HashSet(elementsToSearch).contains(null); + } + catch (ProcessCanceledException e) { + } + catch (Exception e) { + LOG.error(e); + } - if (!progress.isCanceled()) { - final UsageInfo[] finalUsages = usages; - final PsiElement[] _elementsToSearch = - elementsToSearch != null ? PsiUtilCore.toPsiElementArray(elementsToSearch) : PsiElement.EMPTY_ARRAY; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showUsages(_elementsToSearch, finalUsages); - } - }, ModalityState.stateForComponent(DependenciesUsagesPanel.this)); - } - } - }); - myCurrentProgress = null; - } - }, progress); + if (!progress.isCanceled()) { + final UsageInfo[] finalUsages = usages; + final PsiElement[] _elementsToSearch = + elementsToSearch != null ? PsiUtilCore.toPsiElementArray(elementsToSearch) : PsiElement.EMPTY_ARRAY; + ApplicationManager.getApplication().invokeLater(() -> { + showUsages(_elementsToSearch, finalUsages); + }, ModalityState.stateForComponent(DependenciesUsagesPanel.this)); } }); - } - }, 300); + myCurrentProgress = null; + }, progress); + }), 300); } public void addBuilder(DependenciesBuilder builder) { diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/ui/FileTreeModelBuilder.java b/platform/lang-impl/src/com/intellij/packageDependencies/ui/FileTreeModelBuilder.java index 0721b5701000..0df5dfae38f2 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/ui/FileTreeModelBuilder.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/ui/FileTreeModelBuilder.java @@ -144,20 +144,17 @@ public class FileTreeModelBuilder { } public TreeModel build(final Project project, final boolean showProgress, @Nullable final Runnable successRunnable) { - final Runnable buildingRunnable = new Runnable() { - @Override - public void run() { - ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - if (indicator != null) { - indicator.setText(SCANNING_PACKAGES_MESSAGE); - indicator.setIndeterminate(true); - } - countFiles(project); - if (indicator != null) { - indicator.setIndeterminate(false); - } - myFileIndex.iterateContent(new MyContentIterator()); + final Runnable buildingRunnable = () -> { + ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + if (indicator != null) { + indicator.setText(SCANNING_PACKAGES_MESSAGE); + indicator.setIndeterminate(true); } + countFiles(project); + if (indicator != null) { + indicator.setIndeterminate(false); + } + myFileIndex.iterateContent(new MyContentIterator()); }; final TreeModel treeModel = new TreeModel(myRoot); if (showProgress) { @@ -213,13 +210,10 @@ public class FileTreeModelBuilder { myShowFiles = true; } - Runnable buildingRunnable = new Runnable() { - @Override - public void run() { - for (final PsiFile file : files) { - if (file != null) { - buildFileNode(file.getVirtualFile(), null); - } + Runnable buildingRunnable = () -> { + for (final PsiFile file : files) { + if (file != null) { + buildFileNode(file.getVirtualFile(), null); } } }; @@ -475,12 +469,7 @@ public class FileTreeModelBuilder { parentWrapper.add(nestedNode); nestedNode.removeUpReference(); if (myTree != null && expand) { - final Runnable expandRunnable = new Runnable() { - @Override - public void run() { - myTree.expandPath(new TreePath(nestedNode.getPath())); - } - }; + final Runnable expandRunnable = () -> myTree.expandPath(new TreePath(nestedNode.getPath())); SwingUtilities.invokeLater(expandRunnable); } return parentWrapper; diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/ui/PanelProgressIndicator.java b/platform/lang-impl/src/com/intellij/packageDependencies/ui/PanelProgressIndicator.java index 008c1173e5a6..e1086e5ba82c 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/ui/PanelProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/ui/PanelProgressIndicator.java @@ -82,24 +82,18 @@ public class PanelProgressIndicator extends ProgressIndicatorBase { if (myPaintInQueue) return; checkCanceled(); myPaintInQueue = true; - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myAlarm.cancelAllRequests(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPaintInQueue = false; - myProgressPanel.myTextLabel.setText(scanningPackagesMessage); - int fraction = (int)(ffraction * 99 + 0.5); - myProgressPanel.myFractionLabel.setText(fraction + "%"); - if (fraction != -1) { - myProgressPanel.myFractionProgress.setValue(fraction); - } - myProgressPanel.myFractionProgress.setIndeterminate(indeterminate); - } - }); - } + myAlarm.addRequest(() -> { + myAlarm.cancelAllRequests(); + SwingUtilities.invokeLater(() -> { + myPaintInQueue = false; + myProgressPanel.myTextLabel.setText(scanningPackagesMessage); + int fraction = (int)(ffraction * 99 + 0.5); + myProgressPanel.myFractionLabel.setText(fraction + "%"); + if (fraction != -1) { + myProgressPanel.myFractionProgress.setValue(fraction); + } + myProgressPanel.myFractionProgress.setIndeterminate(indeterminate); + }); }, 10); } diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/ui/UsagesPanel.java b/platform/lang-impl/src/com/intellij/packageDependencies/ui/UsagesPanel.java index 8f4084b5504e..f8a72f4c9f3b 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/ui/UsagesPanel.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/ui/UsagesPanel.java @@ -86,19 +86,16 @@ public abstract class UsagesPanel extends JPanel implements Disposable, DataProv } protected void setToComponent(final JComponent cmp) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myCurrentComponent != null) { - if (myCurrentUsageView != null && myCurrentComponent == myCurrentUsageView.getComponent()){ - Disposer.dispose(myCurrentUsageView); - } - remove(myCurrentComponent); + SwingUtilities.invokeLater(() -> { + if (myCurrentComponent != null) { + if (myCurrentUsageView != null && myCurrentComponent == myCurrentUsageView.getComponent()){ + Disposer.dispose(myCurrentUsageView); } - myCurrentComponent = cmp; - add(cmp, BorderLayout.CENTER); - revalidate(); + remove(myCurrentComponent); } + myCurrentComponent = cmp; + add(cmp, BorderLayout.CENTER); + revalidate(); }); } diff --git a/platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.java b/platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.java index eb64fffde0a7..4be800e3c001 100644 --- a/platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.java +++ b/platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.java @@ -63,11 +63,8 @@ public class ModuleAttachProcessor extends ProjectAttachProcessor { final VirtualFile baseDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(projectDir.getParent()); PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(baseDir, newProject); newProject.save(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Disposer.dispose(newProject); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Disposer.dispose(newProject); }); } final String[] files = projectDir.list(); @@ -185,12 +182,7 @@ public class ModuleAttachProcessor extends ProjectAttachProcessor { result.add(module); } } - Collections.sort(result, new Comparator() { - @Override - public int compare(Module module, Module module2) { - return module.getName().compareTo(module2.getName()); - } - }); + Collections.sort(result, (module, module2) -> module.getName().compareTo(module2.getName())); if (primaryModule != null) { result.add(0, primaryModule); } diff --git a/platform/lang-impl/src/com/intellij/platform/PlatformProjectConfigurator.java b/platform/lang-impl/src/com/intellij/platform/PlatformProjectConfigurator.java index ba3e1a43e7a6..de3749291570 100644 --- a/platform/lang-impl/src/com/intellij/platform/PlatformProjectConfigurator.java +++ b/platform/lang-impl/src/com/intellij/platform/PlatformProjectConfigurator.java @@ -37,23 +37,20 @@ public class PlatformProjectConfigurator implements DirectoryProjectConfigurator final ModuleManager moduleManager = ModuleManager.getInstance(project); final Module[] modules = moduleManager.getModules(); if (modules.length == 0) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - String moduleName = baseDir.getName().replace(":", ""); // correct module name when opening root of drive as project (RUBY-5181) - String imlName = baseDir.getPath() + "/.idea/" + moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION; - ModuleTypeManager instance = ModuleTypeManager.getInstance(); - String id = instance == null ? "unknown" : instance.getDefaultModuleType().getId(); - final Module module = moduleManager.newModule(imlName, id); - ModuleRootManager rootManager = ModuleRootManager.getInstance(module); - ModifiableRootModel rootModel = rootManager.getModifiableModel(); - if (rootModel.getContentRoots().length == 0) { - rootModel.addContentEntry(baseDir); - } - rootModel.inheritSdk(); - rootModel.commit(); - moduleRef.set(module); + ApplicationManager.getApplication().runWriteAction(() -> { + String moduleName = baseDir.getName().replace(":", ""); // correct module name when opening root of drive as project (RUBY-5181) + String imlName = baseDir.getPath() + "/.idea/" + moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION; + ModuleTypeManager instance = ModuleTypeManager.getInstance(); + String id = instance == null ? "unknown" : instance.getDefaultModuleType().getId(); + final Module module = moduleManager.newModule(imlName, id); + ModuleRootManager rootManager = ModuleRootManager.getInstance(module); + ModifiableRootModel rootModel = rootManager.getModifiableModel(); + if (rootModel.getContentRoots().length == 0) { + rootModel.addContentEntry(baseDir); } + rootModel.inheritSdk(); + rootModel.commit(); + moduleRef.set(module); }); } } diff --git a/platform/lang-impl/src/com/intellij/platform/PlatformProjectViewOpener.java b/platform/lang-impl/src/com/intellij/platform/PlatformProjectViewOpener.java index 954195af4564..4171782f715d 100644 --- a/platform/lang-impl/src/com/intellij/platform/PlatformProjectViewOpener.java +++ b/platform/lang-impl/src/com/intellij/platform/PlatformProjectViewOpener.java @@ -42,21 +42,13 @@ public class PlatformProjectViewOpener implements DirectoryProjectConfigurator { @Override public void run() { // ensure the dialog is shown after all startup activities are done - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; - final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW); - if (toolWindow != null && toolWindow.getType() != ToolWindowType.SLIDING) { - toolWindow.activate(null); - } - } - }, ModalityState.NON_MODAL); + SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; + final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW); + if (toolWindow != null && toolWindow.getType() != ToolWindowType.SLIDING) { + toolWindow.activate(null); } - }); + }, ModalityState.NON_MODAL)); } }); } diff --git a/platform/lang-impl/src/com/intellij/platform/renameProject/RenameProjectHandler.java b/platform/lang-impl/src/com/intellij/platform/renameProject/RenameProjectHandler.java index f8f70b508531..f7183a8c7a28 100644 --- a/platform/lang-impl/src/com/intellij/platform/renameProject/RenameProjectHandler.java +++ b/platform/lang-impl/src/com/intellij/platform/renameProject/RenameProjectHandler.java @@ -120,22 +120,9 @@ public class RenameProjectHandler implements RenameHandler, TitledHandler { return false; } final Ref success = Ref.create(Boolean.TRUE); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - modifiableModel.commit(); - } - }); - } - }); - } - }, IdeBundle.message("command.renaming.module", myModule.getName()), null); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> modifiableModel.commit()); + }), IdeBundle.message("command.renaming.module", myModule.getName()), null); return success.get().booleanValue(); } return true; diff --git a/platform/lang-impl/src/com/intellij/platform/templates/ArchivedProjectTemplate.java b/platform/lang-impl/src/com/intellij/platform/templates/ArchivedProjectTemplate.java index 2b1a8384ce34..2bb1f876598b 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/ArchivedProjectTemplate.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/ArchivedProjectTemplate.java @@ -130,12 +130,9 @@ public abstract class ArchivedProjectTemplate implements ProjectTemplate { private static List getFields(Element templateElement) { //noinspection unchecked return ContainerUtil - .mapNotNull(templateElement.getChildren(INPUT_FIELD), new Function() { - @Override - public WizardInputField fun(Element element) { - ProjectTemplateParameterFactory factory = WizardInputField.getFactoryById(element.getText()); - return factory == null ? null : factory.createField(element.getAttributeValue(INPUT_DEFAULT)); - } + .mapNotNull(templateElement.getChildren(INPUT_FIELD), element -> { + ProjectTemplateParameterFactory factory = WizardInputField.getFactoryById(element.getText()); + return factory == null ? null : factory.createField(element.getAttributeValue(INPUT_DEFAULT)); }); } diff --git a/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java b/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java index 99aea55e58a0..3965a81481c9 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java @@ -186,11 +186,7 @@ public class SaveProjectAsTemplateAction extends AnAction { } catch (Exception ex) { LOG.error(ex); - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - Messages.showErrorDialog(project, "Can't save project as template", "Internal Error"); - } - }); + UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(project, "Can't save project as template", "Internal Error")); } finally { StreamUtil.closeStream(stream); @@ -221,14 +217,12 @@ public class SaveProjectAsTemplateAction extends AnAction { public static Map computeParameters(final Project project, boolean replaceParameters) { final Map parameters = new HashMap(); if (replaceParameters) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - ProjectTemplateParameterFactory[] extensions = Extensions.getExtensions(ProjectTemplateParameterFactory.EP_NAME); - for (ProjectTemplateParameterFactory extension : extensions) { - String value = extension.detectParameterValue(project); - if (value != null) { - parameters.put(value, extension.getParameterId()); - } + ApplicationManager.getApplication().runReadAction(() -> { + ProjectTemplateParameterFactory[] extensions = Extensions.getExtensions(ProjectTemplateParameterFactory.EP_NAME); + for (ProjectTemplateParameterFactory extension : extensions) { + String value = extension.detectParameterValue(project); + if (value != null) { + parameters.put(value, extension.getParameterId()); } } }); diff --git a/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateDialog.java b/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateDialog.java index 3dca7491cccf..b5b72995bdf7 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateDialog.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/SaveProjectAsTemplateDialog.java @@ -71,11 +71,8 @@ public class SaveProjectAsTemplateDialog extends DialogWrapper { myModuleCombo.setVisible(false); } else { - List items = new ArrayList(ContainerUtil.map(modules, new Function() { - @Override - public String fun(Module module) { - return module.getName(); - } + List items = new ArrayList(ContainerUtil.map(modules, module -> { + return module.getName(); })); items.add(WHOLE_PROJECT); myModuleCombo.setModel(new CollectionComboBoxModel(items, WHOLE_PROJECT)); diff --git a/platform/lang-impl/src/com/intellij/platform/templates/TemplateModuleBuilder.java b/platform/lang-impl/src/com/intellij/platform/templates/TemplateModuleBuilder.java index b22f26d6fa29..18a021538fd6 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/TemplateModuleBuilder.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/TemplateModuleBuilder.java @@ -97,37 +97,26 @@ public class TemplateModuleBuilder extends ModuleBuilder { final Module[] modules = ModuleManager.getInstance(project).getModules(); if (modules.length > 0) { final Module module = modules[0]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - setupModule(module); - } - catch (ConfigurationException e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + setupModule(module); + } + catch (ConfigurationException e) { + LOG.error(e); } }); - StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - ModifiableModuleModel modifiableModuleModel = ModuleManager.getInstance(project).getModifiableModel(); - modifiableModuleModel.renameModule(module, module.getProject().getName()); - modifiableModuleModel.commit(); - fixModuleName(module); - } - catch (ModuleWithNameAlreadyExists exists) { - // do nothing - } - } - }); + StartupManager.getInstance(project).registerPostStartupActivity(() -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + ModifiableModuleModel modifiableModuleModel = ModuleManager.getInstance(project).getModifiableModel(); + modifiableModuleModel.renameModule(module, module.getProject().getName()); + modifiableModuleModel.commit(); + fixModuleName(module); } - }); + catch (ModuleWithNameAlreadyExists exists) { + // do nothing + } + })); return module; } return null; @@ -200,16 +189,12 @@ public class TemplateModuleBuilder extends ModuleBuilder { private void unzip(final @Nullable String projectName, String path, final boolean moduleMode) { final WizardInputField basePackage = getBasePackageField(); try { - final NullableFunction pathConvertor = new NullableFunction() { - @Nullable - @Override - public String fun(String path) { - if (moduleMode && path.contains(Project.DIRECTORY_STORE_FOLDER)) return null; - if (basePackage != null) { - return path.replace(getPathFragment(basePackage.getDefaultValue()), getPathFragment(basePackage.getValue())); - } - return path; + final NullableFunction pathConvertor = path1 -> { + if (moduleMode && path1.contains(Project.DIRECTORY_STORE_FOLDER)) return null; + if (basePackage != null) { + return path1.replace(getPathFragment(basePackage.getDefaultValue()), getPathFragment(basePackage.getValue())); } + return path1; }; final File dir = new File(path); diff --git a/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java b/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java index ac0af0927218..0061af90fc0b 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java @@ -113,18 +113,15 @@ public class DownloadUtil { while (true) { final Ref dataRef = Ref.create(null); final Ref innerExceptionRef = Ref.create(null); - boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - indicator.setText(actionShortDescription); - try { - V data = supplier.call(); - dataRef.set(data); - } - catch (Exception ex) { - innerExceptionRef.set(ex); - } + boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + indicator.setText(actionShortDescription); + try { + V data = supplier.call(); + dataRef.set(data); + } + catch (Exception ex) { + innerExceptionRef.set(ex); } }, progressTitle, true, project); if (!completed) { diff --git a/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java b/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java index 3eae9e04f919..68183c5612a3 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java @@ -69,20 +69,12 @@ public class ZipUtil { { final Outcome outcome = DownloadUtil.provideDataWithProgressSynchronously( project, progressTitle, "Unpacking ...", - new Callable() { - @Override - public Boolean call() throws IOException { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - unzip(progress, extractToDir, zipArchive, pathConvertor, null, unwrapSingleTopLevelFolder); - return true; - } + () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + unzip(progress, extractToDir, zipArchive, pathConvertor, null, unwrapSingleTopLevelFolder); + return true; }, - new Producer() { - @Override - public Boolean produce() { - return false; - } - } + () -> false ); Boolean result = outcome.get(); if (result == null) { diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionsAggregationUtil.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionsAggregationUtil.java index 3707c034ec04..797e606d8365 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionsAggregationUtil.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionsAggregationUtil.java @@ -32,11 +32,8 @@ import java.util.Set; */ public class InspectionsAggregationUtil { public static List getInspectionsKeys(final InspectionConfigTreeNode node) { - return ContainerUtil.map(getInspectionsNodes(node), new Function() { - @Override - public HighlightDisplayKey fun(final InspectionConfigTreeNode node) { - return node.getKey(); - } + return ContainerUtil.map(getInspectionsNodes(node), node1 -> { + return node1.getKey(); }); } diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java index e9bf7ea4e0df..6eb38127beed 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java @@ -313,13 +313,10 @@ public class SingleInspectionProfilePanel extends JPanel { @Override public void stateChanged() { //invoke after all other listeners - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (mySelectedProfile == null) return; //panel was disposed - updateProperSettingsForSelection(); - wereToolSettingsModified(); - } + SwingUtilities.invokeLater(() -> { + if (mySelectedProfile == null) return; //panel was disposed + updateProperSettingsForSelection(); + wereToolSettingsModified(); }); } }); @@ -403,12 +400,7 @@ public class SingleInspectionProfilePanel extends JPanel { Element newConfig = Descriptor.createConfigElement(state.getTool()); if (!JDOMUtil.areElementsEqual(oldConfig, newConfig)) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myTreeTable.repaint(); - } - }, 300); + myAlarm.addRequest(() -> myTreeTable.repaint(), 300); myModified = true; return true; } @@ -424,12 +416,7 @@ public class SingleInspectionProfilePanel extends JPanel { final boolean properSetting = mySelectedProfile.isProperSetting(descriptor.getKey().toString()); if (node.isProperSetting() != properSetting) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myTreeTable.repaint(); - } - }, 300); + myAlarm.addRequest(() -> myTreeTable.repaint(), 300); node.dropCache(); updateUpHierarchy((InspectionConfigTreeNode)node.getParent()); } @@ -856,19 +843,13 @@ public class SingleInspectionProfilePanel extends JPanel { } }; final HighlightSeverity severity = - ScopesAndSeveritiesTable.getSeverity(ContainerUtil.map(nodes, new Function() { - @Override - public ScopeToolState fun(InspectionConfigTreeNode node) { - return node.getDefaultDescriptor().getState(); - } + ScopesAndSeveritiesTable.getSeverity(ContainerUtil.map(nodes, node -> { + return node.getDefaultDescriptor().getState(); })); severityLevelChooser.setChosen(severity); - final ScopesChooser scopesChooser = new ScopesChooser(ContainerUtil.map(nodes, new Function() { - @Override - public Descriptor fun(final InspectionConfigTreeNode node) { - return node.getDefaultDescriptor(); - } + final ScopesChooser scopesChooser = new ScopesChooser(ContainerUtil.map(nodes, node -> { + return node.getDefaultDescriptor(); }), mySelectedProfile, project, null) { @Override protected void onScopesOrderChanged() { diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/ProfilesConfigurableComboBox.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/ProfilesConfigurableComboBox.java index ce9e4f3d26d6..9d74f06e38ee 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/ProfilesConfigurableComboBox.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/ProfilesConfigurableComboBox.java @@ -59,12 +59,7 @@ abstract class ProfilesConfigurableComboBox extends JPanel { mySubmitNameComponent = new ValidatedTextField(mySaveListener); myComboBoxPanel.add(mySubmitNameComponent, EDIT_CARD); - myComboModel = new SortedComboBoxModel(new Comparator() { - @Override - public int compare(final InspectionProfileImpl p1, final InspectionProfileImpl p2) { - return ProfilesConfigurableComboBox.this.compare(p1, p2); - } - }); + myComboModel = new SortedComboBoxModel((p1, p2) -> ProfilesConfigurableComboBox.this.compare(p1, p2)); myProfilesComboBox.setModel(myComboModel); //noinspection GtkPreferredJComboBoxRenderer myProfilesComboBox.setRenderer(new ListCellRenderer() { @@ -129,12 +124,7 @@ abstract class ProfilesConfigurableComboBox extends JPanel { mySaveListener.setDelegate(inputValidator); mySubmitNameComponent.setText(initialValue); myCardLayout.show(myComboBoxPanel, EDIT_CARD); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - mySubmitNameComponent.requestFocus(); - } - }); + SwingUtilities.invokeLater(() -> mySubmitNameComponent.requestFocus()); } void reset(final Collection profiles) { diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java index e3d6f9c138fb..f7a56134aad7 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java @@ -158,13 +158,8 @@ public class InspectionsConfigTreeTable extends TreeTable { protected Transferable createTransferable(JComponent c) { final TreePath path = getTree().getPathForRow(getTree().getLeadSelectionRow()); if (path != null) { - return new TextTransferable(StringUtil.join(ContainerUtil.mapNotNull(path.getPath(), new NullableFunction() { - @Nullable - @Override - public String fun(Object o) { - return o == path.getPath()[0] ? null : o.toString(); - } - }), " | ")); + return new TextTransferable(StringUtil.join(ContainerUtil.mapNotNull(path.getPath(), + (NullableFunction)o -> o == path.getPath()[0] ? null : o.toString()), " | ")); } return null; } @@ -221,11 +216,9 @@ public class InspectionsConfigTreeTable extends TreeTable { public InspectionsConfigTreeTableModel(final InspectionsConfigTreeTableSettings settings, Disposable parentDisposable) { super(settings.getRoot()); mySettings = settings; - myUpdateRunnable = new Runnable() { - public void run() { - settings.updateRightPanel(); - ((AbstractTableModel)myTreeTable.getModel()).fireTableDataChanged(); - } + myUpdateRunnable = () -> { + settings.updateRightPanel(); + ((AbstractTableModel)myTreeTable.getModel()).fireTableDataChanged(); }; myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, parentDisposable); } diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java index e4cbea7fd9ce..206486238c06 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java @@ -79,12 +79,7 @@ public class ScopesAndSeveritiesTable extends JBTable { final TableColumn severityColumn = columnModel.getColumn(SEVERITY_COLUMN); severityColumn.setCellRenderer(SeverityRenderer.create(tableSettings.getInspectionProfile(), null)); - severityColumn.setCellEditor(SeverityRenderer.create(tableSettings.getInspectionProfile(), new Runnable() { - @Override - public void run() { - tableSettings.onSettingsChanged(); - } - })); + severityColumn.setCellEditor(SeverityRenderer.create(tableSettings.getInspectionProfile(), () -> tableSettings.onSettingsChanged())); setColumnSelectionAllowed(false); setRowSelectionAllowed(true); @@ -412,11 +407,8 @@ public class ScopesAndSeveritiesTable extends JBTable { @Override public void addRow() { - final List descriptors = ContainerUtil.map(myTableSettings.getNodes(), new Function() { - @Override - public Descriptor fun(InspectionConfigTreeNode inspectionConfigTreeNode) { - return inspectionConfigTreeNode.getDefaultDescriptor(); - } + final List descriptors = ContainerUtil.map(myTableSettings.getNodes(), inspectionConfigTreeNode -> { + return inspectionConfigTreeNode.getDefaultDescriptor(); }); final ScopesChooser scopesChooser = new ScopesChooser(descriptors, myInspectionProfile, myProject, myScopeNames) { @Override diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/SeverityRenderer.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/SeverityRenderer.java index 52a66754c21e..104b6543eb27 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/SeverityRenderer.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/SeverityRenderer.java @@ -51,11 +51,8 @@ public class SeverityRenderer extends ComboBoxTableRenderer { public static SeverityRenderer create(final InspectionProfileImpl inspectionProfile, @Nullable final Runnable onClose) { final SortedSet severities = LevelChooserAction.getSeverities(((SeverityProvider)inspectionProfile.getProfileManager()).getOwnSeverityRegistrar()); - return new SeverityRenderer(ContainerUtil.map2Array(severities, new SeverityState[severities.size()], new Function() { - @Override - public SeverityState fun(HighlightSeverity severity) { - return new SeverityState(severity, true, false); - } + return new SeverityRenderer(ContainerUtil.map2Array(severities, new SeverityState[severities.size()], severity -> { + return new SeverityState(severity, true, false); }), onClose); } diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java index 98445d3d9145..36810a49c0cd 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java @@ -105,11 +105,8 @@ public class CodeStyleSettingsCodeFragmentFilter { final int rangeEnd = myTextRangeMarker.getEndOffset(); CharSequence textBefore = myDocument.getCharsSequence(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(myProject).reformatText(myFile, rangeStart, rangeEnd); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CodeStyleManager.getInstance(myProject).reformatText(myFile, rangeStart, rangeEnd); }); if (rangeStart != myTextRangeMarker.getStartOffset() || rangeEnd != myTextRangeMarker.getEndOffset()) { diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java index 45b469370155..739b9c94ca80 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java @@ -137,22 +137,19 @@ public class ArrangementEngine { DumbService.getInstance(file.getProject()).setAlternativeResolveEnabled(false); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { + if (documentEx != null) { + //documentEx.setInBulkUpdate(true); + } + try { + doArrange(context); + if (callback != null) { + callback.afterArrangement(context.moveInfos); + } + } + finally { if (documentEx != null) { - //documentEx.setInBulkUpdate(true); - } - try { - doArrange(context); - if (callback != null) { - callback.afterArrangement(context.moveInfos); - } - } - finally { - if (documentEx != null) { - //documentEx.setInBulkUpdate(false); - } + //documentEx.setInBulkUpdate(false); } } }); @@ -357,23 +354,20 @@ public class ArrangementEngine { for (E e : entries) { weights.put(e, ++i); } - ContainerUtil.sort(entries, new Comparator() { - @Override - public int compare(E e1, E e2) { - String name1 = e1 instanceof NameAwareArrangementEntry ? ((NameAwareArrangementEntry)e1).getName() : null; - String name2 = e2 instanceof NameAwareArrangementEntry ? ((NameAwareArrangementEntry)e2).getName() : null; - if (name1 != null && name2 != null) { - return name1.compareTo(name2); - } - else if (name1 == null && name2 == null) { - return weights.get(e1) - weights.get(e2); - } - else if (name2 == null) { - return -1; - } - else { - return 1; - } + ContainerUtil.sort(entries, (e1, e2) -> { + String name1 = e1 instanceof NameAwareArrangementEntry ? ((NameAwareArrangementEntry)e1).getName() : null; + String name2 = e2 instanceof NameAwareArrangementEntry ? ((NameAwareArrangementEntry)e2).getName() : null; + if (name1 != null && name2 != null) { + return name1.compareTo(name2); + } + else if (name1 == null && name2 == null) { + return weights.get(e1) - weights.get(e2); + } + else if (name2 == null) { + return -1; + } + else { + return 1; } }); } diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/RestoreFoldArrangementCallback.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/RestoreFoldArrangementCallback.java index b23b79c8c88b..142e9b2e35df 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/RestoreFoldArrangementCallback.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/RestoreFoldArrangementCallback.java @@ -50,14 +50,11 @@ public class RestoreFoldArrangementCallback implements ArrangementCallback { final CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(project); foldingManager.updateFoldRegions(myEditor); - myEditor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegionInfo info : foldRegionsInfo) { - final FoldRegion foldRegion = foldingManager.findFoldRegion(myEditor, info.myStart, info.myEnd); - if (foldRegion != null) { - foldRegion.setExpanded(info.myIsExpanded); - } + myEditor.getFoldingModel().runBatchFoldingOperation(() -> { + for (FoldRegionInfo info : foldRegionsInfo) { + final FoldRegion foldRegion = foldingManager.findFoldRegion(myEditor, info.myStart, info.myEnd); + if (foldRegion != null) { + foldRegion.setExpanded(info.myIsExpanded); } } }); diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectableIndentOptionsProvider.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectableIndentOptionsProvider.java index 581d1f059440..557fb388544d 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectableIndentOptionsProvider.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectableIndentOptionsProvider.java @@ -103,35 +103,22 @@ public class DetectableIndentOptionsProvider extends FileIndentOptionsProvider i ActionLabelData okAction = new ActionLabelData( ApplicationBundle.message("code.style.indents.detector.accept"), - new Runnable() { - @Override - public void run() { - setAccepted(file); - } - } + () -> setAccepted(file) ); ActionLabelData disableForSingleFile = new ActionLabelData( labels.revertToOldSettingsLabel, - new Runnable() { - @Override - public void run() { - disableForFile(file); - if (editor instanceof EditorEx) { - ((EditorEx)editor).reinitSettings(); - } + () -> { + disableForFile(file); + if (editor instanceof EditorEx) { + ((EditorEx)editor).reinitSettings(); } } ); ActionLabelData showSettings = new ActionLabelData( ApplicationBundle.message("code.style.indents.detector.show.settings"), - new Runnable() { - @Override - public void run() { - ShowSettingsUtilImpl.showSettingsDialog(project, "preferences.sourceCode", "detect indent"); - } - } + () -> ShowSettingsUtilImpl.showSettingsDialog(project, "preferences.sourceCode", "detect indent") ); final List actions = ContainerUtil.newArrayList(okAction, disableForSingleFile, showSettings); diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectedIndentOptionsNotificationProvider.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectedIndentOptionsNotificationProvider.java index c2450d4d5e35..072d297fb842 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectedIndentOptionsNotificationProvider.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/DetectedIndentOptionsNotificationProvider.java @@ -71,12 +71,9 @@ public class DetectedIndentOptionsNotificationProvider extends EditorNotificatio CommonCodeStyleSettings.IndentOptions userOptions = settings.getIndentOptions(psiFile.getFileType()); CommonCodeStyleSettings.IndentOptions detectedOptions = CodeStyleSettingsManager.getSettings(project).getIndentOptionsByFile( psiFile, null, false, - new Processor() { - @Override - public boolean process(FileIndentOptionsProvider provider) { - indentOptionsProviderRef.set(provider); - return false; - } + provider -> { + indentOptionsProviderRef.set(provider); + return false; }); final FileIndentOptionsProvider provider = indentOptionsProviderRef.get(); EditorNotificationInfo info = provider != null && !provider.isAcceptedWithoutWarning(project, file) && !userOptions.equals(detectedOptions) @@ -89,12 +86,9 @@ public class DetectedIndentOptionsNotificationProvider extends EditorNotificatio panel.icon(info.getIcon()); } for (final ActionLabelData actionLabelData : info.getLabelAndActions()) { - Runnable onClickAction = new Runnable() { - @Override - public void run() { - actionLabelData.action.run(); - EditorNotifications.getInstance(project).updateAllNotifications(); - } + Runnable onClickAction = () -> { + actionLabelData.action.run(); + EditorNotifications.getInstance(project).updateAllNotifications(); }; panel.createActionLabel(actionLabelData.label, onClickAction); } diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/FormatterBasedLineIndentInfoBuilder.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/FormatterBasedLineIndentInfoBuilder.java index c2dcc49b328d..b1c70a08c18b 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/FormatterBasedLineIndentInfoBuilder.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/FormatterBasedLineIndentInfoBuilder.java @@ -48,23 +48,20 @@ public class FormatterBasedLineIndentInfoBuilder { public List build() { List newLineBlocks = getBlocksStartingNewLine(); - return ContainerUtil.map(newLineBlocks, new Function() { - @Override - public LineIndentInfo fun(Block newLineBlock) { - int blockStartOffset = newLineBlock.getTextRange().getStartOffset(); - int line = myDocument.getLineNumber(blockStartOffset); - int lineStartOffset = myDocument.getLineStartOffset(line); + return ContainerUtil.map(newLineBlocks, newLineBlock -> { + int blockStartOffset = newLineBlock.getTextRange().getStartOffset(); + int line = myDocument.getLineNumber(blockStartOffset); + int lineStartOffset = myDocument.getLineStartOffset(line); - if (rangeHasTabs(lineStartOffset, blockStartOffset)) { - return LineIndentInfo.LINE_WITH_TABS; - } - - if (hasNormalIndent(newLineBlock)) { - return LineIndentInfo.newNormalIndent(blockStartOffset - lineStartOffset); - } - else { - return LineIndentInfo.LINE_WITH_NOT_COUNTABLE_INDENT; - } + if (rangeHasTabs(lineStartOffset, blockStartOffset)) { + return LineIndentInfo.LINE_WITH_TABS; + } + + if (hasNormalIndent(newLineBlock)) { + return LineIndentInfo.newNormalIndent(blockStartOffset - lineStartOffset); + } + else { + return LineIndentInfo.LINE_WITH_NOT_COUNTABLE_INDENT; } }); } diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/IndentUsageStatisticsImpl.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/IndentUsageStatisticsImpl.java index 82ce76a60af3..6b6b89fcc853 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/IndentUsageStatisticsImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/autodetect/IndentUsageStatisticsImpl.java @@ -25,12 +25,8 @@ import java.util.Comparator; import java.util.List; public class IndentUsageStatisticsImpl implements IndentUsageStatistics { - private static final Comparator DECREASING_ORDER = new Comparator() { - @Override - public int compare(@NotNull IndentUsageInfo o1, @NotNull IndentUsageInfo o2) { - return o1.getTimesUsed() < o2.getTimesUsed() ? 1 : o1.getTimesUsed() == o2.getTimesUsed() ? 0 : -1; - } - }; + private static final Comparator DECREASING_ORDER = + (o1, o2) -> o1.getTimesUsed() < o2.getTimesUsed() ? 1 : o1.getTimesUsed() == o2.getTimesUsed() ? 0 : -1; private List myLineInfos; diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/extractor/ExtractCodeStyleAction.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/extractor/ExtractCodeStyleAction.java index 3b39472805a3..a9674b934b59 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/extractor/ExtractCodeStyleAction.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/extractor/ExtractCodeStyleAction.java @@ -160,18 +160,15 @@ public class ExtractCodeStyleAction extends AnAction implements DumbAware { ApplicationManager.getApplication(). - invokeLater(new Runnable() { - @Override - public void run () { - Window window = WindowManager.getInstance().getFrame(project); - if (window == null) { - window = JOptionPane.getRootFrame(); - } - if (window instanceof IdeFrame) { - BalloonLayout layout = ((IdeFrame) window).getBalloonLayout(); - if (layout != null) { - layout.add(balloon); - } + invokeLater(() -> { + Window window = WindowManager.getInstance().getFrame(project); + if (window == null) { + window = JOptionPane.getRootFrame(); + } + if (window instanceof IdeFrame) { + BalloonLayout layout = ((IdeFrame) window).getBalloonLayout(); + if (layout != null) { + layout.add(balloon); } } } diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java b/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java index 566bd4b8ae43..ae123607adc5 100644 --- a/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java +++ b/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java @@ -154,11 +154,8 @@ public final class InjectedLanguageBlockWrapper implements BlockEx { if (spacing instanceof DependantSpacingImpl && shift != 0) { DependantSpacingImpl hostSpacing = (DependantSpacingImpl)spacing; final int finalShift = shift; - List shiftedRanges = ContainerUtil.map(hostSpacing.getDependentRegionRanges(), new Function() { - @Override - public TextRange fun(TextRange range) { - return range.shiftRight(finalShift); - } + List shiftedRanges = ContainerUtil.map(hostSpacing.getDependentRegionRanges(), range -> { + return range.shiftRight(finalShift); }); return new DependantSpacingImpl( hostSpacing.getMinSpaces(), hostSpacing.getMaxSpaces(), shiftedRanges, diff --git a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java index c8575408e88b..3eaae901b6f7 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java @@ -43,12 +43,7 @@ public class IdIndexImpl extends IdIndex implements CustomInputsIndexFileBasedIn @Override public int getVersion() { FileType[] types = myFileTypeManager.getRegisteredFileTypes(); - Arrays.sort(types, new Comparator() { - @Override - public int compare(FileType o1, FileType o2) { - return Comparing.compare(o1.getName(), o2.getName()); - } - }); + Arrays.sort(types, (o1, o2) -> Comparing.compare(o1.getName(), o2.getName())); int version = super.getVersion(); for(FileType fileType:types) { diff --git a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java index f85e73dbdad9..bc0b02f49c8d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java @@ -103,19 +103,16 @@ public class PsiVFSListener extends VirtualFileAdapter { myConnection = project.getMessageBus().connect(project); - StartupManager.getInstance(project).registerPreStartupActivity(new Runnable() { - @Override - public void run() { - myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener()); - myConnection.subscribe(FileTypeManager.TOPIC, new FileTypeListener.Adapter() { - @Override - public void fileTypesChanged(@NotNull FileTypeEvent e) { - myFileManager.processFileTypesChanged(); - } - }); - myConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new MyFileDocumentManagerAdapter()); - myFileManager.markInitialized(); - } + StartupManager.getInstance(project).registerPreStartupActivity(() -> { + myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener()); + myConnection.subscribe(FileTypeManager.TOPIC, new FileTypeListener.Adapter() { + @Override + public void fileTypesChanged(@NotNull FileTypeEvent e) { + myFileManager.processFileTypesChanged(); + } + }); + myConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new MyFileDocumentManagerAdapter()); + myFileManager.markInitialized(); }); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/include/FileIncludeManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/include/FileIncludeManagerImpl.java index a79e85e91f4d..96d4a9163378 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/include/FileIncludeManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/include/FileIncludeManagerImpl.java @@ -60,18 +60,14 @@ public class FileIncludeManagerImpl extends FileIncludeManager { @Override protected VirtualFile[] computeFiles(final PsiFile file, final boolean compileTimeOnly) { final Set files = new THashSet(); - processIncludes(file, new Processor() { - @Override - public boolean process(FileIncludeInfo info) { - if (compileTimeOnly != info.runtimeOnly) { - PsiFileSystemItem item = resolveFileInclude(info, file); - if (item != null) { - ContainerUtil.addIfNotNull(files, item.getVirtualFile()); - } + processIncludes(file, info -> { + if (compileTimeOnly != info.runtimeOnly) { + PsiFileSystemItem item = resolveFileInclude(info, file); + if (item != null) { + ContainerUtil.addIfNotNull(files, item.getVirtualFile()); } - return true; } - + return true; }); return VfsUtilCore.toVirtualFileArray(files); } @@ -92,12 +88,9 @@ public class FileIncludeManagerImpl extends FileIncludeManager { @Override protected VirtualFile[] computeFiles(PsiFile context, boolean compileTimeOnly) { final Set files = new THashSet(); - processIncludingFiles(context, new Processor>() { - @Override - public boolean process(Pair virtualFileFileIncludeInfoPair) { - files.add(virtualFileFileIncludeInfoPair.first); - return true; - } + processIncludingFiles(context, virtualFileFileIncludeInfoPair -> { + files.add(virtualFileFileIncludeInfoPair.first); + return true; }); return VfsUtilCore.toVirtualFileArray(files); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/PostprocessReformattingAspect.java b/platform/lang-impl/src/com/intellij/psi/impl/source/PostprocessReformattingAspect.java index ce8aaacc2965..1f95e40847c4 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/PostprocessReformattingAspect.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/PostprocessReformattingAspect.java @@ -163,11 +163,8 @@ public class PostprocessReformattingAspect implements PomModelAspect { doPostponedFormatting(); } else { - application.runWriteAction(new Runnable() { - @Override - public void run() { - doPostponedFormatting(); - } + application.runWriteAction(() -> { + doPostponedFormatting(); }); } } @@ -223,23 +220,20 @@ public class PostprocessReformattingAspect implements PomModelAspect { } public void doPostponedFormatting() { - atomic(new Runnable() { - @Override - public void run() { - if (isDisabled()) return; - try { - FileViewProvider[] viewProviders = getContext().myUpdatedProviders.toArray(new FileViewProvider[getContext().myUpdatedProviders.size()]); - for (final FileViewProvider viewProvider : viewProviders) { - doPostponedFormatting(viewProvider); - } - } - catch (Exception e) { - LOG.error(e); - } - finally { - LOG.assertTrue(getContext().myReformatElements.isEmpty(), getContext().myReformatElements); + atomic(() -> { + if (isDisabled()) return; + try { + FileViewProvider[] viewProviders = getContext().myUpdatedProviders.toArray(new FileViewProvider[getContext().myUpdatedProviders.size()]); + for (final FileViewProvider viewProvider : viewProviders) { + doPostponedFormatting(viewProvider); } } + catch (Exception e) { + LOG.error(e); + } + finally { + LOG.assertTrue(getContext().myReformatElements.isEmpty(), getContext().myReformatElements); + } }); } @@ -252,24 +246,16 @@ public class PostprocessReformattingAspect implements PomModelAspect { } private void postponedFormattingImpl(@NotNull final FileViewProvider viewProvider, final boolean check) { - atomic(new Runnable() { - @Override - public void run() { - if (isDisabled() || check && !getContext().myUpdatedProviders.contains(viewProvider)) return; + atomic(() -> { + if (isDisabled() || check && !getContext().myUpdatedProviders.contains(viewProvider)) return; - try { - disablePostprocessFormattingInside(new Runnable() { - @Override - public void run() { - doPostponedFormattingInner(viewProvider); - } - }); - } - finally { - getContext().myUpdatedProviders.remove(viewProvider); - getContext().myReformatElements.remove(viewProvider); - viewProvider.putUserData(REFORMAT_ORIGINATOR, null); - } + try { + disablePostprocessFormattingInside(() -> doPostponedFormattingInner(viewProvider)); + } + finally { + getContext().myUpdatedProviders.remove(viewProvider); + getContext().myReformatElements.remove(viewProvider); + viewProvider.putUserData(REFORMAT_ORIGINATOR, null); } }); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java index c7bd4fd558d4..54af3dadf310 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java @@ -443,16 +443,13 @@ public class CodeFormatterFacade { } try { final Editor editorToUse = editor; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final CaretModel caretModel = editorToUse.getCaretModel(); - final int caretOffset = caretModel.getOffset(); - final RangeMarker caretMarker = editorToUse.getDocument().createRangeMarker(caretOffset, caretOffset); - doWrapLongLinesIfNecessary(editorToUse, file.getProject(), editorToUse.getDocument(), startOffset, endOffset); - if (caretMarker.isValid() && caretModel.getOffset() != caretMarker.getStartOffset()) { - caretModel.moveToOffset(caretMarker.getStartOffset()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final CaretModel caretModel = editorToUse.getCaretModel(); + final int caretOffset = caretModel.getOffset(); + final RangeMarker caretMarker = editorToUse.getDocument().createRangeMarker(caretOffset, caretOffset); + doWrapLongLinesIfNecessary(editorToUse, file.getProject(), editorToUse.getDocument(), startOffset, endOffset); + if (caretMarker.isValid() && caretModel.getOffset() != caretMarker.getStartOffset()) { + caretModel.moveToOffset(caretMarker.getStartOffset()); } }); } @@ -557,12 +554,8 @@ public class CodeFormatterFacade { DataManager.getInstance().saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true); CommandProcessor commandProcessor = CommandProcessor.getInstance(); try { - Runnable command = new Runnable() { - @Override - public void run() { - EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor, dataContext); - } - }; + Runnable command = + () -> EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor, dataContext); if (commandProcessor.getCurrentCommand() == null) { commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java index d539bb0b3f26..588d396b7444 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java @@ -461,18 +461,15 @@ public class MultiHostRegistrarImpl implements MultiHostRegistrar, ModificationT assert shreds.isValid(); if (!oldFile.textMatches(injectedPsi)) { - oldViewProvider.performNonPhysically(new Runnable() { - @Override - public void run() { - DebugUtil.startPsiModification("injected tree diff"); - try { - final DiffLog diffLog = BlockSupportImpl.mergeTrees(oldFile, oldFileNode, injectedNode, new DaemonProgressIndicator(), - oldFileNode.getText()); - DocumentCommitThread.doActualPsiChange(oldFile, diffLog); - } - finally { - DebugUtil.finishPsiModification(); - } + oldViewProvider.performNonPhysically(() -> { + DebugUtil.startPsiModification("injected tree diff"); + try { + final DiffLog diffLog = BlockSupportImpl.mergeTrees(oldFile, oldFileNode, injectedNode, new DaemonProgressIndicator(), + oldFileNode.getText()); + DocumentCommitThread.doActualPsiChange(oldFile, diffLog); + } + finally { + DebugUtil.finishPsiModification(); } }); } @@ -578,11 +575,8 @@ public class MultiHostRegistrarImpl implements MultiHostRegistrar, ModificationT Place shreds = window.getShreds(); Project project = shreds.getHostPointer().getProject(); DocumentEx delegate = ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(project)).getLastCommittedDocument(window.getDelegate()); - Place place = new Place(ContainerUtil.map(shreds, new Function() { - @Override - public PsiLanguageInjectionHost.Shred fun(final PsiLanguageInjectionHost.Shred shred) { - return ((ShredImpl) shred).withPsiRange(); - } + Place place = new Place(ContainerUtil.map(shreds, shred -> { + return ((ShredImpl) shred).withPsiRange(); })); return new DocumentWindowImpl(delegate, window.isOneLine(), place); } diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/SerializationManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/SerializationManagerImpl.java index 1411e836b436..9cc706b22ad8 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/SerializationManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/SerializationManagerImpl.java @@ -58,12 +58,7 @@ public class SerializationManagerImpl extends SerializationManagerEx implements } finally { registerSerializer(PsiFileStubImpl.TYPE); - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - performShutdown(); - } - }); + ShutDownTracker.getInstance().registerShutdownTask(() -> performShutdown()); } } diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java index 35c4a054aa29..91a28916b05f 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java @@ -698,14 +698,11 @@ public class StubIndexImpl extends StubIndex implements ApplicationComponent, Pe protected void prepare() { boolean forceClean = Boolean.TRUE == ourForcedClean.getAndSet(Boolean.FALSE); for (StubIndexExtension extension : myExtensions) { - addNestedInitializationTask(new ThrowableRunnable() { - @Override - public void run() throws IOException { - @SuppressWarnings("unchecked") boolean rebuildRequested = registerIndexer(extension, forceClean, state); - if (rebuildRequested) { - synchronized (updated) { - updated.append(extension).append(' '); - } + addNestedInitializationTask(() -> { + @SuppressWarnings("unchecked") boolean rebuildRequested = registerIndexer(extension, forceClean, state); + if (rebuildRequested) { + synchronized (updated) { + updated.append(extension).append(' '); } } }); @@ -722,11 +719,8 @@ public class StubIndexImpl extends StubIndex implements ApplicationComponent, Pe if (updated.length() > 0) { final Throwable e = new Throwable(updated.toString()); // avoid direct forceRebuild as it produces dependency cycle (IDEA-105485) - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - forceRebuild(e); - } + ApplicationManager.getApplication().invokeLater(() -> { + forceRebuild(e); }, ModalityState.NON_MODAL); } dropUnregisteredIndices(state); diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubProcessingHelper.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubProcessingHelper.java index 4858350c5a79..1c42e63533f9 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubProcessingHelper.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubProcessingHelper.java @@ -25,11 +25,8 @@ public class StubProcessingHelper extends StubProcessingHelperBase { protected void onInternalError(final VirtualFile file) { // requestReindex() may want to acquire write lock (for indices not requiring content loading) // thus, because here we are under read lock, need to use invoke later - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myFileBasedIndex.requestReindex(file); - } + ApplicationManager.getApplication().invokeLater(() -> { + myFileBasedIndex.requestReindex(file); }, ModalityState.NON_MODAL); } diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java index d44abf71d787..2c29125d892f 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java @@ -143,13 +143,10 @@ public class StubTreeLoaderImpl extends StubTreeLoader { private static ObjectStubTree processError(final VirtualFile vFile, String message, @Nullable Exception e) { LOG.error(message, e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final Document doc = FileDocumentManager.getInstance().getCachedDocument(vFile); - if (doc != null) { - FileDocumentManager.getInstance().saveDocument(doc); - } + ApplicationManager.getApplication().invokeLater(() -> { + final Document doc = FileDocumentManager.getInstance().getCachedDocument(vFile); + if (doc != null) { + FileDocumentManager.getInstance().saveDocument(doc); } }, ModalityState.NON_MODAL); diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java index 3c1230170729..aa7320494190 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java @@ -205,45 +205,42 @@ public class StubUpdatingIndex extends CustomImplementationFileBasedIndexExtensi } }; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final Stub rootStub = StubTreeBuilder.buildStubTree(inputData); - if (rootStub == null) return; + ApplicationManager.getApplication().runReadAction(() -> { + final Stub rootStub = StubTreeBuilder.buildStubTree(inputData); + if (rootStub == null) return; - VirtualFile file = inputData.getFile(); - int contentLength; - if (file.getFileType().isBinary()) { - contentLength = -1; - } - else { - contentLength = ((FileContentImpl)inputData).getPsiFileForPsiDependentIndex().getTextLength(); - } - rememberIndexingStamp(file, contentLength); + VirtualFile file = inputData.getFile(); + int contentLength; + if (file.getFileType().isBinary()) { + contentLength = -1; + } + else { + contentLength = ((FileContentImpl)inputData).getPsiFileForPsiDependentIndex().getTextLength(); + } + rememberIndexingStamp(file, contentLength); - final BufferExposingByteArrayOutputStream bytes = new BufferExposingByteArrayOutputStream(); - SerializationManagerEx.getInstanceEx().serialize(rootStub, bytes); + final BufferExposingByteArrayOutputStream bytes = new BufferExposingByteArrayOutputStream(); + SerializationManagerEx.getInstanceEx().serialize(rootStub, bytes); - if (DebugAssertions.DEBUG) { - try { - Stub deserialized = - SerializationManagerEx.getInstanceEx().deserialize(new ByteArrayInputStream(bytes.getInternalBuffer(), 0, bytes.size())); - check(deserialized, rootStub); - } catch(ProcessCanceledException pce) { - throw pce; - } catch (Throwable t) { - LOG.error("Error indexing:" + file, t); - } - } - final int key = Math.abs(FileBasedIndex.getFileId(file)); - SerializedStubTree serializedStubTree = new SerializedStubTree(bytes.getInternalBuffer(), bytes.size(), rootStub, file.getLength(), contentLength); - result.put(key, serializedStubTree); + if (DebugAssertions.DEBUG) { try { - ((StubUpdatingIndexKeys)result.keySet()).myStubIndicesValueMap = calcStubIndicesValueMap(serializedStubTree, key); - } catch (StorageException ex) { - throw new RuntimeException(ex); + Stub deserialized = + SerializationManagerEx.getInstanceEx().deserialize(new ByteArrayInputStream(bytes.getInternalBuffer(), 0, bytes.size())); + check(deserialized, rootStub); + } catch(ProcessCanceledException pce) { + throw pce; + } catch (Throwable t) { + LOG.error("Error indexing:" + file, t); } } + final int key = Math.abs(FileBasedIndex.getFileId(file)); + SerializedStubTree serializedStubTree = new SerializedStubTree(bytes.getInternalBuffer(), bytes.size(), rootStub, file.getLength(), contentLength); + result.put(key, serializedStubTree); + try { + ((StubUpdatingIndexKeys)result.keySet()).myStubIndicesValueMap = calcStubIndicesValueMap(serializedStubTree, key); + } catch (StorageException ex) { + throw new RuntimeException(ex); + } }); return result; diff --git a/platform/lang-impl/src/com/intellij/psi/templateLanguages/ChangeTemplateDataLanguageAction.java b/platform/lang-impl/src/com/intellij/psi/templateLanguages/ChangeTemplateDataLanguageAction.java index 1dbf37cb29d5..a78557755858 100644 --- a/platform/lang-impl/src/com/intellij/psi/templateLanguages/ChangeTemplateDataLanguageAction.java +++ b/platform/lang-impl/src/com/intellij/psi/templateLanguages/ChangeTemplateDataLanguageAction.java @@ -66,12 +66,9 @@ public class ChangeTemplateDataLanguageAction extends AnAction { public static void editSettings(@NotNull Project project, @Nullable final VirtualFile virtualFile) { final TemplateDataLanguageConfigurable configurable = new TemplateDataLanguageConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - if (virtualFile != null) { - configurable.selectFile(virtualFile); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + if (virtualFile != null) { + configurable.selectFile(virtualFile); } }); } diff --git a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataLanguagePatterns.java b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataLanguagePatterns.java index 784bfd8492a3..dda33562fc5e 100644 --- a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataLanguagePatterns.java +++ b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateDataLanguagePatterns.java @@ -90,11 +90,8 @@ public class TemplateDataLanguagePatterns implements PersistentStateComponent() { - @Override - public String fun(FileNameMatcher fileNameMatcher) { - return fileNameMatcher.getPresentableString(); - } + child.setAttribute("value", StringUtil.join(matchers, fileNameMatcher -> { + return fileNameMatcher.getPresentableString(); }, SEPARATOR)); child.setAttribute("lang", language.getID()); } diff --git a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java index 3848f14e7c02..1fdeac6cafc3 100644 --- a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java +++ b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java @@ -74,12 +74,9 @@ public class TemplateLanguageErrorQuickFixProvider implements ErrorQuickFixProvi @Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { final TemplateDataLanguageConfigurable configurable = new TemplateDataLanguageConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - if (virtualFile != null) { - configurable.selectFile(virtualFile); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + if (virtualFile != null) { + configurable.selectFile(virtualFile); } }); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/IntroduceTargetChooser.java b/platform/lang-impl/src/com/intellij/refactoring/IntroduceTargetChooser.java index 4a91d11ed79d..f90f6c23b04e 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/IntroduceTargetChooser.java +++ b/platform/lang-impl/src/com/intellij/refactoring/IntroduceTargetChooser.java @@ -123,14 +123,11 @@ public class IntroduceTargetChooser { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - SmartPsiElementPointer value = (SmartPsiElementPointer)list.getSelectedValue(); - T expr = value != null ? value.getElement() : null; - if (expr != null) { - callback.pass(expr); - } + .setItemChoosenCallback(() -> { + SmartPsiElementPointer value = (SmartPsiElementPointer)list.getSelectedValue(); + T expr = value != null ? value.getElement() : null; + if (expr != null) { + callback.pass(expr); } }) .addListener(new JBPopupAdapter() { diff --git a/platform/lang-impl/src/com/intellij/refactoring/actions/BaseRefactoringAction.java b/platform/lang-impl/src/com/intellij/refactoring/actions/BaseRefactoringAction.java index 8c5f3458b5d8..8e2c7334e2f3 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/actions/BaseRefactoringAction.java +++ b/platform/lang-impl/src/com/intellij/refactoring/actions/BaseRefactoringAction.java @@ -112,12 +112,7 @@ public abstract class BaseRefactoringAction extends AnAction { if (InplaceRefactoring.getActiveInplaceRenamer(editor) == null) { final LookupEx lookup = LookupManager.getActiveLookup(editor); if (lookup instanceof LookupImpl) { - Runnable command = new Runnable() { - @Override - public void run() { - ((LookupImpl)lookup).finishLookup(Lookup.NORMAL_SELECT_CHAR); - } - }; + Runnable command = () -> ((LookupImpl)lookup).finishLookup(Lookup.NORMAL_SELECT_CHAR); assert editor != null; Document doc = editor.getDocument(); DocCommandGroupId group = DocCommandGroupId.noneGroupId(doc); diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/CallerChooserBase.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/CallerChooserBase.java index 6e0ec0b218c3..0f9a370aadc5 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/CallerChooserBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/CallerChooserBase.java @@ -114,12 +114,7 @@ public abstract class CallerChooserBase extends DialogWrap if (path != null) { final MethodNodeBase node = (MethodNodeBase)path.getLastPathComponent(); myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - updateEditorTexts(node); - } - }, 300); + myAlarm.addRequest(() -> updateEditorTexts(node), 300); } } }; @@ -150,12 +145,9 @@ public abstract class CallerChooserBase extends DialogWrap final String calleeText = node != myRoot ? getText(parentNode.getMethod()) : getEmptyCalleeText(); final Document calleeDocument = myCalleeEditor.getDocument(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - callerDocument.setText(callerText); - calleeDocument.setText(calleeText); - } + ApplicationManager.getApplication().runWriteAction(() -> { + callerDocument.setText(callerText); + calleeDocument.setText(calleeText); }); final M caller = callerNode.getMethod(); @@ -182,11 +174,8 @@ public abstract class CallerChooserBase extends DialogWrap protected Collection findElementsToHighlight(M caller, PsiElement callee) { Query references = ReferencesSearch.search(callee, new LocalSearchScope(caller), false); - return ContainerUtil.mapNotNull(references, new Function() { - @Override - public PsiElement fun(PsiReference psiReference) { - return psiReference.getElement(); - } + return ContainerUtil.mapNotNull(references, psiReference -> { + return psiReference.getElement(); }); } @@ -243,15 +232,12 @@ public abstract class CallerChooserBase extends DialogWrap } private Tree createTree() { - final Runnable cancelCallback = new Runnable() { - @Override - public void run() { - if (myInitDone) { - close(CANCEL_EXIT_CODE); - } - else { - throw new ProcessCanceledException(); - } + final Runnable cancelCallback = () -> { + if (myInitDone) { + close(CANCEL_EXIT_CODE); + } + else { + throw new ProcessCanceledException(); } }; final CheckedTreeNode root = createTreeNode(null, new HashSet(), cancelCallback); diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialogBase.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialogBase.java index 2c9c8283c794..7a4c2f12dd04 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialogBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureDialogBase.java @@ -353,12 +353,9 @@ public abstract class ChangeSignatureDialogBase> chooser = new Ref>(); - Consumer> callback = new Consumer>() { - @Override - public void consume(Set callers) { - myMethodsToPropagateParameters = callers; - myParameterPropagationTreeToReuse = chooser.get().getTree(); - } + Consumer> callback = callers -> { + myMethodsToPropagateParameters = callers; + myParameterPropagationTreeToReuse = chooser.get().getTree(); }; try { String message = RefactoringBundle.message("changeSignature.parameter.caller.chooser"); @@ -596,18 +593,10 @@ public abstract class ChangeSignatureDialogBase { + if (myDisposed) return; + myUpdateSignatureAlarm.cancelAllRequests(); + myUpdateSignatureAlarm.addRequest(() -> updateSignatureAlarmFired(), 100, ModalityState.stateForComponent(mySignatureArea)); }; //noinspection SSBasedInspection SwingUtilities.invokeLater(updateRunnable); diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java index 247bee2e0726..f11fbf794e93 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java @@ -94,17 +94,9 @@ public abstract class MethodNodeBase extends CheckedTreeNo private List findCallers() { if (myMethod == null) return Collections.emptyList(); final Ref> callers = new Ref>(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - callers.set(ContainerUtil.filter(computeCallers(), getFilter())); - } - }); - } - }, RefactoringBundle.message("caller.chooser.looking.for.callers"), true, myProject)) { + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + callers.set(ContainerUtil.filter(computeCallers(), getFilter())); + }), RefactoringBundle.message("caller.chooser.looking.for.callers"), true, myProject)) { myCancelCallback.run(); return Collections.emptyList(); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/RenameChangeInfo.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/RenameChangeInfo.java index 5295b1635ea3..46f06774b2bf 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/RenameChangeInfo.java +++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/RenameChangeInfo.java @@ -94,11 +94,8 @@ public abstract class RenameChangeInfo implements ChangeInfo { final PsiNameIdentifierOwner element = getNamedElement(); if (element != null) { final String name = element.getName(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - element.setName(myOldName); - } + ApplicationManager.getApplication().runWriteAction(() -> { + element.setName(myOldName); }); new RenameProcessor(element.getProject(), element, name, false, false).run(); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java b/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java index fd587f813e48..5ae5a67a0590 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java @@ -283,21 +283,13 @@ public class CopyFilesOrDirectoriesDialog extends DialogWrapper { RecentsManager.getInstance(myProject).registerRecentEntry(RECENT_KEYS, targetDirectoryName); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - String path = FileUtil.toSystemIndependentName(targetDirectoryName); - myTargetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(myProject), path); - } - catch (IncorrectOperationException ignored) { } - } - }); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + String path = FileUtil.toSystemIndependentName(targetDirectoryName); + myTargetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(myProject), path); } - }, RefactoringBundle.message("create.directory"), null); + catch (IncorrectOperationException ignored) { } + }), RefactoringBundle.message("create.directory"), null); if (myTargetDirectory == null) { Messages.showErrorDialog(myProject, RefactoringBundle.message("cannot.create.directory"), RefactoringBundle.message("error.title")); diff --git a/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesHandler.java b/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesHandler.java index efe70aced631..217a884d1307 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesHandler.java @@ -233,30 +233,17 @@ public class CopyFilesOrDirectoriesHandler extends CopyHandlerDelegateBase { CopyHandler.updateSelectionInActiveProjectView(firstFile, getProject(), doClone); if (!(firstFile instanceof PsiBinaryFile)) { EditorHelper.openInEditor(firstFile); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ToolWindowManager.getInstance(getProject()).activateEditorComponent(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ToolWindowManager.getInstance(getProject()).activateEditorComponent()); } } } catch (final IncorrectOperationException ex) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(getProject(), ex.getMessage(), RefactoringBundle.message("error.title")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(getProject(), ex.getMessage(), RefactoringBundle.message("error.title"))); } catch (final IOException ex) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(getProject(), ex.getMessage(), RefactoringBundle.message("error.title")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(getProject(), ex.getMessage(), RefactoringBundle.message("error.title"))); } } }.execute(); diff --git a/platform/lang-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHelper.java b/platform/lang-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHelper.java index d3cf43c2bcfa..4c0588d7cdd7 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHelper.java +++ b/platform/lang-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHelper.java @@ -71,12 +71,7 @@ public class ExtractMethodHelper { } }); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - replaceDuplicates(callElement, editor, replacer, duplicates); - } - }); + ApplicationManager.getApplication().invokeLater(() -> replaceDuplicates(callElement, editor, replacer, duplicates)); } }); } @@ -138,17 +133,9 @@ public class ExtractMethodHelper { private static void replaceDuplicate(final Project project, final Consumer> replacer, final Pair replacement) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - replacer.consume(replacement); - } - }); - } - }, "Replace duplicate", null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + replacer.consume(replacement); + }), "Replace duplicate", null); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseDialog.java b/platform/lang-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseDialog.java index a3e777b34739..1e39678f25ac 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseDialog.java @@ -242,20 +242,17 @@ public abstract class ExtractSuperBaseDialog { + try { + preparePackage(); + } + catch (IncorrectOperationException e) { + errorString[0] = e.getMessage(); + myPackageNameField.requestFocusInWindow(); + } + catch (OperationFailedException e) { + errorString[0] = e.getMessage(); + myPackageNameField.requestFocusInWindow(); } }, RefactoringBundle.message("create.directory"), null); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java b/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java index f9aefb0f9492..b8573a72e9c8 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java @@ -66,12 +66,7 @@ public class GenericInlineHandler { } else { final Ref> usagesRef = new Ref>(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - usagesRef.set(ReferencesSearch.search(element).findAll()); - } - }, "Find Usages", false, element.getProject()); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> usagesRef.set(ReferencesSearch.search(element).findAll()), "Find Usages", false, element.getProject()); allReferences = usagesRef.get(); } @@ -109,32 +104,26 @@ public class GenericInlineHandler { if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, elements, true)) { return true; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final String subj = element instanceof PsiNamedElement ? ((PsiNamedElement)element).getName() : "element"; + ApplicationManager.getApplication().runWriteAction(() -> { + final String subj = element instanceof PsiNamedElement ? ((PsiNamedElement)element).getName() : "element"; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - final PsiReference[] references = sortDepthFirstRightLeftOrder(allReferences); + CommandProcessor.getInstance().executeCommand(project, () -> { + final PsiReference[] references = sortDepthFirstRightLeftOrder(allReferences); - final UsageInfo[] usages = new UsageInfo[references.length]; - for (int i = 0; i < references.length; i++) { - usages[i] = new UsageInfo(references[i]); - } + final UsageInfo[] usages = new UsageInfo[references.length]; + for (int i = 0; i < references.length; i++) { + usages[i] = new UsageInfo(references[i]); + } - for (UsageInfo usage : usages) { - inlineReference(usage, element, inliners); - } + for (UsageInfo usage : usages) { + inlineReference(usage, element, inliners); + } - if (!settings.isOnlyOneReferenceToInline()) { - languageSpecific.removeDefinition(element, settings); - } - } - }, RefactoringBundle.message("inline.command", StringUtil.notNullize(subj, "")), null); - } + if (!settings.isOnlyOneReferenceToInline()) { + languageSpecific.removeDefinition(element, settings); + } + }, RefactoringBundle.message("inline.command", StringUtil.notNullize(subj, "")), null); }); return true; } @@ -202,14 +191,11 @@ public class GenericInlineHandler { //order of usages across different files is irrelevant public static PsiReference[] sortDepthFirstRightLeftOrder(final Collection allReferences) { final PsiReference[] usages = allReferences.toArray(new PsiReference[allReferences.size()]); - Arrays.sort(usages, new Comparator() { - @Override - public int compare(final PsiReference usage1, final PsiReference usage2) { - final PsiElement element1 = usage1.getElement(); - final PsiElement element2 = usage2.getElement(); - if (element1 == null || element2 == null) return 0; - return element2.getTextRange().getStartOffset() - element1.getTextRange().getStartOffset(); - } + Arrays.sort(usages, (usage1, usage2) -> { + final PsiElement element1 = usage1.getElement(); + final PsiElement element2 = usage2.getElement(); + if (element1 == null || element2 == null) return 0; + return element2.getTextRange().getStartOffset() - element1.getTextRange().getStartOffset(); }); return usages; } diff --git a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/AbstractInplaceIntroducer.java b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/AbstractInplaceIntroducer.java index c6280cfc159f..44ed9babfca7 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/AbstractInplaceIntroducer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/AbstractInplaceIntroducer.java @@ -142,11 +142,8 @@ public abstract class AbstractInplaceIntroducer { + myPreview.getDocument().replaceString(0, myPreview.getDocument().getTextLength(), text); }); } @@ -213,52 +210,48 @@ public abstract class AbstractInplaceIntroducer result = new Ref(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable()); - final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names); - boolean started = false; - if (variable != null) { - int caretOffset = getCaretOffset(); - myEditor.getCaretModel().moveToOffset(caretOffset); - myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable()); + final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names); + boolean started = false; + if (variable != null) { + int caretOffset = getCaretOffset(); + myEditor.getCaretModel().moveToOffset(caretOffset); + myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); - final LinkedHashSet nameSuggestions = new LinkedHashSet(); - nameSuggestions.add(variable.getName()); - nameSuggestions.addAll(Arrays.asList(names)); - initOccurrencesMarkers(); - setElementToRename(variable); - updateTitle(getVariable()); - started = AbstractInplaceIntroducer.super.performInplaceRefactoring(nameSuggestions); - if (started) { - onRenameTemplateStarted(); - myDocumentAdapter = new DocumentAdapter() { - @Override - public void documentChanged(DocumentEvent e) { - if (myPreview == null) return; - final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); - if (templateState != null) { - final TextResult value = templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME); - if (value != null) { - updateTitle(getVariable(), value.getText()); - } + final LinkedHashSet nameSuggestions = new LinkedHashSet(); + nameSuggestions.add(variable.getName()); + nameSuggestions.addAll(Arrays.asList(names)); + initOccurrencesMarkers(); + setElementToRename(variable); + updateTitle(getVariable()); + started = AbstractInplaceIntroducer.super.performInplaceRefactoring(nameSuggestions); + if (started) { + onRenameTemplateStarted(); + myDocumentAdapter = new DocumentAdapter() { + @Override + public void documentChanged(DocumentEvent e) { + if (myPreview == null) return; + final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); + if (templateState != null) { + final TextResult value = templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME); + if (value != null) { + updateTitle(getVariable(), value.getText()); } } - }; - myEditor.getDocument().addDocumentListener(myDocumentAdapter); - updateTitle(getVariable()); - if (TemplateManagerImpl.getTemplateState(myEditor) != null) { - myEditor.putUserData(ACTIVE_INTRODUCE, AbstractInplaceIntroducer.this); } + }; + myEditor.getDocument().addDocumentListener(myDocumentAdapter); + updateTitle(getVariable()); + if (TemplateManagerImpl.getTemplateState(myEditor) != null) { + myEditor.putUserData(ACTIVE_INTRODUCE, AbstractInplaceIntroducer.this); } } - result.set(started); - if (!started) { - finish(true); - } } - + result.set(started); + if (!started) { + finish(true); + } }, getCommandName(), getCommandName()); return result.get(); } @@ -315,43 +308,37 @@ public abstract class AbstractInplaceIntroducer { + final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); + if (templateState != null) { + myEditor.putUserData(INTRODUCE_RESTART, true); + try { + final TextRange range = templateState.getCurrentVariableRange(); + if (range != null) { + final TextResult inputText = templateState.getVariableValue(PRIMARY_VARIABLE_NAME); + final String inputName = inputText != null ? inputText.getText() : null; + final V variable = getVariable(); + if (inputName == null || variable == null || !isIdentifier(inputName, variable.getLanguage())) { + final String[] names = suggestNames(isReplaceAllOccurrences(), getLocalVariable()); + ApplicationManager.getApplication().runWriteAction(() -> { + myEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), names[0]); + }); + } + } + templateState.gotoEnd(true); try { - final TextRange range = templateState.getCurrentVariableRange(); - if (range != null) { - final TextResult inputText = templateState.getVariableValue(PRIMARY_VARIABLE_NAME); - final String inputName = inputText != null ? inputText.getText() : null; - final V variable = getVariable(); - if (inputName == null || variable == null || !isIdentifier(inputName, variable.getLanguage())) { - final String[] names = suggestNames(isReplaceAllOccurrences(), getLocalVariable()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), names[0]); - } - }); - } - } - templateState.gotoEnd(true); - try { - myShouldSelect = false; - startInplaceIntroduceTemplate(); - } - finally { - myShouldSelect = true; - } + myShouldSelect = false; + startInplaceIntroduceTemplate(); } finally { - myEditor.putUserData(INTRODUCE_RESTART, false); + myShouldSelect = true; } } - updateTitle(getVariable()); + finally { + myEditor.putUserData(INTRODUCE_RESTART, false); + } } + updateTitle(getVariable()); }; CommandProcessor.getInstance().executeCommand(myProject, restartTemplateRunnable, getCommandName(), getCommandName()); } @@ -471,53 +458,50 @@ public abstract class AbstractInplaceIntroducer occurrenceMarkers = getOccurrenceMarkers(); - for (int i = 0, occurrenceMarkersSize = occurrenceMarkers.size(); i < occurrenceMarkersSize; i++) { - RangeMarker marker = occurrenceMarkers.get(i); - if (getExprMarker() != null && marker.getStartOffset() == getExprMarker().getStartOffset() && myExpr != null) { - myOccurrences[i] = myExpr; - continue; - } - final E psiExpression = - restoreExpression(containingFile, psiField, marker, getLocalVariable() != null ? myLocalName : myExprText); - if (psiExpression != null) { - myOccurrences[i] = psiExpression; - } - } - - if (myExpr != null && myExpr.isPhysical()) { - myExprMarker = createMarker(myExpr); - } - myOccurrenceMarkers = null; - deleteTemplateField(psiField); + ApplicationManager.getApplication().runWriteAction(() -> { + final PsiFile containingFile = psiField.getContainingFile(); + final RangeMarker exprMarker = getExprMarker(); + if (exprMarker != null) { + myExpr = restoreExpression(containingFile, psiField, exprMarker, myExprText); } + + if (myLocalMarker != null) { + final PsiElement refVariableElement = containingFile.findElementAt(myLocalMarker.getStartOffset()); + if (refVariableElement != null) { + final PsiElement parent = refVariableElement.getParent(); + if (parent instanceof PsiNamedElement) { + ((PsiNamedElement)parent).setName(myLocalName); + } + } + + final V localVariable = getLocalVariable(); + if (localVariable != null && localVariable.isPhysical()) { + myLocalVariable = localVariable; + final PsiElement nameIdentifier = localVariable.getNameIdentifier(); + if (nameIdentifier != null) { + myLocalMarker = createMarker(nameIdentifier); + } + } + } + final List occurrenceMarkers = getOccurrenceMarkers(); + for (int i = 0, occurrenceMarkersSize = occurrenceMarkers.size(); i < occurrenceMarkersSize; i++) { + RangeMarker marker = occurrenceMarkers.get(i); + if (getExprMarker() != null && marker.getStartOffset() == getExprMarker().getStartOffset() && myExpr != null) { + myOccurrences[i] = myExpr; + continue; + } + final E psiExpression = + restoreExpression(containingFile, psiField, marker, getLocalVariable() != null ? myLocalName : myExprText); + if (psiExpression != null) { + myOccurrences[i] = psiExpression; + } + } + + if (myExpr != null && myExpr.isPhysical()) { + myExprMarker = createMarker(myExpr); + } + myOccurrenceMarkers = null; + deleteTemplateField(psiField); }); } @@ -530,27 +514,24 @@ public abstract class AbstractInplaceIntroducer { + final String refactoringId = getRefactoringId(); + if (refactoringId != null) { + final RefactoringEventData beforeData = new RefactoringEventData(); + final V localVariable = getLocalVariable(); + if (localVariable != null) { + beforeData.addElement(localVariable); } - performIntroduce(); + else { + final E beforeExpr = getBeforeExpr(); + if (beforeExpr != null) { + beforeData.addElement(beforeExpr); + } + } + myProject.getMessageBus() + .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData); } + performIntroduce(); }, getCommandName(), getCommandName()); V variable = getVariable(); @@ -647,12 +628,7 @@ public abstract class AbstractInplaceIntroducer templateState.gotoEnd(true); CommandProcessor.getInstance().executeCommand(myProject, runnable, getCommandName(), getCommandName()); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java index 359e719891a7..50c869bdbba2 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java @@ -80,17 +80,13 @@ public abstract class InplaceVariableIntroducer extends In if (astNode != null) { final Lexer lexer = LanguageParserDefinitions.INSTANCE.forLanguage(expr.getLanguage()).createLexer(project); if (LanguageUtil.canStickTokensTogetherByLexer(prev, prev, lexer) == ParserDefinition.SpaceRequirements.MUST) { - PostprocessReformattingAspect.getInstance(project).disablePostprocessFormattingInside(new Runnable() { - @Override - public void run() { - new WriteCommandAction(project, "Normalize declaration") { - @Override - protected void run(@NotNull Result result) throws Throwable { - node.getTreeParent().addChild(astNode, node); - } - }.execute(); - } - }); + PostprocessReformattingAspect.getInstance(project).disablePostprocessFormattingInside( + (Runnable)() -> new WriteCommandAction(project, "Normalize declaration") { + @Override + protected void run(@NotNull Result result) throws Throwable { + node.getTreeParent().addChild(astNode, node); + } + }.execute()); } } myExpr = expr; diff --git a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/OccurrencesChooser.java b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/OccurrencesChooser.java index 9b8ba1fa9e03..e94452fc4c5c 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/OccurrencesChooser.java +++ b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/OccurrencesChooser.java @@ -140,12 +140,7 @@ public abstract class OccurrencesChooser { .setMovable(true) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - callback.pass((ReplaceChoice)list.getSelectedValue()); - } - }) + .setItemChoosenCallback(() -> callback.pass((ReplaceChoice)list.getSelectedValue())) .addListener(new JBPopupAdapter() { @Override public void onClosed(LightweightWindowEvent event) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java index f3b160dafdbc..c02965e2903e 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java @@ -65,12 +65,7 @@ public class InvertBooleanProcessor extends BaseRefactoringProcessor { @NotNull @Override protected ConflictsDialog createConflictsDialog(@NotNull MultiMap conflicts, @Nullable final UsageInfo[] usages) { - return new ConflictsDialog(myProject, conflicts, usages == null ? null : new Runnable() { - @Override - public void run() { - InvertBooleanProcessor.this.execute(usages); - } - }, false, true); + return new ConflictsDialog(myProject, conflicts, usages == null ? null : (Runnable)() -> InvertBooleanProcessor.this.execute(usages), false, true); } @Override diff --git a/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeDialog.java b/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeDialog.java index 9fc5bfc73300..a749c6a097a3 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeDialog.java @@ -152,25 +152,19 @@ public class ExtractIncludeDialog extends DialogWrapper { return; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - final Runnable action = new Runnable() { - @Override - public void run() { - try { - PsiDirectory targetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(project), directoryName); - targetDirectory.checkCreateFile(targetFileName); - final String webPath = PsiFileSystemItemUtil.getRelativePath(myCurrentDirectory, targetDirectory); - myTargetDirectory = webPath == null ? null : targetDirectory; - } - catch (IncorrectOperationException e) { - CommonRefactoringUtil.showErrorMessage(REFACTORING_NAME, e.getMessage(), null, project); - } - } - }; - ApplicationManager.getApplication().runWriteAction(action); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + final Runnable action = () -> { + try { + PsiDirectory targetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(project), directoryName); + targetDirectory.checkCreateFile(targetFileName); + final String webPath = PsiFileSystemItemUtil.getRelativePath(myCurrentDirectory, targetDirectory); + myTargetDirectory = webPath == null ? null : targetDirectory; + } + catch (IncorrectOperationException e) { + CommonRefactoringUtil.showErrorMessage(REFACTORING_NAME, e.getMessage(), null, project); + } + }; + ApplicationManager.getApplication().runWriteAction(action); }, RefactoringBundle.message("create.directory"), null); if (myTargetDirectory == null) return; super.doOKAction(); diff --git a/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java b/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java index 811e695b6603..c8d1305ef572 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java @@ -116,35 +116,32 @@ public abstract class ExtractIncludeFileBase implements Re ApplicationNamesInfo.getInstance().getProductName()); final int exitCode = Messages.showYesNoDialog(project, message, getRefactoringName(), Messages.getInformationIcon()); if (exitCode == Messages.YES) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - boolean replaceAll = false; - for (IncludeDuplicate pair : duplicates) { - if (!replaceAll) { + CommandProcessor.getInstance().executeCommand(project, () -> { + boolean replaceAll = false; + for (IncludeDuplicate pair : duplicates) { + if (!replaceAll) { - highlightInEditor(project, pair, editor); + highlightInEditor(project, pair, editor); - ReplacePromptDialog promptDialog = new ReplacePromptDialog(false, RefactoringBundle.message("replace.fragment"), project); - promptDialog.show(); - final int promptResult = promptDialog.getExitCode(); - if (promptResult == FindManager.PromptResult.SKIP) continue; - if (promptResult == FindManager.PromptResult.CANCEL) break; + ReplacePromptDialog promptDialog = new ReplacePromptDialog(false, RefactoringBundle.message("replace.fragment"), project); + promptDialog.show(); + final int promptResult = promptDialog.getExitCode(); + if (promptResult == FindManager.PromptResult.SKIP) continue; + if (promptResult == FindManager.PromptResult.CANCEL) break; - if (promptResult == FindManager.PromptResult.OK) { - doReplaceRange(includePath, pair.getStart(), pair.getEnd()); - } - else if (promptResult == FindManager.PromptResult.ALL) { - doReplaceRange(includePath, pair.getStart(), pair.getEnd()); - replaceAll = true; - } - else { - LOG.error("Unknown return status"); - } - } - else { + if (promptResult == FindManager.PromptResult.OK) { doReplaceRange(includePath, pair.getStart(), pair.getEnd()); } + else if (promptResult == FindManager.PromptResult.ALL) { + doReplaceRange(includePath, pair.getStart(), pair.getEnd()); + replaceAll = true; + } + else { + LOG.error("Unknown return status"); + } + } + else { + doReplaceRange(includePath, pair.getStart(), pair.getEnd()); } } }, RefactoringBundle.message("remove.duplicates.command"), null); @@ -221,41 +218,25 @@ public abstract class ExtractIncludeFileBase implements Re final PsiDirectory targetDirectory = dialog.getTargetDirectory(); LOG.assertTrue(targetDirectory != null); final String targetfileName = dialog.getTargetFileName(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - final List> duplicates = new ArrayList>(); - final T first = children.getFirst(); - final T second = children.getSecond(); - PsiEquivalenceUtil.findChildRangeDuplicates(first, second, file, new PairConsumer() { - @Override - public void consume(final PsiElement start, final PsiElement end) { - duplicates.add(new IncludeDuplicate((T) start, (T) end)); - } - }); - final String includePath = processPrimaryFragment(first, second, targetDirectory, targetfileName, file); - editor.getCaretModel().moveToOffset(first.getTextRange().getStartOffset()); - - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - replaceDuplicates(includePath, duplicates, editor, project); - } - }); - } - catch (IncorrectOperationException e) { - CommonRefactoringUtil.showErrorMessage(getRefactoringName(), e.getMessage(), null, project); - } - - editor.getSelectionModel().removeSelection(); - } + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + final List> duplicates = new ArrayList>(); + final T first = children.getFirst(); + final T second = children.getSecond(); + PsiEquivalenceUtil.findChildRangeDuplicates(first, second, file, (start1, end1) -> { + duplicates.add(new IncludeDuplicate((T)start1, (T)end1)); }); + final String includePath = processPrimaryFragment(first, second, targetDirectory, targetfileName, file); + editor.getCaretModel().moveToOffset(first.getTextRange().getStartOffset()); + + ApplicationManager.getApplication().invokeLater(() -> replaceDuplicates(includePath, duplicates, editor, project)); } - }, getRefactoringName(), null); + catch (IncorrectOperationException e) { + CommonRefactoringUtil.showErrorMessage(getRefactoringName(), e.getMessage(), null, project); + } + + editor.getSelectionModel().removeSelection(); + }), getRefactoringName(), null); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/listeners/impl/impl/RefactoringTransactionImpl.java b/platform/lang-impl/src/com/intellij/refactoring/listeners/impl/impl/RefactoringTransactionImpl.java index 144a25dbc617..a52322f346fe 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/listeners/impl/impl/RefactoringTransactionImpl.java +++ b/platform/lang-impl/src/com/intellij/refactoring/listeners/impl/impl/RefactoringTransactionImpl.java @@ -85,16 +85,13 @@ public class RefactoringTransactionImpl implements RefactoringTransaction { @Override public void elementMoved(@NotNull final PsiElement newElement) { - myRunnables.add(new Runnable() { - @Override - public void run() { - for (RefactoringElementListener refactoringElementListener : myListenerList) { - try { - refactoringElementListener.elementMoved(newElement); - } - catch (Throwable e) { - LOG.error(e); - } + myRunnables.add(() -> { + for (RefactoringElementListener refactoringElementListener : myListenerList) { + try { + refactoringElementListener.elementMoved(newElement); + } + catch (Throwable e) { + LOG.error(e); } } }); @@ -102,16 +99,13 @@ public class RefactoringTransactionImpl implements RefactoringTransaction { @Override public void elementRenamed(@NotNull final PsiElement newElement) { - myRunnables.add(new Runnable() { - @Override - public void run() { - for (RefactoringElementListener refactoringElementListener : myListenerList) { - try { - refactoringElementListener.elementRenamed(newElement); - } - catch (Throwable e) { - LOG.error(e); - } + myRunnables.add(() -> { + for (RefactoringElementListener refactoringElementListener : myListenerList) { + try { + refactoringElementListener.elementRenamed(newElement); + } + catch (Throwable e) { + LOG.error(e); } } }); diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/CommonMoveUtil.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/CommonMoveUtil.java index d6a2b64853c8..7066cd55274a 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/CommonMoveUtil.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/CommonMoveUtil.java @@ -22,23 +22,20 @@ public class CommonMoveUtil { public static NonCodeUsageInfo[] retargetUsages(final UsageInfo[] usages, final Map oldToNewElementsMapping) throws IncorrectOperationException { - Arrays.sort(usages, new Comparator() { - @Override - public int compare(UsageInfo o1, UsageInfo o2) { - final VirtualFile file1 = o1.getVirtualFile(); - final VirtualFile file2 = o2.getVirtualFile(); - if (Comparing.equal(file1, file2)) { - final ProperTextRange rangeInElement1 = o1.getRangeInElement(); - final ProperTextRange rangeInElement2 = o2.getRangeInElement(); - if (rangeInElement1 != null && rangeInElement2 != null) { - return rangeInElement2.getStartOffset() - rangeInElement1.getStartOffset(); - } - return 0; + Arrays.sort(usages, (o1, o2) -> { + final VirtualFile file1 = o1.getVirtualFile(); + final VirtualFile file2 = o2.getVirtualFile(); + if (Comparing.equal(file1, file2)) { + final ProperTextRange rangeInElement1 = o1.getRangeInElement(); + final ProperTextRange rangeInElement2 = o2.getRangeInElement(); + if (rangeInElement1 != null && rangeInElement2 != null) { + return rangeInElement2.getStartOffset() - rangeInElement1.getStartOffset(); } - if (file1 == null) return -1; - if (file2 == null) return 1; - return Comparing.compare(file1.getPath(), file2.getPath()); + return 0; } + if (file1 == null) return -1; + if (file2 == null) return 1; + return Comparing.compare(file1.getPath(), file2.getPath()); }); List nonCodeUsages = new ArrayList(); for (UsageInfo usage : usages) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java index 8617a33fb4bb..32556facc308 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java @@ -188,12 +188,7 @@ public class MoveDirectoryWithClassesProcessor extends BaseRefactoringProcessor myNonCodeUsages = CommonMoveUtil.retargetUsages(usages, oldToNewElementsMapping); for (MoveDirectoryWithClassesHelper helper : MoveDirectoryWithClassesHelper.findAll()) { - helper.postProcessUsages(usages, new Function() { - @Override - public PsiDirectory fun(PsiDirectory dir) { - return getResultDirectory(dir).getTargetDirectory(); - } - }); + helper.postProcessUsages(usages, dir -> getResultDirectory(dir).getTargetDirectory()); } for (PsiDirectory directory : myDirectories) { final TargetDirectoryWrapper wrapper = myNestedDirsToMove.get(directory); diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesDialog.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesDialog.java index a57e33df8589..0b6ff15d1104 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesDialog.java @@ -209,35 +209,26 @@ public class MoveFilesOrDirectoriesDialog extends DialogWrapper { return; } - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final Runnable action = new Runnable() { - @Override - public void run() { - String directoryName = myTargetDirectoryField.getChildComponent().getText().replace(File.separatorChar, '/'); - try { - myTargetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(myProject), directoryName); - } - catch (IncorrectOperationException e) { - // ignore - } - } - }; + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final Runnable action = () -> { + String directoryName = myTargetDirectoryField.getChildComponent().getText().replace(File.separatorChar, '/'); + try { + myTargetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(myProject), directoryName); + } + catch (IncorrectOperationException e) { + // ignore + } + }; - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(action); - if (myTargetDirectory == null) { - CommonRefactoringUtil.showErrorMessage(getTitle(), - RefactoringBundle.message("cannot.create.directory"), myHelpID, myProject); - return; - } - myCallback.run(MoveFilesOrDirectoriesDialog.this); - } - }); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> { + ApplicationManager.getApplication().runWriteAction(action); + if (myTargetDirectory == null) { + CommonRefactoringUtil.showErrorMessage(getTitle(), + RefactoringBundle.message("cannot.create.directory"), myHelpID, myProject); + return; + } + myCallback.run(MoveFilesOrDirectoriesDialog.this); + }); }, RefactoringBundle.message("move.title"), null); } @@ -247,12 +238,7 @@ public class MoveFilesOrDirectoriesDialog extends DialogWrapper { @Override public void show() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - MoveFilesOrDirectoriesDialog.super.show(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> MoveFilesOrDirectoriesDialog.super.show()); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java index 7fb0f33cb5ce..c4cb612917d5 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java @@ -204,12 +204,9 @@ public class MoveFilesOrDirectoriesProcessor extends BaseRefactoringProcessor { final String message = e.getMessage(); final int index = message != null ? message.indexOf("java.io.IOException") : -1; if (index >= 0 && message != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String cause = message.substring(index + "java.io.IOException".length()); - Messages.showMessageDialog(myProject, cause, RefactoringBundle.message("error.title"), Messages.getErrorIcon()); - } + ApplicationManager.getApplication().invokeLater(() -> { + String cause = message.substring(index + "java.io.IOException".length()); + Messages.showMessageDialog(myProject, cause, RefactoringBundle.message("error.title"), Messages.getErrorIcon()); }); } else { diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java index 303f3c99da3b..cbb097969026 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java @@ -127,60 +127,54 @@ public class MoveFilesOrDirectoriesUtil { final MoveFilesOrDirectoriesDialog.Callback doRun = new MoveFilesOrDirectoriesDialog.Callback() { @Override public void run(final MoveFilesOrDirectoriesDialog moveDialog) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - final PsiDirectory targetDirectory = moveDialog != null ? moveDialog.getTargetDirectory() : initialTargetDirectory; - if (targetDirectory == null) { - LOG.error("It is null! The target directory, it is null!"); + CommandProcessor.getInstance().executeCommand(project, () -> { + final PsiDirectory targetDirectory1 = moveDialog != null ? moveDialog.getTargetDirectory() : initialTargetDirectory; + if (targetDirectory1 == null) { + LOG.error("It is null! The target directory, it is null!"); + return; + } + + Collection toCheck = ContainerUtil.newArrayList((PsiElement)targetDirectory1); + for (PsiElement e : newElements) { + toCheck.add(e instanceof PsiFileSystemItem && e.getParent() != null ? e.getParent() : e); + } + if (!CommonRefactoringUtil.checkReadOnlyStatus(project, toCheck, false)) { + return; + } + + targetElement[0] = targetDirectory1; + + try { + final int[] choice = elements.length > 1 || elements[0] instanceof PsiDirectory ? new int[]{-1} : null; + final List els = new ArrayList(); + for (final PsiElement psiElement : newElements) { + if (psiElement instanceof PsiFile) { + final PsiFile file = (PsiFile)psiElement; + final boolean fileExist = ApplicationManager.getApplication().runWriteAction(new Computable() { + @Override + public Boolean compute() { + return CopyFilesOrDirectoriesHandler.checkFileExist(targetDirectory1, choice, file, file.getName(), "Move"); + } + }); + if (fileExist) continue; + } + checkMove(psiElement, targetDirectory1); + els.add(psiElement); + } + final Runnable callback = () -> { + if (moveDialog != null) moveDialog.close(DialogWrapper.CANCEL_EXIT_CODE); + }; + if (els.isEmpty()) { + callback.run(); return; } - - Collection toCheck = ContainerUtil.newArrayList((PsiElement)targetDirectory); - for (PsiElement e : newElements) { - toCheck.add(e instanceof PsiFileSystemItem && e.getParent() != null ? e.getParent() : e); - } - if (!CommonRefactoringUtil.checkReadOnlyStatus(project, toCheck, false)) { - return; - } - - targetElement[0] = targetDirectory; - - try { - final int[] choice = elements.length > 1 || elements[0] instanceof PsiDirectory ? new int[]{-1} : null; - final List els = new ArrayList(); - for (final PsiElement psiElement : newElements) { - if (psiElement instanceof PsiFile) { - final PsiFile file = (PsiFile)psiElement; - final boolean fileExist = ApplicationManager.getApplication().runWriteAction(new Computable() { - @Override - public Boolean compute() { - return CopyFilesOrDirectoriesHandler.checkFileExist(targetDirectory, choice, file, file.getName(), "Move"); - } - }); - if (fileExist) continue; - } - checkMove(psiElement, targetDirectory); - els.add(psiElement); - } - final Runnable callback = new Runnable() { - @Override - public void run() { - if (moveDialog != null) moveDialog.close(DialogWrapper.CANCEL_EXIT_CODE); - } - }; - if (els.isEmpty()) { - callback.run(); - return; - } - new MoveFilesOrDirectoriesProcessor(project, els.toArray(new PsiElement[els.size()]), targetDirectory, - RefactoringSettings.getInstance().MOVE_SEARCH_FOR_REFERENCES_FOR_FILE, - false, false, moveCallback, callback).run(); - } - catch (IncorrectOperationException e) { - CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(), - "refactoring.moveFile", project); - } + new MoveFilesOrDirectoriesProcessor(project, els.toArray(new PsiElement[els.size()]), targetDirectory1, + RefactoringSettings.getInstance().MOVE_SEARCH_FOR_REFERENCES_FOR_FILE, + false, false, moveCallback, callback).run(); + } + catch (IncorrectOperationException e) { + CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(), + "refactoring.moveFile", project); } }, MoveHandler.REFACTORING_NAME, null); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/DirectoryAsPackageRenameHandlerBase.java b/platform/lang-impl/src/com/intellij/refactoring/rename/DirectoryAsPackageRenameHandlerBase.java index ea5547f5f761..935b92a6c004 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/DirectoryAsPackageRenameHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/DirectoryAsPackageRenameHandlerBase.java @@ -232,12 +232,7 @@ public abstract class DirectoryAsPackageRenameHandlerBase directoryPresentation = new Function() { - @Override - public String fun(PsiDirectory directory) { - return directory.getVirtualFile().getPresentableUrl(); - } - }; + final Function directoryPresentation = directory -> directory.getVirtualFile().getPresentableUrl(); message.append(StringUtil.join(source, directoryPresentation, "\n")); if (!generated.isEmpty()) { message.append("\n\nalso generated:\n"); diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java index ef76ae11eabb..8b768b742f1f 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java @@ -187,19 +187,16 @@ public class RenameProcessor extends BaseRefactoringProcessor { assertNonCompileElement(element); } myAllRenames.putAll(renames); - final Runnable runnable = new Runnable() { - @Override - public void run() { - for (final Map.Entry entry : renames.entrySet()) { - final UsageInfo[] usages = - ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public UsageInfo[] compute() { - return RenameUtil.findUsages(entry.getKey(), entry.getValue(), mySearchInComments, mySearchTextOccurrences, myAllRenames); - } - }); - Collections.addAll(variableUsages, usages); - } + final Runnable runnable = () -> { + for (final Map.Entry entry : renames.entrySet()) { + final UsageInfo[] usages = + ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public UsageInfo[] compute() { + return RenameUtil.findUsages(entry.getKey(), entry.getValue(), mySearchInComments, mySearchTextOccurrences, myAllRenames); + } + }); + Collections.addAll(variableUsages, usages); } }; if (!ProgressManager.getInstance() @@ -238,19 +235,11 @@ public class RenameProcessor extends BaseRefactoringProcessor { } } - final Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (final AutomaticRenamer renamer : myRenamers) { - renamer.findUsages(variableUsages, mySearchInComments, mySearchTextOccurrences, mySkippedUsages, myAllRenames); - } - } - }); + final Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> { + for (final AutomaticRenamer renamer : myRenamers) { + renamer.findUsages(variableUsages, mySearchInComments, mySearchTextOccurrences, mySkippedUsages, myAllRenames); } - }; + }); return ProgressManager.getInstance() .runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject); @@ -434,29 +423,23 @@ public class RenameProcessor extends BaseRefactoringProcessor { myNonCodeUsages = nonCodeUsages.toArray(new NonCodeUsageInfo[nonCodeUsages.size()]); if (!mySkippedUsages.isEmpty()) { if (!ApplicationManager.getApplication().isUnitTestMode() && !ApplicationManager.getApplication().isHeadlessEnvironment()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final IdeFrame ideFrame = WindowManager.getInstance().getIdeFrame(myProject); - if (ideFrame != null) { + ApplicationManager.getApplication().invokeLater(() -> { + final IdeFrame ideFrame = WindowManager.getInstance().getIdeFrame(myProject); + if (ideFrame != null) { - StatusBarEx statusBar = (StatusBarEx)ideFrame.getStatusBar(); - HyperlinkListener listener = new HyperlinkListener() { - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; - Messages.showMessageDialog("Following usages were safely skipped:
    " + - StringUtil.join(mySkippedUsages, new Function() { - @Override - public String fun(UnresolvableCollisionUsageInfo unresolvableCollisionUsageInfo) { - return unresolvableCollisionUsageInfo.getDescription(); - } - }, "
    ") + - "", "Not All Usages Were Renamed", null); - } - }; - statusBar.notifyProgressByBalloon(MessageType.WARNING, "Unable to rename certain usages. Browse", null, listener); - } + StatusBarEx statusBar = (StatusBarEx)ideFrame.getStatusBar(); + HyperlinkListener listener = new HyperlinkListener() { + @Override + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; + Messages.showMessageDialog("Following usages were safely skipped:
    " + + StringUtil.join(mySkippedUsages, unresolvableCollisionUsageInfo -> { + return unresolvableCollisionUsageInfo.getDescription(); + }, "
    ") + + "", "Not All Usages Were Renamed", null); + } + }; + statusBar.notifyProgressByBalloon(MessageType.WARNING, "Unable to rename certain usages. Browse", null, listener); } }, ModalityState.NON_MODAL); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameUtil.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameUtil.java index 38955d87dd82..0e2cc15320f4 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameUtil.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameUtil.java @@ -194,16 +194,13 @@ public class RenameUtil { //LOG.error(e); //return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final String helpID = RenamePsiElementProcessor.forElement(element).getHelpID(element); - String message = e.getMessage(); - if (StringUtil.isEmpty(message)) { - message = RefactoringBundle.message("rename.not.supported"); - } - CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("rename.title"), message, helpID, project); + ApplicationManager.getApplication().invokeLater(() -> { + final String helpID = RenamePsiElementProcessor.forElement(element).getHelpID(element); + String message = e.getMessage(); + if (StringUtil.isEmpty(message)) { + message = RefactoringBundle.message("rename.not.supported"); } + CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("rename.title"), message, helpID, project); }); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java index 6e4f6717562d..105ff084f60d 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java @@ -426,12 +426,9 @@ public abstract class InplaceRefactoring { private void restoreOldCaretPositionAndSelection(final int offset) { //move to old offset - Runnable runnable = new Runnable() { - @Override - public void run() { - myEditor.getCaretModel().moveToOffset(restoreCaretOffset(offset)); - restoreSelection(); - } + Runnable runnable = () -> { + myEditor.getCaretModel().moveToOffset(restoreCaretOffset(offset)); + restoreSelection(); }; final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); @@ -493,15 +490,12 @@ public abstract class InplaceRefactoring { protected StartMarkAction startRename() throws StartMarkAction.AlreadyStartedException { final StartMarkAction[] markAction = new StartMarkAction[1]; final StartMarkAction.AlreadyStartedException[] ex = new StartMarkAction.AlreadyStartedException[1]; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - try { - markAction[0] = StartMarkAction.start(myEditor, myProject, getCommandName()); - } - catch (StartMarkAction.AlreadyStartedException e) { - ex[0] = e; - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + try { + markAction[0] = StartMarkAction.start(myEditor, myProject, getCommandName()); + } + catch (StartMarkAction.AlreadyStartedException e) { + ex[0] = e; } }, getCommandName(), null); if (ex[0] != null) throw ex[0]; @@ -587,26 +581,20 @@ public abstract class InplaceRefactoring { protected void revertState() { if (myOldName == null) return; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final TemplateState state = TemplateManagerImpl.getTemplateState(topLevelEditor); - assert state != null; - final int segmentsCount = state.getSegmentsCount(); - final Document document = topLevelEditor.getDocument(); - for (int i = 0; i < segmentsCount; i++) { - final TextRange segmentRange = state.getSegmentRange(i); - document.replaceString(segmentRange.getStartOffset(), segmentRange.getEndOffset(), myOldName); - } - } - }); - if (!myProject.isDisposed() && myProject.isOpen()) { - PsiDocumentManager.getInstance(myProject).commitDocument(topLevelEditor.getDocument()); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor); + ApplicationManager.getApplication().runWriteAction(() -> { + final TemplateState state = TemplateManagerImpl.getTemplateState(topLevelEditor); + assert state != null; + final int segmentsCount = state.getSegmentsCount(); + final Document document = topLevelEditor.getDocument(); + for (int i = 0; i < segmentsCount; i++) { + final TextRange segmentRange = state.getSegmentRange(i); + document.replaceString(segmentRange.getStartOffset(), segmentRange.getEndOffset(), myOldName); } + }); + if (!myProject.isDisposed() && myProject.isOpen()) { + PsiDocumentManager.getInstance(myProject).commitDocument(topLevelEditor.getDocument()); } }, getCommandName(), null); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/RenameChooser.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/RenameChooser.java index e680a4080d7a..0f60b60b572f 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/RenameChooser.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/RenameChooser.java @@ -102,12 +102,7 @@ abstract class RenameChooser { .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - runRenameTemplate(ALL_OCCURRENCES.equals(list.getSelectedValue()) ? stringUsages : new ArrayList>()); - } - }) + .setItemChoosenCallback(() -> runRenameTemplate(ALL_OCCURRENCES.equals(list.getSelectedValue()) ? stringUsages : new ArrayList>())) .addListener(new JBPopupAdapter() { @Override public void onClosed(LightweightWindowEvent event) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java index b03621fb276f..91e3f6ce9abd 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java @@ -100,14 +100,11 @@ public class VariableInplaceRenamer extends InplaceRefactoring { final PsiFile currentFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); if (stringToSearch != null) { TextOccurrencesUtil - .processUsagesInStringsAndComments(myElementToRename, stringToSearch, true, new PairProcessor() { - @Override - public boolean process(PsiElement psiElement, TextRange textRange) { - if (psiElement.getContainingFile() == currentFile) { - stringUsages.add(Pair.create(psiElement, textRange)); - } - return true; + .processUsagesInStringsAndComments(myElementToRename, stringToSearch, true, (psiElement, textRange) -> { + if (psiElement.getContainingFile() == currentFile) { + stringUsages.add(Pair.create(psiElement, textRange)); } + return true; }); } } @@ -197,12 +194,8 @@ public class VariableInplaceRenamer extends InplaceRefactoring { final int offset = variable.getTextOffset(); restoreCaretOffset(offset); JBPopupFactory.getInstance() - .createConfirmation("Inserted identifier is not valid", "Continue editing", "Cancel", new Runnable() { - @Override - public void run() { - createInplaceRenamerToRestart(variable, myEditor, newName).performInplaceRefactoring(nameSuggestions); - } - }, 0).showInBestPositionFor(myEditor); + .createConfirmation("Inserted identifier is not valid", "Continue editing", "Cancel", + () -> createInplaceRenamerToRestart(variable, myEditor, newName).performInplaceRefactoring(nameSuggestions), 0).showInBestPositionFor(myEditor); } } @@ -246,17 +239,9 @@ public class VariableInplaceRenamer extends InplaceRefactoring { } } - final Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - renamer.findUsages(usages, false, false); - } - }); - } - }; + final Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> { + renamer.findUsages(usages, false, false); + }); if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) { @@ -264,18 +249,15 @@ public class VariableInplaceRenamer extends InplaceRefactoring { } if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, PsiUtilCore.toPsiElementArray(renamer.getElements()))) return; - final Runnable performAutomaticRename = new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); - final UsageInfo[] usageInfos = usages.toArray(new UsageInfo[usages.size()]); - final MultiMap classified = RenameProcessor.classifyUsages(renamer.getElements(), usageInfos); - for (final PsiNamedElement element : renamer.getElements()) { - final String newElementName = renamer.getNewName(element); - if (newElementName != null) { - final Collection infos = classified.get(element); - RenameUtil.doRename(element, newElementName, infos.toArray(new UsageInfo[infos.size()]), myProject, RefactoringElementListener.DEAF); - } + final Runnable performAutomaticRename = () -> { + CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); + final UsageInfo[] usageInfos = usages.toArray(new UsageInfo[usages.size()]); + final MultiMap classified = RenameProcessor.classifyUsages(renamer.getElements(), usageInfos); + for (final PsiNamedElement element : renamer.getElements()) { + final String newElementName = renamer.getNewName(element); + if (newElementName != null) { + final Collection infos = classified.get(element); + RenameUtil.doRename(element, newElementName, infos.toArray(new UsageInfo[infos.size()]), myProject, RefactoringElementListener.DEAF); } } }; @@ -288,12 +270,7 @@ public class VariableInplaceRenamer extends InplaceRefactoring { if (ApplicationManager.getApplication().isUnitTestMode()) { writeCommandAction.execute(); } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - writeCommandAction.execute(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> writeCommandAction.execute()); } } } @@ -340,11 +317,8 @@ public class VariableInplaceRenamer extends InplaceRefactoring { else { if (mySnapshot != null) { if (isIdentifier(myInsertedName, myLanguage)) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - mySnapshot.apply(myInsertedName); - } + ApplicationManager.getApplication().runWriteAction(() -> { + mySnapshot.apply(myInsertedName); }); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java index a9c6b149c987..0c53a6eb29b7 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/naming/NameSuggester.java @@ -171,11 +171,8 @@ public class NameSuggester { * @return */ private TreeMap, String> calculateReplacements(String[] propertyWords, TIntIntHashMap matches) { - TreeMap, String> replacements = new TreeMap, String>(new Comparator>() { - @Override - public int compare(Pair pair, Pair pair1) { - return pair.getFirst().compareTo(pair1.getFirst()); - } + TreeMap, String> replacements = new TreeMap, String>((pair, pair1) -> { + return pair.getFirst().compareTo(pair1.getFirst()); }); for (final OriginalToNewChange change : myChanges) { final int first = change.oldFirst; diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteDialog.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteDialog.java index 451ed698d280..2e3883f9e1c6 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteDialog.java @@ -200,14 +200,11 @@ public class SafeDeleteDialog extends DialogWrapper { return; } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - if (myCallback != null && isSafeDelete()) { - myCallback.run(SafeDeleteDialog.this); - } else { - SafeDeleteDialog.super.doOKAction(); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + if (myCallback != null && isSafeDelete()) { + myCallback.run(SafeDeleteDialog.this); + } else { + SafeDeleteDialog.super.doOKAction(); } }); diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java index aea4c6b61b8c..8c582b2d6bdc 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java @@ -121,14 +121,11 @@ public class SafeDeleteHandler implements RefactoringActionHandler { final SafeDeleteDialog.Callback callback = new SafeDeleteDialog.Callback() { @Override public void run(final SafeDeleteDialog dialog) { - SafeDeleteProcessor.createInstance(project, new Runnable() { - @Override - public void run() { - if (successRunnable != null) { - successRunnable.run(); - } - dialog.close(DialogWrapper.CANCEL_EXIT_CODE); + SafeDeleteProcessor.createInstance(project, () -> { + if (successRunnable != null) { + successRunnable.run(); } + dialog.close(DialogWrapper.CANCEL_EXIT_CODE); }, elementsToDelete, dialog.isSearchInComments(), dialog.isSearchForTextOccurences(), true).run(); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java index caad0352049c..7d39b32d4c3f 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java @@ -167,15 +167,12 @@ public class SafeDeleteProcessor extends BaseRefactoringProcessor { } public static void findGenericElementUsages(final PsiElement element, final List usages, final PsiElement[] allElementsToDelete) { - ReferencesSearch.search(element).forEach(new Processor() { - @Override - public boolean process(final PsiReference reference) { - final PsiElement refElement = reference.getElement(); - if (!isInside(refElement, allElementsToDelete)) { - usages.add(new SafeDeleteReferenceSimpleDeleteUsageInfo(refElement, element, false)); - } - return true; + ReferencesSearch.search(element).forEach(reference -> { + final PsiElement refElement = reference.getElement(); + if (!isInside(refElement, allElementsToDelete)) { + usages.add(new SafeDeleteReferenceSimpleDeleteUsageInfo(refElement, element, false)); } + return true; }); } @@ -260,17 +257,14 @@ public class SafeDeleteProcessor extends BaseRefactoringProcessor { final UsageView usageView = showUsages(usages, presentation, manager); usageView.addPerformOperationAction(new RerunSafeDelete(myProject, myElements, usageView), RefactoringBundle.message("retry.command"), null, RefactoringBundle.message("rerun.safe.delete")); - usageView.addPerformOperationAction(new Runnable() { - @Override - public void run() { - UsageInfo[] preprocessedUsages = usages; - for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { - preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages); - if (preprocessedUsages == null) return; - } - final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages); - execute(filteredUsages); + usageView.addPerformOperationAction(() -> { + UsageInfo[] preprocessedUsages = usages; + for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { + preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages); + if (preprocessedUsages == null) return; } + final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages); + execute(filteredUsages); }, "Delete Anyway", RefactoringBundle.message("usageView.need.reRun"), RefactoringBundle.message("usageView.doAction")); } @@ -395,18 +389,15 @@ public class SafeDeleteProcessor extends BaseRefactoringProcessor { } } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - for (PsiElement element : myElements) { - for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { - if (delegate.handlesElement(element)) { - delegate.prepareForDeletion(element); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> { + for (PsiElement element : myElements) { + for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { + if (delegate.handlesElement(element)) { + delegate.prepareForDeletion(element); } - - element.delete(); } + + element.delete(); } }); } catch (IncorrectOperationException e) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/ui/NameSuggestionsField.java b/platform/lang-impl/src/com/intellij/refactoring/ui/NameSuggestionsField.java index 3d91672b64ae..1ca3047a20ee 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/ui/NameSuggestionsField.java +++ b/platform/lang-impl/src/com/intellij/refactoring/ui/NameSuggestionsField.java @@ -86,33 +86,30 @@ public class NameSuggestionsField extends JPanel { this(suggestedNames, project, fileType); if (editor == null) return; // later here because EditorTextField creates Editor during addNotify() - final Runnable selectionRunnable = new Runnable() { - @Override - public void run() { - final int offset = editor.getCaretModel().getOffset(); - List ranges = new ArrayList(); - SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editor.getDocument().getCharsSequence(), offset, ranges); - Editor myEditor = getEditor(); - if (myEditor == null) return; - for (TextRange wordRange : ranges) { - String word = editor.getDocument().getText(wordRange); - if (!word.equals(getEnteredName())) continue; - final SelectionModel selectionModel = editor.getSelectionModel(); - myEditor.getSelectionModel().removeSelection(); - final int wordRangeStartOffset = wordRange.getStartOffset(); - int myOffset = offset - wordRangeStartOffset; - myEditor.getCaretModel().moveToOffset(myOffset); - TextRange selected = new TextRange(Math.max(0, selectionModel.getSelectionStart() - wordRangeStartOffset), - Math.max(0, selectionModel.getSelectionEnd() - wordRangeStartOffset)); - selected = selected.intersection(new TextRange(0, myEditor.getDocument().getTextLength())); - if (selectionModel.hasSelection() && selected != null && !selected.isEmpty()) { - myEditor.getSelectionModel().setSelection(selected.getStartOffset(), selected.getEndOffset()); - } - else if (shouldSelectAll()) { - myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength()); - } - break; + final Runnable selectionRunnable = () -> { + final int offset = editor.getCaretModel().getOffset(); + List ranges = new ArrayList(); + SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editor.getDocument().getCharsSequence(), offset, ranges); + Editor myEditor = getEditor(); + if (myEditor == null) return; + for (TextRange wordRange : ranges) { + String word = editor.getDocument().getText(wordRange); + if (!word.equals(getEnteredName())) continue; + final SelectionModel selectionModel = editor.getSelectionModel(); + myEditor.getSelectionModel().removeSelection(); + final int wordRangeStartOffset = wordRange.getStartOffset(); + int myOffset = offset - wordRangeStartOffset; + myEditor.getCaretModel().moveToOffset(myOffset); + TextRange selected = new TextRange(Math.max(0, selectionModel.getSelectionStart() - wordRangeStartOffset), + Math.max(0, selectionModel.getSelectionEnd() - wordRangeStartOffset)); + selected = selected.intersection(new TextRange(0, myEditor.getDocument().getTextLength())); + if (selectionModel.hasSelection() && selected != null && !selected.isEmpty()) { + myEditor.getSelectionModel().setSelection(selected.getStartOffset(), selected.getEndOffset()); } + else if (shouldSelectAll()) { + myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength()); + } + break; } }; SwingUtilities.invokeLater(selectionRunnable); @@ -123,31 +120,25 @@ public class NameSuggestionsField extends JPanel { } public void selectNameWithoutExtension() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Editor editor = getEditor(); - if (editor == null) return; - final int pos = editor.getDocument().getText().lastIndexOf('.'); - if (pos > 0) { - editor.getSelectionModel().setSelection(0, pos); - editor.getCaretModel().moveToOffset(pos); - } + SwingUtilities.invokeLater(() -> { + Editor editor = getEditor(); + if (editor == null) return; + final int pos = editor.getDocument().getText().lastIndexOf('.'); + if (pos > 0) { + editor.getSelectionModel().setSelection(0, pos); + editor.getCaretModel().moveToOffset(pos); } }); } public void select(final int start, final int end) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Editor editor = getEditor(); - if (editor == null) return; - editor.getSelectionModel().setSelection(start, end); - editor.getCaretModel().moveToOffset(end); + SwingUtilities.invokeLater(() -> { + Editor editor = getEditor(); + if (editor == null) return; + editor.getSelectionModel().setSelection(start, end); + editor.getCaretModel().moveToOffset(end); - } }); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/ui/RefactoringDialog.java b/platform/lang-impl/src/com/intellij/refactoring/ui/RefactoringDialog.java index f27c4a662fec..c33fcae49917 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/ui/RefactoringDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/ui/RefactoringDialog.java @@ -178,12 +178,7 @@ public abstract class RefactoringDialog extends DialogWrapper { } protected void invokeRefactoring(BaseRefactoringProcessor processor) { - final Runnable prepareSuccessfulCallback = new Runnable() { - @Override - public void run() { - close(DialogWrapper.OK_EXIT_CODE); - } - }; + final Runnable prepareSuccessfulCallback = () -> close(DialogWrapper.OK_EXIT_CODE); processor.setPrepareSuccessfulSwingThreadCallback(prepareSuccessfulCallback); processor.setPreviewUsages(isPreviewUsages()); processor.run(); diff --git a/platform/lang-impl/src/com/intellij/refactoring/util/RefactoringUIUtil.java b/platform/lang-impl/src/com/intellij/refactoring/util/RefactoringUIUtil.java index e64d5faa977d..2fd10d6bf7d2 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/util/RefactoringUIUtil.java +++ b/platform/lang-impl/src/com/intellij/refactoring/util/RefactoringUIUtil.java @@ -59,12 +59,8 @@ public class RefactoringUIUtil { } final String s = message; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(project, s, RefactoringBundle.message("error.title"), Messages.getErrorIcon()); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showMessageDialog(project, s, RefactoringBundle.message("error.title"), Messages.getErrorIcon())); } public static String calculatePsiElementDescriptionList(PsiElement[] elements) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/util/TextOccurrencesUtil.java b/platform/lang-impl/src/com/intellij/refactoring/util/TextOccurrencesUtil.java index f700ecfe6554..969991d25c73 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/util/TextOccurrencesUtil.java +++ b/platform/lang-impl/src/com/intellij/refactoring/util/TextOccurrencesUtil.java @@ -47,12 +47,9 @@ public class TextOccurrencesUtil { @NotNull GlobalSearchScope searchScope, @NotNull final Collection results, @NotNull final UsageInfoFactory factory) { - PsiSearchHelperImpl.processTextOccurrences(element, stringToSearch, searchScope, new Processor() { - @Override - public boolean process(UsageInfo t) { - results.add(t); - return true; - } + PsiSearchHelperImpl.processTextOccurrences(element, stringToSearch, searchScope, t -> { + results.add(t); + return true; }, factory); } @@ -83,12 +80,7 @@ public class TextOccurrencesUtil { PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(element.getProject()); SearchScope scope = helper.getUseScope(element); scope = GlobalSearchScope.projectScope(element.getProject()).intersectWith(scope); - Processor commentOrLiteralProcessor = new Processor() { - @Override - public boolean process(PsiElement literal) { - return processTextIn(literal, stringToSearch, ignoreReferences, processor); - } - }; + Processor commentOrLiteralProcessor = literal -> processTextIn(literal, stringToSearch, ignoreReferences, processor); return processStringLiteralsContainingIdentifier(stringToSearch, scope, helper, commentOrLiteralProcessor) && helper.processCommentsContainingIdentifier(stringToSearch, scope, commentOrLiteralProcessor); } @@ -98,17 +90,14 @@ public class TextOccurrencesUtil { @NotNull final Collection results, @NotNull final UsageInfoFactory factory) { final Object lock = new Object(); - processUsagesInStringsAndComments(element, stringToSearch, false, new PairProcessor() { - @Override - public boolean process(PsiElement commentOrLiteral, TextRange textRange) { - UsageInfo usageInfo = factory.createUsageInfo(commentOrLiteral, textRange.getStartOffset(), textRange.getEndOffset()); - if (usageInfo != null) { - synchronized (lock) { - results.add(usageInfo); - } + processUsagesInStringsAndComments(element, stringToSearch, false, (commentOrLiteral, textRange) -> { + UsageInfo usageInfo = factory.createUsageInfo(commentOrLiteral, textRange.getStartOffset(), textRange.getEndOffset()); + if (usageInfo != null) { + synchronized (lock) { + results.add(usageInfo); } - return true; } + return true; }); } diff --git a/platform/lang-impl/src/com/intellij/semantic/SemServiceImpl.java b/platform/lang-impl/src/com/intellij/semantic/SemServiceImpl.java index 4c8ba6c67ba4..23719e7ce05b 100644 --- a/platform/lang-impl/src/com/intellij/semantic/SemServiceImpl.java +++ b/platform/lang-impl/src/com/intellij/semantic/SemServiceImpl.java @@ -64,24 +64,18 @@ public class SemServiceImpl extends SemService{ } }); - ((PsiManagerEx)psiManager).registerRunnableToRunOnChange(new Runnable() { - @Override - public void run() { - if (!isInsideAtomicChange()) { - clearCache(); - } + ((PsiManagerEx)psiManager).registerRunnableToRunOnChange(() -> { + if (!isInsideAtomicChange()) { + clearCache(); } }); - LowMemoryWatcher.register(new Runnable() { - @Override - public void run() { - if (myCreatingSem.get() == 0) { - clearCache(); - } - //System.out.println("SemService cache flushed"); + LowMemoryWatcher.register(() -> { + if (myCreatingSem.get() == 0) { + clearCache(); } + //System.out.println("SemService cache flushed"); }, project); } @@ -93,14 +87,11 @@ public class SemServiceImpl extends SemService{ public void registerSemElementProvider(SemKey key, final ElementPattern place, final NullableFunction provider) { - map.putValue(key, new NullableFunction() { - @Override - public SemElement fun(PsiElement element) { - if (place.accepts(element)) { - return provider.fun((V)element); - } - return null; + map.putValue(key, element -> { + if (place.accepts(element)) { + return provider.fun((V)element); } + return null; }); } }; diff --git a/platform/lang-impl/src/com/intellij/slicer/SliceNode.java b/platform/lang-impl/src/com/intellij/slicer/SliceNode.java index 3d313786691c..8e2450d1077b 100644 --- a/platform/lang-impl/src/com/intellij/slicer/SliceNode.java +++ b/platform/lang-impl/src/com/intellij/slicer/SliceNode.java @@ -104,17 +104,14 @@ public class SliceNode extends AbstractTreeNode implements Duplicate // } //}); }, () -> { - Processor processor = new Processor() { - @Override - public boolean process(SliceUsage sliceUsage) { - progress.checkCanceled(); - SliceNode node = new SliceNode(myProject, sliceUsage, targetEqualUsages); - synchronized (children) { - node.index = children.size(); - children.add(node); - } - return true; + Processor processor = sliceUsage -> { + progress.checkCanceled(); + SliceNode node = new SliceNode(myProject, sliceUsage, targetEqualUsages); + synchronized (children) { + node.index = children.size(); + children.add(node); } + return true; }; getValue().processChildren(processor); diff --git a/platform/lang-impl/src/com/intellij/testIntegration/TestFinderHelper.java b/platform/lang-impl/src/com/intellij/testIntegration/TestFinderHelper.java index 029821cea07a..61a0e0adadd9 100644 --- a/platform/lang-impl/src/com/intellij/testIntegration/TestFinderHelper.java +++ b/platform/lang-impl/src/com/intellij/testIntegration/TestFinderHelper.java @@ -79,15 +79,12 @@ public class TestFinderHelper { public static List getSortedElements(final List> elementsWithWeights, final boolean weightsAscending, @Nullable final Comparator sameNameComparator) { - Collections.sort(elementsWithWeights, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - int result = weightsAscending ? o1.second.compareTo(o2.second) : o2.second.compareTo(o1.second); - if (result == 0) result = Comparing.compare(o1.first.getName(), o2.first.getName()); - if (result == 0 && sameNameComparator != null) result = sameNameComparator.compare(o1.first, o2.first); + Collections.sort(elementsWithWeights, (o1, o2) -> { + int result = weightsAscending ? o1.second.compareTo(o2.second) : o2.second.compareTo(o1.second); + if (result == 0) result = Comparing.compare(o1.first.getName(), o2.first.getName()); + if (result == 0 && sameNameComparator != null) result = sameNameComparator.compare(o1.first, o2.first); - return result; - } + return result; }); final List result = new ArrayList(elementsWithWeights.size()); diff --git a/platform/lang-impl/src/com/intellij/tools/AbstractToolBeforeRunTask.java b/platform/lang-impl/src/com/intellij/tools/AbstractToolBeforeRunTask.java index d2d80aaeb05a..c9af72166653 100644 --- a/platform/lang-impl/src/com/intellij/tools/AbstractToolBeforeRunTask.java +++ b/platform/lang-impl/src/com/intellij/tools/AbstractToolBeforeRunTask.java @@ -81,22 +81,17 @@ public abstract class AbstractToolBeforeRunTask result = new Ref(false); try { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - ToolAction.runTool(myToolActionId, context, null, executionId, new ProcessAdapter() { - public void startNotified(final ProcessEvent event) { - targetDone.down(); - } - - @Override - public void processTerminated(ProcessEvent event) { - result.set(event.getExitCode() == 0); - targetDone.up(); - } - }); + ApplicationManager.getApplication().invokeAndWait(() -> ToolAction.runTool(myToolActionId, context, null, executionId, new ProcessAdapter() { + public void startNotified(final ProcessEvent event) { + targetDone.down(); } - }, ModalityState.NON_MODAL); + + @Override + public void processTerminated(ProcessEvent event) { + result.set(event.getExitCode() == 0); + targetDone.up(); + } + }), ModalityState.NON_MODAL); } catch (Exception e) { LOG.error(e); diff --git a/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java b/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java index 53d15d581927..abfbee9b4af5 100644 --- a/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java +++ b/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java @@ -57,32 +57,29 @@ public class ScanSourceCommentsAction extends AnAction { final PrintStream stream = new PrintStream(file); stream.println("Comments in " + p.getName()); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - ProjectRootManager.getInstance(p).getFileIndex().iterateContent(new ContentIterator() { - @Override - public boolean processFile(VirtualFile fileOrDir) { - if (fileOrDir.isDirectory()) { - indicator.setText("Extracting comments"); - indicator.setText2(fileOrDir.getPresentableUrl()); - } - scanCommentsInFile(p, fileOrDir); - return true; + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + ProjectRootManager.getInstance(p).getFileIndex().iterateContent(new ContentIterator() { + @Override + public boolean processFile(VirtualFile fileOrDir) { + if (fileOrDir.isDirectory()) { + indicator.setText("Extracting comments"); + indicator.setText2(fileOrDir.getPresentableUrl()); } - }); - - indicator.setText2(""); - int count = 1; - for (CommentDescriptor descriptor : myComments.values()) { - stream.println("#" + count + " ---------------------------------------------------------------"); - descriptor.print(stream); - stream.println(); - count++; + scanCommentsInFile(p, fileOrDir); + return true; } + }); + indicator.setText2(""); + int count = 1; + for (CommentDescriptor descriptor : myComments.values()) { + stream.println("#" + count + " ---------------------------------------------------------------"); + descriptor.print(stream); + stream.println(); + count++; } + }, "Generating Comments", true, p); @@ -109,20 +106,17 @@ public class ScanSourceCommentsAction extends AnAction { private void scanCommentsInFile(final Project project, final VirtualFile vFile) { if (!vFile.isDirectory() && vFile.getFileType() instanceof LanguageFileType) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); - if (psiFile == null) return; + ApplicationManager.getApplication().runReadAction(() -> { + PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); + if (psiFile == null) return; - for (PsiFile root : psiFile.getViewProvider().getAllFiles()) { - root.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitComment(PsiComment comment) { - commentFound(vFile, comment.getText()); - } - }); - } + for (PsiFile root : psiFile.getViewProvider().getAllFiles()) { + root.accept(new PsiRecursiveElementWalkingVisitor() { + @Override + public void visitComment(PsiComment comment) { + commentFound(vFile, comment.getText()); + } + }); } }); } diff --git a/platform/lang-impl/src/com/intellij/tools/ToolEditorDialog.java b/platform/lang-impl/src/com/intellij/tools/ToolEditorDialog.java index 4b61c5a108a4..3c6f2f7f5148 100644 --- a/platform/lang-impl/src/com/intellij/tools/ToolEditorDialog.java +++ b/platform/lang-impl/src/com/intellij/tools/ToolEditorDialog.java @@ -324,13 +324,10 @@ public class ToolEditorDialog extends DialogWrapper { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); PathChooserDialog chooser = FileChooserFactory.getInstance().createPathChooser(descriptor, myProject, pane); - chooser.choose(null, new Consumer>() { - @Override - public void consume(List files) { - VirtualFile file = !files.isEmpty() ? files.get(0) : null; - if (file != null) { - myTfCommandWorkingDirectory.setText(file.getPresentableUrl()); - } + chooser.choose(null, files -> { + VirtualFile file = !files.isEmpty() ? files.get(0) : null; + if (file != null) { + myTfCommandWorkingDirectory.setText(file.getPresentableUrl()); } }); } @@ -345,18 +342,15 @@ public class ToolEditorDialog extends DialogWrapper { public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileOrExecutableAppDescriptor(); PathChooserDialog chooser = FileChooserFactory.getInstance().createPathChooser(descriptor, myProject, pane); - chooser.choose(null, new Consumer>() { - @Override - public void consume(List files) { - VirtualFile file = !files.isEmpty() ? files.get(0) : null; - if (file != null) { - myTfCommand.setText(file.getPresentableUrl()); - String workingDirectory = myTfCommandWorkingDirectory.getText(); - if (workingDirectory == null || workingDirectory.isEmpty()) { - VirtualFile parent = file.getParent(); - if (parent != null && parent.isDirectory()) { - myTfCommandWorkingDirectory.setText(parent.getPresentableUrl()); - } + chooser.choose(null, files -> { + VirtualFile file = !files.isEmpty() ? files.get(0) : null; + if (file != null) { + myTfCommand.setText(file.getPresentableUrl()); + String workingDirectory = myTfCommandWorkingDirectory.getText(); + if (workingDirectory == null || workingDirectory.isEmpty()) { + VirtualFile parent = file.getParent(); + if (parent != null && parent.isDirectory()) { + myTfCommandWorkingDirectory.setText(parent.getPresentableUrl()); } } } diff --git a/platform/lang-impl/src/com/intellij/tools/ToolProcessAdapter.java b/platform/lang-impl/src/com/intellij/tools/ToolProcessAdapter.java index 713392ce2489..c621af5bdaa0 100644 --- a/platform/lang-impl/src/com/intellij/tools/ToolProcessAdapter.java +++ b/platform/lang-impl/src/com/intellij/tools/ToolProcessAdapter.java @@ -44,21 +44,15 @@ public class ToolProcessAdapter extends ProcessAdapter { final String message = ToolsBundle.message("tools.completed.message", myName, event.getExitCode()); if (mySynchronizeAfterExecution) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - VirtualFileManager.getInstance().asyncRefresh(new Runnable() { - @Override - public void run() { - if (ProjectManagerEx.getInstanceEx().isProjectOpened(myProject)) { - StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject); - if (statusBar != null) { - statusBar.setInfo(message); - } - } + ApplicationManager.getApplication().runReadAction(() -> { + VirtualFileManager.getInstance().asyncRefresh(() -> { + if (ProjectManagerEx.getInstanceEx().isProjectOpened(myProject)) { + StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject); + if (statusBar != null) { + statusBar.setInfo(message); } - }); - } + } + }); }); } if (ProjectManagerEx.getInstanceEx().isProjectOpened(myProject)) { diff --git a/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java b/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java index 2110fafab7a2..45dc9e1814fc 100644 --- a/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java +++ b/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java @@ -129,88 +129,69 @@ public class DeferredIconImpl implements DeferredIcon, RetrievableIcon, Scala final Component target = getTarget(c); final Component paintingParent = SwingUtilities.getAncestorOfClass(PaintingParent.class, c); final Rectangle paintingParentRec = paintingParent == null ? null : ((PaintingParent)paintingParent).getChildRec(c); - ourIconsCalculatingExecutor.execute(new Runnable() { - @Override - public void run() { - int oldWidth = myDelegateIcon.getIconWidth(); - final Icon[] evaluated = new Icon[1]; + ourIconsCalculatingExecutor.execute(() -> { + int oldWidth = myDelegateIcon.getIconWidth(); + final Icon[] evaluated = new Icon[1]; - final long startTime = System.currentTimeMillis(); - if (myNeedReadAction) { - boolean result = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(new Runnable() { - @Override - public void run() { - IconDeferrerImpl.evaluateDeferred(new Runnable() { - @Override - public void run() { - evaluated[0] = evaluate(); - } - }); - if (myAutoUpdatable) { - myLastCalcTime = System.currentTimeMillis(); - myLastTimeSpent = myLastCalcTime - startTime; - } - } - }); - if (!result) { - myIsScheduled = false; - return; - } - } - else { - IconDeferrerImpl.evaluateDeferred(new Runnable() { - @Override - public void run() { - evaluated[0] = evaluate(); - } - }); + final long startTime = System.currentTimeMillis(); + if (myNeedReadAction) { + boolean result = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(() -> { + IconDeferrerImpl.evaluateDeferred(() -> evaluated[0] = evaluate()); if (myAutoUpdatable) { myLastCalcTime = System.currentTimeMillis(); myLastTimeSpent = myLastCalcTime - startTime; } + }); + if (!result) { + myIsScheduled = false; + return; } - final Icon result = evaluated[0]; - myDelegateIcon = result; - checkDelegationDepth(); + } + else { + IconDeferrerImpl.evaluateDeferred(() -> evaluated[0] = evaluate()); + if (myAutoUpdatable) { + myLastCalcTime = System.currentTimeMillis(); + myLastTimeSpent = myLastCalcTime - startTime; + } + } + final Icon result = evaluated[0]; + myDelegateIcon = result; + checkDelegationDepth(); - final boolean shouldRevalidate = - Registry.is("ide.tree.deferred.icon.invalidates.cache") && myDelegateIcon.getIconWidth() != oldWidth; + final boolean shouldRevalidate = + Registry.is("ide.tree.deferred.icon.invalidates.cache") && myDelegateIcon.getIconWidth() != oldWidth; - ourLaterInvocator.offer(new Runnable() { - @Override - public void run() { - setDone(result); + ourLaterInvocator.offer(() -> { + setDone(result); - Component actualTarget = target; - if (actualTarget != null && SwingUtilities.getWindowAncestor(actualTarget) == null) { - actualTarget = paintingParent; - if (actualTarget == null || SwingUtilities.getWindowAncestor(actualTarget) == null) { - actualTarget = null; - } - } + Component actualTarget = target; + if (actualTarget != null && SwingUtilities.getWindowAncestor(actualTarget) == null) { + actualTarget = paintingParent; + if (actualTarget == null || SwingUtilities.getWindowAncestor(actualTarget) == null) { + actualTarget = null; + } + } - if (actualTarget == null) return; + if (actualTarget == null) return; - if (shouldRevalidate) { - // revalidate will not work: JTree caches size of nodes - if (actualTarget instanceof JTree) { - final TreeUI ui = ((JTree)actualTarget).getUI(); - if (ui instanceof BasicTreeUI) { - // this call is "fake" and only need to reset tree layout cache - ((BasicTreeUI)ui).setLeftChildIndent(UIUtil.getTreeLeftChildIndent()); - } - } - } - - if (c == actualTarget) { - c.repaint(x, y, getIconWidth(), getIconHeight()); - } - else { - ourRepaintScheduler.pushDirtyComponent(actualTarget, paintingParentRec); + if (shouldRevalidate) { + // revalidate will not work: JTree caches size of nodes + if (actualTarget instanceof JTree) { + final TreeUI ui = ((JTree)actualTarget).getUI(); + if (ui instanceof BasicTreeUI) { + // this call is "fake" and only need to reset tree layout cache + ((BasicTreeUI)ui).setLeftChildIndent(UIUtil.getTreeLeftChildIndent()); } } - }); - } + } + + if (c == actualTarget) { + c.repaint(x, y, getIconWidth(), getIconHeight()); + } + else { + ourRepaintScheduler.pushDirtyComponent(actualTarget, paintingParentRec); + } + }); }); } @@ -332,20 +313,17 @@ public class DeferredIconImpl implements DeferredIcon, RetrievableIcon, Scala private void pushDirtyComponent(@NotNull Component c, final Rectangle rec) { ApplicationManager.getApplication().assertIsDispatchThread(); // assert myQueue accessed from EDT only myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - for (RepaintRequest each : myQueue) { - Rectangle r = each.getRectangle(); - if (r == null) { - each.getComponent().repaint(); - } - else { - each.getComponent().repaint(r.x, r.y, r.width, r.height); - } + myAlarm.addRequest(() -> { + for (RepaintRequest each : myQueue) { + Rectangle r = each.getRectangle(); + if (r == null) { + each.getComponent().repaint(); + } + else { + each.getComponent().repaint(r.x, r.y, r.width, r.height); } - myQueue.clear(); } + myQueue.clear(); }, 50); myQueue.add(new RepaintRequest(c, rec)); diff --git a/platform/lang-impl/src/com/intellij/ui/EditorTextFieldActionPromoter.java b/platform/lang-impl/src/com/intellij/ui/EditorTextFieldActionPromoter.java index f7ae9d6e0a83..771e3f347e89 100644 --- a/platform/lang-impl/src/com/intellij/ui/EditorTextFieldActionPromoter.java +++ b/platform/lang-impl/src/com/intellij/ui/EditorTextFieldActionPromoter.java @@ -41,17 +41,14 @@ public class EditorTextFieldActionPromoter implements ActionPromoter { * 'expand/reduce selection by word' editor action and 'change dialog width' non-editor action * and we want to use the first one. */ - private static final Comparator ACTIONS_COMPARATOR = new Comparator() { - @Override - public int compare(AnAction o1, AnAction o2) { - boolean textFieldAction1 = o1 instanceof TextComponentEditorAction; - boolean textFieldAction2 = o2 instanceof TextComponentEditorAction; - boolean plainEditorAction1 = o1 instanceof EditorAction && !textFieldAction1; - boolean plainEditorAction2 = o2 instanceof EditorAction && !textFieldAction2; - if (textFieldAction1 && plainEditorAction2) return -1; - if (textFieldAction2 && plainEditorAction1) return 1; - return 0; - } + private static final Comparator ACTIONS_COMPARATOR = (o1, o2) -> { + boolean textFieldAction1 = o1 instanceof TextComponentEditorAction; + boolean textFieldAction2 = o2 instanceof TextComponentEditorAction; + boolean plainEditorAction1 = o1 instanceof EditorAction && !textFieldAction1; + boolean plainEditorAction2 = o2 instanceof EditorAction && !textFieldAction2; + if (textFieldAction1 && plainEditorAction2) return -1; + if (textFieldAction2 && plainEditorAction1) return 1; + return 0; }; @Override diff --git a/platform/lang-impl/src/com/intellij/ui/IconDeferrerImpl.java b/platform/lang-impl/src/com/intellij/ui/IconDeferrerImpl.java index 1ecffdee47e7..94e2c44a9142 100644 --- a/platform/lang-impl/src/com/intellij/ui/IconDeferrerImpl.java +++ b/platform/lang-impl/src/com/intellij/ui/IconDeferrerImpl.java @@ -42,12 +42,7 @@ public class IconDeferrerImpl extends IconDeferrer { }; private long myLastClearTimestamp; @SuppressWarnings("UnusedDeclaration") - private final LowMemoryWatcher myLowMemoryWatcher = LowMemoryWatcher.register(new Runnable() { - @Override - public void run() { - clear(); - } - }); + private final LowMemoryWatcher myLowMemoryWatcher = LowMemoryWatcher.register(() -> clear()); public IconDeferrerImpl(MessageBus bus) { final MessageBusConnection connection = bus.connect(); diff --git a/platform/lang-impl/src/com/intellij/ui/TextFieldWithAutoCompletionListProvider.java b/platform/lang-impl/src/com/intellij/ui/TextFieldWithAutoCompletionListProvider.java index 31fe9d94943e..c56b8986f7a7 100644 --- a/platform/lang-impl/src/com/intellij/ui/TextFieldWithAutoCompletionListProvider.java +++ b/platform/lang-impl/src/com/intellij/ui/TextFieldWithAutoCompletionListProvider.java @@ -99,17 +99,12 @@ public abstract class TextFieldWithAutoCompletionListProvider extends Default final ProgressIndicator indicator = mainIndicator != null ? new SensitiveProgressWrapper(mainIndicator) : new EmptyProgressIndicator(); Future> future = - ApplicationManager.getApplication().executeOnPooledThread(new Callable>() { + ApplicationManager.getApplication().executeOnPooledThread(() -> progressManager.runProcess(new Computable>() { @Override - public Collection call() { - return progressManager.runProcess(new Computable>() { - @Override - public Collection compute() { - return getItems(prefix, false, parameters); - } - }, indicator); + public Collection compute() { + return getItems(prefix, false, parameters); } - }); + }, indicator)); while (true) { try { diff --git a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/ActionTracer.java b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/ActionTracer.java index bc6d8267c89b..4150ec95f14a 100644 --- a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/ActionTracer.java +++ b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/ActionTracer.java @@ -95,12 +95,9 @@ public class ActionTracer implements UiDebuggerExtension, AnActionListener { final Document doc = myText.getDocument(); try { doc.insertString(doc.getLength(), out.toString(), null); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final int y = (int)myText.getBounds().getMaxY(); - myText.scrollRectToVisible(new Rectangle(0, y, myText.getBounds().width, 0)); - } + SwingUtilities.invokeLater(() -> { + final int y = (int)myText.getBounds().getMaxY(); + myText.scrollRectToVisible(new Rectangle(0, y, myText.getBounds().width, 0)); }); } catch (BadLocationException e) { diff --git a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/FocusDebugger.java b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/FocusDebugger.java index 6fc650fa35e1..62d2159adf3b 100644 --- a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/FocusDebugger.java +++ b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/FocusDebugger.java @@ -148,15 +148,12 @@ public class FocusDebugger implements UiDebuggerExtension, PropertyChangeListene myLogModel.addElement(new FocusElement(text, new Throwable())); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myLog != null && myLog.isShowing()) { - final int h = myLog.getFixedCellHeight(); - myLog.scrollRectToVisible(new Rectangle(0, myLog.getPreferredSize().height - h, myLog.getWidth(), h)); - if (myLog.getModel().getSize() > 0) { - myLog.setSelectedIndex(myLog.getModel().getSize() - 1); - } + SwingUtilities.invokeLater(() -> { + if (myLog != null && myLog.isShowing()) { + final int h = myLog.getFixedCellHeight(); + myLog.scrollRectToVisible(new Rectangle(0, myLog.getPreferredSize().height - h, myLog.getWidth(), h)); + if (myLog.getModel().getSize() > 0) { + myLog.setSelectedIndex(myLog.getModel().getSize() - 1); } } }); diff --git a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java index 53a0d9cfbaf5..072f672c94da 100644 --- a/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java +++ b/platform/lang-impl/src/com/intellij/ui/debugger/extensions/PlaybackDebugger.java @@ -190,11 +190,8 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta return; } } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - save(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + save(); }); } } @@ -245,11 +242,8 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta } private void fillDocument(final String text) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myCodeEditor.setText(text == null ? "" : text); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myCodeEditor.setText(text == null ? "" : text); }); } @@ -302,12 +296,7 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta public void actionPerformed(AnActionEvent e) { if (myRunner != null) { myRunner.stop(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myRunner = null; - } - }); + SwingUtilities.invokeLater(() -> myRunner = null); } } } @@ -361,12 +350,7 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta } //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - startWhenFrameActive(); - } - }); + SwingUtilities.invokeLater(() -> startWhenFrameActive()); } @@ -427,17 +411,9 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta final PlaybackRunner runner = myRunner; - myRunner.run().doWhenProcessed(new Runnable() { - @Override - public void run() { - if (runner == myRunner) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myRunner = null; - } - }); - } + myRunner.run().doWhenProcessed(() -> { + if (runner == myRunner) { + SwingUtilities.invokeLater(() -> myRunner = null); } }); } @@ -452,25 +428,22 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta private void message(@Nullable final PlaybackContext context, final String text, final int currentLine, final Type type, final boolean forced) { final int depth = context != null ? context.getCurrentStageDepth() : 0; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (!forced && (context != null && context.isDisposed())) return; + UIUtil.invokeLaterIfNeeded(() -> { + if (!forced && (context != null && context.isDisposed())) return; - switch (type) { - case message: - addInfo(text, currentLine, MESSAGE_COLOR, depth); - break; - case error: - addInfo(text, currentLine, ERROR_COLOR, depth); - break; - case code: - addInfo(text, currentLine, CODE_COLOR, depth); - break; - case test: - addInfo(text, currentLine, TEST_COLOR, depth); - break; - } + switch (type) { + case message: + addInfo(text, currentLine, MESSAGE_COLOR, depth); + break; + case error: + addInfo(text, currentLine, ERROR_COLOR, depth); + break; + case code: + addInfo(text, currentLine, CODE_COLOR, depth); + break; + case test: + addInfo(text, currentLine, TEST_COLOR, depth); + break; } }); } @@ -540,14 +513,11 @@ public class PlaybackDebugger implements UiDebuggerExtension, PlaybackRunner.Sta } private void scrollToLast() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myLog.getDocument().getLength() == 0) return; + SwingUtilities.invokeLater(() -> { + if (myLog.getDocument().getLength() == 0) return; - Rectangle bounds = myLog.getBounds(); - myLog.scrollRectToVisible(new Rectangle(0, (int)bounds.getMaxY() - 1, (int)bounds.getWidth(), 1)); - } + Rectangle bounds = myLog.getBounds(); + myLog.scrollRectToVisible(new Rectangle(0, (int)bounds.getMaxY() - 1, (int)bounds.getWidth(), 1)); }); } diff --git a/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java b/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java index 81d09d7886f8..acbf3755ac9d 100644 --- a/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java +++ b/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java @@ -233,12 +233,9 @@ public class PopupPositionManager { boxes.add(crop(myScreenRect, new Rectangle(myRelativeOnScreen.x, myRelativeOnScreen.y + myRelativeTo.getHeight() + myGap, myScreenRect.width, myScreenRect.height))); - Collections.sort(boxes, new Comparator() { - @Override - public int compare(final Rectangle o1, final Rectangle o2) { - final int i = new Integer(o1.width).compareTo(o2.width); - return i == 0 ? new Integer(o1.height).compareTo(o2.height) : i; - } + Collections.sort(boxes, (o1, o2) -> { + final int i = new Integer(o1.width).compareTo(o2.width); + return i == 0 ? new Integer(o1.height).compareTo(o2.height) : i; }); final Rectangle suitableBox = boxes.get(boxes.size() - 1); diff --git a/platform/lang-impl/src/com/intellij/ui/popup/util/DetailController.java b/platform/lang-impl/src/com/intellij/ui/popup/util/DetailController.java index 0e8bc40cac9e..24b19564ffa8 100644 --- a/platform/lang-impl/src/com/intellij/ui/popup/util/DetailController.java +++ b/platform/lang-impl/src/com/intellij/ui/popup/util/DetailController.java @@ -83,12 +83,9 @@ public class DetailController { doUpdateDetailViewWithItem(mySelectedItem); } else { - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - doUpdateDetailViewWithItem(mySelectedItem); - myUpdateAlarm.cancelAllRequests(); - } + myUpdateAlarm.addRequest(() -> { + doUpdateDetailViewWithItem(mySelectedItem); + myUpdateAlarm.cancelAllRequests(); }, 100); } } diff --git a/platform/lang-impl/src/com/intellij/ui/popup/util/MasterDetailPopupBuilder.java b/platform/lang-impl/src/com/intellij/ui/popup/util/MasterDetailPopupBuilder.java index a095dd09a15e..2ef7c6f63d48 100644 --- a/platform/lang-impl/src/com/intellij/ui/popup/util/MasterDetailPopupBuilder.java +++ b/platform/lang-impl/src/com/intellij/ui/popup/util/MasterDetailPopupBuilder.java @@ -218,17 +218,7 @@ public class MasterDetailPopupBuilder implements MasterController { footerPanel.setBorder(JBUI.Borders.empty(4, 4, 4, SystemInfo.isMac ? 20 : 4)); footerPanel.add(myPathLabel); - Runnable itemCallback = new Runnable() { - @Override - public void run() { - IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - chooseItems(false); - } - }); - } - }; + Runnable itemCallback = () -> IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(() -> chooseItems(false)); JComponent toolBar = null; if (myActions != null) { @@ -250,12 +240,7 @@ public class MasterDetailPopupBuilder implements MasterController { setSettingButton(toolBar). setSouthComponent(footerPanel). setItemChoosenCallback(itemCallback). - setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return ((ItemWrapper)o).speedSearchText(); - } - }); + setFilteringEnabled(o -> ((ItemWrapper)o).speedSearchText()); if (myPopupTuner != null) { myPopupTuner.consume(builder); diff --git a/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java b/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java index ddff95488b2c..07c908a3a21f 100644 --- a/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java +++ b/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java @@ -170,18 +170,10 @@ public class AnalyzeStacktraceUtil { } public final void setText(@NotNull final String text) { - Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Document document = myEditor.getDocument(); - document.replaceString(0, document.getTextLength(), StringUtil.convertLineSeparators(text)); - } - }); - } - }; + Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> { + final Document document = myEditor.getDocument(); + document.replaceString(0, document.getTextLength(), StringUtil.convertLineSeparators(text)); + }); CommandProcessor.getInstance().executeCommand(myProject, runnable, "", this); } diff --git a/platform/lang-impl/src/com/intellij/unscramble/AnnotateStackTraceAction.java b/platform/lang-impl/src/com/intellij/unscramble/AnnotateStackTraceAction.java index e000e02879dc..ec6f4f9bd929 100644 --- a/platform/lang-impl/src/com/intellij/unscramble/AnnotateStackTraceAction.java +++ b/platform/lang-impl/src/com/intellij/unscramble/AnnotateStackTraceAction.java @@ -174,23 +174,20 @@ public class AnnotateStackTraceAction extends AnAction implements DumbAware { final List files = new ArrayList(); final HashMap> files2lines = new HashMap>(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (int line = 0; line < myEditor.getDocument().getLineCount(); line++) { - indicator.checkCanceled(); - VirtualFile file = getHyperlinkVirtualFile(myHyperlinks.findAllHyperlinksOnLine(line)); - if (file == null) continue; + ApplicationManager.getApplication().runReadAction(() -> { + for (int line = 0; line < myEditor.getDocument().getLineCount(); line++) { + indicator.checkCanceled(); + VirtualFile file = getHyperlinkVirtualFile(myHyperlinks.findAllHyperlinksOnLine(line)); + if (file == null) continue; - if (files2lines.containsKey(file)) { - files2lines.get(file).add(line); - } - else { - final ArrayList lines = new ArrayList(); - lines.add(line); - files2lines.put(file, lines); - files.add(file); - } + if (files2lines.containsKey(file)) { + files2lines.get(file).add(line); + } + else { + final ArrayList lines = new ArrayList(); + lines.add(line); + files2lines.put(file, lines); + files.add(file); } } }); @@ -213,15 +210,12 @@ public class AnnotateStackTraceAction extends AnAction implements DumbAware { for (Integer line : lines) { cache.put(line, revision); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!myGutterShowed) { - showGutter(); - } - else { - ((EditorGutterComponentEx)myEditor.getGutter()).revalidateMarkup(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!myGutterShowed) { + showGutter(); + } + else { + ((EditorGutterComponentEx)myEditor.getGutter()).revalidateMarkup(); } }); } diff --git a/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java b/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java index e374d563f628..28af3a52a235 100644 --- a/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java +++ b/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java @@ -149,11 +149,8 @@ public class UsageViewUtil { @NotNull public static PsiElement[] toElements(@NotNull UsageInfo[] usageInfos) { - return ContainerUtil.map2Array(usageInfos, PsiElement.class, new Function() { - @Override - public PsiElement fun(UsageInfo info) { - return info.getElement(); - } + return ContainerUtil.map2Array(usageInfos, PsiElement.class, info -> { + return info.getElement(); }); } diff --git a/platform/lang-impl/src/com/intellij/util/LogicalRootsManagerImpl.java b/platform/lang-impl/src/com/intellij/util/LogicalRootsManagerImpl.java index d7413543e96c..46d982660c0e 100644 --- a/platform/lang-impl/src/com/intellij/util/LogicalRootsManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/util/LogicalRootsManagerImpl.java @@ -65,18 +65,10 @@ public class LogicalRootsManagerImpl extends LogicalRootsManager { bus.asyncPublisher(LOGICAL_ROOTS).logicalRootsChanged(); } }); - registerLogicalRootProvider(LogicalRootType.SOURCE_ROOT, new NotNullFunction>() { - @Override - @NotNull - public List fun(final Module module) { - return ContainerUtil.map2List(ModuleRootManager.getInstance(module).getSourceRoots(), new Function() { - @Override - public VirtualFileLogicalRoot fun(final VirtualFile s) { - return new VirtualFileLogicalRoot(s); - } - }); - } - }); + registerLogicalRootProvider(LogicalRootType.SOURCE_ROOT, + module -> ContainerUtil.map2List(ModuleRootManager.getInstance(module).getSourceRoots(), s -> { + return new VirtualFileLogicalRoot(s); + })); } private synchronized void clear() { @@ -124,11 +116,8 @@ public class LogicalRootsManagerImpl extends LogicalRootsManager { @Override public List getLogicalRoots() { - return ContainerUtil.concat(myModuleManager.getModules(), new Function>() { - @Override - public Collection fun(final Module module) { - return getLogicalRoots(module); - } + return ContainerUtil.concat(myModuleManager.getModules(), module -> { + return getLogicalRoots(module); }); } diff --git a/platform/lang-impl/src/com/intellij/util/PatternValuesIndex.java b/platform/lang-impl/src/com/intellij/util/PatternValuesIndex.java index e7121adc3732..0c6147af0cd9 100644 --- a/platform/lang-impl/src/com/intellij/util/PatternValuesIndex.java +++ b/platform/lang-impl/src/com/intellij/util/PatternValuesIndex.java @@ -29,16 +29,13 @@ public class PatternValuesIndex { public static Set buildStringIndex(Collection> patterns) { final THashSet result = new THashSet(); - processStringValues(patterns, new PairProcessor, Collection>() { - @Override - public boolean process(ElementPattern elementPattern, Collection value) { - for (Object o : value) { - if (o instanceof String) { - result.add((String)o); - } + processStringValues(patterns, (elementPattern, value) -> { + for (Object o : value) { + if (o instanceof String) { + result.add((String)o); } - return true; } + return true; }); return result; } diff --git a/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java b/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java index eb898731da48..fb3ee33f6ffb 100644 --- a/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java +++ b/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java @@ -124,15 +124,12 @@ public class FileDownloaderImpl implements FileDownloader { final Ref>> localFiles = Ref.create(null); final Ref exceptionRef = Ref.create(null); - boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - try { - localFiles.set(download(targetDir)); - } - catch (IOException e) { - exceptionRef.set(e); - } + boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + try { + localFiles.set(download(targetDir)); + } + catch (IOException e) { + exceptionRef.set(e); } }, myDialogTitle, true, project, parentComponent); if (!completed) { @@ -171,46 +168,43 @@ public class FileDownloaderImpl implements FileDownloader { List> results = new ArrayList>(); final AtomicLong totalSize = new AtomicLong(); for (final DownloadableFileDescription description : myFileDescriptions) { - results.add(executor.submit(new Callable() { - @Override - public Void call() throws Exception { - SubTaskProgressIndicator indicator = progressManager.createSubTaskIndicator(); - indicator.checkCanceled(); + results.add(executor.submit(() -> { + SubTaskProgressIndicator indicator = progressManager.createSubTaskIndicator(); + indicator.checkCanceled(); - final File existing = new File(targetDir, description.getDefaultFileName()); - final String url = description.getDownloadUrl(); - if (url.startsWith(LIB_SCHEMA)) { - final String path = FileUtil.toSystemDependentName(StringUtil.trimStart(url, LIB_SCHEMA)); - final File file = PathManager.findFileInLibDirectory(path); + final File existing = new File(targetDir, description.getDefaultFileName()); + final String url = description.getDownloadUrl(); + if (url.startsWith(LIB_SCHEMA)) { + final String path = FileUtil.toSystemDependentName(StringUtil.trimStart(url, LIB_SCHEMA)); + final File file = PathManager.findFileInLibDirectory(path); + existingFiles.add(Pair.create(file, description)); + } + else if (url.startsWith(LocalFileSystem.PROTOCOL_PREFIX)) { + String path = FileUtil.toSystemDependentName(StringUtil.trimStart(url, LocalFileSystem.PROTOCOL_PREFIX)); + File file = new File(path); + if (file.exists()) { existingFiles.add(Pair.create(file, description)); } - else if (url.startsWith(LocalFileSystem.PROTOCOL_PREFIX)) { - String path = FileUtil.toSystemDependentName(StringUtil.trimStart(url, LocalFileSystem.PROTOCOL_PREFIX)); - File file = new File(path); - if (file.exists()) { - existingFiles.add(Pair.create(file, description)); - } + } + else { + File downloaded; + try { + downloaded = downloadFile(description, existing, indicator); + } + catch (IOException e) { + throw new IOException(IdeBundle.message("error.file.download.failed", description.getDownloadUrl(), + e.getMessage()), e); + } + if (FileUtil.filesEqual(downloaded, existing)) { + existingFiles.add(Pair.create(existing, description)); } else { - File downloaded; - try { - downloaded = downloadFile(description, existing, indicator); - } - catch (IOException e) { - throw new IOException(IdeBundle.message("error.file.download.failed", description.getDownloadUrl(), - e.getMessage()), e); - } - if (FileUtil.filesEqual(downloaded, existing)) { - existingFiles.add(Pair.create(existing, description)); - } - else { - totalSize.addAndGet(downloaded.length()); - downloadedFiles.add(Pair.create(downloaded, description)); - } + totalSize.addAndGet(downloaded.length()); + downloadedFiles.add(Pair.create(downloaded, description)); } - indicator.finished(); - return null; } + indicator.finished(); + return null; })); } diff --git a/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java b/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java index 2a17619371bd..9f5794963f5b 100644 --- a/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java +++ b/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java @@ -37,12 +37,8 @@ import java.util.List; * @author nik */ public abstract class FileSetVersionsFetcherBase implements DownloadableFileSetVersions { - private static final Comparator VERSIONS_COMPARATOR = new Comparator() { - @Override - public int compare(DownloadableFileSetDescription o1, DownloadableFileSetDescription o2) { - return -StringUtil.compareVersionNumbers(o1.getVersionString(), o2.getVersionString()); - } - }; + private static final Comparator VERSIONS_COMPARATOR = + (o1, o2) -> -StringUtil.compareVersionNumbers(o1.getVersionString(), o2.getVersionString()); protected final String myGroupId; private final URL[] myLocalUrls; @@ -53,12 +49,7 @@ public abstract class FileSetVersionsFetcherBase callback) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - callback.onSuccess(fetchVersions()); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> callback.onSuccess(fetchVersions())); } @NotNull diff --git a/platform/lang-impl/src/com/intellij/util/indexing/ContentHashesSupport.java b/platform/lang-impl/src/com/intellij/util/indexing/ContentHashesSupport.java index 24044cd97c4b..5f8089dfc8e4 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/ContentHashesSupport.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/ContentHashesSupport.java @@ -43,18 +43,8 @@ class ContentHashesSupport { final File hashEnumeratorFile = new File(IndexInfrastructure.getPersistentIndexRoot(), "hashesWithFileType"); try { hashEnumerator = new ContentHashesUtil.HashEnumerator(hashEnumeratorFile, null); - FlushingDaemon.everyFiveSeconds(new Runnable() { - @Override - public void run() { - flushContentHashes(); - } - }); - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - flushContentHashes(); - } - }); + FlushingDaemon.everyFiveSeconds(() -> flushContentHashes()); + ShutDownTracker.getInstance().registerShutdownTask(() -> flushContentHashes()); ourHashesWithFileType = hashEnumerator; } catch (IOException ex) { IOUtil.deleteAllFilesStartingWith(hashEnumeratorFile); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java index 7ef7eaf8ba4f..9599eee86951 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java @@ -380,11 +380,8 @@ public class FileBasedIndexImpl extends FileBasedIndex { final Set addedTypes = new THashSet(); if (inputFilter instanceof FileBasedIndex.FileTypeSpecificInputFilter) { - ((FileBasedIndex.FileTypeSpecificInputFilter)inputFilter).registerFileTypesUsedForIndexing(new Consumer() { - @Override - public void consume(FileType type) { - if (type != null) addedTypes.add(type); - } + ((FileBasedIndex.FileTypeSpecificInputFilter)inputFilter).registerFileTypesUsedForIndexing(type -> { + if (type != null) addedTypes.add(type); }); } @@ -545,12 +542,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { final List> states = IndexingStamp.getNontrivialFileIndexedStates(fileId); if (!states.isEmpty()) { - ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { - @Override - public void run() { - removeFileDataFromIndices(states, fileId); - } - }); + ProgressManager.getInstance().executeNonCancelableSection(() -> removeFileDataFromIndices(states, fileId)); } } @@ -865,51 +857,48 @@ public class FileBasedIndexImpl extends FileBasedIndex { @Nullable final VirtualFile restrictToFile, @NotNull final ValueProcessor processor, @NotNull final GlobalSearchScope scope, @Nullable final IdFilter idFilter) { ThrowableConvertor, Boolean, StorageException> keyProcessor = - new ThrowableConvertor, Boolean, StorageException>() { - @Override - public Boolean convert(@NotNull UpdatableIndex index) throws StorageException { - final ValueContainer container = index.getData(dataKey); + index -> { + final ValueContainer container = index.getData(dataKey); - boolean shouldContinue = true; + boolean shouldContinue = true; - if (restrictToFile != null) { - if (restrictToFile instanceof VirtualFileWithId) { - final int restrictedFileId = getFileId(restrictToFile); - for (final ValueContainer.ValueIterator valueIt = container.getValueIterator(); valueIt.hasNext(); ) { - final V value = valueIt.next(); - if (valueIt.getValueAssociationPredicate().contains(restrictedFileId)) { - shouldContinue = processor.process(restrictToFile, value); - if (!shouldContinue) { - break; - } - } - } - } - } - else { - final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); - final IdFilter filter = idFilter != null ? idFilter : projectIndexableFiles(scope.getProject()); - VALUES_LOOP: + if (restrictToFile != null) { + if (restrictToFile instanceof VirtualFileWithId) { + final int restrictedFileId = getFileId(restrictToFile); for (final ValueContainer.ValueIterator valueIt = container.getValueIterator(); valueIt.hasNext(); ) { final V value = valueIt.next(); - for (final ValueContainer.IntIterator inputIdsIterator = valueIt.getInputIdsIterator(); inputIdsIterator.hasNext(); ) { - final int id = inputIdsIterator.next(); - if (filter != null && !filter.containsFileId(id)) continue; - VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); - if (file != null && scope.accept(file)) { - shouldContinue = processor.process(file, value); - if (!shouldContinue) { - break VALUES_LOOP; - } - if (ensureValueProcessedOnce) { - break; // continue with the next value - } + if (valueIt.getValueAssociationPredicate().contains(restrictedFileId)) { + shouldContinue = processor.process(restrictToFile, value); + if (!shouldContinue) { + break; } } } } - return shouldContinue; } + else { + final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); + final IdFilter filter = idFilter != null ? idFilter : projectIndexableFiles(scope.getProject()); + VALUES_LOOP: + for (final ValueContainer.ValueIterator valueIt = container.getValueIterator(); valueIt.hasNext(); ) { + final V value = valueIt.next(); + for (final ValueContainer.IntIterator inputIdsIterator = valueIt.getInputIdsIterator(); inputIdsIterator.hasNext(); ) { + final int id = inputIdsIterator.next(); + if (filter != null && !filter.containsFileId(id)) continue; + VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); + if (file != null && scope.accept(file)) { + shouldContinue = processor.process(file, value); + if (!shouldContinue) { + break VALUES_LOOP; + } + if (ensureValueProcessedOnce) { + break; // continue with the next value + } + } + } + } + } + return shouldContinue; }; final Boolean result = processExceptions(indexId, restrictToFile, scope, keyProcessor); return result == null || result.booleanValue(); @@ -1047,56 +1036,52 @@ public class FileBasedIndexImpl extends FileBasedIndex { @Nullable final Condition valueChecker, @Nullable final ProjectIndexableFilesFilter projectFilesFilter) { final ThrowableConvertor, TIntHashSet, StorageException> convertor = - new ThrowableConvertor, TIntHashSet, StorageException>() { - @Nullable - @Override - public TIntHashSet convert(@NotNull UpdatableIndex index) throws StorageException { - TIntHashSet mainIntersection = null; + index -> { + TIntHashSet mainIntersection = null; - for (K dataKey : dataKeys) { - ProgressManager.checkCanceled(); - final TIntHashSet copy = new TIntHashSet(); - final ValueContainer container = index.getData(dataKey); + for (K dataKey : dataKeys) { + ProgressManager.checkCanceled(); + final TIntHashSet copy = new TIntHashSet(); + final ValueContainer container = index.getData(dataKey); - for (final ValueContainer.ValueIterator valueIt = container.getValueIterator(); valueIt.hasNext(); ) { - final V value = valueIt.next(); - if (valueChecker != null && !valueChecker.value(value)) { - continue; - } - - ValueContainer.IntIterator iterator = valueIt.getInputIdsIterator(); - - if (mainIntersection == null || iterator.size() < mainIntersection.size()) { - while (iterator.hasNext()) { - final int id = iterator.next(); - if (mainIntersection == null && (projectFilesFilter == null || projectFilesFilter.containsFileId(id)) || - mainIntersection != null && mainIntersection.contains(id) - ) { - copy.add(id); - } - } - } - else { - mainIntersection.forEach(new TIntProcedure() { - final ValueContainer.IntPredicate predicate = valueIt.getValueAssociationPredicate(); - - @Override - public boolean execute(int id) { - if (predicate.contains(id)) copy.add(id); - return true; - } - }); - } + for (final ValueContainer.ValueIterator valueIt = container.getValueIterator(); valueIt.hasNext(); ) { + final V value = valueIt.next(); + if (valueChecker != null && !valueChecker.value(value)) { + continue; } - mainIntersection = copy; - if (mainIntersection.isEmpty()) { - return new TIntHashSet(); + ValueContainer.IntIterator iterator = valueIt.getInputIdsIterator(); + + if (mainIntersection == null || iterator.size() < mainIntersection.size()) { + while (iterator.hasNext()) { + final int id = iterator.next(); + if (mainIntersection == null && (projectFilesFilter == null || projectFilesFilter.containsFileId(id)) || + mainIntersection != null && mainIntersection.contains(id) + ) { + copy.add(id); + } + } + } + else { + mainIntersection.forEach(new TIntProcedure() { + final ValueContainer.IntPredicate predicate = valueIt.getValueAssociationPredicate(); + + @Override + public boolean execute(int id) { + if (predicate.contains(id)) copy.add(id); + return true; + } + }); } } - return mainIntersection; + mainIntersection = copy; + if (mainIntersection.isEmpty()) { + return new TIntHashSet(); + } } + + return mainIntersection; }; @@ -1311,43 +1296,40 @@ public class FileBasedIndexImpl extends FileBasedIndex { if (previousDocStamp == currentDocStamp) return false; final CharSequence contentText = content.getText(); - myFileTypeManager.freezeFileTypeTemporarilyIn(vFile, new Runnable() { - @Override - public void run() { - if (!isTooLarge(vFile, contentText.length()) && - getAffectedIndexCandidates(vFile).contains(requestedIndexId) && - getInputFilter(requestedIndexId).acceptInput(vFile)) { - // Reasonably attempt to use same file content when calculating indices as we can evaluate them several at once and store in file content - WeakReference previousContentRef = document.getUserData(ourFileContentKey); - FileContentImpl previousContent = com.intellij.reference.SoftReference.dereference(previousContentRef); - final FileContentImpl newFc; - if (previousContent != null && previousContent.getStamp() == currentDocStamp) { - newFc = previousContent; - } - else { - newFc = new FileContentImpl(vFile, contentText, vFile.getCharset(), currentDocStamp); - document.putUserData(ourFileContentKey, new WeakReference(newFc)); - } - - initFileContent(newFc, project, dominantContentFile); - - if (content instanceof AuthenticContent) { - newFc.putUserData(PlatformIdTableBuilding.EDITOR_HIGHLIGHTER, - EditorHighlighterCache.getEditorHighlighterForCachesBuilding(document)); - } - - final int inputId = Math.abs(getFileId(vFile)); - try { - getIndex(requestedIndexId).update(inputId, newFc).compute(); - } - finally { - cleanFileContent(newFc, dominantContentFile); - } + myFileTypeManager.freezeFileTypeTemporarilyIn(vFile, () -> { + if (!isTooLarge(vFile, contentText.length()) && + getAffectedIndexCandidates(vFile).contains(requestedIndexId) && + getInputFilter(requestedIndexId).acceptInput(vFile)) { + // Reasonably attempt to use same file content when calculating indices as we can evaluate them several at once and store in file content + WeakReference previousContentRef = document.getUserData(ourFileContentKey); + FileContentImpl previousContent = com.intellij.reference.SoftReference.dereference(previousContentRef); + final FileContentImpl newFc; + if (previousContent != null && previousContent.getStamp() == currentDocStamp) { + newFc = previousContent; + } + else { + newFc = new FileContentImpl(vFile, contentText, vFile.getCharset(), currentDocStamp); + document.putUserData(ourFileContentKey, new WeakReference(newFc)); } - long previousState = myLastIndexedDocStamps.set(document, requestedIndexId, currentDocStamp); - assert previousState == previousDocStamp; + initFileContent(newFc, project, dominantContentFile); + + if (content instanceof AuthenticContent) { + newFc.putUserData(PlatformIdTableBuilding.EDITOR_HIGHLIGHTER, + EditorHighlighterCache.getEditorHighlighterForCachesBuilding(document)); + } + + final int inputId = Math.abs(getFileId(vFile)); + try { + getIndex(requestedIndexId).update(inputId, newFc).compute(); + } + finally { + cleanFileContent(newFc, dominantContentFile); + } } + + long previousState = myLastIndexedDocStamps.set(document, requestedIndexId, currentDocStamp); + assert previousState == previousDocStamp; }); return true; @@ -1419,28 +1401,25 @@ public class FileBasedIndexImpl extends FileBasedIndex { if (!myInitialized) return; advanceIndexVersion(indexId); - final Runnable rebuildRunnable = new Runnable() { - @Override - public void run() { - final Ref success = Ref.create(true); - new Task.Modal(null, "Updating index", false) { - @Override - public void run(@NotNull final ProgressIndicator indicator) { - indicator.setIndeterminate(true); - try { - doClearIndex(indexId); - } - catch (StorageException e) { - success.set(false); - requestRebuild(indexId); - LOG.info(e); - } + final Runnable rebuildRunnable = () -> { + final Ref success = Ref.create(true); + new Task.Modal(null, "Updating index", false) { + @Override + public void run(@NotNull final ProgressIndicator indicator) { + indicator.setIndeterminate(true); + try { + doClearIndex(indexId); + } + catch (StorageException e) { + success.set(false); + requestRebuild(indexId); + LOG.info(e); } - }.queue(); - if (success.get()) { - scheduleIndexRebuild("checkRebuild"); - status.compareAndSet(REQUIRES_REBUILD, OK); } + }.queue(); + if (success.get()) { + scheduleIndexRebuild("checkRebuild"); + status.compareAndSet(REQUIRES_REBUILD, OK); } }; @@ -1538,67 +1517,64 @@ public class FileBasedIndexImpl extends FileBasedIndex { final FileType fileType = file.getFileType(); final Project finalProject = project == null ? ProjectUtil.guessProjectForFile(file) : project; - myFileTypeManager.freezeFileTypeTemporarilyIn(file, new Runnable() { - @Override - public void run() { - PsiFile psiFile = null; - FileContentImpl fc = null; - int inputId = -1; - - final List> affectedIndexCandidates = getAffectedIndexCandidates(file); - //noinspection ForLoopReplaceableByForEach - for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { - final ID indexId = affectedIndexCandidates.get(i); - if (shouldIndexFile(file, indexId)) { - if (fc == null) { - byte[] currentBytes; - try { - currentBytes = content.getBytes(); - } - catch (IOException e) { - currentBytes = ArrayUtil.EMPTY_BYTE_ARRAY; - } - fc = new FileContentImpl(file, currentBytes); - - if (IdIndex.ourSnapshotMappingsEnabled) { - try { - FileType substituteFileType = SubstitutedFileType.substituteFileType(file, fileType, finalProject); - byte[] hash = fileType.isBinary() ? - ContentHashesSupport.calcContentHash(currentBytes, substituteFileType) : - ContentHashesSupport.calcContentHashWithFileType( - currentBytes, - fc.getCharset(), - substituteFileType - ); - fc.setHash(hash); - } catch (IOException e) { - LOG.error(e); - } - } - - psiFile = content.getUserData(IndexingDataKeys.PSI_FILE); - initFileContent(fc, finalProject, psiFile); - inputId = Math.abs(getFileId(file)); - } + myFileTypeManager.freezeFileTypeTemporarilyIn(file, () -> { + PsiFile psiFile = null; + FileContentImpl fc = null; + int inputId = -1; + final List> affectedIndexCandidates = getAffectedIndexCandidates(file); + //noinspection ForLoopReplaceableByForEach + for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { + final ID indexId = affectedIndexCandidates.get(i); + if (shouldIndexFile(file, indexId)) { + if (fc == null) { + byte[] currentBytes; try { - ProgressManager.checkCanceled(); - updateSingleIndex(indexId, file, inputId, fc); + currentBytes = content.getBytes(); } - catch (ProcessCanceledException e) { - cleanFileContent(fc, psiFile); - throw e; + catch (IOException e) { + currentBytes = ArrayUtil.EMPTY_BYTE_ARRAY; } - catch (StorageException e) { - requestRebuild(indexId); - LOG.info(e); + fc = new FileContentImpl(file, currentBytes); + + if (IdIndex.ourSnapshotMappingsEnabled) { + try { + FileType substituteFileType = SubstitutedFileType.substituteFileType(file, fileType, finalProject); + byte[] hash = fileType.isBinary() ? + ContentHashesSupport.calcContentHash(currentBytes, substituteFileType) : + ContentHashesSupport.calcContentHashWithFileType( + currentBytes, + fc.getCharset(), + substituteFileType + ); + fc.setHash(hash); + } catch (IOException e) { + LOG.error(e); + } } + + psiFile = content.getUserData(IndexingDataKeys.PSI_FILE); + initFileContent(fc, finalProject, psiFile); + inputId = Math.abs(getFileId(file)); + } + + try { + ProgressManager.checkCanceled(); + updateSingleIndex(indexId, file, inputId, fc); + } + catch (ProcessCanceledException e) { + cleanFileContent(fc, psiFile); + throw e; + } + catch (StorageException e) { + requestRebuild(indexId); + LOG.info(e); } } + } - if (psiFile != null) { - psiFile.putUserData(PsiFileImpl.BUILDING_STUB, null); - } + if (psiFile != null) { + psiFile.putUserData(PsiFileImpl.BUILDING_STUB, null); } }); } @@ -1703,12 +1679,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { return updateWithBufferingEnabled(update); } }, - new Runnable() { - @Override - public void run() { - indexedStampUpdate(indexId, file, inputId, hasContent); - } - }); + () -> indexedStampUpdate(indexId, file, inputId, hasContent)); } else { if (updateWithBufferingEnabled(update)) { @@ -1837,31 +1808,28 @@ public class FileBasedIndexImpl extends FileBasedIndex { myChangedFilesCollector.removeScheduledFileFromUpdate(file); } else { - myFileTypeManager.freezeFileTypeTemporarilyIn(file, new Runnable() { - @Override - public void run() { - final List> candidates = getAffectedIndexCandidates(file); - int fileId = getIdMaskingNonIdBasedFile(file); - //noinspection ForLoopReplaceableByForEach - boolean scheduleForUpdate = false; + myFileTypeManager.freezeFileTypeTemporarilyIn(file, () -> { + final List> candidates = getAffectedIndexCandidates(file); + int fileId = getIdMaskingNonIdBasedFile(file); + //noinspection ForLoopReplaceableByForEach + boolean scheduleForUpdate = false; - //noinspection ForLoopReplaceableByForEach - for (int i = 0, size = candidates.size(); i < size; ++i) { - final ID indexId = candidates.get(i); - if (needsFileContentLoading(indexId) && getInputFilter(indexId).acceptInput(file)) { - getIndex(indexId).resetIndexedStateForFile(fileId); - scheduleForUpdate = true; - } + //noinspection ForLoopReplaceableByForEach + for (int i = 0, size = candidates.size(); i < size; ++i) { + final ID indexId = candidates.get(i); + if (needsFileContentLoading(indexId) && getInputFilter(indexId).acceptInput(file)) { + getIndex(indexId).resetIndexedStateForFile(fileId); + scheduleForUpdate = true; } + } - if (scheduleForUpdate) { - IndexingStamp.flushCache(fileId); - myChangedFilesCollector.scheduleForUpdate(file); - } + if (scheduleForUpdate) { + IndexingStamp.flushCache(fileId); + myChangedFilesCollector.scheduleForUpdate(file); + } - if (!myUpToDateIndicesForUnsavedOrTransactedDocuments.isEmpty()) { - clearUpToDateStateForPsiIndicesOfUnsavedDocuments(file); - } + if (!myUpToDateIndicesForUnsavedOrTransactedDocuments.isEmpty()) { + clearUpToDateStateForPsiIndicesOfUnsavedDocuments(file); } }); } @@ -2059,59 +2027,56 @@ public class FileBasedIndexImpl extends FileBasedIndex { if (!(file instanceof VirtualFileWithId)) { return true; } - myFileTypeManager.freezeFileTypeTemporarilyIn(file, new Runnable() { - @Override - public void run() { - boolean oldStuff = true; - if (file.isDirectory() || !isTooLarge(file)) { - final List> affectedIndexCandidates = getAffectedIndexCandidates(file); - //noinspection ForLoopReplaceableByForEach - for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { - final ID indexId = affectedIndexCandidates.get(i); - try { - if (needsFileContentLoading(indexId) && shouldIndexFile(file, indexId)) { - synchronized (myFiles) { - myFiles.add(file); - } - oldStuff = false; - break; - } - } - catch (RuntimeException e) { - final Throwable cause = e.getCause(); - if (cause instanceof IOException || cause instanceof StorageException) { - LOG.info(e); - requestRebuild(indexId); - } - else { - throw e; + myFileTypeManager.freezeFileTypeTemporarilyIn(file, () -> { + boolean oldStuff = true; + if (file.isDirectory() || !isTooLarge(file)) { + final List> affectedIndexCandidates = getAffectedIndexCandidates(file); + //noinspection ForLoopReplaceableByForEach + for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { + final ID indexId = affectedIndexCandidates.get(i); + try { + if (needsFileContentLoading(indexId) && shouldIndexFile(file, indexId)) { + synchronized (myFiles) { + myFiles.add(file); } + oldStuff = false; + break; } } - } - FileContent fileContent = null; - int inputId = Math.abs(getIdMaskingNonIdBasedFile(file)); - for (ID indexId : myNotRequiringContentIndices) { - if (shouldIndexFile(file, indexId)) { - oldStuff = false; - try { - if (fileContent == null) { - fileContent = new FileContentImpl(file); - } - updateSingleIndex(indexId, file, inputId, fileContent); - } - catch (StorageException e) { + catch (RuntimeException e) { + final Throwable cause = e.getCause(); + if (cause instanceof IOException || cause instanceof StorageException) { LOG.info(e); requestRebuild(indexId); } + else { + throw e; + } } } - IndexingStamp.flushCache(inputId); - - if (oldStuff && file instanceof VirtualFileSystemEntry) { - ((VirtualFileSystemEntry)file).setFileIndexed(true); + } + FileContent fileContent = null; + int inputId = Math.abs(getIdMaskingNonIdBasedFile(file)); + for (ID indexId : myNotRequiringContentIndices) { + if (shouldIndexFile(file, indexId)) { + oldStuff = false; + try { + if (fileContent == null) { + fileContent = new FileContentImpl(file); + } + updateSingleIndex(indexId, file, inputId, fileContent); + } + catch (StorageException e) { + LOG.info(e); + requestRebuild(indexId); + } } } + IndexingStamp.flushCache(inputId); + + if (oldStuff && file instanceof VirtualFileSystemEntry) { + ((VirtualFileSystemEntry)file).setFileIndexed(true); + } }); if (myProgressIndicator != null && file.isDirectory()) { // once for dir is cheap enough @@ -2267,12 +2232,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { List tasks = new ArrayList(); final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - tasks.add(new Runnable() { - @Override - public void run() { - projectFileIndex.iterateContent(processor); - } - }); + tasks.add(() -> projectFileIndex.iterateContent(processor)); /* Module[] modules = ModuleManager.getInstance(project).getModules(); for(final Module module: modules) { @@ -2295,23 +2255,17 @@ public class FileBasedIndexImpl extends FileBasedIndex { for (final VirtualFile root : IndexableSetContributor.getRootsToIndex(contributor)) { if (visitedRoots.add(root)) { //System.out.println(root); - tasks.add(new Runnable() { - @Override - public void run() { - if (project.isDisposed() || !root.isValid()) return; - iterateRecursively(root, processor, indicator, visitedRoots, null); - } + tasks.add(() -> { + if (project.isDisposed() || !root.isValid()) return; + iterateRecursively(root, processor, indicator, visitedRoots, null); }); } } for (final VirtualFile root : IndexableSetContributor.getProjectRootsToIndex(contributor, project)) { if (visitedRoots.add(root)) { - tasks.add(new Runnable() { - @Override - public void run() { - if (project.isDisposed() || !root.isValid()) return; - iterateRecursively(root, processor, indicator, visitedRoots, null); - } + tasks.add(() -> { + if (project.isDisposed() || !root.isValid()) return; + iterateRecursively(root, processor, indicator, visitedRoots, null); }); } } @@ -2329,12 +2283,9 @@ public class FileBasedIndexImpl extends FileBasedIndex { for (VirtualFile[] roots : new VirtualFile[][]{libSources, libClasses}) { for (final VirtualFile root : roots) { if (visitedRoots.add(root)) { - tasks.add(new Runnable() { - @Override - public void run() { - if (project.isDisposed() || module.isDisposed() || !root.isValid()) return; - iterateRecursively(root, processor, indicator, visitedRoots, projectFileIndex); - } + tasks.add(() -> { + if (project.isDisposed() || module.isDisposed() || !root.isValid()) return; + iterateRecursively(root, processor, indicator, visitedRoots, projectFileIndex); }); } } @@ -2383,16 +2334,13 @@ public class FileBasedIndexImpl extends FileBasedIndex { if (extension instanceof PsiDependentIndex) myPsiDependentIndices.add(name); myNoLimitCheckTypes.addAll(extension.getFileTypesWithSizeLimitNotApplicable()); - addNestedInitializationTask(new ThrowableRunnable() { - @Override - public void run() throws IOException { - try { - versionChanged.compareAndSet(false, registerIndexer(extension, state)); - } catch (IOException io) { - throw io; - } catch (Throwable t) { - PluginManager.handleComponentError(t, extension.getClass().getName(), null); - } + addNestedInitializationTask(() -> { + try { + versionChanged.compareAndSet(false, registerIndexer(extension, state)); + } catch (IOException io) { + throw io; + } catch (Throwable t) { + PluginManager.handleComponentError(t, extension.getClass().getName(), null); } }); } @@ -2457,12 +2405,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { return state; } finally { - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - performShutdown(); - } - }); + ShutDownTracker.getInstance().registerShutdownTask(() -> performShutdown()); saveRegisteredIndicesAndDropUnregisteredOnes(state.getIndexIDs()); myFlushingFuture = FlushingDaemon.everyFiveSeconds(new Runnable() { diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexProjectHandler.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexProjectHandler.java index df2bd37e7546..9d57ec867e83 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexProjectHandler.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexProjectHandler.java @@ -75,30 +75,27 @@ public class FileBasedIndexProjectHandler extends AbstractProjectComponent imple final StartupManagerEx startupManager = (StartupManagerEx)StartupManager.getInstance(project); if (startupManager != null) { - startupManager.registerPreStartupActivity(new Runnable() { - @Override - public void run() { - PushedFilePropertiesUpdater.getInstance(project).initializeProperties(); + startupManager.registerPreStartupActivity(() -> { + PushedFilePropertiesUpdater.getInstance(project).initializeProperties(); - // schedule dumb mode start after the read action we're currently in - TransactionGuard.submitTransaction(project, () -> { - if (FileBasedIndex.getInstance() instanceof FileBasedIndexImpl) { - DumbService.getInstance(project).queueTask(new UnindexedFilesUpdater(project, true)); - } - }); + // schedule dumb mode start after the read action we're currently in + TransactionGuard.submitTransaction(project, () -> { + if (FileBasedIndex.getInstance() instanceof FileBasedIndexImpl) { + DumbService.getInstance(project).queueTask(new UnindexedFilesUpdater(project, true)); + } + }); - myIndex.registerIndexableSet(FileBasedIndexProjectHandler.this, project); - projectManager.addProjectManagerListener(project, new ProjectManagerAdapter() { - private boolean removed; - @Override - public void projectClosing(Project project) { - if (!removed) { - removed = true; - myIndex.removeIndexableSet(FileBasedIndexProjectHandler.this); - } + myIndex.registerIndexableSet(FileBasedIndexProjectHandler.this, project); + projectManager.addProjectManagerListener(project, new ProjectManagerAdapter() { + private boolean removed; + @Override + public void projectClosing(Project project1) { + if (!removed) { + removed = true; + myIndex.removeIndexableSet(FileBasedIndexProjectHandler.this); } - }); - } + } + }); }); } } @@ -159,11 +156,6 @@ public class FileBasedIndexProjectHandler extends AbstractProjectComponent imple Collection files, final Project project, final FileBasedIndexImpl index) { - CacheUpdateRunner.processFiles(indicator, true, files, project, new Consumer() { - @Override - public void consume(FileContent content) { - index.processRefreshedFile(project, content); - } - }); + CacheUpdateRunner.processFiles(indicator, true, files, project, content -> index.processRefreshedFile(project, content)); } } diff --git a/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java b/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java index 9382ce5792f4..98af24011abe 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java @@ -189,12 +189,7 @@ public class IndexInfrastructure { CacheUpdateRunner.indexingThreadCount()); for (ThrowableRunnable callable : myNestedInitializationTasks) { - taskExecutor.submit(new Runnable() { - @Override - public void run() { - executeNestedInitializationTask(callable, proceedLatch); - } - }); + taskExecutor.submit(() -> executeNestedInitializationTask(callable, proceedLatch)); } proceedLatch.await(); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java index cf4ee32c9191..fb98093f174e 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java @@ -258,14 +258,11 @@ public final class MapIndexStorage implements IndexStorage() { - @Override - public boolean process(int[] key) { - if (!idFilter.containsFileId(key[1])) return true; - finalHashMaskSet.add(key[0]); - ProgressManager.checkCanceled(); - return true; - } + myKeyHashToVirtualFileMapping.iterateData(key -> { + if (!idFilter.containsFileId(key[1])) return true; + finalHashMaskSet.add(key[0]); + ProgressManager.checkCanceled(); + return true; }); if (useCachedHashIds) { @@ -277,12 +274,9 @@ public final class MapIndexStorage implements IndexStorage() { - @Override - public boolean process(Key key) { - if (!finalHashMaskSet.contains(myKeyDescriptor.getHashCode(key))) return true; - return processor.process(key); - } + return myMap.processKeys(key -> { + if (!finalHashMaskSet.contains(myKeyDescriptor.getHashCode(key))) return true; + return processor.process(key); }); } return myMap.processKeys(processor); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java index 93c8ab82f831..435aa3852546 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java @@ -132,17 +132,14 @@ public class MemoryIndexStorage implements IndexStorage public boolean processKeys(@NotNull final Processor processor, GlobalSearchScope scope, IdFilter idFilter) throws StorageException { final Set stopList = new HashSet(); - Processor decoratingProcessor = new Processor() { - @Override - public boolean process(final Key key) { - if (stopList.contains(key)) return true; + Processor decoratingProcessor = key -> { + if (stopList.contains(key)) return true; - final UpdatableValueContainer container = myMap.get(key); - if (container != null && container.size() == 0) { - return true; - } - return processor.process(key); + final UpdatableValueContainer container = myMap.get(key); + if (container != null && container.size() == 0) { + return true; } + return processor.process(key); }; for (Key key : myMap.keySet()) { diff --git a/platform/lang-impl/src/com/intellij/util/indexing/TaskQueue.java b/platform/lang-impl/src/com/intellij/util/indexing/TaskQueue.java index 66b4b4fc3bcb..31325c46e7c9 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/TaskQueue.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/TaskQueue.java @@ -46,19 +46,16 @@ class TaskQueue { void submit(@NotNull final Computable update, @NotNull final Runnable successRunnable) { int currentTasksCount = myUpdatesCount.incrementAndGet(); - myPendingWriteRequestsQueue.add(new Runnable() { - @Override - public void run() { - try { - Boolean result = update.compute(); - if (result == Boolean.TRUE) { - myTimestampUpdates.add(successRunnable); - } - } - finally { - myUpdatesCount.decrementAndGet(); + myPendingWriteRequestsQueue.add(() -> { + try { + Boolean result = update.compute(); + if (result == Boolean.TRUE) { + myTimestampUpdates.add(successRunnable); } } + finally { + myUpdatesCount.decrementAndGet(); + } }); if (currentTasksCount > myLimit) { @@ -80,14 +77,11 @@ class TaskQueue { private void applyTimeStamps(final int max) { final Runnable runnable = myTimestampUpdates.poll(); if (runnable == null) return; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - int updates = 0; - for (Runnable r = runnable; r != null; r = myTimestampUpdates.poll()) { - r.run(); - if (++updates == max) break; - } + ApplicationManager.getApplication().runReadAction(() -> { + int updates = 0; + for (Runnable r = runnable; r != null; r = myTimestampUpdates.poll()) { + r.run(); + if (++updates == max) break; } }); } @@ -117,24 +111,21 @@ class TaskQueue { if(Registry.is("idea.concurrent.scanning.files.to.index")) return; myDoWorkRequest.incrementAndGet(); // we have 3 content independent indices but only one of them is heavy IO bound so there is no need in more than one thread - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - while(true) { - Runnable runnable = myPendingWriteRequestsQueue.poll(2000, TimeUnit.MILLISECONDS); - if (runnable != null) { - runnable.run(); - } else { - // we have no work for 2s and there is no currently running updates - if(myDoWorkRequest.compareAndSet(1, 0)) { - break; - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + while(true) { + Runnable runnable = myPendingWriteRequestsQueue.poll(2000, TimeUnit.MILLISECONDS); + if (runnable != null) { + runnable.run(); + } else { + // we have no work for 2s and there is no currently running updates + if(myDoWorkRequest.compareAndSet(1, 0)) { + break; } } } - catch (InterruptedException ignore) {} } + catch (InterruptedException ignore) {} }); } } diff --git a/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java b/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java index 968495027cb5..2d873d86596e 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java @@ -102,12 +102,7 @@ public class UnindexedFilesUpdater extends DumbModeTask { } private void indexFiles(ProgressIndicator indicator, List files) { - CacheUpdateRunner.processFiles(indicator, true, files, myProject, new Consumer() { - @Override - public void consume(FileContent content) { - myIndex.indexFileContent(myProject, content); - } - }); + CacheUpdateRunner.processFiles(indicator, true, files, myProject, content -> myIndex.indexFileContent(myProject, content)); } @Override diff --git a/platform/lang-impl/src/com/intellij/util/textCompletion/TextCompletionUtil.java b/platform/lang-impl/src/com/intellij/util/textCompletion/TextCompletionUtil.java index e6255e310f9e..4156da31ac24 100644 --- a/platform/lang-impl/src/com/intellij/util/textCompletion/TextCompletionUtil.java +++ b/platform/lang-impl/src/com/intellij/util/textCompletion/TextCompletionUtil.java @@ -70,12 +70,8 @@ public class TextCompletionUtil { @Override public void focusGained(final Editor editor) { if (toShowHintRef.get() && editor.getDocument().getText().isEmpty()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - HintManager.getInstance().showInformationHint(editor, "Code completion available ( " + completionShortcutText + " )"); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> HintManager.getInstance().showInformationHint(editor, "Code completion available ( " + completionShortcutText + " )")); } } diff --git a/platform/lang-impl/src/com/intellij/util/ui/tree/AbstractFileTreeTable.java b/platform/lang-impl/src/com/intellij/util/ui/tree/AbstractFileTreeTable.java index be3e2d29d98a..76b2f75e1d5b 100644 --- a/platform/lang-impl/src/com/intellij/util/ui/tree/AbstractFileTreeTable.java +++ b/platform/lang-impl/src/com/intellij/util/ui/tree/AbstractFileTreeTable.java @@ -420,21 +420,18 @@ public class AbstractFileTreeTable extends TreeTable { setUserObject(myObject); final List children = new ArrayList(); appendChildrenTo(children); - Collections.sort(children, new Comparator() { - @Override - public int compare(final ConvenientNode node1, final ConvenientNode node2) { - Object o1 = node1.getObject(); - Object o2 = node2.getObject(); - if (o1 == o2) return 0; - if (o1 instanceof Project) return -1; - if (o2 instanceof Project) return 1; - VirtualFile file1 = (VirtualFile)o1; - VirtualFile file2 = (VirtualFile)o2; - if (file1.isDirectory() != file2.isDirectory()) { - return file1.isDirectory() ? -1 : 1; - } - return file1.getName().compareTo(file2.getName()); + Collections.sort(children, (node1, node2) -> { + Object o1 = node1.getObject(); + Object o2 = node2.getObject(); + if (o1 == o2) return 0; + if (o1 instanceof Project) return -1; + if (o2 instanceof Project) return 1; + VirtualFile file1 = (VirtualFile)o1; + VirtualFile file2 = (VirtualFile)o2; + if (file1.isDirectory() != file2.isDirectory()) { + return file1.isDirectory() ? -1 : 1; } + return file1.getName().compareTo(file2.getName()); }); int i = 0; for (ConvenientNode child : children) { diff --git a/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java b/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java index 6f1ede87d213..b42ab8048d81 100644 --- a/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java +++ b/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java @@ -300,12 +300,7 @@ public abstract class LanguagePerFileConfigurable implements SearchableConfig group.add(createChooseAction(myVirtualFile, null)); } final List values = new ArrayList(myMappings.getAvailableValues(myVirtualFile)); - Collections.sort(values, new Comparator() { - @Override - public int compare(final T o1, final T o2) { - return visualize(o1).compareTo(visualize(o2)); - } - }); + Collections.sort(values, (o1, o2) -> visualize(o1).compareTo(visualize(o2))); for (T t : values) { if (myMappings.isSelectable(t)) { group.add(createChooseAction(myVirtualFile, t)); diff --git a/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java b/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java index 85d6150dbbbd..f53c23d91a8b 100644 --- a/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java +++ b/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java @@ -207,66 +207,54 @@ public class InstalledPackagesPanel extends JPanel { return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final PackageManagementService.Listener listener = new PackageManagementService.Listener() { - @Override - public void operationStarted(final String packageName) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myPackagesTable.setPaintBusy(true); - myCurrentlyInstalling.add(packageName); - } - }); - } - - @Override - public void operationFinished(final String packageName, - @Nullable final PackageManagementService.ErrorDescription errorDescription) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myPackagesTable.clearSelection(); - updatePackages(selPackageManagementService); - myPackagesTable.setPaintBusy(false); - myCurrentlyInstalling.remove(packageName); - if (errorDescription == null) { - myNotificationArea.showSuccess("Package " + packageName + " successfully upgraded"); - } - else { - myNotificationArea.showError("Upgrade packages failed. Details...", "Upgrade Packages Failed", - errorDescription); - } - - if (myCurrentlyInstalling.isEmpty() && !myWaitingToUpgrade.isEmpty()) { - upgradePostponedPackages(); - } - } - }); - } - }; - PackageManagementServiceEx serviceEx = getServiceEx(); - if (serviceEx != null) { - serviceEx.updatePackage(pkg, toVersion, listener); + ApplicationManager.getApplication().invokeLater(() -> { + final PackageManagementService.Listener listener = new PackageManagementService.Listener() { + @Override + public void operationStarted(final String packageName) { + UIUtil.invokeLaterIfNeeded(() -> { + myPackagesTable.setPaintBusy(true); + myCurrentlyInstalling.add(packageName); + }); } - else { - myPackageManagementService.installPackage(new RepoPackage(pkg.getName(), null /* TODO? */), null, true, null, listener, false); + + @Override + public void operationFinished(final String packageName, + @Nullable final PackageManagementService.ErrorDescription errorDescription) { + UIUtil.invokeLaterIfNeeded(() -> { + myPackagesTable.clearSelection(); + updatePackages(selPackageManagementService); + myPackagesTable.setPaintBusy(false); + myCurrentlyInstalling.remove(packageName); + if (errorDescription == null) { + myNotificationArea.showSuccess("Package " + packageName + " successfully upgraded"); + } + else { + myNotificationArea.showError("Upgrade packages failed. Details...", "Upgrade Packages Failed", + errorDescription); + } + + if (myCurrentlyInstalling.isEmpty() && !myWaitingToUpgrade.isEmpty()) { + upgradePostponedPackages(); + } + }); } - myUpgradeButton.setEnabled(false); + }; + PackageManagementServiceEx serviceEx = getServiceEx(); + if (serviceEx != null) { + serviceEx.updatePackage(pkg, toVersion, listener); } + else { + myPackageManagementService.installPackage(new RepoPackage(pkg.getName(), null /* TODO? */), null, true, null, listener, false); + } + myUpgradeButton.setEnabled(false); }, ModalityState.any()); } @Override public void consume(Exception e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog("Error occurred. Please, check your internet connection.", - "Upgrade Package Failed."); - } + ApplicationManager.getApplication().invokeLater(() -> { + Messages.showErrorDialog("Error occurred. Please, check your internet connection.", + "Upgrade Package Failed."); }, ModalityState.any()); } }); @@ -335,36 +323,28 @@ public class InstalledPackagesPanel extends JPanel { PackageManagementService.Listener listener = new PackageManagementService.Listener() { @Override public void operationStarted(String packageName) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myPackagesTable.setPaintBusy(true); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myPackagesTable.setPaintBusy(true)); } @Override public void operationFinished(final String packageName, @Nullable final PackageManagementService.ErrorDescription errorDescription) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myPackagesTable.clearSelection(); - updatePackages(selPackageManagementService); - myPackagesTable.setPaintBusy(false); - if (errorDescription == null) { - if (packageName != null) { - myNotificationArea.showSuccess("Package '" + packageName + "' successfully uninstalled"); - } - else { - myNotificationArea.showSuccess("Packages successfully uninstalled"); - } + UIUtil.invokeLaterIfNeeded(() -> { + myPackagesTable.clearSelection(); + updatePackages(selPackageManagementService); + myPackagesTable.setPaintBusy(false); + if (errorDescription == null) { + if (packageName != null) { + myNotificationArea.showSuccess("Package '" + packageName + "' successfully uninstalled"); } else { - myNotificationArea.showError("Uninstall packages failed. Details...", "Uninstall Packages Failed", - errorDescription); + myNotificationArea.showSuccess("Packages successfully uninstalled"); } } + else { + myNotificationArea.showError("Uninstall packages failed. Details...", "Uninstall Packages Failed", + errorDescription); + } }); } }; @@ -412,47 +392,41 @@ public class InstalledPackagesPanel extends JPanel { public void doUpdatePackages(@NotNull final PackageManagementService packageManagementService) { onUpdateStarted(); final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - Collection packages = Lists.newArrayList(); - try { - packages = packageManagementService.getInstalledPackages(); - } - catch (IOException e) { - LOG.warn(e.getMessage()); // do nothing, we already have an empty list - } - finally { - final Collection finalPackages = packages; + application.executeOnPooledThread(() -> { + Collection packages = Lists.newArrayList(); + try { + packages = packageManagementService.getInstalledPackages(); + } + catch (IOException e) { + LOG.warn(e.getMessage()); // do nothing, we already have an empty list + } + finally { + final Collection finalPackages = packages; - final Map cache = buildNameToPackageMap(packageManagementService.getAllPackagesCached()); - final boolean shouldFetchLatestVersionsForOnlyInstalledPackages = shouldFetchLatestVersionsForOnlyInstalledPackages(); - if (cache.isEmpty()) { - if (!shouldFetchLatestVersionsForOnlyInstalledPackages) { - refreshLatestVersions(packageManagementService); + final Map cache = buildNameToPackageMap(packageManagementService.getAllPackagesCached()); + final boolean shouldFetchLatestVersionsForOnlyInstalledPackages = shouldFetchLatestVersionsForOnlyInstalledPackages(); + if (cache.isEmpty()) { + if (!shouldFetchLatestVersionsForOnlyInstalledPackages) { + refreshLatestVersions(packageManagementService); + } + } + UIUtil.invokeLaterIfNeeded(() -> { + if (packageManagementService == myPackageManagementService) { + myPackagesTableModel.getDataVector().clear(); + for (InstalledPackage pkg : finalPackages) { + RepoPackage repoPackage = cache.get(pkg.getName()); + final String version = repoPackage != null ? repoPackage.getLatestVersion() : null; + myPackagesTableModel + .addRow(new Object[]{pkg, pkg.getVersion(), version == null ? "" : version}); + } + if (!cache.isEmpty()) { + onUpdateFinished(); + } + if (shouldFetchLatestVersionsForOnlyInstalledPackages) { + setLatestVersionsForInstalledPackages(); } } - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (packageManagementService == myPackageManagementService) { - myPackagesTableModel.getDataVector().clear(); - for (InstalledPackage pkg : finalPackages) { - RepoPackage repoPackage = cache.get(pkg.getName()); - final String version = repoPackage != null ? repoPackage.getLatestVersion() : null; - myPackagesTableModel - .addRow(new Object[]{pkg, pkg.getVersion(), version == null ? "" : version}); - } - if (!cache.isEmpty()) { - onUpdateFinished(); - } - if (shouldFetchLatestVersionsForOnlyInstalledPackages) { - setLatestVersionsForInstalledPackages(); - } - } - } - }); - } + }); } }); } @@ -484,27 +458,19 @@ public class InstalledPackagesPanel extends JPanel { @Override public void consume(Exception e) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - decrement(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> decrement()); } @Override public void consume(@Nullable final String latestVersion) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (finalIndex < myPackagesTableModel.getRowCount()) { - InstalledPackage p = getInstalledPackageAt(finalIndex); - if (pkg == p) { - myPackagesTableModel.setValueAt(latestVersion, finalIndex, 2); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (finalIndex < myPackagesTableModel.getRowCount()) { + InstalledPackage p = getInstalledPackageAt(finalIndex); + if (pkg == p) { + myPackagesTableModel.setValueAt(latestVersion, finalIndex, 2); } - decrement(); } + decrement(); }); } }); @@ -535,28 +501,22 @@ public class InstalledPackagesPanel extends JPanel { private void refreshLatestVersions(@NotNull final PackageManagementService packageManagementService) { final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - if (packageManagementService == myPackageManagementService) { - try { - List packages = packageManagementService.reloadAllPackages(); - final Map packageMap = buildNameToPackageMap(packages); - application.invokeLater(new Runnable() { - @Override - public void run() { - for (int i = 0; i != myPackagesTableModel.getRowCount(); ++i) { - final InstalledPackage pyPackage = (InstalledPackage)myPackagesTableModel.getValueAt(i, 0); - final RepoPackage repoPackage = packageMap.get(pyPackage.getName()); - myPackagesTableModel.setValueAt(repoPackage == null ? null : repoPackage.getLatestVersion(), i, 2); - } - myPackagesTable.setPaintBusy(false); - } - }, ModalityState.stateForComponent(myPackagesTable)); - } - catch (IOException ignored) { + application.executeOnPooledThread(() -> { + if (packageManagementService == myPackageManagementService) { + try { + List packages = packageManagementService.reloadAllPackages(); + final Map packageMap = buildNameToPackageMap(packages); + application.invokeLater(() -> { + for (int i = 0; i != myPackagesTableModel.getRowCount(); ++i) { + final InstalledPackage pyPackage = (InstalledPackage)myPackagesTableModel.getValueAt(i, 0); + final RepoPackage repoPackage = packageMap.get(pyPackage.getName()); + myPackagesTableModel.setValueAt(repoPackage == null ? null : repoPackage.getLatestVersion(), i, 2); + } myPackagesTable.setPaintBusy(false); - } + }, ModalityState.stateForComponent(myPackagesTable)); + } + catch (IOException ignored) { + myPackagesTable.setPaintBusy(false); } } }); diff --git a/platform/lang-impl/src/com/intellij/webcore/packaging/ManagePackagesDialog.java b/platform/lang-impl/src/com/intellij/webcore/packaging/ManagePackagesDialog.java index 08e3462591cb..526521a306ba 100644 --- a/platform/lang-impl/src/com/intellij/webcore/packaging/ManagePackagesDialog.java +++ b/platform/lang-impl/src/com/intellij/webcore/packaging/ManagePackagesDialog.java @@ -101,24 +101,18 @@ public class ManagePackagesDialog extends DialogWrapper { public void actionPerformed(AnActionEvent e) { myPackages.setPaintBusy(true); final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - myController.reloadAllPackages(); - initModel(); + application.executeOnPooledThread(() -> { + try { + myController.reloadAllPackages(); + initModel(); + myPackages.setPaintBusy(false); + } + catch (final IOException e1) { + application.invokeLater(() -> { + //noinspection DialogTitleCapitalization + Messages.showErrorDialog(myMainPanel, "Error updating package list: " + e1.getMessage(), "Reload List of Packages"); myPackages.setPaintBusy(false); - } - catch (final IOException e) { - application.invokeLater(new Runnable() { - @Override - public void run() { - //noinspection DialogTitleCapitalization - Messages.showErrorDialog(myMainPanel, "Error updating package list: " + e.getMessage(), "Reload List of Packages"); - myPackages.setPaintBusy(false); - } - }, ModalityState.any()); - } + }, ModalityState.any()); } }); } @@ -160,12 +154,7 @@ public class ManagePackagesDialog extends DialogWrapper { } }); - UiNotifyConnector.doWhenFirstShown(myPackages, new Runnable() { - @Override - public void run() { - initModel(); - } - }); + UiNotifyConnector.doWhenFirstShown(myPackages, () -> initModel()); myOptionsCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { @@ -233,11 +222,8 @@ public class ManagePackagesDialog extends DialogWrapper { @Override public void operationStarted(final String packageName) { if (!ApplicationManager.getApplication().isDispatchThread()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - handleInstallationStarted(packageName); - } + ApplicationManager.getApplication().invokeLater(() -> { + handleInstallationStarted(packageName); }, ModalityState.stateForComponent(myMainPanel)); } else { @@ -249,11 +235,8 @@ public class ManagePackagesDialog extends DialogWrapper { public void operationFinished(final String packageName, @Nullable final PackageManagementService.ErrorDescription errorDescription) { if (!ApplicationManager.getApplication().isDispatchThread()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - handleInstallationFinished(packageName, errorDescription); - } + ApplicationManager.getApplication().invokeLater(() -> { + handleInstallationFinished(packageName, errorDescription); }, ModalityState.stateForComponent(myMainPanel)); } else { @@ -291,24 +274,18 @@ public class ManagePackagesDialog extends DialogWrapper { } private void updateInstalledPackages() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - final Collection installedPackages = myController.getInstalledPackages(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myInstalledPackages.clear(); - for (InstalledPackage pkg : installedPackages) { - myInstalledPackages.add(pkg.getName()); - } - } - }); - } - catch(IOException e) { - LOG.info("Error updating list of installed packages:" + e); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + final Collection installedPackages = myController.getInstalledPackages(); + UIUtil.invokeLaterIfNeeded(() -> { + myInstalledPackages.clear(); + for (InstalledPackage pkg : installedPackages) { + myInstalledPackages.add(pkg.getName()); + } + }); + } + catch(IOException e) { + LOG.info("Error updating list of installed packages:" + e); } }); } @@ -316,33 +293,24 @@ public class ManagePackagesDialog extends DialogWrapper { public void initModel() { setDownloadStatus(true); final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - myPackagesModel = new PackagesModel(myController.getAllPackages()); + application.executeOnPooledThread(() -> { + try { + myPackagesModel = new PackagesModel(myController.getAllPackages()); - application.invokeLater(new Runnable() { - @Override - public void run() { - myPackages.setModel(myPackagesModel); - ((MyPackageFilter)myFilter).filter(); - doSelectPackage(mySelectedPackageName); - setDownloadStatus(false); - } - }, ModalityState.any()); - } - catch (final IOException e) { - application.invokeLater(new Runnable() { - @Override - public void run() { - if (myMainPanel.isShowing()) { - Messages.showErrorDialog(myMainPanel, "Error loading package list:" + e.getMessage(), "Packages"); - } - setDownloadStatus(false); - } - }, ModalityState.any()); - } + application.invokeLater(() -> { + myPackages.setModel(myPackagesModel); + ((MyPackageFilter)myFilter).filter(); + doSelectPackage(mySelectedPackageName); + setDownloadStatus(false); + }, ModalityState.any()); + } + catch (final IOException e) { + application.invokeLater(() -> { + if (myMainPanel.isShowing()) { + Messages.showErrorDialog(myMainPanel, "Error loading package list:" + e.getMessage(), "Packages"); + } + setDownloadStatus(false); + }, ModalityState.any()); } }); } @@ -487,14 +455,11 @@ public class ManagePackagesDialog extends DialogWrapper { myController.fetchPackageVersions(packageName, new CatchingConsumer, Exception>() { @Override public void consume(final List releases) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myPackages.getSelectedValue() == pyPackage) { - myVersionComboBox.removeAllItems(); - for (String release : releases) { - myVersionComboBox.addItem(release); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myPackages.getSelectedValue() == pyPackage) { + myVersionComboBox.removeAllItems(); + for (String release : releases) { + myVersionComboBox.addItem(release); } } }, ModalityState.any()); @@ -511,27 +476,19 @@ public class ManagePackagesDialog extends DialogWrapper { myController.fetchPackageDetails(packageName, new CatchingConsumer() { @Override public void consume(final String details) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myPackages.getSelectedValue() == pyPackage) { - myDescriptionTextArea.setText(details); - myDescriptionTextArea.setCaretPosition(0); - }/* else { - do nothing, because other package gets selected - }*/ - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myPackages.getSelectedValue() == pyPackage) { + myDescriptionTextArea.setText(details); + myDescriptionTextArea.setCaretPosition(0); + }/* else { + do nothing, because other package gets selected + }*/ }); } @Override public void consume(Exception exception) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myDescriptionTextArea.setText("No information available"); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myDescriptionTextArea.setText("No information available")); LOG.info("Error retrieving package details", exception); } }); diff --git a/platform/lang-impl/testSources/com/intellij/execution/impl/ExecutionTestUtil.java b/platform/lang-impl/testSources/com/intellij/execution/impl/ExecutionTestUtil.java index 4c4e877c2df3..89049e79a6e3 100644 --- a/platform/lang-impl/testSources/com/intellij/execution/impl/ExecutionTestUtil.java +++ b/platform/lang-impl/testSources/com/intellij/execution/impl/ExecutionTestUtil.java @@ -54,17 +54,14 @@ public class ExecutionTestUtil { @NotNull private static String stringifyDescriptors(@NotNull List descriptors) { - return "Actual descriptors: " + StringUtil.join(descriptors, new Function() { - @Override - public String fun(RunContentDescriptor descriptor) { - if (descriptor == null) { - return "null"; - } - ProcessHandler processHandler = descriptor.getProcessHandler(); - return String.format("[%s, %s]", - descriptor.getDisplayName(), - processHandler != null ? processHandler.getClass().getName() : null); + return "Actual descriptors: " + StringUtil.join(descriptors, descriptor -> { + if (descriptor == null) { + return "null"; } + ProcessHandler processHandler = descriptor.getProcessHandler(); + return String.format("[%s, %s]", + descriptor.getDisplayName(), + processHandler != null ? processHandler.getClass().getName() : null); }, ", "); } } diff --git a/platform/lang-impl/testSources/com/intellij/slicer/SliceTestUtil.java b/platform/lang-impl/testSources/com/intellij/slicer/SliceTestUtil.java index 144acf4a267d..20debdbb9953 100644 --- a/platform/lang-impl/testSources/com/intellij/slicer/SliceTestUtil.java +++ b/platform/lang-impl/testSources/com/intellij/slicer/SliceTestUtil.java @@ -75,33 +75,26 @@ public class SliceTestUtil { } private static void extract(final Document document, final Map sliceUsageName2Offset, final String name) { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - for (int i = 1; i < 9; i++) { - String newName = name + i; - String s = ""; - if (!document.getText().contains(s)) break; - int off = document.getText().indexOf(s); + WriteCommandAction.runWriteCommandAction(null, () -> { + for (int i = 1; i < 9; i++) { + String newName = name + i; + String s = ""; + if (!document.getText().contains(s)) break; + int off = document.getText().indexOf(s); - document.deleteString(off, off + s.length()); - RangeMarker prev = sliceUsageName2Offset.put(newName, document.createRangeMarker(off, off)); - assertNull(prev); + document.deleteString(off, off + s.length()); + RangeMarker prev = sliceUsageName2Offset.put(newName, document.createRangeMarker(off, off)); + assertNull(prev); - extract(document, sliceUsageName2Offset, newName); - } + extract(document, sliceUsageName2Offset, newName); } }); } public static void checkUsages(final SliceUsage usage, final TIntObjectHashMap flownOffsets) { final List children = new ArrayList(); - boolean b = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - usage.processChildren(new CommonProcessors.CollectProcessor(children)); - } - }, "Expanding", true, usage.getElement().getProject()); + boolean b = ProgressManager.getInstance().runProcessWithProgressSynchronously( + () -> usage.processChildren(new CommonProcessors.CollectProcessor(children)), "Expanding", true, usage.getElement().getProject()); assertTrue(b); int startOffset = usage.getElement().getTextOffset(); IntArrayList list = flownOffsets.get(startOffset); @@ -110,12 +103,7 @@ public class SliceTestUtil { int size = offsets.length; assertEquals(message(startOffset, usage), size, children.size()); - Collections.sort(children, new Comparator() { - @Override - public int compare(SliceUsage o1, SliceUsage o2) { - return o1.compareTo(o2); - } - }); + Collections.sort(children, (o1, o2) -> o1.compareTo(o2)); for (int i = 0; i < children.size(); i++) { SliceUsage child = children.get(i); diff --git a/platform/lvcs-impl/src/com/intellij/history/core/ChangeList.java b/platform/lvcs-impl/src/com/intellij/history/core/ChangeList.java index 1483368d5548..4629aa9a8ee4 100644 --- a/platform/lvcs-impl/src/com/intellij/history/core/ChangeList.java +++ b/platform/lvcs-impl/src/com/intellij/history/core/ChangeList.java @@ -172,11 +172,9 @@ public class ChangeList { } public synchronized void purgeObsolete(long period) { - myStorage.purge(period, myIntervalBetweenActivities, new Consumer() { - public void consume(ChangeSet changeSet) { - for (Content each : changeSet.getContentsToPurge()) { - each.release(); - } + myStorage.purge(period, myIntervalBetweenActivities, changeSet -> { + for (Content each : changeSet.getContentsToPurge()) { + each.release(); } }); } diff --git a/platform/lvcs-impl/src/com/intellij/history/core/changes/ChangeSet.java b/platform/lvcs-impl/src/com/intellij/history/core/changes/ChangeSet.java index 1385137c4030..5853b0f52bf4 100644 --- a/platform/lvcs-impl/src/com/intellij/history/core/changes/ChangeSet.java +++ b/platform/lvcs-impl/src/com/intellij/history/core/changes/ChangeSet.java @@ -92,157 +92,101 @@ public class ChangeSet { @Nullable public String getLabel() { - return accessChanges(new Producer() { - @Override - public String produce() { - for (Change each : myChanges) { - if (each instanceof PutLabelChange) { - return ((PutLabelChange)each).getName(); - } + return accessChanges(() -> { + for (Change each : myChanges) { + if (each instanceof PutLabelChange) { + return ((PutLabelChange)each).getName(); } - return null; } + return null; }); } public int getLabelColor() { - return accessChanges(new Producer() { - @Override - public Integer produce() { - for (Change each : myChanges) { - if (each instanceof PutSystemLabelChange) { - return ((PutSystemLabelChange)each).getColor(); - } + return accessChanges(() -> { + for (Change each : myChanges) { + if (each instanceof PutSystemLabelChange) { + return ((PutSystemLabelChange)each).getColor(); } - return -1; } + return -1; }); } public void addChange(final Change c) { LocalHistoryLog.LOG.assertTrue(!isLocked, "Changeset is already locked"); - accessChanges(new Runnable() { - @Override - public void run() { - myChanges.add(c); - } - }); + accessChanges((Runnable)() -> myChanges.add(c)); } public List getChanges() { - return accessChanges(new Producer>() { - @Override - public List produce() { - if (isLocked) return myChanges; - return Collections.unmodifiableList(new ArrayList(myChanges)); - } + return accessChanges(() -> { + if (isLocked) return myChanges; + return Collections.unmodifiableList(new ArrayList(myChanges)); }); } public boolean isEmpty() { - return accessChanges(new Producer() { - @Override - public Boolean produce() { - return myChanges.isEmpty(); - } - }); + return accessChanges(() -> myChanges.isEmpty()); } public boolean affectsPath(final String paths) { - return accessChanges(new Producer() { - @Override - public Boolean produce() { - for (Change c : myChanges) { - if (c.affectsPath(paths)) return true; - } - return false; + return accessChanges(() -> { + for (Change c : myChanges) { + if (c.affectsPath(paths)) return true; } + return false; }); } public boolean isCreationalFor(final String path) { - return accessChanges(new Producer() { - @Override - public Boolean produce() { - for (Change c : myChanges) { - if (c.isCreationalFor(path)) return true; - } - return false; + return accessChanges(() -> { + for (Change c : myChanges) { + if (c.isCreationalFor(path)) return true; } + return false; }); } public List getContentsToPurge() { - return accessChanges(new Producer>() { - @Override - public List produce() { - List result = new ArrayList(); - for (Change c : myChanges) { - result.addAll(c.getContentsToPurge()); - } - return result; + return accessChanges(() -> { + List result = new ArrayList(); + for (Change c : myChanges) { + result.addAll(c.getContentsToPurge()); } + return result; }); } public boolean isContentChangeOnly() { - return accessChanges(new Producer() { - @Override - public Boolean produce() { - return myChanges.size() == 1 && getFirstChange() instanceof ContentChange; - } - }); + return accessChanges(() -> myChanges.size() == 1 && getFirstChange() instanceof ContentChange); } public boolean isLabelOnly() { - return accessChanges(new Producer() { - @Override - public Boolean produce() { - return myChanges.size() == 1 && getFirstChange() instanceof PutLabelChange; - } - }); + return accessChanges(() -> myChanges.size() == 1 && getFirstChange() instanceof PutLabelChange); } public Change getFirstChange() { - return accessChanges(new Producer() { - @Override - public Change produce() { - return myChanges.get(0); - } - }); + return accessChanges(() -> myChanges.get(0)); } public Change getLastChange() { - return accessChanges(new Producer() { - @Override - public Change produce() { - return myChanges.get(myChanges.size() - 1); - } - }); + return accessChanges(() -> myChanges.get(myChanges.size() - 1)); } public List getAffectedPaths() { - return accessChanges(new Producer>() { - @Override - public List produce() { - List result = new SmartList(); - for (Change each : myChanges) { - if (each instanceof StructuralChange) { - result.add(((StructuralChange)each).getPath()); - } + return accessChanges(() -> { + List result = new SmartList(); + for (Change each : myChanges) { + if (each instanceof StructuralChange) { + result.add(((StructuralChange)each).getPath()); } - return result; } + return result; }); } public String toString() { - return accessChanges(new Producer() { - @Override - public String produce() { - return myChanges.toString(); - } - }); + return accessChanges(() -> myChanges.toString()); } public long getId() { @@ -298,12 +242,9 @@ public class ChangeSet { } private void accessChanges(@NotNull final Runnable func) { - accessChanges(new Producer() { - @Override - public Object produce() { - func.run(); - return null; - } + accessChanges(() -> { + func.run(); + return null; }); } } diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java b/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java index 946695712e94..ebe834d9764a 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java @@ -272,27 +272,21 @@ public class IdeaGateway { } private void doCreateChildren(@NotNull DirectoryEntry parent, Iterable children, final boolean forDeletion) { - List entries = ContainerUtil.mapNotNull(children, new NullableFunction() { - @Override - public Entry fun(@NotNull VirtualFile each) { - return doCreateEntry(each, forDeletion); - } + List entries = ContainerUtil.mapNotNull(children, (NullableFunction)each -> { + return doCreateEntry(each, forDeletion); }); parent.addChildren(entries); } public void registerUnsavedDocuments(@NotNull final LocalHistoryFacade vcs) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - vcs.beginChangeSet(); - for (Document d : FileDocumentManager.getInstance().getUnsavedDocuments()) { - VirtualFile f = getFile(d); - if (!shouldRegisterDocument(f)) continue; - registerDocumentContents(vcs, f, d); - } - vcs.endChangeSet(null); + ApplicationManager.getApplication().runReadAction(() -> { + vcs.beginChangeSet(); + for (Document d : FileDocumentManager.getInstance().getUnsavedDocuments()) { + VirtualFile f = getFile(d); + if (!shouldRegisterDocument(f)) continue; + registerDocumentContents(vcs, f, d); } + vcs.endChangeSet(null); }); } diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java b/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java index 20bcfb645d36..8f1417b3dd2d 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java @@ -64,12 +64,7 @@ public class LocalHistoryImpl extends LocalHistory implements ApplicationCompone public void initComponent() { if (!ApplicationManager.getApplication().isUnitTestMode() && ApplicationManager.getApplication().isHeadlessEnvironment()) return; - myShutdownTask = new Runnable() { - @Override - public void run() { - disposeComponent(); - } - }; + myShutdownTask = () -> disposeComponent(); ShutDownTracker.getInstance().registerShutdownTask(myShutdownTask); initHistory(); @@ -99,12 +94,7 @@ public class LocalHistoryImpl extends LocalHistory implements ApplicationCompone fm.addVirtualFileManagerListener(myEventDispatcher); if (ApplicationManager.getApplication().isInternal() && !ApplicationManager.getApplication().isUnitTestMode()) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - validateStorage(); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> validateStorage()); } } diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/DirectoryHistoryDialog.java b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/DirectoryHistoryDialog.java index 12563326da59..f55e92e40d15 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/DirectoryHistoryDialog.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/DirectoryHistoryDialog.java @@ -108,11 +108,9 @@ public class DirectoryHistoryDialog extends HistoryDialog() { - public void consume(DirectoryHistoryDialogModel m) { - m.setFilter(field.getText()); - field.addCurrentTextToHistory(); - } + scheduleRevisionsUpdate(m -> { + m.setFilter(field.getText()); + field.addCurrentTextToHistory(); }); } }); @@ -129,11 +127,7 @@ public class DirectoryHistoryDialog extends HistoryDialog new ShowDifferenceAction().performIfEnabled()); myChangesTree.installPopupHandler(createChangesTreeActions(root)); } @@ -179,11 +173,7 @@ public class DirectoryHistoryDialog extends HistoryDialog changes = model.getChanges(); - return new Runnable() { - public void run() { - myChangesTree.setChangesToDisplay(changes); - } - }; + return () -> myChangesTree.setChangesToDisplay(changes); } @Override diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/FileHistoryDialog.java b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/FileHistoryDialog.java index 54630e9d43a6..de8e43c406c6 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/FileHistoryDialog.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/FileHistoryDialog.java @@ -71,11 +71,7 @@ public class FileHistoryDialog extends HistoryDialog { @Override protected Runnable doUpdateDiffs(final FileHistoryDialogModel model) { final FileDifferenceModel diffModel = model.getDifferenceModel(); - return new Runnable() { - public void run() { - myDiffPanel.setRequest(createDifference(diffModel)); - } - }; + return () -> myDiffPanel.setRequest(createDifference(diffModel)); } @Override diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java index 5d7ae75afd20..cf489b7d07d5 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java @@ -133,11 +133,7 @@ public abstract class HistoryDialog extends FrameW myModel.clearRevisions(); myModel.getRevisions();// force load } - return new Runnable() { - public void run() { - myRevisionsList.updateData(myModel); - } - }; + return () -> myRevisionsList.updateData(myModel); } }); } @@ -270,14 +266,12 @@ public abstract class HistoryDialog extends FrameW public void run() { if (isDisposed() || myProject.isDisposed()) return; - invokeAndWait(new Runnable() { - public void run() { - if (isDisposed() || myProject.isDisposed()) return; + invokeAndWait(() -> { + if (isDisposed() || myProject.isDisposed()) return; - isUpdating = true; - updateActions(); - myDiffView.startUpdating(); - } + isUpdating = true; + updateActions(); + myDiffView.startUpdating(); }); Runnable apply = null; @@ -289,22 +283,20 @@ public abstract class HistoryDialog extends FrameW } final Runnable finalApply = apply; - invokeAndWait(new Runnable() { - public void run() { - if (isDisposed() || myProject.isDisposed()) return; + invokeAndWait(() -> { + if (isDisposed() || myProject.isDisposed()) return; - isUpdating = false; - if (finalApply != null) { - try { - finalApply.run(); - } - catch (Exception e) { - LocalHistoryLog.LOG.error(e); - } + isUpdating = false; + if (finalApply != null) { + try { + finalApply.run(); + } + catch (Exception e) { + LocalHistoryLog.LOG.error(e); } - updateActions(); - myDiffView.finishUpdating(); } + updateActions(); + myDiffView.finishUpdating(); }); } }); @@ -340,18 +332,15 @@ public abstract class HistoryDialog extends FrameW new Task.Modal(myProject, message("message.processing.revisions"), false) { public void run(@NotNull final ProgressIndicator i) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - RevisionProcessingProgressAdapter p = new RevisionProcessingProgressAdapter(i); - p.processingLeftRevision(); - DiffContent left = m.getLeftDiffContent(p); + ApplicationManager.getApplication().runReadAction(() -> { + RevisionProcessingProgressAdapter p = new RevisionProcessingProgressAdapter(i); + p.processingLeftRevision(); + DiffContent left = m.getLeftDiffContent(p); - p.processingRightRevision(); - DiffContent right = m.getRightDiffContent(p); + p.processingRightRevision(); + DiffContent right = m.getRightDiffContent(p); - requestRef.set(new SimpleDiffRequest(m.getTitle(), left, right, m.getLeftTitle(p), m.getRightTitle(p))); - } + requestRef.set(new SimpleDiffRequest(m.getTitle(), left, right, m.getLeftTitle(p), m.getRightTitle(p))); }); } }.queue(); @@ -434,18 +423,16 @@ public abstract class HistoryDialog extends FrameW } private void showNotification(final String title) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final Balloon b = - JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(title, null, MessageType.INFO.getPopupBackground(), null) - .setFadeoutTime(3000) - .setShowCallout(false) - .createBalloon(); + SwingUtilities.invokeLater(() -> { + final Balloon b = + JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(title, null, MessageType.INFO.getPopupBackground(), null) + .setFadeoutTime(3000) + .setShowCallout(false) + .createBalloon(); - Dimension size = myDiffView.getSize(); - RelativePoint point = new RelativePoint(myDiffView, new Point(size.width / 2, size.height / 2)); - b.show(point, Balloon.Position.above); - } + Dimension size = myDiffView.getSize(); + RelativePoint point = new RelativePoint(myDiffView, new Point(size.width / 2, size.height / 2)); + b.show(point, Balloon.Position.above); }); } @@ -496,11 +483,7 @@ public abstract class HistoryDialog extends FrameW b.setPreferredFocusComponent(IdeFocusTraversalPolicy.getPreferredFocusedComponent(createPatchPanel)); b.setTitle(message("create.patch.dialog.title")); b.setCenterPanel(createPatchPanel); - p.installOkEnabledListener(new Consumer() { - public void consume(final Boolean aBoolean) { - b.setOkActionEnabled(aBoolean); - } - }); + p.installOkEnabledListener(aBoolean -> b.setOkActionEnabled(aBoolean)); return b.show() == DialogWrapper.OK_EXIT_CODE; } diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/RecentChangesPopup.java b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/RecentChangesPopup.java index 9aa8b3ec22c4..7118e436af42 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/RecentChangesPopup.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/RecentChangesPopup.java @@ -53,11 +53,9 @@ public class RecentChangesPopup { list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setCellRenderer(new RecentChangesListCellRenderer()); - Runnable selectAction = new Runnable() { - public void run() { - RecentChange c = (RecentChange)list.getSelectedValue(); - showRecentChangeDialog(c); - } + Runnable selectAction = () -> { + RecentChange c = (RecentChange)list.getSelectedValue(); + showRecentChangeDialog(c); }; showList(list, selectAction); diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/SelectionHistoryDialogModel.java b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/SelectionHistoryDialogModel.java index 70ea7546e405..56bad55b97b5 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/SelectionHistoryDialogModel.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/SelectionHistoryDialogModel.java @@ -66,12 +66,7 @@ public class SelectionHistoryDialogModel extends FileHistoryDialogModel { List revisionList = new ArrayList(); revisionList.add(getCurrentRevision()); - revisionList.addAll(ContainerUtil.map(getRevisions(), new Function() { - @Override - public Revision fun(RevisionItem revisionItem) { - return revisionItem.revision; - } - })); + revisionList.addAll(ContainerUtil.map(getRevisions(), revisionItem -> revisionItem.revision)); myCalculatorCache = new SelectionCalculator(myGateway, revisionList, myFrom, myTo); } return myCalculatorCache; diff --git a/platform/platform-api/src/com/intellij/execution/process/OSProcessHandler.java b/platform/platform-api/src/com/intellij/execution/process/OSProcessHandler.java index ed9c8c9cae7b..585e9d530bfe 100644 --- a/platform/platform-api/src/com/intellij/execution/process/OSProcessHandler.java +++ b/platform/platform-api/src/com/intellij/execution/process/OSProcessHandler.java @@ -137,12 +137,7 @@ public class OSProcessHandler extends BaseOSProcessHandler { killProcessTreeSync(process); } else { - executeOnPooledThread(new Runnable() { - @Override - public void run() { - killProcessTreeSync(process); - } - }); + executeOnPooledThread(() -> killProcessTreeSync(process)); } } diff --git a/platform/platform-api/src/com/intellij/execution/process/ProcessTerminatedListener.java b/platform/platform-api/src/com/intellij/execution/process/ProcessTerminatedListener.java index 96ea7875a17c..c4111dc29423 100644 --- a/platform/platform-api/src/com/intellij/execution/process/ProcessTerminatedListener.java +++ b/platform/platform-api/src/com/intellij/execution/process/ProcessTerminatedListener.java @@ -69,11 +69,9 @@ public class ProcessTerminatedListener extends ProcessAdapter { processHandler.removeProcessListener(this); final String message = myProcessFinishedMessage.replaceAll(EXIT_CODE_REGEX, stringifyExitCode(event.getExitCode())); processHandler.notifyTextAvailable(message, ProcessOutputTypes.SYSTEM); - if (myProject != null) ApplicationManager.getApplication().invokeLater(new Runnable(){ - public void run() { - if (myProject.isDisposed()) return; - StatusBar.Info.set(message, myProject); - } + if (myProject != null) ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; + StatusBar.Info.set(message, myProject); }); } diff --git a/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java b/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java index 589d39ba292d..09de7995eb94 100644 --- a/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java +++ b/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java @@ -193,11 +193,8 @@ public class ExecUtil { GeneralCommandLine sudoCommandLine; if (SystemInfo.isMac) { - String escapedCommandLine = StringUtil.join(command, new Function() { - @Override - public String fun(String s) { - return escapeAppleScriptArgument(s); - } + String escapedCommandLine = StringUtil.join(command, s -> { + return escapeAppleScriptArgument(s); }, " & \" \" & "); String escapedScript = "tell current application\n" + " activate\n" + @@ -222,11 +219,8 @@ public class ExecUtil { sudoCommandLine = new GeneralCommandLine(command); } else if (SystemInfo.isUnix && hasTerminalApp()) { - String escapedCommandLine = StringUtil.join(command, new Function() { - @Override - public String fun(String s) { - return escapeUnixShellArgument(s); - } + String escapedCommandLine = StringUtil.join(command, s -> { + return escapeUnixShellArgument(s); }, " "); File script = createTempExecutableScript( "sudo", ".sh", diff --git a/platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.java b/platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.java index 8c7ed1e1b3b8..aeb901b507da 100644 --- a/platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.java +++ b/platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.java @@ -197,12 +197,7 @@ public class BrowserLauncherAppless extends BrowserLauncher { Runnable launchTask = null; if (browserPath == null && browser != null) { browserPath = PathUtil.toSystemDependentName(browser.getPath()); - launchTask = new Runnable() { - @Override - public void run() { - browseUsingPath(url, null, browser, project, additionalParameters); - } - }; + launchTask = () -> browseUsingPath(url, null, browser, project, additionalParameters); } return doLaunch(url, browserPath, browser, project, additionalParameters, launchTask); } diff --git a/platform/platform-api/src/com/intellij/ide/util/BrowseFilesListener.java b/platform/platform-api/src/com/intellij/ide/util/BrowseFilesListener.java index d2c127f29563..7d0d27f43732 100644 --- a/platform/platform-api/src/com/intellij/ide/util/BrowseFilesListener.java +++ b/platform/platform-api/src/com/intellij/ide/util/BrowseFilesListener.java @@ -78,11 +78,8 @@ public class BrowseFilesListener implements ActionListener { final VirtualFile fileToSelect = getFileToSelect(); myChooserDescriptor.setTitle(myTitle); // important to set title and description here because a shared descriptor instance can be used myChooserDescriptor.setDescription(myDescription); - FileChooser.chooseFiles(myChooserDescriptor, null, fileToSelect, new Consumer>() { - @Override - public void consume(final List files) { - doSetText(FileUtil.toSystemDependentName(files.get(0).getPath())); - } + FileChooser.chooseFiles(myChooserDescriptor, null, fileToSelect, files -> { + doSetText(FileUtil.toSystemDependentName(files.get(0).getPath())); }); } } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java index 861893622541..7a0c2a5b7b6c 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java @@ -47,13 +47,10 @@ public class AbstractTreeBuilder implements Disposable { @NonNls private static final String TREE_BUILDER = "TreeBuilder"; public static final boolean DEFAULT_UPDATE_INACTIVE = true; private final TransferToEDTQueue - myLaterInvocator = new TransferToEDTQueue("Tree later invocator", new Processor() { - @Override - public boolean process(Runnable runnable) { + myLaterInvocator = new TransferToEDTQueue("Tree later invocator", runnable -> { runnable.run(); return true; - } - }, new Condition() { + }, new Condition() { @Override public boolean value(Object o) { return isDisposed(); diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index 7838d6438eba..2d7f5ae626ec 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -900,27 +900,24 @@ public class AbstractTreeUi { } } - promise.done(new Consumer() { - @Override - public void consume(final Boolean changes) { - if (!changes) { - return; - } + promise.done(changes -> { + if (!changes) { + return; + } - invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.update: on done result") { - @Override - public void perform() { - Object element = nodeDescriptor.getElement(); - DefaultMutableTreeNode node = getNodeForElement(element, false); - if (node != null) { - TreePath path = getPathFor(node); - if (myTree.isVisible(path)) { - updateNodeImageAndPosition(node, false, true); - } + invokeLaterIfNeeded(false, new TreeRunnable("AbstractTreeUi.update: on done result") { + @Override + public void perform() { + Object element = nodeDescriptor.getElement(); + DefaultMutableTreeNode node = getNodeForElement(element, false); + if (node != null) { + TreePath path = getPathFor(node); + if (myTree.isVisible(path)) { + updateNodeImageAndPosition(node, false, true); } } - }); - } + } + }); }); return promise; } @@ -1133,19 +1130,16 @@ public class AbstractTreeUi { final Object prevElement = getElementFromDescriptor(descriptor); if (prevElement == null) return; update(descriptor, false) - .done(new Consumer() { - @Override - public void consume(Boolean changes) { - if (!isValid(descriptor)) { - if (isInStructure(prevElement)) { - getUpdater().addSubtreeToUpdateByElement(getTreeStructure().getParentElement(prevElement)); - return; - } - } - if (changes) { - updateNodeImageAndPosition(node, false, changes); + .done(changes -> { + if (!isValid(descriptor)) { + if (isInStructure(prevElement)) { + getUpdater().addSubtreeToUpdateByElement(getTreeStructure().getParentElement(prevElement)); + return; } } + if (changes) { + updateNodeImageAndPosition(node, false, changes); + } }); } @@ -2255,12 +2249,9 @@ public class AbstractTreeUi { final ActionCallback update = new ActionCallback(); if (needToUpdate) { update(childDescr, false) - .done(new Consumer() { - @Override - public void consume(Boolean changes) { - loadedChildren.putDescriptor(child, childDescr, changes); - update.setDone(); - } + .done(changes -> { + loadedChildren.putDescriptor(child, childDescr, changes); + update.setDone(); }); } else { @@ -3022,118 +3013,107 @@ public class AbstractTreeUi { final AsyncPromise result = new AsyncPromise(); final Ref childDesc = new Ref(childDescriptor); - update.done(new Consumer() { - @Override - public void consume(Boolean isChanged) { - final AtomicBoolean changes = new AtomicBoolean(isChanged); - final AtomicBoolean forceRemapping = new AtomicBoolean(); - final Ref newElement = new Ref(getElementFromDescriptor(childDesc.get())); + update.done(isChanged -> { + final AtomicBoolean changes = new AtomicBoolean(isChanged); + final AtomicBoolean forceRemapping = new AtomicBoolean(); + final Ref newElement = new Ref(getElementFromDescriptor(childDesc.get())); - final Integer index = newElement.get() == null ? null : elementToIndexMap.getValue(getBuilder().getTreeStructureElement(childDesc.get())); - Promise promise; - if (index == null) { - promise = Promise.resolve(false); - } - else { - final Object elementFromMap = elementToIndexMap.getKey(index); - if (elementFromMap != newElement.get() && elementFromMap.equals(newElement.get())) { - if (isInStructure(elementFromMap) && isInStructure(newElement.get())) { - final AsyncPromise updateIndexDone = new AsyncPromise(); - promise = updateIndexDone; - if (parentNode.getUserObject() instanceof NodeDescriptor) { - final NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); - childDesc.set(getTreeStructure().createDescriptor(elementFromMap, parentDescriptor)); - NodeDescriptor oldDesc = getDescriptorFrom(childNode); - if (oldDesc != null) { - childDesc.get().applyFrom(oldDesc); - } - - childNode.setUserObject(childDesc.get()); - newElement.set(elementFromMap); - forceRemapping.set(true); - update(childDesc.get(), false) - .done(new Consumer() { - @Override - public void consume(Boolean isChanged) { - changes.set(isChanged); - updateIndexDone.setResult(isChanged); - } - }); + final Integer index = newElement.get() == null ? null : elementToIndexMap.getValue(getBuilder().getTreeStructureElement(childDesc.get())); + Promise promise; + if (index == null) { + promise = Promise.resolve(false); + } + else { + final Object elementFromMap = elementToIndexMap.getKey(index); + if (elementFromMap != newElement.get() && elementFromMap.equals(newElement.get())) { + if (isInStructure(elementFromMap) && isInStructure(newElement.get())) { + final AsyncPromise updateIndexDone = new AsyncPromise(); + promise = updateIndexDone; + if (parentNode.getUserObject() instanceof NodeDescriptor) { + final NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); + childDesc.set(getTreeStructure().createDescriptor(elementFromMap, parentDescriptor)); + NodeDescriptor oldDesc = getDescriptorFrom(childNode); + if (oldDesc != null) { + childDesc.get().applyFrom(oldDesc); } - // todo why we don't process promise here? - } - else { - promise = Promise.resolve(changes.get()); + + childNode.setUserObject(childDesc.get()); + newElement.set(elementFromMap); + forceRemapping.set(true); + update(childDesc.get(), false) + .done(isChanged1 -> { + changes.set(isChanged1); + updateIndexDone.setResult(isChanged1); + }); } + // todo why we don't process promise here? } else { promise = Promise.resolve(changes.get()); } - - promise - .done(new TreeConsumer("AbstractTreeUi.processExistingNode: on done index updating after update") { - @Override - public void perform() { - if (childDesc.get().getIndex() != index.intValue()) { - changes.set(true); - } - childDesc.get().setIndex(index.intValue()); - } - }); + } + else { + promise = Promise.resolve(changes.get()); } promise - .done(new TreeConsumer("AbstractTreeUi.processExistingNode: on done index updating") { + .done(new TreeConsumer("AbstractTreeUi.processExistingNode: on done index updating after update") { @Override public void perform() { - if (!oldElement.equals(newElement.get()) || forceRemapping.get()) { - removeMapping(oldElement, childNode, newElement.get()); - Object newE = newElement.get(); - if (newE != null) { - createMapping(newE, childNode); - } - NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); - if (parentDescriptor != null) { - parentDescriptor.setChildrenSortingStamp(-1); + if (childDesc.get().getIndex() != index.intValue()) { + changes.set(true); } + childDesc.get().setIndex(index.intValue()); } + }); + } - if (index == null) { - int selectedIndex = -1; - if (TreeBuilderUtil.isNodeOrChildSelected(myTree, childNode)) { - selectedIndex = parentNode.getIndex(childNode); + promise + .done(new TreeConsumer("AbstractTreeUi.processExistingNode: on done index updating") { + @Override + public void perform() { + if (!oldElement.equals(newElement.get()) || forceRemapping.get()) { + removeMapping(oldElement, childNode, newElement.get()); + Object newE = newElement.get(); + if (newE != null) { + createMapping(newE, childNode); } - - if (childNode.getParent() instanceof DefaultMutableTreeNode) { - final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)childNode.getParent(); - if (myTree.isExpanded(new TreePath(parent.getPath()))) { - if (parent.getChildCount() == 1 && parent.getChildAt(0) == childNode) { - insertLoadingNode(parent, false); - } - } - } - - Object disposedElement = getElementFor(childNode); - - removeNodeFromParent(childNode, selectedIndex >= 0); - disposeNode(childNode); - - adjustSelectionOnChildRemove(parentNode, selectedIndex, disposedElement); - result.setResult(null); - } - else { - elementToIndexMap.remove(getBuilder().getTreeStructureElement(childDesc.get())); - updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true, true) - .doWhenDone(new Runnable() { - @Override - public void run() { - result.setResult(null); - } - }); + NodeDescriptor parentDescriptor = getDescriptorFrom(parentNode); + if (parentDescriptor != null) { + parentDescriptor.setChildrenSortingStamp(-1); } } - }); - } + + if (index == null) { + int selectedIndex = -1; + if (TreeBuilderUtil.isNodeOrChildSelected(myTree, childNode)) { + selectedIndex = parentNode.getIndex(childNode); + } + + if (childNode.getParent() instanceof DefaultMutableTreeNode) { + final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)childNode.getParent(); + if (myTree.isExpanded(new TreePath(parent.getPath()))) { + if (parent.getChildCount() == 1 && parent.getChildAt(0) == childNode) { + insertLoadingNode(parent, false); + } + } + } + + Object disposedElement = getElementFor(childNode); + + removeNodeFromParent(childNode, selectedIndex >= 0); + disposeNode(childNode); + + adjustSelectionOnChildRemove(parentNode, selectedIndex, disposedElement); + result.setResult(null); + } + else { + elementToIndexMap.remove(getBuilder().getTreeStructureElement(childDesc.get())); + updateNodeChildren(childNode, pass, null, false, canSmartExpand, forceUpdate, true, true) + .doWhenDone(() -> result.setResult(null)); + } + } + }); }); return result; } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java b/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java index 4e47eb39ef5b..ab006e2dd9ef 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java @@ -175,14 +175,11 @@ public class UpdaterTreeState { myUi._select(toSelect, new TreeRunnable("UpdaterTreeState.restore") { @Override public void perform() { - processUnsuccessfulSelections(toSelect, new Function() { - @Override - public Object fun(final Object o) { - if (myUi.getTree().isRootVisible() || !myUi.getTreeStructure().getRootElement().equals(o)) { - addSelection(o); - } - return o; + processUnsuccessfulSelections(toSelect, o -> { + if (myUi.getTree().isRootVisible() || !myUi.getTreeStructure().getRootElement().equals(o)) { + addSelection(o); } + return o; }, originallySelected); processAjusted(adjusted, originallySelected).doWhenDone(new TreeRunnable("UpdaterTreeState.restore: on done") { @@ -276,16 +273,13 @@ public class UpdaterTreeState { @Override public void perform() { final Set hangByParent = new HashSet (); - processUnsuccessfulSelections(newSelection, new Function() { - @Override - public Object fun(final Object o) { - if (myUi.isInStructure(o) && !adjusted.get(o).value(o)) { - hangByParent.add(o); - } else { - addAdjustedSelection(o, adjusted.get(o), null); - } - return null; + processUnsuccessfulSelections(newSelection, o -> { + if (myUi.isInStructure(o) && !adjusted.get(o).value(o)) { + hangByParent.add(o); + } else { + addAdjustedSelection(o, adjusted.get(o), null); } + return null; }, originallySelected); processHangByParent(hangByParent).notify(result); diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java index 35a1489f2503..b5177b5a7fc2 100644 --- a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java @@ -448,12 +448,9 @@ public abstract class AbstractWizard extends DialogWrapper { } private static void requestFocusTo(final JComponent component) { - UiNotifyConnector.doWhenFirstShown(component, new Runnable() { - @Override - public void run() { - final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(component); - focusManager.requestFocus(component, false); - } + UiNotifyConnector.doWhenFirstShown(component, () -> { + final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(component); + focusManager.requestFocus(component, false); }); } diff --git a/platform/platform-api/src/com/intellij/notification/Notifications.java b/platform/platform-api/src/com/intellij/notification/Notifications.java index cbba370a5077..1b050c4affc3 100644 --- a/platform/platform-api/src/com/intellij/notification/Notifications.java +++ b/platform/platform-api/src/com/intellij/notification/Notifications.java @@ -49,13 +49,10 @@ public interface Notifications { public static void register(@NotNull final String group_id, @NotNull final NotificationDisplayType defaultDisplayType) { if (ApplicationManager.getApplication().isUnitTestMode()) return; //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Application app = ApplicationManager.getApplication(); - if (!app.isDisposed()) { - app.getMessageBus().syncPublisher(TOPIC).register(group_id, defaultDisplayType); - } + SwingUtilities.invokeLater(() -> { + Application app = ApplicationManager.getApplication(); + if (!app.isDisposed()) { + app.getMessageBus().syncPublisher(TOPIC).register(group_id, defaultDisplayType); } }); } @@ -69,12 +66,7 @@ public interface Notifications { doNotify(notification, project); } else { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - doNotify(notification, project); - } - }); + UIUtil.invokeLaterIfNeeded(() -> doNotify(notification, project)); } } diff --git a/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java b/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java index e5031736e5d9..72337a1362a6 100644 --- a/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java +++ b/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java @@ -50,19 +50,13 @@ public class MnemonicHelper extends ComponentTreeWatcher { public void propertyChange(PropertyChangeEvent evt) { final Object source = evt.getSource(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - // It is needed to process this event later, - // because the method is invoked from the setText method - // before Swing updates mnemonics - @Override - public void run() { - if (source instanceof AbstractButton) { - // see javax.swing.AbstractButton.setText - DialogUtil.registerMnemonic(((AbstractButton)source)); - } else if (source instanceof JLabel) { - // javax.swing.JLabel.setText - DialogUtil.registerMnemonic(((JLabel)source), null); - } + SwingUtilities.invokeLater(() -> { + if (source instanceof AbstractButton) { + // see javax.swing.AbstractButton.setText + DialogUtil.registerMnemonic(((AbstractButton)source)); + } else if (source instanceof JLabel) { + // javax.swing.JLabel.setText + DialogUtil.registerMnemonic(((JLabel)source), null); } }); } diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/AsyncUpdateAction.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/AsyncUpdateAction.java index b948336425cc..660887e3ee93 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/AsyncUpdateAction.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/AsyncUpdateAction.java @@ -40,22 +40,16 @@ public abstract class AsyncUpdateAction extends AnAction { final Presentation originalPresentation = e.getPresentation(); if (!forceSyncUpdate(e) && isDumbAware()) { final Presentation realPresentation = originalPresentation.clone(); - ourUpdaterService.submit(new Runnable() { - @Override - public void run() { - performUpdate(realPresentation, data); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (originalPresentation.isVisible() != realPresentation.isVisible()) { - LOG.error("Async update is not supported for actions that change their visibility." + - "Either stop extending AsyncUpdateAction or override forceSyncUpdate() to return true." + - "Action class is: " + AsyncUpdateAction.this.getClass().getName()); - } - originalPresentation.copyFrom(realPresentation); - } - }); - } + ourUpdaterService.submit(() -> { + performUpdate(realPresentation, data); + SwingUtilities.invokeLater(() -> { + if (originalPresentation.isVisible() != realPresentation.isVisible()) { + LOG.error("Async update is not supported for actions that change their visibility." + + "Either stop extending AsyncUpdateAction or override forceSyncUpdate() to return true." + + "Action class is: " + AsyncUpdateAction.this.getClass().getName()); + } + originalPresentation.copyFrom(realPresentation); + }); }); originalPresentation.setVisible(true); diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java index f6056927ebaa..3e5c5414fa98 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java @@ -168,12 +168,7 @@ public abstract class ComboBoxAction extends AnAction implements CustomComponent @Override public void actionPerformed(ActionEvent e) { if (!myForcePressed) { - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - showPopup(); - } - }); + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> showPopup()); } } } @@ -251,20 +246,14 @@ public abstract class ComboBoxAction extends AnAction implements CustomComponent myForcePressed = true; repaint(); - return new Runnable() { - @Override - public void run() { - // give the button a chance to handle action listener - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myForcePressed = false; - myPopup = null; - } - }, ModalityState.any()); - repaint(); - fireStateChanged(); - } + return () -> { + // give the button a chance to handle action listener + ApplicationManager.getApplication().invokeLater(() -> { + myForcePressed = false; + myPopup = null; + }, ModalityState.any()); + repaint(); + fireStateChanged(); }; } diff --git a/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java b/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java index 10b1aacc5ac2..77e7c834afd5 100644 --- a/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java +++ b/platform/platform-api/src/com/intellij/openapi/diff/DocumentsSynchronizer.java @@ -77,17 +77,11 @@ abstract class DocumentsSynchronizer { LOG.assertTrue(!myDuringModification); try { myDuringModification = true; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - LOG.assertTrue(endOffset <= document.getTextLength()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(startOffset, endOffset, newText); - } - }); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + LOG.assertTrue(endOffset <= document.getTextLength()); + ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(startOffset, endOffset, newText); + }); }, DiffBundle.message("save.merge.result.command.name"), document); } finally { diff --git a/platform/platform-api/src/com/intellij/openapi/editor/highlighter/FragmentedEditorHighlighter.java b/platform/platform-api/src/com/intellij/openapi/editor/highlighter/FragmentedEditorHighlighter.java index db138237af81..7554170e66a8 100644 --- a/platform/platform-api/src/com/intellij/openapi/editor/highlighter/FragmentedEditorHighlighter.java +++ b/platform/platform-api/src/com/intellij/openapi/editor/highlighter/FragmentedEditorHighlighter.java @@ -113,12 +113,7 @@ public class FragmentedEditorHighlighter implements EditorHighlighter { @NotNull @Override public HighlighterIterator createIterator(int startOffset) { - int index = Collections.binarySearch(myPieces, new Element(startOffset, 0, null, null), new Comparator() { - @Override - public int compare(Element o1, Element o2) { - return o1.getStart() - o2.getStart(); - } - }); + int index = Collections.binarySearch(myPieces, new Element(startOffset, 0, null, null), (o1, o2) -> o1.getStart() - o2.getStart()); // index: (-insertion point - 1), where insertionPoint is the index of the first element greater than the key // and we need index of the first element that is less or equal (floorElement) if (index < 0) index = Math.max(-index - 2, 0); diff --git a/platform/platform-api/src/com/intellij/openapi/fileChooser/FileChooser.java b/platform/platform-api/src/com/intellij/openapi/fileChooser/FileChooser.java index fee268813d14..12c04d0cdca1 100644 --- a/platform/platform-api/src/com/intellij/openapi/fileChooser/FileChooser.java +++ b/platform/platform-api/src/com/intellij/openapi/fileChooser/FileChooser.java @@ -145,11 +145,6 @@ public class FileChooser { @Nullable final VirtualFile toSelect, @NotNull final Consumer callback) { LOG.assertTrue(!descriptor.isChooseMultiple()); - chooseFiles(descriptor, project, parent, toSelect, new Consumer>() { - @Override - public void consume(List files) { - callback.consume(files.get(0)); - } - }); + chooseFiles(descriptor, project, parent, toSelect, files -> callback.consume(files.get(0))); } } diff --git a/platform/platform-api/src/com/intellij/openapi/fileChooser/FileTypeDescriptor.java b/platform/platform-api/src/com/intellij/openapi/fileChooser/FileTypeDescriptor.java index 109eaaeb3adb..3301f040524c 100644 --- a/platform/platform-api/src/com/intellij/openapi/fileChooser/FileTypeDescriptor.java +++ b/platform/platform-api/src/com/intellij/openapi/fileChooser/FileTypeDescriptor.java @@ -31,14 +31,11 @@ public class FileTypeDescriptor extends FileChooserDescriptor { public FileTypeDescriptor(String title, @NotNull String... extensions) { super(true, false, false, true, false, false); assert extensions.length > 0 : "There should be at least one extension"; - myExtensions = ContainerUtil.immutableList(ContainerUtil.map(extensions, new Function() { - @Override - public String fun(String ext) { - if (ext.startsWith(".")) { - return ext; - } - return "." + ext; + myExtensions = ContainerUtil.immutableList(ContainerUtil.map(extensions, ext -> { + if (ext.startsWith(".")) { + return ext; } + return "." + ext; })); setTitle(title); diff --git a/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java b/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java index 316fdd4640b2..13092fa5239e 100644 --- a/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java +++ b/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java @@ -219,13 +219,10 @@ public class OpenFileDescriptor implements Navigatable, Comparable { + for (FoldRegion region : allRegions) { + if (!region.isExpanded() && range.intersects(TextRange.create(region))) { + region.setExpanded(true); } } }); diff --git a/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java b/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java index cd89fcdae5a4..319358f1c32b 100644 --- a/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java +++ b/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java @@ -113,11 +113,9 @@ public abstract class CompositeSettingsEditor extends SettingsEditor { + if (!myIsDisposed) { + sync(); } }, 300); } diff --git a/platform/platform-api/src/com/intellij/openapi/progress/RunBackgroundable.java b/platform/platform-api/src/com/intellij/openapi/progress/RunBackgroundable.java index 2aa21638942b..6c38ccdbcffc 100644 --- a/platform/platform-api/src/com/intellij/openapi/progress/RunBackgroundable.java +++ b/platform/platform-api/src/com/intellij/openapi/progress/RunBackgroundable.java @@ -47,14 +47,12 @@ public class RunBackgroundable { } final boolean finalCanceled = canceled; - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - if (finalCanceled) { - task.onCancel(); - } - else { - task.onSuccess(); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (finalCanceled) { + task.onCancel(); + } + else { + task.onSuccess(); } }); } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java b/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java index 7a9f7826093e..b31e5fcf549f 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java @@ -106,17 +106,14 @@ public class ComboBox extends ComboBoxWithWidePopup implements AWTEventLis final JBList list = createJBList(getModel()); myJBPopup = JBPopupFactory.getInstance() .createListPopupBuilder(list) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value != null) { - configureEditor(getEditor(), value); - IdeFocusManager.getGlobalInstance().requestFocus(ComboBox.this, true); - assert myJBPopup != null; - ComboBox.this.getUI().setPopupVisible(ComboBox.this, false); - myJBPopup.cancel(); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value != null) { + configureEditor(getEditor(), value); + IdeFocusManager.getGlobalInstance().requestFocus(ComboBox.this, true); + assert myJBPopup != null; + ComboBox.this.getUI().setPopupVisible(ComboBox.this, false); + myJBPopup.cancel(); } }) .setFocusOwners(new Component[]{this}) diff --git a/platform/platform-api/src/com/intellij/openapi/ui/ComboBoxTableRenderer.java b/platform/platform-api/src/com/intellij/openapi/ui/ComboBoxTableRenderer.java index f35d76fff51c..e3090e994d0d 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/ComboBoxTableRenderer.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/ComboBoxTableRenderer.java @@ -88,11 +88,7 @@ public class ComboBoxTableRenderer extends JLabel implements TableCellRendere protected Runnable onChosen(@NotNull final T value) { stopCellEditing(value); - return new Runnable() { - public void run() { - stopCellEditing(value); - } - }; + return () -> stopCellEditing(value); } @Override @@ -120,11 +116,7 @@ public class ComboBoxTableRenderer extends JLabel implements TableCellRendere customizeComponent(t, table, true); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - showPopup(t, row); - } - }); + SwingUtilities.invokeLater(() -> showPopup(t, row)); return this; } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/ComponentWithBrowseButton.java b/platform/platform-api/src/com/intellij/openapi/ui/ComponentWithBrowseButton.java index 262fed0d8e61..d4cf86f4df4c 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/ComponentWithBrowseButton.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/ComponentWithBrowseButton.java @@ -257,11 +257,8 @@ public class ComponentWithBrowseButton extends JPanel i } } - FileChooser.chooseFile(fileChooserDescriptor, getProject(), getInitialFile(), new Consumer() { - @Override - public void consume(VirtualFile file) { - onFileChosen(file); - } + FileChooser.chooseFile(fileChooserDescriptor, getProject(), getInitialFile(), file -> { + onFileChosen(file); }); } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java index 75743bade835..bfea932601da 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java @@ -338,14 +338,11 @@ public abstract class DialogWrapper { myErrorPainter.setValidationInfo(info); if (!myErrorText.isTextSet(info.message)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myDisposed) return; - setErrorText(info.message); - myPeer.getRootPane().getGlassPane().repaint(); - getOKAction().setEnabled(false); - } + SwingUtilities.invokeLater(() -> { + if (myDisposed) return; + setErrorText(info.message); + myPeer.getRootPane().getGlassPane().repaint(); + getOKAction().setEnabled(false); }); } } @@ -353,25 +350,17 @@ public abstract class DialogWrapper { private void installErrorPainter() { if (myErrorPainterInstalled) return; myErrorPainterInstalled = true; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - IdeGlassPaneUtil.installPainter(getContentPanel(), myErrorPainter, myDisposable); - } - }); + UIUtil.invokeLaterIfNeeded(() -> IdeGlassPaneUtil.installPainter(getContentPanel(), myErrorPainter, myDisposable)); } private void clearProblems() { myErrorPainter.setValidationInfo(null); if (!myErrorText.isTextSet(null)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myDisposed) return; - setErrorText(null); - myPeer.getRootPane().getGlassPane().repaint(); - getOKAction().setEnabled(true); - } + SwingUtilities.invokeLater(() -> { + if (myDisposed) return; + setErrorText(null); + myPeer.getRootPane().getGlassPane().repaint(); + getOKAction().setEnabled(true); }); } } @@ -1339,34 +1328,28 @@ public abstract class DialogWrapper { } void startTrackingValidation() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!myValidationStarted && !myDisposed) { - myValidationStarted = true; - initValidation(); - } + SwingUtilities.invokeLater(() -> { + if (!myValidationStarted && !myDisposed) { + myValidationStarted = true; + initValidation(); } }); } protected final void initValidation() { myValidationAlarm.cancelAllRequests(); - final Runnable validateRequest = new Runnable() { - @Override - public void run() { - if (myDisposed) return; - final ValidationInfo result = doValidate(); - if (result == null) { - clearProblems(); - } - else { - reportProblem(result); - } + final Runnable validateRequest = () -> { + if (myDisposed) return; + final ValidationInfo result = doValidate(); + if (result == null) { + clearProblems(); + } + else { + reportProblem(result); + } - if (!myDisposed) { - initValidation(); - } + if (!myDisposed) { + initValidation(); } }; @@ -1907,15 +1890,12 @@ public abstract class DialogWrapper { } myLastErrorText = text; myErrorTextAlarm.cancelAllRequests(); - myErrorTextAlarm.addRequest(new Runnable() { - @Override - public void run() { - final String text = myLastErrorText; - if (myActualSize == null && !myErrorText.isVisible()) { - myActualSize = getSize(); - } - myErrorText.setError(text); + myErrorTextAlarm.addRequest(() -> { + final String text1 = myLastErrorText; + if (myActualSize == null && !myErrorText.isVisible()) { + myActualSize = getSize(); } + myErrorText.setError(text1); }, 300, null); } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/LoadingDecorator.java b/platform/platform-api/src/com/intellij/openapi/ui/LoadingDecorator.java index 327050ab352f..514e449746a2 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/LoadingDecorator.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/LoadingDecorator.java @@ -98,16 +98,10 @@ public class LoadingDecorator { myStartRequest = true; if (myDelay > 0) { - myStartAlarm.addRequest(new Runnable() { - public void run() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - if (!myStartRequest) return; - _startLoading(takeSnapshot); - } - }); - } - }, myDelay); + myStartAlarm.addRequest(() -> UIUtil.invokeLaterIfNeeded(() -> { + if (!myStartRequest) return; + _startLoading(takeSnapshot); + }), myDelay); } else { _startLoading(takeSnapshot); diff --git a/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsComponent.java b/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsComponent.java index 2e00b3febc1a..a9c1942f2436 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsComponent.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsComponent.java @@ -557,11 +557,7 @@ public abstract class MasterDetailsComponent implements Configurable, DetailsCom } protected Comparator getNodeComparator() { - return new Comparator() { - public int compare(final MyNode o1, final MyNode o2) { - return StringUtil.naturalCompare(o1.getDisplayName(), o2.getDisplayName()); - } - }; + return (o1, o2) -> StringUtil.naturalCompare(o1.getDisplayName(), o2.getDisplayName()); } public ActionCallback selectNodeInTree(final DefaultMutableTreeNode nodeToSelect) { @@ -830,11 +826,8 @@ public abstract class MasterDetailsComponent implements Configurable, DetailsCom presentation.setEnabled(false); final TreePath[] selectionPath = myTree.getSelectionPaths(); if (selectionPath != null) { - Object[] nodes = ContainerUtil.map2Array(selectionPath, new Function() { - @Override - public Object fun(TreePath treePath) { - return treePath.getLastPathComponent(); - } + Object[] nodes = ContainerUtil.map2Array(selectionPath, treePath -> { + return treePath.getLastPathComponent(); }); if (!myCondition.value(nodes)) return; presentation.setEnabled(true); diff --git a/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsStateService.java b/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsStateService.java index 25f886af1bcb..9f44e93986d3 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsStateService.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/MasterDetailsStateService.java @@ -73,12 +73,7 @@ public class MasterDetailsStateService implements PersistentStateComponent() { - @Override - public int compare(ComponentState o1, ComponentState o2) { - return o1.myKey.compareTo(o2.myKey); - } - }); + Collections.sort(states.getStates(), (o1, o2) -> o1.myKey.compareTo(o2.myKey)); return states; } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java index bb9ca4072eca..521c3dff8467 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java @@ -639,12 +639,7 @@ public class Messages { final int defaultOptionIndex, final int focusedOptionIndex, Icon icon) { return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, checkboxText, checked, defaultOptionIndex, focusedOptionIndex, icon, - new PairFunction() { - @Override - public Integer fun(final Integer exitCode, final JCheckBox cb) { - return exitCode == -1 ? CANCEL : exitCode + (cb.isSelected() ? 1 : 0); - } - }); + (exitCode, cb) -> exitCode == -1 ? CANCEL : exitCode + (cb.isSelected() ? 1 : 0)); } public static int showCheckboxMessageDialog(String message, @Nls(capitalization = Nls.Capitalization.Title) String title, @NotNull String[] options, String checkboxText, final boolean checked, @@ -1221,12 +1216,9 @@ public class Messages { builder.setTitle(rawText); builder.addOkAction(); builder.addCancelAction(); - builder.setOkOperation(new Runnable() { - @Override - public void run() { - textField.setText(lineJoiner.fun(Arrays.asList(StringUtil.splitByLines(textArea.getText())))); - builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); - } + builder.setOkOperation(() -> { + textField.setText(lineJoiner.fun(Arrays.asList(StringUtil.splitByLines(textArea.getText())))); + builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); }); builder.show(); } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/popup/PopupChooserBuilder.java b/platform/platform-api/src/com/intellij/openapi/ui/popup/PopupChooserBuilder.java index f1b888f84207..c4d44822d59a 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/popup/PopupChooserBuilder.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/popup/PopupChooserBuilder.java @@ -212,12 +212,7 @@ public class PopupChooserBuilder { if (myChooserComponent instanceof JList) { list = (JList)myChooserComponent; myChooserComponent = ListWithFilter.wrap(list, new MyListWrapper(list), myItemsNamer); - keyEventHandler = new BooleanFunction() { - @Override - public boolean fun(KeyEvent keyEvent) { - return keyEvent.isConsumed(); - } - }; + keyEventHandler = keyEvent -> keyEvent.isConsumed(); } else { list = null; diff --git a/platform/platform-api/src/com/intellij/openapi/ui/popup/util/PopupUtil.java b/platform/platform-api/src/com/intellij/openapi/ui/popup/util/PopupUtil.java index fa1ce0b8617b..bd941dad168e 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/popup/util/PopupUtil.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/popup/util/PopupUtil.java @@ -115,8 +115,40 @@ public class PopupUtil { } public static void showBalloonForActiveFrame(@NotNull final String message, final MessageType type) { - final Runnable runnable = new Runnable() { - public void run() { + final Runnable runnable = () -> { + final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); + if (frame == null) { + final Project[] projects = ProjectManager.getInstance().getOpenProjects(); + final Project project = projects == null || projects.length == 0 ? ProjectManager.getInstance().getDefaultProject() : projects[0]; + final JFrame jFrame = WindowManager.getInstance().getFrame(project); + if (jFrame != null) { + showBalloonForComponent(jFrame, message, type, true, project); + } else { + LOG.info("Can not get component to show message: " + message); + } + return; + } + showBalloonForComponent(frame.getComponent(), message, type, true, frame.getProject()); + }; + UIUtil.invokeLaterIfNeeded(runnable); + } + + public static void showBalloonForActiveComponent(@NotNull final String message, final MessageType type) { + Runnable runnable = () -> { + Window[] windows = Window.getWindows(); + Window targetWindow = null; + for (Window each : windows) { + if (each.isActive()) { + targetWindow = each; + break; + } + } + + if (targetWindow == null) { + targetWindow = JOptionPane.getRootFrame(); + } + + if (targetWindow == null) { final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); if (frame == null) { final Project[] projects = ProjectManager.getInstance().getOpenProjects(); @@ -130,44 +162,8 @@ public class PopupUtil { return; } showBalloonForComponent(frame.getComponent(), message, type, true, frame.getProject()); - } - }; - UIUtil.invokeLaterIfNeeded(runnable); - } - - public static void showBalloonForActiveComponent(@NotNull final String message, final MessageType type) { - Runnable runnable = new Runnable() { - public void run() { - Window[] windows = Window.getWindows(); - Window targetWindow = null; - for (Window each : windows) { - if (each.isActive()) { - targetWindow = each; - break; - } - } - - if (targetWindow == null) { - targetWindow = JOptionPane.getRootFrame(); - } - - if (targetWindow == null) { - final IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); - if (frame == null) { - final Project[] projects = ProjectManager.getInstance().getOpenProjects(); - final Project project = projects == null || projects.length == 0 ? ProjectManager.getInstance().getDefaultProject() : projects[0]; - final JFrame jFrame = WindowManager.getInstance().getFrame(project); - if (jFrame != null) { - showBalloonForComponent(jFrame, message, type, true, project); - } else { - LOG.info("Can not get component to show message: " + message); - } - return; - } - showBalloonForComponent(frame.getComponent(), message, type, true, frame.getProject()); - } else { - showBalloonForComponent(targetWindow, message, type, true, null); - } + } else { + showBalloonForComponent(targetWindow, message, type, true, null); } }; UIUtil.invokeLaterIfNeeded(runnable); diff --git a/platform/platform-api/src/com/intellij/openapi/util/EdtRunnable.java b/platform/platform-api/src/com/intellij/openapi/util/EdtRunnable.java index 84f174706322..5222ab8ac85d 100644 --- a/platform/platform-api/src/com/intellij/openapi/util/EdtRunnable.java +++ b/platform/platform-api/src/com/intellij/openapi/util/EdtRunnable.java @@ -22,11 +22,9 @@ public abstract class EdtRunnable implements ExpirableRunnable { private boolean myExpired; public final void run() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - if (!isExpired()) { - runEdt(); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (!isExpired()) { + runEdt(); } }); } diff --git a/platform/platform-api/src/com/intellij/openapi/util/process/InterruptibleActivity.java b/platform/platform-api/src/com/intellij/openapi/util/process/InterruptibleActivity.java index 05a895a60559..923fdb123207 100644 --- a/platform/platform-api/src/com/intellij/openapi/util/process/InterruptibleActivity.java +++ b/platform/platform-api/src/com/intellij/openapi/util/process/InterruptibleActivity.java @@ -56,24 +56,18 @@ public abstract class InterruptibleActivity { final Semaphore semaphore = new Semaphore(); semaphore.down(); - application.executeOnPooledThread(new Runnable() { - public void run() { - try { - start(); - } - finally { - semaphore.up(); - } + application.executeOnPooledThread(() -> { + try { + start(); + } + finally { + semaphore.up(); } }); final int rc = waitForSemaphore(semaphore); if (rc != 0) { - application.executeOnPooledThread(new Runnable() { - public void run() { - interrupt(); - } - }); + application.executeOnPooledThread(() -> interrupt()); } return rc; @@ -107,11 +101,7 @@ public abstract class InterruptibleActivity { final int[] retcode = new int[1]; try { - GuiUtils.runOrInvokeAndWait(new Runnable() { - public void run() { - retcode[0] = processTimeout(); - } - }); + GuiUtils.runOrInvokeAndWait(() -> retcode[0] = processTimeout()); } catch (Exception e) { throw new RuntimeException(e); diff --git a/platform/platform-api/src/com/intellij/openapi/util/process/ProcessCloseUtil.java b/platform/platform-api/src/com/intellij/openapi/util/process/ProcessCloseUtil.java index 6f6db5543ffd..eb9a3fabb0a6 100644 --- a/platform/platform-api/src/com/intellij/openapi/util/process/ProcessCloseUtil.java +++ b/platform/platform-api/src/com/intellij/openapi/util/process/ProcessCloseUtil.java @@ -34,32 +34,28 @@ public class ProcessCloseUtil { outerSemaphore.down(); final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - public void run() { - try { - final Semaphore semaphore = new Semaphore(); - semaphore.down(); + application.executeOnPooledThread(() -> { + try { + final Semaphore semaphore = new Semaphore(); + semaphore.down(); - final Runnable closeRunnable = new Runnable() { - public void run() { - try { - closeProcessImpl(process); - } - finally { - semaphore.up(); - } - } - }; - - final Future innerFuture = application.executeOnPooledThread(closeRunnable); - semaphore.waitFor(ourAsynchronousWaitTimeout); - if ( ! (innerFuture.isDone() || innerFuture.isCancelled())) { - innerFuture.cancel(true); // will call interrupt() + final Runnable closeRunnable = () -> { + try { + closeProcessImpl(process); } + finally { + semaphore.up(); + } + }; + + final Future innerFuture = application.executeOnPooledThread(closeRunnable); + semaphore.waitFor(ourAsynchronousWaitTimeout); + if ( ! (innerFuture.isDone() || innerFuture.isCancelled())) { + innerFuture.cancel(true); // will call interrupt() } - finally { - outerSemaphore.up(); - } + } + finally { + outerSemaphore.up(); } }); diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/VfsUtil.java b/platform/platform-api/src/com/intellij/openapi/vfs/VfsUtil.java index e78c36163226..0637a47a59f8 100644 --- a/platform/platform-api/src/com/intellij/openapi/vfs/VfsUtil.java +++ b/platform/platform-api/src/com/intellij/openapi/vfs/VfsUtil.java @@ -460,12 +460,9 @@ public class VfsUtil extends VfsUtilCore { @NotNull public static List collectChildrenRecursively(@NotNull final VirtualFile root) { final List result = new ArrayList(); - processFilesRecursively(root, new Processor() { - @Override - public boolean process(final VirtualFile t) { - result.add(t); - return true; - } + processFilesRecursively(root, t -> { + result.add(t); + return true; }); return result; } diff --git a/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java b/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java index 3895ce94636b..e0b6424bf445 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/StatusBar.java @@ -47,11 +47,8 @@ public interface StatusBar extends StatusBarInfo, Disposable { if (project != null) { if (project.isDisposed()) return; if (!project.isInitialized()) { - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - public void run() { - project.getMessageBus().syncPublisher(TOPIC).setInfo(text, requestor); - } - }); + StartupManager.getInstance(project).runWhenProjectIsInitialized( + () -> project.getMessageBus().syncPublisher(TOPIC).setInfo(text, requestor)); return; } } diff --git a/platform/platform-api/src/com/intellij/ui/AutoScrollFromSourceHandler.java b/platform/platform-api/src/com/intellij/ui/AutoScrollFromSourceHandler.java index 89f9190ce71a..81fb978c4714 100644 --- a/platform/platform-api/src/com/intellij/ui/AutoScrollFromSourceHandler.java +++ b/platform/platform-api/src/com/intellij/ui/AutoScrollFromSourceHandler.java @@ -80,12 +80,7 @@ public abstract class AutoScrollFromSourceHandler implements Disposable { final FileEditor editor = event.getNewEditor(); if (editor != null && myComponent.isShowing() && isAutoScrollEnabled()) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - selectElementFromEditor(editor); - } - }, getAlarmDelay(), getModalityState()); + myAlarm.addRequest(() -> selectElementFromEditor(editor), getAlarmDelay(), getModalityState()); } } }); diff --git a/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java b/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java index 0259031eb7c2..1a80823dc6df 100644 --- a/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java +++ b/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java @@ -142,11 +142,7 @@ public abstract class AutoScrollToSourceHandler { public void onMouseClicked(final Component component) { myAutoScrollAlarm.cancelAllRequests(); if (isAutoScrollMode()){ - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - scrollToSource(component); - } - }); + ApplicationManager.getApplication().invokeLater(() -> scrollToSource(component)); } } @@ -162,11 +158,9 @@ public abstract class AutoScrollToSourceHandler { myAutoScrollAlarm.cancelAllRequests(); myAutoScrollAlarm.addRequest( - new Runnable() { - public void run() { - if (component.isShowing()) { //for tests - scrollToSource(component); - } + () -> { + if (component.isShowing()) { //for tests + scrollToSource(component); } }, 500 @@ -182,31 +176,28 @@ public abstract class AutoScrollToSourceHandler { protected void scrollToSource(final Component tree) { DataContext dataContext=DataManager.getInstance().getDataContext(tree); - getReady(dataContext).doWhenDone(new Runnable() { - @Override - public void run() { - DataContext context = DataManager.getInstance().getDataContext(tree); - final VirtualFile vFile = CommonDataKeys.VIRTUAL_FILE.getData(context); - if (vFile != null) { - // Attempt to navigate to the virtual file with unknown file type will show a modal dialog - // asking to register some file type for this file. This behaviour is undesirable when autoscrolling. - if (vFile.getFileType() == FileTypes.UNKNOWN || vFile.getFileType() instanceof INativeFileType) return; + getReady(dataContext).doWhenDone(() -> { + DataContext context = DataManager.getInstance().getDataContext(tree); + final VirtualFile vFile = CommonDataKeys.VIRTUAL_FILE.getData(context); + if (vFile != null) { + // Attempt to navigate to the virtual file with unknown file type will show a modal dialog + // asking to register some file type for this file. This behaviour is undesirable when autoscrolling. + if (vFile.getFileType() == FileTypes.UNKNOWN || vFile.getFileType() instanceof INativeFileType) return; - //IDEA-84881 Don't autoscroll to very large files - if (vFile.getLength() > PersistentFSConstants.getMaxIntellisenseFileSize()) return; - } - Navigatable[] navigatables = CommonDataKeys.NAVIGATABLE_ARRAY.getData(context); - if (navigatables != null) { - if (navigatables.length > 1) { - return; - } - for (Navigatable navigatable : navigatables) { - // we are not going to open modal dialog during autoscrolling - if (!navigatable.canNavigateToSource()) return; - } - } - OpenSourceUtil.navigate(false, true, navigatables); + //IDEA-84881 Don't autoscroll to very large files + if (vFile.getLength() > PersistentFSConstants.getMaxIntellisenseFileSize()) return; } + Navigatable[] navigatables = CommonDataKeys.NAVIGATABLE_ARRAY.getData(context); + if (navigatables != null) { + if (navigatables.length > 1) { + return; + } + for (Navigatable navigatable : navigatables) { + // we are not going to open modal dialog during autoscrolling + if (!navigatable.canNavigateToSource()) return; + } + } + OpenSourceUtil.navigate(false, true, navigatables); }); } diff --git a/platform/platform-api/src/com/intellij/ui/EditorNotificationPanel.java b/platform/platform-api/src/com/intellij/ui/EditorNotificationPanel.java index c449c2afe497..a7c1731ce73a 100644 --- a/platform/platform-api/src/com/intellij/ui/EditorNotificationPanel.java +++ b/platform/platform-api/src/com/intellij/ui/EditorNotificationPanel.java @@ -90,11 +90,8 @@ public class EditorNotificationPanel extends JPanel implements IntentionActionPr } public HyperlinkLabel createActionLabel(final String text, @NonNls final String actionId) { - return createActionLabel(text, new Runnable() { - @Override - public void run() { - executeAction(actionId); - } + return createActionLabel(text, () -> { + executeAction(actionId); }); } diff --git a/platform/platform-api/src/com/intellij/ui/ExcludingTraversalPolicy.java b/platform/platform-api/src/com/intellij/ui/ExcludingTraversalPolicy.java index 52f58a17a900..6815d929c312 100644 --- a/platform/platform-api/src/com/intellij/ui/ExcludingTraversalPolicy.java +++ b/platform/platform-api/src/com/intellij/ui/ExcludingTraversalPolicy.java @@ -47,11 +47,7 @@ public class ExcludingTraversalPolicy extends FocusTraversalPolicy { try { if (!myRecursionGuard.add("getComponentAfter")) return null; - return traverse(aContainer, aComponent, new Function, Component>() { - public Component fun(Pair param) { - return myWrappee.getComponentAfter(param.first, param.second); - } - }); + return traverse(aContainer, aComponent, param -> myWrappee.getComponentAfter(param.first, param.second)); } finally { myRecursionGuard.clear(); @@ -63,11 +59,7 @@ public class ExcludingTraversalPolicy extends FocusTraversalPolicy { try { if (!myRecursionGuard.add("getComponentBefore")) return null; - return traverse(aContainer, aComponent, new Function, Component>() { - public Component fun(Pair param) { - return myWrappee.getComponentBefore(param.first, param.second); - } - }); + return traverse(aContainer, aComponent, param -> myWrappee.getComponentBefore(param.first, param.second)); } finally { myRecursionGuard.clear(); diff --git a/platform/platform-api/src/com/intellij/ui/FilterComponent.java b/platform/platform-api/src/com/intellij/ui/FilterComponent.java index 2d4f97ec1b5c..25104386cfd7 100644 --- a/platform/platform-api/src/com/intellij/ui/FilterComponent.java +++ b/platform/platform-api/src/com/intellij/ui/FilterComponent.java @@ -47,12 +47,9 @@ public abstract class FilterComponent extends JPanel { @Override protected Runnable createItemChosenCallback(JList list) { final Runnable callback = super.createItemChosenCallback(list); - return new Runnable() { - @Override - public void run() { - callback.run(); - filter(); - } + return () -> { + callback.run(); + filter(); }; } @@ -109,11 +106,7 @@ public abstract class FilterComponent extends JPanel { private void onChange() { if (myOnTheFly) { myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable(){ - public void run() { - onlineFilter(); - } - }, 100, ModalityState.stateForComponent(myFilter)); + myUpdateAlarm.addRequest(() -> onlineFilter(), 100, ModalityState.stateForComponent(myFilter)); } } diff --git a/platform/platform-api/src/com/intellij/ui/GuiUtils.java b/platform/platform-api/src/com/intellij/ui/GuiUtils.java index 8879ab6f4c92..792556e50111 100644 --- a/platform/platform-api/src/com/intellij/ui/GuiUtils.java +++ b/platform/platform-api/src/com/intellij/ui/GuiUtils.java @@ -237,19 +237,16 @@ public class GuiUtils { if (pane.getDividerLocation() > 0) { // let the component chance to resize itself - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - double proportion; - if (pane.getOrientation() == JSplitPane.VERTICAL_SPLIT) { - proportion = pane.getDividerLocation() / (double)(parent.getHeight() - pane.getDividerSize()); - } - else { - proportion = pane.getDividerLocation() / (double)(parent.getWidth() - pane.getDividerSize()); - } - if (proportion > 0 && proportion < 1) { - splitter.setProportion((float)proportion); - } + SwingUtilities.invokeLater(() -> { + double proportion; + if (pane.getOrientation() == JSplitPane.VERTICAL_SPLIT) { + proportion = pane.getDividerLocation() / (double)(parent.getHeight() - pane.getDividerSize()); + } + else { + proportion = pane.getDividerLocation() / (double)(parent.getWidth() - pane.getDividerSize()); + } + if (proportion > 0 && proportion < 1) { + splitter.setProportion((float)proportion); } }); } @@ -309,12 +306,7 @@ public class GuiUtils { } public static void enableChildren(Component container, final boolean enabled, JComponent... excludeComponents) { - iterateChildren(container, new Consumer() { - @Override - public void consume(final Component t) { - enableComponent(t, enabled); - } - }, excludeComponents); + iterateChildren(container, t -> enableComponent(t, enabled), excludeComponents); } private static void enableComponent(Component component, boolean enabled) { diff --git a/platform/platform-api/src/com/intellij/ui/HyperlinkLabel.java b/platform/platform-api/src/com/intellij/ui/HyperlinkLabel.java index 0051af59a488..002e2abda263 100644 --- a/platform/platform-api/src/com/intellij/ui/HyperlinkLabel.java +++ b/platform/platform-api/src/com/intellij/ui/HyperlinkLabel.java @@ -48,13 +48,9 @@ import java.util.List; * @author Eugene Belyaev */ public class HyperlinkLabel extends HighlightableComponent { - private static final TextAttributes BOLD_ATTRIBUTES = new TextAttributes(new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - final Color foreground = UIUtil.getLabelTextForeground(); - return foreground == null ? UIUtil.getLabelForeground() : foreground; - } + private static final TextAttributes BOLD_ATTRIBUTES = new TextAttributes(new JBColor(() -> { + final Color foreground1 = UIUtil.getLabelTextForeground(); + return foreground1 == null ? UIUtil.getLabelForeground() : foreground1; }), null, null, null, Font.BOLD); private static final Logger LOG = Logger.getInstance(HyperlinkLabel.class.getName()); diff --git a/platform/platform-api/src/com/intellij/ui/PathsChooserComponent.java b/platform/platform-api/src/com/intellij/ui/PathsChooserComponent.java index 1ab89834457f..9c6fbe770c6a 100644 --- a/platform/platform-api/src/com/intellij/ui/PathsChooserComponent.java +++ b/platform/platform-api/src/com/intellij/ui/PathsChooserComponent.java @@ -66,15 +66,12 @@ public class PathsChooserComponent implements ComponentWithEmptyText { dirChooser.setShowFileSystemRoots(true); dirChooser.setHideIgnored(true); dirChooser.setTitle(UIBundle.message("file.chooser.default.title")); - FileChooser.chooseFiles(dirChooser, myProject, null, new Consumer>() { - @Override - public void consume(List files) { - for (VirtualFile file : files) { - // adding to the end - final String path = file.getPath(); - if (processor.addPath(myWorkingCollection, path)) { - myListModel.addElement(path); - } + FileChooser.chooseFiles(dirChooser, myProject, null, files -> { + for (VirtualFile file : files) { + // adding to the end + final String path = file.getPath(); + if (processor.addPath(myWorkingCollection, path)) { + myListModel.addElement(path); } } }); diff --git a/platform/platform-api/src/com/intellij/ui/RowsDnDSupport.java b/platform/platform-api/src/com/intellij/ui/RowsDnDSupport.java index 7097b9d961e1..c9f6ec8f08f2 100644 --- a/platform/platform-api/src/com/intellij/ui/RowsDnDSupport.java +++ b/platform/platform-api/src/com/intellij/ui/RowsDnDSupport.java @@ -51,12 +51,9 @@ public class RowsDnDSupport { private static void installImpl(@NotNull final JComponent component, @NotNull final EditableModel model) { component.setTransferHandler(new TransferHandler(null)); DnDSupport.createBuilder(component) - .setBeanProvider(new Function() { - @Override - public DnDDragStartBean fun(DnDActionInfo info) { - final Point p = info.getPoint(); - return new DnDDragStartBean(new RowDragInfo(component, Integer.valueOf(getRow(component, p)))); - } + .setBeanProvider(info -> { + final Point p = info.getPoint(); + return new DnDDragStartBean(new RowDragInfo(component, Integer.valueOf(getRow(component, p)))); }) .setTargetChecker(new DnDTargetChecker() { @Override diff --git a/platform/platform-api/src/com/intellij/ui/SearchTextField.java b/platform/platform-api/src/com/intellij/ui/SearchTextField.java index ad481b02af64..07a4d6db4d71 100644 --- a/platform/platform-api/src/com/intellij/ui/SearchTextField.java +++ b/platform/platform-api/src/com/intellij/ui/SearchTextField.java @@ -416,15 +416,13 @@ public class SearchTextField extends JPanel { } protected Runnable createItemChosenCallback(final JList list) { - return new Runnable() { - public void run() { - final String value = (String)list.getSelectedValue(); - getTextEditor().setText(value != null ? value : ""); - addCurrentTextToHistory(); - if (myPopup != null) { - myPopup.cancel(); - myPopup = null; - } + return () -> { + final String value = (String)list.getSelectedValue(); + getTextEditor().setText(value != null ? value : ""); + addCurrentTextToHistory(); + if (myPopup != null) { + myPopup.cancel(); + myPopup = null; } }; } diff --git a/platform/platform-api/src/com/intellij/ui/TableToolbarDecorator.java b/platform/platform-api/src/com/intellij/ui/TableToolbarDecorator.java index 2f6155cf2b8e..137ae5dc899e 100644 --- a/platform/platform-api/src/com/intellij/ui/TableToolbarDecorator.java +++ b/platform/platform-api/src/com/intellij/ui/TableToolbarDecorator.java @@ -124,15 +124,12 @@ class TableToolbarDecorator extends ToolbarDecorator { TableUtil.updateScroller(table); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final Component editorComponent = table.getEditorComponent(); - if (editorComponent != null) { - final Rectangle bounds = editorComponent.getBounds(); - table.scrollRectToVisible(bounds); - editorComponent.requestFocus(); - } + SwingUtilities.invokeLater(() -> { + final Component editorComponent = table.getEditorComponent(); + if (editorComponent != null) { + final Rectangle bounds = editorComponent.getBounds(); + table.scrollRectToVisible(bounds); + editorComponent.requestFocus(); } }); diff --git a/platform/platform-api/src/com/intellij/ui/ToolbarDecorator.java b/platform/platform-api/src/com/intellij/ui/ToolbarDecorator.java index 79e36f691f19..df7fd1f7e8e1 100644 --- a/platform/platform-api/src/com/intellij/ui/ToolbarDecorator.java +++ b/platform/platform-api/src/com/intellij/ui/ToolbarDecorator.java @@ -169,19 +169,16 @@ public abstract class ToolbarDecorator implements CommonActionsPanel.ListenerFac public ToolbarDecorator setButtonComparator(String...actionNames) { final List names = Arrays.asList(actionNames); - myButtonComparator = new Comparator() { - @Override - public int compare(AnActionButton o1, AnActionButton o2) { - final String t1 = o1.getTemplatePresentation().getText(); - final String t2 = o2.getTemplatePresentation().getText(); - if (t1 == null || t2 == null) return 0; - - final int ind1 = names.indexOf(t1); - final int ind2 = names.indexOf(t2); - if (ind1 == -1 && ind2 >= 0) return 1; - if (ind2 == -1 && ind1 >= 0) return -1; - return ind1 - ind2; - } + myButtonComparator = (o1, o2) -> { + final String t1 = o1.getTemplatePresentation().getText(); + final String t2 = o2.getTemplatePresentation().getText(); + if (t1 == null || t2 == null) return 0; + + final int ind1 = names.indexOf(t1); + final int ind2 = names.indexOf(t2); + if (ind1 == -1 && ind2 >= 0) return 1; + if (ind2 == -1 && ind1 >= 0) return -1; + return ind1 - ind2; }; return this; } diff --git a/platform/platform-api/src/com/intellij/ui/ToolbarDecoratorActionPromoter.java b/platform/platform-api/src/com/intellij/ui/ToolbarDecoratorActionPromoter.java index 45d6795b4c69..2ca53a7d1dd5 100644 --- a/platform/platform-api/src/com/intellij/ui/ToolbarDecoratorActionPromoter.java +++ b/platform/platform-api/src/com/intellij/ui/ToolbarDecoratorActionPromoter.java @@ -28,16 +28,13 @@ import java.util.List; * @author Konstantin Bulenkov */ public class ToolbarDecoratorActionPromoter implements ActionPromoter { - private static final Comparator ACTION_BUTTONS_SORTER = new Comparator() { - @Override - public int compare(AnAction a1, AnAction a2) { - if (a1 instanceof AnActionButton && a2 instanceof AnActionButton) { - final JComponent c1 = ((AnActionButton)a1).getContextComponent(); - final JComponent c2 = ((AnActionButton)a2).getContextComponent(); - return c1.hasFocus() ? -1 : c2.hasFocus() ? 1 : 0; - } - return 0; + private static final Comparator ACTION_BUTTONS_SORTER = (a1, a2) -> { + if (a1 instanceof AnActionButton && a2 instanceof AnActionButton) { + final JComponent c1 = ((AnActionButton)a1).getContextComponent(); + final JComponent c2 = ((AnActionButton)a2).getContextComponent(); + return c1.hasFocus() ? -1 : c2.hasFocus() ? 1 : 0; } + return 0; }; @Override diff --git a/platform/platform-api/src/com/intellij/ui/components/JBList.java b/platform/platform-api/src/com/intellij/ui/components/JBList.java index baea7416a7bb..f0fa98b7daaa 100644 --- a/platform/platform-api/src/com/intellij/ui/components/JBList.java +++ b/platform/platform-api/src/com/intellij/ui/components/JBList.java @@ -139,11 +139,9 @@ public class JBList extends JList implements ComponentWithEmptyText, ComponentWi else { myBusyIcon.suspend(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (myBusyIcon != null) { - repaint(); - } + SwingUtilities.invokeLater(() -> { + if (myBusyIcon != null) { + repaint(); } }); } diff --git a/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java b/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java index 02796df6d1b0..353f11349d8a 100644 --- a/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java +++ b/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java @@ -204,12 +204,7 @@ public class JBOptionButton extends JButton implements MouseMotionListener, Weig if (popup != null && listener.get() != null) { popup.removePopupMenuListener(listener.get()); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPopupIsShowing = false; - } - }); + SwingUtilities.invokeLater(() -> myPopupIsShowing = false); } @Override @@ -219,30 +214,27 @@ public class JBOptionButton extends JButton implements MouseMotionListener, Weig popup.addPopupMenuListener(listener.get()); popup.show(this, 0, y); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (popup == null || !popup.isShowing() || !myPopupIsShowing) return; - - Action selection = actionToSelect; - if (selection == null && myOptions.length > 0 && ensureSelection) { - selection = getAction(); - } + SwingUtilities.invokeLater(() -> { + if (popup == null || !popup.isShowing() || !myPopupIsShowing) return; - if (selection == null) return; - - final MenuElement[] elements = popup.getSubElements(); - for (MenuElement eachElement : elements) { - if (eachElement instanceof JMenuItem) { - JMenuItem eachItem = (JMenuItem)eachElement; - if (selection.equals(eachItem.getAction())) { - final MenuSelectionManager mgr = MenuSelectionManager.defaultManager(); - final MenuElement[] path = new MenuElement[2]; - path[0] = popup; - path[1] = eachItem; - mgr.setSelectedPath(path); - break; - } + Action selection = actionToSelect; + if (selection == null && myOptions.length > 0 && ensureSelection) { + selection = getAction(); + } + + if (selection == null) return; + + final MenuElement[] elements = popup.getSubElements(); + for (MenuElement eachElement : elements) { + if (eachElement instanceof JMenuItem) { + JMenuItem eachItem = (JMenuItem)eachElement; + if (selection.equals(eachItem.getAction())) { + final MenuSelectionManager mgr = MenuSelectionManager.defaultManager(); + final MenuElement[] path = new MenuElement[2]; + path[0] = popup; + path[1] = eachItem; + mgr.setSelectedPath(path); + break; } } } diff --git a/platform/platform-api/src/com/intellij/ui/components/JBSlidingPanel.java b/platform/platform-api/src/com/intellij/ui/components/JBSlidingPanel.java index ceccfa3d9cf2..63035c4fa511 100644 --- a/platform/platform-api/src/com/intellij/ui/components/JBSlidingPanel.java +++ b/platform/platform-api/src/com/intellij/ui/components/JBSlidingPanel.java @@ -57,12 +57,7 @@ public class JBSlidingPanel extends JBPanel { public ActionCallback swipe(String id, JBCardLayout.SwipeDirection direction) { final ActionCallback done = new ActionCallback(); - getLayout().swipe(this, id, direction, new Runnable() { - @Override - public void run() { - done.setDone(); - } - }); + getLayout().swipe(this, id, direction, () -> done.setDone()); return done; } @@ -76,12 +71,7 @@ public class JBSlidingPanel extends JBPanel { private ActionCallback applySlide(JBCardLayout.SwipeDirection direction) { final ActionCallback callback = new ActionCallback(); - getLayout().swipe(this, mySlides.get(mySelectedIndex).first, direction, new Runnable() { - @Override - public void run() { - callback.setDone(); - } - }); + getLayout().swipe(this, mySlides.get(mySelectedIndex).first, direction, () -> callback.setDone()); return callback; } diff --git a/platform/platform-api/src/com/intellij/ui/components/MacScrollBarUI.java b/platform/platform-api/src/com/intellij/ui/components/MacScrollBarUI.java index 64af0286464e..9d5018f53004 100644 --- a/platform/platform-api/src/com/intellij/ui/components/MacScrollBarUI.java +++ b/platform/platform-api/src/com/intellij/ui/components/MacScrollBarUI.java @@ -117,12 +117,7 @@ final class MacScrollBarUI extends DefaultScrollBarUI { myThumbAnimator.rewind(true); myAlarm.cancelAllRequests(); if (!myTrackHovered) { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myThumbAnimator.start(false); - } - }, 700); + myAlarm.addRequest(() -> myThumbAnimator.start(false), 700); } } } @@ -259,20 +254,14 @@ final class MacScrollBarUI extends DefaultScrollBarUI { return 1 == behavior.intValue() ? JumpToSpot : NextPage; } }; - private static final Producer INIT = new Producer() { - @Nullable - @Override - public ID produce() { - return invoke(invoke("NSDistributedNotificationCenter", "defaultCenter"), - "addObserver:selector:name:object:", - createDelegate("JBScrollBarBehaviorObserver", createSelector("handleBehaviorChanged:"), CURRENT), - createSelector("handleBehaviorChanged:"), - nsString("AppleNoRedisplayAppearancePreferenceChanged"), - ID.NIL, - 2 // NSNotificationSuspensionBehaviorCoalesce - ); - } - }; + private static final Producer INIT = () -> invoke(invoke("NSDistributedNotificationCenter", "defaultCenter"), + "addObserver:selector:name:object:", + createDelegate("JBScrollBarBehaviorObserver", createSelector("handleBehaviorChanged:"), CURRENT), + createSelector("handleBehaviorChanged:"), + nsString("AppleNoRedisplayAppearancePreferenceChanged"), + ID.NIL, + 2 // NSNotificationSuspensionBehaviorCoalesce + ); } private enum Style { @@ -300,19 +289,13 @@ final class MacScrollBarUI extends DefaultScrollBarUI { return 1 == style.intValue() ? Overlay : Legacy; } }; - private static final Producer INIT = new Producer() { - @Nullable - @Override - public ID produce() { - return invoke(invoke("NSNotificationCenter", "defaultCenter"), - "addObserver:selector:name:object:", - createDelegate("JBScrollBarStyleObserver", createSelector("handleScrollerStyleChanged:"), CURRENT), - createSelector("handleScrollerStyleChanged:"), - nsString("NSPreferredScrollerStyleDidChangeNotification"), - ID.NIL - ); - } - }; + private static final Producer INIT = () -> invoke(invoke("NSNotificationCenter", "defaultCenter"), + "addObserver:selector:name:object:", + createDelegate("JBScrollBarStyleObserver", createSelector("handleScrollerStyleChanged:"), CURRENT), + createSelector("handleScrollerStyleChanged:"), + nsString("NSPreferredScrollerStyleDidChangeNotification"), + ID.NIL + ); } private static abstract class Native implements Callback, Runnable, Producer { diff --git a/platform/platform-api/src/com/intellij/ui/components/editors/JBComboBoxTableCellEditorComponent.java b/platform/platform-api/src/com/intellij/ui/components/editors/JBComboBoxTableCellEditorComponent.java index 82b49fa96c8a..c324c048a03e 100644 --- a/platform/platform-api/src/com/intellij/ui/components/editors/JBComboBoxTableCellEditorComponent.java +++ b/platform/platform-api/src/com/intellij/ui/components/editors/JBComboBoxTableCellEditorComponent.java @@ -149,19 +149,16 @@ public class JBComboBoxTableCellEditorComponent extends JBLabel { final boolean surrendersFocusOnKeystrokeOldValue = myTable instanceof JBTable ? ((JBTable)myTable).surrendersFocusOnKeyStroke() : myTable.getSurrendersFocusOnKeystroke(); final JBPopup popup = JBPopupFactory.getInstance() .createListPopupBuilder(myList) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - myValue = myList.getSelectedValue(); - final ActionEvent event = new ActionEvent(myList, ActionEvent.ACTION_PERFORMED, "elementChosen"); - for (ActionListener listener : myListeners) { - listener.actionPerformed(event); - } - TableUtil.stopEditing(myTable); - - myTable.setValueAt(myValue, myRow, myColumn); // on Mac getCellEditorValue() called before myValue is set. - myTable.tableChanged(new TableModelEvent(myTable.getModel(), myRow)); // force repaint + .setItemChoosenCallback(() -> { + myValue = myList.getSelectedValue(); + final ActionEvent event = new ActionEvent(myList, ActionEvent.ACTION_PERFORMED, "elementChosen"); + for (ActionListener listener : myListeners) { + listener.actionPerformed(event); } + TableUtil.stopEditing(myTable); + + myTable.setValueAt(myValue, myRow, myColumn); // on Mac getCellEditorValue() called before myValue is set. + myTable.tableChanged(new TableModelEvent(myTable.getModel(), myRow)); // force repaint }) .setCancelCallback(new Computable() { @Override diff --git a/platform/platform-api/src/com/intellij/ui/messager/CalloutComponent.java b/platform/platform-api/src/com/intellij/ui/messager/CalloutComponent.java index 7ba868294b3e..d6684b3d9bf3 100644 --- a/platform/platform-api/src/com/intellij/ui/messager/CalloutComponent.java +++ b/platform/platform-api/src/com/intellij/ui/messager/CalloutComponent.java @@ -186,11 +186,9 @@ public class CalloutComponent { myFrame.setBounds(frameBounds); myFrame.setVisible(true); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - installDisposeListeners(); - myFrame.setVisible(true); - } + SwingUtilities.invokeLater(() -> { + installDisposeListeners(); + myFrame.setVisible(true); }); } @@ -206,11 +204,9 @@ public class CalloutComponent { } private void installDisposeListeners() { - myKeyEventDispatcher = new KeyEventDispatcher() { - public boolean dispatchKeyEvent(KeyEvent e) { - dispose(); - return false; - } + myKeyEventDispatcher = e -> { + dispose(); + return false; }; myKeyboardFocusManager.addKeyEventDispatcher(myKeyEventDispatcher); @@ -284,23 +280,21 @@ public class CalloutComponent { private void dispose() { - Runnable runnable = new Runnable() { - public void run() { - myFrame.dispose(); + Runnable runnable = () -> { + myFrame.dispose(); - Toolkit.getDefaultToolkit().removeAWTEventListener(myMulticastListener); - myKeyboardFocusManager.removeKeyEventDispatcher(myKeyEventDispatcher); + Toolkit.getDefaultToolkit().removeAWTEventListener(myMulticastListener); + myKeyboardFocusManager.removeKeyEventDispatcher(myKeyEventDispatcher); - myTargetComponent.removeComponentListener(myComponentListener); - myTargetWindow.removeWindowListener(myWindowListener); - myTargetWindow.removeWindowStateListener(myWindowStateListener); + myTargetComponent.removeComponentListener(myComponentListener); + myTargetWindow.removeWindowListener(myWindowListener); + myTargetWindow.removeWindowStateListener(myWindowStateListener); - final Container parent = myPointerComponent.getParent(); - final Rectangle bounds = myPointerComponent.getBounds(); - if (parent != null) { - parent.remove(myPointerComponent); - parent.repaint(bounds.x, bounds.y, bounds.width, bounds.height); - } + final Container parent = myPointerComponent.getParent(); + final Rectangle bounds = myPointerComponent.getBounds(); + if (parent != null) { + parent.remove(myPointerComponent); + parent.repaint(bounds.x, bounds.y, bounds.width, bounds.height); } }; diff --git a/platform/platform-api/src/com/intellij/ui/navigation/History.java b/platform/platform-api/src/com/intellij/ui/navigation/History.java index 672424d62c68..95b19f916d2e 100644 --- a/platform/platform-api/src/com/intellij/ui/navigation/History.java +++ b/platform/platform-api/src/com/intellij/ui/navigation/History.java @@ -104,17 +104,9 @@ public final class History { fireStarted(from, next); try { final ActionCallback callback = myRoot.navigateTo(next, false); - callback.doWhenDone(new Runnable() { - @Override - public void run() { - myCurrentPos = nextPos; - } - }).doWhenProcessed(new Runnable() { - @Override - public void run() { - myNavigatedNow = false; - fireFinished(from, next); - } + callback.doWhenDone(() -> myCurrentPos = nextPos).doWhenProcessed(() -> { + myNavigatedNow = false; + fireFinished(from, next); }); } catch (Throwable e) { diff --git a/platform/platform-api/src/com/intellij/ui/speedSearch/SpeedSearchUtil.java b/platform/platform-api/src/com/intellij/ui/speedSearch/SpeedSearchUtil.java index f751039f268a..a3f052882620 100644 --- a/platform/platform-api/src/com/intellij/ui/speedSearch/SpeedSearchUtil.java +++ b/platform/platform-api/src/com/intellij/ui/speedSearch/SpeedSearchUtil.java @@ -139,17 +139,14 @@ public final class SpeedSearchUtil { } final int[] lastOffset = {0}; - ContainerUtil.process(searchTerms, new Processor>() { - @Override - public boolean process(Pair pair) { - if (pair.second > lastOffset[0]) { - simpleColoredComponent.append(text.substring(lastOffset[0], pair.second), plain); - } - - simpleColoredComponent.append(text.substring(pair.second, pair.second + pair.first.length()), highlighted); - lastOffset[0] = pair.second + pair.first.length(); - return true; + ContainerUtil.process(searchTerms, pair -> { + if (pair.second > lastOffset[0]) { + simpleColoredComponent.append(text.substring(lastOffset[0], pair.second), plain); } + + simpleColoredComponent.append(text.substring(pair.second, pair.second + pair.first.length()), highlighted); + lastOffset[0] = pair.second + pair.first.length(); + return true; }); if (lastOffset[0] < text.length()) { diff --git a/platform/platform-api/src/com/intellij/ui/switcher/QuickActionManager.java b/platform/platform-api/src/com/intellij/ui/switcher/QuickActionManager.java index bcc0c719c30d..4bbfabea79ac 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/QuickActionManager.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/QuickActionManager.java @@ -94,11 +94,8 @@ public class QuickActionManager implements ProjectComponent { } JBPopupFactory.getInstance() - .createActionGroupPopup(null, group, context, JBPopupFactory.ActionSelectionAid.ALPHA_NUMBERING, true, new Runnable() { - public void run() { - myActiveProvider = null; - } - }, -1).showInFocusCenter(); + .createActionGroupPopup(null, group, context, JBPopupFactory.ActionSelectionAid.ALPHA_NUMBERING, true, + () -> myActiveProvider = null, -1).showInFocusCenter(); } } }); diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java index 7a5c24ab9e7b..3ea0fd009bb8 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java @@ -70,19 +70,11 @@ public class SwitchManager { if (areAllModifiersPressed(e.getModifiers(), myQa.getModiferCodes())) { myWaitingForAutoInitSession = true; myAutoInitSessionEvent = e; - Runnable initRunnable = new Runnable() { - @Override - public void run() { - IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - if (myWaitingForAutoInitSession) { - tryToInitSessionFromFocus(null, false); - } - } - }); + Runnable initRunnable = () -> IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(() -> { + if (myWaitingForAutoInitSession) { + tryToInitSessionFromFocus(null, false); } - }; + }); if (myFadingAway.isEmpty()) { myInitSessionAlarm.addRequest(initRunnable, Registry.intValue("actionSystem.keyGestureHoldTime")); } @@ -176,12 +168,8 @@ public class SwitchManager { @Override public void consume(final SwitchTarget switchTarget) { mySession = null; - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - tryToInitSessionFromFocus(switchTarget, showSpots).doWhenProcessed(result.createSetDoneRunnable()); - } - }); + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown( + () -> tryToInitSessionFromFocus(switchTarget, showSpots).doWhenProcessed(result.createSetDoneRunnable())); } }); } diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java index b8a6801b2ef6..7742fdf5daf3 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java @@ -425,12 +425,7 @@ public class SwitchingSession implements KeyEventDispatcher, Disposable { if (myFadingAway) { myManager.addFadingAway(this); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - _dispose(); - } - }, Registry.intValue("actionSystem.keyGestureDblClickTime")); + myAlarm.addRequest(() -> _dispose(), Registry.intValue("actionSystem.keyGestureDblClickTime")); } else { _dispose(); } @@ -449,11 +444,9 @@ public class SwitchingSession implements KeyEventDispatcher, Disposable { final AsyncResult result = new AsyncResult(); final SwitchTarget selection = getSelection(); if (selection != null) { - selection.switchTo(true).doWhenDone(new Runnable() { - public void run() { - myManager.disposeCurrentSession(fadeAway); - result.setDone(selection); - } + selection.switchTo(true).doWhenDone(() -> { + myManager.disposeCurrentSession(fadeAway); + result.setDone(selection); }).notifyWhenRejected(result); } else { Disposer.dispose(this); diff --git a/platform/platform-api/src/com/intellij/ui/table/JBTable.java b/platform/platform-api/src/com/intellij/ui/table/JBTable.java index d92404c065be..e5677e2206a7 100644 --- a/platform/platform-api/src/com/intellij/ui/table/JBTable.java +++ b/platform/platform-api/src/com/intellij/ui/table/JBTable.java @@ -381,12 +381,9 @@ public class JBTable extends JTable implements ComponentWithEmptyText, Component else { myBusyIcon.suspend(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myBusyIcon != null) { - repaint(); - } + SwingUtilities.invokeLater(() -> { + if (myBusyIcon != null) { + repaint(); } }); } @@ -454,12 +451,7 @@ public class JBTable extends JTable implements ComponentWithEmptyText, Component // this replaces focus request in JTable.processKeyBinding final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(this); focusManager.setTypeaheadEnabled(false); - focusManager.requestFocus(editorComp, true).doWhenProcessed(new Runnable() { - @Override - public void run() { - focusManager.setTypeaheadEnabled(true); - } - }); + focusManager.requestFocus(editorComp, true).doWhenProcessed(() -> focusManager.setTypeaheadEnabled(true)); } setCellEditor(editor); @@ -809,12 +801,7 @@ public class JBTable extends JTable implements ComponentWithEmptyText, Component tableSize.width += newWidth - column.getWidth(); JBTable.this.setSize(tableSize); // let the table update it's layout with resizing column set - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - setResizingColumn(null); - } - }); + ApplicationManager.getApplication().invokeLater(() -> setResizingColumn(null)); } private int getColumnToPack(Point p) { diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabs.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabs.java index 031deb482370..3f74c6cdeab6 100644 --- a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabs.java +++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabs.java @@ -53,12 +53,9 @@ public class JBEditorTabs extends JBTabsImpl { @Override public void afterValueChanged(RegistryValue value) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - resetTabsCache(); - relayout(true, false); - } + ApplicationManager.getApplication().invokeLater(() -> { + resetTabsCache(); + relayout(true, false); }); } }, parent); diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java index 82fd5560b77c..7fc9b900fa86 100644 --- a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java +++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java @@ -72,12 +72,7 @@ public class JBTabsImpl extends JComponent public static final int DEFAULT_MAX_TAB_WIDTH = JBUI.scale(300); public static final Color MAC_AQUA_BG_COLOR = Gray._200; - private static final Comparator ABC_COMPARATOR = new Comparator() { - @Override - public int compare(TabInfo o1, TabInfo o2) { - return StringUtil.naturalCompare(o1.getText(), o2.getText()); - } - }; + private static final Comparator ABC_COMPARATOR = (o1, o2) -> StringUtil.naturalCompare(o1.getText(), o2.getText()); @NotNull final ActionManager myActionManager; private final List myVisibleInfos = new ArrayList(); @@ -349,12 +344,7 @@ public class JBTabsImpl extends JComponent @Override public Iterator iterator() { return JBIterable.from(getVisibleInfos()).filter(Conditions.not(Conditions.is(mySelectedInfo))).transform( - new Function() { - @Override - public JComponent fun(TabInfo info) { - return info.getComponent(); - } - }).iterator(); + info -> info.getComponent()).iterator(); } }); } @@ -923,15 +913,12 @@ public class JBTabsImpl extends JComponent final JComponent toFocus = getToFocus(); if (myProject != null && toFocus != null) { final ActionCallback result = new ActionCallback(); - requestFocus(toFocus).doWhenProcessed(new Runnable() { - @Override - public void run() { - if (myDisposed) { - result.setRejected(); - } - else { - removeDeferred().notifyWhenDone(result); - } + requestFocus(toFocus).doWhenProcessed(() -> { + if (myDisposed) { + result.setRejected(); + } + else { + removeDeferred().notifyWhenDone(result); } }); return result; @@ -1012,12 +999,9 @@ public class JBTabsImpl extends JComponent } } }); - myDeferredFocusRequest = new Runnable() { - @Override - public void run() { - queued.set(true); - requestor.requestFocus(new FocusCommand.ByComponent(toFocus, new Exception()), true).notify(result); - } + myDeferredFocusRequest = () -> { + queued.set(true); + requestor.requestFocus(new FocusCommand.ByComponent(toFocus, new Exception()), true).notify(result); }; return result; } @@ -1032,15 +1016,12 @@ public class JBTabsImpl extends JComponent final long executionRequest = ++myRemoveDeferredRequest; - final Runnable onDone = new Runnable() { - @Override - public void run() { - if (myRemoveDeferredRequest == executionRequest) { - removeDeferredNow(); - } - - callback.setDone(); + final Runnable onDone = () -> { + if (myRemoveDeferredRequest == executionRequest) { + removeDeferredNow(); } + + callback.setDone(); }; myFocusManager.doWhenFocusSettlesDown(onDone); @@ -1404,12 +1385,7 @@ public class JBTabsImpl extends JComponent private void resetPopup() { //todo [kirillk] dirty hack, should rely on ActionManager to understand that menu item was either chosen on or cancelled - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myPopupInfo = null; - } - }); + SwingUtilities.invokeLater(() -> myPopupInfo = null); } @Override @@ -2395,12 +2371,7 @@ public class JBTabsImpl extends JComponent return computeSizeBySelected(true); } - return computeSize(new Function() { - @Override - public Dimension fun(JComponent component) { - return component.getMinimumSize(); - } - }, 1); + return computeSize(component -> component.getMinimumSize(), 1); } @Override @@ -2409,12 +2380,7 @@ public class JBTabsImpl extends JComponent return computeSizeBySelected(false); } - return computeSize(new Function() { - @Override - public Dimension fun(JComponent component) { - return component.getPreferredSize(); - } - }, 3); + return computeSize(component -> component.getPreferredSize(), 3); } @NotNull @@ -2567,12 +2533,7 @@ public class JBTabsImpl extends JComponent if (clearSelection) { mySelectedInfo = info; } - _setSelected(toSelect, transferFocus).doWhenProcessed(new Runnable() { - @Override - public void run() { - removeDeferred().notifyWhenDone(result); - } - }); + _setSelected(toSelect, transferFocus).doWhenProcessed(() -> removeDeferred().notifyWhenDone(result)); } else { processRemove(info, true); @@ -3131,13 +3092,10 @@ public class JBTabsImpl extends JComponent @Override public void updateUI() { super.updateUI(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - applyDecoration(); + SwingUtilities.invokeLater(() -> { + applyDecoration(); - revalidateAndRepaint(false); - } + revalidateAndRepaint(false); }); } diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/TabLabel.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/TabLabel.java index ce89193e5eb9..b37dd2f82601 100644 --- a/platform/platform-api/src/com/intellij/ui/tabs/impl/TabLabel.java +++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/TabLabel.java @@ -258,12 +258,7 @@ public class TabLabel extends JPanel implements Accessible { } private void doPaint(final Graphics g) { - doTranslate(new PairConsumer() { - @Override - public void consume(Integer x, Integer y) { - g.translate(x, y); - } - }); + doTranslate((x, y) -> g.translate(x, y)); final Composite oldComposite = ((Graphics2D)g).getComposite(); //if (myTabs instanceof JBEditorTabs && !myTabs.isSingleRow() && myTabs.getSelectedInfo() != myInfo) { @@ -272,12 +267,7 @@ public class TabLabel extends JPanel implements Accessible { super.paint(g); ((Graphics2D)g).setComposite(oldComposite); - doTranslate(new PairConsumer() { - @Override - public void consume(Integer x, Integer y) { - g.translate(-x, -y); - } - }); + doTranslate((x2, y2) -> g.translate(-x2, -y2)); } protected int getNonSelectedOffset() { @@ -347,15 +337,13 @@ public class TabLabel extends JPanel implements Accessible { public void setText(final SimpleColoredText text) { - myLabel.change(new Runnable() { - public void run() { - myLabel.clear(); - myLabel.setIcon(hasIcons() ? myIcon : null); + myLabel.change(() -> { + myLabel.clear(); + myLabel.setIcon(hasIcons() ? myIcon : null); - if (text != null) { - SimpleColoredText derive = myTabs.useBoldLabels() ? text.derive(SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES, true) : text; - derive.appendToComponent(myLabel); - } + if (text != null) { + SimpleColoredText derive = myTabs.useBoldLabels() ? text.derive(SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES, true) : text; + derive.appendToComponent(myLabel); } }, false); diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/singleRow/SingleRowLayout.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/singleRow/SingleRowLayout.java index 2f130a7095cd..f57e6dc7ce59 100644 --- a/platform/platform-api/src/com/intellij/ui/tabs/impl/singleRow/SingleRowLayout.java +++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/singleRow/SingleRowLayout.java @@ -370,11 +370,7 @@ public class SingleRowLayout extends TabLayout { public void mousePressed(final MouseEvent e) { if (JBTabsImpl.isSelectionClick(e, true) && myInfo != null) { myRowDropPolicy = before; - myTabs.select(myInfo, true).doWhenDone(new Runnable() { - public void run() { - myRowDropPolicy = after; - } - }); + myTabs.select(myInfo, true).doWhenDone(() -> myRowDropPolicy = after); } else { MouseEvent event = SwingUtilities.convertMouseEvent(e.getComponent(), e, myTabs); myTabs.processMouseEvent(event); diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTree.java b/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTree.java index 4ce2384597ae..43c997e4d78e 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTree.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTree.java @@ -330,11 +330,7 @@ public class SimpleTree extends Tree implements CellEditorListener { myEditorComponent.requestFocusInWindow(); } - SwingUtilities.invokeLater(new Runnable() { - public void run() { - scrollPathToVisible(path); - } - }); + SwingUtilities.invokeLater(() -> scrollPathToVisible(path)); } } @@ -400,11 +396,7 @@ public class SimpleTree extends Tree implements CellEditorListener { } private void handleDoubleClickOrEnter(final TreePath treePath, final InputEvent e) { - Runnable runnable = new Runnable() { - public void run() { - getNodeFor(treePath).handleDoubleClickOrEnter(SimpleTree.this, e); - } - }; + Runnable runnable = () -> getNodeFor(treePath).handleDoubleClickOrEnter(SimpleTree.this, e); ApplicationManager.getApplication().invokeLater(runnable, ModalityState.stateForComponent(this)); } @@ -418,11 +410,9 @@ public class SimpleTree extends Tree implements CellEditorListener { } protected void invokeContextMenu(final MouseEvent e) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu(myPlace, myPopupGroup); - menu.getComponent().show(e.getComponent(), e.getPoint().x, e.getPoint().y); - } + SwingUtilities.invokeLater(() -> { + final ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu(myPlace, myPopupGroup); + menu.getComponent().show(e.getComponent(), e.getPoint().x, e.getPoint().y); }); } diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTreeBuilder.java b/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTreeBuilder.java index c584835fe11c..65ebad9e4abf 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/SimpleTreeBuilder.java @@ -57,12 +57,9 @@ public class SimpleTreeBuilder extends AbstractTreeBuilder { SimpleTreeBuilder.super.queueUpdate(); } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!isDisposed()) { - SimpleTreeBuilder.super.queueUpdate(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!isDisposed()) { + SimpleTreeBuilder.super.queueUpdate(); } }); } diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java b/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java index 28aa4733903c..2a6078aea2db 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java @@ -283,12 +283,9 @@ public class Tree extends JTree implements ComponentWithEmptyText, ComponentWith myBusyIcon.suspend(); myBusyIcon.setToolTipText(null); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myBusyIcon != null) { - repaint(); - } + SwingUtilities.invokeLater(() -> { + if (myBusyIcon != null) { + repaint(); } }); } diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeBuilder.java b/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeBuilder.java index ec381a374d1b..961c864b3291 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeBuilder.java @@ -164,36 +164,30 @@ public class FilteringTreeBuilder extends AbstractTreeBuilder { getFilteredStructure().refilter(); getUi().updateSubtree(getRootNode(), false); - final Runnable selectionRunnable = new Runnable() { - @Override - public void run() { - revalidateTree(); + final Runnable selectionRunnable = () -> { + revalidateTree(); - Object toSelect = preferredSelection != null ? preferredSelection : myLastSuccessfulSelect; + Object toSelect = preferredSelection != null ? preferredSelection : myLastSuccessfulSelect; - if (adjustSelection && toSelect != null) { - final FilteringTreeStructure.FilteringNode nodeToSelect = getFilteredStructure().getVisibleNodeFor(toSelect); + if (adjustSelection && toSelect != null) { + final FilteringTreeStructure.FilteringNode nodeToSelect = getFilteredStructure().getVisibleNodeFor(toSelect); - if (nodeToSelect != null) { - select(nodeToSelect, new Runnable() { - @Override - public void run() { - if (getSelectedElements().contains(nodeToSelect)) { - myLastSuccessfulSelect = getOriginalNode(nodeToSelect); - } - selectionDone.setDone(); - } - }); - } - else { - TreeUtil.ensureSelection(myTree); + if (nodeToSelect != null) { + select(nodeToSelect, () -> { + if (getSelectedElements().contains(nodeToSelect)) { + myLastSuccessfulSelect = getOriginalNode(nodeToSelect); + } selectionDone.setDone(); - } + }); } else { + TreeUtil.ensureSelection(myTree); selectionDone.setDone(); } } + else { + selectionDone.setDone(); + } }; if (!ApplicationManager.getApplication().isUnitTestMode()) { queueUpdate().doWhenProcessed(selectionRunnable); diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeStructure.java b/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeStructure.java index 96a922e9a26e..e2b13169f913 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeStructure.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/filtered/FilteringTreeStructure.java @@ -242,12 +242,8 @@ public class FilteringTreeStructure extends AbstractTreeStructure { public SimpleNode[] getChildren() { List nodes = myNodesCache.get(this); if (nodes == null) { - return myDelegate instanceof SimpleNode ? ContainerUtil.map(((SimpleNode)myDelegate).getChildren(), new Function() { - @Override - public SimpleNode fun(SimpleNode node) { - return new FilteringNode(FilteringNode.this, node); - } - }, NO_CHILDREN) : NO_CHILDREN; + return myDelegate instanceof SimpleNode ? ContainerUtil.map(((SimpleNode)myDelegate).getChildren(), + node -> new FilteringNode(FilteringNode.this, node), NO_CHILDREN) : NO_CHILDREN; } ArrayList result = new ArrayList(); diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/treetable/TreeTableModelAdapter.java b/platform/platform-api/src/com/intellij/ui/treeStructure/treetable/TreeTableModelAdapter.java index 32897d722dad..cbca7f173ad9 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/treetable/TreeTableModelAdapter.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/treetable/TreeTableModelAdapter.java @@ -123,11 +123,7 @@ public class TreeTableModelAdapter extends AbstractTableModel { * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - fireTableDataChanged(); - } - }); + SwingUtilities.invokeLater(() -> fireTableDataChanged()); } public void fireTableDataChanged() { diff --git a/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessorRemovePartner.java b/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessorRemovePartner.java index 9cecc5dd14ad..d5ce4c9ccf74 100644 --- a/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessorRemovePartner.java +++ b/platform/platform-api/src/com/intellij/util/concurrency/QueueProcessorRemovePartner.java @@ -36,16 +36,13 @@ public class QueueProcessorRemovePartner { myConsumer = consumer; myMap = new HashMap(); myLock = new Object(); - myProcessor = new QueueProcessor(new Consumer() { - @Override - public void consume(Key key) { - final Task task; - synchronized (myLock) { - task = myMap.remove(key); - } - if (task != null) { - myConsumer.consume(task); - } + myProcessor = new QueueProcessor(key -> { + final Task task; + synchronized (myLock) { + task = myMap.remove(key); + } + if (task != null) { + myConsumer.consume(task); } }, project.getDisposed(), true); } diff --git a/platform/platform-api/src/com/intellij/util/concurrency/SwingWorker.java b/platform/platform-api/src/com/intellij/util/concurrency/SwingWorker.java index 47a5de7ba487..358586a11698 100644 --- a/platform/platform-api/src/com/intellij/util/concurrency/SwingWorker.java +++ b/platform/platform-api/src/com/intellij/util/concurrency/SwingWorker.java @@ -143,11 +143,7 @@ public abstract class SwingWorker { public SwingWorker() { myModalityState = ModalityState.current(); - final Runnable doFinished = new Runnable() { - public void run() { - finished(); - } - }; + final Runnable doFinished = () -> finished(); Runnable doConstruct = new Runnable() { public void run() { diff --git a/platform/platform-api/src/com/intellij/util/config/AbstractProperty.java b/platform/platform-api/src/com/intellij/util/config/AbstractProperty.java index 97b6e4d882c6..61272dc158f0 100644 --- a/platform/platform-api/src/com/intellij/util/config/AbstractProperty.java +++ b/platform/platform-api/src/com/intellij/util/config/AbstractProperty.java @@ -21,11 +21,8 @@ import org.jetbrains.annotations.NonNls; import java.util.Comparator; public abstract class AbstractProperty { - public static final Comparator NAME_COMPARATOR = new Comparator() { - public int compare(AbstractProperty property, AbstractProperty property1) { - return property.getName().compareTo(property1.getName()); - } - }; + public static final Comparator NAME_COMPARATOR = + (property, property1) -> property.getName().compareTo(property1.getName()); @NonNls public abstract String getName(); diff --git a/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java b/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java index c5e28131e8b4..3de4fe9a9ccc 100644 --- a/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java +++ b/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java @@ -256,31 +256,28 @@ public class HttpConfigurable implements PersistentStateComponent value = Ref.create(); - runAboveAll(new Runnable() { - @Override - public void run() { - if (isGenericPasswordCanceled(host, port)) { - return; - } + runAboveAll(() -> { + if (isGenericPasswordCanceled(host, port)) { + return; + } - PasswordAuthentication password = getGenericPassword(host, port); - if (password != null) { - value.set(password); - return; - } + PasswordAuthentication password = getGenericPassword(host, port); + if (password != null) { + value.set(password); + return; + } - AuthenticationDialog dialog = new AuthenticationDialog(PopupUtil.getActiveComponent(), prefix + host, - "Please enter credentials for: " + prompt, "", "", remember); - dialog.show(); - if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { - AuthenticationPanel panel = dialog.getPanel(); - PasswordAuthentication passwordAuthentication = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); - putGenericPassword(host, port, passwordAuthentication, remember && panel.isRememberPassword()); - value.set(passwordAuthentication); - } - else { - setGenericPasswordCanceled(host, port); - } + AuthenticationDialog dialog = new AuthenticationDialog(PopupUtil.getActiveComponent(), prefix + host, + "Please enter credentials for: " + prompt, "", "", remember); + dialog.show(); + if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { + AuthenticationPanel panel = dialog.getPanel(); + PasswordAuthentication passwordAuthentication = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); + putGenericPassword(host, port, passwordAuthentication, remember && panel.isRememberPassword()); + value.set(passwordAuthentication); + } + else { + setGenericPasswordCanceled(host, port); } }); return value.get(); @@ -303,32 +300,29 @@ public class HttpConfigurable implements PersistentStateComponent { + if (AUTHENTICATION_CANCELLED) { + return; + } - // password might have changed, and the check below is for that - String password = getPlainProxyPassword(); - if (PROXY_AUTHENTICATION && ! StringUtil.isEmptyOrSpaces(PROXY_LOGIN) && ! StringUtil.isEmptyOrSpaces(password)) { - value[0] = new PasswordAuthentication(PROXY_LOGIN, password.toCharArray()); - return; - } - AuthenticationDialog dialog = new AuthenticationDialog(PopupUtil.getActiveComponent(), "Proxy authentication: " + host, - "Please enter credentials for: " + prompt, PROXY_LOGIN, "", KEEP_PROXY_PASSWORD); - dialog.show(); - if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { - PROXY_AUTHENTICATION = true; - AuthenticationPanel panel = dialog.getPanel(); - KEEP_PROXY_PASSWORD = panel.isRememberPassword(); - PROXY_LOGIN = StringUtil.nullize(panel.getLogin()); - setPlainProxyPassword(String.valueOf(panel.getPassword())); - value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); - } else { - AUTHENTICATION_CANCELLED = true; - } + // password might have changed, and the check below is for that + String password1 = getPlainProxyPassword(); + if (PROXY_AUTHENTICATION && ! StringUtil.isEmptyOrSpaces(PROXY_LOGIN) && ! StringUtil.isEmptyOrSpaces(password1)) { + value[0] = new PasswordAuthentication(PROXY_LOGIN, password1.toCharArray()); + return; + } + AuthenticationDialog dialog = new AuthenticationDialog(PopupUtil.getActiveComponent(), "Proxy authentication: " + host, + "Please enter credentials for: " + prompt, PROXY_LOGIN, "", KEEP_PROXY_PASSWORD); + dialog.show(); + if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { + PROXY_AUTHENTICATION = true; + AuthenticationPanel panel = dialog.getPanel(); + KEEP_PROXY_PASSWORD = panel.isRememberPassword(); + PROXY_LOGIN = StringUtil.nullize(panel.getLogin()); + setPlainProxyPassword(String.valueOf(panel.getPassword())); + value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword()); + } else { + AUTHENTICATION_CANCELLED = true; } }); return value[0]; @@ -356,17 +350,14 @@ public class HttpConfigurable implements PersistentStateComponent { + IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); + if (frame != null) { + USE_PROXY_PAC = false; + Messages.showMessageDialog(frame.getComponent(), "Proxy: both 'use proxy' and 'autodetect proxy' settings were set." + + "\nOnly one of these options should be selected.\nPlease re-configure.", + "Proxy Setup", Messages.getWarningIcon()); + editConfigurable(frame.getComponent()); } }, ModalityState.NON_MODAL); } diff --git a/platform/platform-api/src/com/intellij/util/net/HttpProxySettingsUi.java b/platform/platform-api/src/com/intellij/util/net/HttpProxySettingsUi.java index 7cf912f1daeb..c252ed7a52fc 100644 --- a/platform/platform-api/src/com/intellij/util/net/HttpProxySettingsUi.java +++ b/platform/platform-api/src/com/intellij/util/net/HttpProxySettingsUi.java @@ -169,54 +169,48 @@ class HttpProxySettingsUi implements ConfigurableUi { myCheckButton.setEnabled(false); myCheckButton.setText("Check connection (in progress...)"); myConnectionCheckInProgress = true; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - //already checked for null above - //noinspection ConstantConditions - HttpRequests.request(answer) - .readTimeout(3 * 1000) - .tryConnect(); - } - catch (IOException e) { - exceptionReference.set(e); - } - - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myConnectionCheckInProgress = false; - reset(settings); // since password might have been set - Component parent; - if (myMainPanel.isShowing()) { - parent = myMainPanel; - myCheckButton.setText("Check connection"); - myCheckButton.setEnabled(canEnableConnectionCheck()); - } - else { - IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); - if (frame == null) { - return; - } - parent = frame.getComponent(); - } - //noinspection ThrowableResultOfMethodCallIgnored - final IOException exception = exceptionReference.get(); - if (exception == null) { - Messages.showMessageDialog(parent, "Connection successful", title, Messages.getInformationIcon()); - } - else { - final String message = exception.getMessage(); - if (settings.USE_HTTP_PROXY) { - settings.LAST_ERROR = message; - } - Messages.showErrorDialog(parent, errorText(message)); - } - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + //already checked for null above + //noinspection ConstantConditions + HttpRequests.request(answer) + .readTimeout(3 * 1000) + .tryConnect(); } + catch (IOException e1) { + exceptionReference.set(e1); + } + + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + myConnectionCheckInProgress = false; + reset(settings); // since password might have been set + Component parent; + if (myMainPanel.isShowing()) { + parent = myMainPanel; + myCheckButton.setText("Check connection"); + myCheckButton.setEnabled(canEnableConnectionCheck()); + } + else { + IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame(); + if (frame == null) { + return; + } + parent = frame.getComponent(); + } + //noinspection ThrowableResultOfMethodCallIgnored + final IOException exception = exceptionReference.get(); + if (exception == null) { + Messages.showMessageDialog(parent, "Connection successful", title, Messages.getInformationIcon()); + } + else { + final String message = exception.getMessage(); + if (settings.USE_HTTP_PROXY) { + settings.LAST_ERROR = message; + } + Messages.showErrorDialog(parent, errorText(message)); + } + }); }); } }); diff --git a/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java b/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java index d5532b4f284d..2bcf191f1779 100644 --- a/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java +++ b/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java @@ -77,13 +77,10 @@ public class IOExceptionDialog extends DialogWrapper { public static boolean showErrorDialog(final String title, final String text) { final Ref ok = Ref.create(false); try { - GuiUtils.runOrInvokeAndWait(new Runnable() { - @Override - public void run() { - IOExceptionDialog dialog = new IOExceptionDialog(title, text); - dialog.show(); - ok.set(dialog.isOK()); - } + GuiUtils.runOrInvokeAndWait(() -> { + IOExceptionDialog dialog = new IOExceptionDialog(title, text); + dialog.show(); + ok.set(dialog.isOK()); }); } catch (InterruptedException e) { diff --git a/platform/platform-api/src/com/intellij/util/net/ssl/CertificateConfigurable.java b/platform/platform-api/src/com/intellij/util/net/ssl/CertificateConfigurable.java index b0e0eee80f75..527b9526eecd 100644 --- a/platform/platform-api/src/com/intellij/util/net/ssl/CertificateConfigurable.java +++ b/platform/platform-api/src/com/intellij/util/net/ssl/CertificateConfigurable.java @@ -78,23 +78,20 @@ public class CertificateConfigurable implements SearchableConfigurable, Configur @Override public void run(AnActionButton button) { // show choose file dialog, add certificate - FileChooser.chooseFile(CERTIFICATE_DESCRIPTOR, null, null, new Consumer() { - @Override - public void consume(VirtualFile file) { - String path = file.getPath(); - X509Certificate certificate = CertificateUtil.loadX509Certificate(path); - if (certificate == null) { - Messages.showErrorDialog(myRootPanel, "Malformed X509 server certificate", "Not Imported"); - } - else if (myCertificates.contains(certificate)) { - Messages.showWarningDialog(myRootPanel, "Certificate already exists", "Not Imported"); - } - else { - myCertificates.add(certificate); - myTreeBuilder.addCertificate(certificate); - addCertificatePanel(certificate); - myTreeBuilder.selectCertificate(certificate); - } + FileChooser.chooseFile(CERTIFICATE_DESCRIPTOR, null, null, file -> { + String path = file.getPath(); + X509Certificate certificate = CertificateUtil.loadX509Certificate(path); + if (certificate == null) { + Messages.showErrorDialog(myRootPanel, "Malformed X509 server certificate", "Not Imported"); + } + else if (myCertificates.contains(certificate)) { + Messages.showWarningDialog(myRootPanel, "Certificate already exists", "Not Imported"); + } + else { + myCertificates.add(certificate); + myTreeBuilder.addCertificate(certificate); + addCertificatePanel(certificate); + myTreeBuilder.selectCertificate(certificate); } }); } @@ -248,26 +245,21 @@ public class CertificateConfigurable implements SearchableConfigurable, Configur @Override public void certificateAdded(final X509Certificate certificate) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myTreeBuilder != null && !myCertificates.contains(certificate)) { - myCertificates.add(certificate); - myTreeBuilder.addCertificate(certificate); - addCertificatePanel(certificate); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myTreeBuilder != null && !myCertificates.contains(certificate)) { + myCertificates.add(certificate); + myTreeBuilder.addCertificate(certificate); + addCertificatePanel(certificate); } }); } @Override public void certificateRemoved(final X509Certificate certificate) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - if (myTreeBuilder != null && myCertificates.contains(certificate)) { - myCertificates.remove(certificate); - myTreeBuilder.removeCertificate(certificate); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myTreeBuilder != null && myCertificates.contains(certificate)) { + myCertificates.remove(certificate); + myTreeBuilder.removeCertificate(certificate); } }); } diff --git a/platform/platform-api/src/com/intellij/util/net/ssl/CertificateManager.java b/platform/platform-api/src/com/intellij/util/net/ssl/CertificateManager.java index de7ac7d1b5e0..0482681a5455 100644 --- a/platform/platform-api/src/com/intellij/util/net/ssl/CertificateManager.java +++ b/platform/platform-api/src/com/intellij/util/net/ssl/CertificateManager.java @@ -294,24 +294,21 @@ public class CertificateManager implements PersistentStateComponent dialogRef = new AtomicReference(); - Runnable showDialog = new Runnable() { - @Override - public void run() { - // skip if certificate was already rejected due to timeout or interrupt - if (proceeded.getCount() == 0) { - return; - } - try { - DialogWrapper dialog = dialogFactory.call(); - dialogRef.set(dialog); - accepted.set(dialog.showAndGet()); - } - catch (Exception e) { - LOG.error(e); - } - finally { - proceeded.countDown(); - } + Runnable showDialog = () -> { + // skip if certificate was already rejected due to timeout or interrupt + if (proceeded.getCount() == 0) { + return; + } + try { + DialogWrapper dialog = dialogFactory.call(); + dialogRef.set(dialog); + accepted.set(dialog.showAndGet()); + } + catch (Exception e) { + LOG.error(e); + } + finally { + proceeded.countDown(); } }; if (app.isDispatchThread()) { diff --git a/platform/platform-api/src/com/intellij/util/net/ssl/CertificateTreeBuilder.java b/platform/platform-api/src/com/intellij/util/net/ssl/CertificateTreeBuilder.java index 0d1141bf0998..26c7ed66677d 100644 --- a/platform/platform-api/src/com/intellij/util/net/ssl/CertificateTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/util/net/ssl/CertificateTreeBuilder.java @@ -37,19 +37,16 @@ public class CertificateTreeBuilder extends AbstractTreeBuilder { private final MultiMap myCertificates = new MultiMap(); public CertificateTreeBuilder(@NotNull Tree tree) { - init(tree, new DefaultTreeModel(new DefaultMutableTreeNode()), new MyTreeStructure(), new Comparator() { - @Override - public int compare(NodeDescriptor o1, NodeDescriptor o2) { - if (o1 instanceof OrganizationDescriptor && o2 instanceof OrganizationDescriptor) { - return ((String)o1.getElement()).compareTo((String)o2.getElement()); - } - else if (o1 instanceof CertificateDescriptor && o2 instanceof CertificateDescriptor) { - String cn1 = ((CertificateDescriptor)o1).getElement().getSubjectField(COMMON_NAME); - String cn2 = ((CertificateDescriptor)o2).getElement().getSubjectField(COMMON_NAME); - return cn1.compareTo(cn2); - } - return 0; + init(tree, new DefaultTreeModel(new DefaultMutableTreeNode()), new MyTreeStructure(), (o1, o2) -> { + if (o1 instanceof OrganizationDescriptor && o2 instanceof OrganizationDescriptor) { + return ((String)o1.getElement()).compareTo((String)o2.getElement()); } + else if (o1 instanceof CertificateDescriptor && o2 instanceof CertificateDescriptor) { + String cn1 = ((CertificateDescriptor)o1).getElement().getSubjectField(COMMON_NAME); + String cn2 = ((CertificateDescriptor)o2).getElement().getSubjectField(COMMON_NAME); + return cn1.compareTo(cn2); + } + return 0; }, true); initRootNode(); } @@ -61,12 +58,7 @@ public class CertificateTreeBuilder extends AbstractTreeBuilder { } // expand organization nodes at the same time //initRootNode(); - queueUpdateFrom(RootDescriptor.ROOT, true).doWhenDone(new Runnable() { - @Override - public void run() { - CertificateTreeBuilder.this.expandAll(null); - } - }); + queueUpdateFrom(RootDescriptor.ROOT, true).doWhenDone(() -> CertificateTreeBuilder.this.expandAll(null)); } public void addCertificate(@NotNull X509Certificate certificate) { @@ -139,11 +131,8 @@ public class CertificateTreeBuilder extends AbstractTreeBuilder { } private static List extract(Collection wrappers) { - return ContainerUtil.map(wrappers, new Function() { - @Override - public X509Certificate fun(CertificateWrapper wrapper) { - return wrapper.getCertificate(); - } + return ContainerUtil.map(wrappers, wrapper -> { + return wrapper.getCertificate(); }); } diff --git a/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingHostnameVerifier.java b/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingHostnameVerifier.java index 7aae1f1838f7..72d18fc5c88d 100644 --- a/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingHostnameVerifier.java +++ b/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingHostnameVerifier.java @@ -84,12 +84,7 @@ class ConfirmingHostnameVerifier implements X509HostnameVerifier { } private static boolean accepted(final String host, final X509Certificate cert) { - return CertificateManager.showAcceptDialog(new Callable() { - @Override - public DialogWrapper call() throws Exception { - return CertificateWarningDialog.createHostnameMismatchWarning(cert, host); - } - }); + return CertificateManager.showAcceptDialog(() -> CertificateWarningDialog.createHostnameMismatchWarning(cert, host)); } // Copied from httpclient 4.2 sources, read class level commentary for explanation. diff --git a/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingTrustManager.java b/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingTrustManager.java index 1d223502dfee..ad8afd6c619e 100644 --- a/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingTrustManager.java +++ b/platform/platform-api/src/com/intellij/util/net/ssl/ConfirmingTrustManager.java @@ -149,12 +149,9 @@ public class ConfirmingTrustManager extends ClientOnlyTrustManager { } return true; } - boolean accepted = askUser && CertificateManager.showAcceptDialog(new Callable() { - @Override - public DialogWrapper call() throws Exception { - // TODO may be another kind of warning, if default trust store is missing - return CertificateWarningDialog.createUntrustedCertificateWarning(endPoint); - } + boolean accepted = askUser && CertificateManager.showAcceptDialog(() -> { + // TODO may be another kind of warning, if default trust store is missing + return CertificateWarningDialog.createUntrustedCertificateWarning(endPoint); }); if (accepted) { LOG.info("Certificate was accepted by user"); diff --git a/platform/platform-api/src/com/intellij/util/ui/Animator.java b/platform/platform-api/src/com/intellij/util/ui/Animator.java index cd4ac6c02c86..82e766e55188 100644 --- a/platform/platform-api/src/com/intellij/util/ui/Animator.java +++ b/platform/platform-api/src/com/intellij/util/ui/Animator.java @@ -105,12 +105,7 @@ public abstract class Animator implements Disposable { private void animationDone() { stopTicker(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - paintCycleEnd(); - } - }); + SwingUtilities.invokeLater(() -> paintCycleEnd()); } private void stopTicker() { diff --git a/platform/platform-api/src/com/intellij/util/ui/AsyncProcessIcon.java b/platform/platform-api/src/com/intellij/util/ui/AsyncProcessIcon.java index 7c24303782b1..e2d44b91603b 100644 --- a/platform/platform-api/src/com/intellij/util/ui/AsyncProcessIcon.java +++ b/platform/platform-api/src/com/intellij/util/ui/AsyncProcessIcon.java @@ -78,12 +78,7 @@ public class AsyncProcessIcon extends AnimatedIcon { setBounds(newBounds); // painting problems with scrollpane // repaint shouldn't be called from paint method - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - container.repaint(); - } - }); + SwingUtilities.invokeLater(() -> container.repaint()); } } diff --git a/platform/platform-api/src/com/intellij/util/ui/BaseButtonBehavior.java b/platform/platform-api/src/com/intellij/util/ui/BaseButtonBehavior.java index 082aaef5c6c7..089e5b360698 100644 --- a/platform/platform-api/src/com/intellij/util/ui/BaseButtonBehavior.java +++ b/platform/platform-api/src/com/intellij/util/ui/BaseButtonBehavior.java @@ -142,13 +142,10 @@ public abstract class BaseButtonBehavior { repaintComponent(); BaseButtonBehavior.this.execute(e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!myComponent.isShowing()) { - setHovered(false); - myMouseDeadzone.clear(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!myComponent.isShowing()) { + setHovered(false); + myMouseDeadzone.clear(); } }); diff --git a/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java b/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java index b1429f7e0086..a0a9d9a12a04 100644 --- a/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java +++ b/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java @@ -83,13 +83,7 @@ public class ButtonlessScrollBarUI extends BasicScrollBarUI { } private JBColor jbColor(final Color regular, final Color dark) { - return new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - return isDark() ? dark : regular; - } - }); + return new JBColor(() -> isDark() ? dark : regular); } private int getAnimationColorShift() { @@ -404,12 +398,7 @@ public class ButtonlessScrollBarUI extends BasicScrollBarUI { Application application = ApplicationManager.getApplication(); if (!myMouseOverScrollbar && !sb.getValueIsAdjusting() && (application == null || !application.isUnitTestMode())) { - myMacScrollbarFadeTimer.addRequest(new Runnable() { - @Override - public void run() { - myMacScrollbarFadeAnimator.resume(); - } - }, 700, null); + myMacScrollbarFadeTimer.addRequest(() -> myMacScrollbarFadeAnimator.resume(), 700, null); } } } @@ -810,13 +799,7 @@ public class ButtonlessScrollBarUI extends BasicScrollBarUI { RenderingHints oldHints = g2d.getRenderingHints(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - JBColor baseColor = new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - return !isDark() ? Gray._0 : Gray._128; - } - }); + JBColor baseColor = new JBColor(() -> !isDark() ? Gray._0 : Gray._128); int arc = Math.min(thumbBounds.width, thumbBounds.height); diff --git a/platform/platform-api/src/com/intellij/util/ui/EditorAdapter.java b/platform/platform-api/src/com/intellij/util/ui/EditorAdapter.java index 6dbea01829a4..a65f45ec43d9 100644 --- a/platform/platform-api/src/com/intellij/util/ui/EditorAdapter.java +++ b/platform/platform-api/src/com/intellij/util/ui/EditorAdapter.java @@ -61,11 +61,7 @@ public class EditorAdapter { private final Project myProject; private final boolean myScrollToTheEndOnAppend; - private final Runnable myFlushDeferredRunnable = new Runnable() { - public void run() { - flushStoredLines(); - } - }; + private final Runnable myFlushDeferredRunnable = () -> flushStoredLines(); private synchronized void flushStoredLines() { Collection lines; @@ -99,33 +95,27 @@ public class EditorAdapter { } private Runnable writingCommand(final Collection lines) { - final Runnable command = new Runnable() { - public void run() { + final Runnable command = () -> { - Document document = myEditor.getDocument(); + Document document = myEditor.getDocument(); - StringBuilder buffer = new StringBuilder(); - for (Line line : lines) { - buffer.append(line.getValue()); - } - int endBefore = document.getTextLength(); - int endBeforeLine = endBefore; - document.insertString(endBefore, buffer.toString()); - for (Line line : lines) { - myEditor.getMarkupModel() - .addRangeHighlighter(endBeforeLine, Math.min(document.getTextLength(), endBeforeLine + line.getValue().length()), HighlighterLayer.ADDITIONAL_SYNTAX, - line.getAttributes(), HighlighterTargetArea.EXACT_RANGE); - endBeforeLine += line.getValue().length(); - if (endBeforeLine > document.getTextLength()) break; - } - shiftCursorToTheEndOfDocument(); + StringBuilder buffer = new StringBuilder(); + for (Line line : lines) { + buffer.append(line.getValue()); } - }; - return new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, command, "", null, UndoConfirmationPolicy.DEFAULT, myEditor.getDocument()); + int endBefore = document.getTextLength(); + int endBeforeLine = endBefore; + document.insertString(endBefore, buffer.toString()); + for (Line line : lines) { + myEditor.getMarkupModel() + .addRangeHighlighter(endBeforeLine, Math.min(document.getTextLength(), endBeforeLine + line.getValue().length()), HighlighterLayer.ADDITIONAL_SYNTAX, + line.getAttributes(), HighlighterTargetArea.EXACT_RANGE); + endBeforeLine += line.getValue().length(); + if (endBeforeLine > document.getTextLength()) break; } + shiftCursorToTheEndOfDocument(); }; + return () -> CommandProcessor.getInstance().executeCommand(myProject, command, "", null, UndoConfirmationPolicy.DEFAULT, myEditor.getDocument()); } private void shiftCursorToTheEndOfDocument() { diff --git a/platform/platform-api/src/com/intellij/util/ui/NSScrollerHelper.java b/platform/platform-api/src/com/intellij/util/ui/NSScrollerHelper.java index 09a0b92cf6b4..adce85f91a4c 100644 --- a/platform/platform-api/src/com/intellij/util/ui/NSScrollerHelper.java +++ b/platform/platform-api/src/com/intellij/util/ui/NSScrollerHelper.java @@ -36,23 +36,13 @@ class NSScrollerHelper { private static final Callback APPEARANCE_CALLBACK = new Callback() { @SuppressWarnings("UnusedDeclaration") public void callback(ID self, Pointer selector, ID event) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - fireStyleChanged(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> fireStyleChanged()); } }; private static final Callback BEHAVIOR_CALLBACK = new Callback() { @SuppressWarnings("UnusedDeclaration") public void callback(ID self, Pointer selector, ID event) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - updateBehaviorPreferences(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> updateBehaviorPreferences()); } }; diff --git a/platform/platform-api/src/com/intellij/util/ui/RangeBlinker.java b/platform/platform-api/src/com/intellij/util/ui/RangeBlinker.java index f4f815b77116..fb254c343ba7 100644 --- a/platform/platform-api/src/com/intellij/util/ui/RangeBlinker.java +++ b/platform/platform-api/src/com/intellij/util/ui/RangeBlinker.java @@ -85,14 +85,11 @@ public class RangeBlinker { removeHighlights(); } stopBlinking(); - myBlinkingAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myTimeToLive > 0 || show) { - myTimeToLive--; - show = !show; - startBlinking(); - } + myBlinkingAlarm.addRequest(() -> { + if (myTimeToLive > 0 || show) { + myTimeToLive--; + show = !show; + startBlinking(); } }, 400); } diff --git a/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java b/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java index 92348089686e..593f3804a493 100644 --- a/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java +++ b/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java @@ -506,19 +506,16 @@ public final class TreeUtil { } } - Runnable selectRunnable = new Runnable() { - @Override - public void run() { - if (!tree.isRowSelected(row)) { - if (addToSelection) { - tree.getSelectionModel().addSelectionPath(tree.getPathForRow(row)); - } else { - tree.setSelectionRow(row); - } - } else if (resetSelection) { - if (!addToSelection) { - tree.setSelectionRow(row); - } + Runnable selectRunnable = () -> { + if (!tree.isRowSelected(row)) { + if (addToSelection) { + tree.getSelectionModel().addSelectionPath(tree.getPathForRow(row)); + } else { + tree.setSelectionRow(row); + } + } else if (resetSelection) { + if (!addToSelection) { + tree.setSelectionRow(row); } } }; @@ -583,47 +580,36 @@ public final class TreeUtil { } final Rectangle b1 = bounds; - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (scroll) { - AbstractTreeBuilder builder = AbstractTreeBuilder.getBuilderFor(tree); - if (builder != null) { - builder.getReady(TreeUtil.class).doWhenDone(new Runnable() { - @Override - public void run() { - tree.scrollRectToVisible(b1); - } - }); - callback.setDone(); - } else { - tree.scrollRectToVisible(b1); + final Runnable runnable = () -> { + if (scroll) { + AbstractTreeBuilder builder = AbstractTreeBuilder.getBuilderFor(tree); + if (builder != null) { + builder.getReady(TreeUtil.class).doWhenDone(() -> tree.scrollRectToVisible(b1)); + callback.setDone(); + } else { + tree.scrollRectToVisible(b1); - Long ts = (Long)tree.getClientProperty(TREE_UTIL_SCROLL_TIME_STAMP); - if (ts == null) { - ts = 0L; - } - ts = ts.longValue() + 1; - tree.putClientProperty(TREE_UTIL_SCROLL_TIME_STAMP, ts); - - final long targetValue = ts.longValue(); - - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Long actual = (Long)tree.getClientProperty(TREE_UTIL_SCROLL_TIME_STAMP); - if (actual == null || targetValue < actual.longValue()) return; - - if (!tree.getVisibleRect().contains(b1)) { - tree.scrollRectToVisible(b1); - } - callback.setDone(); - } - }); + Long ts = (Long)tree.getClientProperty(TREE_UTIL_SCROLL_TIME_STAMP); + if (ts == null) { + ts = 0L; } + ts = ts.longValue() + 1; + tree.putClientProperty(TREE_UTIL_SCROLL_TIME_STAMP, ts); + + final long targetValue = ts.longValue(); + + SwingUtilities.invokeLater(() -> { + Long actual = (Long)tree.getClientProperty(TREE_UTIL_SCROLL_TIME_STAMP); + if (actual == null || targetValue < actual.longValue()) return; + + if (!tree.getVisibleRect().contains(b1)) { + tree.scrollRectToVisible(b1); + } + callback.setDone(); + }); } - callback.setDone(); } + callback.setDone(); }; runnable.run(); @@ -774,15 +760,12 @@ public final class TreeUtil { public static void expandRootChildIfOnlyOne(@Nullable final JTree tree) { if (tree == null) return; - final Runnable runnable = new Runnable() { - @Override - public void run() { - final DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot(); - tree.expandPath(new TreePath(new Object[]{root})); - if (root.getChildCount() == 1) { - TreeNode firstChild = root.getFirstChild(); - tree.expandPath(new TreePath(new Object[]{root, firstChild})); - } + final Runnable runnable = () -> { + final DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot(); + tree.expandPath(new TreePath(new Object[]{root})); + if (root.getChildCount() == 1) { + TreeNode firstChild = root.getFirstChild(); + tree.expandPath(new TreePath(new Object[]{root, firstChild})); } }; UIUtil.invokeLaterIfNeeded(runnable); @@ -1015,11 +998,6 @@ public final class TreeUtil { @NotNull public static Comparator getDisplayOrderComparator(@NotNull final JTree tree) { - return new Comparator() { - @Override - public int compare(TreePath path1, TreePath path2) { - return tree.getRowForPath(path1) - tree.getRowForPath(path2); - } - }; + return (path1, path2) -> tree.getRowForPath(path1) - tree.getRowForPath(path2); } } diff --git a/platform/platform-api/src/com/intellij/util/ui/update/LazyUiDisposable.java b/platform/platform-api/src/com/intellij/util/ui/update/LazyUiDisposable.java index eb0dbc7ec499..009e2e00d8d1 100644 --- a/platform/platform-api/src/com/intellij/util/ui/update/LazyUiDisposable.java +++ b/platform/platform-api/src/com/intellij/util/ui/update/LazyUiDisposable.java @@ -57,15 +57,13 @@ public abstract class LazyUiDisposable implements Activata try { findParentDisposable() - .done(new Consumer() { - public void consume(Disposable parent) { - Project project = null; - if (ApplicationManager.getApplication() != null) { - project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); - } - initialize(parent, myChild, project); - Disposer.register(parent, myChild); + .done(parent -> { + Project project = null; + if (ApplicationManager.getApplication() != null) { + project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); } + initialize(parent, myChild, project); + Disposer.register(parent, myChild); }); } finally { diff --git a/platform/platform-api/src/com/intellij/util/ui/update/MergingUpdateQueue.java b/platform/platform-api/src/com/intellij/util/ui/update/MergingUpdateQueue.java index 137d164d0e9b..f7b4c0327a9c 100644 --- a/platform/platform-api/src/com/intellij/util/ui/update/MergingUpdateQueue.java +++ b/platform/platform-api/src/com/intellij/util/ui/update/MergingUpdateQueue.java @@ -152,11 +152,8 @@ public class MergingUpdateQueue implements Runnable, Disposable, Activatable { @NotNull private List getAllScheduledUpdates() { - return ContainerUtil.concat(myScheduledUpdates.values(), new Function, Collection>() { - @Override - public Collection fun(Map map) { - return map.keySet(); - } + return ContainerUtil.concat(myScheduledUpdates.values(), map -> { + return map.keySet(); }); } @@ -249,28 +246,25 @@ public class MergingUpdateQueue implements Runnable, Disposable, Activatable { } myFlushing = true; - final Runnable toRun = new Runnable() { - @Override - public void run() { - try { - final List all; + final Runnable toRun = () -> { + try { + final List all; - synchronized (myScheduledUpdates) { - all = getAllScheduledUpdates(); - myScheduledUpdates.clear(); - } - - for (Update each : all) { - each.setProcessed(); - } - - execute(all.toArray(new Update[all.size()])); + synchronized (myScheduledUpdates) { + all = getAllScheduledUpdates(); + myScheduledUpdates.clear(); } - finally { - myFlushing = false; - if (isEmpty()) { - finishActivity(); - } + + for (Update each : all) { + each.setProcessed(); + } + + execute(all.toArray(new Update[all.size()])); + } + finally { + myFlushing = false; + if (isEmpty()) { + finishActivity(); } } }; @@ -312,11 +306,8 @@ public class MergingUpdateQueue implements Runnable, Disposable, Activatable { } if (each.executeInWriteAction()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - execute(each); - } + ApplicationManager.getApplication().runWriteAction(() -> { + execute(each); }); } else { diff --git a/platform/platform-impl/src/com/intellij/application/options/SchemesToImportPopup.java b/platform/platform-impl/src/com/intellij/application/options/SchemesToImportPopup.java index 3a15c1ccbd50..8373f3309479 100644 --- a/platform/platform-impl/src/com/intellij/application/options/SchemesToImportPopup.java +++ b/platform/platform-impl/src/com/intellij/application/options/SchemesToImportPopup.java @@ -44,12 +44,7 @@ public abstract class SchemesToImportPopup { list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setCellRenderer(new SchemesToImportListCellRenderer()); - Runnable selectAction = new Runnable() { - @Override - public void run() { - onSchemeSelected((T)list.getSelectedValue()); - } - }; + Runnable selectAction = () -> onSchemeSelected((T)list.getSelectedValue()); showList(list, selectAction); } diff --git a/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroListEditor.java b/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroListEditor.java index c1588801d21a..ae98bc7b3414 100644 --- a/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroListEditor.java +++ b/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroListEditor.java @@ -89,14 +89,12 @@ public class PathMacroListEditor { } public void commit() throws ConfigurationException { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myPathMacroTable.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + myPathMacroTable.commit(); - final Collection ignored = parseIgnoredVariables(); - final PathMacros instance = PathMacros.getInstance(); - instance.setIgnoredMacroNames(ignored); - } + final Collection ignored = parseIgnoredVariables(); + final PathMacros instance = PathMacros.getInstance(); + instance.setIgnoredMacroNames(ignored); }); } diff --git a/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroTable.java b/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroTable.java index 0669e0b717cf..54cf150b2287 100644 --- a/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroTable.java +++ b/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroTable.java @@ -45,11 +45,7 @@ public class PathMacroTable extends Table { private static final int VALUE_COLUMN = 1; private final List> myMacros = new ArrayList>(); - private static final Comparator> MACRO_COMPARATOR = new Comparator>() { - public int compare(Couple pair, Couple pair1) { - return pair.getFirst().compareTo(pair1.getFirst()); - } - }; + private static final Comparator> MACRO_COMPARATOR = (pair, pair1) -> pair.getFirst().compareTo(pair1.getFirst()); private final Collection myUndefinedMacroNames; diff --git a/platform/platform-impl/src/com/intellij/codeInsight/hint/EditorFragmentComponent.java b/platform/platform-impl/src/com/intellij/codeInsight/hint/EditorFragmentComponent.java index 59199087107d..08033e60a7d3 100644 --- a/platform/platform-impl/src/com/intellij/codeInsight/hint/EditorFragmentComponent.java +++ b/platform/platform-impl/src/com/intellij/codeInsight/hint/EditorFragmentComponent.java @@ -287,12 +287,7 @@ public class EditorFragmentComponent extends JPanel { // needed for Alt-Q multiple times // Q: not good? SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - MyComponentHint.super.hide(); - } - } + () -> MyComponentHint.super.hide() ); } } diff --git a/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java b/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java index 3472f16d2333..0b3133987f61 100644 --- a/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java @@ -286,13 +286,11 @@ public class HintManagerImpl extends HintManager implements Disposable { */ public void showEditorHint(final LightweightHint hint, final Editor editor, @PositionFlags final short constraint, @HideFlags final int flags, final int timeout, final boolean reviveOnEditorChange) { editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); - editor.getScrollingModel().runActionOnScrollingFinished(new Runnable() { - @Override - public void run() { - LogicalPosition pos = editor.getCaretModel().getLogicalPosition(); - Point p = getHintPosition(hint, editor, pos, constraint); - showEditorHint(hint, editor, p, flags, timeout, reviveOnEditorChange, createHintHint(editor, p, hint, constraint)); - }}); + editor.getScrollingModel().runActionOnScrollingFinished(() -> { + LogicalPosition pos = editor.getCaretModel().getLogicalPosition(); + Point p = getHintPosition(hint, editor, pos, constraint); + showEditorHint(hint, editor, p, flags, timeout, reviveOnEditorChange, createHintHint(editor, p, hint, constraint)); + }); } /** diff --git a/platform/platform-impl/src/com/intellij/codeInsight/hint/HintUtil.java b/platform/platform-impl/src/com/intellij/codeInsight/hint/HintUtil.java index 0d3b085cdfc5..40294242cfde 100644 --- a/platform/platform-impl/src/com/intellij/codeInsight/hint/HintUtil.java +++ b/platform/platform-impl/src/com/intellij/codeInsight/hint/HintUtil.java @@ -73,15 +73,12 @@ public class HintUtil { label.myPane.addMouseListener(mouseListener); } if (updatedTextConsumer != null) { - updatedTextConsumer.set(new Consumer() { - @Override - public void consume(String s) { - label.myPane.setText(s); - - // Force preferred size recalculation. - label.setPreferredSize(null); - label.myPane.setPreferredSize(null); - } + updatedTextConsumer.set(s -> { + label.myPane.setText(s); + + // Force preferred size recalculation. + label.setPreferredSize(null); + label.myPane.setPreferredSize(null); }); } diff --git a/platform/platform-impl/src/com/intellij/concurrency/AsyncFutureResultImpl.java b/platform/platform-impl/src/com/intellij/concurrency/AsyncFutureResultImpl.java index 30a606fca27b..ee38db564d9b 100644 --- a/platform/platform-impl/src/com/intellij/concurrency/AsyncFutureResultImpl.java +++ b/platform/platform-impl/src/com/intellij/concurrency/AsyncFutureResultImpl.java @@ -35,19 +35,16 @@ public class AsyncFutureResultImpl implements AsyncFutureResult { @Override public void addConsumer(@NotNull Executor executor, @NotNull final ResultConsumer consumer) { - myFuture.addListener(new Runnable() { - @Override - public void run() { - try { - final V result = myFuture.get(); - consumer.onSuccess(result); - } - catch (ExecutionException e) { - consumer.onFailure(e.getCause()); - } - catch (Throwable throwable) { - consumer.onFailure(throwable); - } + myFuture.addListener(() -> { + try { + final V result = myFuture.get(); + consumer.onSuccess(result); + } + catch (ExecutionException e) { + consumer.onFailure(e.getCause()); + } + catch (Throwable throwable) { + consumer.onFailure(throwable); } }, executor); } diff --git a/platform/platform-impl/src/com/intellij/designer/LightFillLayout.java b/platform/platform-impl/src/com/intellij/designer/LightFillLayout.java index e2cc44fc471f..7301d9899365 100644 --- a/platform/platform-impl/src/com/intellij/designer/LightFillLayout.java +++ b/platform/platform-impl/src/com/intellij/designer/LightFillLayout.java @@ -67,22 +67,12 @@ public class LightFillLayout implements LayoutManager2 { @Override public Dimension preferredLayoutSize(Container parent) { - return layoutSize(parent, myVertical, new Function() { - @Override - public Dimension fun(Component component) { - return component.getPreferredSize(); - } - }); + return layoutSize(parent, myVertical, component -> component.getPreferredSize()); } @Override public Dimension minimumLayoutSize(Container parent) { - return layoutSize(parent, myVertical, new Function() { - @Override - public Dimension fun(Component component) { - return component.getMinimumSize(); - } - }); + return layoutSize(parent, myVertical, component -> component.getMinimumSize()); } private static Dimension layoutSize(Container parent, boolean vertical, Function getSize) { diff --git a/platform/platform-impl/src/com/intellij/designer/LightToolWindowManager.java b/platform/platform-impl/src/com/intellij/designer/LightToolWindowManager.java index 6a6ab4d5dca6..9c244785edc1 100644 --- a/platform/platform-impl/src/com/intellij/designer/LightToolWindowManager.java +++ b/platform/platform-impl/src/com/intellij/designer/LightToolWindowManager.java @@ -66,12 +66,7 @@ public abstract class LightToolWindowManager implements ProjectComponent { @Override public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - bindToDesigner(getActiveDesigner()); - } - }); + ApplicationManager.getApplication().invokeLater(() -> bindToDesigner(getActiveDesigner())); } @Override @@ -252,28 +247,16 @@ public abstract class LightToolWindowManager implements ProjectComponent { toolWindow.dispose(); } - private final ParameterizedRunnable myCreateAction = new ParameterizedRunnable() { - @Override - public void run(DesignerEditorPanelFacade designer) { - designer.putClientProperty(getComponentName(), createContent(designer)); - } - }; + private final ParameterizedRunnable myCreateAction = + designer -> designer.putClientProperty(getComponentName(), createContent(designer)); private final ParameterizedRunnable myUpdateAnchorAction = - new ParameterizedRunnable() { - @Override - public void run(DesignerEditorPanelFacade designer) { - LightToolWindow toolWindow = (LightToolWindow)designer.getClientProperty(getComponentName()); - toolWindow.updateAnchor(getEditorMode()); - } + designer -> { + LightToolWindow toolWindow = (LightToolWindow)designer.getClientProperty(getComponentName()); + toolWindow.updateAnchor(getEditorMode()); }; - private final ParameterizedRunnable myDisposeAction = new ParameterizedRunnable() { - @Override - public void run(DesignerEditorPanelFacade designer) { - disposeContent(designer); - } - }; + private final ParameterizedRunnable myDisposeAction = designer -> disposeContent(designer); private void runUpdateContent(ParameterizedRunnable action) { for (FileEditor editor : myFileEditorManager.getAllEditors()) { diff --git a/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java b/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java index 41a72cc9d427..0996890a140f 100644 --- a/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java +++ b/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java @@ -63,18 +63,8 @@ import java.util.List; */ public abstract class PropertyTable extends JBTable { private static final Logger LOG = Logger.getInstance("#com.intellij.designer.propertyTable.PropertyTable"); - private static final Comparator GROUP_COMPARATOR = new Comparator() { - @Override - public int compare(String o1, String o2) { - return StringUtil.compare(o1, o2, true); - } - }; - private static final Comparator PROPERTY_COMPARATOR = new Comparator() { - @Override - public int compare(Property o1, Property o2) { - return StringUtil.compare(o1.getName(), o2.getName(), true); - } - }; + private static final Comparator GROUP_COMPARATOR = (o1, o2) -> StringUtil.compare(o1, o2, true); + private static final Comparator PROPERTY_COMPARATOR = (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true); private boolean mySorted; private boolean myShowGroups; @@ -114,13 +104,10 @@ public abstract class PropertyTable extends JBTable { addMouseListener(new MouseTableListener()); - mySpeedSearch = new TableSpeedSearch(this, new PairFunction() { - @Override - public String fun(Object object, Cell cell) { - if (cell.column != 0) return null; - if (object instanceof GroupProperty) return null; - return ((Property)object).getName(); - } + mySpeedSearch = new TableSpeedSearch(this, (object, cell) -> { + if (cell.column != 0) return null; + if (object instanceof GroupProperty) return null; + return ((Property)object).getName(); }) { @Override protected void selectElement(Object element, String selectedText) { @@ -238,13 +225,10 @@ public abstract class PropertyTable extends JBTable { cellEditor.stopCellEditing(); } - doRestoreDefault(new ThrowableRunnable() { - @Override - public void run() throws Exception { - for (PropertiesContainer component : myContainers) { - if (!property.isDefaultRecursively(component)) { - property.setDefaultValue(component); - } + doRestoreDefault(() -> { + for (PropertiesContainer component : myContainers) { + if (!property.isDefaultRecursively(component)) { + property.setDefaultValue(component); } } }); @@ -343,21 +327,18 @@ public abstract class PropertyTable extends JBTable { private void sortPropertiesAndCreateGroups(List rootProperties) { if (!mySorted && !myShowGroups) return; - Collections.sort(rootProperties, new Comparator() { - @Override - public int compare(Property o1, Property o2) { - if (o1.getParent() != null || o2.getParent() != null) { - if (o1.getParent() == o2) return -1; - if (o2.getParent() == o1) return 1; - return 0; - } - - if (myShowGroups) { - int result = getGroupComparator().compare(o1.getGroup(), o2.getGroup()); - if (result != 0) return result; - } - return mySorted ? getPropertyComparator().compare(o1, o2) : 0; + Collections.sort(rootProperties, (o1, o2) -> { + if (o1.getParent() != null || o2.getParent() != null) { + if (o1.getParent() == o2) return -1; + if (o2.getParent() == o1) return 1; + return 0; } + + if (myShowGroups) { + int result = getGroupComparator().compare(o1.getGroup(), o2.getGroup()); + if (result != 0) return result; + } + return mySorted ? getPropertyComparator().compare(o1, o2) : 0; }); if (myShowGroups) { @@ -777,12 +758,7 @@ public abstract class PropertyTable extends JBTable { if (startedWithKeyboard) { // waiting for focus is necessary in case, if 'activate' opens dialog. If we don't wait for focus, after the dialog is shown we'll // end up with the table focused instead of the dialog - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - editor.activate(); - } - }); + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> editor.activate()); } } @@ -845,13 +821,10 @@ public abstract class PropertyTable extends JBTable { final boolean[] needRefresh = new boolean[1]; if (isNewValue) { - isSetValue = doSetValue(new ThrowableRunnable() { - @Override - public void run() throws Exception { - for (PropertiesContainer component : myContainers) { - property.setValue(component, newValue); - needRefresh[0] |= property.needRefreshPropertyList(component, oldValue[0], newValue); - } + isSetValue = doSetValue(() -> { + for (PropertiesContainer component : myContainers) { + property.setValue(component, newValue); + needRefresh[0] |= property.needRefreshPropertyList(component, oldValue[0], newValue); } }); } @@ -1176,11 +1149,7 @@ public abstract class PropertyTable extends JBTable { return errComponent; } finally { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - updateEditActions(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> updateEditActions()); } } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java b/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java index 37a9ecb5763f..9a72786c4f3a 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java @@ -81,11 +81,7 @@ public class DefaultIdeaErrorLogger implements ErrorLogger { final MemoryKind kind = getOOMErrorKind(throwable); if (kind != null) { ourOomOccurred = true; - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - new OutOfMemoryDialog(kind).show(); - } - }); + SwingUtilities.invokeAndWait(() -> new OutOfMemoryDialog(kind).show()); } else if (throwable instanceof MappingFailedException) { processMappingFailed(event); diff --git a/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java b/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java index 2a8cb06e8520..060246aa93bc 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java @@ -58,15 +58,12 @@ public class DialogAppender extends AppenderSkeleton { else { // Note, we MUST avoid SYNCHRONOUS invokeAndWait to prevent deadlocks //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - appendToLoggers(event, new ErrorLogger[]{ DEFAULT_LOGGER }); - } - finally { - myPendingAppendCounts.decrementAndGet(); - } + SwingUtilities.invokeLater(() -> { + try { + appendToLoggers(event, new ErrorLogger[]{ DEFAULT_LOGGER }); + } + finally { + myPendingAppendCounts.decrementAndGet(); } }); } @@ -94,15 +91,12 @@ public class DialogAppender extends AppenderSkeleton { if (!logger.canHandle(ideaEvent)) { continue; } - myDialogRunnable = new Runnable() { - @Override - public void run() { - try { - logger.handle(ideaEvent); - } - finally { - myDialogRunnable = null; - } + myDialogRunnable = () -> { + try { + logger.handle(ideaEvent); + } + finally { + myDialogRunnable = null; } }; diff --git a/platform/platform-impl/src/com/intellij/diagnostic/GroupedLogMessage.java b/platform/platform-impl/src/com/intellij/diagnostic/GroupedLogMessage.java index 87d827d14377..8dbe026cbd5d 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/GroupedLogMessage.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/GroupedLogMessage.java @@ -70,11 +70,8 @@ public class GroupedLogMessage extends AbstractMessage { @NotNull @Override public List getAllAttachments() { - return ContainerUtil.concat(getMessages(), new Function>() { - @Override - public Collection fun(AbstractMessage message) { - return message.getAllAttachments(); - } + return ContainerUtil.concat(getMessages(), message -> { + return message.getAllAttachments(); }); } } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/ITNReporter.java b/platform/platform-impl/src/com/intellij/diagnostic/ITNReporter.java index 41dd934cc942..85dd18e9add8 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/ITNReporter.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/ITNReporter.java @@ -120,74 +120,57 @@ public class ITNReporter extends ErrorReportSubmitter { password = "guest"; } - ITNProxy.sendError(project, login, password, errorBean, new Consumer() { - @Override - public void consume(Integer threadId) { - updatePreviousThreadId(threadId); - String url = ITNProxy.getBrowseUrl(threadId); - String linkText = String.valueOf(threadId); - final SubmittedReportInfo reportInfo = new SubmittedReportInfo(url, linkText, SubmittedReportInfo.SubmissionStatus.NEW_ISSUE); - callback.consume(reportInfo); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - StringBuilder text = new StringBuilder(); - IdeErrorsDialog.appendSubmissionInformation(reportInfo, text); - text.append('.').append("
    ").append(DiagnosticBundle.message("error.report.gratitude")); - String content = XmlStringUtil.wrapInHtml(text); - ReportMessages.GROUP - .createNotification(ReportMessages.ERROR_REPORT, content, NotificationType.INFORMATION, NotificationListener.URL_OPENING_LISTENER) - .setImportant(false) - .notify(project); - } - }); - } - }, new Consumer() { - @Override - public void consume(final Exception e) { - Logger.getInstance(ITNReporter.class).info("reporting failed: " + e); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String msg; - if (e instanceof NoSuchEAPUserException) { - msg = DiagnosticBundle.message("error.report.authentication.failed"); - } - else if (e instanceof InternalEAPException) { - msg = DiagnosticBundle.message("error.report.posting.failed", e.getMessage()); + ITNProxy.sendError(project, login, password, errorBean, threadId -> { + updatePreviousThreadId(threadId); + String url = ITNProxy.getBrowseUrl(threadId); + String linkText = String.valueOf(threadId); + final SubmittedReportInfo reportInfo = new SubmittedReportInfo(url, linkText, SubmittedReportInfo.SubmissionStatus.NEW_ISSUE); + callback.consume(reportInfo); + ApplicationManager.getApplication().invokeLater(() -> { + StringBuilder text = new StringBuilder(); + IdeErrorsDialog.appendSubmissionInformation(reportInfo, text); + text.append('.').append("
    ").append(DiagnosticBundle.message("error.report.gratitude")); + String content = XmlStringUtil.wrapInHtml(text); + ReportMessages.GROUP + .createNotification(ReportMessages.ERROR_REPORT, content, NotificationType.INFORMATION, NotificationListener.URL_OPENING_LISTENER) + .setImportant(false) + .notify(project); + }); + }, e -> { + Logger.getInstance(ITNReporter.class).info("reporting failed: " + e); + ApplicationManager.getApplication().invokeLater(() -> { + String msg; + if (e instanceof NoSuchEAPUserException) { + msg = DiagnosticBundle.message("error.report.authentication.failed"); + } + else if (e instanceof InternalEAPException) { + msg = DiagnosticBundle.message("error.report.posting.failed", e.getMessage()); + } + else { + msg = DiagnosticBundle.message("error.report.sending.failure"); + } + if (e instanceof UpdateAvailableException) { + String message = DiagnosticBundle.message("error.report.new.eap.build.message", e.getMessage()); + showMessageDialog(parentComponent, project, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()); + callback.consume(new SubmittedReportInfo(SubmittedReportInfo.SubmissionStatus.FAILED)); + } + else if (showYesNoDialog(parentComponent, project, msg, ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != Messages.YES) { + callback.consume(new SubmittedReportInfo(SubmittedReportInfo.SubmissionStatus.FAILED)); + } + else { + if (e instanceof NoSuchEAPUserException) { + final JetBrainsAccountDialog dialog; + if (parentComponent.isShowing()) { + dialog = new JetBrainsAccountDialog(parentComponent); } else { - msg = DiagnosticBundle.message("error.report.sending.failure"); - } - if (e instanceof UpdateAvailableException) { - String message = DiagnosticBundle.message("error.report.new.eap.build.message", e.getMessage()); - showMessageDialog(parentComponent, project, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()); - callback.consume(new SubmittedReportInfo(SubmittedReportInfo.SubmissionStatus.FAILED)); - } - else if (showYesNoDialog(parentComponent, project, msg, ReportMessages.ERROR_REPORT, Messages.getErrorIcon()) != Messages.YES) { - callback.consume(new SubmittedReportInfo(SubmittedReportInfo.SubmissionStatus.FAILED)); - } - else { - if (e instanceof NoSuchEAPUserException) { - final JetBrainsAccountDialog dialog; - if (parentComponent.isShowing()) { - dialog = new JetBrainsAccountDialog(parentComponent); - } - else { - dialog = new JetBrainsAccountDialog(project); - } - dialog.show(); - } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - doSubmit(event, parentComponent, callback, errorBean, description); - } - }); + dialog = new JetBrainsAccountDialog(project); } + dialog.show(); } - }); - } + ApplicationManager.getApplication().invokeLater(() -> doSubmit(event, parentComponent, callback, errorBean, description)); + } + }); }); return true; } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java b/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java index 60353a0b6c0b..582c9ced5311 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java @@ -183,20 +183,14 @@ public class IdeErrorsDialog extends DialogWrapper implements MessagePoolListene } public void newEntryAdded() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - rebuildHeaders(); - updateControls(); - } + SwingUtilities.invokeLater(() -> { + rebuildHeaders(); + updateControls(); }); } public void poolCleared() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - doOKAction(); - } - }); + SwingUtilities.invokeLater(() -> doOKAction()); } @Override @@ -899,20 +893,14 @@ public class IdeErrorsDialog extends DialogWrapper implements MessagePoolListene } return submitter.submit( - getEvents(logMessage), logMessage.getAdditionalInfo(), parentComponent, new Consumer() { - @Override - public void consume(final SubmittedReportInfo submittedReportInfo) { - logMessage.setSubmitting(false); - logMessage.setSubmitted(submittedReportInfo); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!dialogClosed) { - updateOnSubmit(); - } - } - }); - } + getEvents(logMessage), logMessage.getAdditionalInfo(), parentComponent, submittedReportInfo -> { + logMessage.setSubmitting(false); + logMessage.setSubmitted(submittedReportInfo); + ApplicationManager.getApplication().invokeLater(() -> { + if (!dialogClosed) { + updateOnSubmit(); + } + }); }); } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java b/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java index 9ef2e3764c71..9eac82b10387 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java @@ -152,12 +152,7 @@ public class IdeMessagePanel extends JPanel implements MessagePoolListener, Icon private void updateState(final IdeFatalErrorsIcon.State state) { myIdeFatal.setState(state); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - setVisible(state != IdeFatalErrorsIcon.State.NoErrors); - } - }); + UIUtil.invokeLaterIfNeeded(() -> setVisible(state != IdeFatalErrorsIcon.State.NoErrors)); } private void disposeDialog(final IdeErrorsDialog listDialog) { @@ -223,24 +218,22 @@ public class IdeMessagePanel extends JPanel implements MessagePoolListener, Icon myNotificationPopupAlreadyShown = false; } else if (state == IdeFatalErrorsIcon.State.UnreadErrors && !myNotificationPopupAlreadyShown) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - String notificationText = tryGetFromMessages(myMessagePool.getFatalErrors(false, false)); - if (NotificationsManagerImpl.newEnabled()) { - showErrorNotification(notificationText); - return; - } - if (notificationText == null) { - notificationText = INTERNAL_ERROR_NOTICE; - } - final JLabel label = new JLabel(notificationText); - label.setIcon(AllIcons.Ide.FatalError); - new NotificationPopup(IdeMessagePanel.this, label, LightColors.RED, false, new ActionListener() { - public void actionPerformed(ActionEvent e) { - _openFatals(null); - } - }, true); + SwingUtilities.invokeLater(() -> { + String notificationText = tryGetFromMessages(myMessagePool.getFatalErrors(false, false)); + if (NotificationsManagerImpl.newEnabled()) { + showErrorNotification(notificationText); + return; } + if (notificationText == null) { + notificationText = INTERNAL_ERROR_NOTICE; + } + final JLabel label = new JLabel(notificationText); + label.setIcon(AllIcons.Ide.FatalError); + new NotificationPopup(IdeMessagePanel.this, label, LightColors.RED, false, new ActionListener() { + public void actionPerformed(ActionEvent e) { + _openFatals(null); + } + }, true); }); myNotificationPopupAlreadyShown = true; } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java b/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java index b124e141b572..48d45962cdd0 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java @@ -157,30 +157,24 @@ public class OutOfMemoryDialog extends DialogWrapper { myDumpMessageLabel.setVisible(true); myDumpMessageLabel.setText("Dumping memory..."); - Runnable task = new Runnable() { - @Override - public void run() { - TimeoutUtil.sleep(250); // to give UI chance to update - String message = ""; - try { - String name = ApplicationNamesInfo.getInstance().getLowercaseProductName(); - String path = SystemProperties.getUserHome() + File.separator + "heapDump-" + name + '-' + System.currentTimeMillis() + ".hprof.zip"; - MemoryDumpHelper.captureMemoryDumpZipped(path); - message = "Dumped to " + path; - } - catch (Throwable t) { - message = "Error: " + t.getMessage(); - } - finally { - final String _message = message; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myDumpMessageLabel.setText(_message); - enableControls(true); - } - }); - } + Runnable task = () -> { + TimeoutUtil.sleep(250); // to give UI chance to update + String message = ""; + try { + String name = ApplicationNamesInfo.getInstance().getLowercaseProductName(); + String path = SystemProperties.getUserHome() + File.separator + "heapDump-" + name + '-' + System.currentTimeMillis() + ".hprof.zip"; + MemoryDumpHelper.captureMemoryDumpZipped(path); + message = "Dumped to " + path; + } + catch (Throwable t) { + message = "Error: " + t.getMessage(); + } + finally { + final String _message = message; + SwingUtilities.invokeLater(() -> { + myDumpMessageLabel.setText(_message); + enableControls(true); + }); } }; new Thread(task, "OOME Heap Dump").start(); diff --git a/platform/platform-impl/src/com/intellij/diagnostic/errordialog/DisablePluginWarningDialog.java b/platform/platform-impl/src/com/intellij/diagnostic/errordialog/DisablePluginWarningDialog.java index 3130b4aed190..8c3d0e2b805a 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/errordialog/DisablePluginWarningDialog.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/errordialog/DisablePluginWarningDialog.java @@ -48,12 +48,7 @@ public class DisablePluginWarningDialog extends DialogWrapper { public static void disablePlugin(@NotNull PluginId pluginId, @NotNull JComponent parentComponent) { IdeaPluginDescriptor plugin = PluginManager.getPlugin(pluginId); final Ref hasDependants = new Ref(false); - PluginManagerCore.checkDependants(plugin, new Function() { - @Override - public IdeaPluginDescriptor fun(PluginId pluginId) { - return PluginManager.getPlugin(pluginId); - } - }, new Condition() { + PluginManagerCore.checkDependants(plugin, pluginId1 -> PluginManager.getPlugin(pluginId1), new Condition() { @Override public boolean value(PluginId pluginId) { if (PluginManagerCore.CORE_PLUGIN_ID.equals(pluginId.getIdString())) { diff --git a/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java b/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java index 3eb4730d0308..b0b8b0ce5494 100644 --- a/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java +++ b/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java @@ -87,11 +87,8 @@ public class DelayedDocumentWatcher { @Override public void beforeAllDocumentsSaving() { myDocumentSavingInProgress = true; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myDocumentSavingInProgress = false; - } + ApplicationManager.getApplication().invokeLater(() -> { + myDocumentSavingInProgress = false; }, ModalityState.any()); } }); @@ -149,49 +146,40 @@ public class DelayedDocumentWatcher { @Override public void run() { final int oldModificationStamp = myModificationStamp; - asyncCheckErrors(myChangedFiles, new Consumer() { - @Override - public void consume(Boolean errorsFound) { - if (myModificationStamp != oldModificationStamp) { - // 'documentChanged' event was raised during async checking files for errors - // Do nothing in that case, this method will be invoked subsequently. - return; - } - if (errorsFound) { - // Do nothing, if some changed file has syntax errors. - // This method will be invoked subsequently, when syntax errors are fixed. - return; - } - myChangedFiles.clear(); - myModificationStampConsumer.consume(myModificationStamp); + asyncCheckErrors(myChangedFiles, errorsFound -> { + if (myModificationStamp != oldModificationStamp) { + // 'documentChanged' event was raised during async checking files for errors + // Do nothing in that case, this method will be invoked subsequently. + return; } + if (errorsFound) { + // Do nothing, if some changed file has syntax errors. + // This method will be invoked subsequently, when syntax errors are fixed. + return; + } + myChangedFiles.clear(); + myModificationStampConsumer.consume(myModificationStamp); }); } } private void asyncCheckErrors(@NotNull final Collection files, @NotNull final Consumer errorsFoundConsumer) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final boolean errorsFound = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - for (VirtualFile file : files) { - if (PsiErrorElementUtil.hasErrors(myProject, file)) { - return true; - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final boolean errorsFound = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public Boolean compute() { + for (VirtualFile file : files) { + if (PsiErrorElementUtil.hasErrors(myProject, file)) { + return true; } - return false; } - }); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - errorsFoundConsumer.consume(errorsFound); - } - }, ModalityState.any()); - } + return false; + } + }); + ApplicationManager.getApplication().invokeLater(() -> { + errorsFoundConsumer.consume(errorsFound); + }, ModalityState.any()); }); } } diff --git a/platform/platform-impl/src/com/intellij/execution/ExecutableValidator.java b/platform/platform-impl/src/com/intellij/execution/ExecutableValidator.java index b26a9e430141..1c6c78b95cb4 100644 --- a/platform/platform-impl/src/com/intellij/execution/ExecutableValidator.java +++ b/platform/platform-impl/src/com/intellij/execution/ExecutableValidator.java @@ -211,12 +211,7 @@ public abstract class ExecutableValidator { if (!isExecutableValid(getCurrentExecutable())) { if (Messages.OK == showMessage(parentComponent)) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showSettings(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> showSettings()); } return false; } diff --git a/platform/platform-impl/src/com/intellij/execution/impl/ConsoleViewUtil.java b/platform/platform-impl/src/com/intellij/execution/impl/ConsoleViewUtil.java index 00020f5ada47..338cb602916a 100644 --- a/platform/platform-impl/src/com/intellij/execution/impl/ConsoleViewUtil.java +++ b/platform/platform-impl/src/com/intellij/execution/impl/ConsoleViewUtil.java @@ -66,31 +66,28 @@ public class ConsoleViewUtil { } public static void setupConsoleEditor(@NotNull final EditorEx editor, final boolean foldingOutlineShown, final boolean lineMarkerAreaShown) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - editor.setSoftWrapAppliancePlace(SoftWrapAppliancePlaces.CONSOLE); + ApplicationManager.getApplication().runReadAction(() -> { + editor.setSoftWrapAppliancePlace(SoftWrapAppliancePlaces.CONSOLE); - final EditorSettings editorSettings = editor.getSettings(); - editorSettings.setLineMarkerAreaShown(lineMarkerAreaShown); - editorSettings.setIndentGuidesShown(false); - editorSettings.setLineNumbersShown(false); - editorSettings.setFoldingOutlineShown(foldingOutlineShown); - editorSettings.setAdditionalPageAtBottom(false); - editorSettings.setAdditionalColumnsCount(0); - editorSettings.setAdditionalLinesCount(0); - editorSettings.setRightMarginShown(false); - editorSettings.setCaretRowShown(false); - editor.getGutterComponentEx().setPaintBackground(false); + final EditorSettings editorSettings = editor.getSettings(); + editorSettings.setLineMarkerAreaShown(lineMarkerAreaShown); + editorSettings.setIndentGuidesShown(false); + editorSettings.setLineNumbersShown(false); + editorSettings.setFoldingOutlineShown(foldingOutlineShown); + editorSettings.setAdditionalPageAtBottom(false); + editorSettings.setAdditionalColumnsCount(0); + editorSettings.setAdditionalLinesCount(0); + editorSettings.setRightMarginShown(false); + editorSettings.setCaretRowShown(false); + editor.getGutterComponentEx().setPaintBackground(false); - editor.putUserData(EDITOR_IS_CONSOLE_VIEW, true); + editor.putUserData(EDITOR_IS_CONSOLE_VIEW, true); - final DelegateColorScheme scheme = updateConsoleColorScheme(editor.getColorsScheme()); - if (UISettings.getInstance().PRESENTATION_MODE) { - scheme.setEditorFontSize(UISettings.getInstance().PRESENTATION_MODE_FONT_SIZE); - } - editor.setColorsScheme(scheme); + final DelegateColorScheme scheme = updateConsoleColorScheme(editor.getColorsScheme()); + if (UISettings.getInstance().PRESENTATION_MODE) { + scheme.setEditorFontSize(UISettings.getInstance().PRESENTATION_MODE_FONT_SIZE); } + editor.setColorsScheme(scheme); }); } diff --git a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java index 84c043df1e83..1abe6434e97c 100644 --- a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java +++ b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java @@ -131,19 +131,16 @@ public class EditorHyperlinkSupport { if (range != null) { final HyperlinkInfo hyperlinkInfo = getHyperlinkInfo(range); if (hyperlinkInfo != null) { - return new Runnable() { - @Override - public void run() { - if (hyperlinkInfo instanceof HyperlinkInfoBase) { - final Point point = myEditor.logicalPositionToXY(logical); - final MouseEvent event = new MouseEvent(myEditor.getContentComponent(), 0, 0, 0, point.x, point.y, 1, false); - ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(event)); - } - else { - hyperlinkInfo.navigate(myProject); - } - linkFollowed(myEditor, getHyperlinks(0, myEditor.getDocument().getTextLength(),myEditor), range); + return () -> { + if (hyperlinkInfo instanceof HyperlinkInfoBase) { + final Point point = myEditor.logicalPositionToXY(logical); + final MouseEvent event = new MouseEvent(myEditor.getContentComponent(), 0, 0, 0, point.x, point.y, 1, false); + ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(event)); } + else { + hyperlinkInfo.navigate(myProject); + } + linkFollowed(myEditor, getHyperlinks(0, myEditor.getDocument().getTextLength(),myEditor), range); }; } } diff --git a/platform/platform-impl/src/com/intellij/execution/process/impl/ProcessListUtil.java b/platform/platform-impl/src/com/intellij/execution/process/impl/ProcessListUtil.java index fc52580be38e..21e83f3730c5 100644 --- a/platform/platform-impl/src/com/intellij/execution/process/impl/ProcessListUtil.java +++ b/platform/platform-impl/src/com/intellij/execution/process/impl/ProcessListUtil.java @@ -167,20 +167,8 @@ public class ProcessListUtil { // 12 S user ./command argument list return parseCommandOutput(Arrays.asList("/bin/ps", "-a", "-x", "-o", "pid,state,user,comm"), - new NullableFunction>() { - @Nullable - @Override - public List fun(final String commandOnly) { - return parseCommandOutput(Arrays.asList("/bin/ps", "-a", "-x", "-o", "pid,state,user,command"), - new NullableFunction>() { - @Nullable - @Override - public List fun(String full) { - return parseMacOutput(commandOnly, full); - } - }); - } - }); + commandOnly -> parseCommandOutput(Arrays.asList("/bin/ps", "-a", "-x", "-o", "pid,state,user,command"), + full -> parseMacOutput(commandOnly, full))); } @@ -268,13 +256,7 @@ public class ProcessListUtil { @Nullable static List getProcessList_WindowsWMIC() { return parseCommandOutput(Arrays.asList("wmic.exe", "path", "win32_process", "get", "Caption,Processid,Commandline,ExecutablePath"), - new NullableFunction>() { - @Nullable - @Override - public List fun(String output) { - return parseWMICOutput(output); - } - }); + output -> parseWMICOutput(output)); } @Nullable @@ -326,13 +308,7 @@ public class ProcessListUtil { @Nullable static List getProcessList_WindowsTaskList() { return parseCommandOutput(Arrays.asList("tasklist.exe", "/fo", "csv", "/nh", "/v"), - new NullableFunction>() { - @Nullable - @Override - public List fun(String output) { - return parseListTasksOutput(output); - } - }); + output -> parseListTasksOutput(output)); } @Nullable diff --git a/platform/platform-impl/src/com/intellij/externalDependencies/impl/CheckRequiredPluginsActivity.java b/platform/platform-impl/src/com/intellij/externalDependencies/impl/CheckRequiredPluginsActivity.java index aa1723fdb94c..ca4a462dda5c 100644 --- a/platform/platform-impl/src/com/intellij/externalDependencies/impl/CheckRequiredPluginsActivity.java +++ b/platform/platform-impl/src/com/intellij/externalDependencies/impl/CheckRequiredPluginsActivity.java @@ -126,12 +126,7 @@ public class CheckRequiredPluginsActivity implements StartupActivity, DumbAware for (PluginId pluginId : notInstalled) { pluginIds.add(pluginId.getIdString()); } - PluginsAdvertiser.installAndEnablePlugins(pluginIds, new Runnable() { - @Override - public void run() { - notification.expire(); - } - }); + PluginsAdvertiser.installAndEnablePlugins(pluginIds, () -> notification.expire()); } } } diff --git a/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesConfigurable.java b/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesConfigurable.java index 64923f7ff141..ce2d5cfc43a7 100644 --- a/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesConfigurable.java +++ b/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesConfigurable.java @@ -174,12 +174,7 @@ public class ExternalDependenciesConfigurable implements SearchableConfigurable, if (!original.getPluginId().isEmpty() && !pluginIds.contains(original.getPluginId())) { pluginIds.add(original.getPluginId()); } - Collections.sort(pluginIds, new Comparator() { - @Override - public int compare(String o1, String o2) { - return getPluginNameById(o1).compareToIgnoreCase(getPluginNameById(o2)); - } - }); + Collections.sort(pluginIds, (o1, o2) -> getPluginNameById(o1).compareToIgnoreCase(getPluginNameById(o2))); final ComboBox pluginChooser = new ComboBox(ArrayUtilRt.toStringArray(pluginIds), 250); pluginChooser.setRenderer(new ListCellRendererWrapper() { diff --git a/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesManagerImpl.java b/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesManagerImpl.java index 06ffe4cb92db..73adfb3b5065 100644 --- a/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/externalDependencies/impl/ExternalDependenciesManagerImpl.java @@ -47,14 +47,11 @@ public class ExternalDependenciesManagerImpl extends ExternalDependenciesManager myProject = project; } - private static final Comparator DEPENDENCY_COMPARATOR = new Comparator() { - @Override - public int compare(ProjectExternalDependency o1, ProjectExternalDependency o2) { - int i = o1.getClass().getSimpleName().compareToIgnoreCase(o2.getClass().getSimpleName()); - if (i != 0) return i; - //noinspection unchecked - return ((Comparable)o1).compareTo(o2); - } + private static final Comparator DEPENDENCY_COMPARATOR = (o1, o2) -> { + int i = o1.getClass().getSimpleName().compareToIgnoreCase(o2.getClass().getSimpleName()); + if (i != 0) return i; + //noinspection unchecked + return ((Comparable)o1).compareTo(o2); }; private List myDependencies = new ArrayList(); diff --git a/platform/platform-impl/src/com/intellij/featureStatistics/actions/ShowFeatureUsageStatisticsDialog.java b/platform/platform-impl/src/com/intellij/featureStatistics/actions/ShowFeatureUsageStatisticsDialog.java index c7f2e2fd492c..fbdeaa97811f 100644 --- a/platform/platform-impl/src/com/intellij/featureStatistics/actions/ShowFeatureUsageStatisticsDialog.java +++ b/platform/platform-impl/src/com/intellij/featureStatistics/actions/ShowFeatureUsageStatisticsDialog.java @@ -50,26 +50,12 @@ import java.util.Date; public class ShowFeatureUsageStatisticsDialog extends DialogWrapper { private static final Logger LOG = Logger.getInstance("#com.intellij.featureStatistics.actions.ShowFeatureUsageStatisticsDialog"); - private static final Comparator DISPLAY_NAME_COMPARATOR = new Comparator() { - public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) { - return fd1.getDisplayName().compareTo(fd2.getDisplayName()); - } - }; - private static final Comparator GROUP_NAME_COMPARATOR = new Comparator() { - public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) { - return getGroupName(fd1).compareTo(getGroupName(fd2)); - } - }; - private static final Comparator USAGE_COUNT_COMPARATOR = new Comparator() { - public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) { - return fd1.getUsageCount() - fd2.getUsageCount(); - } - }; - private static final Comparator LAST_USED_COMPARATOR = new Comparator() { - public int compare(FeatureDescriptor fd1, FeatureDescriptor fd2) { - return new Date(fd2.getLastTimeUsed()).compareTo(new Date(fd1.getLastTimeUsed())); - } - }; + private static final Comparator DISPLAY_NAME_COMPARATOR = + (fd1, fd2) -> fd1.getDisplayName().compareTo(fd2.getDisplayName()); + private static final Comparator GROUP_NAME_COMPARATOR = (fd1, fd2) -> getGroupName(fd1).compareTo(getGroupName(fd2)); + private static final Comparator USAGE_COUNT_COMPARATOR = (fd1, fd2) -> fd1.getUsageCount() - fd2.getUsageCount(); + private static final Comparator LAST_USED_COMPARATOR = + (fd1, fd2) -> new Date(fd2.getLastTimeUsed()).compareTo(new Date(fd1.getLastTimeUsed())); private static final ColumnInfo DISPLAY_NAME = new ColumnInfo(FeatureStatisticsBundle.message("feature.statistics.column.feature")) { public String valueOf(FeatureDescriptor featureDescriptor) { diff --git a/platform/platform-impl/src/com/intellij/ide/ClipboardSynchronizer.java b/platform/platform-impl/src/com/intellij/ide/ClipboardSynchronizer.java index 2779f139927d..6727ecd3c639 100644 --- a/platform/platform-impl/src/com/intellij/ide/ClipboardSynchronizer.java +++ b/platform/platform-impl/src/com/intellij/ide/ClipboardSynchronizer.java @@ -245,13 +245,10 @@ public class ClipboardSynchronizer implements ApplicationComponent { private static Transferable getContentsSafe() { final FutureResult result = new FutureResult(); - Foundation.executeOnMainThread(new Runnable() { - @Override - public void run() { - Transferable transferable = getClipboardContentNatively(); - if (transferable != null) { - result.set(transferable); - } + Foundation.executeOnMainThread(() -> { + Transferable transferable = getClipboardContentNatively(); + if (transferable != null) { + result.set(transferable); } }, true, false); diff --git a/platform/platform-impl/src/com/intellij/ide/CommandLineProcessor.java b/platform/platform-impl/src/com/intellij/ide/CommandLineProcessor.java index d0bed22e870c..1786904fd9d2 100644 --- a/platform/platform-impl/src/com/intellij/ide/CommandLineProcessor.java +++ b/platform/platform-impl/src/com/intellij/ide/CommandLineProcessor.java @@ -54,11 +54,9 @@ public class CommandLineProcessor { public static void openFileOrProject(final String name) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (name != null) { - doOpenFileOrProject(name); - } + SwingUtilities.invokeLater(() -> { + if (name != null) { + doOpenFileOrProject(name); } }); } @@ -151,11 +149,8 @@ public class CommandLineProcessor { try { final String url = URLDecoder.decode(command, "UTF-8"); JetBrainsProtocolHandler.processJetBrainsLauncherParameters(url); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - JBProtocolCommand.handleCurrentCommand(); - } + ApplicationManager.getApplication().invokeLater(() -> { + JBProtocolCommand.handleCurrentCommand(); }, ModalityState.any()); } catch (UnsupportedEncodingException e) { diff --git a/platform/platform-impl/src/com/intellij/ide/FileChangedNotificationProvider.java b/platform/platform-impl/src/com/intellij/ide/FileChangedNotificationProvider.java index 5417155a3dbd..141b36a56ff5 100644 --- a/platform/platform-impl/src/com/intellij/ide/FileChangedNotificationProvider.java +++ b/platform/platform-impl/src/com/intellij/ide/FileChangedNotificationProvider.java @@ -105,13 +105,10 @@ public class FileChangedNotificationProvider extends EditorNotifications.Provide private EditorNotificationPanel createPanel(@NotNull final VirtualFile file) { EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(IdeBundle.message("file.changed.externally.message")); - panel.createActionLabel(IdeBundle.message("file.changed.externally.reload"), new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed()) { - file.refresh(false, false); - EditorNotifications.getInstance(myProject).updateNotifications(file); - } + panel.createActionLabel(IdeBundle.message("file.changed.externally.reload"), () -> { + if (!myProject.isDisposed()) { + file.refresh(false, false); + EditorNotifications.getInstance(myProject).updateNotifications(file); } }); return panel; diff --git a/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java index 150166b86bf4..87d75bec7f74 100644 --- a/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java @@ -64,13 +64,10 @@ public class FrameStateManagerImpl extends FrameStateManager { @Override public void applicationDeactivated(IdeFrame ideFrame) { mySyncAlarm.cancelAllRequests(); - mySyncAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!app.isActive() && !app.isDisposed()) { - myShouldSynchronize = true; - fireDeactivationEvent(); - } + mySyncAlarm.addRequest(() -> { + if (!app.isActive() && !app.isDisposed()) { + myShouldSynchronize = true; + fireDeactivationEvent(); } }, 200); } diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index 59f4c14f09dd..aa75d5ffc1b7 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -188,12 +188,9 @@ public class IdeEventQueue extends EventQueue { myIdleTimeCounterAlarm.cancelAllRequests(); myLastActiveTime = System.currentTimeMillis(); - myIdleTimeCounterAlarm.addRequest(new Runnable() { - @Override - public void run() { - myIdleTime += System.currentTimeMillis() - myLastActiveTime; - addIdleTimeCounterRequest(); - } + myIdleTimeCounterAlarm.addRequest(() -> { + myIdleTime += System.currentTimeMillis() - myLastActiveTime; + addIdleTimeCounterRequest(); }, 20000, ModalityState.NON_MODAL); } @@ -244,12 +241,7 @@ public class IdeEventQueue extends EventQueue { myIdleListeners.add(runnable); final MyFireIdleRequest request = new MyFireIdleRequest(runnable, timeout); myListener2Request.put(runnable, request); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myIdleRequestsAlarm.addRequest(request, timeout); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myIdleRequestsAlarm.addRequest(request, timeout)); } } @@ -655,12 +647,7 @@ public class IdeEventQueue extends EventQueue { new MouseEvent(me.getComponent(), me.getID(), System.currentTimeMillis(), me.getModifiers(), me.getX(), me.getY(), 1, me.isPopupTrigger(), me.getButton()); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - dispatchEvent(toDispatch); - } - }); + SwingUtilities.invokeLater(() -> dispatchEvent(toDispatch)); } if (!myMouseEventDispatcher.dispatchMouseEvent(me)) { defaultDispatchEvent(e); @@ -1041,12 +1028,9 @@ public class IdeEventQueue extends EventQueue { } else { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myReady.add(runnable); - maybeReady(); - } + SwingUtilities.invokeLater(() -> { + myReady.add(runnable); + maybeReady(); }); } } @@ -1088,24 +1072,21 @@ public class IdeEventQueue extends EventQueue { } else if (component != null) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - final Window window = UIUtil.getWindow(component); - if (window == null || !window.isActive()) { - return; - } - myWaitingForAltRelease = true; - if (myRobot == null) { - myRobot = new Robot(); - } - myRobot.keyPress(KeyEvent.VK_ALT); - myRobot.keyRelease(KeyEvent.VK_ALT); + SwingUtilities.invokeLater(() -> { + try { + final Window window = UIUtil.getWindow(component); + if (window == null || !window.isActive()) { + return; } - catch (AWTException e1) { - LOG.debug(e1); + myWaitingForAltRelease = true; + if (myRobot == null) { + myRobot = new Robot(); } + myRobot.keyPress(KeyEvent.VK_ALT); + myRobot.keyRelease(KeyEvent.VK_ALT); + } + catch (AWTException e1) { + LOG.debug(e1); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/IdePopupManager.java b/platform/platform-impl/src/com/intellij/ide/IdePopupManager.java index 0131dda4ac0f..a610e0ee0b68 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdePopupManager.java +++ b/platform/platform-impl/src/com/intellij/ide/IdePopupManager.java @@ -50,39 +50,37 @@ public final class IdePopupManager implements IdeEventQueue.EventDispatcher { LOG.assertTrue(isPopupActive()); if (e.getID() == WindowEvent.WINDOW_LOST_FOCUS) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (!isPopupActive()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (!isPopupActive()) return; - boolean shouldCloseAllPopup = false; + boolean shouldCloseAllPopup = false; - Window focused = ((WindowEvent)e).getOppositeWindow(); - if (focused == null) { - focused = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); - } + Window focused = ((WindowEvent)e).getOppositeWindow(); + if (focused == null) { + focused = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); + } - if (focused == null) { + if (focused == null) { + shouldCloseAllPopup = true; + } + + Component ultimateParentForFocusedComponent = UIUtil.findUltimateParent(focused); + Component ultimateParentForEventWindow = UIUtil.findUltimateParent(((WindowEvent)e).getWindow()); + + if (!shouldCloseAllPopup && ultimateParentForEventWindow == null || ultimateParentForFocusedComponent == null) { + shouldCloseAllPopup = true; + } + + if (!shouldCloseAllPopup && ultimateParentForEventWindow instanceof IdeFrameEx) { + IdeFrameEx ultimateParentWindowForEvent = ((IdeFrameEx)ultimateParentForEventWindow); + if (ultimateParentWindowForEvent.isInFullScreen() + && !ultimateParentForFocusedComponent.equals(ultimateParentForEventWindow)) { shouldCloseAllPopup = true; } + } - Component ultimateParentForFocusedComponent = UIUtil.findUltimateParent(focused); - Component ultimateParentForEventWindow = UIUtil.findUltimateParent(((WindowEvent)e).getWindow()); - - if (!shouldCloseAllPopup && ultimateParentForEventWindow == null || ultimateParentForFocusedComponent == null) { - shouldCloseAllPopup = true; - } - - if (!shouldCloseAllPopup && ultimateParentForEventWindow instanceof IdeFrameEx) { - IdeFrameEx ultimateParentWindowForEvent = ((IdeFrameEx)ultimateParentForEventWindow); - if (ultimateParentWindowForEvent.isInFullScreen() - && !ultimateParentForFocusedComponent.equals(ultimateParentForEventWindow)) { - shouldCloseAllPopup = true; - } - } - - if (shouldCloseAllPopup) { - closeAllPopups(); - } + if (shouldCloseAllPopup) { + closeAllPopups(); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java b/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java index 3519a2969d0b..c4a88552ee43 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java @@ -234,24 +234,21 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener myQueuedComponent = tooltip.getComponent(); myQueuedTooltip = tooltip; - myShowRequest = new Runnable() { - @Override - public void run() { - if (myShowRequest == null) { - return; - } + myShowRequest = () -> { + if (myShowRequest == null) { + return; + } - if (myQueuedComponent != tooltip.getComponent() || !tooltip.getComponent().isShowing()) { - hideCurrent(null, tooltip, null, null, animationEnabled); - return; - } + if (myQueuedComponent != tooltip.getComponent() || !tooltip.getComponent().isShowing()) { + hideCurrent(null, tooltip, null, null, animationEnabled); + return; + } - if (tooltip.beforeShow()) { - show(tooltip, null, animationEnabled); - } - else { - hideCurrent(null, tooltip, null, null, animationEnabled); - } + if (tooltip.beforeShow()) { + show(tooltip, null, animationEnabled); + } + else { + hideCurrent(null, tooltip, null, null, animationEnabled); } }; @@ -346,12 +343,9 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener }); myCurrentTipUi.show(new RelativePoint(tooltip.getComponent(), effectivePoint), tooltip.getPreferredPosition()); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myCurrentTooltip == tooltip && tooltip.canBeDismissedOnTimeout()) { - hideCurrent(null, null, null); - } + myAlarm.addRequest(() -> { + if (myCurrentTooltip == tooltip && tooltip.canBeDismissedOnTimeout()) { + hideCurrent(null, null, null); } }, tooltip.getDismissDelay()); } @@ -448,13 +442,10 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener } } - myHideRunnable = new Runnable() { - @Override - public void run() { - if (myHideRunnable != null) { - hideCurrentNow(animationEnabled); - myHideRunnable = null; - } + myHideRunnable = () -> { + if (myHideRunnable != null) { + hideCurrentNow(animationEnabled); + myHideRunnable = null; } }; @@ -475,12 +466,7 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener myCurrentTipUi.hide(); myCurrentTooltip.onHidden(); myShowDelay = false; - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myShowDelay = true; - } - }, Registry.intValue("ide.tooltip.reshowDelay")); + myAlarm.addRequest(() -> myShowDelay = true, Registry.intValue("ide.tooltip.reshowDelay")); } myShowRequest = null; diff --git a/platform/platform-impl/src/com/intellij/ide/MacOSApplicationProvider.java b/platform/platform-impl/src/com/intellij/ide/MacOSApplicationProvider.java index 67666ba85877..1590561a1f20 100644 --- a/platform/platform-impl/src/com/intellij/ide/MacOSApplicationProvider.java +++ b/platform/platform-impl/src/com/intellij/ide/MacOSApplicationProvider.java @@ -58,13 +58,10 @@ public class MacOSApplicationProvider implements ApplicationComponent { @SuppressWarnings("unused") public void callback(ID self, String selector) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ActionManagerEx am = ActionManagerEx.getInstanceEx(); - MouseEvent me = new MouseEvent(JOptionPane.getRootFrame(), MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, 0, 0, 1, false); - am.tryToExecute(am.getAction("CheckForUpdate"), me, null, null, false); - } + SwingUtilities.invokeLater(() -> { + ActionManagerEx am = ActionManagerEx.getInstanceEx(); + MouseEvent me = new MouseEvent(JOptionPane.getRootFrame(), MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, 0, 0, 1, false); + am.tryToExecute(am.getAction("CheckForUpdate"), me, null, null, false); }); } }; diff --git a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java index 92f74436c627..31a8ffa609a1 100644 --- a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java +++ b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java @@ -339,19 +339,16 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im if (!isDuplicatesCacheUpdating) { isDuplicatesCacheUpdating = true; //assuming that this check happens only on EDT. So, no synchronised block or double-checked locking needed - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - Set names = ContainerUtil.newHashSet(); - final HashSet duplicates = ContainerUtil.newHashSet(); - for (String path : ContainerUtil.concat(openedPaths, recentPaths)) { - if (!names.add(getProjectName(path))) { - duplicates.add(path); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + Set names = ContainerUtil.newHashSet(); + final HashSet duplicates = ContainerUtil.newHashSet(); + for (String path : ContainerUtil.concat(openedPaths, recentPaths)) { + if (!names.add(getProjectName(path))) { + duplicates.add(path); } - myDuplicatesCache = duplicates; - isDuplicatesCacheUpdating = false; } + myDuplicatesCache = duplicates; + isDuplicatesCacheUpdating = false; }); } return ContainerUtil.newHashSet(); @@ -541,14 +538,11 @@ public abstract class RecentProjectsManagerBase extends RecentProjectsManager im synchronized (myNamesToResolve) { myNamesToResolve.add(path); } - myNamesResolver.addRequest(new Runnable() { - @Override - public void run() { - final Set paths = Collections.synchronizedSet(myNamesToResolve); - synchronized (myNamesToResolve) {myNamesToResolve.clear();} - for (String p : paths) { - myNameCache.put(p, readProjectName(p)); - } + myNamesResolver.addRequest(() -> { + final Set paths = Collections.synchronizedSet(myNamesToResolve); + synchronized (myNamesToResolve) {myNamesToResolve.clear();} + for (String p : paths) { + myNameCache.put(p, readProjectName(p)); } }, 50); return FileUtilRt.getNameWithoutExtension(new File(path).getName()); diff --git a/platform/platform-impl/src/com/intellij/ide/RemoteDesktopDetector.java b/platform/platform-impl/src/com/intellij/ide/RemoteDesktopDetector.java index cf45db4d1455..4796e2c52a1c 100644 --- a/platform/platform-impl/src/com/intellij/ide/RemoteDesktopDetector.java +++ b/platform/platform-impl/src/com/intellij/ide/RemoteDesktopDetector.java @@ -59,15 +59,11 @@ public class RemoteDesktopDetector { if (myRemoteDesktopConnected) { // We postpone notification to avoid recursive initialization of RemoteDesktopDetector // (in case it's initialized by request from com.intellij.notification.EventLog) - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, - ApplicationBundle.message("remote.desktop.detected.title"), - ApplicationBundle - .message("remote.desktop.detected.message"), - NotificationType.INFORMATION)); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, + ApplicationBundle.message("remote.desktop.detected.title"), + ApplicationBundle + .message("remote.desktop.detected.message"), + NotificationType.INFORMATION))); } } } diff --git a/platform/platform-impl/src/com/intellij/ide/SwingCleanuper.java b/platform/platform-impl/src/com/intellij/ide/SwingCleanuper.java index 0ed5d2eca543..26ff09e988d3 100644 --- a/platform/platform-impl/src/com/intellij/ide/SwingCleanuper.java +++ b/platform/platform-impl/src/com/intellij/ide/SwingCleanuper.java @@ -71,86 +71,82 @@ public final class SwingCleanuper implements ApplicationComponent{ public void projectClosed(final Project project){ myAlarm.cancelAllRequests(); myAlarm.addRequest( - new Runnable() { - public void run() { - // request focus into some focusable component inside IdeFrame - final IdeFrameImpl frame; - final Window window=KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); - if(window instanceof IdeFrameImpl){ - frame=(IdeFrameImpl)window; - }else{ - frame=(IdeFrameImpl)SwingUtilities.getAncestorOfClass(IdeFrameImpl.class,window); - } - if(frame!=null){ - final Application app = ApplicationManager.getApplication(); - if (app != null && app.isActive()) { - StatusBar statusBar = frame.getStatusBar(); - if (statusBar != null) ((JComponent)statusBar).requestFocus(); - } + () -> { + // request focus into some focusable component inside IdeFrame + final IdeFrameImpl frame; + final Window window=KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); + if(window instanceof IdeFrameImpl){ + frame=(IdeFrameImpl)window; + }else{ + frame=(IdeFrameImpl)SwingUtilities.getAncestorOfClass(IdeFrameImpl.class,window); + } + if(frame!=null){ + final Application app = ApplicationManager.getApplication(); + if (app != null && app.isActive()) { + StatusBar statusBar = frame.getStatusBar(); + if (statusBar != null) ((JComponent)statusBar).requestFocus(); } + } - //noinspection SSBasedInspection - SwingUtilities.invokeLater( - new Runnable() { - public void run() { + //noinspection SSBasedInspection + SwingUtilities.invokeLater( + () -> { - // KeyboardFocusManager.newFocusOwner - ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "newFocusOwner"); + // KeyboardFocusManager.newFocusOwner + ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "newFocusOwner"); - // Clear "realOppositeComponent", "realOppositeWindow" - final KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - resetField(focusManager, Component.class, "realOppositeComponent"); - resetField(focusManager, Window.class, "realOppositeWindow"); + // Clear "realOppositeComponent", "realOppositeWindow" + final KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); + resetField(focusManager, Component.class, "realOppositeComponent"); + resetField(focusManager, Window.class, "realOppositeWindow"); - // Memory leak on static field in BasicPopupMenuUI + // Memory leak on static field in BasicPopupMenuUI - try { - Object helperObject = ReflectionUtil.getStaticFieldValue(BasicPopupMenuUI.class, Object.class, "menuKeyboardHelper"); - if (helperObject != null) { - resetField(helperObject, Component.class, "lastFocused"); - } - } - catch (Exception e) { - // Ignore - } - - // Memory leak on javax.swing.TransferHandler$SwingDragGestureRecognizer.component - - try{ - DragGestureRecognizer recognizer = ReflectionUtil.getStaticFieldValue(TransferHandler.class, DragGestureRecognizer.class, "recognizer"); - - if (recognizer != null) { // that is memory leak - recognizer.setComponent(null); - } - } - catch (Exception e){ - // Ignore - } - try { - fixJTextComponentMemoryLeak(); - } - catch(Exception e) { - // Ignore - } - - focusManager.setGlobalCurrentFocusCycleRoot(null); //Remove focus leaks - - try { - final Method m = ReflectionUtil.getDeclaredMethod(KeyboardFocusManager.class,"setGlobalFocusOwner", Component.class); - m.invoke(focusManager, new Object[]{null}); - } - catch (Exception e) { - // Ignore - } - - ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "newFocusOwner"); - ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "permanentFocusOwner"); - ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "currentFocusCycleRoot"); + try { + Object helperObject = ReflectionUtil.getStaticFieldValue(BasicPopupMenuUI.class, Object.class, "menuKeyboardHelper"); + if (helperObject != null) { + resetField(helperObject, Component.class, "lastFocused"); } } - ); - } + catch (Exception e) { + // Ignore + } + + // Memory leak on javax.swing.TransferHandler$SwingDragGestureRecognizer.component + + try{ + DragGestureRecognizer recognizer = ReflectionUtil.getStaticFieldValue(TransferHandler.class, DragGestureRecognizer.class, "recognizer"); + + if (recognizer != null) { // that is memory leak + recognizer.setComponent(null); + } + } + catch (Exception e){ + // Ignore + } + try { + fixJTextComponentMemoryLeak(); + } + catch(Exception e) { + // Ignore + } + + focusManager.setGlobalCurrentFocusCycleRoot(null); //Remove focus leaks + + try { + final Method m = ReflectionUtil.getDeclaredMethod(KeyboardFocusManager.class,"setGlobalFocusOwner", Component.class); + m.invoke(focusManager, new Object[]{null}); + } + catch (Exception e) { + // Ignore + } + + ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "newFocusOwner"); + ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "permanentFocusOwner"); + ReflectionUtil.resetStaticField(KeyboardFocusManager.class, "currentFocusCycleRoot"); + } + ); }, 2500 ); diff --git a/platform/platform-impl/src/com/intellij/ide/SystemHealthMonitor.java b/platform/platform-impl/src/com/intellij/ide/SystemHealthMonitor.java index 93971bfd8aa9..cfd9290d3675 100644 --- a/platform/platform-impl/src/com/intellij/ide/SystemHealthMonitor.java +++ b/platform/platform-impl/src/com/intellij/ide/SystemHealthMonitor.java @@ -111,37 +111,34 @@ public class SystemHealthMonitor extends ApplicationComponent.Adapter { app.getMessageBus().connect(app).subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() { @Override public void appFrameCreated(String[] commandLineArgs, @NotNull Ref willOpenProject) { - app.invokeLater(new Runnable() { - @Override - public void run() { - JComponent component = WindowManager.getInstance().findVisibleFrame().getRootPane(); - if (component != null) { - Rectangle rect = component.getVisibleRect(); - JBPopupFactory.getInstance() - .createHtmlTextBalloonBuilder(message, MessageType.WARNING, new HyperlinkAdapter() { - @Override - protected void hyperlinkActivated(HyperlinkEvent e) { - String url = e.getDescription(); - if ("ack".equals(url)) { - myProperties.setValue(ignoreKey, "true"); - } - else { - BrowserUtil.browse(url); - } + app.invokeLater(() -> { + JComponent component = WindowManager.getInstance().findVisibleFrame().getRootPane(); + if (component != null) { + Rectangle rect = component.getVisibleRect(); + JBPopupFactory.getInstance() + .createHtmlTextBalloonBuilder(message, MessageType.WARNING, new HyperlinkAdapter() { + @Override + protected void hyperlinkActivated(HyperlinkEvent e) { + String url = e.getDescription(); + if ("ack".equals(url)) { + myProperties.setValue(ignoreKey, "true"); } - }) - .setFadeoutTime(-1) - .setHideOnFrameResize(false) - .setHideOnLinkClick(true) - .setDisposable(app) - .createBalloon() - .show(new RelativePoint(component, new Point(rect.x + 30, rect.y + rect.height - 10)), Balloon.Position.above); - } - - Notification notification = LOG_GROUP.createNotification(message, NotificationType.WARNING); - notification.setImportant(true); - Notifications.Bus.notify(notification); + else { + BrowserUtil.browse(url); + } + } + }) + .setFadeoutTime(-1) + .setHideOnFrameResize(false) + .setHideOnLinkClick(true) + .setDisposable(app) + .createBalloon() + .show(new RelativePoint(component, new Point(rect.x + 30, rect.y + rect.height - 10)), Balloon.Position.above); } + + Notification notification = LOG_GROUP.createNotification(message, NotificationType.WARNING); + notification.setImportant(true); + Notifications.Bus.notify(notification); }); } }); @@ -165,19 +162,16 @@ public class SystemHealthMonitor extends ApplicationComponent.Adapter { if (!reported.get()) { Future future = ourFreeSpaceCalculation.get(); if (future == null) { - ourFreeSpaceCalculation.set(future = ApplicationManager.getApplication().executeOnPooledThread(new Callable() { - @Override - public Long call() throws Exception { - // file.getUsableSpace() can fail and return 0 e.g. after MacOSX restart or awakening from sleep - // so several times try to recalculate usable space on receiving 0 to be sure - long fileUsableSpace = file.getUsableSpace(); - while (fileUsableSpace == 0) { - TimeoutUtil.sleep(5000); // hopefully we will not hummer disk too much - fileUsableSpace = file.getUsableSpace(); - } - - return fileUsableSpace; + ourFreeSpaceCalculation.set(future = ApplicationManager.getApplication().executeOnPooledThread(() -> { + // file.getUsableSpace() can fail and return 0 e.g. after MacOSX restart or awakening from sleep + // so several times try to recalculate usable space on receiving 0 to be sure + long fileUsableSpace = file.getUsableSpace(); + while (fileUsableSpace == 0) { + TimeoutUtil.sleep(5000); // hopefully we will not hummer disk too much + fileUsableSpace = file.getUsableSpace(); } + + return fileUsableSpace; })); } if (!future.isDone() || future.isCancelled()) { @@ -199,26 +193,20 @@ public class SystemHealthMonitor extends ApplicationComponent.Adapter { reported.compareAndSet(false, true); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - String productName = ApplicationNamesInfo.getInstance().getFullProductName(); - String message = IdeBundle.message("low.disk.space.message", productName); - if (fileUsableSpace < 100 * 1024) { - LOG.warn(message + " (" + fileUsableSpace + ")"); - Messages.showErrorDialog(message, "Fatal Configuration Problem"); + SwingUtilities.invokeLater(() -> { + String productName = ApplicationNamesInfo.getInstance().getFullProductName(); + String message = IdeBundle.message("low.disk.space.message", productName); + if (fileUsableSpace < 100 * 1024) { + LOG.warn(message + " (" + fileUsableSpace + ")"); + Messages.showErrorDialog(message, "Fatal Configuration Problem"); + reported.compareAndSet(true, false); + restart(timeout); + } + else { + GROUP.createNotification(message, file.getPath(), NotificationType.ERROR, null).whenExpired(() -> { reported.compareAndSet(true, false); restart(timeout); - } - else { - GROUP.createNotification(message, file.getPath(), NotificationType.ERROR, null).whenExpired(new Runnable() { - @Override - public void run() { - reported.compareAndSet(true, false); - restart(timeout); - } - }).notify(null); - } + }).notify(null); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/TipOfTheDayManager.java b/platform/platform-impl/src/com/intellij/ide/TipOfTheDayManager.java index b52ea34f7ffc..58f635c31db7 100644 --- a/platform/platform-impl/src/com/intellij/ide/TipOfTheDayManager.java +++ b/platform/platform-impl/src/com/intellij/ide/TipOfTheDayManager.java @@ -33,16 +33,12 @@ public class TipOfTheDayManager implements StartupActivity, DumbAware { myVeryFirstProjectOpening = false; - ToolWindowManager.getInstance(project).invokeLater(new Runnable() { - public void run() { + ToolWindowManager.getInstance(project).invokeLater(() -> { + if (project.isDisposed()) return; + ToolWindowManager.getInstance(project).invokeLater(() -> { if (project.isDisposed()) return; - ToolWindowManager.getInstance(project).invokeLater(new Runnable() { - public void run() { - if (project.isDisposed()) return; - TipDialog.createForProject(project).show(); - } - }); - } + TipDialog.createForProject(project).show(); + }); }); } } diff --git a/platform/platform-impl/src/com/intellij/ide/UiActivityMonitorImpl.java b/platform/platform-impl/src/com/intellij/ide/UiActivityMonitorImpl.java index e9de64905415..a0800a64ad98 100644 --- a/platform/platform-impl/src/com/intellij/ide/UiActivityMonitorImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/UiActivityMonitorImpl.java @@ -83,12 +83,7 @@ public class UiActivityMonitorImpl extends UiActivityMonitor implements Modality @Override public void beforeModalityStateChanged(boolean entering) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - maybeReady(); - } - }); + SwingUtilities.invokeLater(() -> maybeReady()); } public void maybeReady() { @@ -125,24 +120,14 @@ public class UiActivityMonitorImpl extends UiActivityMonitor implements Modality if (!isActive()) return; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBusyContainer(project).addActivity(activity, effectiveModalityState); - } - }); + UIUtil.invokeLaterIfNeeded(() -> getBusyContainer(project).addActivity(activity, effectiveModalityState)); } @Override public void removeActivity(@NotNull final Project project, @NotNull final UiActivity activity) { if (!isActive()) return; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - _getBusy(project).removeActivity(activity); - } - }); + UIUtil.invokeLaterIfNeeded(() -> _getBusy(project).removeActivity(activity)); } @Override @@ -158,24 +143,14 @@ public class UiActivityMonitorImpl extends UiActivityMonitor implements Modality public void addActivity(@NotNull final UiActivity activity, @NotNull final ModalityState effectiveModalityState) { if (!isActive()) return; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBusyContainer(null).addActivity(activity, effectiveModalityState); - } - }); + UIUtil.invokeLaterIfNeeded(() -> getBusyContainer(null).addActivity(activity, effectiveModalityState)); } @Override public void removeActivity(@NotNull final UiActivity activity) { if (!isActive()) return; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - _getBusy(null).removeActivity(activity); - } - }); + UIUtil.invokeLaterIfNeeded(() -> _getBusy(null).removeActivity(activity)); } @NotNull @@ -308,17 +283,14 @@ public class UiActivityMonitorImpl extends UiActivityMonitor implements Modality myQueuedToRemove.add(activity); - Runnable runnable = new Runnable() { - @Override - public void run() { - if (!myQueuedToRemove.contains(activity)) return; + Runnable runnable = () -> { + if (!myQueuedToRemove.contains(activity)) return; - myQueuedToRemove.remove(activity); - myActivities.remove(activity); - myContainer.onActivityRemoved(BusyImpl.this, activity); - - onReady(); - } + myQueuedToRemove.remove(activity); + myActivities.remove(activity); + myContainer.onActivityRemoved(BusyImpl.this, activity); + + onReady(); }; SwingUtilities.invokeLater(runnable); } diff --git a/platform/platform-impl/src/com/intellij/ide/actionMacro/ActionMacroManager.java b/platform/platform-impl/src/com/intellij/ide/actionMacro/ActionMacroManager.java index 7718013bfbd2..91e48da23019 100644 --- a/platform/platform-impl/src/com/intellij/ide/actionMacro/ActionMacroManager.java +++ b/platform/platform-impl/src/com/intellij/ide/actionMacro/ActionMacroManager.java @@ -395,19 +395,11 @@ public class ActionMacroManager implements PersistentStateComponent, Di myIsPlaying = true; runner.run() - .doWhenDone(new Runnable() { - @Override - public void run() { - StatusBar statusBar = frame.getStatusBar(); - statusBar.setInfo("Script execution finished"); - } + .doWhenDone(() -> { + StatusBar statusBar = frame.getStatusBar(); + statusBar.setInfo("Script execution finished"); }) - .doWhenProcessed(new Runnable() { - @Override - public void run() { - myIsPlaying = false; - } - }); + .doWhenProcessed(() -> myIsPlaying = false); } public boolean isRecording() { @@ -512,12 +504,7 @@ public class ActionMacroManager implements PersistentStateComponent, Di @Override public void actionPerformed(AnActionEvent e) { - IdeEventQueue.getInstance().doWhenReady(new Runnable() { - @Override - public void run() { - getInstance().playMacro(myMacro); - } - }); + IdeEventQueue.getInstance().doWhenReady(() -> getInstance().playMacro(myMacro)); } @Override diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ActivateToolWindowAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ActivateToolWindowAction.java index 4dfa4e525c1c..1f722849c513 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ActivateToolWindowAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ActivateToolWindowAction.java @@ -112,11 +112,7 @@ public class ActivateToolWindowAction extends DumbAwareAction { if (event instanceof KeyEvent && event.isShiftDown()) { final Content[] contents = window.getContentManager().getContents(); if (contents.length > 0 && window.getContentManager().getSelectedContent() != contents[0]) { - run = new Runnable() { - public void run() { - window.getContentManager().setSelectedContent(contents[0], true, true); - } - }; + run = () -> window.getContentManager().setSelectedContent(contents[0], true, true); } } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/CloseAllEditorsAction.java b/platform/platform-impl/src/com/intellij/ide/actions/CloseAllEditorsAction.java index b0305317d8ea..576cd5d4165b 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/CloseAllEditorsAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/CloseAllEditorsAction.java @@ -34,22 +34,20 @@ public class CloseAllEditorsAction extends AnAction implements DumbAware { final Project project = e.getData(CommonDataKeys.PROJECT); CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - project, new Runnable(){ - public void run() { - final EditorWindow window = e.getData(EditorWindow.DATA_KEY); - if (window != null){ - final VirtualFile[] files = window.getFiles(); - for (final VirtualFile file : files) { - window.closeFile(file); - } - return; - } - FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project); - VirtualFile selectedFile = fileEditorManager.getSelectedFiles()[0]; - VirtualFile[] openFiles = fileEditorManager.getSiblings(selectedFile); - for (final VirtualFile openFile : openFiles) { - fileEditorManager.closeFile(openFile); + project, () -> { + final EditorWindow window = e.getData(EditorWindow.DATA_KEY); + if (window != null){ + final VirtualFile[] files = window.getFiles(); + for (final VirtualFile file : files) { + window.closeFile(file); } + return; + } + FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project); + VirtualFile selectedFile = fileEditorManager.getSelectedFiles()[0]; + VirtualFile[] openFiles = fileEditorManager.getSiblings(selectedFile); + for (final VirtualFile openFile : openFiles) { + fileEditorManager.closeFile(openFile); } }, IdeBundle.message("command.close.all.editors"), null ); diff --git a/platform/platform-impl/src/com/intellij/ide/actions/CloseEditorsActionBase.java b/platform/platform-impl/src/com/intellij/ide/actions/CloseEditorsActionBase.java index ecf2f41ee3d2..6601ffb758a9 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/CloseEditorsActionBase.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/CloseEditorsActionBase.java @@ -66,13 +66,11 @@ public abstract class CloseEditorsActionBase extends AnAction implements DumbAwa final Project project = e.getData(CommonDataKeys.PROJECT); final CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - project, new Runnable(){ - public void run() { - final ArrayList> filesToClose = getFilesToClose (e); - for (int i = 0; i != filesToClose.size (); ++ i) { - final Pair we = filesToClose.get(i); - we.getSecond ().closeFile (we.getFirst ().getFile ()); - } + project, () -> { + final ArrayList> filesToClose = getFilesToClose (e); + for (int i = 0; i != filesToClose.size (); ++ i) { + final Pair we = filesToClose.get(i); + we.getSecond ().closeFile (we.getFirst ().getFile ()); } }, IdeBundle.message("command.close.all.unmodified.editors"), null ); diff --git a/platform/platform-impl/src/com/intellij/ide/actions/FixLineSeparatorsAction.java b/platform/platform-impl/src/com/intellij/ide/actions/FixLineSeparatorsAction.java index 0a0e00e4200d..aaeeb85df2cd 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/FixLineSeparatorsAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/FixLineSeparatorsAction.java @@ -38,11 +38,9 @@ public class FixLineSeparatorsAction extends AnAction { Project project = e.getData(CommonDataKeys.PROJECT); final VirtualFile[] vFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); if (project == null || vFiles == null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - for (VirtualFile vFile : vFiles) { - fixSeparators(vFile); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + for (VirtualFile vFile : vFiles) { + fixSeparators(vFile); } }, "fixing line separators", null); } @@ -73,15 +71,13 @@ public class FixLineSeparatorsAction extends AnAction { } private static void fixSeparators(final Document document) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - int i = 1; - while(i < document.getLineCount()) { - final int start = document.getLineEndOffset(i); - final int end = document.getLineEndOffset(i) + document.getLineSeparatorLength(i); - document.deleteString(start, end); - i++; - } + ApplicationManager.getApplication().runWriteAction(() -> { + int i = 1; + while(i < document.getLineCount()) { + final int start = document.getLineEndOffset(i); + final int end = document.getLineEndOffset(i) + document.getLineSeparatorLength(i); + document.deleteString(start, end); + i++; } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/GotoLineAction.java b/platform/platform-impl/src/com/intellij/ide/actions/GotoLineAction.java index 682da3e77e3f..d5b8af78bf94 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/GotoLineAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/GotoLineAction.java @@ -39,12 +39,10 @@ public class GotoLineAction extends AnAction implements DumbAware { else { CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand( - project, new Runnable(){ - public void run() { - GotoLineNumberDialog dialog = new GotoLineNumberDialog(project, editor); - dialog.show(); - IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); - } + project, () -> { + GotoLineNumberDialog dialog = new GotoLineNumberDialog(project, editor); + dialog.show(); + IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); }, IdeBundle.message("command.go.to.line"), null diff --git a/platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesAction.java b/platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesAction.java index a35407797b65..fe1f52ed4027 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/InvalidateCachesAction.java @@ -69,12 +69,7 @@ public class InvalidateCachesAction extends AnAction implements DumbAware { } else { warnings += "The following items will also be cleared:\n" - + StringUtil.join(descriptions, new Function() { - @Override - public String fun(String s) { - return " " + s; - } - }, "\n"); + + StringUtil.join(descriptions, s -> " " + s, "\n"); } String message = "The caches will be invalidated and rebuilt on the next startup.\n\n" + diff --git a/platform/platform-impl/src/com/intellij/ide/actions/NextSplitAction.java b/platform/platform-impl/src/com/intellij/ide/actions/NextSplitAction.java index 42b48b46f080..1175bf3a3577 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/NextSplitAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/NextSplitAction.java @@ -32,11 +32,9 @@ public class NextSplitAction extends AnAction implements DumbAware { final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); final CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - project, new Runnable(){ - public void run() { - final FileEditorManagerEx manager = FileEditorManagerEx.getInstanceEx(project); - manager.setCurrentWindow(manager.getNextWindow(manager.getCurrentWindow())); - } + project, () -> { + final FileEditorManagerEx manager = FileEditorManagerEx.getInstanceEx(project); + manager.setCurrentWindow(manager.getNextWindow(manager.getCurrentWindow())); }, IdeBundle.message("command.go.to.next.split"), null ); } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java b/platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java index 884b00f2d827..5e0be6d90835 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.java @@ -55,18 +55,15 @@ public class OpenFileAction extends AnAction implements DumbAware { final FileChooserDescriptor descriptor = showFiles ? new ProjectOrFileChooserDescriptor() : new ProjectOnlyFileChooserDescriptor(); descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, showFiles); - FileChooser.chooseFiles(descriptor, project, VfsUtil.getUserHomeDir(), new Consumer>() { - @Override - public void consume(final List files) { - for (VirtualFile file : files) { - if (!descriptor.isFileSelectable(file)) { - String message = IdeBundle.message("error.dir.contains.no.project", file.getPresentableUrl()); - Messages.showInfoMessage(project, message, IdeBundle.message("title.cannot.open.project")); - return; - } + FileChooser.chooseFiles(descriptor, project, VfsUtil.getUserHomeDir(), files -> { + for (VirtualFile file : files) { + if (!descriptor.isFileSelectable(file)) { + String message = IdeBundle.message("error.dir.contains.no.project", file.getPresentableUrl()); + Messages.showInfoMessage(project, message, IdeBundle.message("title.cannot.open.project")); + return; } - doOpenFile(project, files); } + doOpenFile(project, files); }); } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/PrevSplitAction.java b/platform/platform-impl/src/com/intellij/ide/actions/PrevSplitAction.java index 318e97fd22a6..a7058f9ebe94 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/PrevSplitAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/PrevSplitAction.java @@ -29,11 +29,9 @@ public class PrevSplitAction extends AnAction implements DumbAware { final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); final CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - project, new Runnable(){ - public void run() { - final FileEditorManagerEx manager = FileEditorManagerEx.getInstanceEx(project); - manager.setCurrentWindow(manager.getPrevWindow(manager.getCurrentWindow())); - } + project, () -> { + final FileEditorManagerEx manager = FileEditorManagerEx.getInstanceEx(project); + manager.setCurrentWindow(manager.getPrevWindow(manager.getCurrentWindow())); }, IdeBundle.message("command.go.to.prev.split"), null ); } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/PruneEmptyDirectoriesAction.java b/platform/platform-impl/src/com/intellij/ide/actions/PruneEmptyDirectoriesAction.java index 8f65b31b5f45..b4ba4bf4f6a9 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/PruneEmptyDirectoriesAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/PruneEmptyDirectoriesAction.java @@ -82,16 +82,14 @@ public class PruneEmptyDirectoriesAction extends AnAction { } private static void delete(final VirtualFile file) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - file.delete(PruneEmptyDirectoriesAction.class); - //noinspection UseOfSystemOutOrSystemErr - System.out.println("Deleted: " + file.getPresentableUrl()); - } - catch (IOException e) { - Messages.showErrorDialog("Cannot delete '" + file.getPresentableUrl() + "', " + e.getLocalizedMessage(), "IOException"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + file.delete(PruneEmptyDirectoriesAction.class); + //noinspection UseOfSystemOutOrSystemErr + System.out.println("Deleted: " + file.getPresentableUrl()); + } + catch (IOException e) { + Messages.showErrorDialog("Cannot delete '" + file.getPresentableUrl() + "', " + e.getLocalizedMessage(), "IOException"); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/SelectAllAction.java b/platform/platform-impl/src/com/intellij/ide/actions/SelectAllAction.java index 8c9415e175ed..0b200c9f8df3 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/SelectAllAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/SelectAllAction.java @@ -35,11 +35,8 @@ public class SelectAllAction extends TextComponentEditorAction implements DumbAw @Override public void execute(final Editor editor, DataContext dataContext) { CommandProcessor processor = CommandProcessor.getInstance(); - processor.executeCommand(CommonDataKeys.PROJECT.getData(dataContext), new Runnable() { - public void run() { - editor.getSelectionModel().setSelection(0, editor.getDocument().getTextLength()); - } - }, IdeBundle.message("command.select.all"), null); + processor.executeCommand(CommonDataKeys.PROJECT.getData(dataContext), + () -> editor.getSelectionModel().setSelection(0, editor.getDocument().getTextLength()), IdeBundle.message("command.select.all"), null); } } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ShowSettingsAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ShowSettingsAction.java index 98b371e366eb..8f03f05b5fc4 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ShowSettingsAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ShowSettingsAction.java @@ -54,12 +54,10 @@ public class ShowSettingsAction extends AnAction implements DumbAware { } final long startTime = System.nanoTime(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final long endTime = System.nanoTime(); - if (ApplicationManagerEx.getApplicationEx().isInternal()) { - System.out.println("Displaying settings dialog took " + ((endTime - startTime) / 1000000) + " ms"); - } + SwingUtilities.invokeLater(() -> { + final long endTime = System.nanoTime(); + if (ApplicationManagerEx.getApplicationEx().isInternal()) { + System.out.println("Displaying settings dialog took " + ((endTime - startTime) / 1000000) + " ms"); } }); ShowSettingsUtil.getInstance().showSettingsDialog(project, ShowSettingsUtilImpl.getConfigurableGroups(project, true)); diff --git a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java index f08eb8d0983c..3b17b14136a8 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java @@ -87,13 +87,10 @@ public class Switcher extends AnAction implements DumbAware { private static final Color ON_MOUSE_OVER_BG_COLOR = new JBColor(new Color(231, 242, 249), new Color(77, 80, 84)); private static int CTRL_KEY; private static int ALT_KEY; - @Nullable public static final Runnable CHECKER = new Runnable() { - @Override - public void run() { - synchronized (Switcher.class) { - if (SWITCHER != null) { - SWITCHER.navigate(null); - } + @Nullable public static final Runnable CHECKER = () -> { + synchronized (Switcher.class) { + if (SWITCHER != null) { + SWITCHER.navigate(null); } } }; @@ -329,12 +326,7 @@ public class Switcher extends AnAction implements DumbAware { } twShortcuts = createShortcuts(windows); final Map map = ContainerUtil.reverseMap(twShortcuts); - Collections.sort(windows, new Comparator() { - @Override - public int compare(@NotNull ToolWindow o1, @NotNull ToolWindow o2) { - return StringUtil.compare(map.get(o1), map.get(o2), false); - } - }); + Collections.sort(windows, (o1, o2) -> StringUtil.compare(map.get(o1), map.get(o2), false)); for (ToolWindow window : windows) { twModel.addElement(window); } @@ -342,12 +334,8 @@ public class Switcher extends AnAction implements DumbAware { toolWindows = new JBList(twModel); toolWindows.addFocusListener(new MyToolWindowsListFocusListener()); if (pinned) { - new NameFilteringListModel(toolWindows, new Function() { - @NotNull - @Override - public String fun(@NotNull ToolWindow window) { - return window.getStripeTitle(); - } + new NameFilteringListModel(toolWindows, window -> { + return window.getStripeTitle(); }, new Condition() { @Override public boolean value(@NotNull String s) { @@ -526,11 +514,7 @@ public class Switcher extends AnAction implements DumbAware { } public void valueChanged(@NotNull final ListSelectionEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - updatePathLabel(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> updatePathLabel()); } private void updatePathLabel() { @@ -548,11 +532,8 @@ public class Switcher extends AnAction implements DumbAware { files = new JBList(filesModel); if (pinned) { - new NameFilteringListModel(files, new Function() { - @Override - public String fun(@NotNull FileInfo info) { - return info.getNameForRendering(); - } + new NameFilteringListModel(files, info -> { + return info.getNameForRendering(); }, new Condition() { @Override public boolean value(@NotNull String s) { @@ -768,15 +749,12 @@ public class Switcher extends AnAction implements DumbAware { final IdeFocusManager focusManager = IdeFocusManager.getInstance(project); myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - JComponent focusTarget = selectedList; - if (selectedList.getModel().getSize() == 0) { - focusTarget = selectedList == files ? toolWindows : files; - } - focusManager.requestFocus(focusTarget, true); + myAlarm.addRequest(() -> { + JComponent focusTarget = selectedList; + if (selectedList.getModel().getSize() == 0) { + focusTarget = selectedList == files ? toolWindows : files; } + focusManager.requestFocus(focusTarget, true); }, 300); if (jList.getModel().getSize() == 1) { removeElementAt(jList, selectedIndex); @@ -899,45 +877,32 @@ public class Switcher extends AnAction implements DumbAware { } else if (values[0] instanceof ToolWindow) { final ToolWindow toolWindow = (ToolWindow)values[0]; - IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - toolWindow.activate(null, true, true); - } - }); + IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> toolWindow.activate(null, true, true)); } else { - IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - final FileEditorManagerImpl manager = (FileEditorManagerImpl)FileEditorManager.getInstance(project); - for (Object value : values) { - if (value instanceof FileInfo) { - final FileInfo info = (FileInfo)value; + IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> { + final FileEditorManagerImpl manager = (FileEditorManagerImpl)FileEditorManager.getInstance(project); + for (Object value : values) { + if (value instanceof FileInfo) { + final FileInfo info = (FileInfo)value; - VirtualFile file = info.first; - if (openInNewWindow) { - manager.openFileInNewWindow(file); + VirtualFile file = info.first; + if (openInNewWindow) { + manager.openFileInNewWindow(file); + } + else if (info.second != null) { + EditorWindow wnd = findAppropriateWindow(info); + if (wnd != null) { + manager.openFileImpl2(wnd, file, true); + manager.addSelectionRecord(file, wnd); } - else if (info.second != null) { - EditorWindow wnd = findAppropriateWindow(info); - if (wnd != null) { - manager.openFileImpl2(wnd, file, true); - manager.addSelectionRecord(file, wnd); - } - } - else { - boolean oldValue = UISettings.getInstance().REUSE_NOT_MODIFIED_TABS; - UISettings.getInstance().REUSE_NOT_MODIFIED_TABS = false; - manager.openFile(file, true, true); - if (oldValue) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - UISettings.getInstance().REUSE_NOT_MODIFIED_TABS = true; - } - }, "", null); - } + } + else { + boolean oldValue = UISettings.getInstance().REUSE_NOT_MODIFIED_TABS; + UISettings.getInstance().REUSE_NOT_MODIFIED_TABS = false; + manager.openFile(file, true, true); + if (oldValue) { + CommandProcessor.getInstance().executeCommand(project, () -> UISettings.getInstance().REUSE_NOT_MODIFIED_TABS = true, "", null); } } } @@ -951,31 +916,25 @@ public class Switcher extends AnAction implements DumbAware { if (gotoFile != null && !StringUtil.isEmpty(fileName)) { myPopup.cancel(); final AnAction action = gotoFile; - SwingUtilities.invokeLater(new Runnable() { + SwingUtilities.invokeLater(() -> DataManager.getInstance().getDataContextFromFocus().doWhenDone(new Consumer() { @Override - public void run() { - - DataManager.getInstance().getDataContextFromFocus().doWhenDone(new Consumer() { + public void consume(@NotNull final DataContext context) { + final DataContext dataContext = new DataContext() { + @Nullable @Override - public void consume(@NotNull final DataContext context) { - final DataContext dataContext = new DataContext() { - @Nullable - @Override - public Object getData(@NonNls String dataId) { - if (PlatformDataKeys.PREDEFINED_TEXT.is(dataId)) { - return fileName; - } - return context.getData(dataId); - } - }; - final AnActionEvent event = - new AnActionEvent(e, dataContext, ActionPlaces.EDITOR_POPUP, new PresentationFactory().getPresentation(action), - ActionManager.getInstance(), 0); - action.actionPerformed(event); + public Object getData(@NonNls String dataId) { + if (PlatformDataKeys.PREDEFINED_TEXT.is(dataId)) { + return fileName; + } + return context.getData(dataId); } - }); + }; + final AnActionEvent event = + new AnActionEvent(e, dataContext, ActionPlaces.EDITOR_POPUP, new PresentationFactory().getPresentation(action), + ActionManager.getInstance(), 0); + action.actionPerformed(event); } - }); + })); } } @@ -1110,21 +1069,12 @@ public class Switcher extends AnAction implements DumbAware { protected void selectElement(final Object element, String selectedText) { if (element instanceof FileInfo) { if (!toolWindows.isSelectionEmpty()) toolWindows.clearSelection(); - IdeFocusManager.findInstanceByComponent(files).requestFocus(files, true).doWhenDone(new Runnable() { - @Override - public void run() { - files.setSelectedValue(element, true); - } - }); + IdeFocusManager.findInstanceByComponent(files).requestFocus(files, true).doWhenDone(() -> files.setSelectedValue(element, true)); } else { if (!files.isSelectionEmpty()) files.clearSelection(); - IdeFocusManager.findInstanceByComponent(toolWindows).requestFocus(toolWindows, true).doWhenDone(new Runnable() { - @Override - public void run() { - toolWindows.setSelectedValue(element, true); - } - }); + IdeFocusManager.findInstanceByComponent(toolWindows).requestFocus(toolWindows, true).doWhenDone( + () -> toolWindows.setSelectedValue(element, true)); } } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java b/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java index 628221c3950e..aa2658f23c33 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java @@ -82,13 +82,10 @@ public class TogglePresentationModeAction extends AnAction implements DumbAware tweakUIDefaults(settings, inPresentation); ActionCallback callback = project == null ? ActionCallback.DONE : tweakFrameFullScreen(project, inPresentation); - callback.doWhenProcessed(new Runnable() { - @Override - public void run() { - tweakEditorAndFireUpdateUI(settings, inPresentation); + callback.doWhenProcessed(() -> { + tweakEditorAndFireUpdateUI(settings, inPresentation); - restoreToolWindows(project, layoutStored, inPresentation); - } + restoreToolWindows(project, layoutStored, inPresentation); }); } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ToolWindowsGroup.java b/platform/platform-impl/src/com/intellij/ide/actions/ToolWindowsGroup.java index 5ce3d1b43a24..556ac9e09167 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ToolWindowsGroup.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ToolWindowsGroup.java @@ -32,24 +32,22 @@ import java.util.List; */ public final class ToolWindowsGroup extends ActionGroup implements DumbAware { - private static final Comparator COMPARATOR = new Comparator() { - public int compare(ActivateToolWindowAction a1, ActivateToolWindowAction a2) { - int m1 = ActivateToolWindowAction.getMnemonicForToolWindow(a1.getToolWindowId()); - int m2 = ActivateToolWindowAction.getMnemonicForToolWindow(a2.getToolWindowId()); + private static final Comparator COMPARATOR = (a1, a2) -> { + int m1 = ActivateToolWindowAction.getMnemonicForToolWindow(a1.getToolWindowId()); + int m2 = ActivateToolWindowAction.getMnemonicForToolWindow(a2.getToolWindowId()); - if (m1 != -1 && m2 == -1) { - return -1; - } - else if (m1 == -1 && m2 != -1) { - return 1; - } - else if (m1 != -1) { - return m1 - m2; - } - else { - // Both actions have no mnemonic, therefore they are sorted alphabetically - return a1.getToolWindowId().compareToIgnoreCase(a2.getToolWindowId()); - } + if (m1 != -1 && m2 == -1) { + return -1; + } + else if (m1 == -1 && m2 != -1) { + return 1; + } + else if (m1 != -1) { + return m1 - m2; + } + else { + // Both actions have no mnemonic, therefore they are sorted alphabetically + return a1.getToolWindowId().compareToIgnoreCase(a2.getToolWindowId()); } }; diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java index aa24919594e9..f1ec6f6e385b 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java @@ -57,12 +57,7 @@ public class CustomizeFeaturedPluginsStepPanel extends AbstractCustomizeWizardSt setLayout(new GridLayout(1, 1)); add(myInProgressLabel = new JLabel("Loading...", SwingConstants.CENTER)); myPluginGroups = pluginGroups; - myPluginGroups.setLoadingCallback(new Runnable() { - @Override - public void run() { - onPluginGroupsLoaded(); - } - }); + myPluginGroups.setLoadingCallback(() -> onPluginGroupsLoaded()); } private void onPluginGroupsLoaded() { @@ -143,37 +138,26 @@ public class CustomizeFeaturedPluginsStepPanel extends AbstractCustomizeWizardSt public void start() { myCanceled.set(false); super.start(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - wrapperLayout.show(buttonWrapper, "progress"); - } - }); + SwingUtilities.invokeLater(() -> wrapperLayout.show(buttonWrapper, "progress")); } @Override public void processFinish() { super.processFinish(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - wrapperLayout.show(buttonWrapper, "button"); - installButton.setEnabled(false); - installButton.setText("Installed"); - } + SwingUtilities.invokeLater(() -> { + wrapperLayout.show(buttonWrapper, "button"); + installButton.setEnabled(false); + installButton.setText("Installed"); }); } @Override public void setFraction(final double fraction) { super.setFraction(fraction); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - int value = (int)(100 * fraction + .5); - progressBar.setValue(value); - progressBar.setString(value + "%"); - } + SwingUtilities.invokeLater(() -> { + int value = (int)(100 * fraction + .5); + progressBar.setValue(value); + progressBar.setString(value + "%"); }); } @@ -182,13 +166,10 @@ public class CustomizeFeaturedPluginsStepPanel extends AbstractCustomizeWizardSt stop(); myCanceled.set(true); super.cancel(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - wrapperLayout.show(buttonWrapper, "button"); - progressBar.setValue(0); - progressBar.setString("0%"); - } + SwingUtilities.invokeLater(() -> { + wrapperLayout.show(buttonWrapper, "button"); + progressBar.setValue(0); + progressBar.setString("0%"); }); } }; @@ -215,13 +196,10 @@ public class CustomizeFeaturedPluginsStepPanel extends AbstractCustomizeWizardSt void onFail() { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - indicator.stop(); - wrapperLayout.show(buttonWrapper, "progress"); - progressBar.setString("Cannot download plugin"); - } + SwingUtilities.invokeLater(() -> { + indicator.stop(); + wrapperLayout.show(buttonWrapper, "progress"); + progressBar.setString("Cannot download plugin"); }); } }); diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java index 10dee3283560..a8fe1c307ed5 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java @@ -178,13 +178,10 @@ public class CustomizeIDEWizardDialog extends DialogWrapper implements ActionLis private void initCurrentStep(boolean forward) { final AbstractCustomizeWizardStep myCurrentStep = mySteps.get(myIndex); myCurrentStep.beforeShown(forward); - myCardLayout.swipe(myContentPanel, myCurrentStep.getTitle(), JBCardLayout.SwipeDirection.AUTO, new Runnable() { - @Override - public void run() { - Component component = myCurrentStep.getDefaultFocusedComponent(); - if (component != null) { - component.requestFocus(); - } + myCardLayout.swipe(myContentPanel, myCurrentStep.getTitle(), JBCardLayout.SwipeDirection.AUTO, () -> { + Component component = myCurrentStep.getDefaultFocusedComponent(); + if (component != null) { + component.requestFocus(); } }); diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeMacKeyboardLayoutStep.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeMacKeyboardLayoutStep.java index 011b6fbedc2c..bc2153cf52b5 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeMacKeyboardLayoutStep.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeMacKeyboardLayoutStep.java @@ -35,12 +35,8 @@ public class CustomizeMacKeyboardLayoutStep extends AbstractCustomizeWizardStep JRadioButton macRadioButton = new JRadioButton("I've never used " + ApplicationNamesInfo.getInstance().getProductName()); macRadioButton.setOpaque(false); - JPanel macPanel = createBigButtonPanel(new VerticalFlowLayout(), macRadioButton, new Runnable() { - @Override - public void run() { - WelcomeWizardUtil.setWizardKeymap(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP); - } - }); + JPanel macPanel = createBigButtonPanel(new VerticalFlowLayout(), macRadioButton, + () -> WelcomeWizardUtil.setWizardKeymap(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP)); macPanel.add(macRadioButton); macPanel.add(new JLabel("" + style + "

    " + KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP + " keymap

    " + "Adapted for OS X

    " + @@ -52,12 +48,8 @@ public class CustomizeMacKeyboardLayoutStep extends AbstractCustomizeWizardStep JRadioButton defaultRadioButton = new JRadioButton("I used " + ApplicationNamesInfo.getInstance().getProductName() + " before"); defaultRadioButton.setOpaque(false); - JPanel defaultPanel = createBigButtonPanel(new VerticalFlowLayout(), defaultRadioButton, new Runnable() { - @Override - public void run() { - WelcomeWizardUtil.setWizardKeymap(KeymapManager.MAC_OS_X_KEYMAP); - } - }); + JPanel defaultPanel = createBigButtonPanel(new VerticalFlowLayout(), defaultRadioButton, + () -> WelcomeWizardUtil.setWizardKeymap(KeymapManager.MAC_OS_X_KEYMAP)); defaultPanel.add(defaultRadioButton); defaultPanel.add(new JLabel("" + style + "

    " + KeymapManager.MAC_OS_X_KEYMAP + " keymap

    " + "Default for all platforms

    EXAMPLES
    " + diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java index f961181d9a33..614e88c24727 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java @@ -93,12 +93,9 @@ public class CustomizeUIThemeStepPanel extends AbstractCustomizeWizardStep { for (final ThemeInfo theme: myThemes) { final JRadioButton radioButton = new JRadioButton(theme.name, myDefaultTheme == theme); radioButton.setOpaque(false); - final JPanel panel = createBigButtonPanel(createSmallBorderLayout(), radioButton, new Runnable() { - @Override - public void run() { - applyLaf(theme, CustomizeUIThemeStepPanel.this); - theme.apply(); - } + final JPanel panel = createBigButtonPanel(createSmallBorderLayout(), radioButton, () -> { + applyLaf(theme, CustomizeUIThemeStepPanel.this); + theme.apply(); }); panel.setBorder(createSmallEmptyBorder()); panel.add(radioButton, myColumnMode ? BorderLayout.WEST : BorderLayout.NORTH); @@ -121,12 +118,7 @@ public class CustomizeUIThemeStepPanel extends AbstractCustomizeWizardStep { wrapperPanel.add(myPreviewLabel); add(wrapperPanel, BorderLayout.CENTER); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - applyLaf(myDefaultTheme, CustomizeUIThemeStepPanel.this); - } - }); + SwingUtilities.invokeLater(() -> applyLaf(myDefaultTheme, CustomizeUIThemeStepPanel.this)); myInitial = false; } diff --git a/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java b/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java index 2665fce2e969..7a22c26e4d2e 100644 --- a/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java +++ b/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java @@ -129,14 +129,10 @@ public class VirtualFileDiffElement extends DiffElement { @Override public Callable> getElementChooser(final Project project) { - return new Callable>() { - @Nullable - @Override - public DiffElement call() throws Exception { - final FileChooserDescriptor descriptor = getChooserDescriptor(); - final VirtualFile[] result = FileChooser.chooseFiles(descriptor, project, getValue()); - return result.length == 1 ? createElement(result[0]) : null; - } + return () -> { + final FileChooserDescriptor descriptor = getChooserDescriptor(); + final VirtualFile[] result = FileChooser.chooseFiles(descriptor, project, getValue()); + return result.length == 1 ? createElement(result[0]) : null; }; } diff --git a/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java index 60e21c1c4417..fb985ff50cf7 100644 --- a/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java @@ -112,13 +112,11 @@ public class DnDManagerImpl extends DnDManager implements Disposable { } private void cleanup(@Nullable final DnDSource source, @Nullable final DnDTarget target, @Nullable final JComponent targetComponent) { - Runnable cleanup = new Runnable() { - public void run() { - if (shouldCancelCurrentDnDOperation(source, target, targetComponent)) { - myLastProcessedOverComponent = null; - myCurrentDragContext = null; - resetEvents("cleanup"); - } + Runnable cleanup = () -> { + if (shouldCancelCurrentDnDOperation(source, target, targetComponent)) { + myLastProcessedOverComponent = null; + myCurrentDragContext = null; + resetEvents("cleanup"); } }; @@ -423,16 +421,14 @@ public class DnDManagerImpl extends DnDManager implements Disposable { } private void queueTooltip(final DnDEvent aEvent, final JLayeredPane aLayeredPane, final Rectangle aRectangle) { - myHighlighterShowRequest = new Runnable() { - public void run() { - if (myCurrentEvent != aEvent) return; - Highlighters.hide(DnDEvent.DropTargetHighlightingType.TEXT | DnDEvent.DropTargetHighlightingType.ERROR_TEXT); - if (aEvent.isDropPossible()) { - Highlighters.show(DnDEvent.DropTargetHighlightingType.TEXT, aLayeredPane, aRectangle, aEvent); - } - else { - Highlighters.show(DnDEvent.DropTargetHighlightingType.ERROR_TEXT, aLayeredPane, aRectangle, aEvent); - } + myHighlighterShowRequest = () -> { + if (myCurrentEvent != aEvent) return; + Highlighters.hide(DnDEvent.DropTargetHighlightingType.TEXT | DnDEvent.DropTargetHighlightingType.ERROR_TEXT); + if (aEvent.isDropPossible()) { + Highlighters.show(DnDEvent.DropTargetHighlightingType.TEXT, aLayeredPane, aRectangle, aEvent); + } + else { + Highlighters.show(DnDEvent.DropTargetHighlightingType.ERROR_TEXT, aLayeredPane, aRectangle, aEvent); } }; myTooltipTimer.restart(); diff --git a/platform/platform-impl/src/com/intellij/ide/dnd/LinuxDragAndDropSupport.java b/platform/platform-impl/src/com/intellij/ide/dnd/LinuxDragAndDropSupport.java index cdc3a94db03a..ce86ab1f2c90 100644 --- a/platform/platform-impl/src/com/intellij/ide/dnd/LinuxDragAndDropSupport.java +++ b/platform/platform-impl/src/com/intellij/ide/dnd/LinuxDragAndDropSupport.java @@ -84,11 +84,8 @@ public class LinuxDragAndDropSupport { @NotNull public static String toUriList(@NotNull final List files) { - return StringUtil.join(files, new Function() { - @Override - public String fun(final File file) { - return file.toURI().toString(); - } + return StringUtil.join(files, file -> { + return file.toURI().toString(); }, "\n"); } diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/ErrorViewStructure.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/ErrorViewStructure.java index e96b5baa092d..45819e3b810f 100644 --- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/ErrorViewStructure.java +++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/ErrorViewStructure.java @@ -422,13 +422,10 @@ public class ErrorViewStructure extends AbstractTreeStructure { removeGroup(groupingElement.getName()); final VirtualFile virtualFile = groupingElement.getFile(); if (virtualFile != null) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiFile psiFile = virtualFile.isValid()? PsiManager.getInstance(myProject).findFile(virtualFile) : null; - if (psiFile != null) { - DaemonCodeAnalyzer.getInstance(myProject).restart(psiFile); // urge the daemon to re-highlight the file despite no modification has been made - } + ApplicationManager.getApplication().runReadAction(() -> { + final PsiFile psiFile = virtualFile.isValid()? PsiManager.getInstance(myProject).findFile(virtualFile) : null; + if (psiFile != null) { + DaemonCodeAnalyzer.getInstance(myProject).restart(psiFile); // urge the daemon to re-highlight the file despite no modification has been made } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java index 5970bdd58fcc..c7d6c209a69d 100644 --- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java @@ -197,12 +197,9 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur public void performCopy(@NotNull DataContext dataContext) { List descriptors = getSelectedNodeDescriptors(); if (!descriptors.isEmpty()) { - CopyPasteManager.getInstance().setContents(new StringSelection(StringUtil.join(descriptors, new Function() { - @Override - public String fun(ErrorTreeNodeDescriptor descriptor) { - ErrorTreeElement element = descriptor.getElement(); - return NewErrorTreeRenderer.calcPrefix(element) + StringUtil.join(element.getText(), "\n"); - } + CopyPasteManager.getInstance().setContents(new StringSelection(StringUtil.join(descriptors, descriptor -> { + ErrorTreeElement element = descriptor.getElement(); + return NewErrorTreeRenderer.calcPrefix(element) + StringUtil.join(element.getText(), "\n"); }, "\n"))); } } @@ -249,12 +246,9 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur public void selectFirstMessage() { final ErrorTreeElement firstError = myErrorViewStructure.getFirstMessage(ErrorTreeElementKind.ERROR); if (firstError != null) { - selectElement(firstError, new Runnable() { - @Override - public void run() { - if (shouldShowFirstErrorInEditor()) { - navigateToSource(false); - } + selectElement(firstError, () -> { + if (shouldShowFirstErrorInEditor()) { + navigateToSource(false); } }); } @@ -471,17 +465,14 @@ public class NewErrorTreeViewPanel extends JPanel implements DataProvider, Occur return; } myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - final float fraction = myFraction; - final String text = myProgressText; - if (fraction > 0.0f) { - myProgressLabel.setText((int)(fraction * 100 + 0.5) + "% " + text); - } - else { - myProgressLabel.setText(text); - } + myUpdateAlarm.addRequest(() -> { + final float fraction = myFraction; + final String text = myProgressText; + if (fraction > 0.0f) { + myProgressLabel.setText((int)(fraction * 100 + 0.5) + "% " + text); + } + else { + myProgressLabel.setText(text); } }, 50, ModalityState.NON_MODAL); diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/actions/TestErrorViewAction.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/actions/TestErrorViewAction.java index 52635295ee59..0c56f54d833c 100644 --- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/actions/TestErrorViewAction.java +++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/actions/TestErrorViewAction.java @@ -90,14 +90,12 @@ public abstract class TestErrorViewAction extends AnAction{ } private void addMessage(final ErrorTreeView view, final String[] message, final int type) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - final long start = System.currentTimeMillis(); - view.addMessage(type, message, null, -1, -1, null); - final long duration = System.currentTimeMillis() - start; - myMillis += duration; - incMessageCount(); - } + ApplicationManager.getApplication().invokeLater(() -> { + final long start = System.currentTimeMillis(); + view.addMessage(type, message, null, -1, -1, null); + final long duration = System.currentTimeMillis() - start; + myMillis += duration; + incMessageCount(); }, ModalityState.NON_MODAL); } diff --git a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java index f62211b496c9..f0a169e486db 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java @@ -211,12 +211,7 @@ public class DataManagerImpl extends DataManager { public AsyncResult getDataContextFromFocus() { final AsyncResult context = new AsyncResult(); - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - context.setDone(getDataContext()); - } - }); + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> context.setDone(getDataContext())); return context; } diff --git a/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java b/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java index 4340318b9f69..1c8b1f173831 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java @@ -130,14 +130,11 @@ public class ProjectUtil { final Project project = provider.doOpenProject(virtualFile, projectToClose, forceOpenInNewFrame); if (project != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW); - if (toolWindow != null) { - toolWindow.activate(null); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!project.isDisposed()) { + final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW); + if (toolWindow != null) { + toolWindow.activate(null); } } }, ModalityState.NON_MODAL); diff --git a/platform/platform-impl/src/com/intellij/ide/impl/SelectInEditorManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/impl/SelectInEditorManagerImpl.java index 2eebf984707a..793f5d946f3e 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/SelectInEditorManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/SelectInEditorManagerImpl.java @@ -75,12 +75,9 @@ public class SelectInEditorManagerImpl extends SelectInEditorManager implements openEditor(file, endOffset); final Editor editor = openEditor(file, textRange.getStartOffset()); - SwingUtilities.invokeLater(new Runnable(){ // later to let focus listener chance to handle events - @Override - public void run() { - if (editor != null && !editor.isDisposed()) { - doSelect(toUseNormalSelection, editor, toSelectLine, textRange); - } + SwingUtilities.invokeLater(() -> { + if (editor != null && !editor.isDisposed()) { + doSelect(toUseNormalSelection, editor, toSelectLine, textRange); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java index 336637a42746..4673d50ab02b 100644 --- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java +++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java @@ -231,12 +231,9 @@ public class MasterKeyPasswordSafe extends BasePasswordSafeProvider { ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator(); synchronized (ourEDTLock) { if (indicator != null && indicator.isModal()) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (!runnable.isExpired()) { - runnable.run(); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (!runnable.isExpired()) { + runnable.run(); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/ui/PasswordSafePromptDialog.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/ui/PasswordSafePromptDialog.java index 8aa0099ccd1d..16b53889ca9c 100644 --- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/ui/PasswordSafePromptDialog.java +++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/ui/PasswordSafePromptDialog.java @@ -178,28 +178,26 @@ public class PasswordSafePromptDialog extends DialogWrapper { } } final Ref ref = Ref.create(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - public void run() { - PasswordSafeSettings.ProviderType type = ps.getSettings().getProviderType(); - final PasswordPromptComponent component = new PasswordPromptComponent(type, message, false, promptLabel, checkboxLabel); - PasswordSafePromptDialog d = new PasswordSafePromptDialog(project, title, component); + ApplicationManager.getApplication().invokeAndWait(() -> { + PasswordSafeSettings.ProviderType type = ps.getSettings().getProviderType(); + final PasswordPromptComponent component = new PasswordPromptComponent(type, message, false, promptLabel, checkboxLabel); + PasswordSafePromptDialog d = new PasswordSafePromptDialog(project, title, component); - d.setErrorText(error); - if (d.showAndGet()) { - ref.set(new String(component.getPassword())); - try { - if (component.isRememberSelected()) { - ps.storePassword(project, requestor, key, ref.get()); - } - else if (!type.equals(PasswordSafeSettings.ProviderType.DO_NOT_STORE)) { - ps.getMemoryProvider().storePassword(project, requestor, key, ref.get()); - } + d.setErrorText(error); + if (d.showAndGet()) { + ref.set(new String(component.getPassword())); + try { + if (component.isRememberSelected()) { + ps.storePassword(project, requestor, key, ref.get()); } - catch (PasswordSafeException e) { - Messages.showErrorDialog(project, e.getMessage(), "Failed to Store Password"); - if (LOG.isDebugEnabled()) { - LOG.debug("Failed to store password", e); - } + else if (!type.equals(PasswordSafeSettings.ProviderType.DO_NOT_STORE)) { + ps.getMemoryProvider().storePassword(project, requestor, key, ref.get()); + } + } + catch (PasswordSafeException e) { + Messages.showErrorDialog(project, e.getMessage(), "Failed to Store Password"); + if (LOG.isDebugEnabled()) { + LOG.debug("Failed to store password", e); } } } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/AvailablePluginsManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/AvailablePluginsManagerMain.java index aeb87e133a20..b2e106c566d6 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/AvailablePluginsManagerMain.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/AvailablePluginsManagerMain.java @@ -155,12 +155,7 @@ public class AvailablePluginsManagerMain extends PluginManagerMain { @Override public void reset() { - UiNotifyConnector.doWhenFirstShown(getPluginTable(), new Runnable() { - @Override - public void run() { - loadAvailablePlugins(); - } - }); + UiNotifyConnector.doWhenFirstShown(getPluginTable(), () -> loadAvailablePlugins()); super.reset(); } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/DisabledPluginsUsagesCollector.java b/platform/platform-impl/src/com/intellij/ide/plugins/DisabledPluginsUsagesCollector.java index 8a5633fda4c3..ce51eeabf51c 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/DisabledPluginsUsagesCollector.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/DisabledPluginsUsagesCollector.java @@ -34,11 +34,8 @@ public class DisabledPluginsUsagesCollector extends UsagesCollector { @NotNull public Set getUsages() { - return ContainerUtil.map2Set(PluginManagerCore.getDisabledPlugins(), new Function() { - @Override - public UsageDescriptor fun(String descriptor) { - return new UsageDescriptor(descriptor, 1); - } + return ContainerUtil.map2Set(PluginManagerCore.getDisabledPlugins(), descriptor -> { + return new UsageDescriptor(descriptor, 1); }); } } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/InstallPluginAction.java b/platform/platform-impl/src/com/intellij/ide/plugins/InstallPluginAction.java index 98638ce7bff6..cd6ec1df2360 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/InstallPluginAction.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/InstallPluginAction.java @@ -123,42 +123,36 @@ public class InstallPluginAction extends AnAction implements DumbAware { } try { - Runnable onInstallRunnable = new Runnable() { - @Override - public void run() { + Runnable onInstallRunnable = () -> { + for (PluginNode node : list) { + installedModel.appendOrUpdateDescriptor(node); + } + if (!myInstalled.isDisposed()) { + getPluginTable().updateUI(); + myInstalled.setRequireShutdown(true); + } + else { + boolean needToRestart = false; for (PluginNode node : list) { - installedModel.appendOrUpdateDescriptor(node); - } - if (!myInstalled.isDisposed()) { - getPluginTable().updateUI(); - myInstalled.setRequireShutdown(true); - } - else { - boolean needToRestart = false; - for (PluginNode node : list) { - final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(node.getPluginId()); - if (pluginDescriptor == null || pluginDescriptor.isEnabled()) { - needToRestart = true; - break; - } + final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(node.getPluginId()); + if (pluginDescriptor == null || pluginDescriptor.isEnabled()) { + needToRestart = true; + break; } + } - if (needToRestart) { - PluginManagerMain.notifyPluginsUpdated(null); - } - } - if (onSuccess != null) { - onSuccess.run(); + if (needToRestart) { + PluginManagerMain.notifyPluginsUpdated(null); } } + if (onSuccess != null) { + onSuccess.run(); + } }; - Runnable cleanupRunnable = new Runnable() { - @Override - public void run() { - ourInstallingNodes.removeAll(list); - if (cleanup != null) { - cleanup.run(); - } + Runnable cleanupRunnable = () -> { + ourInstallingNodes.removeAll(list); + if (cleanup != null) { + cleanup.run(); } }; final List plugins = myHost.getPluginsModel().getAllPlugins(); @@ -168,12 +162,7 @@ public class InstallPluginAction extends AnAction implements DumbAware { ourInstallingNodes.removeAll(list); PluginManagerMain.LOG.error(e1); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - IOExceptionDialog.showErrorDialog(IdeBundle.message("action.download.and.install.plugin"), IdeBundle.message("error.plugin.download.failed")); - } - }); + SwingUtilities.invokeLater(() -> IOExceptionDialog.showErrorDialog(IdeBundle.message("action.download.and.install.plugin"), IdeBundle.message("error.plugin.download.failed"))); } } } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java index 0a829118fd87..aa07a3e56191 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java @@ -92,13 +92,10 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { @Override public void actionPerformed(ActionEvent e) { final InstalledPluginsTableModel model = (InstalledPluginsTableModel)pluginsModel; - chooseAndInstall(model, new Consumer>() { - @Override - public void consume(Pair pair) { - model.appendOrUpdateDescriptor(pair.second); - setRequireShutdown(true); - select(pair.second); - } + chooseAndInstall(model, pair -> { + model.appendOrUpdateDescriptor(pair.second); + setRequireShutdown(true); + select(pair.second); }, myActionsPanel); } }); @@ -123,47 +120,44 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { descriptor.setDescription("JAR and ZIP archives are accepted"); final String oldPath = PropertiesComponent.getInstance().getValue(PLUGINS_PRESELECTION_PATH); final VirtualFile toSelect = oldPath == null ? null : VfsUtil.findFileByIoFile(new File(FileUtil.toSystemDependentName(oldPath)), false); - FileChooser.chooseFile(descriptor, null, parent, toSelect, new Consumer() { - @Override - public void consume(@NotNull VirtualFile virtualFile) { - File file = VfsUtilCore.virtualToIoFile(virtualFile); - PropertiesComponent.getInstance().setValue(PLUGINS_PRESELECTION_PATH, FileUtil.toSystemIndependentName(file.getParent())); + FileChooser.chooseFile(descriptor, null, parent, toSelect, virtualFile -> { + File file = VfsUtilCore.virtualToIoFile(virtualFile); + PropertiesComponent.getInstance().setValue(PLUGINS_PRESELECTION_PATH, FileUtil.toSystemIndependentName(file.getParent())); - try { - IdeaPluginDescriptorImpl pluginDescriptor = PluginDownloader.loadDescriptionFromJar(file); - if (pluginDescriptor == null) { - MessagesEx.showErrorDialog(parent, "Fail to load plugin descriptor from file " + file.getName(), CommonBundle.getErrorTitle()); - return; - } - - if (ourState.wasInstalled(pluginDescriptor.getPluginId())) { - String message = "Plugin '" + pluginDescriptor.getName() + "' was already installed"; - MessagesEx.showWarningDialog(parent, message, CommonBundle.getWarningTitle()); - return; - } - - if (PluginManagerCore.isIncompatible(pluginDescriptor)) { - String message = "Plugin '" + pluginDescriptor.getName() + "' is incompatible with this installation"; - MessagesEx.showErrorDialog(parent, message, CommonBundle.getErrorTitle()); - return; - } - - IdeaPluginDescriptor installedPlugin = PluginManager.getPlugin(pluginDescriptor.getPluginId()); - if (installedPlugin != null && !installedPlugin.isBundled()) { - File oldFile = installedPlugin.getPath(); - if (oldFile != null) { - StartupActionScriptManager.addActionCommand(new StartupActionScriptManager.DeleteCommand(oldFile)); - } - } - - PluginInstaller.install(file, file.getName(), false); - ourState.onPluginInstall(pluginDescriptor); - checkInstalledPluginDependencies(model, pluginDescriptor, parent); - callback.consume(pair(file, (IdeaPluginDescriptor)pluginDescriptor)); + try { + IdeaPluginDescriptorImpl pluginDescriptor = PluginDownloader.loadDescriptionFromJar(file); + if (pluginDescriptor == null) { + MessagesEx.showErrorDialog(parent, "Fail to load plugin descriptor from file " + file.getName(), CommonBundle.getErrorTitle()); + return; } - catch (IOException ex) { - MessagesEx.showErrorDialog(parent, ex.getMessage(), CommonBundle.getErrorTitle()); + + if (ourState.wasInstalled(pluginDescriptor.getPluginId())) { + String message = "Plugin '" + pluginDescriptor.getName() + "' was already installed"; + MessagesEx.showWarningDialog(parent, message, CommonBundle.getWarningTitle()); + return; } + + if (PluginManagerCore.isIncompatible(pluginDescriptor)) { + String message = "Plugin '" + pluginDescriptor.getName() + "' is incompatible with this installation"; + MessagesEx.showErrorDialog(parent, message, CommonBundle.getErrorTitle()); + return; + } + + IdeaPluginDescriptor installedPlugin = PluginManager.getPlugin(pluginDescriptor.getPluginId()); + if (installedPlugin != null && !installedPlugin.isBundled()) { + File oldFile = installedPlugin.getPath(); + if (oldFile != null) { + StartupActionScriptManager.addActionCommand(new StartupActionScriptManager.DeleteCommand(oldFile)); + } + } + + PluginInstaller.install(file, file.getName(), false); + ourState.onPluginInstall(pluginDescriptor); + checkInstalledPluginDependencies(model, pluginDescriptor, parent); + callback.consume(pair(file, (IdeaPluginDescriptor)pluginDescriptor)); + } + catch (IOException ex) { + MessagesEx.showErrorDialog(parent, ex.getMessage(), CommonBundle.getErrorTitle()); } }); } @@ -187,11 +181,8 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { } } if (!notInstalled.isEmpty()) { - String deps = StringUtil.join(notInstalled, new Function() { - @Override - public String fun(PluginId id) { - return id.toString(); - } + String deps = StringUtil.join(notInstalled, id -> { + return id.toString(); }, ", "); String message = "Plugin " + pluginDescriptor.getName() + " depends on unknown plugin" + (notInstalled.size() > 1 ? "s " : " ") + deps; MessagesEx.showWarningDialog(parent, message, CommonBundle.getWarningTitle()); @@ -204,11 +195,8 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { } } String part = "disabled plugin" + (dependencies.size() > 1 ? "s " : " "); - String deps = StringUtil.join(dependencies, new Function() { - @Override - public String fun(IdeaPluginDescriptor descriptor) { - return descriptor.getName(); - } + String deps = StringUtil.join(dependencies, descriptor -> { + return descriptor.getName(); }, ", "); String message = "Plugin " + pluginDescriptor.getName() + " depends on " + part + deps + ". Enable " + part.trim() + "?"; if (MessagesEx.showOkCancelDialog(parent, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()) == Messages.OK) { @@ -387,12 +375,9 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { if (!dependentToRequiredListMap.isEmpty()) { return "Unable to apply changes: plugin" + (dependentToRequiredListMap.size() == 1 ? " " : "s ") + - StringUtil.join(dependentToRequiredListMap.keySet(), new Function() { - @Override - public String fun(final PluginId pluginId) { - final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId); - return "\"" + (ideaPluginDescriptor != null ? ideaPluginDescriptor.getName() : pluginId.getIdString()) + "\""; - } + StringUtil.join(dependentToRequiredListMap.keySet(), pluginId -> { + final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId); + return "\"" + (ideaPluginDescriptor != null ? ideaPluginDescriptor.getName() : pluginId.getIdString()) + "\""; }, ", ") + " won't be able to load."; } @@ -485,12 +470,7 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { @Override public void actionPerformed(AnActionEvent e) { - chooseAndInstall(new InstalledPluginsTableModel(), new Consumer>() { - @Override - public void consume(Pair pair) { - PluginManagerConfigurable.shutdownOrRestartApp(); - } - }, null); + chooseAndInstall(new InstalledPluginsTableModel(), pair -> PluginManagerConfigurable.shutdownOrRestartApp(), null); } } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java index 645ab59d476b..810698019376 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsTableModel.java @@ -145,13 +145,7 @@ public class InstalledPluginsTableModel extends PluginTableModel { if (descriptor instanceof IdeaPluginDescriptorImpl && ((IdeaPluginDescriptorImpl)descriptor).isDeleted()) continue; final Boolean enabled = myEnabled.get(pluginId); if (enabled == null || enabled.booleanValue()) { - PluginManagerCore.checkDependants(descriptor, new Function() { - @Override - @Nullable - public IdeaPluginDescriptor fun(final PluginId pluginId) { - return PluginManager.getPlugin(pluginId); - } - }, new Condition() { + PluginManagerCore.checkDependants(descriptor, pluginId1 -> PluginManager.getPlugin(pluginId1), new Condition() { @Override public boolean value(final PluginId dependantPluginId) { final Boolean enabled = myEnabled.get(dependantPluginId); @@ -197,15 +191,12 @@ public class InstalledPluginsTableModel extends PluginTableModel { private void hideNotApplicablePlugins(Boolean value, final IdeaPluginDescriptor... ideaPluginDescriptors) { if (!value && ENABLED.equals(myEnabledFilter) || (value && DISABLED.equals(myEnabledFilter))) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - for (IdeaPluginDescriptor ideaPluginDescriptor : ideaPluginDescriptors) { - view.remove(ideaPluginDescriptor); - filtered.add(ideaPluginDescriptor); - } - fireTableDataChanged(); + SwingUtilities.invokeLater(() -> { + for (IdeaPluginDescriptor ideaPluginDescriptor : ideaPluginDescriptors) { + view.remove(ideaPluginDescriptor); + filtered.add(ideaPluginDescriptor); } + fireTableDataChanged(); }); } } @@ -326,24 +317,21 @@ public class InstalledPluginsTableModel extends PluginTableModel { @Override public Comparator getComparator() { - return new Comparator() { - @Override - public int compare(final IdeaPluginDescriptor o1, final IdeaPluginDescriptor o2) { - final Boolean enabled1 = myEnabled.get(o1.getPluginId()); - final Boolean enabled2 = myEnabled.get(o2.getPluginId()); - if (enabled1 != null && enabled1.booleanValue()) { - if (enabled2 != null && enabled2.booleanValue()) { - return 0; - } + return (o1, o2) -> { + final Boolean enabled1 = myEnabled.get(o1.getPluginId()); + final Boolean enabled2 = myEnabled.get(o2.getPluginId()); + if (enabled1 != null && enabled1.booleanValue()) { + if (enabled2 != null && enabled2.booleanValue()) { + return 0; + } - return 1; - } - else { - if (enabled2 == null || !enabled2.booleanValue()) { - return 0; - } - return -1; + return 1; + } + else { + if (enabled2 == null || !enabled2.booleanValue()) { + return 0; } + return -1; } }; } @@ -373,13 +361,7 @@ public class InstalledPluginsTableModel extends PluginTableModel { } for (final IdeaPluginDescriptor ideaPluginDescriptor : descriptorsToCheckDependencies) { - PluginManagerCore.checkDependants(ideaPluginDescriptor, new Function() { - @Override - @Nullable - public IdeaPluginDescriptor fun(final PluginId pluginId) { - return PluginManager.getPlugin(pluginId); - } - }, new Condition() { + PluginManagerCore.checkDependants(ideaPluginDescriptor, pluginId -> PluginManager.getPlugin(pluginId), new Condition() { @Override public boolean value(final PluginId pluginId) { Boolean enabled = myEnabled.get(pluginId); @@ -409,21 +391,15 @@ public class InstalledPluginsTableModel extends PluginTableModel { ); } if (!deps.isEmpty()) { - final String listOfSelectedPlugins = StringUtil.join(ideaPluginDescriptors, new Function() { - @Override - public String fun(IdeaPluginDescriptor pluginDescriptor) { - return pluginDescriptor.getName(); - } + final String listOfSelectedPlugins = StringUtil.join(ideaPluginDescriptors, pluginDescriptor -> { + return pluginDescriptor.getName(); }, ", "); final Set pluginDependencies = new HashSet(); - final String listOfDependencies = StringUtil.join(deps, new Function() { - @Override - public String fun(final PluginId pluginId) { - final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(pluginId); - assert pluginDescriptor != null; - pluginDependencies.add(pluginDescriptor); - return pluginDescriptor.getName(); - } + final String listOfDependencies = StringUtil.join(deps, pluginId -> { + final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(pluginId); + assert pluginDescriptor != null; + pluginDependencies.add(pluginDescriptor); + return pluginDescriptor.getName(); }, "
    "); final String message = !newVal ? "The following plugins
    " + listOfDependencies + "
    are enabled and depend" +(deps.size() == 1 ? "s" : "") + " on selected plugins. " + "
    Would you like to disable them too?" @@ -458,58 +434,55 @@ public class InstalledPluginsTableModel extends PluginTableModel { @Override public Comparator getComparator() { final Comparator comparator = getColumnComparator(); - return new Comparator() { - @Override - public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) { - if (isSortByStatus()) { - final boolean incompatible1 = PluginManagerCore.isIncompatible(o1); - final boolean incompatible2 = PluginManagerCore.isIncompatible(o2); - if (incompatible1) { - if (incompatible2) return comparator.compare(o1, o2); - return -1; - } - if (incompatible2) return 1; - - final boolean hasNewerVersion1 = ourState.hasNewerVersion(o1.getPluginId()); - final boolean hasNewerVersion2 = ourState.hasNewerVersion(o2.getPluginId()); - if (hasNewerVersion1) { - if (hasNewerVersion2) return comparator.compare(o1, o2); - return -1; - } - if (hasNewerVersion2) return 1; - - - final boolean wasUpdated1 = ourState.wasUpdated(o1.getPluginId()); - final boolean wasUpdated2 = ourState.wasUpdated(o2.getPluginId()); - if (wasUpdated1) { - if (wasUpdated2) return comparator.compare(o1, o2); - return -1; - } - if (wasUpdated2) return 1; - - - if (o1 instanceof PluginNode) { - if (o2 instanceof PluginNode) return comparator.compare(o1, o2); - return -1; - } - if (o2 instanceof PluginNode) return 1; - - - final boolean deleted1 = o1 instanceof IdeaPluginDescriptorImpl && ((IdeaPluginDescriptorImpl)o1).isDeleted(); - final boolean deleted2 = o2 instanceof IdeaPluginDescriptorImpl && ((IdeaPluginDescriptorImpl)o2).isDeleted(); - if (deleted1) { - if (deleted2) return comparator.compare(o1, o2); - return -1; - } - if (deleted2) return 1; - - final boolean enabled1 = isEnabled(o1.getPluginId()); - final boolean enabled2 = isEnabled(o2.getPluginId()); - if (enabled1 && !enabled2) return -1; - if (enabled2 && !enabled1) return 1; + return (o1, o2) -> { + if (isSortByStatus()) { + final boolean incompatible1 = PluginManagerCore.isIncompatible(o1); + final boolean incompatible2 = PluginManagerCore.isIncompatible(o2); + if (incompatible1) { + if (incompatible2) return comparator.compare(o1, o2); + return -1; } - return comparator.compare(o1, o2); + if (incompatible2) return 1; + + final boolean hasNewerVersion1 = ourState.hasNewerVersion(o1.getPluginId()); + final boolean hasNewerVersion2 = ourState.hasNewerVersion(o2.getPluginId()); + if (hasNewerVersion1) { + if (hasNewerVersion2) return comparator.compare(o1, o2); + return -1; + } + if (hasNewerVersion2) return 1; + + + final boolean wasUpdated1 = ourState.wasUpdated(o1.getPluginId()); + final boolean wasUpdated2 = ourState.wasUpdated(o2.getPluginId()); + if (wasUpdated1) { + if (wasUpdated2) return comparator.compare(o1, o2); + return -1; + } + if (wasUpdated2) return 1; + + + if (o1 instanceof PluginNode) { + if (o2 instanceof PluginNode) return comparator.compare(o1, o2); + return -1; + } + if (o2 instanceof PluginNode) return 1; + + + final boolean deleted1 = o1 instanceof IdeaPluginDescriptorImpl && ((IdeaPluginDescriptorImpl)o1).isDeleted(); + final boolean deleted2 = o2 instanceof IdeaPluginDescriptorImpl && ((IdeaPluginDescriptorImpl)o2).isDeleted(); + if (deleted1) { + if (deleted2) return comparator.compare(o1, o2); + return -1; + } + if (deleted2) return 1; + + final boolean enabled1 = isEnabled(o1.getPluginId()); + final boolean enabled2 = isEnabled(o2.getPluginId()); + if (enabled1 && !enabled2) return -1; + if (enabled2 && !enabled1) return 1; } + return comparator.compare(o1, o2); }; } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/NonBundledPluginsUsagesCollector.java b/platform/platform-impl/src/com/intellij/ide/plugins/NonBundledPluginsUsagesCollector.java index d0e670be62aa..43cc38b2db6e 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/NonBundledPluginsUsagesCollector.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/NonBundledPluginsUsagesCollector.java @@ -43,11 +43,8 @@ public class NonBundledPluginsUsagesCollector extends UsagesCollector { } }); - return ContainerUtil.map2Set(nonBundledEnabledPlugins, new Function() { - @Override - public UsageDescriptor fun(IdeaPluginDescriptor descriptor) { - return new UsageDescriptor(descriptor.getPluginId().getIdString(), 1); - } + return ContainerUtil.map2Set(nonBundledEnabledPlugins, descriptor -> { + return new UsageDescriptor(descriptor.getPluginId().getIdString(), 1); }); } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginHeaderPanel.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginHeaderPanel.java index 8d8a5b285fe4..72c6a23fc133 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginHeaderPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginHeaderPanel.java @@ -266,12 +266,7 @@ public class PluginHeaderPanel { switch (myActionId) { case UPDATE: case INSTALL: - Runnable setPlugin = new Runnable() { - @Override - public void run() { - setPlugin(myPlugin); - } - }; + Runnable setPlugin = () -> setPlugin(myPlugin); new InstallPluginAction(myManager.getAvailable(), myManager.getInstalled()).install(setPlugin, setPlugin, true); break; case UNINSTALL: @@ -287,17 +282,14 @@ public class PluginHeaderPanel { dialog.close(DialogWrapper.OK_EXIT_CODE); } //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final DialogWrapper settings = - DialogWrapper.findInstance(IdeFocusManager.findInstance().getFocusOwner()); - if (settings instanceof SettingsDialog) { - ((SettingsDialog)settings).doOKAction(); - ApplicationManager.getApplication().restart(); - } else { - ApplicationManager.getApplication().restart(); - } + SwingUtilities.invokeLater(() -> { + final DialogWrapper settings = + DialogWrapper.findInstance(IdeFocusManager.findInstance().getFocusOwner()); + if (settings instanceof SettingsDialog) { + ((SettingsDialog)settings).doOKAction(); + ApplicationManager.getApplication().restart(); + } else { + ApplicationManager.getApplication().restart(); } }); break; diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginInstaller.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginInstaller.java index 4d596f1360bd..0ed02be2c956 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginInstaller.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginInstaller.java @@ -171,19 +171,13 @@ public class PluginInstaller { if (depends.size() > 0) { // has something to install prior installing the plugin final boolean[] proceed = new boolean[1]; try { - GuiUtils.runOrInvokeAndWait(new Runnable() { - @Override - public void run() { - String title = IdeBundle.message("plugin.manager.dependencies.detected.title"); - String deps = StringUtil.join(depends, new Function() { - @Override - public String fun(PluginNode node) { - return node.getName(); - } - }, ", "); - String message = IdeBundle.message("plugin.manager.dependencies.detected.message", depends.size(), deps); - proceed[0] = Messages.showYesNoDialog(message, title, Messages.getWarningIcon()) == Messages.YES; - } + GuiUtils.runOrInvokeAndWait(() -> { + String title = IdeBundle.message("plugin.manager.dependencies.detected.title"); + String deps = StringUtil.join(depends, node -> { + return node.getName(); + }, ", "); + String message = IdeBundle.message("plugin.manager.dependencies.detected.message", depends.size(), deps); + proceed[0] = Messages.showYesNoDialog(message, title, Messages.getWarningIcon()) == Messages.YES; }); } catch (Exception e) { @@ -197,19 +191,13 @@ public class PluginInstaller { if (optionalDeps.size() > 0) { final boolean[] proceed = new boolean[1]; try { - GuiUtils.runOrInvokeAndWait(new Runnable() { - @Override - public void run() { - String title = IdeBundle.message("plugin.manager.dependencies.detected.title"); - String deps = StringUtil.join(optionalDeps, new Function() { - @Override - public String fun(PluginNode node) { - return node.getName(); - } - }, ", "); - String message = IdeBundle.message("plugin.manager.optional.dependencies.detected.message", optionalDeps.size(), deps); - proceed[0] = Messages.showYesNoDialog(message, title, Messages.getWarningIcon()) == Messages.YES; - } + GuiUtils.runOrInvokeAndWait(() -> { + String title = IdeBundle.message("plugin.manager.dependencies.detected.title"); + String deps = StringUtil.join(optionalDeps, node -> { + return node.getName(); + }, ", "); + String message = IdeBundle.message("plugin.manager.optional.dependencies.detected.message", optionalDeps.size(), deps); + proceed[0] = Messages.showYesNoDialog(message, title, Messages.getWarningIcon()) == Messages.YES; }); } catch (Exception e) { diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java index 208afd6db431..fc8722fb7f85 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java @@ -79,21 +79,18 @@ public class PluginManager extends PluginManagerCore { } }; - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - ClassUtilCore.clearJarURLCache(); + Runnable runnable = () -> { + try { + ClassUtilCore.clearJarURLCache(); - Class aClass = Class.forName(mainClass); - Method method = aClass.getDeclaredMethod(methodName, ArrayUtil.EMPTY_STRING_ARRAY.getClass()); - method.setAccessible(true); - Object[] argsArray = {args}; - method.invoke(null, argsArray); - } - catch (Throwable t) { - throw new StartupAbortedException(t); - } + Class aClass = Class.forName(mainClass); + Method method = aClass.getDeclaredMethod(methodName, ArrayUtil.EMPTY_STRING_ARRAY.getClass()); + method.setAccessible(true); + Object[] argsArray = {args}; + method.invoke(null, argsArray); + } + catch (Throwable t) { + throw new StartupAbortedException(t); } }; @@ -155,12 +152,7 @@ public class PluginManager extends PluginManagerCore { return null; } - private static Thread.UncaughtExceptionHandler HANDLER = new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - processException(e); - } - }; + private static Thread.UncaughtExceptionHandler HANDLER = (t, e) -> processException(e); public static void installExceptionHandler() { Thread.currentThread().setUncaughtExceptionHandler(HANDLER); diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerColumnInfo.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerColumnInfo.java index 4412aea8717e..4eb1939db918 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerColumnInfo.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerColumnInfo.java @@ -124,39 +124,37 @@ class PluginManagerColumnInfo extends ColumnInfo { if (isSortByStatus()) { final RowSorter.SortKey defaultSortKey = myModel.getDefaultSortKey(); final int up = defaultSortKey != null && defaultSortKey.getSortOrder() == SortOrder.ASCENDING ? -1 : 1; - return new Comparator() { - public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) { - if (o1 instanceof PluginNode && o2 instanceof PluginNode) { - final int status1 = ((PluginNode)o1).getStatus(); - final int status2 = ((PluginNode)o2).getStatus(); - if (isDownloaded((PluginNode)o1)){ - if (!isDownloaded((PluginNode)o2)) return up; - return comparator.compare(o1, o2); - } - if (isDownloaded((PluginNode)o2)) return -up; + return (o1, o2) -> { + if (o1 instanceof PluginNode && o2 instanceof PluginNode) { + final int status1 = ((PluginNode)o1).getStatus(); + final int status2 = ((PluginNode)o2).getStatus(); + if (isDownloaded((PluginNode)o1)){ + if (!isDownloaded((PluginNode)o2)) return up; + return comparator.compare(o1, o2); + } + if (isDownloaded((PluginNode)o2)) return -up; - if (status1 == PluginNode.STATUS_DELETED) { - if (status2 != PluginNode.STATUS_DELETED) return up; - return comparator.compare(o1, o2); - } - if (status2 == PluginNode.STATUS_DELETED) return -up; + if (status1 == PluginNode.STATUS_DELETED) { + if (status2 != PluginNode.STATUS_DELETED) return up; + return comparator.compare(o1, o2); + } + if (status2 == PluginNode.STATUS_DELETED) return -up; - if (status1 == PluginNode.STATUS_INSTALLED) { - if (status2 !=PluginNode.STATUS_INSTALLED) return up; - final boolean hasNewerVersion1 = ourState.hasNewerVersion(o1.getPluginId()); - final boolean hasNewerVersion2 = ourState.hasNewerVersion(o2.getPluginId()); - if (hasNewerVersion1 != hasNewerVersion2) { - if (hasNewerVersion1) return up; - return -up; - } - return comparator.compare(o1, o2); - } - if (status2 == PluginNode.STATUS_INSTALLED) { + if (status1 == PluginNode.STATUS_INSTALLED) { + if (status2 !=PluginNode.STATUS_INSTALLED) return up; + final boolean hasNewerVersion1 = ourState.hasNewerVersion(o1.getPluginId()); + final boolean hasNewerVersion2 = ourState.hasNewerVersion(o2.getPluginId()); + if (hasNewerVersion1 != hasNewerVersion2) { + if (hasNewerVersion1) return up; return -up; } + return comparator.compare(o1, o2); + } + if (status2 == PluginNode.STATUS_INSTALLED) { + return -up; } - return comparator.compare(o1, o2); } + return comparator.compare(o1, o2); }; } @@ -164,43 +162,41 @@ class PluginManagerColumnInfo extends ColumnInfo { } protected Comparator getColumnComparator() { - return new Comparator() { - public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) { - if (myModel.isSortByRating()) { - final String rating1 = ((PluginNode)o1).getRating(); - final String rating2 = ((PluginNode)o2).getRating(); - final int compare = Comparing.compare(rating2, rating1); - if (compare != 0) { - return compare; - } + return (o1, o2) -> { + if (myModel.isSortByRating()) { + final String rating1 = ((PluginNode)o1).getRating(); + final String rating2 = ((PluginNode)o2).getRating(); + final int compare = Comparing.compare(rating2, rating1); + if (compare != 0) { + return compare; } - - if (isSortByDate()) { - long date1 = (o1 instanceof PluginNode) ? ((PluginNode)o1).getDate() : ((IdeaPluginDescriptorImpl)o1).getDate(); - long date2 = (o2 instanceof PluginNode) ? ((PluginNode)o2).getDate() : ((IdeaPluginDescriptorImpl)o2).getDate(); - date1 /= 60 * 1000; - date2 /= 60 * 1000; - if (date2 != date1) { - return date2 - date1 > 0L ? 1 : -1; - } - } - - if (isSortByDownloads()) { - String count1 = o1.getDownloads(); - String count2 = o2.getDownloads(); - if (count1 != null && count2 != null) { - final Long result = Long.valueOf(count2); - if (result != 0) { - return result.compareTo(Long.valueOf(count1)); - } - } - else { - return count1 != null ? -1 : 1; - } - } - - return StringUtil.compare(o1.getName(), o2.getName(), true); } + + if (isSortByDate()) { + long date1 = (o1 instanceof PluginNode) ? ((PluginNode)o1).getDate() : ((IdeaPluginDescriptorImpl)o1).getDate(); + long date2 = (o2 instanceof PluginNode) ? ((PluginNode)o2).getDate() : ((IdeaPluginDescriptorImpl)o2).getDate(); + date1 /= 60 * 1000; + date2 /= 60 * 1000; + if (date2 != date1) { + return date2 - date1 > 0L ? 1 : -1; + } + } + + if (isSortByDownloads()) { + String count1 = o1.getDownloads(); + String count2 = o2.getDownloads(); + if (count1 != null && count2 != null) { + final Long result = Long.valueOf(count2); + if (result != 0) { + return result.compareTo(Long.valueOf(count1)); + } + } + else { + return count1 != null ? -1 : 1; + } + } + + return StringUtil.compare(o1.getName(), o2.getName(), true); }; } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java index 60a3193a8e08..edf602138cf6 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java @@ -131,11 +131,8 @@ public class PluginManagerConfigurable extends BaseConfigurable implements Searc Disposer.register(d, new Disposable() { @Override public void dispose() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showShutdownDialogIfNeeded(); - } + ApplicationManager.getApplication().invokeLater(() -> { + showShutdownDialogIfNeeded(); }, ApplicationManager.getApplication().getDisposed()); } }); @@ -192,12 +189,9 @@ public class PluginManagerConfigurable extends BaseConfigurable implements Searc @Override @Nullable public Runnable enableSearch(final String option) { - return new Runnable() { - @Override - public void run() { - if (myPluginManagerMain != null) { - myPluginManagerMain.filter(option); - } + return () -> { + if (myPluginManagerMain != null) { + myPluginManagerMain.filter(option); } }; } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java index 02e64a402657..1926a6ca6d9c 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java @@ -233,12 +233,9 @@ public abstract class PluginManagerMain implements Disposable { } public void reset() { - UiNotifyConnector.doWhenFirstShown(getPluginTable(), new Runnable() { - @Override - public void run() { - requireShutdown = false; - TableUtil.ensureSelectionExists(getPluginTable()); - } + UiNotifyConnector.doWhenFirstShown(getPluginTable(), () -> { + requireShutdown = false; + TableUtil.ensureSelectionExists(getPluginTable()); }); } @@ -248,11 +245,8 @@ public abstract class PluginManagerMain implements Disposable { @NotNull public static List mapToPluginIds(List plugins) { - return ContainerUtil.map(plugins, new Function() { - @Override - public PluginId fun(IdeaPluginDescriptor descriptor) { - return descriptor.getPluginId(); - } + return ContainerUtil.map(plugins, descriptor -> { + return descriptor.getPluginId(); }); } @@ -335,65 +329,59 @@ public abstract class PluginManagerMain implements Disposable { protected void loadPluginsFromHostInBackground() { setDownloadStatus(true); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final List list = ContainerUtil.newArrayList(); - final Map errors = ContainerUtil.newLinkedHashMap(); - ProgressIndicator indicator = new EmptyProgressIndicator(); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final List list = ContainerUtil.newArrayList(); + final Map errors = ContainerUtil.newLinkedHashMap(); + ProgressIndicator indicator = new EmptyProgressIndicator(); - List hosts = RepositoryHelper.getPluginHosts(); - Set unique = ContainerUtil.newHashSet(); - for (String host : hosts) { - try { - if (host == null || acceptHost(host)) { - List plugins = RepositoryHelper.loadPlugins(host, indicator); - for (IdeaPluginDescriptor plugin : plugins) { - if (unique.add(plugin.getPluginId())) { - list.add(plugin); - } + List hosts = RepositoryHelper.getPluginHosts(); + Set unique = ContainerUtil.newHashSet(); + for (String host : hosts) { + try { + if (host == null || acceptHost(host)) { + List plugins = RepositoryHelper.loadPlugins(host, indicator); + for (IdeaPluginDescriptor plugin : plugins) { + if (unique.add(plugin.getPluginId())) { + list.add(plugin); } } } - catch (FileNotFoundException e) { - LOG.info(host, e); - } - catch (IOException e) { - LOG.info(host, e); - if (host != ApplicationInfoEx.getInstanceEx().getBuiltinPluginsUrl()) { - errors.put(host, String.format("'%s' for '%s'", e.getMessage(), host)); - } - } } - - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - setDownloadStatus(false); - - if (!list.isEmpty()) { - InstalledPluginsState state = InstalledPluginsState.getInstance(); - for (IdeaPluginDescriptor descriptor : list) { - state.onDescriptorDownload(descriptor); - } - - modifyPluginsList(list); - propagateUpdates(list); - } - - if (!errors.isEmpty()) { - String message = IdeBundle.message("error.list.of.plugins.was.not.loaded", - StringUtil.join(errors.keySet(), ", "), - StringUtil.join(errors.values(), ",\n")); - String title = IdeBundle.message("title.plugins"); - String ok = CommonBundle.message("button.retry"), cancel = CommonBundle.getCancelButtonText(); - if (Messages.showOkCancelDialog(message, title, ok, cancel, Messages.getErrorIcon()) == Messages.OK) { - loadPluginsFromHostInBackground(); - } - } + catch (FileNotFoundException e) { + LOG.info(host, e); + } + catch (IOException e) { + LOG.info(host, e); + if (host != ApplicationInfoEx.getInstanceEx().getBuiltinPluginsUrl()) { + errors.put(host, String.format("'%s' for '%s'", e.getMessage(), host)); } - }); + } } + + UIUtil.invokeLaterIfNeeded(() -> { + setDownloadStatus(false); + + if (!list.isEmpty()) { + InstalledPluginsState state = InstalledPluginsState.getInstance(); + for (IdeaPluginDescriptor descriptor : list) { + state.onDescriptorDownload(descriptor); + } + + modifyPluginsList(list); + propagateUpdates(list); + } + + if (!errors.isEmpty()) { + String message = IdeBundle.message("error.list.of.plugins.was.not.loaded", + StringUtil.join(errors.keySet(), ", "), + StringUtil.join(errors.values(), ",\n")); + String title = IdeBundle.message("title.plugins"); + String ok = CommonBundle.message("button.retry"), cancel = CommonBundle.getCancelButtonText(); + if (Messages.showOkCancelDialog(message, title, ok, cancel, Messages.getErrorIcon()) == Messages.OK) { + loadPluginsFromHostInBackground(); + } + } + }); }); } @@ -671,11 +659,8 @@ public abstract class PluginManagerMain implements Disposable { message += "Updated plugin '" + disabled.iterator().next().getName() + "' is disabled."; } else if (!disabled.isEmpty()) { - message += "Updated plugins " + StringUtil.join(disabled, new Function() { - @Override - public String fun(IdeaPluginDescriptor pluginDescriptor) { - return pluginDescriptor.getName(); - } + message += "Updated plugins " + StringUtil.join(disabled, pluginDescriptor -> { + return pluginDescriptor.getName(); }, ", ") + " are disabled."; } @@ -686,11 +671,8 @@ public abstract class PluginManagerMain implements Disposable { message += " plugin '" + disabledDependants.iterator().next().getName() + "'."; } else { - message += " plugins " + StringUtil.join(disabledDependants, new Function() { - @Override - public String fun(IdeaPluginDescriptor pluginDescriptor) { - return pluginDescriptor.getName(); - } + message += " plugins " + StringUtil.join(disabledDependants, pluginDescriptor -> { + return pluginDescriptor.getName(); }, ", ") + "."; } } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java index f8463dff4332..f119fedb297d 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java @@ -60,17 +60,11 @@ public class PluginTable extends JBTable { protected Transferable createTransferable(JComponent c) { final IdeaPluginDescriptor[] selectedValues = getSelectedObjects(); if (selectedValues == null) return null; - final String text = StringUtil.join(selectedValues, new Function() { - @Override - public String fun(IdeaPluginDescriptor descriptor) { - return descriptor.getName(); - } + final String text = StringUtil.join(selectedValues, descriptor -> { + return descriptor.getName(); }, ", "); - final String htmlText = "\n
      \n" + StringUtil.join(selectedValues, new Function() { - @Override - public String fun(IdeaPluginDescriptor descriptor) { - return descriptor.getName(); - } + final String htmlText = "\n
        \n" + StringUtil.join(selectedValues, descriptor -> { + return descriptor.getName(); }, "\n
      • ") + "
      \n\n"; return new TextTransferable(XmlStringUtil.wrapInHtml(htmlText), text); } diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginsTableRenderer.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginsTableRenderer.java index 71045b1e607a..671db000a630 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginsTableRenderer.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginsTableRenderer.java @@ -232,12 +232,9 @@ public class PluginsTableRenderer extends DefaultTableCellRenderer { sb.append(IdeBundle.message("plugin.manager.incompatible.ultimate.tooltip")); } else { - String deps = StringUtil.join(required, new Function() { - @Override - public String fun(PluginId id) { - IdeaPluginDescriptor plugin = PluginManager.getPlugin(id); - return plugin != null ? plugin.getName() : id.getIdString(); - } + String deps = StringUtil.join(required, id -> { + IdeaPluginDescriptor plugin = PluginManager.getPlugin(id); + return plugin != null ? plugin.getName() : id.getIdString(); }, ", "); sb.append(IdeBundle.message("plugin.manager.incompatible.deps.tooltip", required.size(), deps)); } diff --git a/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java index dcf12da8b06b..fa5b644f6ad9 100644 --- a/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java @@ -112,42 +112,35 @@ public class StartupManagerImpl extends StartupManagerEx { } public void runStartupActivities() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - @SuppressWarnings("SynchronizeOnThis") - public void run() { - AccessToken token = HeavyProcessLatch.INSTANCE.processStarted("Running Startup Activities"); - try { - runActivities(myPreStartupActivities); + ApplicationManager.getApplication().runReadAction(() -> { + AccessToken token = HeavyProcessLatch.INSTANCE.processStarted("Running Startup Activities"); + try { + runActivities(myPreStartupActivities); - // to avoid atomicity issues if runWhenProjectIsInitialized() is run at the same time - synchronized (StartupManagerImpl.this) { - myPreStartupActivitiesPassed = true; - myStartupActivitiesRunning = true; - } - - runActivities(myStartupActivities); - - synchronized (StartupManagerImpl.this) { - myStartupActivitiesRunning = false; - myStartupActivitiesPassed = true; - } + // to avoid atomicity issues if runWhenProjectIsInitialized() is run at the same time + synchronized (StartupManagerImpl.this) { + myPreStartupActivitiesPassed = true; + myStartupActivitiesRunning = true; } - finally { - token.finish(); + + runActivities(myStartupActivities); + + synchronized (StartupManagerImpl.this) { + myStartupActivitiesRunning = false; + myStartupActivitiesPassed = true; } } + finally { + token.finish(); + } }); } public void runPostStartupActivitiesFromExtensions() { for (final StartupActivity extension : Extensions.getExtensions(StartupActivity.POST_STARTUP_ACTIVITY)) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed()) { - extension.runActivity(myProject); - } + final Runnable runnable = () -> { + if (!myProject.isDisposed()) { + extension.runActivity(myProject); } }; if (extension instanceof DumbAware) { @@ -161,12 +154,7 @@ public class StartupManagerImpl extends StartupManagerEx { // queue each activity in smart mode separately so that if one of them starts dumb mode, the next ones just wait for it to finish private void queueSmartModeActivity(final Runnable activity) { - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - runActivity(activity); - } - }); + DumbService.getInstance(myProject).runWhenSmart(() -> runActivity(activity)); } public void runPostStartupActivities() { @@ -210,30 +198,27 @@ public class StartupManagerImpl extends StartupManagerEx { } public void scheduleInitialVfsRefresh() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; + UIUtil.invokeLaterIfNeeded(() -> { + if (myProject.isDisposed()) return; - markContentRootsForRefresh(); + markContentRootsForRefresh(); - Application app = ApplicationManager.getApplication(); - if (!app.isHeadlessEnvironment()) { - final long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); - final MessageBusConnection connection = app.getMessageBus().connect(); - connection.subscribe(ProjectLifecycleListener.TOPIC, new ProjectLifecycleListener.Adapter() { - @Override - public void afterProjectClosed(@NotNull Project project) { - if (project != myProject) return; + Application app = ApplicationManager.getApplication(); + if (!app.isHeadlessEnvironment()) { + final long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); + final MessageBusConnection connection = app.getMessageBus().connect(); + connection.subscribe(ProjectLifecycleListener.TOPIC, new ProjectLifecycleListener.Adapter() { + @Override + public void afterProjectClosed(@NotNull Project project) { + if (project != myProject) return; - RefreshQueue.getInstance().cancelSession(sessionId); - connection.disconnect(); - } - }); - } - else { - VirtualFileManager.getInstance().syncRefresh(); - } + RefreshQueue.getInstance().cancelSession(sessionId); + connection.disconnect(); + } + }); + } + else { + VirtualFileManager.getInstance().syncRefresh(); } }); } @@ -367,12 +352,9 @@ public class StartupManagerImpl extends StartupManagerEx { } } - Runnable runnable = new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed()) { - action.run(); - } + Runnable runnable = () -> { + if (!myProject.isDisposed()) { + action.run(); } }; if (application.isDispatchThread() && ModalityState.current() == ModalityState.NON_MODAL) { diff --git a/platform/platform-impl/src/com/intellij/ide/startupWizard/SelectPluginsStep.java b/platform/platform-impl/src/com/intellij/ide/startupWizard/SelectPluginsStep.java index e000ecb7e4a5..3445582b622f 100644 --- a/platform/platform-impl/src/com/intellij/ide/startupWizard/SelectPluginsStep.java +++ b/platform/platform-impl/src/com/intellij/ide/startupWizard/SelectPluginsStep.java @@ -151,11 +151,8 @@ public class SelectPluginsStep extends WizardStep { requiresBuffer.append(" ("); } requiresBuffer.append("required by "); - requiresBuffer.append(StringUtil.join(requiredBy, new Function() { - @Override - public String fun(IdeaPluginDescriptor ideaPluginDescriptor) { - return getAbbreviatedName(ideaPluginDescriptor); - } + requiresBuffer.append(StringUtil.join(requiredBy, ideaPluginDescriptor -> { + return getAbbreviatedName(ideaPluginDescriptor); }, ", ")); } if (requiresBuffer.length() > 0) { @@ -228,11 +225,7 @@ public class SelectPluginsStep extends WizardStep { } public void fillPlugins() { - Collections.sort(myPlugins, new Comparator() { - public int compare(final IdeaPluginDescriptor o1, final IdeaPluginDescriptor o2) { - return StringUtil.compare(o1.getName(), o2.getName(), true); - } - }); + Collections.sort(myPlugins, (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true)); myPluginsList.setModel(new CollectionListModel(myPlugins)); myPluginsList.setSelectedIndex(0); } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java b/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java index 6651cf9bdc7f..61300754dff2 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java @@ -251,14 +251,11 @@ public class AppearanceConfigurable extends BaseConfigurable implements Searchab final boolean wasDarcula = UIUtil.isUnderDarcula(); lafManager.setCurrentLookAndFeel(lafInfo); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (UIUtil.isUnderDarcula()) { - DarculaInstaller.install(); - } else if (wasDarcula) { - DarculaInstaller.uninstall(); - } + SwingUtilities.invokeLater(() -> { + if (UIUtil.isUnderDarcula()) { + DarculaInstaller.install(); + } else if (wasDarcula) { + DarculaInstaller.uninstall(); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomActionsSchema.java b/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomActionsSchema.java index 07fd68c3df0f..597814456df5 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomActionsSchema.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomActionsSchema.java @@ -211,14 +211,11 @@ public class CustomActionsSchema implements PersistentStateComponent { isFirstLoadState = false; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - initActionIcons(); + ApplicationManager.getApplication().invokeLater(() -> { + initActionIcons(); - if (reload) { - setCustomizationSchemaForCurrentProjects(); - } + if (reload) { + setCustomizationSchemaForCurrentProjects(); } }); } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java index 91fb3cff2250..30e959ef3ae5 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java @@ -165,13 +165,10 @@ public final class LafManagerImpl extends LafManager implements ApplicationCompo // do not sort LaFs on mac - the order is determined as Default, Darcula. // when we leave only system LaFs on other OSes, the order also should be determined as Default, Darcula - Arrays.sort(myLaFs, new Comparator() { - @Override - public int compare(UIManager.LookAndFeelInfo obj1, UIManager.LookAndFeelInfo obj2) { - String name1 = obj1.getName(); - String name2 = obj2.getName(); - return name1.compareToIgnoreCase(name2); - } + Arrays.sort(myLaFs, (obj1, obj2) -> { + String name1 = obj1.getName(); + String name2 = obj2.getName(); + return name1.compareToIgnoreCase(name2); }); } @@ -236,12 +233,9 @@ public final class LafManagerImpl extends LafManager implements ApplicationCompo @Override public void propertyChange(final PropertyChangeEvent evt) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - fixGtkPopupStyle(); - patchGtkDefaults(UIManager.getLookAndFeelDefaults()); - } + SwingUtilities.invokeLater(() -> { + fixGtkPopupStyle(); + patchGtkDefaults(UIManager.getLookAndFeelDefaults()); }); } }; diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java index 0ae2a1dc3caa..ae7e220dc9c7 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java @@ -438,12 +438,7 @@ public class DarculaLaf extends BasicLookAndFeel { myMnemonicAlarm.cancelAllRequests(); final Component focusOwner = IdeFocusManager.findInstance().getFocusOwner(); if (focusOwner != null) { - myMnemonicAlarm.addRequest(new Runnable() { - @Override - public void run() { - repaintMnemonics(focusOwner, myAltPressed); - } - }, 10); + myMnemonicAlarm.addRequest(() -> repaintMnemonics(focusOwner, myAltPressed), 10); } } return false; diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java index 3e788f9e549c..aeeab00fbe4b 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaRootPaneUI.java @@ -190,11 +190,9 @@ public class DarculaRootPaneUI extends BasicRootPaneUI { || (parent.getClass().getName().compareTo("javax.swing.Popup$HeavyWeightWindow") == 0)) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - root.removeHierarchyListener(myHierarchyListener); - myHierarchyListener = null; - } + SwingUtilities.invokeLater(() -> { + root.removeHierarchyListener(myHierarchyListener); + myHierarchyListener = null; }); } @@ -212,13 +210,11 @@ public class DarculaRootPaneUI extends BasicRootPaneUI { @Override public void windowClosed(WindowEvent e) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - Frame[] frames = Frame.getFrames(); - for (Frame frame : frames) { - if (frame.isDisplayable()) { - return; - } + SwingUtilities.invokeLater(() -> { + Frame[] frames = Frame.getFrames(); + for (Frame frame : frames) { + if (frame.isDisplayable()) { + return; } } }); @@ -242,35 +238,33 @@ public class DarculaRootPaneUI extends BasicRootPaneUI { private void processNewPosition() { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (myWindow == null) { - return; - } + SwingUtilities.invokeLater(() -> { + if (myWindow == null) { + return; + } - if (!myWindow.isShowing() || !myWindow.isDisplayable()) { - currentRootPaneGC = null; - return; - } + if (!myWindow.isShowing() || !myWindow.isDisplayable()) { + currentRootPaneGC = null; + return; + } - GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - GraphicsDevice[] gds = ge.getScreenDevices(); - if (gds.length == 1) { - return; - } - Point midLoc = new Point(myWindow.getLocationOnScreen().x + myWindow.getWidth() / 2, - myWindow.getLocationOnScreen().y + myWindow.getHeight() / 2); + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + GraphicsDevice[] gds = ge.getScreenDevices(); + if (gds.length == 1) { + return; + } + Point midLoc = new Point(myWindow.getLocationOnScreen().x + myWindow.getWidth() / 2, + myWindow.getLocationOnScreen().y + myWindow.getHeight() / 2); - for (GraphicsDevice gd : gds) { - GraphicsConfiguration gc = gd.getDefaultConfiguration(); - Rectangle bounds = gc.getBounds(); - if (bounds.contains(midLoc)) { - if (gc != currentRootPaneGC) { - currentRootPaneGC = gc; - setMaximized(); - } - break; + for (GraphicsDevice gd : gds) { + GraphicsConfiguration gc = gd.getDefaultConfiguration(); + Rectangle bounds = gc.getBounds(); + if (bounds.contains(midLoc)) { + if (gc != currentRootPaneGC) { + currentRootPaneGC = gc; + setMaximized(); } + break; } } }); diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java index 87db7cdbdb6d..b986f411ba63 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java @@ -118,11 +118,6 @@ public class DarculaTest { } } }, AWTEvent.KEY_EVENT_MASK); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - frame.setVisible(true); - } - }); + SwingUtilities.invokeLater(() -> frame.setVisible(true)); } } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/search/SearchUtil.java b/platform/platform-impl/src/com/intellij/ide/ui/search/SearchUtil.java index 70ad6d139253..8b57720c1ae3 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/search/SearchUtil.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/search/SearchUtil.java @@ -176,11 +176,9 @@ public class SearchUtil { final JComponent component, final String option, final GlassPanel glassPanel) { - return new Runnable() { - public void run() { - if (!traverseComponentsTree(configurable, glassPanel, component, option, true)) { - traverseComponentsTree(configurable, glassPanel, component, option, false); - } + return () -> { + if (!traverseComponentsTree(configurable, glassPanel, component, option, true)) { + traverseComponentsTree(configurable, glassPanel, component, option, false); } }; } @@ -507,20 +505,16 @@ public class SearchUtil { if (model.size() > 0) { - final Runnable onChosen = new Runnable() { - public void run() { - final Object selectedValue = list.getSelectedValue(); - if (selectedValue instanceof OptionDescription) { - final OptionDescription description = ((OptionDescription)selectedValue); - searchField.setText(description.getHit()); - searchField.addCurrentTextToHistory(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { //do not show look up again - showHintAlarm.cancelAllRequests(); - selectConfigurable.consume(description.getConfigurableId()); - } - }); - } + final Runnable onChosen = () -> { + final Object selectedValue = list.getSelectedValue(); + if (selectedValue instanceof OptionDescription) { + final OptionDescription description = ((OptionDescription)selectedValue); + searchField.setText(description.getHit()); + searchField.addCurrentTextToHistory(); + SwingUtilities.invokeLater(() -> { //do not show look up again + showHintAlarm.cancelAllRequests(); + selectConfigurable.consume(description.getConfigurableId()); + }); } }; final JBPopup popup = JBPopupFactory.getInstance() diff --git a/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java b/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java index 22945eff55c5..5657ffcd078d 100644 --- a/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java +++ b/platform/platform-impl/src/com/intellij/idea/IdeaApplication.java @@ -331,13 +331,10 @@ public class IdeaApplication { windowManager.showFrame(); } - app.invokeLater(new Runnable() { - @Override - public void run() { - if (mySplash != null) { - mySplash.dispose(); - mySplash = null; // Allow GC collect the splash window - } + app.invokeLater(() -> { + if (mySplash != null) { + mySplash.dispose(); + mySplash = null; // Allow GC collect the splash window } }, ModalityState.any()); diff --git a/platform/platform-impl/src/com/intellij/idea/SocketLock.java b/platform/platform-impl/src/com/intellij/idea/SocketLock.java index 0fcf78556d4f..5c2256b49218 100644 --- a/platform/platform-impl/src/com/intellij/idea/SocketLock.java +++ b/platform/platform-impl/src/com/intellij/idea/SocketLock.java @@ -115,42 +115,34 @@ public final class SocketLock { public ActivateStatus lock(@NotNull final String[] args) throws Exception { log("enter: lock(config=%s system=%s)", myConfigPath, mySystemPath); - return underLocks(new Callable() { - @Override - public ActivateStatus call() throws Exception { - File portMarkerC = new File(myConfigPath, PORT_FILE); - File portMarkerS = new File(mySystemPath, PORT_FILE); + return underLocks(() -> { + File portMarkerC = new File(myConfigPath, PORT_FILE); + File portMarkerS = new File(mySystemPath, PORT_FILE); - MultiMap portToPath = MultiMap.createSmart(); - addExistingPort(portMarkerC, myConfigPath, portToPath); - addExistingPort(portMarkerS, mySystemPath, portToPath); - if (!portToPath.isEmpty()) { - for (Map.Entry> entry : portToPath.entrySet()) { - ActivateStatus status = tryActivate(entry.getKey(), entry.getValue(), args); - if (status != ActivateStatus.NO_INSTANCE) { - return status; - } + MultiMap portToPath = MultiMap.createSmart(); + addExistingPort(portMarkerC, myConfigPath, portToPath); + addExistingPort(portMarkerS, mySystemPath, portToPath); + if (!portToPath.isEmpty()) { + for (Map.Entry> entry : portToPath.entrySet()) { + ActivateStatus status = tryActivate(entry.getKey(), entry.getValue(), args); + if (status != ActivateStatus.NO_INSTANCE) { + return status; } } - - if (isShutdownCommand()) { - System.exit(0); - } - final String[] lockedPaths = {myConfigPath, mySystemPath}; - int workerCount = PlatformUtils.isIdeaCommunity() || PlatformUtils.isDatabaseIDE() || PlatformUtils.isCidr() ? 1 : 2; - myServer = BuiltInServer.startNioOrOio(workerCount, 6942, 50, false, new NotNullProducer() { - @NotNull - @Override - public ChannelHandler produce() { - return new MyChannelInboundHandler(lockedPaths, myActivateListener); - } - }); - byte[] portBytes = Integer.toString(myServer.getPort()).getBytes(CharsetToolkit.UTF8_CHARSET); - FileUtil.writeToFile(portMarkerC, portBytes); - FileUtil.writeToFile(portMarkerS, portBytes); - log("exit: lock(): succeed"); - return ActivateStatus.NO_INSTANCE; } + + if (isShutdownCommand()) { + System.exit(0); + } + final String[] lockedPaths = {myConfigPath, mySystemPath}; + int workerCount = PlatformUtils.isIdeaCommunity() || PlatformUtils.isDatabaseIDE() || PlatformUtils.isCidr() ? 1 : 2; + myServer = BuiltInServer.startNioOrOio(workerCount, 6942, 50, false, + () -> new MyChannelInboundHandler(lockedPaths, myActivateListener)); + byte[] portBytes = Integer.toString(myServer.getPort()).getBytes(CharsetToolkit.UTF8_CHARSET); + FileUtil.writeToFile(portMarkerC, portBytes); + FileUtil.writeToFile(portMarkerS, portBytes); + log("exit: lock(): succeed"); + return ActivateStatus.NO_INSTANCE; }); } diff --git a/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java b/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java index 140246f6c228..cc28a9cd01d5 100644 --- a/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java +++ b/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java @@ -75,22 +75,19 @@ public class DebugAttachDetector { if (myPort < 0) return; - myTask = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - boolean attached = !NetUtils.canConnectToRemoteSocket(myHost, myPort); - if (!myReady) { - myAttached = attached; - myReady = true; - } - else if (attached != myAttached) { - myAttached = attached; - Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, - "Remote debugger", - myAttached ? "attached" : "detached", - NotificationType.WARNING)); - } - } - }, 5, 5, TimeUnit.SECONDS); + myTask = JobScheduler.getScheduler().scheduleWithFixedDelay(() -> { + boolean attached = !NetUtils.canConnectToRemoteSocket(myHost, myPort); + if (!myReady) { + myAttached = attached; + myReady = true; + } + else if (attached != myAttached) { + myAttached = attached; + Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, + "Remote debugger", + myAttached ? "attached" : "detached", + NotificationType.WARNING)); + } + }, 5, 5, TimeUnit.SECONDS); } } diff --git a/platform/platform-impl/src/com/intellij/internal/anomalies/TopAnomaliesAction.java b/platform/platform-impl/src/com/intellij/internal/anomalies/TopAnomaliesAction.java index 5e0d78d23d42..3c5ae79c952a 100644 --- a/platform/platform-impl/src/com/intellij/internal/anomalies/TopAnomaliesAction.java +++ b/platform/platform-impl/src/com/intellij/internal/anomalies/TopAnomaliesAction.java @@ -36,23 +36,20 @@ import java.util.TreeSet; * User: Vassiliy.Kudryashov */ public class TopAnomaliesAction extends ActionGroup { - private static final Comparator> COMPARATOR = new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - int i = o2.getSecond() - o1.getSecond(); - if (i != 0) { - return i; - } - int h1 = o1.hashCode(); - int h2 = o2.hashCode(); - if (h1 > h2) { - return 1; - } - if (h1 < h2) { - return -1; - } - return 0; + private static final Comparator> COMPARATOR = (o1, o2) -> { + int i = o2.getSecond() - o1.getSecond(); + if (i != 0) { + return i; } + int h1 = o1.hashCode(); + int h2 = o2.hashCode(); + if (h1 > h2) { + return 1; + } + if (h1 < h2) { + return -1; + } + return 0; }; private static final int LIMIT = 10; diff --git a/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java b/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java index 6edcdc6a12cd..d07dd0f995e6 100644 --- a/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java +++ b/platform/platform-impl/src/com/intellij/internal/inspector/UiInspectorAction.java @@ -884,16 +884,13 @@ public class UiInspectorAction extends ToggleAction implements DumbAware { final Method finalGetter = getter; final Method setter = myComponent.getClass().getMethod("set" + StringUtil.capitalize(name), getter.getReturnType()); setter.setAccessible(true); - return new Function() { - @Override - public Object fun(Object o) { - try { - setter.invoke(myComponent, fromObject(o, finalGetter.getReturnType())); - return finalGetter.invoke(myComponent); - } - catch (Exception e) { - throw new RuntimeException(e); - } + return o -> { + try { + setter.invoke(myComponent, fromObject(o, finalGetter.getReturnType())); + return finalGetter.invoke(myComponent); + } + catch (Exception e) { + throw new RuntimeException(e); } }; } @@ -902,16 +899,13 @@ public class UiInspectorAction extends ToggleAction implements DumbAware { if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { return null; } - return new Function() { - @Override - public Object fun(Object o) { - try { - field.set(myComponent, fromObject(o, field.getType())); - return field.get(myComponent); - } - catch (Exception e) { - throw new RuntimeException(e); - } + return o -> { + try { + field.set(myComponent, fromObject(o, field.getType())); + return field.get(myComponent); + } + catch (Exception e1) { + throw new RuntimeException(e1); } }; } diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/UsageTrigger.java b/platform/platform-impl/src/com/intellij/internal/statistic/UsageTrigger.java index 9a93ede4f5c3..c03eca78eea7 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/UsageTrigger.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/UsageTrigger.java @@ -82,10 +82,8 @@ public class UsageTrigger implements PersistentStateComponent getUsages() { State state = getInstance().getState(); assert state != null; - return ContainerUtil.map2Set(state.myValues.entrySet(), new Function, UsageDescriptor>() { - public UsageDescriptor fun(final Map.Entry e) { - return new UsageDescriptor(e.getKey(), e.getValue()); - } + return ContainerUtil.map2Set(state.myValues.entrySet(), e -> { + return new UsageDescriptor(e.getKey(), e.getValue()); }); } diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/beans/ConvertUsagesUtil.java b/platform/platform-impl/src/com/intellij/internal/statistic/beans/ConvertUsagesUtil.java index 97bbea8fde45..69f5b94e1910 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/beans/ConvertUsagesUtil.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/beans/ConvertUsagesUtil.java @@ -149,11 +149,9 @@ public class ConvertUsagesUtil { //@NotNull public static Map> sortDescriptorsByPriority(Map> descriptors) { assert descriptors != null; - final SortedMap> map = new TreeMap>(new Comparator() { - public int compare(GroupDescriptor g1, GroupDescriptor g2) { - final int priority = (int)(g2.getPriority() - g1.getPriority()); - return priority == 0 ? g1.getId().compareTo(g2.getId()) : priority; - } + final SortedMap> map = new TreeMap>((g1, g2) -> { + final int priority = (int)(g2.getPriority() - g1.getPriority()); + return priority == 0 ? g1.getId().compareTo(g2.getId()) : priority; }); map.putAll(descriptors); diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsConnectionService.java b/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsConnectionService.java index b2d2eb6fd3db..fb1f8acbd1e0 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsConnectionService.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsConnectionService.java @@ -60,11 +60,8 @@ public class StatisticsConnectionService extends SettingsConnectionService { } final List disabledGroupsList = StringUtil.split(disabledGroupsString, ","); - return ContainerUtil.map2Set(disabledGroupsList, new Function() { - @Override - public String fun(String s) { - return s.trim(); - } + return ContainerUtil.map2Set(disabledGroupsList, s -> { + return s.trim(); }); } } diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/persistence/ApplicationStatisticsPersistenceComponent.java b/platform/platform-impl/src/com/intellij/internal/statistic/persistence/ApplicationStatisticsPersistenceComponent.java index 10a7d7acd028..d9266935d53d 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/persistence/ApplicationStatisticsPersistenceComponent.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/persistence/ApplicationStatisticsPersistenceComponent.java @@ -156,13 +156,10 @@ public class ApplicationStatisticsPersistenceComponent extends ApplicationStatis private static String joinUsages(@NotNull Set usages) { // for instance, usage can be: "_foo"(equals "_foo=1") or "_foo=2" - return StringUtil.join(usages, new Function() { - @Override - public String fun(UsageDescriptor usageDescriptor) { - final String key = usageDescriptor.getKey(); - final int value = usageDescriptor.getValue(); - return value != 1 ? key + "=" + value : key; - } + return StringUtil.join(usages, usageDescriptor -> { + final String key = usageDescriptor.getKey(); + final int value = usageDescriptor.getValue(); + return value != 1 ? key + "=" + value : key; }, TOKENIZER); } @@ -196,12 +193,9 @@ public class ApplicationStatisticsPersistenceComponent extends ApplicationStatis } private void persistPeriodically() { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - persistOpenedProjects(); - persistPeriodically(); - } + myAlarm.addRequest(() -> { + persistOpenedProjects(); + persistPeriodically(); }, PERSIST_PERIOD); } diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/tmp/SendStatisticsAction.java b/platform/platform-impl/src/com/intellij/internal/statistic/tmp/SendStatisticsAction.java index c8f75a6aab2e..068731eaa6d5 100755 --- a/platform/platform-impl/src/com/intellij/internal/statistic/tmp/SendStatisticsAction.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/tmp/SendStatisticsAction.java @@ -46,14 +46,10 @@ public class SendStatisticsAction extends AnAction { StatisticsService service = StatisticsUploadAssistant.getStatisticsService(); final StatisticsResult result = service.send(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMultilineInputDialog(project, "Result: " + result.getCode(), "Statistics Result", - StringUtil.replace(result.getDescription(), ";", "\n"), - null, null); - } - }, ModalityState.NON_MODAL, project.getDisposed()); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showMultilineInputDialog(project, "Result: " + result.getCode(), "Statistics Result", + StringUtil.replace(result.getDescription(), ";", "\n"), + null, null), ModalityState.NON_MODAL, project.getDisposed()); } }); } diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/updater/SendStatisticsComponent.java b/platform/platform-impl/src/com/intellij/internal/statistic/updater/SendStatisticsComponent.java index 7a37f12deb04..ac63c6e31b30 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/updater/SendStatisticsComponent.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/updater/SendStatisticsComponent.java @@ -79,12 +79,7 @@ public class SendStatisticsComponent implements ApplicationComponent { @Override public void onFrameActivated() { if (isEmpty(((WindowManagerEx)WindowManager.getInstance()).getMostRecentFocusedWindow())) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - StatisticsNotificationManager.showNotification(statisticsService); - } - }); + ApplicationManager.getApplication().invokeLater(() -> StatisticsNotificationManager.showNotification(statisticsService)); myFrameStateManager.removeListener(this); } } @@ -107,12 +102,7 @@ public class SendStatisticsComponent implements ApplicationComponent { } private void runWithDelay(final @NotNull StatisticsService statisticsService) { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - statisticsService.send(); - } - }, Time.MINUTE * DELAY_IN_MIN); + myAlarm.addRequest(() -> statisticsService.send(), Time.MINUTE * DELAY_IN_MIN); } @Override diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/updater/StatisticsNotificationManager.java b/platform/platform-impl/src/com/intellij/internal/statistic/updater/StatisticsNotificationManager.java index 4fe3863522ca..327cbc773727 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/updater/StatisticsNotificationManager.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/updater/StatisticsNotificationManager.java @@ -48,12 +48,7 @@ public class StatisticsNotificationManager { mySettings.setShowNotification(false); notification.expire(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - myStatisticsService.send(); - } - }); + ApplicationManager.getApplication().executeOnPooledThread((Runnable)() -> myStatisticsService.send()); } else if ("decline".equals(description)) { mySettings.setAllowed(false); diff --git a/platform/platform-impl/src/com/intellij/internal/ui/AnimatorTestAction.java b/platform/platform-impl/src/com/intellij/internal/ui/AnimatorTestAction.java index 9213d0b54ff3..6ce288d5d2b1 100644 --- a/platform/platform-impl/src/com/intellij/internal/ui/AnimatorTestAction.java +++ b/platform/platform-impl/src/com/intellij/internal/ui/AnimatorTestAction.java @@ -36,17 +36,8 @@ import java.util.concurrent.TimeUnit; public class AnimatorTestAction extends AnAction { @Override public void actionPerformed(final AnActionEvent e) { - ScheduledFuture future = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - TimeoutUtil.sleep(30); - } - }); - } - }, 0, 123, TimeUnit.MILLISECONDS); + ScheduledFuture future = JobScheduler.getScheduler().scheduleWithFixedDelay( + () -> SwingUtilities.invokeLater(() -> TimeoutUtil.sleep(30)), 0, 123, TimeUnit.MILLISECONDS); try { new DialogWrapper(e.getProject()) { diff --git a/platform/platform-impl/src/com/intellij/internal/validation/CheckMessagesButtonsOrderAction.java b/platform/platform-impl/src/com/intellij/internal/validation/CheckMessagesButtonsOrderAction.java index 3e28560955c2..1b44980f0119 100644 --- a/platform/platform-impl/src/com/intellij/internal/validation/CheckMessagesButtonsOrderAction.java +++ b/platform/platform-impl/src/com/intellij/internal/validation/CheckMessagesButtonsOrderAction.java @@ -37,109 +37,106 @@ public class CheckMessagesButtonsOrderAction extends AnAction implements DumbAw super.run(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { + SwingUtilities.invokeLater(() -> { - // Case 0 + // Case 0 - String message = 2 + " usage" + (2 > 1 ? "s were" : " was") + - " found in comments and non-code files.\nWould you like to rename " + (2 > 1 ? "them" : "it") + "?"; - String[] options = {"Show Usages", "Cancel", "Rename Only Code Usages", "Rename All Usages"}; - int focusedOptionIndex = 2; - Messages.showDialog(message, "Rename", options, 0, focusedOptionIndex, Messages.getQuestionIcon(), null); + String message = 2 + " usage" + (2 > 1 ? "s were" : " was") + + " found in comments and non-code files.\nWould you like to rename " + (2 > 1 ? "them" : "it") + "?"; + String[] options = {"Show Usages", "Cancel", "Rename Only Code Usages", "Rename All Usages"}; + int focusedOptionIndex = 2; + Messages.showDialog(message, "Rename", options, 0, focusedOptionIndex, Messages.getQuestionIcon(), null); - // Case 1 + // Case 1 - Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____,Cancel, *Show ussages*", - "Message 1", new String [] {"Show usages", "Cancel", "Proceed"}, 0, 0, - Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____,Cancel, *Show ussages*", + "Message 1", new String [] {"Show usages", "Cancel", "Proceed"}, 0, 0, + Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 2 + // Case 2 - Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____,Cancel, *Show ussages*", - "Message 2", new String [] {"Show usages", "Cancel", "Proceed"}, 0, 1, - Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____,Cancel, *Show ussages*", + "Message 2", new String [] {"Show usages", "Cancel", "Proceed"}, 0, 1, + Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 3 + // Case 3 - Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____, *Cancel*, Show ussages", - "Message 3", new String [] {"Show usages", "Cancel", "Proceed"}, 1, 0, - Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____, *Cancel*, Show ussages", + "Message 3", new String [] {"Show usages", "Cancel", "Proceed"}, 1, 0, + Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 4 + // Case 4 - Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____, *Cancel*, Show ussages", - "Message 4", new String [] {"Show usages", "Cancel", "Proceed"}, 1, 1, - Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog("unchecked unfocused checkbox, [Proceed], ____, *Cancel*, Show ussages", + "Message 4", new String [] {"Show usages", "Cancel", "Proceed"}, 1, 1, + Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 5 + // Case 5 - Messages.showDialog("[Proceed], ____, Cancel, *Show ussages*", - "Message 5", new String [] {"Show usages", "Cancel", "Proceed"}, 0, 1, - Messages.getQuestionIcon(), null); + Messages.showDialog("[Proceed], ____, Cancel, *Show ussages*", + "Message 5", new String [] {"Show usages", "Cancel", "Proceed"}, 0, 1, + Messages.getQuestionIcon(), null); - // Case 6 + // Case 6 - Messages.showYesNoCancelDialog("unchecked unfocused checkbox, [New Window], ____, Cancel, *This Window*", - "Message 6", - "This window", - "New Window", - CommonBundle.getCancelButtonText(), - Messages.getQuestionIcon(), - new ProjectNewWindowDoNotAskOption()); + Messages.showYesNoCancelDialog("unchecked unfocused checkbox, [New Window], ____, Cancel, *This Window*", + "Message 6", + "This window", + "New Window", + CommonBundle.getCancelButtonText(), + Messages.getQuestionIcon(), + new ProjectNewWindowDoNotAskOption()); - // Case 7 + // Case 7 - Messages.showDialog("[Variant 1], Variant 2, Variant 3, Cancel, *Ok*", - "Message 7", - new String[]{"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, - 0, 1, Messages.getQuestionIcon(), null); + Messages.showDialog("[Variant 1], Variant 2, Variant 3, Cancel, *Ok*", + "Message 7", + new String[]{"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, + 0, 1, Messages.getQuestionIcon(), null); - // Case 8 + // Case 8 - Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, Cancel, *Ok*", - "Message 8", - new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, - 0, 0, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, Cancel, *Ok*", + "Message 8", + new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, + 0, 0, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 9 + // Case 9 - Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, *Cancel*, Ok", - "Message 9", - new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, - 1, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, *Cancel*, Ok", + "Message 9", + new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, + 1, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 10 + // Case 10 - Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, Cancel, *Ok*", - "Message 10", - new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, - 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, Cancel, *Ok*", + "Message 10", + new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, + 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 11 + // Case 11 - Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, Cancel, *Ok*", - "Message 11", - new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, - 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog( "unchecked unfocused checkbox, [Variant 1], Variant 2, Variant 3, Cancel, *Ok*", + "Message 11", + new String [] {"Ok", "Cancel", "Variant 3", "Variant 2", "Variant 1"}, + 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 12 + // Case 12 - Messages.showDialog( "unchecked unfocused checkbox, [Cancel], Variant 1, Variant 2, Variant 3, *Ok*", - "Message 12", - new String [] {"Ok", "Variant 3", "Variant 2", "Variant 1", "Cancel"}, - 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog( "unchecked unfocused checkbox, [Cancel], Variant 1, Variant 2, Variant 3, *Ok*", + "Message 12", + new String [] {"Ok", "Variant 3", "Variant 2", "Variant 1", "Cancel"}, + 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - // Case 13 + // Case 13 - Messages.showDialog( "unchecked unfocused checkbox, [Cancel], Variant 1, Ok, Variant 2, Variant 3, *Ok*", - "Message 13", - new String [] {"Variant 3", "Variant 2", "Ok", "Variant 1", "Cancel"}, - 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); + Messages.showDialog( "unchecked unfocused checkbox, [Cancel], Variant 1, Ok, Variant 2, Variant 3, *Ok*", + "Message 13", + new String [] {"Variant 3", "Variant 2", "Ok", "Variant 1", "Cancel"}, + 0, 1, Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption()); - } }); } diff --git a/platform/platform-impl/src/com/intellij/internal/validation/MacMessagesTest.java b/platform/platform-impl/src/com/intellij/internal/validation/MacMessagesTest.java index be94c5a1c816..9383aa2b1f17 100644 --- a/platform/platform-impl/src/com/intellij/internal/validation/MacMessagesTest.java +++ b/platform/platform-impl/src/com/intellij/internal/validation/MacMessagesTest.java @@ -111,13 +111,10 @@ public class MacMessagesTest extends AnAction { public void actionPerformed(ActionEvent e) { final Task task = new Task.Modal(null, "Test task", true) { public void run(@NotNull final ProgressIndicator indicator) { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - FocusManagerImpl fmi = FocusManagerImpl.getInstance(); - final Project p = fmi.getLastFocusedFrame().getProject(); - showTestMessage(p); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + FocusManagerImpl fmi1 = FocusManagerImpl.getInstance(); + final Project p1 = fmi1.getLastFocusedFrame().getProject(); + showTestMessage(p1); }, ModalityState.any()); } diff --git a/platform/platform-impl/src/com/intellij/internal/validation/TestDnd.java b/platform/platform-impl/src/com/intellij/internal/validation/TestDnd.java index e8f913235a9a..830e724cde6e 100644 --- a/platform/platform-impl/src/com/intellij/internal/validation/TestDnd.java +++ b/platform/platform-impl/src/com/intellij/internal/validation/TestDnd.java @@ -47,18 +47,8 @@ public class TestDnd extends AnAction { protected JComponent createCenterPanel() { JBList list = new JBList(new String[]{"1111111", "222222", "333333", "44444", "555555555555555555555555"}); DnDSupport.createBuilder(list) - .setBeanProvider(new Function() { - @Override - public DnDDragStartBean fun(DnDActionInfo info) { - return new DnDDragStartBean("something"); - } - }) - .setImageProvider(new Function() { - @Override - public DnDImage fun(DnDActionInfo info) { - return new DnDImage(IconUtil.toImage(AllIcons.Icon)); - } - }) + .setBeanProvider(info -> new DnDDragStartBean("something")) + .setImageProvider(info -> new DnDImage(IconUtil.toImage(AllIcons.Icon))) .install(); return list; diff --git a/platform/platform-impl/src/com/intellij/internal/validation/TestMacMessagesSequencesAction.java b/platform/platform-impl/src/com/intellij/internal/validation/TestMacMessagesSequencesAction.java index 1d4392d799c6..3797eebfeb4b 100644 --- a/platform/platform-impl/src/com/intellij/internal/validation/TestMacMessagesSequencesAction.java +++ b/platform/platform-impl/src/com/intellij/internal/validation/TestMacMessagesSequencesAction.java @@ -29,11 +29,8 @@ public class TestMacMessagesSequencesAction extends AnAction { public void actionPerformed(AnActionEvent e) { for (int i=0;i<10;i++){ final int k = i; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Messages.showDialog("Message # " + k, "Title of " + k, new String[] { "Option one", "Option two" }, 0, Messages.getQuestionIcon()); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showDialog("Message # " + k, "Title of " + k, new String[] { "Option one", "Option two" }, 0, Messages.getQuestionIcon())); } } diff --git a/platform/platform-impl/src/com/intellij/notification/EventLog.java b/platform/platform-impl/src/com/intellij/notification/EventLog.java index fc03c6b20f6a..bd7926eb550e 100644 --- a/platform/platform-impl/src/com/intellij/notification/EventLog.java +++ b/platform/platform-impl/src/com/intellij/notification/EventLog.java @@ -442,18 +442,15 @@ public class EventLog { } private static void activate(@NotNull ToolWindow eventLog, @Nullable final String groupId, @Nullable final Runnable r) { - eventLog.activate(new Runnable() { - @Override - public void run() { - if (groupId == null) return; - String contentName = getContentName(groupId); - Content content = eventLog.getContentManager().findContent(contentName); - if (content != null) { - eventLog.getContentManager().setSelectedContent(content); - } - if (r != null) { - r.run(); - } + eventLog.activate(() -> { + if (groupId == null) return; + String contentName = getContentName(groupId); + Content content = eventLog.getContentManager().findContent(contentName); + if (content != null) { + eventLog.getContentManager().setSelectedContent(content); + } + if (r != null) { + r.run(); } }, true); } @@ -519,10 +516,8 @@ public class EventLog { @Override public void run() { if (!ShutDownTracker.isShutdownHookRunning() && !myProject.isDisposed()) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - console.doPrintNotification(notification); - } + ApplicationManager.getApplication().runReadAction(() -> { + console.doPrintNotification(notification); }); } } @@ -532,13 +527,10 @@ public class EventLog { private void showNotification(@NotNull final String groupId, @NotNull final List ids) { ToolWindow eventLog = getEventLog(myProject); if (eventLog != null) { - activate(eventLog, groupId, new Runnable() { - @Override - public void run() { - EventLogConsole console = getConsole(groupId); - if (console != null) { - console.showNotification(ids); - } + activate(eventLog, groupId, () -> { + EventLogConsole console = getConsole(groupId); + if (console != null) { + console.showNotification(ids); } }); } diff --git a/platform/platform-impl/src/com/intellij/notification/EventLogConsole.java b/platform/platform-impl/src/com/intellij/notification/EventLogConsole.java index 199ba24103d4..3388d3c92d2b 100644 --- a/platform/platform-impl/src/com/intellij/notification/EventLogConsole.java +++ b/platform/platform-impl/src/com/intellij/notification/EventLogConsole.java @@ -172,16 +172,13 @@ class EventLogConsole { return; } int offset = editor.logicalPositionToOffset(position); - editor.getMarkupModel().processRangeHighlightersOverlappingWith(offset, offset, new Processor() { - @Override - public boolean process(RangeHighlighterEx rangeHighlighter) { - String groupId = GROUP_ID.get(rangeHighlighter); - if (groupId != null) { - addConfigureNotificationAction(actions, groupId); - return false; - } - return true; + editor.getMarkupModel().processRangeHighlightersOverlappingWith(offset, offset, rangeHighlighter -> { + String groupId = GROUP_ID.get(rangeHighlighter); + if (groupId != null) { + addConfigureNotificationAction(actions, groupId); + return false; } + return true; }); } @@ -341,27 +338,24 @@ class EventLogConsole { final Document document = getConsoleEditor().getDocument(); - final Runnable removeHandler = new Runnable() { - @Override - public void run() { - TextAttributes expired = - EditorColorsManager.getInstance().getGlobalScheme().getAttributes(ConsoleViewContentType.LOG_EXPIRED_ENTRY); - TextAttributes italic = new TextAttributes(null, null, null, null, Font.ITALIC); - for (RangeHighlighter colorHighlighter : lineColors) { - if (colorHighlighter.isValid()) { - int line = document.getLineNumber(colorHighlighter.getStartOffset()); + final Runnable removeHandler = () -> { + TextAttributes expired = + EditorColorsManager.getInstance().getGlobalScheme().getAttributes(ConsoleViewContentType.LOG_EXPIRED_ENTRY); + TextAttributes italic = new TextAttributes(null, null, null, null, Font.ITALIC); + for (RangeHighlighter colorHighlighter : lineColors) { + if (colorHighlighter.isValid()) { + int line = document.getLineNumber(colorHighlighter.getStartOffset()); - markupModel.addLineHighlighter(line, HighlighterLayer.CARET_ROW + 1, expired); + markupModel.addLineHighlighter(line, HighlighterLayer.CARET_ROW + 1, expired); - for (RangeHighlighter highlighter : myHyperlinkSupport.getValue().findAllHyperlinksOnLine(line)) { - markupModel - .addRangeHighlighter(highlighter.getStartOffset(), highlighter.getEndOffset(), HighlighterLayer.CARET_ROW + 2, italic, - HighlighterTargetArea.EXACT_RANGE); - myHyperlinkSupport.getValue().removeHyperlink(highlighter); - } + for (RangeHighlighter highlighter : myHyperlinkSupport.getValue().findAllHyperlinksOnLine(line)) { + markupModel + .addRangeHighlighter(highlighter.getStartOffset(), highlighter.getEndOffset(), HighlighterLayer.CARET_ROW + 2, italic, + HighlighterTargetArea.EXACT_RANGE); + myHyperlinkSupport.getValue().removeHyperlink(highlighter); } - markupModel.removeHighlighter(colorHighlighter); } + markupModel.removeHighlighter(colorHighlighter); } }; if (!notification.isExpired()) { @@ -432,15 +426,12 @@ class EventLogConsole { final Ref highlighter = new Ref<>(); editor.getMarkupModel() - .processRangeHighlightersOverlappingWith(0, editor.getDocument().getTextLength(), new Processor() { - @Override - public boolean process(RangeHighlighterEx rangeHighlighter) { - if (id.equals(NOTIFICATION_ID.get(rangeHighlighter))) { - highlighter.set(rangeHighlighter); - return false; - } - return true; + .processRangeHighlightersOverlappingWith(0, editor.getDocument().getTextLength(), rangeHighlighter -> { + if (id.equals(NOTIFICATION_ID.get(rangeHighlighter))) { + highlighter.set(rangeHighlighter); + return false; } + return true; }); return highlighter.get(); diff --git a/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java b/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java index 71cc4ba11b70..0001f57221fa 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/IdeNotificationArea.java @@ -68,17 +68,8 @@ public class IdeNotificationArea extends JLabel implements CustomStatusBarWidget } }.installOn(this); - ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(LogModel.LOG_MODEL_CHANGED, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - updateStatus(); - } - }); - } - }); + ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(LogModel.LOG_MODEL_CHANGED, + () -> ApplicationManager.getApplication().invokeLater(() -> updateStatus())); } public WidgetPresentation getPresentation(@NotNull PlatformType type) { diff --git a/platform/platform-impl/src/com/intellij/notification/impl/MacEventReader.java b/platform/platform-impl/src/com/intellij/notification/impl/MacEventReader.java index 599c26df18d2..473489ba5fa0 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/MacEventReader.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/MacEventReader.java @@ -70,18 +70,15 @@ class MacEventReader { if (!message.isEmpty()) { final String copy = message; - getService().submit(new Runnable() { - @Override - public void run() { - try { - Runtime.getRuntime().exec("say " + copy).waitFor(); - } - catch (IOException e) { - LOG.warn(e); - } - catch (InterruptedException e) { - LOG.warn(e); - } + getService().submit(() -> { + try { + Runtime.getRuntime().exec("say " + copy).waitFor(); + } + catch (IOException e) { + LOG.warn(e); + } + catch (InterruptedException e) { + LOG.warn(e); } }); } diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurable.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurable.java index 99871d163225..197675ee456e 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurable.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurable.java @@ -83,11 +83,6 @@ public class NotificationsConfigurable implements Configurable, SearchableConfig @Override public Runnable enableSearch(final String option) { - return new Runnable() { - @Override - public void run() { - myComponent.selectGroup(option); - } - }; + return () -> myComponent.selectGroup(option); } } diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurationImpl.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurationImpl.java index 048d4502de98..fc793c27fc00 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurationImpl.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsConfigurationImpl.java @@ -50,12 +50,8 @@ public class NotificationsConfigurationImpl private static final String SHOW_BALLOONS_ATTRIBUTE = "showBalloons"; private static final String SYSTEM_NOTIFICATIONS_ATTRIBUTE = "systemNotifications"; - private static final Comparator NOTIFICATION_SETTINGS_COMPARATOR = new Comparator() { - @Override - public int compare(@NotNull NotificationSettings o1, @NotNull NotificationSettings o2) { - return o1.getGroupId().compareToIgnoreCase(o2.getGroupId()); - } - }; + private static final Comparator NOTIFICATION_SETTINGS_COMPARATOR = + (o1, o2) -> o1.getGroupId().compareToIgnoreCase(o2.getGroupId()); private final Map myIdToSettingsMap = new THashMap(); private final Map myToolWindowCapable = new THashMap(); diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java index 503c0bbf29fa..14345a677cf3 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java @@ -98,12 +98,7 @@ public class NotificationsManagerImpl extends NotificationsManager { @Override public void expire(@NotNull final Notification notification) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - EventLog.expireNotification(notification); - } - }); + UIUtil.invokeLaterIfNeeded(() -> EventLog.expireNotification(notification)); } @Override @@ -157,11 +152,8 @@ public class NotificationsManagerImpl extends NotificationsManager { private static void showNotification(@NotNull final Notification notification, @Nullable final Project project) { Application application = ApplicationManager.getApplication(); if (application instanceof ApplicationEx && !((ApplicationEx)application).isLoaded()) { - application.invokeLater(new Runnable() { - @Override - public void run() { - showNotification(notification, project); - } + application.invokeLater(() -> { + showNotification(notification, project); }, ModalityState.current()); return; } @@ -1244,22 +1236,12 @@ public class NotificationsManagerImpl extends NotificationsManager { @Override public Dimension preferredLayoutSize(Container parent) { - return layoutSize(new Function() { - @Override - public Dimension fun(Component component) { - return component.getPreferredSize(); - } - }); + return layoutSize(component -> component.getPreferredSize()); } @Override public Dimension minimumLayoutSize(Container parent) { - return layoutSize(new Function() { - @Override - public Dimension fun(Component component) { - return component.getMinimumSize(); - } - }); + return layoutSize(component -> component.getMinimumSize()); } private Dimension layoutSize(@NotNull Function size) { diff --git a/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java b/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java index b46254eb6a1c..5cdb671deb2e 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java @@ -128,12 +128,7 @@ public class NotificationTestAction extends AnAction implements DumbAware { notification.expire(); } }); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - myMessageBus.syncPublisher(Notifications.TOPIC).notify(notification); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> myMessageBus.syncPublisher(Notifications.TOPIC).notify(notification)); } private void newNotification(String text) { @@ -192,12 +187,9 @@ public class NotificationTestAction extends AnAction implements DumbAware { } } - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - for (NotificationInfo info : notifications) { - myMessageBus.syncPublisher(Notifications.TOPIC).notify(info.getNotification()); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + for (NotificationInfo info : notifications) { + myMessageBus.syncPublisher(Notifications.TOPIC).notify(info.getNotification()); } }); } diff --git a/platform/platform-impl/src/com/intellij/notification/impl/actions/ShowDelayedMessageInternalAction.java b/platform/platform-impl/src/com/intellij/notification/impl/actions/ShowDelayedMessageInternalAction.java index aa4d7e06c7b7..8ac707672ab3 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/actions/ShowDelayedMessageInternalAction.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/actions/ShowDelayedMessageInternalAction.java @@ -41,14 +41,9 @@ public class ShowDelayedMessageInternalAction extends AnAction implements DumbAw TimeoutUtil.sleep(3000); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - MessageDialogBuilder.yesNo("Nothing happens after that", "Some message goes here").yesText( - ApplicationBundle.message("command.exit")).noText( - CommonBundle.message("button.cancel")).show(); - } - }); + SwingUtilities.invokeLater(() -> MessageDialogBuilder.yesNo("Nothing happens after that", "Some message goes here").yesText( + ApplicationBundle.message("command.exit")).noText( + CommonBundle.message("button.cancel")).show()); } }.start(); diff --git a/platform/platform-impl/src/com/intellij/notification/impl/ui/NotificationsConfigurablePanel.java b/platform/platform-impl/src/com/intellij/notification/impl/ui/NotificationsConfigurablePanel.java index 28c2eb4ca72c..31fca63015a8 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/ui/NotificationsConfigurablePanel.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/ui/NotificationsConfigurablePanel.java @@ -374,22 +374,19 @@ public class NotificationsConfigurablePanel extends JPanel implements Disposable } } - Collections.sort(rootChildren, new Comparator() { - @Override - public int compare(DefaultMutableTreeNode node1, DefaultMutableTreeNode node2) { - Object object1 = node1.getUserObject(); - Object object2 = node2.getUserObject(); - if (object1 instanceof NotificationParentGroupBean) { - if (object2 instanceof NotificationParentGroupBean) { - return object1.toString().compareTo(object2.toString()); - } - return -1; + Collections.sort(rootChildren, (node1, node2) -> { + Object object1 = node1.getUserObject(); + Object object2 = node2.getUserObject(); + if (object1 instanceof NotificationParentGroupBean) { + if (object2 instanceof NotificationParentGroupBean) { + return object1.toString().compareTo(object2.toString()); } - if (object2 instanceof SettingsWrapper) { - return ((SettingsWrapper)object1).getGroupId().compareTo(((SettingsWrapper)object2).getGroupId()); - } - return 1; + return -1; } + if (object2 instanceof SettingsWrapper) { + return ((SettingsWrapper)object1).getGroupId().compareTo(((SettingsWrapper)object2).getGroupId()); + } + return 1; }); DefaultMutableTreeNode root = new DefaultMutableTreeNode(); diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.java index 7a424a3d7251..892b19e4a7e7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.java @@ -94,12 +94,7 @@ public class QuickListsManager implements ExportableApplicationComponent { public void initComponent() { for (BundledQuickListsProvider provider : BundledQuickListsProvider.EP_NAME.getExtensions()) { for (final String path : provider.getBundledListsRelativePaths()) { - mySchemeManager.loadBundledScheme(path, provider, new ThrowableConvertor() { - @Override - public QuickList convert(Element element) throws Throwable { - return createItem(element); - } - }); + mySchemeManager.loadBundledScheme(path, provider, element -> createItem(element)); } } mySchemeManager.loadSchemes(); diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java index 28c774edeeb2..7f356e9dea0c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java @@ -1072,12 +1072,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Disposab @Override public Comparator getRegistrationOrderComparator() { - return new Comparator() { - @Override - public int compare(String id1, String id2) { - return myId2Index.get(id1) - myId2Index.get(id2); - } - }; + return (id1, id2) -> myId2Index.get(id1) - myId2Index.get(id2); } @NotNull @@ -1275,12 +1270,7 @@ public final class ActionManagerImpl extends ActionManagerEx implements Disposab assert app.isDispatchThread(); final ActionCallback result = new ActionCallback(); - final Runnable doRunnable = new Runnable() { - @Override - public void run() { - tryToExecuteNow(action, inputEvent, contextComponent, place, result); - } - }; + final Runnable doRunnable = () -> tryToExecuteNow(action, inputEvent, contextComponent, place, result); if (now) { doRunnable.run(); diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java index cfafd82257a2..6c9775ace92b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java @@ -364,26 +364,20 @@ public final class ActionMenu extends JMenu { private SingleAlarm myCheckAlarm; private UsabilityHelper(Component component) { - myCallbackAlarm = new SingleAlarm(new Runnable() { - @Override - public void run() { - Disposer.dispose(myCallbackAlarm); - myCallbackAlarm = null; - if (myEventToRedispatch != null) { - IdeEventQueue.getInstance().dispatchEvent(myEventToRedispatch); - } + myCallbackAlarm = new SingleAlarm(() -> { + Disposer.dispose(myCallbackAlarm); + myCallbackAlarm = null; + if (myEventToRedispatch != null) { + IdeEventQueue.getInstance().dispatchEvent(myEventToRedispatch); } }, 50, this); - myCheckAlarm = new SingleAlarm(new Runnable() { - @Override - public void run() { - if (myLastEventTime > 0 && System.currentTimeMillis() - myLastEventTime > 1500) { - if (!myInBounds && myCallbackAlarm != null && !myCallbackAlarm.isDisposed()) { - myCallbackAlarm.request(); - } + myCheckAlarm = new SingleAlarm(() -> { + if (myLastEventTime > 0 && System.currentTimeMillis() - myLastEventTime > 1500) { + if (!myInBounds && myCallbackAlarm != null && !myCallbackAlarm.isDisposed()) { + myCallbackAlarm.request(); } - myCheckAlarm.request(); } + myCheckAlarm.request(); }, 100, this); myComponent = component; PointerInfo info = MouseInfo.getPointerInfo(); diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java index 702cb669baf9..950d6ed6ddc2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java @@ -278,42 +278,31 @@ public class ActionMenuItem extends JCheckBoxMenuItem { FeatureUsageTracker.getInstance().triggerFeatureUsed("context.menu.click.stats." + id.replace(' ', '.')); } fm.typeAheadUntil(typeAhead); - fm.runOnOwnContext(myContext, new Runnable() { - @Override - public void run() { - final AnActionEvent event = new AnActionEvent( - new MouseEvent(ActionMenuItem.this, MouseEvent.MOUSE_PRESSED, 0, e.getModifiers(), getWidth() / 2, getHeight() / 2, 1, false), - myContext, myPlace, myPresentation, ActionManager.getInstance(), e.getModifiers() - ); - final AnAction action = myAction.getAction(); - if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) { - ActionManagerEx actionManager = ActionManagerEx.getInstanceEx(); - actionManager.fireBeforeActionPerformed(action, myContext, event); - Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(event.getDataContext()); - if (component != null && !isInTree(component)) { - typeAhead.setDone(); - return; - } - - SimpleTimer.getInstance().setUp(new Runnable() { - @Override - public void run() { - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - fm.doWhenFocusSettlesDown(typeAhead.createSetDoneRunnable()); - } - }); - } - }, Registry.intValue("actionSystem.typeAheadTimeAfterPopupAction")); - - ActionUtil.performActionDumbAware(action, event); - actionManager.queueActionPerformedEvent(action, myContext, event); - } - else { + fm.runOnOwnContext(myContext, () -> { + final AnActionEvent event = new AnActionEvent( + new MouseEvent(ActionMenuItem.this, MouseEvent.MOUSE_PRESSED, 0, e.getModifiers(), getWidth() / 2, getHeight() / 2, 1, false), + myContext, myPlace, myPresentation, ActionManager.getInstance(), e.getModifiers() + ); + final AnAction action1 = myAction.getAction(); + if (ActionUtil.lastUpdateAndCheckDumb(action1, event, false)) { + ActionManagerEx actionManager = ActionManagerEx.getInstanceEx(); + actionManager.fireBeforeActionPerformed(action1, myContext, event); + Component component1 = PlatformDataKeys.CONTEXT_COMPONENT.getData(event.getDataContext()); + if (component1 != null && !isInTree(component1)) { typeAhead.setDone(); + return; } + + SimpleTimer.getInstance().setUp(() -> { + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> fm.doWhenFocusSettlesDown(typeAhead.createSetDoneRunnable())); + }, Registry.intValue("actionSystem.typeAheadTimeAfterPopupAction")); + + ActionUtil.performActionDumbAware(action1, event); + actionManager.queueActionPerformedEvent(action1, myContext, event); + } + else { + typeAhead.setDone(); } }); } @@ -374,12 +363,9 @@ public class ActionMenuItem extends JCheckBoxMenuItem { if (queueForDispose) { // later since we cannot remove property listeners inside event processing //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (getParent() == null) { - uninstallSynchronizer(); - } + SwingUtilities.invokeLater(() -> { + if (getParent() == null) { + uninstallSynchronizer(); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java index bf793590eeef..7d7eca87f1f6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java @@ -1023,12 +1023,7 @@ public class ActionToolbarImpl extends JPanel implements ActionToolbar { return; } if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) { - IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - showAutoPopup(); - } - }); + IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(() -> showAutoPopup()); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ToolbarUpdater.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ToolbarUpdater.java index 6bcfe8b54b98..8fa5792ba06a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ToolbarUpdater.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ToolbarUpdater.java @@ -108,12 +108,7 @@ public abstract class ToolbarUpdater implements Activatable { fm.doWhenFocusSettlesDown(updateRunnable); } else { - UiNotifyConnector.doWhenFirstShown(myComponent, new Runnable() { - @Override - public void run() { - fm.doWhenFocusSettlesDown(updateRunnable); - } - }); + UiNotifyConnector.doWhenFirstShown(myComponent, () -> fm.doWhenFocusSettlesDown(updateRunnable)); } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java index 9af1d30c28bf..521e1fb0436d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java @@ -351,43 +351,37 @@ public class Utils{ if (fixMacScreenMenu) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - for (Component each : children) { - if (each.getParent() != null && each instanceof ActionMenuItem) { - ((ActionMenuItem)each).prepare(); - } + SwingUtilities.invokeLater(() -> { + for (Component each : children) { + if (each.getParent() != null && each instanceof ActionMenuItem) { + ((ActionMenuItem)each).prepare(); } - menuBuilt.setDone(); } + menuBuilt.setDone(); }); } else { menuBuilt.setDone(); } - menuBuilt.doWhenDone(new Runnable() { - public void run() { - if (!mayDataContextBeInvalid) return; + menuBuilt.doWhenDone(() -> { + if (!mayDataContextBeInvalid) return; - if (IdeFocusManager.getInstance(null).isFocusBeingTransferred()) { - IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(new Runnable() { - public void run() { - if (!component.isShowing()) return; + if (IdeFocusManager.getInstance(null).isFocusBeingTransferred()) { + IdeFocusManager.getInstance(null).doWhenFocusSettlesDown(() -> { + if (!component.isShowing()) return; - DataContext context = DataManager.getInstance().getDataContext(); - expandActionGroup(group, new ArrayList(), presentationFactory, context, place, ActionManager.getInstance()); + DataContext context1 = DataManager.getInstance().getDataContext(); + expandActionGroup(group, new ArrayList(), presentationFactory, context1, place, ActionManager.getInstance()); - for (Component each : children) { - if (each instanceof ActionMenuItem) { - ((ActionMenuItem)each).updateContext(context); - } else if (each instanceof ActionMenu) { - ((ActionMenu)each).updateContext(context); - } - } + for (Component each : children) { + if (each instanceof ActionMenuItem) { + ((ActionMenuItem)each).updateContext(context1); + } else if (each instanceof ActionMenu) { + ((ActionMenu)each).updateContext(context1); } - }); - } + } + }); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/application/ConfigImportHelper.java b/platform/platform-impl/src/com/intellij/openapi/application/ConfigImportHelper.java index bbcd4bf3ebbc..ae09bf37aaa1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/ConfigImportHelper.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/ConfigImportHelper.java @@ -125,13 +125,8 @@ public class ConfigImportHelper { final String prefix = getPrefixFromSelector(selector); final String customPrefix = customPathSelector != null ? getPrefixFromSelector(customPathSelector) : null; - for (File file : parent.listFiles(new FilenameFilter() { - @Override - public boolean accept(@NotNull File file, @NotNull String name) { - return StringUtil.startsWithIgnoreCase(name, prefix) || - customPrefix != null && StringUtil.startsWithIgnoreCase(name, customPrefix); - } - })) { + for (File file : parent.listFiles((file1, name) -> StringUtil.startsWithIgnoreCase(name, prefix) || + customPrefix != null && StringUtil.startsWithIgnoreCase(name, customPrefix))) { File options = new File(file, CONFIG_RELATED_PATH + OPTIONS_XML); if (!options.exists()) { continue; @@ -203,12 +198,7 @@ public class ConfigImportHelper { File oldPluginsDir = new File(src, PLUGINS_PATH); if (!oldPluginsDir.isDirectory() && SystemInfo.isMac) { oldPluginsDir = getSettingsPath(oldInstallationHome, settings, PathManager.PROPERTY_PLUGINS_PATH, - new Function() { - @Override - public String fun(String pathSelector) { - return PathManager.getDefaultPluginPathFor(pathSelector); - } - }); + pathSelector -> PathManager.getDefaultPluginPathFor(pathSelector)); if (oldPluginsDir == null) { //e.g. installation home referred to config home. Try with default selector, same as config name oldPluginsDir = new File(PathManager.getDefaultPluginPathFor(src.getName())); @@ -259,12 +249,8 @@ public class ConfigImportHelper { return new File(oldInstallHome, "config"); } - return getSettingsPath(oldInstallHome, settings, PathManager.PROPERTY_CONFIG_PATH, new Function() { - @Override - public String fun(String pathsSelector) { - return PathManager.getDefaultConfigPathFor(pathsSelector); - } - }); + return getSettingsPath(oldInstallHome, settings, PathManager.PROPERTY_CONFIG_PATH, + pathsSelector -> PathManager.getDefaultConfigPathFor(pathsSelector)); } private static File getSettingsPath(File installHome, ConfigImportSettings settings, String propertyName, Function fromPathSelector) { diff --git a/platform/platform-impl/src/com/intellij/openapi/application/PluginPathManager.java b/platform/platform-impl/src/com/intellij/openapi/application/PluginPathManager.java index 9bad9d2d3774..4a3aa69a96c0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/PluginPathManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/PluginPathManager.java @@ -50,21 +50,11 @@ public class PluginPathManager { @NotNull private static File[] getSortedGitRoots(@NotNull File dir) { - File[] gitRoots = dir.listFiles(new FileFilter() { - @Override - public boolean accept(File child) { - return child.isDirectory() && new File(child, ".git").exists(); - } - }); + File[] gitRoots = dir.listFiles(child -> child.isDirectory() && new File(child, ".git").exists()); if (gitRoots == null) { return new File[0]; } - Arrays.sort(gitRoots, new Comparator() { - @Override - public int compare(File file, File file2) { - return FileUtil.compareFiles(file, file2); - } - }); + Arrays.sort(gitRoots, (file, file2) -> FileUtil.compareFiles(file, file2)); return gitRoots; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/application/Preloader.java b/platform/platform-impl/src/com/intellij/openapi/application/Preloader.java index 27c506c3d9bb..ea3c1a4b1cf5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/Preloader.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/Preloader.java @@ -62,26 +62,20 @@ public class Preloader implements ApplicationComponent { } for (final PreloadingActivity activity : PreloadingActivity.EP_NAME.getExtensions()) { - myExecutor.execute(new Runnable() { - @Override - public void run() { - if (myIndicator.isCanceled()) return; + myExecutor.execute(() -> { + if (myIndicator.isCanceled()) return; - checkHeavyProcessRunning(); - if (myIndicator.isCanceled()) return; + checkHeavyProcessRunning(); + if (myIndicator.isCanceled()) return; - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - try { - activity.preload(myWrappingIndicator); - } - catch (ProcessCanceledException ignore) { - } - LOG.info("Finished preloading " + activity); - } - }, myIndicator); - } + ProgressManager.getInstance().runProcess(() -> { + try { + activity.preload(myWrappingIndicator); + } + catch (ProcessCanceledException ignore) { + } + LOG.info("Finished preloading " + activity); + }, myIndicator); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/FinishMarkAction.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/FinishMarkAction.java index caf58254b4f0..82385656cf23 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/FinishMarkAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/FinishMarkAction.java @@ -71,12 +71,10 @@ public class FinishMarkAction extends BasicUndoableAction { public static void finish(final Project project, final Editor editor, @Nullable final StartMarkAction startAction) { if (startAction == null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - DocumentReference reference = DocumentReferenceManager.getInstance().create(editor.getDocument()); - UndoManager.getInstance(project).undoableActionPerformed(new FinishMarkAction(reference, startAction)); - StartMarkAction.markFinished(project); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + DocumentReference reference = DocumentReferenceManager.getInstance().create(editor.getDocument()); + UndoManager.getInstance(project).undoableActionPerformed(new FinishMarkAction(reference, startAction)); + StartMarkAction.markFinished(project); }, "finish", null); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java index 19dc202ae74f..95b487a1f17f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java @@ -163,12 +163,7 @@ public class UndoManagerImpl extends UndoManager implements ProjectComponent, Ap runStartupActivity(); } else { - myStartupManager.registerStartupActivity(new Runnable() { - @Override - public void run() { - runStartupActivity(); - } - }); + myStartupManager.registerStartupActivity(() -> runStartupActivity()); } } @@ -421,22 +416,19 @@ public class UndoManagerImpl extends UndoManager implements ProjectComponent, Ap myCurrentOperationState = isUndo ? UNDO : REDO; final RuntimeException[] exception = new RuntimeException[1]; - Runnable executeUndoOrRedoAction = new Runnable() { - @Override - public void run() { - try { - if (myProject != null) { - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - } - CopyPasteManager.getInstance().stopKillRings(); - myMerger.undoOrRedo(editor, isUndo); - } - catch (RuntimeException ex) { - exception[0] = ex; - } - finally { - myCurrentOperationState = NONE; + Runnable executeUndoOrRedoAction = () -> { + try { + if (myProject != null) { + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); } + CopyPasteManager.getInstance().stopKillRings(); + myMerger.undoOrRedo(editor, isUndo); + } + catch (RuntimeException ex) { + exception[0] = ex; + } + finally { + myCurrentOperationState = NONE; } }; @@ -612,12 +604,7 @@ public class UndoManagerImpl extends UndoManager implements ProjectComponent, Ap if (refs.size() <= FREE_QUEUES_LIMIT) return; DocumentReference[] backSorted = refs.toArray(new DocumentReference[refs.size()]); - Arrays.sort(backSorted, new Comparator() { - @Override - public int compare(DocumentReference a, DocumentReference b) { - return getLastCommandTimestamp(a) - getLastCommandTimestamp(b); - } - }); + Arrays.sort(backSorted, (a, b) -> getLastCommandTimestamp(a) - getLastCommandTimestamp(b)); for (int i = 0; i < backSorted.length - FREE_QUEUES_LIMIT; i++) { DocumentReference each = backSorted[i]; diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoableGroup.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoableGroup.java index a738137939b7..63a63b1132a3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoableGroup.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoableGroup.java @@ -123,38 +123,36 @@ class UndoableGroup { // perform undo action by action, setting bulk update flag if possible // if multiple consecutive actions share a document, then set the bulk flag only once final Set bulkDocuments = new THashSet(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - for (final UndoableAction action : isUndo ? ContainerUtil.iterateBackward(myActions) : myActions) { - if (wrapInBulkUpdate) { - DocumentEx newDocument = getDocumentToSetBulkMode(action); - if (newDocument == null) { - for (DocumentEx document : bulkDocuments) { - document.setInBulkUpdate(false); - } - bulkDocuments.clear(); - } - else if (bulkDocuments.add(newDocument)) { - newDocument.setInBulkUpdate(true); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + for (final UndoableAction action : isUndo ? ContainerUtil.iterateBackward(myActions) : myActions) { + if (wrapInBulkUpdate) { + DocumentEx newDocument = getDocumentToSetBulkMode(action); + if (newDocument == null) { + for (DocumentEx document : bulkDocuments) { + document.setInBulkUpdate(false); } + bulkDocuments.clear(); } + else if (bulkDocuments.add(newDocument)) { + newDocument.setInBulkUpdate(true); + } + } - if (isUndo) { - action.undo(); - } - else { - action.redo(); - } + if (isUndo) { + action.undo(); + } + else { + action.redo(); } } - catch (UnexpectedUndoException e) { - reportUndoProblem(e, isUndo); - } - finally { - for (DocumentEx bulkDocument : bulkDocuments) { - bulkDocument.setInBulkUpdate(false); - } + } + catch (UnexpectedUndoException e) { + reportUndoProblem(e, isUndo); + } + finally { + for (DocumentEx bulkDocument : bulkDocuments) { + bulkDocument.setInBulkUpdate(false); } } }); @@ -357,12 +355,7 @@ class UndoableGroup { if (multiline) result.append("\n"); - result.append(StringUtil.join(myActions, new Function() { - @Override - public String fun(UndoableAction each) { - return (multiline ? " " : "") + each.toString(); - } - }, ",\n")); + result.append(StringUtil.join(myActions, each -> (multiline ? " " : "") + each.toString(), ",\n")); if (multiline) result.append("\n"); result.append("]"); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/BaseDiffAction.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/BaseDiffAction.java index e59f132196ac..58a36be001f7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/BaseDiffAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/actions/BaseDiffAction.java @@ -35,13 +35,11 @@ abstract class BaseDiffAction extends AnAction implements PreloadableAction, Dum if (diffData == null) return; final DiffContent[] contents = diffData.getContents(); final FileDocumentManager documentManager = FileDocumentManager.getInstance(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - for (DiffContent content : contents) { - Document document = content.getDocument(); - if (document != null) { - documentManager.saveDocument(document); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (DiffContent content : contents) { + Document document = content.getDocument(); + if (document != null) { + documentManager.saveDocument(document); } } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeOperations.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeOperations.java index 8fdd8438af49..71a957703e57 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeOperations.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeOperations.java @@ -122,11 +122,7 @@ public class MergeOperations { private static Runnable replaceModification(TextRange range, Document document, final TextRange otherRange, final Document otherDocument) { final String replacement = getSubstring(document, range); - return new Runnable() { - public void run() { - otherDocument.replaceString(otherRange.getStartOffset(), otherRange.getEndOffset(), replacement); - } - }; + return () -> otherDocument.replaceString(otherRange.getStartOffset(), otherRange.getEndOffset(), replacement); } private static Operation insertOperation(TextRange range, int offset, Document document, Document otherDocument, FragmentSide base) { @@ -139,11 +135,7 @@ public class MergeOperations { private static Runnable insertModification(TextRange range, Document document, final int offset, final Document otherDocument) { final String insertion = getSubstring(document, range); - return new Runnable(){ - public void run() { - otherDocument.insertString(offset, insertion); - } - }; + return () -> otherDocument.insertString(offset, insertion); } private static String getSubstring(Document document, TextRange range) { @@ -162,11 +154,7 @@ public class MergeOperations { } private static Runnable removeModification(final TextRange range, final Document document) { - return new Runnable(){ - public void run() { - document.deleteString(range.getStartOffset(), range.getEndOffset()); - } - }; + return () -> document.deleteString(range.getStartOffset(), range.getEndOffset()); } private Document getDocument() { @@ -209,10 +197,8 @@ public class MergeOperations { final ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(file); if (status.hasReadonlyFiles()) return; } - ApplicationManager.getApplication().runWriteAction(new Runnable(){ - public void run() { - CommandProcessor.getInstance().executeCommand(project, myModification, getName(), null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, myModification, getName(), null); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java index 1ccf842898cd..4799d0d14259 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java @@ -784,37 +784,31 @@ public class DiffPanelImpl implements DiffPanelEx, ContentChangeListener, TwoSid final FragmentList fragmentList = getFragments(); final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - final ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(fragmentList.iterator(), document, false); - final CacheOneStepIterator> cacheOneStepIterator = - new CacheOneStepIterator>(changedLinesIterator); - final NavigationContextChecker checker = new NavigationContextChecker(cacheOneStepIterator, scrollContext); - int line = checker.contextMatchCheck(); - if (line < 0) { - // this will work for the case, when spaces changes are ignored, and corresponding fragments are not reported as changed - // just try to find target line -> +- - final ChangedLinesIterator changedLinesIterator2 = new ChangedLinesIterator(fragmentList.iterator(), document, true); - final CacheOneStepIterator> cacheOneStepIterator2 = - new CacheOneStepIterator>(changedLinesIterator2); - final NavigationContextChecker checker2 = new NavigationContextChecker(cacheOneStepIterator2, scrollContext); - line = checker2.contextMatchCheck(); - } - final int finalLine = line; - final ModalityState modalityState = myOwnerWindow == null ? ModalityState.NON_MODAL : ModalityState.stateForComponent(myOwnerWindow); - application.invokeLater(new Runnable() { - @Override - public void run() { - if (finalLine >= 0) { - final int line = myLineBlocks.transform(myRightSide.getSide(), finalLine); - myLeftSide.scrollToFirstDiff(line); - } else { - scrollCurrentToFirstDiff(); - } - } - }, modalityState); + application.executeOnPooledThread(() -> { + final ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(fragmentList.iterator(), document, false); + final CacheOneStepIterator> cacheOneStepIterator = + new CacheOneStepIterator>(changedLinesIterator); + final NavigationContextChecker checker = new NavigationContextChecker(cacheOneStepIterator, scrollContext); + int line = checker.contextMatchCheck(); + if (line < 0) { + // this will work for the case, when spaces changes are ignored, and corresponding fragments are not reported as changed + // just try to find target line -> +- + final ChangedLinesIterator changedLinesIterator2 = new ChangedLinesIterator(fragmentList.iterator(), document, true); + final CacheOneStepIterator> cacheOneStepIterator2 = + new CacheOneStepIterator>(changedLinesIterator2); + final NavigationContextChecker checker2 = new NavigationContextChecker(cacheOneStepIterator2, scrollContext); + line = checker2.contextMatchCheck(); } + final int finalLine = line; + final ModalityState modalityState = myOwnerWindow == null ? ModalityState.NON_MODAL : ModalityState.stateForComponent(myOwnerWindow); + application.invokeLater(() -> { + if (finalLine >= 0) { + final int line1 = myLineBlocks.transform(myRightSide.getSide(), finalLine); + myLeftSide.scrollToFirstDiff(line1); + } else { + scrollCurrentToFirstDiff(); + } + }, modalityState); }); } } @@ -859,22 +853,19 @@ public class DiffPanelImpl implements DiffPanelEx, ContentChangeListener, TwoSid if (fragment == null) return null; final TextRange textRange = fragment.getRange(FragmentSide.SIDE2); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final int startLine = myDocument.getLineNumber(textRange.getStartOffset()); - final int endFragmentOffset = textRange.getEndOffset(); - final int endLine = myDocument.getLineNumber(endFragmentOffset); - for (int i = startLine; i <= endLine; i++) { - int lineEndOffset = myDocument.getLineEndOffset(i); - final int lineStartOffset = myDocument.getLineStartOffset(i); - if (lineEndOffset > endFragmentOffset && endFragmentOffset == lineStartOffset) { - lineEndOffset = endFragmentOffset; - } - if (lineStartOffset > lineEndOffset) continue; - String text = myDocument.getText().substring(lineStartOffset, lineEndOffset); - myBuffer.add(new Pair(i, text)); + ApplicationManager.getApplication().runReadAction(() -> { + final int startLine = myDocument.getLineNumber(textRange.getStartOffset()); + final int endFragmentOffset = textRange.getEndOffset(); + final int endLine = myDocument.getLineNumber(endFragmentOffset); + for (int i = startLine; i <= endLine; i++) { + int lineEndOffset = myDocument.getLineEndOffset(i); + final int lineStartOffset = myDocument.getLineStartOffset(i); + if (lineEndOffset > endFragmentOffset && endFragmentOffset == lineStartOffset) { + lineEndOffset = endFragmentOffset; } + if (lineStartOffset > lineEndOffset) continue; + String text = myDocument.getText().substring(lineStartOffset, lineEndOffset); + myBuffer.add(new Pair(i, text)); } }); if (myBuffer.isEmpty()) return null; diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/ExtMergeFiles.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/ExtMergeFiles.java index 7b02d98a4ae7..49a67d9bdef7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/ExtMergeFiles.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/ExtMergeFiles.java @@ -101,12 +101,8 @@ public class ExtMergeFiles extends BaseExternalTool { "Merge In External Tool", "Mark as Resolved", "Revert", null)) { result = DialogWrapper.OK_EXIT_CODE; } - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - ((MergeRequestImpl)request).getResultContent().getFile().refresh(false, false); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> ((MergeRequestImpl)request).getResultContent().getFile().refresh(false, false)); // We can actually check exit code of external tool, but some of them could work with tabs -> do not close at all } catch (Exception e) { diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/FrameDiffTool.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/FrameDiffTool.java index 036881cc098d..93e4df11c0af 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/FrameDiffTool.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/FrameDiffTool.java @@ -52,12 +52,9 @@ public class FrameDiffTool implements DiffTool { } final Runnable onOkRunnable = request.getOnOkRunnable(); if (onOkRunnable != null){ - builder.setOkOperation(new Runnable() { - @Override - public void run() { - builder.getDialogWrapper().close(0); - onOkRunnable.run(); - } + builder.setOkOperation(() -> { + builder.getDialogWrapper().close(0); + onOkRunnable.run(); }); } else { builder.removeAllActions(); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/MultiLevelDiffTool.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/MultiLevelDiffTool.java index 04b8d4a86a93..3725f9c9b938 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/MultiLevelDiffTool.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/MultiLevelDiffTool.java @@ -66,12 +66,9 @@ public class MultiLevelDiffTool implements DiffTool, DiscloseMultiRequest { } final Runnable onOkRunnable = request.getOnOkRunnable(); if (onOkRunnable != null){ - builder.setOkOperation(new Runnable() { - @Override - public void run() { - builder.getDialogWrapper().close(0); - onOkRunnable.run(); - } + builder.setOkOperation(() -> { + builder.getDialogWrapper().close(0); + onOkRunnable.run(); }); } else { builder.removeAllActions(); @@ -151,13 +148,10 @@ public class MultiLevelDiffTool implements DiffTool, DiscloseMultiRequest { } public Map discloseRequest(DiffRequest request) { - final Map pairs = new TreeMap(new Comparator() { - @Override - public int compare(String o1, String o2) { - if (ourDefaultTab.equals(o1)) return -1; - if (ourDefaultTab.equals(o2)) return 1; - return Comparing.compare(o1, o2); - } + final Map pairs = new TreeMap((o1, o2) -> { + if (ourDefaultTab.equals(o1)) return -1; + if (ourDefaultTab.equals(o2)) return 1; + return Comparing.compare(o1, o2); }); final List> layers = request.getOtherLayers(); for (Pair layer : layers) { diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffPanelState.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffPanelState.java index 33245989c5b3..a875c7d48c16 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffPanelState.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffPanelState.java @@ -38,11 +38,9 @@ public class DiffPanelState extends SimpleDiffPanelState { } public void setContents(final DiffContent content1, final DiffContent content2) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myAppender1.setContent(content1); - myAppender2.setContent(content2); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myAppender1.setContent(content1); + myAppender2.setContent(content2); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/SimpleDiffPanelState.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/SimpleDiffPanelState.java index ccaa5190e587..afbdaec1c154 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/SimpleDiffPanelState.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/SimpleDiffPanelState.java @@ -89,14 +89,12 @@ public abstract class SimpleDiffPanelState implements Disposable { } private LineBlocks addMarkup(final List lines) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final FragmentHighlighterImpl fragmentHighlighter = new FragmentHighlighterImpl(myAppender1, myAppender2); - for (Iterator iterator = lines.iterator(); iterator.hasNext();) { - LineFragment line = iterator.next(); - fragmentHighlighter.setIsLast(!iterator.hasNext()); - line.highlight(fragmentHighlighter); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final FragmentHighlighterImpl fragmentHighlighter = new FragmentHighlighterImpl(myAppender1, myAppender2); + for (Iterator iterator = lines.iterator(); iterator.hasNext();) { + LineFragment line = iterator.next(); + fragmentHighlighter.setIsLast(!iterator.hasNext()); + line.highlight(fragmentHighlighter); } }); ArrayList allLineFragments = new ArrayList(); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/Change.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/Change.java index 4bc8ac344dbf..d5886d3ed3bc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/Change.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/Change.java @@ -153,16 +153,8 @@ public abstract class Change { } public static void apply(final Change change, final FragmentSide fromSide) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(change.getProject(), new Runnable() { - @Override - public void run() { - doApply(change, fromSide); - } - }, null, DiffBundle.message("save.merge.result.command.name")); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(change.getProject(), () -> doApply(change, fromSide), null, DiffBundle.message("save.merge.result.command.name")); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/ApplyNonConflicts.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/ApplyNonConflicts.java index 6f43f9375e5a..7a945a8dc2a1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/ApplyNonConflicts.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/ApplyNonConflicts.java @@ -49,24 +49,18 @@ public class ApplyNonConflicts extends AnAction implements DumbAware { final List notConflicts = ContainerUtil.collect(getNotConflicts(mergeList)); final Project project = mergeList.getLeftChangeList().getProject(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - mergeList.startBulkUpdate(); - try { - for (Change change : notConflicts) { - Change.doApply(change, MergeList.BRANCH_SIDE); - } - } - finally { - mergeList.finishBulkUpdate(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> { + mergeList.startBulkUpdate(); + try { + for (Change change : notConflicts) { + Change.doApply(change, MergeList.BRANCH_SIDE); } - }, null, DiffBundle.message("save.merge.result.command.name")); - } + } + finally { + mergeList.finishBulkUpdate(); + } + }, null, DiffBundle.message("save.merge.result.command.name")); }); if (myDiffPanel != null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeRequestImpl.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeRequestImpl.java index e8e17b3c6ed2..f6d2012dd6f0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeRequestImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeRequestImpl.java @@ -208,12 +208,9 @@ public class MergeRequestImpl extends MergeRequest { } configureAction(builder, builder.getOkAction(), myOkButtonPresentation); - builder.setOkOperation(new Runnable() { - @Override - public void run() { - if (preOkHook != null && !preOkHook.convert(builder.getDialogWrapper())) return; - myOkButtonPresentation.run(builder.getDialogWrapper()); - } + builder.setOkOperation(() -> { + if (preOkHook != null && !preOkHook.convert(builder.getDialogWrapper())) return; + myOkButtonPresentation.run(builder.getDialogWrapper()); }); } @@ -223,12 +220,7 @@ public class MergeRequestImpl extends MergeRequest { } configureAction(builder, builder.getCancelAction(), myCancelButtonPresentation); - builder.setCancelOperation(new Runnable() { - @Override - public void run() { - myCancelButtonPresentation.run(builder.getDialogWrapper()); - } - }); + builder.setCancelOperation(() -> myCancelButtonPresentation.run(builder.getDialogWrapper())); } if (getMergeContent() != null && mergePanel.getMergeList() != null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeVersion.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeVersion.java index 099420ee2c9e..763123002251 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeVersion.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/mergeTool/MergeVersion.java @@ -76,15 +76,12 @@ public interface MergeVersion { workingDocument.setReadOnly(false); final DocumentReference ref = DocumentReferenceManager.getInstance().create(workingDocument); myTextBeforeMerge = myDocument.getText(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - setDocumentText(workingDocument, myOriginalText, DiffBundle.message("merge.init.merge.content.command.name"), project); - if (project != null) { - final UndoManager undoManager = UndoManager.getInstance(project); - if (undoManager != null) { //idea.sh merge command - undoManager.nonundoableActionPerformed(ref, false); - } + ApplicationManager.getApplication().runWriteAction(() -> { + setDocumentText(workingDocument, myOriginalText, DiffBundle.message("merge.init.merge.content.command.name"), project); + if (project != null) { + final UndoManager undoManager = UndoManager.getInstance(project); + if (undoManager != null) { //idea.sh merge command + undoManager.nonundoableActionPerformed(ref, false); } } }); @@ -93,16 +90,8 @@ public interface MergeVersion { @Override public void applyText(@NotNull final String text, final Project project) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - doApplyText(text, project); - } - }, "Merge changes", null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> doApplyText(text, project), "Merge changes", null); }); } @@ -129,24 +118,18 @@ public interface MergeVersion { } } } - return vfs.isEmpty() ? null : new Runnable() { - @Override - public void run() { - ProjectManagerEx ex = ProjectManagerEx.getInstanceEx(); - for (VirtualFile vf : vfs) { - ex.saveChangedProjectFile(vf, project); - } + return vfs.isEmpty() ? null : (Runnable)() -> { + ProjectManagerEx ex = ProjectManagerEx.getInstanceEx(); + for (VirtualFile vf : vfs) { + ex.saveChangedProjectFile(vf, project); } }; } @Override public void restoreOriginalContent(final Project project) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - doRestoreOriginalContent(project); - } + ApplicationManager.getApplication().runWriteAction(() -> { + doRestoreOriginalContent(project); }); } @@ -179,12 +162,7 @@ public interface MergeVersion { } private static void setDocumentText(@NotNull final Document document, @NotNull final String text, @Nullable String name, @Nullable Project project) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - document.replaceString(0, document.getTextLength(), StringUtil.convertLineSeparators(text)); - } - }, name, null); + CommandProcessor.getInstance().executeCommand(project, () -> document.replaceString(0, document.getTextLength(), StringUtil.convertLineSeparators(text)), name, null); } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/splitter/Interval.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/splitter/Interval.java index 3e24316087d1..01155bab7dd2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/splitter/Interval.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/splitter/Interval.java @@ -18,18 +18,14 @@ package com.intellij.openapi.diff.impl.splitter; import java.util.Comparator; public class Interval { - public static final Comparator START_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - if (o1 instanceof Interval) return ((Interval) o1).compareToStart((Integer) o2); - return -((Interval) o2).compareToStart((Integer) o1); - } + public static final Comparator START_COMPARATOR = (o1, o2) -> { + if (o1 instanceof Interval) return ((Interval) o1).compareToStart((Integer) o2); + return -((Interval) o2).compareToStart((Integer) o1); }; - public static final Comparator END_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - if (o1 instanceof Interval) return ((Interval) o1).compareToEnd((Integer) o2); - return -((Interval)o2).compareToEnd((Integer) o1); - } + public static final Comparator END_COMPARATOR = (o1, o2) -> { + if (o1 instanceof Interval) return ((Interval) o1).compareToEnd((Integer) o2); + return -((Interval)o2).compareToEnd((Integer) o1); }; private final int myStart; private final int myLength; diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java index 35e43a46526b..9ac9b6d3f6c3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java @@ -226,11 +226,7 @@ public class DiffPanelOuterComponent extends JPanel implements DataProvider { public void deferScroll(final DiffPanelOuterComponent outer) { if (!outer.isDisplayable()) return; - SwingUtilities.invokeLater(new Runnable() { - public void run() { - outer.performScroll(); - } - }); + SwingUtilities.invokeLater(() -> outer.performScroll()); } }; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/ContentChooser.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/ContentChooser.java index d671a791db7e..682aa4798dab 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/ContentChooser.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/ContentChooser.java @@ -160,12 +160,7 @@ public abstract class ContentChooser extends DialogWrapper { } }); - mySplitter.setFirstComponent(ListWithFilter.wrap(myList, ScrollPaneFactory.createScrollPane(myList), new Function() { - @Override - public String fun(Object o) { - return ((Item)o).longText; - } - })); + mySplitter.setFirstComponent(ListWithFilter.wrap(myList, ScrollPaneFactory.createScrollPane(myList), o -> ((Item)o).longText)); mySplitter.setSecondComponent(new JPanel()); rebuildListContent(); @@ -176,12 +171,7 @@ public abstract class ContentChooser extends DialogWrapper { @Override public void valueChanged(ListSelectionEvent e) { myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - updateViewerForSelection(); - } - }, 100); + myUpdateAlarm.addRequest(() -> updateViewerForSelection(), 100); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java index 13d2cf7bb43e..2cb4ded96c54 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java @@ -49,35 +49,32 @@ public class DeleteLineAction extends TextComponentEditorAction { final List carets = caret == null ? editor.getCaretModel().getAllCarets() : Collections.singletonList(caret); - editor.getCaretModel().runBatchCaretOperation(new Runnable() { - @Override - public void run() { - int[] caretColumns = new int[carets.size()]; - int caretIndex = carets.size() - 1; - TextRange range = getRangeToDelete(editor, carets.get(caretIndex)); + editor.getCaretModel().runBatchCaretOperation(() -> { + int[] caretColumns = new int[carets.size()]; + int caretIndex = carets.size() - 1; + TextRange range = getRangeToDelete(editor, carets.get(caretIndex)); - while (caretIndex >= 0) { - int currentCaretIndex = caretIndex; - TextRange currentRange = range; - // find carets with overlapping line ranges - while (--caretIndex >= 0) { - range = getRangeToDelete(editor, carets.get(caretIndex)); - if (range.getEndOffset() < currentRange.getStartOffset()) { - break; - } - currentRange = new TextRange(range.getStartOffset(), currentRange.getEndOffset()); + while (caretIndex >= 0) { + int currentCaretIndex = caretIndex; + TextRange currentRange = range; + // find carets with overlapping line ranges + while (--caretIndex >= 0) { + range = getRangeToDelete(editor, carets.get(caretIndex)); + if (range.getEndOffset() < currentRange.getStartOffset()) { + break; } + currentRange = new TextRange(range.getStartOffset(), currentRange.getEndOffset()); + } - for (int i = caretIndex + 1; i <= currentCaretIndex; i++) { - caretColumns[i] = carets.get(i).getVisualPosition().column; - } - int targetLine = editor.offsetToVisualPosition(currentRange.getStartOffset()).line; + for (int i = caretIndex + 1; i <= currentCaretIndex; i++) { + caretColumns[i] = carets.get(i).getVisualPosition().column; + } + int targetLine = editor.offsetToVisualPosition(currentRange.getStartOffset()).line; - document.deleteString(currentRange.getStartOffset(), currentRange.getEndOffset()); + document.deleteString(currentRange.getStartOffset(), currentRange.getEndOffset()); - for (int i = caretIndex + 1; i <= currentCaretIndex; i++) { - carets.get(i).moveToVisualPosition(new VisualPosition(targetLine, caretColumns[i])); - } + for (int i = caretIndex + 1; i <= currentCaretIndex; i++) { + carets.get(i).moveToVisualPosition(new VisualPosition(targetLine, caretColumns[i])); } } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/EditorActionUtil.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/EditorActionUtil.java index 427ab5871b19..c4c168399314 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/EditorActionUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/EditorActionUtil.java @@ -893,12 +893,7 @@ public class EditorActionUtil { FoldRegion collapsedRegionAtOffset; while ((collapsedRegionAtOffset = foldingModel.getCollapsedRegionAtOffset(offset)) != null) { final FoldRegion region = collapsedRegionAtOffset; - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - region.setExpanded(true); - } - }); + foldingModel.runBatchFoldingOperation(() -> region.setExpanded(true)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/colors/impl/EditorColorsManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/colors/impl/EditorColorsManagerImpl.java index 9c190e9faf35..f87e4a812cf0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/colors/impl/EditorColorsManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/colors/impl/EditorColorsManagerImpl.java @@ -147,12 +147,7 @@ public class EditorColorsManagerImpl extends EditorColorsManager implements Pers private void loadBundledSchemes() { if (!isUnitTestOrHeadlessMode()) { for (BundledColorSchemeEP ep : BundledColorSchemeEP.EP_NAME.getExtensions()) { - mySchemeManager.loadBundledScheme(ep.path + ".xml", ep, new ThrowableConvertor() { - @Override - public EditorColorsScheme convert(Element element) throws Throwable { - return new ReadOnlyColorsSchemeImpl(element); - } - }); + mySchemeManager.loadBundledScheme(ep.path + ".xml", ep, element -> new ReadOnlyColorsSchemeImpl(element)); } } } @@ -232,15 +227,12 @@ public class EditorColorsManagerImpl extends EditorColorsManager implements Pers @Override public EditorColorsScheme[] getAllSchemes() { EditorColorsScheme[] result = getAllVisibleSchemes(mySchemeManager.getAllSchemes()); - Arrays.sort(result, new Comparator() { - @Override - public int compare(@NotNull EditorColorsScheme s1, @NotNull EditorColorsScheme s2) { - if (isDefaultScheme(s1) && !isDefaultScheme(s2)) return -1; - if (!isDefaultScheme(s1) && isDefaultScheme(s2)) return 1; - if (s1.getName().equals(DEFAULT_NAME)) return -1; - if (s2.getName().equals(DEFAULT_NAME)) return 1; - return s1.getName().compareToIgnoreCase(s2.getName()); - } + Arrays.sort(result, (s1, s2) -> { + if (isDefaultScheme(s1) && !isDefaultScheme(s2)) return -1; + if (!isDefaultScheme(s1) && isDefaultScheme(s2)) return 1; + if (s1.getName().equals(DEFAULT_NAME)) return -1; + if (s2.getName().equals(DEFAULT_NAME)) return 1; + return s1.getName().compareToIgnoreCase(s2.getName()); }); return result; } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java index 63f5fdcd4c69..a31ca2e4d818 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java @@ -858,12 +858,9 @@ public final class EditorUtil { if (startFoldRegion != null || endFoldRegion != null) { final FoldRegion finalStartFoldRegion = startFoldRegion; final FoldRegion finalEndFoldRegion = endFoldRegion; - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - if (finalStartFoldRegion != null) finalStartFoldRegion.setExpanded(true); - if (finalEndFoldRegion != null) finalEndFoldRegion.setExpanded(true); - } + foldingModel.runBatchFoldingOperation(() -> { + if (finalStartFoldRegion != null) finalStartFoldRegion.setExpanded(true); + if (finalEndFoldRegion != null) finalEndFoldRegion.setExpanded(true); }); } editor.getSelectionModel().setSelection(startOffset, endOffset); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/BorderEffect.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/BorderEffect.java index ae9a89d50b05..964c66be9097 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/BorderEffect.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/BorderEffect.java @@ -80,15 +80,12 @@ public class BorderEffect { } public void paintHighlighters(MarkupModelEx markupModel) { - markupModel.processRangeHighlightersOverlappingWith(myStartOffset, myEndOffset, new Processor() { - @Override - public boolean process(RangeHighlighterEx rangeHighlighter) { - TextAttributes textAttributes = rangeHighlighter.getTextAttributes(); - if (isBorder(textAttributes)) { - paintBorder(rangeHighlighter, textAttributes); - } - return true; + markupModel.processRangeHighlightersOverlappingWith(myStartOffset, myEndOffset, rangeHighlighter -> { + TextAttributes textAttributes = rangeHighlighter.getTextAttributes(); + if (isBorder(textAttributes)) { + paintBorder(rangeHighlighter, textAttributes); } + return true; }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java index 808cd18d572c..13c6e5c39bc5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java @@ -195,32 +195,29 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { if (mySkipChangeRequests) { return; } - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - final LogicalPosition logicalPosition = myEditor.offsetToLogicalPosition(offset); - CaretEvent event = moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, null, false); - final LogicalPosition positionByOffsetAfterMove = myEditor.offsetToLogicalPosition(myOffset); - if (!positionByOffsetAfterMove.equals(logicalPosition)) { - StringBuilder debugBuffer = new StringBuilder(); - moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, debugBuffer, true); - int textStart = Math.max(0, Math.min(offset, myOffset) - 1); - final DocumentEx document = myEditor.getDocument(); - int textEnd = Math.min(document.getTextLength() - 1, Math.max(offset, myOffset) + 1); - CharSequence text = document.getCharsSequence().subSequence(textStart, textEnd); - int inverseOffset = myEditor.logicalPositionToOffset(logicalPosition); - LogMessageEx.error( - LOG, "caret moved to wrong offset. Please submit a dedicated ticket and attach current editor's text to it.", - "Requested: offset=" + offset + ", logical position='" + logicalPosition + "' but actual: offset=" + - myOffset + ", logical position='" + myLogicalCaret + "' (" + positionByOffsetAfterMove + "). " + myEditor.dumpState() + - "\ninterested text [" + textStart + ";" + textEnd + "): '" + text + "'\n debug trace: " + debugBuffer + - "\nLogical position -> offset ('" + logicalPosition + "'->'" + inverseOffset + "')" - ); - } - if (event != null) { - myEditor.getCaretModel().fireCaretPositionChanged(event); - EditorActionUtil.selectNonexpandableFold(myEditor); - } + myEditor.getCaretModel().doWithCaretMerging(() -> { + final LogicalPosition logicalPosition = myEditor.offsetToLogicalPosition(offset); + CaretEvent event = moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, null, false); + final LogicalPosition positionByOffsetAfterMove = myEditor.offsetToLogicalPosition(myOffset); + if (!positionByOffsetAfterMove.equals(logicalPosition)) { + StringBuilder debugBuffer = new StringBuilder(); + moveToLogicalPosition(logicalPosition, locateBeforeSoftWrap, debugBuffer, true); + int textStart = Math.max(0, Math.min(offset, myOffset) - 1); + final DocumentEx document = myEditor.getDocument(); + int textEnd = Math.min(document.getTextLength() - 1, Math.max(offset, myOffset) + 1); + CharSequence text = document.getCharsSequence().subSequence(textStart, textEnd); + int inverseOffset = myEditor.logicalPositionToOffset(logicalPosition); + LogMessageEx.error( + LOG, "caret moved to wrong offset. Please submit a dedicated ticket and attach current editor's text to it.", + "Requested: offset=" + offset + ", logical position='" + logicalPosition + "' but actual: offset=" + + myOffset + ", logical position='" + myLogicalCaret + "' (" + positionByOffsetAfterMove + "). " + myEditor.dumpState() + + "\ninterested text [" + textStart + ";" + textEnd + "): '" + text + "'\n debug trace: " + debugBuffer + + "\nLogical position -> offset ('" + logicalPosition + "'->'" + inverseOffset + "')" + ); + } + if (event != null) { + myEditor.getCaretModel().fireCaretPositionChanged(event); + EditorActionUtil.selectNonexpandableFold(myEditor); } }); } @@ -248,169 +245,161 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { if (!myEditor.isStickySelection() && !myEditor.getCaretModel().isDocumentChanged) { CopyPasteManager.getInstance().stopKillRings(); } - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - int oldOffset = myOffset; - final int leadSelectionOffset = getLeadSelectionOffset(); - final VisualPosition leadSelectionPosition = getLeadSelectionPosition(); - EditorSettings editorSettings = myEditor.getSettings(); - VisualPosition visualCaret = getVisualPosition(); + myEditor.getCaretModel().doWithCaretMerging(() -> { + int oldOffset = myOffset; + final int leadSelectionOffset = getLeadSelectionOffset(); + final VisualPosition leadSelectionPosition = getLeadSelectionPosition(); + EditorSettings editorSettings = myEditor.getSettings(); + VisualPosition visualCaret = getVisualPosition(); - int lastColumnNumber = myLastColumnNumber; - int desiredX = myDesiredX; - if (columnShift == 0) { - if (myDesiredX < 0) { - desiredX = getCurrentX(); - } - } - else { - myDesiredX = desiredX = -1; + int lastColumnNumber = myLastColumnNumber; + int desiredX = myDesiredX; + if (columnShift == 0) { + if (myDesiredX < 0) { + desiredX = getCurrentX(); } + } + else { + myDesiredX = desiredX = -1; + } - int newLineNumber = visualCaret.line + lineShift; - int newColumnNumber = visualCaret.column + columnShift; - boolean newLeansRight = lineShift == 0 && columnShift != 0 ? columnShift < 0 : visualCaret.leansRight; - - if (desiredX >= 0) { - newColumnNumber = myEditor.xyToVisualPosition(new Point(desiredX, Math.max(0, newLineNumber) * myEditor.getLineHeight())).column; - } + int newLineNumber = visualCaret.line + lineShift; + int newColumnNumber = visualCaret.column + columnShift; + boolean newLeansRight = lineShift == 0 && columnShift != 0 ? columnShift < 0 : visualCaret.leansRight; - Document document = myEditor.getDocument(); - if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == 1) { - int lastLine = document.getLineCount() - 1; - if (lastLine < 0) lastLine = 0; - if (newColumnNumber > EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber) && - newLineNumber < myEditor.logicalToVisualPosition(new LogicalPosition(lastLine, 0)).line) { - newColumnNumber = 0; - newLineNumber++; - } - } - else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == -1) { - if (newColumnNumber < 0 && newLineNumber > 0) { - newLineNumber--; - newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); - } - } + if (desiredX >= 0) { + newColumnNumber = myEditor.xyToVisualPosition(new Point(desiredX, Math.max(0, newLineNumber) * myEditor.getLineHeight())).column; + } - if (newColumnNumber < 0) newColumnNumber = 0; - - // There is a possible case that caret is located at the first line and user presses 'Shift+Up'. We want to select all text - // from the document start to the current caret position then. So, we have a dedicated flag for tracking that. - boolean selectToDocumentStart = false; - if (newLineNumber < 0) { - selectToDocumentStart = true; - newLineNumber = 0; - - // We want to move caret to the first column if it's already located at the first line and 'Up' is pressed. + Document document = myEditor.getDocument(); + if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == 1) { + int lastLine = document.getLineCount() - 1; + if (lastLine < 0) lastLine = 0; + if (newColumnNumber > EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber) && + newLineNumber < myEditor.logicalToVisualPosition(new LogicalPosition(lastLine, 0)).line) { newColumnNumber = 0; + newLineNumber++; } + } + else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == -1) { + if (newColumnNumber < 0 && newLineNumber > 0) { + newLineNumber--; + newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); + } + } - VisualPosition pos = new VisualPosition(newLineNumber, newColumnNumber); - if (!myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { - LogicalPosition log = myEditor.visualToLogicalPosition(new VisualPosition(newLineNumber, newColumnNumber, newLeansRight)); - int offset = myEditor.logicalPositionToOffset(log); - if (offset >= document.getTextLength() && (!myEditor.myUseNewRendering || columnShift == 0)) { - int lastOffsetColumn = myEditor.offsetToVisualPosition(document.getTextLength(), true, false).column; - // We want to move caret to the last column if if it's located at the last line and 'Down' is pressed. - if (lastOffsetColumn > newColumnNumber) { - newColumnNumber = lastOffsetColumn; - newLeansRight = true; - } - } - if (!editorSettings.isCaretInsideTabs()) { - CharSequence text = document.getCharsSequence(); - if (offset >= 0 && offset < document.getTextLength()) { - if (text.charAt(offset) == '\t' && (columnShift <= 0 || offset == myOffset)) { - if (columnShift <= 0) { - newColumnNumber = myEditor.offsetToVisualPosition(offset, true, false).column; - } - else { - SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset + 1); - // There is a possible case that tabulation symbol is the last document symbol represented on a visual line before - // soft wrap. We can't just use column from 'offset + 1' because it would point on a next visual line. - if (softWrap == null) { - newColumnNumber = myEditor.offsetToVisualPosition(offset + 1).column; - } - else { - newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); - } - } - } - } - } - } + if (newColumnNumber < 0) newColumnNumber = 0; - pos = new VisualPosition(newLineNumber, newColumnNumber, newLeansRight); - if (columnShift != 0 && lineShift == 0 && myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { - LogicalPosition logical = myEditor.visualToLogicalPosition(pos); - int softWrapOffset = myEditor.logicalPositionToOffset(logical); - if (columnShift >= 0) { - moveToOffset(softWrapOffset); - } - else { - int line = myEditor.offsetToVisualLine(softWrapOffset - 1); - moveToVisualPosition(new VisualPosition(line, EditorUtil.getLastVisualLineColumnNumber(myEditor, line))); - } - } - else { - moveToVisualPosition(pos); - if (!editorSettings.isVirtualSpace() && columnShift == 0 && lastColumnNumber >=0) { - setLastColumnNumber(lastColumnNumber); - } - } + // There is a possible case that caret is located at the first line and user presses 'Shift+Up'. We want to select all text + // from the document start to the current caret position then. So, we have a dedicated flag for tracking that. + boolean selectToDocumentStart = false; + if (newLineNumber < 0) { + selectToDocumentStart = true; + newLineNumber = 0; - if (withSelection) { - if (selectToDocumentStart) { - setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(0), 0); + // We want to move caret to the first column if it's already located at the first line and 'Up' is pressed. + newColumnNumber = 0; + } + + VisualPosition pos = new VisualPosition(newLineNumber, newColumnNumber); + if (!myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { + LogicalPosition log = myEditor.visualToLogicalPosition(new VisualPosition(newLineNumber, newColumnNumber, newLeansRight)); + int offset = myEditor.logicalPositionToOffset(log); + if (offset >= document.getTextLength() && (!myEditor.myUseNewRendering || columnShift == 0)) { + int lastOffsetColumn = myEditor.offsetToVisualPosition(document.getTextLength(), true, false).column; + // We want to move caret to the last column if if it's located at the last line and 'Down' is pressed. + if (lastOffsetColumn > newColumnNumber) { + newColumnNumber = lastOffsetColumn; + newLeansRight = true; } - else if (pos.line >= myEditor.getVisibleLineCount()) { - int endOffset = document.getTextLength(); - if (leadSelectionOffset < endOffset) { - setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(endOffset), endOffset); - } - } - else { - int selectionStartToUse = leadSelectionOffset; - VisualPosition selectionStartPositionToUse = leadSelectionPosition; - if (isUnknownDirection() || oldOffset > getSelectionStart() && oldOffset < getSelectionEnd()) { - if (getOffset() > leadSelectionOffset ^ getSelectionStart() < getSelectionEnd()) { - selectionStartToUse = getSelectionEnd(); - selectionStartPositionToUse = getSelectionEndPosition(); + } + if (!editorSettings.isCaretInsideTabs()) { + CharSequence text = document.getCharsSequence(); + if (offset >= 0 && offset < document.getTextLength()) { + if (text.charAt(offset) == '\t' && (columnShift <= 0 || offset == myOffset)) { + if (columnShift <= 0) { + newColumnNumber = myEditor.offsetToVisualPosition(offset, true, false).column; } else { - selectionStartToUse = getSelectionStart(); - selectionStartPositionToUse = getSelectionStartPosition(); + SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset + 1); + // There is a possible case that tabulation symbol is the last document symbol represented on a visual line before + // soft wrap. We can't just use column from 'offset + 1' because it would point on a next visual line. + if (softWrap == null) { + newColumnNumber = myEditor.offsetToVisualPosition(offset + 1).column; + } + else { + newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber); + } } } - setSelection(selectionStartPositionToUse, selectionStartToUse, getVisualPosition(), getOffset()); + } + } + } + + pos = new VisualPosition(newLineNumber, newColumnNumber, newLeansRight); + if (columnShift != 0 && lineShift == 0 && myEditor.getSoftWrapModel().isInsideSoftWrap(pos)) { + LogicalPosition logical = myEditor.visualToLogicalPosition(pos); + int softWrapOffset = myEditor.logicalPositionToOffset(logical); + if (columnShift >= 0) { + moveToOffset(softWrapOffset); + } + else { + int line = myEditor.offsetToVisualLine(softWrapOffset - 1); + moveToVisualPosition(new VisualPosition(line, EditorUtil.getLastVisualLineColumnNumber(myEditor, line))); + } + } + else { + moveToVisualPosition(pos); + if (!editorSettings.isVirtualSpace() && columnShift == 0 && lastColumnNumber >=0) { + setLastColumnNumber(lastColumnNumber); + } + } + + if (withSelection) { + if (selectToDocumentStart) { + setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(0), 0); + } + else if (pos.line >= myEditor.getVisibleLineCount()) { + int endOffset = document.getTextLength(); + if (leadSelectionOffset < endOffset) { + setSelection(leadSelectionPosition, leadSelectionOffset, myEditor.offsetToVisualPosition(endOffset), endOffset); } } else { - removeSelection(); + int selectionStartToUse = leadSelectionOffset; + VisualPosition selectionStartPositionToUse = leadSelectionPosition; + if (isUnknownDirection() || oldOffset > getSelectionStart() && oldOffset < getSelectionEnd()) { + if (getOffset() > leadSelectionOffset ^ getSelectionStart() < getSelectionEnd()) { + selectionStartToUse = getSelectionEnd(); + selectionStartPositionToUse = getSelectionEndPosition(); + } + else { + selectionStartToUse = getSelectionStart(); + selectionStartPositionToUse = getSelectionStartPosition(); + } + } + setSelection(selectionStartPositionToUse, selectionStartToUse, getVisualPosition(), getOffset()); } - - if (scrollToCaret) { - myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - } - - if (desiredX >= 0) { - myDesiredX = desiredX; - } - - EditorActionUtil.selectNonexpandableFold(myEditor); } + else { + removeSelection(); + } + + if (scrollToCaret) { + myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + } + + if (desiredX >= 0) { + myDesiredX = desiredX; + } + + EditorActionUtil.selectNonexpandableFold(myEditor); }); } @Override public void moveToLogicalPosition(@NotNull final LogicalPosition pos) { - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - moveToLogicalPosition(pos, false, null, true); - } - }); + myEditor.getCaretModel().doWithCaretMerging(() -> moveToLogicalPosition(pos, false, null, true)); } @@ -502,13 +491,10 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { if (debugBuffer != null) { debugBuffer.append("Scheduling expansion of fold region ").append(collapsedAt).append("\n"); } - Runnable runnable = new Runnable() { - @Override - public void run() { - FoldRegion[] allCollapsedAt = myEditor.getFoldingModel().fetchCollapsedAt(offset); - for (FoldRegion foldRange : allCollapsedAt) { - foldRange.setExpanded(true); - } + Runnable runnable = () -> { + FoldRegion[] allCollapsedAt = myEditor.getFoldingModel().fetchCollapsedAt(offset); + for (FoldRegion foldRange : allCollapsedAt) { + foldRange.setExpanded(true); } }; @@ -611,12 +597,7 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { @Override public void moveToVisualPosition(@NotNull final VisualPosition pos) { - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - moveToVisualPosition(pos, true); - } - }); + myEditor.getCaretModel().doWithCaretMerging(() -> moveToVisualPosition(pos, true)); } void moveToVisualPosition(@NotNull VisualPosition pos, boolean fireListeners) { @@ -989,12 +970,8 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { if (myEditor.getCaretModel().addCaret(clone, true)) { if (hasNewSelection) { - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - clone.setSelection(newSelectionStartPosition, newSelectionStartOffset, newSelectionEndPosition, newSelectionEndOffset); - } - }); + myEditor.getCaretModel().doWithCaretMerging( + () -> clone.setSelection(newSelectionStartPosition, newSelectionStartOffset, newSelectionEndPosition, newSelectionEndOffset)); if (!clone.isValid()) { return null; } @@ -1167,102 +1144,99 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { final boolean visualPositionAware, final boolean updateSystemSelection) { - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - int startOffset = _startOffset; - int endOffset = _endOffset; - myUnknownDirection = false; - final Document doc = myEditor.getDocument(); + myEditor.getCaretModel().doWithCaretMerging(() -> { + int startOffset = _startOffset; + int endOffset = _endOffset; + myUnknownDirection = false; + final Document doc = myEditor.getDocument(); - validateContext(true); + validateContext(true); - int textLength = doc.getTextLength(); - if (startOffset < 0 || startOffset > textLength) { - LOG.error("Wrong startOffset: " + startOffset + ", textLength=" + textLength); - } - if (endOffset < 0 || endOffset > textLength) { - LOG.error("Wrong endOffset: " + endOffset + ", textLength=" + textLength); - } + int textLength = doc.getTextLength(); + if (startOffset < 0 || startOffset > textLength) { + LOG.error("Wrong startOffset: " + startOffset + ", textLength=" + textLength); + } + if (endOffset < 0 || endOffset > textLength) { + LOG.error("Wrong endOffset: " + endOffset + ", textLength=" + textLength); + } - if (!visualPositionAware && startOffset == endOffset) { - removeSelection(); - return; - } + if (!visualPositionAware && startOffset == endOffset) { + removeSelection(); + return; + } - /* Normalize selection */ - boolean switchedOffsets = false; - if (startOffset > endOffset) { - int tmp = startOffset; - startOffset = endOffset; - endOffset = tmp; - switchedOffsets = true; - } + /* Normalize selection */ + boolean switchedOffsets = false; + if (startOffset > endOffset) { + int tmp = startOffset; + startOffset = endOffset; + endOffset = tmp; + switchedOffsets = true; + } - FoldingModelEx foldingModel = myEditor.getFoldingModel(); - FoldRegion startFold = foldingModel.getCollapsedRegionAtOffset(startOffset); - if (startFold != null && startFold.getStartOffset() < startOffset) { - startOffset = startFold.getStartOffset(); - } + FoldingModelEx foldingModel = myEditor.getFoldingModel(); + FoldRegion startFold = foldingModel.getCollapsedRegionAtOffset(startOffset); + if (startFold != null && startFold.getStartOffset() < startOffset) { + startOffset = startFold.getStartOffset(); + } - FoldRegion endFold = foldingModel.getCollapsedRegionAtOffset(endOffset); - if (endFold != null && endFold.getStartOffset() < endOffset) { - // All visual positions that lay at collapsed fold region placeholder are mapped to the same offset. Hence, there are - // at least two distinct situations - selection end is located inside collapsed fold region placeholder and just before it. - // We want to expand selection to the fold region end at the former case and keep selection as-is at the latest one. - endOffset = endFold.getEndOffset(); - } + FoldRegion endFold = foldingModel.getCollapsedRegionAtOffset(endOffset); + if (endFold != null && endFold.getStartOffset() < endOffset) { + // All visual positions that lay at collapsed fold region placeholder are mapped to the same offset. Hence, there are + // at least two distinct situations - selection end is located inside collapsed fold region placeholder and just before it. + // We want to expand selection to the fold region end at the former case and keep selection as-is at the latest one. + endOffset = endFold.getEndOffset(); + } - int oldSelectionStart; - int oldSelectionEnd; + int oldSelectionStart; + int oldSelectionEnd; - if (hasSelection()) { - oldSelectionStart = getSelectionStart(); - oldSelectionEnd = getSelectionEnd(); - if (oldSelectionStart == startOffset && oldSelectionEnd == endOffset && !visualPositionAware) return; + if (hasSelection()) { + oldSelectionStart = getSelectionStart(); + oldSelectionEnd = getSelectionEnd(); + if (oldSelectionStart == startOffset && oldSelectionEnd == endOffset && !visualPositionAware) return; + } + else { + oldSelectionStart = oldSelectionEnd = getOffset(); + } + + RangeMarker marker = mySelectionMarker; + if (marker != null) { + marker.dispose(); + } + + marker = doc.createRangeMarker(startOffset, endOffset); + myStartVirtualOffset = 0; + myEndVirtualOffset = 0; + if (visualPositionAware) { + if (endPosition.after(startPosition)) { + setRangeMarkerStartPosition(startPosition); + setRangeMarkerEndPosition(endPosition); + setRangeMarkerEndPositionIsLead(false); } else { - oldSelectionStart = oldSelectionEnd = getOffset(); + setRangeMarkerStartPosition(endPosition); + setRangeMarkerEndPosition(startPosition); + setRangeMarkerEndPositionIsLead(true); } - RangeMarker marker = mySelectionMarker; - if (marker != null) { - marker.dispose(); + if (isVirtualSelectionEnabled() && + myEditor.getDocument().getLineNumber(startOffset) == myEditor.getDocument().getLineNumber(endOffset)) { + int endLineColumn = myEditor.offsetToVisualPosition(endOffset).column; + int startDiff = + EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? endOffset : startOffset) ? startPosition.column - endLineColumn : 0; + int endDiff = + EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? startOffset : endOffset) ? endPosition.column - endLineColumn : 0; + myStartVirtualOffset = Math.max(0, Math.min(startDiff, endDiff)); + myEndVirtualOffset = Math.max(0, Math.max(startDiff, endDiff)); } + } + mySelectionMarker = marker; - marker = doc.createRangeMarker(startOffset, endOffset); - myStartVirtualOffset = 0; - myEndVirtualOffset = 0; - if (visualPositionAware) { - if (endPosition.after(startPosition)) { - setRangeMarkerStartPosition(startPosition); - setRangeMarkerEndPosition(endPosition); - setRangeMarkerEndPositionIsLead(false); - } - else { - setRangeMarkerStartPosition(endPosition); - setRangeMarkerEndPosition(startPosition); - setRangeMarkerEndPositionIsLead(true); - } + myEditor.getSelectionModel().fireSelectionChanged(oldSelectionStart, oldSelectionEnd, startOffset, endOffset); - if (isVirtualSelectionEnabled() && - myEditor.getDocument().getLineNumber(startOffset) == myEditor.getDocument().getLineNumber(endOffset)) { - int endLineColumn = myEditor.offsetToVisualPosition(endOffset).column; - int startDiff = - EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? endOffset : startOffset) ? startPosition.column - endLineColumn : 0; - int endDiff = - EditorUtil.isAtLineEnd(myEditor, switchedOffsets ? startOffset : endOffset) ? endPosition.column - endLineColumn : 0; - myStartVirtualOffset = Math.max(0, Math.min(startDiff, endDiff)); - myEndVirtualOffset = Math.max(0, Math.max(startDiff, endDiff)); - } - } - mySelectionMarker = marker; - - myEditor.getSelectionModel().fireSelectionChanged(oldSelectionStart, oldSelectionEnd, startOffset, endOffset); - - if (updateSystemSelection) { - updateSystemSelection(); - } + if (updateSystemSelection) { + updateSystemSelection(); } }); } @@ -1283,21 +1257,18 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { // However, we don't want to do that for 'sticky selection'. return; } - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - validateContext(true); - int caretOffset = getOffset(); - RangeMarker marker = mySelectionMarker; - if (marker != null) { - int startOffset = marker.getStartOffset(); - int endOffset = marker.getEndOffset(); - marker.dispose(); - mySelectionMarker = null; - myStartVirtualOffset = 0; - myEndVirtualOffset = 0; - myEditor.getSelectionModel().fireSelectionChanged(startOffset, endOffset, caretOffset, caretOffset); - } + myEditor.getCaretModel().doWithCaretMerging(() -> { + validateContext(true); + int caretOffset = getOffset(); + RangeMarker marker = mySelectionMarker; + if (marker != null) { + int startOffset = marker.getStartOffset(); + int endOffset = marker.getEndOffset(); + marker.dispose(); + mySelectionMarker = null; + myStartVirtualOffset = 0; + myEndVirtualOffset = 0; + myEditor.getSelectionModel().fireSelectionChanged(startOffset, endOffset, caretOffset, caretOffset); } }); } @@ -1377,37 +1348,29 @@ public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable { @Override public void selectLineAtCaret() { validateContext(true); - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - SelectionModelImpl.doSelectLineAtCaret(myEditor); - } - }); + myEditor.getCaretModel().doWithCaretMerging(() -> SelectionModelImpl.doSelectLineAtCaret(myEditor)); } @Override public void selectWordAtCaret(final boolean honorCamelWordsSettings) { validateContext(true); - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - @Override - public void run() { - removeSelection(); - final EditorSettings settings = myEditor.getSettings(); - boolean camelTemp = settings.isCamelWords(); + myEditor.getCaretModel().doWithCaretMerging(() -> { + removeSelection(); + final EditorSettings settings = myEditor.getSettings(); + boolean camelTemp = settings.isCamelWords(); - final boolean needOverrideSetting = camelTemp && !honorCamelWordsSettings; + final boolean needOverrideSetting = camelTemp && !honorCamelWordsSettings; + if (needOverrideSetting) { + settings.setCamelWords(false); + } + + try { + EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET); + handler.execute(myEditor, CaretImpl.this, myEditor.getDataContext()); + } + finally { if (needOverrideSetting) { - settings.setCamelWords(false); - } - - try { - EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET); - handler.execute(myEditor, CaretImpl.this, myEditor.getDataContext()); - } - finally { - if (needOverrideSetting) { - settings.resetCamelWords(); - } + settings.resetCamelWords(); } } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java index 89866d91bd75..f817cbfa97e3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java @@ -70,12 +70,9 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, } void onBulkDocumentUpdateFinished() { - doWithCaretMerging(new Runnable() { - @Override - public void run() { - for (CaretImpl caret : myCarets) { - caret.onBulkDocumentUpdateFinished(); - } + doWithCaretMerging(() -> { + for (CaretImpl caret : myCarets) { + caret.onBulkDocumentUpdateFinished(); } }); } @@ -85,12 +82,9 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, isDocumentChanged = true; try { myIsInUpdate = false; - doWithCaretMerging(new Runnable() { - @Override - public void run() { - for (CaretImpl caret : myCarets) { - caret.updateCaretPosition((DocumentEventImpl)e); - } + doWithCaretMerging(() -> { + for (CaretImpl caret : myCarets) { + caret.updateCaretPosition((DocumentEventImpl)e); } }); } @@ -344,22 +338,20 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, if (myCurrentCaret != null) { throw new IllegalStateException("Current caret is defined, cannot operate on other ones"); } - doWithCaretMerging(new Runnable() { - public void run() { - try { - List sortedCarets = getAllCarets(); - if (reverseOrder) { - Collections.reverse(sortedCarets); - } - for (Caret caret : sortedCarets) { - myCurrentCaret = (CaretImpl)caret; - action.perform(caret); - } + doWithCaretMerging(() -> { + try { + List sortedCarets = getAllCarets(); + if (reverseOrder) { + Collections.reverse(sortedCarets); } - finally { - myCurrentCaret = null; + for (Caret caret : sortedCarets) { + myCurrentCaret = (CaretImpl)caret; + action.perform(caret); } } + finally { + myCurrentCaret = null; + } }); } @@ -453,49 +445,47 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, if (caretStates.isEmpty()) { throw new IllegalArgumentException("At least one caret should exist"); } - doWithCaretMerging(new Runnable() { - public void run() { - int index = 0; - int oldCaretCount = myCarets.size(); - Iterator caretIterator = myCarets.iterator(); - for (CaretState caretState : caretStates) { - CaretImpl caret; - boolean caretAdded; - if (index++ < oldCaretCount) { - caret = caretIterator.next(); - caretAdded = false; - } - else { - caret = new CaretImpl(myEditor); - if (caretState != null && caretState.getCaretPosition() != null) { - caret.moveToLogicalPosition(caretState.getCaretPosition(), false, null, false); - } - synchronized (myCarets) { - myCarets.add(caret); - } - fireCaretAdded(caret); - caretAdded = true; - } - if (caretState != null && caretState.getCaretPosition() != null && !caretAdded) { - caret.moveToLogicalPosition(caretState.getCaretPosition()); - } - if (caretState != null && caretState.getSelectionStart() != null && caretState.getSelectionEnd() != null) { - caret.setSelection(myEditor.logicalToVisualPosition(caretState.getSelectionStart()), - myEditor.logicalPositionToOffset(caretState.getSelectionStart()), - myEditor.logicalToVisualPosition(caretState.getSelectionEnd()), - myEditor.logicalPositionToOffset(caretState.getSelectionEnd()), - updateSystemSelection); - } + doWithCaretMerging(() -> { + int index = 0; + int oldCaretCount = myCarets.size(); + Iterator caretIterator = myCarets.iterator(); + for (CaretState caretState : caretStates) { + CaretImpl caret; + boolean caretAdded; + if (index++ < oldCaretCount) { + caret = caretIterator.next(); + caretAdded = false; } - int caretsToRemove = myCarets.size() - caretStates.size(); - for (int i = 0; i < caretsToRemove; i++) { - CaretImpl caret; + else { + caret = new CaretImpl(myEditor); + if (caretState != null && caretState.getCaretPosition() != null) { + caret.moveToLogicalPosition(caretState.getCaretPosition(), false, null, false); + } synchronized (myCarets) { - caret = myCarets.removeLast(); + myCarets.add(caret); } - fireCaretRemoved(caret); - Disposer.dispose(caret); + fireCaretAdded(caret); + caretAdded = true; } + if (caretState != null && caretState.getCaretPosition() != null && !caretAdded) { + caret.moveToLogicalPosition(caretState.getCaretPosition()); + } + if (caretState != null && caretState.getSelectionStart() != null && caretState.getSelectionEnd() != null) { + caret.setSelection(myEditor.logicalToVisualPosition(caretState.getSelectionStart()), + myEditor.logicalPositionToOffset(caretState.getSelectionStart()), + myEditor.logicalToVisualPosition(caretState.getSelectionEnd()), + myEditor.logicalPositionToOffset(caretState.getSelectionEnd()), + updateSystemSelection); + } + } + int caretsToRemove = myCarets.size() - caretStates.size(); + for (int i = 0; i < caretsToRemove; i++) { + CaretImpl caret; + synchronized (myCarets) { + caret = myCarets.removeLast(); + } + fireCaretRemoved(caret); + Disposer.dispose(caret); } }); } @@ -533,12 +523,9 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, ", document changed: " + isDocumentChanged + ", perform caret merging: " + myPerformCaretMergingAfterCurrentOperation + ", current caret: " + myCurrentCaret + - ", all carets: " + ContainerUtil.map(myCarets, new Function() { - @Override - public String fun(CaretImpl caret) { - return caret.dumpState(); - } - }) + "]"; + ", all carets: " + ContainerUtil.map(myCarets, caret -> { + return caret.dumpState(); + }) + "]"; } private static class VisualPositionComparator implements Comparator { diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java index 949d41ec5e63..701a4892fd5d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java @@ -190,12 +190,7 @@ public class EditorComponentImpl extends JTextComponent implements Scrollable, D @Override public ActionCallback type(final String text) { final ActionCallback result = new ActionCallback(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myEditor.type(text).notify(result); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myEditor.type(text).notify(result)); return result; } @@ -694,34 +689,30 @@ public class EditorComponentImpl extends JTextComponent implements Scrollable, D if (!FileDocumentManager.getInstance().requestWriting(document, project)) { return; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, project) { - @Override - public void run() { - document.startGuardedBlockChecking(); - try { - if (text == null) { - // remove - document.deleteString(offset, offset + length); - } else if (length == 0) { - // insert - document.insertString(offset, text); - } else { - document.replaceString(offset, offset + length, text); - } - } - catch (ReadOnlyFragmentModificationException e) { - EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e); - } - finally { - document.stopGuardedBlockChecking(); - } - } - }); - } - }, "", document, UndoConfirmationPolicy.DEFAULT, document); + CommandProcessor.getInstance().executeCommand(project, + () -> ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, project) { + @Override + public void run() { + document.startGuardedBlockChecking(); + try { + if (text == null) { + // remove + document.deleteString(offset, offset + length); + } else if (length == 0) { + // insert + document.insertString(offset, text); + } else { + document.replaceString(offset, offset + length, text); + } + } + catch (ReadOnlyFragmentModificationException e) { + EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e); + } + finally { + document.stopGuardedBlockChecking(); + } + } + }), "", document, UndoConfirmationPolicy.DEFAULT, document); } /** {@linkplain DefaultCaret} does a lot of work we don't want (listening @@ -964,12 +955,9 @@ public class EditorComponentImpl extends JTextComponent implements Scrollable, D fireJTextComponentDocumentChange(event); } } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos); - fireJTextComponentDocumentChange(event); - } + ApplicationManager.getApplication().invokeLater(() -> { + firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos); + fireJTextComponentDocumentChange(event); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java index 65f1909c5585..70a6f69c2eb3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java @@ -178,17 +178,14 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse @SuppressWarnings({"ConstantConditions"}) private void installDnD() { DnDSupport.createBuilder(this) - .setBeanProvider(new Function() { - @Override - public DnDDragStartBean fun(DnDActionInfo info) { - final GutterMark renderer = getGutterRenderer(info.getPoint()); - if (renderer instanceof GutterIconRenderer && - ((GutterIconRenderer)renderer).getDraggableObject() != null && - (info.isCopy() || info.isMove())) { - return new DnDDragStartBean(renderer); - } - return null; + .setBeanProvider(info -> { + final GutterMark renderer = getGutterRenderer(info.getPoint()); + if (renderer instanceof GutterIconRenderer && + ((GutterIconRenderer)renderer).getDraggableObject() != null && + (info.isCopy() || info.isMove())) { + return new DnDDragStartBean(renderer); } + return null; }) .setDropHandler(new DnDDropHandler() { @Override @@ -238,12 +235,9 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse return true; } }) - .setImageProvider(new NullableFunction() { - @Override - public DnDImage fun(DnDActionInfo info) { - Image image = IconUtil.toImage(scaleIcon(getGutterRenderer(info.getPoint()).getIcon())); - return new DnDImage(image, new Point(image.getWidth(null) / 2, image.getHeight(null) / 2)); - } + .setImageProvider((NullableFunction)info -> { + Image image = IconUtil.toImage(scaleIcon(getGutterRenderer(info.getPoint()).getIcon())); + return new DnDImage(image, new Point(image.getWidth(null) / 2, image.getHeight(null) / 2)); }) .enableAsNativeTarget() // required to accept dragging from editor (as editor component doesn't use DnDSupport to implement drag'n'drop) .install(); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java index 8d7da70aadf0..443a1b61663d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java @@ -2006,18 +2006,15 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi assertIsDispatchThread(); if (!updatingSize) { updatingSize = true; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - try { - if (!isDisposed()) { - myGutterComponent.updateSize(); - } - } - finally { - updatingSize = false; + SwingUtilities.invokeLater(() -> { + try { + if (!isDisposed()) { + myGutterComponent.updateSize(); } } + finally { + updatingSize = false; + } }); } } @@ -2104,12 +2101,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi public void stopDumbLater() { if (ApplicationManager.getApplication().isUnitTestMode()) return; - final Runnable stopDumbRunnable = new Runnable() { - @Override - public void run() { - stopDumb(); - } - }; + final Runnable stopDumbRunnable = () -> stopDumb(); ApplicationManager.getApplication().invokeLater(stopDumbRunnable, ModalityState.current()); } @@ -2203,15 +2195,12 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi private static final String WHITESPACE_CHARS = " \t" + IDEOGRAPHIC_SPACE; private void paintCustomRenderers(@NotNull final Graphics2D g, final int clipStartOffset, final int clipEndOffset) { - myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx highlighter) { - final CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer(); - if (customRenderer != null && clipStartOffset < highlighter.getEndOffset() && highlighter.getStartOffset() < clipEndOffset) { - customRenderer.paint(EditorImpl.this, highlighter, g); - } - return true; + myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, highlighter -> { + final CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer(); + if (customRenderer != null && clipStartOffset < highlighter.getEndOffset() && highlighter.getStartOffset() < clipEndOffset) { + customRenderer.paint(EditorImpl.this, highlighter, g); } + return true; }); } @@ -2369,12 +2358,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi final int startLine = yToVisibleLine(clip.y); final int endLine = yToVisibleLine(clip.y + clip.height) + 1; - Processor paintProcessor = new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx highlighter) { - paintSegmentHighlighterAfterEndOfLine(g, highlighter, startLine, endLine); - return true; - } + Processor paintProcessor = highlighter -> { + paintSegmentHighlighterAfterEndOfLine(g, highlighter, startLine, endLine); + return true; }; docMarkup.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, paintProcessor); myMarkupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, paintProcessor); @@ -3298,12 +3284,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi @NotNull MarkupModelEx markupModel, int clipStartOffset, int clipEndOffset) { - markupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx lineMarker) { - paintLineMarkerSeparator(lineMarker, clip, g); - return true; - } + markupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, lineMarker -> { + paintLineMarkerSeparator(lineMarker, clip, g); + return true; }); } @@ -4306,12 +4289,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi // if (myMousePressedInsideSelection) getSelectionModel().removeSelection(); final FoldRegion region = getFoldingModel().getFoldingPlaceholderAt(e.getPoint()); if (e.getX() >= 0 && e.getY() >= 0 && region != null && region == myMouseSelectedRegion) { - getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - myFoldingModel.flushCaretShift(); - region.setExpanded(true); - } + getFoldingModel().runBatchFoldingOperation(() -> { + myFoldingModel.flushCaretShift(); + region.setExpanded(true); }); // The call below is performed because gutter's height is not updated sometimes, i.e. it sticks to the value that corresponds @@ -4397,12 +4377,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (myCommandProcessor == null || myMousePressedEvent != null && myMousePressedEvent.isConsumed()) { return; } - myCommandProcessor.executeCommand(myProject, new Runnable() { - @Override - public void run() { - processMouseDragged(e); - } - }, "", MOUSE_DRAGGED_GROUP, UndoConfirmationPolicy.DEFAULT, getDocument()); + myCommandProcessor.executeCommand(myProject, () -> processMouseDragged(e), "", MOUSE_DRAGGED_GROUP, UndoConfirmationPolicy.DEFAULT, getDocument()); } private void processMouseDragged(@NotNull MouseEvent e) { @@ -5406,12 +5381,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi myMouseSelectionStateAlarm.cancelAllRequests(); if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE) { if (myMouseSelectionStateResetRunnable == null) { - myMouseSelectionStateResetRunnable = new Runnable() { - @Override - public void run() { - resetMouseSelectionState(null); - } - }; + myMouseSelectionStateResetRunnable = () -> resetMouseSelectionState(null); } myMouseSelectionStateAlarm.addRequest(myMouseSelectionStateResetRunnable, Registry.intValue("editor.mouseSelectionStateResetTimeout"), ModalityState.stateForComponent(myEditorComponent)); @@ -5711,17 +5681,8 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi } private void runUndoTransparent(@NotNull final Runnable runnable) { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(runnable); - } - }, "", getDocument(), UndoConfirmationPolicy.DEFAULT, getDocument()); - } - }); + CommandProcessor.getInstance().runUndoTransparentAction( + () -> CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(runnable), "", getDocument(), UndoConfirmationPolicy.DEFAULT, getDocument())); } private void replaceInputMethodText(@NotNull InputMethodEvent e) { @@ -5752,14 +5713,11 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (composedText != null) { if (!isViewer() && doc.isWritable()) { - runUndoTransparent(new Runnable() { - @Override - public void run() { - int docLength = doc.getTextLength(); - ProperTextRange range = composedTextRange.intersection(new TextRange(0, docLength)); - if (range != null) { - doc.deleteString(range.getStartOffset(), range.getEndOffset()); - } + runUndoTransparent(() -> { + int docLength = doc.getTextLength(); + ProperTextRange range = composedTextRange.intersection(new TextRange(0, docLength)); + if (range != null) { + doc.deleteString(range.getStartOffset(), range.getEndOffset()); } }); } @@ -5785,12 +5743,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (composedTextIndex < text.getEndIndex()) { createComposedString(composedTextIndex, text); - runUndoTransparent(new Runnable() { - @Override - public void run() { - EditorModificationUtil.insertStringAtCaret(EditorImpl.this, composedText, false, false); - } - }); + runUndoTransparent(() -> EditorModificationUtil.insertStringAtCaret(EditorImpl.this, composedText, false, false)); composedTextRange = ProperTextRange.from(getCaretModel().getOffset(), composedText.length()); } @@ -5869,12 +5822,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi } if (myCommandProcessor != null) { - Runnable runnable = new Runnable() { - @Override - public void run() { - if (processMousePressed(e) && myProject != null && !myProject.isDefault()) { - IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); - } + Runnable runnable = () -> { + if (processMousePressed(e) && myProject != null && !myProject.isDefault()) { + IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); } }; myCommandProcessor @@ -5925,12 +5875,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi } if (myCommandProcessor != null) { - Runnable runnable = new Runnable() { - @Override - public void run() { - processMouseReleased(e); - } - }; + Runnable runnable = () -> processMouseReleased(e); myCommandProcessor .executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); @@ -5985,16 +5930,13 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi final boolean expansion = !range.isExpanded(); int scrollShift = y - getScrollingModel().getVerticalScrollOffset(); - Runnable processor = new Runnable() { - @Override - public void run() { - myFoldingModel.flushCaretShift(); - range.setExpanded(expansion); - if (e.isAltDown()) { - for (FoldRegion region : myFoldingModel.getAllFoldRegions()) { - if (region.getStartOffset() >= range.getStartOffset() && region.getEndOffset() <= range.getEndOffset()) { - region.setExpanded(expansion); - } + Runnable processor = () -> { + myFoldingModel.flushCaretShift(); + range.setExpanded(expansion); + if (e.isAltDown()) { + for (FoldRegion region : myFoldingModel.getAllFoldRegions()) { + if (region.getStartOffset() >= range.getStartOffset() && region.getEndOffset() <= range.getEndOffset()) { + region.setExpanded(expansion); } } } @@ -6548,51 +6490,38 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi editor.getCaretModel().moveToOffset(editor.mySavedCaretOffsetForDNDUndoHack); } - CommandProcessor.getInstance().executeCommand(editor.myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - editor.getSelectionModel().removeSelection(); + CommandProcessor.getInstance().executeCommand(editor.myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + editor.getSelectionModel().removeSelection(); - final int offset; - if (editor.myDraggedRange != null) { - editor.getCaretModel().moveToOffset(caretOffset); - offset = caretOffset; - } - else { - offset = editor.getCaretModel().getOffset(); - } - if (editor.getDocument().getRangeGuard(offset, offset) != null) { - return; - } + final int offset; + if (editor.myDraggedRange != null) { + editor.getCaretModel().moveToOffset(caretOffset); + offset = caretOffset; + } + else { + offset = editor.getCaretModel().getOffset(); + } + if (editor.getDocument().getRangeGuard(offset, offset) != null) { + return; + } - editor.putUserData(LAST_PASTED_REGION, null); + editor.putUserData(LAST_PASTED_REGION, null); - EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE); - LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler); - ((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), new Producer() { - @Override - public Transferable produce() { - return t; - } - }); + EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE); + LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler); + ((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), () -> t); - TextRange range = editor.getUserData(LAST_PASTED_REGION); - if (range != null) { - editor.getCaretModel().moveToOffset(range.getStartOffset()); - editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); - } - } - catch (Exception exception) { - LOG.error(exception); - } - } - }); + TextRange range = editor.getUserData(LAST_PASTED_REGION); + if (range != null) { + editor.getCaretModel().moveToOffset(range.getStartOffset()); + editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); + } } - }, EditorBundle.message("paste.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); + catch (Exception exception) { + LOG.error(exception); + } + }), EditorBundle.message("paste.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); return true; } @@ -6658,27 +6587,19 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), editor.getProject())) { return; } - CommandProcessor.getInstance().executeCommand(editor.myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Document doc = editor.getDocument(); - doc.startGuardedBlockChecking(); - try { - doc.deleteString(editor.myDraggedRange.getStartOffset(), editor.myDraggedRange.getEndOffset()); - } - catch (ReadOnlyFragmentModificationException e) { - EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e); - } - finally { - doc.stopGuardedBlockChecking(); - } - } - }); + CommandProcessor.getInstance().executeCommand(editor.myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + Document doc = editor.getDocument(); + doc.startGuardedBlockChecking(); + try { + doc.deleteString(editor.myDraggedRange.getStartOffset(), editor.myDraggedRange.getEndOffset()); } - }, EditorBundle.message("move.selection.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); + catch (ReadOnlyFragmentModificationException e) { + EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e); + } + finally { + doc.stopGuardedBlockChecking(); + } + }), EditorBundle.message("move.selection.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); } editor.clearDraggedRange(); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java index 58ddf0cf5cc9..3cf9137e10db 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java @@ -255,16 +255,13 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark private void collectRangeHighlighters(@NotNull MarkupModelEx markupModel, final int visualLine, @NotNull final Collection highlighters) { final int startOffset = getOffset(fitLineToEditor(visualLine - myPreviewLines), true); final int endOffset = getOffset(fitLineToEditor(visualLine + myPreviewLines), false); - markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx highlighter) { - if (highlighter.getErrorStripeMarkColor() != null) { - if (highlighter.getStartOffset() < endOffset && highlighter.getEndOffset() > startOffset) { - highlighters.add(highlighter); - } + markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> { + if (highlighter.getErrorStripeMarkColor() != null) { + if (highlighter.getStartOffset() < endOffset && highlighter.getEndOffset() > startOffset) { + highlighters.add(highlighter); } - return true; } + return true; }); } @@ -291,18 +288,15 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark @NotNull final Collection nearest) { int startOffset = yPositionToOffset(scrollBarY - myMinMarkHeight, true); int endOffset = yPositionToOffset(scrollBarY + myMinMarkHeight, false); - markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx highlighter) { - if (highlighter.getErrorStripeMarkColor() != null) { - ProperTextRange range = offsetsToYPositions(highlighter.getStartOffset(), highlighter.getEndOffset()); - if (scrollBarY >= range.getStartOffset() - myMinMarkHeight * 2 && - scrollBarY <= range.getEndOffset() + myMinMarkHeight * 2) { - nearest.add(highlighter); - } + markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> { + if (highlighter.getErrorStripeMarkColor() != null) { + ProperTextRange range = offsetsToYPositions(highlighter.getStartOffset(), highlighter.getEndOffset()); + if (scrollBarY >= range.getStartOffset() - myMinMarkHeight * 2 && + scrollBarY <= range.getEndOffset() + myMinMarkHeight * 2) { + nearest.add(highlighter); } - return true; } + return true; }); } @@ -723,18 +717,8 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark } private void drawMarkup(@NotNull final Graphics g, int startOffset, int endOffset, @NotNull MarkupModelEx markup1, @NotNull MarkupModelEx markup2) { - final Queue thinEnds = new PriorityQueue(5, new Comparator() { - @Override - public int compare(@NotNull PositionedStripe o1, @NotNull PositionedStripe o2) { - return o1.yEnd - o2.yEnd; - } - }); - final Queue wideEnds = new PriorityQueue(5, new Comparator() { - @Override - public int compare(@NotNull PositionedStripe o1, @NotNull PositionedStripe o2) { - return o1.yEnd - o2.yEnd; - } - }); + final Queue thinEnds = new PriorityQueue(5, (o1, o2) -> o1.yEnd - o2.yEnd); + final Queue wideEnds = new PriorityQueue(5, (o1, o2) -> o1.yEnd - o2.yEnd); // sorted by layer final List thinStripes = new ArrayList(); // layer desc final List wideStripes = new ArrayList(); // layer desc @@ -746,70 +730,67 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark MarkupIterator iterator = IntervalTreeImpl.mergeIterators(iterator1, iterator2, RangeHighlighterEx.BY_AFFECTED_START_OFFSET); try { - ContainerUtil.process(iterator, new Processor() { - @Override - public boolean process(@NotNull RangeHighlighterEx highlighter) { - Color color = highlighter.getErrorStripeMarkColor(); - if (color == null) return true; - boolean isThin = highlighter.isThinErrorStripeMark(); - int[] yStart = isThin ? thinYStart : wideYStart; - List stripes = isThin ? thinStripes : wideStripes; - Queue ends = isThin ? thinEnds : wideEnds; + ContainerUtil.process(iterator, highlighter -> { + Color color = highlighter.getErrorStripeMarkColor(); + if (color == null) return true; + boolean isThin = highlighter.isThinErrorStripeMark(); + int[] yStart = isThin ? thinYStart : wideYStart; + List stripes = isThin ? thinStripes : wideStripes; + Queue ends = isThin ? thinEnds : wideEnds; - ProperTextRange range = offsetsToYPositions(highlighter.getStartOffset(), highlighter.getEndOffset()); - final int ys = range.getStartOffset(); - int ye = range.getEndOffset(); - if (ye - ys < myMinMarkHeight) ye = ys + myMinMarkHeight; + ProperTextRange range = offsetsToYPositions(highlighter.getStartOffset(), highlighter.getEndOffset()); + final int ys = range.getStartOffset(); + int ye = range.getEndOffset(); + if (ye - ys < myMinMarkHeight) ye = ys + myMinMarkHeight; - yStart[0] = drawStripesEndingBefore(ys, ends, stripes, g, yStart[0]); + yStart[0] = drawStripesEndingBefore(ys, ends, stripes, g, yStart[0]); - final int layer = highlighter.getLayer(); + final int layer = highlighter.getLayer(); - PositionedStripe stripe = null; - int i; - for (i = 0; i < stripes.size(); i++) { - PositionedStripe s = stripes.get(i); - if (s.layer == layer) { - stripe = s; - break; - } - if (s.layer < layer) { - break; - } + PositionedStripe stripe = null; + int i; + for (i = 0; i < stripes.size(); i++) { + PositionedStripe s = stripes.get(i); + if (s.layer == layer) { + stripe = s; + break; } - if (stripe == null) { - // started new stripe, draw previous above - if (i == 0 && yStart[0] != ys) { - if (!stripes.isEmpty()) { - PositionedStripe top = stripes.get(0); - drawSpot(g, top.thin, yStart[0], ys, top.color); - } - yStart[0] = ys; + if (s.layer < layer) { + break; + } + } + if (stripe == null) { + // started new stripe, draw previous above + if (i == 0 && yStart[0] != ys) { + if (!stripes.isEmpty()) { + PositionedStripe top = stripes.get(0); + drawSpot(g, top.thin, yStart[0], ys, top.color); } - stripe = new PositionedStripe(color, ye, isThin, layer); - stripes.add(i, stripe); + yStart[0] = ys; + } + stripe = new PositionedStripe(color, ye, isThin, layer); + stripes.add(i, stripe); + ends.offer(stripe); + } + else { + if (stripe.yEnd < ye) { + if (!color.equals(stripe.color)) { + // paint previous stripe on this layer + if (i == 0 && yStart[0] != ys) { + drawSpot(g, stripe.thin, yStart[0], ys, stripe.color); + yStart[0] = ys; + } + stripe.color = color; + } + + // key changed, reinsert into queue + ends.remove(stripe); + stripe.yEnd = ye; ends.offer(stripe); } - else { - if (stripe.yEnd < ye) { - if (!color.equals(stripe.color)) { - // paint previous stripe on this layer - if (i == 0 && yStart[0] != ys) { - drawSpot(g, stripe.thin, yStart[0], ys, stripe.color); - yStart[0] = ys; - } - stripe.color = color; - } - - // key changed, reinsert into queue - ends.remove(stripe); - stripe.yEnd = ye; - ends.offer(stripe); - } - } - - return true; } + + return true; }); } finally { @@ -864,12 +845,7 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark // mouse events @Override public void mouseClicked(@NotNull final MouseEvent e) { - CommandProcessor.getInstance().executeCommand(myEditor.getProject(), new Runnable() { - @Override - public void run() { - doMouseClicked(e); - } - }, + CommandProcessor.getInstance().executeCommand(myEditor.getProject(), () -> doMouseClicked(e), EditorBundle.message("move.caret.command.name"), DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument() @@ -943,12 +919,7 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark private void showTrafficLightTooltip(@NotNull MouseEvent e) { if (myTrafficTooltipRenderer == null) { - myTrafficTooltipRenderer = myTooltipRendererProvider.createTrafficTooltipRenderer(new Runnable() { - @Override - public void run() { - myTrafficTooltipRenderer = null; - } - }, myEditor); + myTrafficTooltipRenderer = myTooltipRendererProvider.createTrafficTooltipRenderer(() -> myTrafficTooltipRenderer = null, myEditor); } showTooltip(e, myTrafficTooltipRenderer, new HintHint(e).setAwtTooltip(true).setMayCenterPosition(true).setContentActive(false) .setPreferredPosition(Balloon.Position.atLeft)); @@ -1222,13 +1193,11 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark for (RangeHighlighterEx rangeHighlighter : rangeHighlighters) { myHighlighters.add(rangeHighlighter); } - Collections.sort(myHighlighters, new Comparator() { - public int compare(@NotNull RangeHighlighterEx ex1, @NotNull RangeHighlighterEx ex2) { - LogicalPosition startPos1 = myEditor.offsetToLogicalPosition(ex1.getAffectedAreaStartOffset()); - LogicalPosition startPos2 = myEditor.offsetToLogicalPosition(ex2.getAffectedAreaStartOffset()); - if (startPos1.line != startPos2.line) return 0; - return startPos1.column - startPos2.column; - } + Collections.sort(myHighlighters, (ex1, ex2) -> { + LogicalPosition startPos1 = myEditor.offsetToLogicalPosition(ex1.getAffectedAreaStartOffset()); + LogicalPosition startPos2 = myEditor.offsetToLogicalPosition(ex2.getAffectedAreaStartOffset()); + if (startPos1.line != startPos2.line) return 0; + return startPos1.column - startPos2.column; }); } @@ -1406,13 +1375,10 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark if (needDelay && !myShowInstantly) { myDelayed = true; Alarm alarm = new Alarm(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - if (myEditorPreviewHint == null || !myDelayed) return; - showEditorHint(hintManager, myPointHolder.get(), myHintHolder.get()); - myDelayed = false; - } + alarm.addRequest(() -> { + if (myEditorPreviewHint == null || !myDelayed) return; + showEditorHint(hintManager, myPointHolder.get(), myHintHolder.get()); + myDelayed = false; }, /*Registry.intValue("ide.tooltip.initialDelay")*/300); } else if (!myDelayed) { diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java index 9de2346e741d..0feccd5f35d8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java @@ -40,15 +40,12 @@ abstract class FoldRegionsTree { @NotNull private List myRegions = ContainerUtil.newArrayList(); - private static final Comparator BY_END_OFFSET = new Comparator() { - @Override - public int compare(FoldRegion r1, FoldRegion r2) { - int end1 = r1.getEndOffset(); - int end2 = r2.getEndOffset(); - if (end1 < end2) return -1; - if (end1 > end2) return 1; - return 0; - } + private static final Comparator BY_END_OFFSET = (r1, r2) -> { + int end1 = r1.getEndOffset(); + int end2 = r2.getEndOffset(); + if (end1 < end2) return -1; + if (end1 > end2) return 1; + return 0; }; private static final Comparator BY_END_OFFSET_REVERSE = Collections.reverseOrder(BY_END_OFFSET); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FontInfo.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FontInfo.java index 9d8e0b228831..8429657af5d2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FontInfo.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FontInfo.java @@ -97,12 +97,7 @@ public class FontInfo { return font.deriveFont(Collections.singletonMap(TextAttribute.LIGATURES, TextAttribute.LIGATURES_ON)); } - private static final Comparator BY_NAME = new Comparator() { - @Override - public int compare(File file1, File file2) { - return file1.getName().compareTo(file2.getName()); - } - }; + private static final Comparator BY_NAME = (file1, file2) -> file1.getName().compareTo(file2.getName()); @Nullable private static File findFileForFont(@NotNull String familyName, int style) { @@ -115,14 +110,11 @@ public class FontInfo { @Nullable private static File doFindFileForFont(@NotNull String familyName, final int style) { final String normalizedFamilyName = familyName.toLowerCase(Locale.getDefault()).replace(" ", ""); - FilenameFilter filter = new FilenameFilter() { - @Override - public boolean accept(File file, String name) { - String normalizedName = name.toLowerCase(Locale.getDefault()); - return normalizedName.startsWith(normalizedFamilyName) && - (normalizedName.endsWith(".otf") || normalizedName.endsWith(".ttf")) && - (style == -1 || style == getFontStyle(normalizedName)); - } + FilenameFilter filter = (file, name) -> { + String normalizedName = name.toLowerCase(Locale.getDefault()); + return normalizedName.startsWith(normalizedFamilyName) && + (normalizedName.endsWith(".otf") || normalizedName.endsWith(".ttf")) && + (style == -1 || style == getFontStyle(normalizedName)); }; List files = new ArrayList(); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/ForcedSoftWrapsNotificationProvider.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/ForcedSoftWrapsNotificationProvider.java index bbb338e819a1..0c366cf767d6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/ForcedSoftWrapsNotificationProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/ForcedSoftWrapsNotificationProvider.java @@ -51,19 +51,13 @@ public class ForcedSoftWrapsNotificationProvider extends EditorNotifications.Pro final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(EditorBundle.message("forced.soft.wrap.message")); - panel.createActionLabel(EditorBundle.message("forced.soft.wrap.hide.message"), new Runnable() { - @Override - public void run() { - editor.putUserData(EditorImpl.FORCED_SOFT_WRAPS, null); - EditorNotifications.getInstance(project).updateNotifications(file); - } + panel.createActionLabel(EditorBundle.message("forced.soft.wrap.hide.message"), () -> { + editor.putUserData(EditorImpl.FORCED_SOFT_WRAPS, null); + EditorNotifications.getInstance(project).updateNotifications(file); }); - panel.createActionLabel(EditorBundle.message("forced.soft.wrap.dont.show.again.message"), new Runnable() { - @Override - public void run() { - PropertiesComponent.getInstance().setValue(DISABLED_NOTIFICATION_KEY, "true"); - EditorNotifications.getInstance(project).updateAllNotifications(); - } + panel.createActionLabel(EditorBundle.message("forced.soft.wrap.dont.show.again.message"), () -> { + PropertiesComponent.getInstance().setValue(DISABLED_NOTIFICATION_KEY, "true"); + EditorNotifications.getInstance(project).updateAllNotifications(); }); return panel; } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java index bf46c6d14e22..8acaf90927fb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java @@ -40,41 +40,38 @@ import java.util.List; public final class IterationState { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.IterationState"); - private static final Comparator BY_LAYER_THEN_ATTRIBUTES = new Comparator() { - @Override - public int compare(RangeHighlighterEx o1, RangeHighlighterEx o2) { - final int result = LayerComparator.INSTANCE.compare(o1, o2); - if (result != 0) { - return result; - } - - // There is a possible case when more than one highlighter target the same region (e.g. 'identifier under caret' and 'identifier'). - // We want to prefer the one that defines foreground color to the one that doesn't define (has either fore- or background colors - // while the other one has only foreground color). See IDEA-85697 for concrete example. - final TextAttributes a1 = o1.getTextAttributes(); - final TextAttributes a2 = o2.getTextAttributes(); - if (a1 == null ^ a2 == null) { - return a1 == null ? 1 : -1; - } - - if (a1 == null) { - return result; - } - - final Color fore1 = a1.getForegroundColor(); - final Color fore2 = a2.getForegroundColor(); - if (fore1 == null ^ fore2 == null) { - return fore1 == null ? 1 : -1; - } - - final Color back1 = a1.getBackgroundColor(); - final Color back2 = a2.getBackgroundColor(); - if (back1 == null ^ back2 == null) { - return back1 == null ? 1 : -1; - } - + private static final Comparator BY_LAYER_THEN_ATTRIBUTES = (o1, o2) -> { + final int result = LayerComparator.INSTANCE.compare(o1, o2); + if (result != 0) { return result; } + + // There is a possible case when more than one highlighter target the same region (e.g. 'identifier under caret' and 'identifier'). + // We want to prefer the one that defines foreground color to the one that doesn't define (has either fore- or background colors + // while the other one has only foreground color). See IDEA-85697 for concrete example. + final TextAttributes a1 = o1.getTextAttributes(); + final TextAttributes a2 = o2.getTextAttributes(); + if (a1 == null ^ a2 == null) { + return a1 == null ? 1 : -1; + } + + if (a1 == null) { + return result; + } + + final Color fore1 = a1.getForegroundColor(); + final Color fore2 = a2.getForegroundColor(); + if (fore1 == null ^ fore2 == null) { + return fore1 == null ? 1 : -1; + } + + final Color back1 = a1.getBackgroundColor(); + final Color back2 = a2.getBackgroundColor(); + if (back1 == null ^ back2 == null) { + return back1 == null ? 1 : -1; + } + + return result; }; private final TextAttributes myMergedAttributes = new TextAttributes(); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SelectionModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SelectionModelImpl.java index 01db347cb86b..8c8da8b25098 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SelectionModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SelectionModelImpl.java @@ -68,11 +68,9 @@ public class SelectionModelImpl implements SelectionModel, PrioritizedDocumentLi @Override public void documentChanged(DocumentEvent event) { if (myEditor.getDocument().isInBulkUpdate()) return; - myEditor.getCaretModel().doWithCaretMerging(new Runnable() { - public void run() { - for (Caret caret : myEditor.getCaretModel().getAllCarets()) { - ((CaretImpl)caret).documentChanged(); - } + myEditor.getCaretModel().doWithCaretMerging(() -> { + for (Caret caret : myEditor.getCaretModel().getAllCarets()) { + ((CaretImpl)caret).documentChanged(); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SettingsImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SettingsImpl.java index 899cb32b2577..258bdd1ba0cc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/SettingsImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/SettingsImpl.java @@ -350,12 +350,8 @@ public class SettingsImpl implements EditorSettings { CommonCodeStyleSettings.IndentOptions options = settings.getIndentOptionsByFile(file); if (CodeStyleSettings.isRecalculateForCommittedDocument(options)) { - PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() { - @Override - public void run() { - CodeStyleSettingsManager.updateDocumentIndentOptions(project, document); - } - }); + PsiDocumentManager.getInstance(project).performForCommittedDocument(document, + () -> CodeStyleSettingsManager.updateDocumentIndentOptions(project, document)); } else { CodeStyleSettingsManager.updateDocumentIndentOptions(project, document); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/TrailingSpacesStripper.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/TrailingSpacesStripper.java index c2a157ade4e4..df561d0185eb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/TrailingSpacesStripper.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/TrailingSpacesStripper.java @@ -95,15 +95,12 @@ public final class TrailingSpacesStripper extends FileDocumentManagerAdapter { ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, null) { @Override public void run() { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - if (CharArrayUtil.containsOnlyWhiteSpaces(content.subSequence(start, end)) && doStrip) { - document.deleteString(start, end); - } - else { - document.insertString(end, "\n"); - } + CommandProcessor.getInstance().runUndoTransparentAction(() -> { + if (CharArrayUtil.containsOnlyWhiteSpaces(content.subSequence(start, end)) && doStrip) { + document.deleteString(start, end); + } + else { + document.insertString(end, "\n"); } }); } @@ -187,14 +184,11 @@ public final class TrailingSpacesStripper extends FileDocumentManagerAdapter { inChangedLinesOnly, isVirtualSpaceEnabled, caretOffsets); if (activeEditor != null && !ShutDownTracker.isShutdownHookRunning()) { - activeEditor.getCaretModel().runBatchCaretOperation(new Runnable() { - @Override - public void run() { - for (int i = 0; i < carets.size(); i++) { - Caret caret = carets.get(i); - if (caret.isValid()) { - caret.moveToVisualPosition(visualCarets.get(i)); - } + activeEditor.getCaretModel().runBatchCaretOperation(() -> { + for (int i = 0; i < carets.size(); i++) { + Caret caret = carets.get(i); + if (caret.isValid()) { + caret.moveToVisualPosition(visualCarets.get(i)); } } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapper.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapper.java index 7ff3dd7e2808..1c36d82dd316 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapper.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapper.java @@ -138,23 +138,20 @@ public class CachingSoftWrapDataMapper implements SoftWrapAwareDocumentParsingLi newSoftWrap.getEnd() - lengthDiff), newSoftWrap.getIndentInColumns(), newSoftWrap.getIndentInPixels()), - new Comparator() { - @Override - public int compare(SoftWrapImpl o1, SoftWrapImpl o2) { - int offsetDiff = o1.getStart() - o2.getStart(); - if (offsetDiff != 0) { - return offsetDiff; - } - int textDiff = o1.getText().toString().compareTo(o2.getText().toString()); - if (textDiff != 0) { - return textDiff; - } - int colIndentDiff = o1.getIndentInColumns() - o2.getIndentInColumns(); - if (colIndentDiff != 0) { - return colIndentDiff; - } - return o1.getIndentInPixels() - o2.getIndentInPixels(); + (o1, o2) -> { + int offsetDiff = o1.getStart() - o2.getStart(); + if (offsetDiff != 0) { + return offsetDiff; } + int textDiff = o1.getText().toString().compareTo(o2.getText().toString()); + if (textDiff != 0) { + return textDiff; + } + int colIndentDiff = o1.getIndentInColumns() - o2.getIndentInColumns(); + if (colIndentDiff != 0) { + return colIndentDiff; + } + return o1.getIndentInPixels() - o2.getIndentInPixels(); }) >= 0; } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorPainter.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorPainter.java index db6cabc2ffdb..5083126add33 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorPainter.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorPainter.java @@ -279,15 +279,12 @@ class EditorPainter implements TextDrawingCallback { } private void paintCustomRenderers(final Graphics2D g, final int startOffset, final int endOffset) { - myEditor.getMarkupModel().processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(RangeHighlighterEx highlighter) { - CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer(); - if (customRenderer != null && startOffset < highlighter.getEndOffset() && highlighter.getStartOffset() < endOffset) { - customRenderer.paint(myEditor, highlighter, g); - } - return true; + myEditor.getMarkupModel().processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> { + CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer(); + if (customRenderer != null && startOffset < highlighter.getEndOffset() && highlighter.getStartOffset() < endOffset) { + customRenderer.paint(myEditor, highlighter, g); } + return true; }); } @@ -296,12 +293,9 @@ class EditorPainter implements TextDrawingCallback { MarkupModelEx markupModel, int startOffset, int endOffset) { - markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(RangeHighlighterEx highlighter) { - paintLineMarkerSeparator(highlighter, clip, g); - return true; - } + markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> { + paintLineMarkerSeparator(highlighter, clip, g); + return true; }); } @@ -526,14 +520,11 @@ class EditorPainter implements TextDrawingCallback { MarkupModelEx markupModel, final int startOffset, int endOffset) { - markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { - @Override - public boolean process(RangeHighlighterEx highlighter) { - if (highlighter.getStartOffset() >= startOffset) { - paintHighlighterAfterEndOfLine(g, highlighter); - } - return true; + markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> { + if (highlighter.getStartOffset() >= startOffset) { + paintHighlighterAfterEndOfLine(g, highlighter); } + return true; }); } @@ -575,16 +566,13 @@ class EditorPainter implements TextDrawingCallback { MarkupModelEx markupModel, int clipStartOffset, int clipEndOffset) { - markupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, new Processor() { - @Override - public boolean process(RangeHighlighterEx rangeHighlighter) { - TextAttributes attributes = rangeHighlighter.getTextAttributes(); - if (isBorder(attributes)) { - paintBorderEffect(g, clipDetector, rangeHighlighter.getAffectedAreaStartOffset(), rangeHighlighter.getAffectedAreaEndOffset(), - attributes); - } - return true; + markupModel.processRangeHighlightersOverlappingWith(clipStartOffset, clipEndOffset, rangeHighlighter -> { + TextAttributes attributes = rangeHighlighter.getTextAttributes(); + if (isBorder(attributes)) { + paintBorderEffect(g, clipDetector, rangeHighlighter.getAffectedAreaStartOffset(), rangeHighlighter.getAffectedAreaEndOffset(), + attributes); } + return true; }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorSizeManager.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorSizeManager.java index 01a8f98b5124..e62031c00d39 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorSizeManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/EditorSizeManager.java @@ -248,12 +248,7 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold int width = myLineWidths.get(visualLine); if (width == UNKNOWN_WIDTH) { final Ref approximateValue = new Ref(Boolean.FALSE); - width = getVisualLineWidth(iterator, new Runnable() { - @Override - public void run() { - approximateValue.set(Boolean.TRUE); - } - }); + width = getVisualLineWidth(iterator, () -> approximateValue.set(Boolean.TRUE)); if (approximateValue.get()) width = -width; myLineWidths.set(visualLine, width); } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/IterationState.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/IterationState.java index c734b1b669cb..46282c539f76 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/IterationState.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/view/IterationState.java @@ -47,49 +47,42 @@ import java.util.List; public class IterationState { private static final Logger LOG = Logger.getInstance(IterationState.class); - private static final Comparator BY_LAYER_THEN_ATTRIBUTES = new Comparator() { - @Override - public int compare(RangeHighlighterEx o1, RangeHighlighterEx o2) { - final int result = LayerComparator.INSTANCE.compare(o1, o2); - if (result != 0) { - return result; - } - - // There is a possible case when more than one highlighter target the same region (e.g. 'identifier under caret' and 'identifier'). - // We want to prefer the one that defines foreground color to the one that doesn't define (has either fore- or background colors - // while the other one has only foreground color). See IDEA-85697 for concrete example. - final TextAttributes a1 = o1.getTextAttributes(); - final TextAttributes a2 = o2.getTextAttributes(); - if (a1 == null ^ a2 == null) { - return a1 == null ? 1 : -1; - } - - if (a1 == null) { - return result; - } - - final Color fore1 = a1.getForegroundColor(); - final Color fore2 = a2.getForegroundColor(); - if (fore1 == null ^ fore2 == null) { - return fore1 == null ? 1 : -1; - } - - final Color back1 = a1.getBackgroundColor(); - final Color back2 = a2.getBackgroundColor(); - if (back1 == null ^ back2 == null) { - return back1 == null ? 1 : -1; - } - + private static final Comparator BY_LAYER_THEN_ATTRIBUTES = (o1, o2) -> { + final int result = LayerComparator.INSTANCE.compare(o1, o2); + if (result != 0) { return result; } + + // There is a possible case when more than one highlighter target the same region (e.g. 'identifier under caret' and 'identifier'). + // We want to prefer the one that defines foreground color to the one that doesn't define (has either fore- or background colors + // while the other one has only foreground color). See IDEA-85697 for concrete example. + final TextAttributes a1 = o1.getTextAttributes(); + final TextAttributes a2 = o2.getTextAttributes(); + if (a1 == null ^ a2 == null) { + return a1 == null ? 1 : -1; + } + + if (a1 == null) { + return result; + } + + final Color fore1 = a1.getForegroundColor(); + final Color fore2 = a2.getForegroundColor(); + if (fore1 == null ^ fore2 == null) { + return fore1 == null ? 1 : -1; + } + + final Color back1 = a1.getBackgroundColor(); + final Color back2 = a2.getBackgroundColor(); + if (back1 == null ^ back2 == null) { + return back1 == null ? 1 : -1; + } + + return result; }; - private static final Comparator BY_AFFECTED_END_OFFSET_REVERSED = new Comparator() { - @Override - public int compare(RangeHighlighterEx r1, RangeHighlighterEx r2) { - return r2.getAffectedAreaEndOffset() - r1.getAffectedAreaEndOffset(); - } - }; + private static final Comparator BY_AFFECTED_END_OFFSET_REVERSED = + (r1, r2) -> r2.getAffectedAreaEndOffset() - r1.getAffectedAreaEndOffset(); private final TextAttributes myMergedAttributes = new TextAttributes(); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoDesktopDirAction.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoDesktopDirAction.java index 238b78a31565..48255b60a166 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoDesktopDirAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoDesktopDirAction.java @@ -41,11 +41,8 @@ public class GotoDesktopDirAction extends FileChooserAction { protected void actionPerformed(final FileSystemTree tree, AnActionEvent e) { final VirtualFile dir = myDesktopDirectory.getValue(); if (dir != null) { - tree.select(dir, new Runnable() { - @Override - public void run() { - tree.expand(dir, null); - } + tree.select(dir, () -> { + tree.expand(dir, null); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoHomeAction.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoHomeAction.java index 55f0680f4e84..3363b2ba2823 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoHomeAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoHomeAction.java @@ -28,10 +28,8 @@ public final class GotoHomeAction extends FileChooserAction { protected void actionPerformed(final FileSystemTree fileSystemTree, final AnActionEvent e) { final VirtualFile userHomeDir = VfsUtil.getUserHomeDir(); if (userHomeDir != null) { - fileSystemTree.select(userHomeDir, new Runnable() { - public void run() { - fileSystemTree.expand(userHomeDir, null); - } + fileSystemTree.select(userHomeDir, () -> { + fileSystemTree.expand(userHomeDir, null); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoProjectDirectory.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoProjectDirectory.java index 68b2c0962705..bb4d4eb0ec31 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoProjectDirectory.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/actions/GotoProjectDirectory.java @@ -36,10 +36,8 @@ public final class GotoProjectDirectory extends FileChooserAction { protected void actionPerformed(final FileSystemTree fileSystemTree, final AnActionEvent e) { final VirtualFile projectPath = getProjectDir(e); if (projectPath != null) { - fileSystemTree.select(projectPath, new Runnable() { - public void run() { - fileSystemTree.expand(projectPath, null); - } + fileSystemTree.select(projectPath, () -> { + fileSystemTree.expand(projectPath, null); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java index a2b6dba33a61..edc19252cf4d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileChooserDialogImpl.java @@ -172,18 +172,16 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD final VirtualFile file = FileChooserUtil.getFileToSelect(myChooserDescriptor, myProject, toSelect, lastOpenedFile); if (file != null && file.isValid()) { - myFileSystemTree.select(file, new Runnable() { - public void run() { - if (!file.equals(myFileSystemTree.getSelectedFile())) { - VirtualFile parent = file.getParent(); - if (parent != null) { - myFileSystemTree.select(parent, null); - } - } - else if (file.isDirectory()) { - myFileSystemTree.expand(file, null); + myFileSystemTree.select(file, () -> { + if (!file.equals(myFileSystemTree.getSelectedFile())) { + VirtualFile parent = file.getParent(); + if (parent != null) { + myFileSystemTree.select(parent, null); } } + else if (file.isDirectory()) { + myFileSystemTree.expand(file, null); + } }); } } @@ -265,12 +263,8 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD }); JBPopupFactory.getInstance() .createListPopupBuilder(files) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - myPathTextField.getField().setText(files.getSelectedValue().toString()); - } - }).createPopup().showUnderneathOf(myPathTextField.getField()); + .setItemChoosenCallback( + () -> myPathTextField.getField().setText(files.getSelectedValue().toString())).createPopup().showUnderneathOf(myPathTextField.getField()); } @@ -367,12 +361,8 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD .subscribe(ApplicationActivationListener.TOPIC, new ApplicationActivationListener.Adapter() { @Override public void applicationActivated(IdeFrame ideFrame) { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - ((SaveAndSyncHandlerImpl)SaveAndSyncHandler.getInstance()).maybeRefresh(ModalityState.current()); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, + () -> ((SaveAndSyncHandlerImpl)SaveAndSyncHandler.getInstance()).maybeRefresh(ModalityState.current())); } }); @@ -450,11 +440,7 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD internalTree.setShowsRootHandles(true); Disposer.register(myDisposable, myFileSystemTree); - myFileSystemTree.addOkAction(new Runnable() { - public void run() { - doOKAction(); - } - }); + myFileSystemTree.addOkAction(() -> doOKAction()); JTree tree = myFileSystemTree.getTree(); tree.setCellRenderer(new NodeRenderer()); tree.getSelectionModel().addTreeSelectionListener(new FileTreeSelectionListener()); @@ -677,11 +663,9 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD } } - myPathTextField.setText(text, now, new Runnable() { - public void run() { - myPathTextField.getField().selectAll(); - setErrorText(null); - } + myPathTextField.setText(text, now, () -> { + myPathTextField.getField().selectAll(); + setErrorText(null); }); } @@ -692,17 +676,15 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD myUiUpdater.queue(new Update("treeFromPath.1") { public void run() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - final LocalFsFinder.VfsFile toFind = (LocalFsFinder.VfsFile)myPathTextField.getFile(); - if (toFind == null || !toFind.exists()) return; + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final LocalFsFinder.VfsFile toFind = (LocalFsFinder.VfsFile)myPathTextField.getFile(); + if (toFind == null || !toFind.exists()) return; - myUiUpdater.queue(new Update("treeFromPath.2") { - public void run() { - selectInTree(toFind.getFile(), text); - } - }); - } + myUiUpdater.queue(new Update("treeFromPath.2") { + public void run() { + selectInTree(toFind.getFile(), text); + } + }); }); } }); @@ -723,24 +705,18 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD myTreeIsUpdating = true; final List fileList = Arrays.asList(array); if (!Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) { - myFileSystemTree.select(array, new Runnable() { - public void run() { - if (!myFileSystemTree.areHiddensShown() && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) { - myFileSystemTree.showHiddens(true); - selectInTree(array, requestFocus); - return; - } + myFileSystemTree.select(array, () -> { + if (!myFileSystemTree.areHiddensShown() && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) { + myFileSystemTree.showHiddens(true); + selectInTree(array, requestFocus); + return; + } - myTreeIsUpdating = false; - setErrorText(null); - if (requestFocus) { - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - myFileSystemTree.getTree().requestFocus(); - } - }); - } + myTreeIsUpdating = false; + setErrorText(null); + if (requestFocus) { + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> myFileSystemTree.getTree().requestFocus()); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileSystemTreeImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileSystemTreeImpl.java index 20e79659fb14..3a27be3c7d4f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileSystemTreeImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileSystemTreeImpl.java @@ -102,12 +102,10 @@ public class FileSystemTreeImpl implements FileSystemTree { myTree.addTreeExpansionListener(myExpansionListener); - myTreeBuilder = createTreeBuilder(myTree, treeModel, myTreeStructure, FileComparator.getInstance(), descriptor, new Runnable() { - public void run() { - myTree.expandPath(new TreePath(treeModel.getRoot())); - if (onInitialized != null) { - onInitialized.run(); - } + myTreeBuilder = createTreeBuilder(myTree, treeModel, myTreeStructure, FileComparator.getInstance(), descriptor, () -> { + myTree.expandPath(new TreePath(treeModel.getRoot())); + if (onInitialized != null) { + onInitialized.run(); } }); @@ -366,12 +364,9 @@ public class FileSystemTreeImpl implements FileSystemTree { @NotNull public VirtualFile[] getSelectedFiles() { - final List files = collectSelectedElements(new NullableFunction() { - @Override - public VirtualFile fun(final FileElement element) { - final VirtualFile file = element.getFile(); - return file != null && file.isValid() ? file : null; - } + final List files = collectSelectedElements((NullableFunction)element -> { + final VirtualFile file = element.getFile(); + return file != null && file.isValid() ? file : null; }); return VfsUtilCore.toVirtualFileArray(files); } @@ -473,15 +468,12 @@ public class FileSystemTreeImpl implements FileSystemTree { AbstractTreeStructure treeStructure = myTreeBuilder.getTreeStructure(); final boolean async = treeStructure != null && treeStructure.isToBuildChildrenInBackground(virtualFile); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - if (virtualFile instanceof NewVirtualFile) { - RefreshQueue.getInstance().refresh(async, false, null, ModalityState.stateForComponent(myTree), virtualFile); - } - else { - virtualFile.refresh(async, false); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> { + if (virtualFile instanceof NewVirtualFile) { + RefreshQueue.getInstance().refresh(async, false, null, ModalityState.stateForComponent(myTree), virtualFile); + } + else { + virtualFile.refresh(async, false); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileTextFieldImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileTextFieldImpl.java index cda2aa936254..bb81ce40c4dd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileTextFieldImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/FileTextFieldImpl.java @@ -211,19 +211,15 @@ public abstract class FileTextFieldImpl implements FileLookup, Disposable, FileT result.myCompletionBase = completionBase; if (result.myCompletionBase == null) return; result.myFieldText = myPathTextField.getText(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - processCompletion(result); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (!result.myCompletionBase.equals(getCompletionBase())) return; + ApplicationManager.getApplication().executeOnPooledThread(() -> { + processCompletion(result); + SwingUtilities.invokeLater(() -> { + if (!result.myCompletionBase.equals(getCompletionBase())) return; - int pos = selectCompletionRemoveText(result, selectReplacedText); + int pos = selectCompletionRemoveText(result, selectReplacedText); - showCompletionPopup(result, pos, isExplicitCall); - } - }); - } + showCompletionPopup(result, pos, isExplicitCall); + }); }); } }); @@ -388,18 +384,10 @@ public abstract class FileTextFieldImpl implements FileLookup, Disposable, FileT myPathTextField.setSelectionStart(caret); myPathTextField.setSelectionEnd(caret); myPathTextField.setFocusTraversalKeysEnabled(true); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - getField().requestFocus(); - } - }); + SwingUtilities.invokeLater(() -> getField().requestFocus()); return Boolean.TRUE; } - }).setItemChoosenCallback(new Runnable() { - public void run() { - processChosenFromCompletion(false); - } - }).setCancelKeyEnabled(false).setAlpha(0.1f).setFocusOwners(new Component[]{myPathTextField}). + }).setItemChoosenCallback(() -> processChosenFromCompletion(false)).setCancelKeyEnabled(false).setAlpha(0.1f).setFocusOwners(new Component[]{myPathTextField}). createPopup(); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java index c02c77b83469..c779fc820729 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/LocalFsFinder.java @@ -154,11 +154,7 @@ public class LocalFsFinder implements FileLookup.Finder, FileLookup { result.add(eachFile); } } - Collections.sort(result, new Comparator() { - public int compare(LookupFile o1, LookupFile o2) { - return FileUtil.comparePaths(o1.getName(), o2.getName()); - } - }); + Collections.sort(result, (o1, o2) -> FileUtil.comparePaths(o1.getName(), o2.getName())); return result; } @@ -218,21 +214,15 @@ public class LocalFsFinder implements FileLookup.Finder, FileLookup { public List getChildren(final LookupFilter filter) { List result = new ArrayList(); - File[] files = myIoFile.listFiles(new FileFilter() { - public boolean accept(final File pathname) { - return filter.isAccepted(new IoFile(pathname)); - } + File[] files = myIoFile.listFiles(pathname -> { + return filter.isAccepted(new IoFile(pathname)); }); if (files == null) return result; for (File each : files) { result.add(new IoFile(each)); } - Collections.sort(result, new Comparator() { - public int compare(LookupFile o1, LookupFile o2) { - return FileUtil.comparePaths(o1.getName(), o2.getName()); - } - }); + Collections.sort(result, (o1, o2) -> FileUtil.comparePaths(o1.getName(), o2.getName())); return result; } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileChooserUtil.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileChooserUtil.java index 1f1ebf363f9a..cc2295396d11 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileChooserUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileChooserUtil.java @@ -90,11 +90,6 @@ public final class FileChooserUtil { @NotNull public static List getChosenFiles(@NotNull final FileChooserDescriptor descriptor, @NotNull final List selectedFiles) { - return ContainerUtil.mapNotNull(selectedFiles, new NullableFunction() { - @Override - public VirtualFile fun(final VirtualFile file) { - return file != null && file.isValid() ? descriptor.getFileToSelect(file) : null; - } - }); + return ContainerUtil.mapNotNull(selectedFiles, (NullableFunction)file -> file != null && file.isValid() ? descriptor.getFileToSelect(file) : null); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorComposite.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorComposite.java index c8d01d02a17b..87f8aeb222e2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorComposite.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorComposite.java @@ -139,16 +139,13 @@ public abstract class EditorComposite implements Disposable { final VirtualFile oldFile = event.getOldFile(); final VirtualFile newFile = event.getNewFile(); if (Comparing.equal(oldFile, newFile) && Comparing.equal(getFile(), newFile)) { - Runnable runnable = new Runnable() { - @Override - public void run() { - final FileEditor oldEditor = event.getOldEditor(); - if (oldEditor != null) oldEditor.deselectNotify(); - final FileEditor newEditor = event.getNewEditor(); - if (newEditor != null) newEditor.selectNotify(); - ((FileEditorProviderManagerImpl)FileEditorProviderManager.getInstance()).providerSelected(EditorComposite.this); - ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myFileEditorManager.getProject())).onSelectionChanged(); - } + Runnable runnable = () -> { + final FileEditor oldEditor = event.getOldEditor(); + if (oldEditor != null) oldEditor.deselectNotify(); + final FileEditor newEditor = event.getNewEditor(); + if (newEditor != null) newEditor.selectNotify(); + ((FileEditorProviderManagerImpl)FileEditorProviderManager.getInstance()).providerSelected(EditorComposite.this); + ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myFileEditorManager.getProject())).onSelectionChanged(); }; if (ApplicationManager.getApplication().isDispatchThread()) { CommandProcessor.getInstance().executeCommand(myFileEditorManager.getProject(), runnable, "Switch Active Editor", null); @@ -221,13 +218,10 @@ public abstract class EditorComposite implements Disposable { private void fireSelectedEditorChanged(final FileEditor oldSelectedEditor, final FileEditor newSelectedEditor){ if ((!EventQueue.isDispatchThread() || !myFileEditorManager.isInsideChange()) && !Comparing.equal(oldSelectedEditor, newSelectedEditor)) { - myFileEditorManager.notifyPublisher(new Runnable() { - @Override - public void run() { - final FileEditorManagerEvent event = new FileEditorManagerEvent(myFileEditorManager, myFile, oldSelectedEditor, myFile, newSelectedEditor); - final FileEditorManagerListener publisher = myFileEditorManager.getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); - publisher.selectionChanged(event); - } + myFileEditorManager.notifyPublisher(() -> { + final FileEditorManagerEvent event = new FileEditorManagerEvent(myFileEditorManager, myFile, oldSelectedEditor, myFile, newSelectedEditor); + final FileEditorManagerListener publisher = myFileEditorManager.getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); + publisher.selectionChanged(event); }); final JComponent component = newSelectedEditor.getComponent(); final EditorWindowHolder holder = UIUtil.getParentOfType(EditorWindowHolder.class, component); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorEmptyTextPainter.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorEmptyTextPainter.java index b1bc24c5e0a8..09af707f60cf 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorEmptyTextPainter.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorEmptyTextPainter.java @@ -48,14 +48,11 @@ public class EditorEmptyTextPainter { g.setFont(JBUI.Fonts.label(16f)); UIUtil.TextPainter painter = new UIUtil.TextPainter().withLineSpacing(1.8f); advertiseActions(splitters, painter); - painter.draw(g, new PairFunction>() { - @Override - public Couple fun(Integer width, Integer height) { - Dimension s = splitters.getSize(); - int w = (s.width - width) / 2; - int h = (int)(s.height * heightRatio()); - return Couple.of(w, h); - } + painter.draw(g, (width, height) -> { + Dimension s = splitters.getSize(); + int w = (s.width - width) / 2; + int h = (int)(s.height * heightRatio()); + return Couple.of(w, h); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java index 7b0c9708a7a4..be146f687077 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java @@ -378,12 +378,9 @@ public final class EditorHistoryManager implements PersistentStateComponent { + updateHistoryEntry(event.getOldFile(), event.getOldEditor(), event.getOldProvider(), false); + updateHistoryEntry(event.getNewFile(), true); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java index a87a444cd8de..d0c88d444110 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java @@ -136,12 +136,9 @@ public final class EditorTabbedContainer implements Disposable, CloseAction.Clos @Override public ActionCallback execute(TabInfo info, boolean requestFocus, @NotNull final ActiveRunnable doChangeSelection) { final ActionCallback result = new ActionCallback(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); - result.notify(doChangeSelection.run()); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); + result.notify(doChangeSelection.run()); }, "EditorChange", null); return result; } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWindow.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWindow.java index cbc8a0f1fb62..d9ce7edb271b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWindow.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWindow.java @@ -285,15 +285,12 @@ public class EditorWindow { finally { editorManager.removeSelectionRecord(file, EditorWindow.this); - editorManager.notifyPublisher(new Runnable() { - @Override - public void run() { - final Project project = editorManager.getProject(); - if (!project.isDisposed()) { - final FileEditorManagerListener afterPublisher = - project.getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); - afterPublisher.fileClosed(editorManager, file); - } + editorManager.notifyPublisher(() -> { + final Project project = editorManager.getProject(); + if (!project.isDisposed()) { + final FileEditorManagerListener afterPublisher = + project.getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER); + afterPublisher.fileClosed(editorManager, file); } }); @@ -531,14 +528,11 @@ public class EditorWindow { addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!TComp.this.hasFocus()) return; - final JComponent focus = myEditor.getSelectedEditorWithProvider().getFirst().getPreferredFocusedComponent(); - if (focus != null && !focus.hasFocus()) { - IdeFocusManager.getGlobalInstance().requestFocus(focus, true); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!TComp.this.hasFocus()) return; + final JComponent focus = myEditor.getSelectedEditorWithProvider().getFirst().getPreferredFocusedComponent(); + if (focus != null && !focus.hasFocus()) { + IdeFocusManager.getGlobalInstance().requestFocus(focus, true); } }); } @@ -635,12 +629,9 @@ public class EditorWindow { if (editor != null) { final int index = findFileIndex(editor.getFile()); if (index != -1) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myTabbedPane != null) { - myTabbedPane.setSelectedIndex(index, focusEditor); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myTabbedPane != null) { + myTabbedPane.setSelectedIndex(index, focusEditor); } }); } @@ -825,12 +816,9 @@ public class EditorWindow { final ScrollingModel scrollingModel = editor.getScrollingModel(); scrollingModel.scrollVertically(scrollOffset); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!editor.isDisposed()) { - scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE); - } + SwingUtilities.invokeLater(() -> { + if (!editor.isDisposed()) { + scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE); } }); } @@ -1081,18 +1069,15 @@ public class EditorWindow { void trimToSize(final int limit, @Nullable final VirtualFile fileToIgnore, final boolean transferFocus) { if (myTabbedPane == null) return; - FileEditorManagerEx.getInstanceEx(getManager().getProject()).getReady(this).doWhenDone(new Runnable() { - @Override - public void run() { - if (myTabbedPane == null) return; - final boolean closeNonModifiedFilesFirst = UISettings.getInstance().CLOSE_NON_MODIFIED_FILES_FIRST; - final EditorComposite selectedComposite = getSelectedEditor(); - try { - doTrimSize(limit, fileToIgnore, closeNonModifiedFilesFirst, transferFocus); - } - finally { - setSelectedEditor(selectedComposite, false); - } + FileEditorManagerEx.getInstanceEx(getManager().getProject()).getReady(this).doWhenDone(() -> { + if (myTabbedPane == null) return; + final boolean closeNonModifiedFilesFirst = UISettings.getInstance().CLOSE_NON_MODIFIED_FILES_FIRST; + final EditorComposite selectedComposite = getSelectedEditor(); + try { + doTrimSize(limit, fileToIgnore, closeNonModifiedFilesFirst, transferFocus); + } + finally { + setSelectedEditor(selectedComposite, false); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java index 4c375399c102..2373cb8f1940 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java @@ -369,15 +369,12 @@ public class EditorsSplitters extends IdePanePanel implements UISettingsListener private void updateFileIconLater(VirtualFile file) { myFilesToUpdateIconsFor.add(file); myIconUpdaterAlarm.cancelAllRequests(); - myIconUpdaterAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myManager.getProject().isDisposed()) return; - for (VirtualFile file : myFilesToUpdateIconsFor) { - updateFileIconImmediately(file); - } - myFilesToUpdateIconsFor.clear(); + myIconUpdaterAlarm.addRequest(() -> { + if (myManager.getProject().isDisposed()) return; + for (VirtualFile file1 : myFilesToUpdateIconsFor) { + updateFileIconImmediately(file1); } + myFilesToUpdateIconsFor.clear(); }, 200, ModalityState.stateForComponent(this)); } @@ -621,12 +618,7 @@ public class EditorsSplitters extends IdePanePanel implements UISettingsListener void setCurrentWindow(@Nullable final EditorWindow window, final boolean requestFocus) { final EditorWithProviderComposite newEditor = window == null ? null : window.getSelectedEditor(); - Runnable fireRunnable = new Runnable() { - @Override - public void run() { - getManager().fireSelectionChanged(newEditor); - } - }; + Runnable fireRunnable = () -> getManager().fireSelectionChanged(newEditor); setCurrentWindow(window); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java index a926abf28bee..6722933c245d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java @@ -270,22 +270,19 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt private void saveAllDocumentsLater() { // later because some document might have been blocked by PSI right now - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (ApplicationManager.getApplication().isDisposed()) { - return; - } - final Document[] unsavedDocuments = getUnsavedDocuments(); - for (Document document : unsavedDocuments) { - VirtualFile file = getFile(document); - if (file == null) continue; - Project project = ProjectUtil.guessProjectForFile(file); - if (project == null) continue; - if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue; + ApplicationManager.getApplication().invokeLater(() -> { + if (ApplicationManager.getApplication().isDisposed()) { + return; + } + final Document[] unsavedDocuments = getUnsavedDocuments(); + for (Document document : unsavedDocuments) { + VirtualFile file = getFile(document); + if (file == null) continue; + Project project = ProjectUtil.guessProjectForFile(file); + if (project == null) continue; + if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue; - saveDocument(document); - } + saveDocument(document); } }); } @@ -422,25 +419,22 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt return; } - PomModelImpl.guardPsiModificationsIn(new ThrowableRunnable() { - @Override - public void run() throws IOException { - myMultiCaster.beforeDocumentSaving(document); - LOG.assertTrue(file.isValid()); + PomModelImpl.guardPsiModificationsIn(() -> { + myMultiCaster.beforeDocumentSaving(document); + LOG.assertTrue(file.isValid()); - String text = document.getText(); - String lineSeparator = getLineSeparator(document, file); - if (!lineSeparator.equals("\n")) { - text = StringUtil.convertLineSeparators(text, lineSeparator); - } - - Project project = ProjectLocator.getInstance().guessProjectForFile(file); - LoadTextUtil.write(project, file, FileDocumentManagerImpl.this, text, document.getModificationStamp()); - - myUnsavedDocuments.remove(document); - LOG.assertTrue(!myUnsavedDocuments.contains(document)); - myTrailingSpacesStripper.clearLineModificationFlags(document); + String text = document.getText(); + String lineSeparator = getLineSeparator(document, file); + if (!lineSeparator.equals("\n")) { + text = StringUtil.convertLineSeparators(text, lineSeparator); } + + Project project = ProjectLocator.getInstance().guessProjectForFile(file); + LoadTextUtil.write(project, file, FileDocumentManagerImpl.this, text, document.getModificationStamp()); + + myUnsavedDocuments.remove(document); + LOG.assertTrue(!myUnsavedDocuments.contains(document)); + myTrailingSpacesStripper.clearLineModificationFlags(document); }); } @@ -637,26 +631,23 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt } final Project project = ProjectLocator.getInstance().guessProjectForFile(file); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction( - new ExternalChangeAction.ExternalDocumentChange(document, project) { - @Override - public void run() { - boolean wasWritable = document.isWritable(); - DocumentEx documentEx = (DocumentEx)document; - documentEx.setReadOnly(false); - LoadTextUtil.setCharsetWasDetectedFromBytes(file, null); - file.setBOM(null); // reset BOM in case we had one and the external change stripped it away - if (!isBinaryWithoutDecompiler(file)) { - documentEx.replaceText(LoadTextUtil.loadText(file), file.getModificationStamp()); - documentEx.setReadOnly(!wasWritable); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + ApplicationManager.getApplication().runWriteAction( + new ExternalChangeAction.ExternalDocumentChange(document, project) { + @Override + public void run() { + boolean wasWritable = document.isWritable(); + DocumentEx documentEx = (DocumentEx)document; + documentEx.setReadOnly(false); + LoadTextUtil.setCharsetWasDetectedFromBytes(file, null); + file.setBOM(null); // reset BOM in case we had one and the external change stripped it away + if (!isBinaryWithoutDecompiler(file)) { + documentEx.replaceText(LoadTextUtil.loadText(file), file.getModificationStamp()); + documentEx.setReadOnly(!wasWritable); } } - ); - } + } + ); }, UIBundle.message("file.cache.conflict.action"), null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); myUnsavedDocuments.remove(document); @@ -664,47 +655,44 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt myMultiCaster.fileContentReloaded(file, document); } - private volatile PairProcessor askReloadFromDisk = new PairProcessor() { - @Override - public boolean process(final VirtualFile file, final Document document) { - String message = UIBundle.message("file.cache.conflict.message.text", file.getPresentableUrl()); + private volatile PairProcessor askReloadFromDisk = (file, document) -> { + String message = UIBundle.message("file.cache.conflict.message.text", file.getPresentableUrl()); - final DialogBuilder builder = new DialogBuilder(); - builder.setCenterPanel(new JLabel(message, Messages.getQuestionIcon(), SwingConstants.CENTER)); - builder.addOkAction().setText(UIBundle.message("file.cache.conflict.load.fs.changes.button")); - builder.addCancelAction().setText(UIBundle.message("file.cache.conflict.keep.memory.changes.button")); - builder.addAction(new AbstractAction(UIBundle.message("file.cache.conflict.show.difference.button")) { - @Override - public void actionPerformed(ActionEvent e) { - final ProjectEx project = (ProjectEx)ProjectLocator.getInstance().guessProjectForFile(file); + final DialogBuilder builder = new DialogBuilder(); + builder.setCenterPanel(new JLabel(message, Messages.getQuestionIcon(), SwingConstants.CENTER)); + builder.addOkAction().setText(UIBundle.message("file.cache.conflict.load.fs.changes.button")); + builder.addCancelAction().setText(UIBundle.message("file.cache.conflict.keep.memory.changes.button")); + builder.addAction(new AbstractAction(UIBundle.message("file.cache.conflict.show.difference.button")) { + @Override + public void actionPerformed(ActionEvent e) { + final ProjectEx project = (ProjectEx)ProjectLocator.getInstance().guessProjectForFile(file); - FileType fileType = file.getFileType(); - String fsContent = LoadTextUtil.loadText(file).toString(); - DocumentContent content1 = DiffContentFactory.getInstance().create(fsContent, fileType); - DocumentContent content2 = DiffContentFactory.getInstance().create(project, document, file); - String title = UIBundle.message("file.cache.conflict.for.file.dialog.title", file.getPresentableUrl()); - String title1 = UIBundle.message("file.cache.conflict.diff.content.file.system.content"); - String title2 = UIBundle.message("file.cache.conflict.diff.content.memory.content"); - DiffRequest request = new SimpleDiffRequest(title, content1, content2, title1, title2); - request.putUserData(DiffUserDataKeys.GO_TO_SOURCE_DISABLE, true); - DialogBuilder diffBuilder = new DialogBuilder(project); - DiffRequestPanel diffPanel = DiffManager.getInstance().createRequestPanel(project, diffBuilder, diffBuilder.getWindow()); - diffPanel.setRequest(request); - diffBuilder.setCenterPanel(diffPanel.getComponent()); - diffBuilder.setDimensionServiceKey("FileDocumentManager.FileCacheConflict"); - diffBuilder.addOkAction().setText(UIBundle.message("file.cache.conflict.save.changes.button")); - diffBuilder.addCancelAction(); - diffBuilder.setTitle(title); - if (diffBuilder.show() == DialogWrapper.OK_EXIT_CODE) { - builder.getDialogWrapper().close(DialogWrapper.CANCEL_EXIT_CODE); - } + FileType fileType = file.getFileType(); + String fsContent = LoadTextUtil.loadText(file).toString(); + DocumentContent content1 = DiffContentFactory.getInstance().create(fsContent, fileType); + DocumentContent content2 = DiffContentFactory.getInstance().create(project, document, file); + String title = UIBundle.message("file.cache.conflict.for.file.dialog.title", file.getPresentableUrl()); + String title1 = UIBundle.message("file.cache.conflict.diff.content.file.system.content"); + String title2 = UIBundle.message("file.cache.conflict.diff.content.memory.content"); + DiffRequest request = new SimpleDiffRequest(title, content1, content2, title1, title2); + request.putUserData(DiffUserDataKeys.GO_TO_SOURCE_DISABLE, true); + DialogBuilder diffBuilder = new DialogBuilder(project); + DiffRequestPanel diffPanel = DiffManager.getInstance().createRequestPanel(project, diffBuilder, diffBuilder.getWindow()); + diffPanel.setRequest(request); + diffBuilder.setCenterPanel(diffPanel.getComponent()); + diffBuilder.setDimensionServiceKey("FileDocumentManager.FileCacheConflict"); + diffBuilder.addOkAction().setText(UIBundle.message("file.cache.conflict.save.changes.button")); + diffBuilder.addCancelAction(); + diffBuilder.setTitle(title); + if (diffBuilder.show() == DialogWrapper.OK_EXIT_CODE) { + builder.getDialogWrapper().close(DialogWrapper.CANCEL_EXIT_CODE); } - }); - builder.setTitle(UIBundle.message("file.cache.conflict.dialog.title")); - builder.setButtonsAlignment(SwingConstants.CENTER); - builder.setHelpId("reference.dialogs.fileCacheConflict"); - return builder.show() == 0; - } + } + }); + builder.setTitle(UIBundle.message("file.cache.conflict.dialog.title")); + builder.setButtonsAlignment(SwingConstants.CENTER); + builder.setHelpId("reference.dialogs.fileCacheConflict"); + return builder.show() == 0; }; @TestOnly @@ -841,11 +829,8 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt LOG.warn(exception); } - final String text = StringUtil.join(failures.values(), new Function() { - @Override - public String fun(IOException e) { - return e.getMessage(); - } + final String text = StringUtil.join(failures.values(), e -> { + return e.getMessage(); }, "\n"); final DialogWrapper dialog = new DialogWrapper(null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java index cc69e40fbdd0..7f060b2d7d44 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java @@ -170,12 +170,9 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis @Override public void exitDumbMode() { // can happen under write action, so postpone to avoid deadlock on FileEditorProviderManager.getProviders() - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed()) - dumbModeFinished(myProject); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!myProject.isDisposed()) + dumbModeFinished(myProject); }); } }); @@ -269,35 +266,32 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis final AsyncResult result = new AsyncResult(); final IdeFocusManager fm = IdeFocusManager.getInstance(myProject); - Runnable run = new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) { - result.setRejected(); - return; - } + Runnable run = () -> { + if (myProject.isDisposed()) { + result.setRejected(); + return; + } - Component focusOwner = fm.getFocusOwner(); - if (focusOwner == null && !async) { - focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); - } + Component focusOwner = fm.getFocusOwner(); + if (focusOwner == null && !async) { + focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + } - if (focusOwner == null && !async) { - focusOwner = fm.getLastFocusedFor(fm.getLastFocusedFrame()); - } + if (focusOwner == null && !async) { + focusOwner = fm.getLastFocusedFor(fm.getLastFocusedFrame()); + } - DockContainer container = myDockManager.getContainerFor(focusOwner); - if (container == null && !async) { - focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); - container = myDockManager.getContainerFor(focusOwner); - } + DockContainer container = myDockManager.getContainerFor(focusOwner); + if (container == null && !async) { + focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); + container = myDockManager.getContainerFor(focusOwner); + } - if (container instanceof DockableEditorTabbedContainer) { - result.setDone(((DockableEditorTabbedContainer)container).getSplitters()); - } - else { - result.setDone(getMainSplitters()); - } + if (container instanceof DockableEditorTabbedContainer) { + result.setDone(((DockableEditorTabbedContainer)container).getSplitters()); + } + else { + result.setDone(getMainSplitters()); } }; @@ -606,12 +600,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis @NotNull private AsyncResult _getActiveWindow(boolean now) { - return getActiveSplitters(now).subResult(new Function() { - @Override - public EditorWindow fun(EditorsSplitters splitters) { - return splitters.getCurrentWindow(); - } - }); + return getActiveSplitters(now).subResult(splitters -> splitters.getCurrentWindow()); } @Override @@ -628,12 +617,9 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis assertDispatchThread(); ourOpenFilesSetModificationCount.incrementAndGet(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - if (window.isFileOpen(file)) { - window.closeFile(file, true, transferFocus); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + if (window.isFileOpen(file)) { + window.closeFile(file, true, transferFocus); } }, IdeBundle.message("command.close.active.editor"), null); removeSelectionRecord(file, window); @@ -654,12 +640,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis public void closeFile(@NotNull final VirtualFile file, final boolean moveFocus, final boolean closeAllCopies) { assertDispatchThread(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - closeFileImpl(file, moveFocus, closeAllCopies); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myProject, () -> closeFileImpl(file, moveFocus, closeAllCopies), "", null); } private void closeFileImpl(@NotNull final VirtualFile file, final boolean moveFocus, boolean closeAllCopies) { @@ -786,12 +767,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis @NotNull final VirtualFile file, final boolean focusEditor) { final Ref> result = new Ref>(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - result.set(openFileImpl3(window, file, focusEditor, null, true)); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myProject, () -> result.set(openFileImpl3(window, file, focusEditor, null, true)), "", null); return result.get(); } @@ -875,123 +851,117 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis newProviders = null; builders = null; } - Runnable runnable = new Runnable() { - @Override - public void run() { - if (myProject.isDisposed() || !file.isValid()) { - return; - } - compositeRef.set(window.findFileComposite(file)); - boolean newEditor = compositeRef.isNull(); - if (newEditor) { - clearWindowIfNeeded(window); + Runnable runnable = () -> { + if (myProject.isDisposed() || !file.isValid()) { + return; + } + compositeRef.set(window.findFileComposite(file)); + boolean newEditor = compositeRef.isNull(); + if (newEditor) { + clearWindowIfNeeded(window); - ourOpenFilesSetModificationCount.incrementAndGet(); - getProject().getMessageBus().syncPublisher(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER).beforeFileOpened(FileEditorManagerImpl.this, file); + ourOpenFilesSetModificationCount.incrementAndGet(); + getProject().getMessageBus().syncPublisher(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER).beforeFileOpened(FileEditorManagerImpl.this, file); - FileEditor[] newEditors = new FileEditor[newProviders.length]; - for (int i = 0; i < newProviders.length; i++) { - try { - final FileEditorProvider provider = newProviders[i]; - final FileEditor editor = builders[i] == null ? provider.createEditor(myProject, file) : builders[i].build(); - LOG.assertTrue(editor.isValid(), "Invalid editor created by provider " + - (provider == null ? null : provider.getClass().getName())); - newEditors[i] = editor; - // Register PropertyChangeListener into editor - editor.addPropertyChangeListener(myEditorPropertyChangeListener); - editor.putUserData(DUMB_AWARE, DumbService.isDumbAware(provider)); - } - catch (Exception e) { - LOG.error(e); - } - catch (AssertionError e) { - LOG.error(e); - } + FileEditor[] newEditors = new FileEditor[newProviders.length]; + for (int i = 0; i < newProviders.length; i++) { + try { + final FileEditorProvider provider = newProviders[i]; + final FileEditor editor = builders[i] == null ? provider.createEditor(myProject, file) : builders[i].build(); + LOG.assertTrue(editor.isValid(), "Invalid editor created by provider " + + (provider == null ? null : provider.getClass().getName())); + newEditors[i] = editor; + // Register PropertyChangeListener into editor + editor.addPropertyChangeListener(myEditorPropertyChangeListener); + editor.putUserData(DUMB_AWARE, DumbService.isDumbAware(provider)); } - - // Now we have to create EditorComposite and insert it into the TabbedEditorComponent. - // After that we have to select opened editor. - EditorWithProviderComposite composite = createComposite(file, newEditors, newProviders); - if (composite == null) return; - - if (index >= 0) { - composite.getFile().putUserData(EditorWindow.INITIAL_INDEX_KEY, index); + catch (Exception e) { + LOG.error(e); } - - compositeRef.set(composite); - } - - final EditorWithProviderComposite composite = compositeRef.get(); - FileEditor[] editors = composite.getEditors(); - FileEditorProvider[] providers = composite.getProviders(); - - window.setEditor(composite, current, focusEditor); - - for (int i = 0; i < editors.length; i++) { - restoreEditorState(file, providers[i], editors[i], entry, newEditor); - } - - // Restore selected editor - final FileEditorProvider selectedProvider; - if (entry == null) { - selectedProvider = ((FileEditorProviderManagerImpl)FileEditorProviderManager.getInstance()) - .getSelectedFileEditorProvider(EditorHistoryManager.getInstance(myProject), file, providers); - } - else { - selectedProvider = entry.getSelectedProvider(); - } - if (selectedProvider != null) { - for (int i = editors.length - 1; i >= 0; i--) { - final FileEditorProvider provider = providers[i]; - if (provider.equals(selectedProvider)) { - composite.setSelectedEditor(i); - break; - } + catch (AssertionError e) { + LOG.error(e); } } - // Notify editors about selection changes - window.getOwner().setCurrentWindow(window, focusEditor); - window.getOwner().afterFileOpen(file); - addSelectionRecord(file, window); + // Now we have to create EditorComposite and insert it into the TabbedEditorComponent. + // After that we have to select opened editor. + EditorWithProviderComposite composite = createComposite(file, newEditors, newProviders); + if (composite == null) return; - composite.getSelectedEditor().selectNotify(); + if (index >= 0) { + composite.getFile().putUserData(EditorWindow.INITIAL_INDEX_KEY, index); + } - // Transfer focus into editor - if (!ApplicationManagerEx.getApplicationEx().isUnitTestMode()) { - if (focusEditor) { - //myFirstIsActive = myTabbedContainer1.equals(tabbedContainer); - window.setAsCurrentWindow(true); - ToolWindowManager.getInstance(myProject).activateEditorComponent(); - IdeFocusManager.getInstance(myProject).toFront(window.getOwner()); + compositeRef.set(composite); + } + + final EditorWithProviderComposite composite = compositeRef.get(); + FileEditor[] editors = composite.getEditors(); + FileEditorProvider[] providers = composite.getProviders(); + + window.setEditor(composite, current, focusEditor); + + for (int i = 0; i < editors.length; i++) { + restoreEditorState(file, providers[i], editors[i], entry, newEditor); + } + + // Restore selected editor + final FileEditorProvider selectedProvider; + if (entry == null) { + selectedProvider = ((FileEditorProviderManagerImpl)FileEditorProviderManager.getInstance()) + .getSelectedFileEditorProvider(EditorHistoryManager.getInstance(myProject), file, providers); + } + else { + selectedProvider = entry.getSelectedProvider(); + } + if (selectedProvider != null) { + for (int i = editors.length - 1; i >= 0; i--) { + final FileEditorProvider provider = providers[i]; + if (provider.equals(selectedProvider)) { + composite.setSelectedEditor(i); + break; } } + } - if (newEditor) { - notifyPublisher(new Runnable() { - @Override - public void run() { - if (isFileOpen(file)) { - getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER) - .fileOpened(FileEditorManagerImpl.this, file); - } - } - }); + // Notify editors about selection changes + window.getOwner().setCurrentWindow(window, focusEditor); + window.getOwner().afterFileOpen(file); + addSelectionRecord(file, window); + + composite.getSelectedEditor().selectNotify(); + + // Transfer focus into editor + if (!ApplicationManagerEx.getApplicationEx().isUnitTestMode()) { + if (focusEditor) { + //myFirstIsActive = myTabbedContainer1.equals(tabbedContainer); + window.setAsCurrentWindow(true); + ToolWindowManager.getInstance(myProject).activateEditorComponent(); + IdeFocusManager.getInstance(myProject).toFront(window.getOwner()); } + } - //[jeka] this is a hack to support back-forward navigation - // previously here was incorrect call to fireSelectionChanged() with a side-effect - ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); + if (newEditor) { + notifyPublisher(() -> { + if (isFileOpen(file)) { + getProject().getMessageBus().syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER) + .fileOpened(FileEditorManagerImpl.this, file); + } + }); + } - // Update frame and tab title - updateFileName(file); + //[jeka] this is a hack to support back-forward navigation + // previously here was incorrect call to fireSelectionChanged() with a side-effect + ((IdeDocumentHistoryImpl)IdeDocumentHistory.getInstance(myProject)).onSelectionChanged(); - // Make back/forward work - IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); + // Update frame and tab title + updateFileName(file); - if (pin != null) { - window.setFilePinned(file, pin); - } + // Make back/forward work + IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); + + if (pin != null) { + window.setFilePinned(file, pin); } }; @@ -1073,12 +1043,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis if (state != null) { if (!isDumbAware(editor)) { final FileEditorState finalState = state; - DumbService.getInstance(getProject()).runWhenSmart(new Runnable() { - @Override - public void run() { - editor.setState(finalState); - } - }); + DumbService.getInstance(getProject()).runWhenSmart(() -> editor.setState(finalState)); } else { editor.setState(state); @@ -1178,28 +1143,25 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis } final List result = new SmartList(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - VirtualFile file = descriptor.getFile(); - final FileEditor[] editors = openFile(file, focusEditor, !descriptor.isUseCurrentWindow()); - ContainerUtil.addAll(result, editors); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + VirtualFile file = descriptor.getFile(); + final FileEditor[] editors = openFile(file, focusEditor, !descriptor.isUseCurrentWindow()); + ContainerUtil.addAll(result, editors); - boolean navigated = false; - for (final FileEditor editor : editors) { - if (editor instanceof NavigatableFileEditor && - getSelectedEditor(descriptor.getFile()) == editor) { // try to navigate opened editor - navigated = navigateAndSelectEditor((NavigatableFileEditor)editor, descriptor); - if (navigated) break; - } + boolean navigated = false; + for (final FileEditor editor : editors) { + if (editor instanceof NavigatableFileEditor && + getSelectedEditor(descriptor.getFile()) == editor) { // try to navigate opened editor + navigated = navigateAndSelectEditor((NavigatableFileEditor)editor, descriptor); + if (navigated) break; } + } - if (!navigated) { - for (final FileEditor editor : editors) { - if (editor instanceof NavigatableFileEditor && getSelectedEditor(descriptor.getFile()) != editor) { // try other editors - if (navigateAndSelectEditor((NavigatableFileEditor)editor, descriptor)) { - break; - } + if (!navigated) { + for (final FileEditor editor : editors) { + if (editor instanceof NavigatableFileEditor && getSelectedEditor(descriptor.getFile()) != editor) { // try other editors + if (navigateAndSelectEditor((NavigatableFileEditor)editor, descriptor)) { + break; } } } @@ -1536,29 +1498,18 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis if (myProject.isDisposed()) return; setTabsMode(UISettings.getInstance().EDITOR_TAB_PLACEMENT != UISettings.TABS_NONE); - ToolWindowManager.getInstance(myProject).invokeLater(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { + ToolWindowManager.getInstance(myProject).invokeLater(() -> CommandProcessor.getInstance().executeCommand(myProject, () -> { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - long currentTime = System.nanoTime(); - Long startTime = myProject.getUserData(ProjectImpl.CREATION_TIME); - if (startTime != null) { - LOG.info("Project opening took " + (currentTime - startTime.longValue()) / 1000000 + " ms"); - PluginManagerCore.dumpPluginClassStatistics(); - } - } - }, myProject.getDisposed()); - // group 1 - } - }, "", null); - } - }); + ApplicationManager.getApplication().invokeLater(() -> { + long currentTime = System.nanoTime(); + Long startTime = myProject.getUserData(ProjectImpl.CREATION_TIME); + if (startTime != null) { + LOG.info("Project opening took " + (currentTime - startTime.longValue()) / 1000000 + " ms"); + PluginManagerCore.dumpPluginClassStatistics(); + } + }, myProject.getDisposed()); + // group 1 + }, "", null)); } }); } @@ -1633,12 +1584,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis addSelectionRecord(newData.first, holder.getEditorWindow()); } } - notifyPublisher(new Runnable() { - @Override - public void run() { - publisher.selectionChanged(event); - } - }); + notifyPublisher(() -> publisher.selectionChanged(event)); } } @@ -1852,14 +1798,11 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis for (int i = openFiles.length - 1; i >= 0; i--) { final VirtualFile file = openFiles[i]; LOG.assertTrue(file != null); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (LOG.isDebugEnabled()) { - LOG.debug("updating file status in tab for " + file.getPath()); - } - updateFileStatus(file); + ApplicationManager.getApplication().invokeLater(() -> { + if (LOG.isDebugEnabled()) { + LOG.debug("updating file status in tab for " + file.getPath()); } + updateFileStatus(file); }, ModalityState.NON_MODAL, myProject.getDisposed()); } } @@ -1901,12 +1844,9 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis public void rootsChanged(ModuleRootEvent event) { if (myScheduled) return; myScheduled = true; - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - myScheduled = false; - handleRootChange(); - } + DumbService.getInstance(myProject).runWhenSmart(() -> { + myScheduled = false; + handleRootChange(); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorProviderManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorProviderManagerImpl.java index 1a9327ac4762..e305a1353481 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorProviderManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorProviderManagerImpl.java @@ -151,12 +151,7 @@ public final class FileEditorProviderManagerImpl extends FileEditorProviderManag mySelectedProviders.putAll(state.mySelectedProviders); } - private static final Function EDITOR_PROVIDER_STRING_FUNCTION = new Function() { - @Override - public String fun(FileEditorProvider provider) { - return provider.getEditorTypeId(); - } - }; + private static final Function EDITOR_PROVIDER_STRING_FUNCTION = provider -> provider.getEditorTypeId(); private final Map mySelectedProviders = new HashMap(); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FilePreviewPanelProvider.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FilePreviewPanelProvider.java index ac569d75b691..c9b49cb954e6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FilePreviewPanelProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FilePreviewPanelProvider.java @@ -66,12 +66,7 @@ public class FilePreviewPanelProvider extends PreviewPanelProvider initComponent(VirtualFile file, boolean requestFocus) { Pair result = myManager.openFileWithProviders(file, requestFocus, myWindow); - IdeFocusManager.findInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - myWindow.requestFocus(true); - } - }); + IdeFocusManager.findInstance().doWhenFocusSettlesDown(() -> myWindow.requestFocus(true)); return result; } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java index b6cb1d8f1af0..0fcc45ed39a5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java @@ -335,12 +335,7 @@ public class IdeDocumentHistoryImpl extends IdeDocumentHistory implements Projec myBackInProgress = true; try { - executeCommand(new Runnable() { - @Override - public void run() { - gotoPlaceInfo(info); - } - }, "", null); + executeCommand(() -> gotoPlaceInfo(info), "", null); } finally { myBackInProgress = false; @@ -356,12 +351,7 @@ public class IdeDocumentHistoryImpl extends IdeDocumentHistory implements Projec myForwardInProgress = true; try { - executeCommand(new Runnable() { - @Override - public void run() { - gotoPlaceInfo(target); - } - }, "", null); + executeCommand(() -> gotoPlaceInfo(target), "", null); } finally { myForwardInProgress = false; } @@ -401,12 +391,7 @@ public class IdeDocumentHistoryImpl extends IdeDocumentHistory implements Projec int index = myCurrentIndex - 1; final PlaceInfo info = myChangePlaces.get(index - myStartIndex); - executeCommand(new Runnable() { - @Override - public void run() { - gotoPlaceInfo(info); - } - }, "", null); + executeCommand(() -> gotoPlaceInfo(info), "", null); myCurrentIndex = index; } @@ -431,12 +416,7 @@ public class IdeDocumentHistoryImpl extends IdeDocumentHistory implements Projec int index = myCurrentIndex + 1; final PlaceInfo info = myChangePlaces.get(index - myStartIndex); - executeCommand(new Runnable() { - @Override - public void run() { - gotoPlaceInfo(info); - } - }, "", null); + executeCommand(() -> gotoPlaceInfo(info), "", null); myCurrentIndex = index; } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java index 8ec2cc92b633..80fd36ffae83 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java @@ -48,13 +48,7 @@ public class NonProjectFileWritingAccessProvider extends WritingAccessProvider { private static final Key ENABLE_IN_TESTS = Key.create("NON_PROJECT_FILE_ACCESS_ENABLE_IN_TESTS"); private static final Key ALL_ACCESS_ALLOWED = Key.create("NON_PROJECT_FILE_ALL_ACCESS_STATUS"); private static final NotNullLazyKey, Project> ACCESS_STATUS - = NotNullLazyKey.create("NON_PROJECT_FILE_ACCESS_STATUS", new NotNullFunction>() { - @NotNull - @Override - public Map fun(Project project) { - return new HashMap(); - } - }); + = NotNullLazyKey.create("NON_PROJECT_FILE_ACCESS_STATUS", project -> new HashMap()); @NotNull private final Project myProject; @Nullable private static NullableFunction, UnlockOption> ourCustomUnlocker; diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java index c14a07ccc7a2..9b269ef1518c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java @@ -41,23 +41,10 @@ class HttpFileEditor extends BaseRemoteFileEditor { RemoteFileInfo fileInfo = virtualFile.getFileInfo(); assert fileInfo != null; fileInfo.download() - .done(new Consumer() { - @Override - public void consume(VirtualFile file) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - contentLoaded(); - } - }, myProject.getDisposed()); - } - }) - .rejected(new Consumer() { - @Override - public void consume(Throwable throwable) { - contentRejected(); - } - }); + .done(file -> ApplicationManager.getApplication().invokeLater(() -> { + contentLoaded(); + }, myProject.getDisposed())) + .rejected(throwable -> contentRejected()); } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java index 4bd5549d85ff..35d03e231b23 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java @@ -139,17 +139,14 @@ public class RemoteFilePanel { private void switchEditor() { LOG.debug("Switching editor..."); - AppUIUtil.invokeOnEdt(new Runnable() { - @Override - public void run() { - TextEditor textEditor = (TextEditor)TextEditorProvider.getInstance().createEditor(myProject, myVirtualFile); - textEditor.addPropertyChangeListener(myPropertyChangeListener); - myEditorPanel.removeAll(); - myEditorPanel.add(textEditor.getComponent(), BorderLayout.CENTER); - myFileEditor = textEditor; - showCard(EDITOR_CARD); - LOG.debug("Editor for downloaded file opened."); - } + AppUIUtil.invokeOnEdt(() -> { + TextEditor textEditor = (TextEditor)TextEditorProvider.getInstance().createEditor(myProject, myVirtualFile); + textEditor.addPropertyChangeListener(myPropertyChangeListener); + myEditorPanel.removeAll(); + myEditorPanel.add(textEditor.getComponent(), BorderLayout.CENTER); + myFileEditor = textEditor; + showCard(EDITOR_CARD); + LOG.debug("Editor for downloaded file opened."); }, myProject.getDisposed()); } @@ -163,25 +160,19 @@ public class RemoteFilePanel { } public void selectNotify() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myProgressUpdatesQueue.showNotify(); - if (myFileEditor != null) { - myFileEditor.selectNotify(); - } + UIUtil.invokeLaterIfNeeded(() -> { + myProgressUpdatesQueue.showNotify(); + if (myFileEditor != null) { + myFileEditor.selectNotify(); } }); } public void deselectNotify() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myProgressUpdatesQueue.hideNotify(); - if (myFileEditor != null) { - myFileEditor.deselectNotify(); - } + UIUtil.invokeLaterIfNeeded(() -> { + myProgressUpdatesQueue.hideNotify(); + if (myFileEditor != null) { + myFileEditor.deselectNotify(); } }); } @@ -202,38 +193,27 @@ public class RemoteFilePanel { @Override public void downloadingCancelled() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myFileEditor != null) { - showCard(EDITOR_CARD); - } - else { - myErrorLabel.setText("Downloading cancelled"); - showCard(ERROR_CARD); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myFileEditor != null) { + showCard(EDITOR_CARD); + } + else { + myErrorLabel.setText("Downloading cancelled"); + showCard(ERROR_CARD); } }); } @Override public void downloadingStarted() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showCard(DOWNLOADING_CARD); - } - }); + ApplicationManager.getApplication().invokeLater(() -> showCard(DOWNLOADING_CARD)); } @Override public void errorOccurred(@NotNull final String errorMessage) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myErrorLabel.setText(errorMessage); - showCard(ERROR_CARD); - } + ApplicationManager.getApplication().invokeLater(() -> { + myErrorLabel.setText(errorMessage); + showCard(ERROR_CARD); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorComponent.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorComponent.java index 0bb52db179e3..d298268bc901 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorComponent.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorComponent.java @@ -291,12 +291,9 @@ class TextEditorComponent extends JBLoadingPanel implements DataProvider { private boolean myUpdateScheduled; public MyDocumentListener() { - myUpdateRunnable = new Runnable() { - @Override - public void run() { - myUpdateScheduled = false; - updateModifiedProperty(); - } + myUpdateRunnable = () -> { + myUpdateScheduled = false; + updateModifiedProperty(); }; } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java index 80431efbcbf8..538c874ffb4f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java @@ -163,11 +163,8 @@ public class FileTypeChooser extends DialogWrapper { final FileType type = chooser.getSelectedType(); if (type == FileTypes.UNKNOWN || type == null) return null; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileTypeManagerEx.getInstanceEx().associatePattern(type, (String)chooser.myPattern.getSelectedItem()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + FileTypeManagerEx.getInstanceEx().associatePattern(type, (String)chooser.myPattern.getSelectedItem()); }); return type; diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeIdentifiableByVirtualFile.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeIdentifiableByVirtualFile.java index e5072b8f4f2b..122ce2463e03 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeIdentifiableByVirtualFile.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeIdentifiableByVirtualFile.java @@ -31,11 +31,6 @@ public interface FileTypeIdentifiableByVirtualFile extends FileType { boolean isMyFileType(@NotNull VirtualFile file); FileTypeIdentifiableByVirtualFile[] EMPTY_ARRAY = new FileTypeIdentifiableByVirtualFile[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public FileTypeIdentifiableByVirtualFile[] create(int count) { - return count == 0 ? EMPTY_ARRAY : new FileTypeIdentifiableByVirtualFile[count]; - } - }; + ArrayFactory ARRAY_FACTORY = + count -> count == 0 ? EMPTY_ARRAY : new FileTypeIdentifiableByVirtualFile[count]; } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/ApproveRemovedMappingsActivity.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/ApproveRemovedMappingsActivity.java index 3734165ffa7f..06a901334aba 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/ApproveRemovedMappingsActivity.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/ApproveRemovedMappingsActivity.java @@ -59,20 +59,16 @@ public class ApproveRemovedMappingsActivity implements StartupActivity { NotificationType.WARNING, new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - FileTypeManager.getInstance().associate(PlainTextFileType.INSTANCE, matcher); - map.put(matcher, Pair.create(fileType, true)); - } + ApplicationManager.getApplication().runWriteAction(() -> { + FileTypeManager.getInstance().associate(PlainTextFileType.INSTANCE, matcher); + map.put(matcher, Pair.create(fileType, true)); }); notification.expire(); } }); Notifications.Bus.notify(notification, project); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - FileTypeManager.getInstance().associate(fileType, matcher); - } + ApplicationManager.getApplication().runWriteAction(() -> { + FileTypeManager.getInstance().associate(fileType, matcher); }); iterator.remove(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java index 9e67bd1dcca5..f5cd0f46744a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java @@ -434,11 +434,8 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent } } if (!changed.isEmpty()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - FileContentUtilCore.reparseFiles(changed); - } + ApplicationManager.getApplication().invokeLater(() -> { + FileContentUtilCore.reparseFiles(changed); }, ApplicationManager.getApplication().getDisposed()); } } @@ -798,55 +795,52 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent final Ref result = new Ref(UnknownFileType.INSTANCE); boolean r = false; try { - r = processFirstBytes(inputStream, DETECT_BUFFER_SIZE, new Processor() { - @Override - public boolean process(ByteSequence byteSequence) { - boolean isText = guessIfText(file, byteSequence); - CharSequence text; - if (isText) { - byte[] bytes = Arrays.copyOf(byteSequence.getBytes(), byteSequence.getLength()); - text = LoadTextUtil.getTextByBinaryPresentation(bytes, file, true, true, UnknownFileType.INSTANCE); - } - else { - text = null; - } + r = processFirstBytes(inputStream, DETECT_BUFFER_SIZE, byteSequence -> { + boolean isText = guessIfText(file, byteSequence); + CharSequence text; + if (isText) { + byte[] bytes = Arrays.copyOf(byteSequence.getBytes(), byteSequence.getLength()); + text = LoadTextUtil.getTextByBinaryPresentation(bytes, file, true, true, UnknownFileType.INSTANCE); + } + else { + text = null; + } - FileTypeDetector[] detectors = Extensions.getExtensions(FileTypeDetector.EP_NAME); - if (toLog()) { - log("F: detectFromContentAndCache.processFirstBytes(" + file.getName()+ "): " + - "byteSequence.length="+byteSequence.getLength()+ - "; isText="+isText+ - "; text='"+(text==null?null:StringUtil.first(text, 100, true))+ - "', detectors="+Arrays.toString(detectors)); + FileTypeDetector[] detectors = Extensions.getExtensions(FileTypeDetector.EP_NAME); + if (toLog()) { + log("F: detectFromContentAndCache.processFirstBytes(" + file.getName()+ "): " + + "byteSequence.length="+byteSequence.getLength()+ + "; isText="+isText+ + "; text='"+(text==null?null:StringUtil.first(text, 100, true))+ + "', detectors="+Arrays.toString(detectors)); + } + FileType detected = null; + for (FileTypeDetector detector : detectors) { + try { + detected = detector.detect(file, byteSequence, text); } - FileType detected = null; - for (FileTypeDetector detector : detectors) { - try { - detected = detector.detect(file, byteSequence, text); - } - catch (Exception e) { - LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e); - } - if (detected != null) { - if (toLog()) { - log("F: detectFromContentAndCache.processFirstBytes(" + file.getName()+ "): " + - "detector " + detector + - " type as " + detected.getName()); - } - break; - } + catch (Exception e) { + LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e); } - - if (detected == null) { - detected = isText ? PlainTextFileType.INSTANCE : UnknownFileType.INSTANCE; + if (detected != null) { if (toLog()) { log("F: detectFromContentAndCache.processFirstBytes(" + file.getName()+ "): " + - "no detector was able to detect. assigned " + detected.getName()); + "detector " + detector + + " type as " + detected.getName()); } + break; } - result.set(detected); - return true; } + + if (detected == null) { + detected = isText ? PlainTextFileType.INSTANCE : UnknownFileType.INSTANCE; + if (toLog()) { + log("F: detectFromContentAndCache.processFirstBytes(" + file.getName()+ "): " + + "no detector was able to detect. assigned " + detected.getName()); + } + } + result.set(detected); + return true; }); } finally { @@ -941,25 +935,19 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent @Override public void registerFileType(@NotNull final FileType type, @NotNull final List defaultAssociations) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - fireBeforeFileTypesChanged(); - registerFileTypeWithoutNotification(type, defaultAssociations, true); - fireFileTypesChanged(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + fireBeforeFileTypesChanged(); + registerFileTypeWithoutNotification(type, defaultAssociations, true); + fireFileTypesChanged(); }); } @Override public void unregisterFileType(@NotNull final FileType fileType) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - fireBeforeFileTypesChanged(); - unregisterFileTypeWithoutNotification(fileType); - fireFileTypesChanged(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + fireBeforeFileTypesChanged(); + unregisterFileTypeWithoutNotification(fileType); + fireFileTypesChanged(); }); } @@ -1250,12 +1238,7 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent } } if (!notExternalizableFileTypes.isEmpty()) { - Collections.sort(notExternalizableFileTypes, new Comparator() { - @Override - public int compare(@NotNull FileType o1, @NotNull FileType o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(notExternalizableFileTypes, (o1, o2) -> o1.getName().compareTo(o2.getName())); for (FileType type : notExternalizableFileTypes) { writeExtensionsMap(map, type, true); } @@ -1263,12 +1246,7 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent if (!myUnresolvedMappings.isEmpty()) { FileNameMatcher[] unresolvedMappingKeys = myUnresolvedMappings.keySet().toArray(new FileNameMatcher[myUnresolvedMappings.size()]); - Arrays.sort(unresolvedMappingKeys, new Comparator() { - @Override - public int compare(@NotNull FileNameMatcher o1, @NotNull FileNameMatcher o2) { - return o1.getPresentableString().compareTo(o2.getPresentableString()); - } - }); + Arrays.sort(unresolvedMappingKeys, (o1, o2) -> o1.getPresentableString().compareTo(o2.getPresentableString())); for (FileNameMatcher fileNameMatcher : unresolvedMappingKeys) { Element content = AbstractFileType.writeMapping(myUnresolvedMappings.get(fileNameMatcher), fileNameMatcher, true); diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java index a0d3613cfb00..50fc4e9e47cb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/IdeKeyEventDispatcher.java @@ -111,14 +111,11 @@ public final class IdeKeyEventDispatcher implements Disposable { private final IdeEventQueue myQueue; private final Alarm mySecondStrokeTimeout = new Alarm(); - private final Runnable mySecondStrokeTimeoutRunnable = new Runnable() { - @Override - public void run() { - if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) { - resetState(); - final DataContext dataContext = myContext.getDataContext(); - StatusBar.Info.set(null, dataContext == null ? null : CommonDataKeys.PROJECT.getData(dataContext)); - } + private final Runnable mySecondStrokeTimeoutRunnable = () -> { + if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) { + resetState(); + final DataContext dataContext = myContext.getDataContext(); + StatusBar.Info.set(null, dataContext == null ? null : CommonDataKeys.PROJECT.getData(dataContext)); } }; @@ -469,13 +466,10 @@ public final class IdeKeyEventDispatcher implements Disposable { mySecondKeystrokePopupTimeout.cancelAllRequests(); if (secondKeyStrokes.size() > 1) { final DataContext oldContext = myContext.getDataContext(); - mySecondKeystrokePopupTimeout.addRequest(new Runnable() { - @Override - public void run() { - if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) { - StatusBar.Info.set(null, CommonDataKeys.PROJECT.getData(oldContext)); - new SecondaryKeystrokePopup(myFirstKeyStroke, secondKeyStrokes, oldContext).showInBestPositionFor(oldContext); - } + mySecondKeystrokePopupTimeout.addRequest(() -> { + if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) { + StatusBar.Info.set(null, CommonDataKeys.PROJECT.getData(oldContext)); + new SecondaryKeystrokePopup(myFirstKeyStroke, secondKeyStrokes, oldContext).showInBestPositionFor(oldContext); } }, Registry.intValue("actionSystem.secondKeystrokePopupTimeout")); } @@ -598,12 +592,7 @@ public final class IdeKeyEventDispatcher implements Disposable { } if (Registry.is("actionSystem.fixLostTyping")) { - IdeEventQueue.getInstance().doWhenReady(new Runnable() { - @Override - public void run() { - IdeEventQueue.getInstance().getKeyEventDispatcher().resetState(); - } - }); + IdeEventQueue.getInstance().doWhenReady(() -> IdeEventQueue.getInstance().getKeyEventDispatcher().resetState()); } } }; @@ -659,13 +648,10 @@ public final class IdeKeyEventDispatcher implements Disposable { private static void showDumbModeWarningLaterIfNobodyConsumesEvent(final InputEvent e, final AnActionEvent... actionEvents) { if (ModalityState.current() == ModalityState.NON_MODAL) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (e.isConsumed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (e.isConsumed()) return; - ActionUtil.showDumbModeWarning(actionEvents); - } + ActionUtil.showDumbModeWarning(actionEvents); }); } } @@ -840,34 +826,31 @@ public final class IdeKeyEventDispatcher implements Disposable { } private void registerActions(@NotNull final KeyStroke firstKeyStroke, @NotNull final List> actions, final DataContext ctx) { - ContainerUtil.process(actions, new Processor>() { - @Override - public boolean process(final Pair pair) { - final String actionText = pair.getFirst().getTemplatePresentation().getText(); - final AbstractAction a = new AbstractAction() { - @Override - public void actionPerformed(final ActionEvent e) { - cancel(); - invokeAction(pair.getFirst(), ctx); - } - }; - - final KeyStroke keyStroke = pair.getSecond(); - if (keyStroke != null) { - registerAction(actionText, keyStroke, a); - - if (keyStroke.getModifiers() == 0) { - // do a little trick here, so if I will press Command+R and the second keystroke is just 'R', - // I want to be able to hold the Command while pressing 'R' - - final KeyStroke additionalKeyStroke = KeyStroke.getKeyStroke(keyStroke.getKeyCode(), firstKeyStroke.getModifiers()); - final String _existing = getActionForKeyStroke(additionalKeyStroke); - if (_existing == null) registerAction("__additional__" + actionText, additionalKeyStroke, a); - } + ContainerUtil.process(actions, pair -> { + final String actionText = pair.getFirst().getTemplatePresentation().getText(); + final AbstractAction a = new AbstractAction() { + @Override + public void actionPerformed(final ActionEvent e) { + cancel(); + invokeAction(pair.getFirst(), ctx); } + }; - return true; + final KeyStroke keyStroke = pair.getSecond(); + if (keyStroke != null) { + registerAction(actionText, keyStroke, a); + + if (keyStroke.getModifiers() == 0) { + // do a little trick here, so if I will press Command+R and the second keystroke is just 'R', + // I want to be able to hold the Command while pressing 'R' + + final KeyStroke additionalKeyStroke = KeyStroke.getKeyStroke(keyStroke.getKeyCode(), firstKeyStroke.getModifiers()); + final String _existing = getActionForKeyStroke(additionalKeyStroke); + if (_existing == null) registerAction("__additional__" + actionText, additionalKeyStroke, a); + } } + + return true; }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTreeUtil.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTreeUtil.java index 3deb5359fdb1..dc240c51b876 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTreeUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTreeUtil.java @@ -91,11 +91,7 @@ public class ActionsTreeUtil { ActionManagerEx managerEx = ActionManagerEx.getInstanceEx(); final List plugins = new ArrayList(); Collections.addAll(plugins, PluginManagerCore.getPlugins()); - Collections.sort(plugins, new Comparator() { - public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(plugins, (o1, o2) -> o1.getName().compareTo(o2.getName())); List collected = new ArrayList(); for (IdeaPluginDescriptor plugin : plugins) { @@ -111,11 +107,7 @@ public class ActionsTreeUtil { if (pluginActions == null || pluginActions.length == 0) { continue; } - Arrays.sort(pluginActions, new Comparator() { - public int compare(String o1, String o2) { - return getTextToCompare(o1).compareTo(getTextToCompare(o2)); - } - }); + Arrays.sort(pluginActions, (o1, o2) -> getTextToCompare(o1).compareTo(getTextToCompare(o2))); for (String pluginAction : pluginActions) { if (keymapManager.getBoundActions().contains(pluginAction)) continue; final AnAction anAction = managerEx.getActionOrStub(pluginAction); @@ -354,11 +346,7 @@ public class ActionsTreeUtil { } private static Group createQuickListsGroup(final Condition filtered, final String filter, final boolean forceFiltering, final QuickList[] quickLists) { - Arrays.sort(quickLists, new Comparator() { - public int compare(QuickList l1, QuickList l2) { - return l1.getActionId().compareTo(l2.getActionId()); - } - }); + Arrays.sort(quickLists, (l1, l2) -> l1.getActionId().compareTo(l2.getActionId())); Group group = new Group(KeyMapBundle.message("quick.lists.group.title"), null, null); for (QuickList quickList : quickLists) { @@ -412,11 +400,7 @@ public class ActionsTreeUtil { filterOtherActionsGroup(result); - ContainerUtil.quickSort(result, new Comparator() { - public int compare(String id1, String id2) { - return getTextToCompare(id1).compareToIgnoreCase(getTextToCompare(id2)); - } - }); + ContainerUtil.quickSort(result, (id1, id2) -> getTextToCompare(id1).compareToIgnoreCase(getTextToCompare(id2))); Group group = new Group(KeyMapBundle.message("other.group.title"), AllIcons.Nodes.KeymapOther); for (String id : result) { diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ChooseActionsDialog.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ChooseActionsDialog.java index 83428ed2cd4d..df003f39495d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ChooseActionsDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ChooseActionsDialog.java @@ -161,19 +161,17 @@ public class ChooseActionsDialog extends DialogWrapper { myFilterComponent = new FilterComponent("KEYMAP_IN_QUICK_LISTS", 5) { public void filter() { alarm.cancelAllRequests(); - alarm.addRequest(new Runnable() { - public void run() { - if (!myFilterComponent.isShowing()) return; - if (!myTreeExpansionMonitor.isFreeze()) myTreeExpansionMonitor.freeze(); - myFilteringPanel.setShortcut(null); - final String filter = getFilter(); - myActionsTree.filter(filter, myQuicklists); - final JTree tree = myActionsTree.getTree(); - TreeUtil.expandAll(tree); - if (filter == null || filter.length() == 0) { - TreeUtil.collapseAll(tree, 0); - myTreeExpansionMonitor.restore(); - } + alarm.addRequest(() -> { + if (!myFilterComponent.isShowing()) return; + if (!myTreeExpansionMonitor.isFreeze()) myTreeExpansionMonitor.freeze(); + myFilteringPanel.setShortcut(null); + final String filter = getFilter(); + myActionsTree.filter(filter, myQuicklists); + final JTree tree = myActionsTree.getTree(); + TreeUtil.expandAll(tree); + if (filter == null || filter.length() == 0) { + TreeUtil.collapseAll(tree, 0); + myTreeExpansionMonitor.restore(); } }, 300); } diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/EditKeymapsDialog.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/EditKeymapsDialog.java index be4989328ebd..b42cf1894117 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/EditKeymapsDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/EditKeymapsDialog.java @@ -30,11 +30,7 @@ public class EditKeymapsDialog extends SingleConfigurableEditor { public void show() { if (myActionToSelect != null) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - ((KeymapPanel)getConfigurable()).selectAction(myActionToSelect); - } - }); + SwingUtilities.invokeLater(() -> ((KeymapPanel)getConfigurable()).selectAction(myActionToSelect)); } super.show(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeymapPanel.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeymapPanel.java index af27fec07d51..437252b88932 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeymapPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeymapPanel.java @@ -203,12 +203,7 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi @Override public Runnable enableSearch(final String option) { - return new Runnable() { - @Override - public void run() { - showOption(option); - } - }; + return () -> showOption(option); } @Override @@ -397,23 +392,20 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi @Override public void filter() { alarm.cancelAllRequests(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - if (!myFilterComponent.isShowing()) return; - myTreeExpansionMonitor.freeze(); - myFilteringPanel.setShortcut(null); - final String filter = getFilter(); - myActionsTree.filter(filter, myQuickLists); - final JTree tree = myActionsTree.getTree(); - TreeUtil.expandAll(tree); - if (filter == null || filter.length() == 0) { - TreeUtil.collapseAll(tree, 0); - myTreeExpansionMonitor.restore(); - } - else { - myTreeExpansionMonitor.unfreeze(); - } + alarm.addRequest(() -> { + if (!myFilterComponent.isShowing()) return; + myTreeExpansionMonitor.freeze(); + myFilteringPanel.setShortcut(null); + final String filter = getFilter(); + myActionsTree.filter(filter, myQuickLists); + final JTree tree = myActionsTree.getTree(); + TreeUtil.expandAll(tree); + if (filter == null || filter.length() == 0) { + TreeUtil.collapseAll(tree, 0); + myTreeExpansionMonitor.restore(); + } + else { + myTreeExpansionMonitor.unfreeze(); } }, 300); } diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/QuickListsUi.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/QuickListsUi.java index 62cb2d072fb3..bd85ef3d542c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/QuickListsUi.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/QuickListsUi.java @@ -145,14 +145,11 @@ class QuickListsUi implements ConfigurableUi> { itemPanel.apply(); editor.ensureNonEmptyNames("Quick list should have non empty name"); - editor.processModifiedItems(new PairProcessor() { - @Override - public boolean process(QuickList newItem, QuickList oldItem) { - if (!oldItem.getName().equals(newItem.getName())) { - keymapListener.quickListRenamed(oldItem, newItem); - } - return true; + editor.processModifiedItems((newItem, oldItem) -> { + if (!oldItem.getName().equals(newItem.getName())) { + keymapListener.quickListRenamed(oldItem, newItem); } + return true; }); if (isModified(settings)) { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/binding/ControlBinder.java b/platform/platform-impl/src/com/intellij/openapi/options/binding/ControlBinder.java index bc200d07bfdd..8a95315b6fd4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/binding/ControlBinder.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/binding/ControlBinder.java @@ -57,11 +57,7 @@ public class ControlBinder { final Pair binding = Pair.create(controlAccessor, beanAccessor); myBindings.add(binding); if (instant) { - controlAccessor.addChangeListener(new Runnable() { - public void run() { - apply(binding); - } - }); + controlAccessor.addChangeListener(() -> apply(binding)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/SingleConfigurableEditor.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/SingleConfigurableEditor.java index 4987e9164122..328b8c9b180a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/SingleConfigurableEditor.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/SingleConfigurableEditor.java @@ -124,12 +124,7 @@ public class SingleConfigurableEditor extends DialogWrapper { @Override public void show() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - SingleConfigurableEditor.super.show(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> SingleConfigurableEditor.super.show()); } public Configurable getConfigurable() { @@ -229,12 +224,7 @@ public class SingleConfigurableEditor extends DialogWrapper { }; // invokeLater necessary to make sure dialog is already shown so we calculate modality state correctly. - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - addUpdateRequest(updateRequest); - } - }); + SwingUtilities.invokeLater(() -> addUpdateRequest(updateRequest)); } private void addUpdateRequest(final Runnable updateRequest) { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/Weighted.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/Weighted.java index fd2c640d0c22..37ec0f53a5c2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/Weighted.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/Weighted.java @@ -26,16 +26,13 @@ import java.util.Comparator; interface Weighted { int getWeight(); - Comparator COMPARATOR = new Comparator() { - @Override - public int compare(Configurable configurable1, Configurable configurable2) { - int weight1 = configurable1 instanceof Weighted ? ((Weighted)configurable1).getWeight() : 0; - int weight2 = configurable2 instanceof Weighted ? ((Weighted)configurable2).getWeight() : 0; - return weight1 > weight2 ? -1 : - weight1 < weight2 ? 1 : - StringUtil.naturalCompare( - configurable1 == null ? null : configurable1.getDisplayName(), - configurable2 == null ? null : configurable2.getDisplayName()); - } + Comparator COMPARATOR = (configurable1, configurable2) -> { + int weight1 = configurable1 instanceof Weighted ? ((Weighted)configurable1).getWeight() : 0; + int weight2 = configurable2 instanceof Weighted ? ((Weighted)configurable2).getWeight() : 0; + return weight1 > weight2 ? -1 : + weight1 < weight2 ? 1 : + StringUtil.naturalCompare( + configurable1 == null ? null : configurable1.getDisplayName(), + configurable2 == null ? null : configurable2.getDisplayName()); }; } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java index bab190acf4e0..cb09c138c633 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/ConfigurableEditor.java @@ -75,12 +75,7 @@ class ConfigurableEditor extends AbstractEditor implements AnActionListener, AWT private final AbstractAction myApplyAction = new AbstractAction(CommonBundle.getApplyButtonText()) { @Override public void actionPerformed(ActionEvent event) { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - apply(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> apply()); } }; private final AbstractAction myResetAction = new AbstractAction(RESET_NAME) { @@ -247,12 +242,9 @@ class ConfigurableEditor extends AbstractEditor implements AnActionListener, AWT final ActionCallback select(final Configurable configurable) { assert !myDisposed : "Already disposed"; ActionCallback callback = myCardPanel.select(configurable, false); - callback.doWhenDone(new Runnable() { - @Override - public void run() { - myConfigurable = configurable; - updateCurrent(configurable, false); - } + callback.doWhenDone(() -> { + myConfigurable = configurable; + updateCurrent(configurable, false); }); return callback; } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java index 2d41df1698e5..6207c6afb897 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java @@ -74,12 +74,7 @@ public class SettingsDialog extends DialogWrapper implements DataProvider { @Override public void show() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - SettingsDialog.super.show(); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> SettingsDialog.super.show()); } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsEditor.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsEditor.java index d0b74234546d..796b414f683a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsEditor.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsEditor.java @@ -117,12 +117,7 @@ final class SettingsEditor extends AbstractEditor implements DataProvider { } checkModified(oldConfigurable); ActionCallback result = myEditor.select(configurable); - result.doWhenDone(new Runnable() { - @Override - public void run() { - myLoadingDecorator.stopLoading(); - } - }); + result.doWhenDone(() -> myLoadingDecorator.stopLoading()); return result; } @@ -261,24 +256,16 @@ final class SettingsEditor extends AbstractEditor implements DataProvider { configurable = ConfigurableVisitor.ALL.find(groups); } } - myTreeView.select(configurable).doWhenDone(new Runnable() { - @Override - public void run() { - myFilter.update(filter, false, true); - } - }); + myTreeView.select(configurable).doWhenDone(() -> myFilter.update(filter, false, true)); Disposer.register(this, myTreeView); installSpotlightRemover(); mySearch.getTextEditor().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - myTreeView.select(myFilter.myContext.getCurrentConfigurable()).doWhenDone(new Runnable() { - @Override - public void run() { - JComponent component = myEditor.getPreferredFocusedComponent(); - if (component != null) { - IdeFocusManager.findInstanceByComponent(component).requestFocus(component, true); - } + myTreeView.select(myFilter.myContext.getCurrentConfigurable()).doWhenDone(() -> { + JComponent component1 = myEditor.getPreferredFocusedComponent(); + if (component1 != null) { + IdeFocusManager.findInstanceByComponent(component1).requestFocus(component1, true); } }); } @@ -373,12 +360,9 @@ final class SettingsEditor extends AbstractEditor implements DataProvider { myEditor.revalidate(); } if (configurable != null) { - new Alarm().addRequest(new Runnable() { - @Override - public void run() { - if (!myDisposed && mySpotlightPainter != null) { - mySpotlightPainter.updateNow(); - } + new Alarm().addRequest(() -> { + if (!myDisposed && mySpotlightPainter != null) { + mySpotlightPainter.updateNow(); } }, 300); } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java index e243115154b6..8dc32474bec4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java @@ -365,29 +365,18 @@ final class SettingsTreeView extends JComponent implements Accessible, Disposabl fireSelected(null, callback); } else { - myBuilder.getReady(this).doWhenDone(new Runnable() { - @Override - public void run() { - if (configurable != myQueuedConfigurable) return; + myBuilder.getReady(this).doWhenDone(() -> { + if (configurable != myQueuedConfigurable) return; - MyNode editorNode = findNode(configurable); - FilteringTreeStructure.FilteringNode editorUiNode = myBuilder.getVisibleNodeFor(editorNode); - if (editorUiNode == null) return; + MyNode editorNode = findNode(configurable); + FilteringTreeStructure.FilteringNode editorUiNode = myBuilder.getVisibleNodeFor(editorNode); + if (editorUiNode == null) return; - if (!myBuilder.getSelectedElements().contains(editorUiNode)) { - myBuilder.select(editorUiNode, new Runnable() { - public void run() { - fireSelected(configurable, callback); - } - }); - } - else { - myBuilder.scrollSelectionToVisible(new Runnable() { - public void run() { - fireSelected(configurable, callback); - } - }, false); - } + if (!myBuilder.getSelectedElements().contains(editorUiNode)) { + myBuilder.select(editorUiNode, () -> fireSelected(configurable, callback)); + } + else { + myBuilder.scrollSelectionToVisible(() -> fireSelected(configurable, callback), false); } }); } @@ -860,12 +849,10 @@ final class SettingsTreeView extends JComponent implements Accessible, Disposabl ActionCallback result = super.refilterNow(preferredSelection, adjustSelection); myRefilteringNow = true; - return result.doWhenDone(new Runnable() { - public void run() { - myRefilteringNow = false; - if (!myFilter.myContext.isHoldingFilter() && getSelectedElements().isEmpty()) { - restoreExpandedState(toRestore); - } + return result.doWhenDone(() -> { + myRefilteringNow = false; + if (!myFilter.myContext.isHoldingFilter() && getSelectedElements().isEmpty()) { + restoreExpandedState(toRestore); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/preview/impl/PreviewManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/preview/impl/PreviewManagerImpl.java index 75ff469b4621..3e53e2aa23ea 100644 --- a/platform/platform-impl/src/com/intellij/openapi/preview/impl/PreviewManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/preview/impl/PreviewManagerImpl.java @@ -70,12 +70,9 @@ public class PreviewManagerImpl implements PreviewManager, PersistentStateCompon private ArrayList myHistory = new ArrayList(); - private TreeSet myProviders = new TreeSet(new Comparator() { - @Override - public int compare(PreviewPanelProvider o1, PreviewPanelProvider o2) { - int result = Float.compare(o1.getMenuOrder(), o2.getMenuOrder()); - return result != 0 ? result : o1.toString().compareTo(o2.toString()); - } + private TreeSet myProviders = new TreeSet((o1, o2) -> { + int result = Float.compare(o1.getMenuOrder(), o2.getMenuOrder()); + return result != 0 ? result : o1.toString().compareTo(o2.toString()); }); private Set myActiveProviderIds = new HashSet(); private Set myLockedProviderIds = new HashSet(); @@ -186,12 +183,7 @@ public class PreviewManagerImpl implements PreviewManager, PersistentStateCompon myGearActions.add(new ContentTypeToggleAction(provider)); } myToolWindow.setAdditionalGearActions(new DefaultActionGroup("Preview", myGearActions)); - myToolWindow.activate(new Runnable() { - @Override - public void run() { - myToolWindow.activate(null); - } - }); + myToolWindow.activate(() -> myToolWindow.activate(null)); } } @@ -402,12 +394,9 @@ public class PreviewManagerImpl implements PreviewManager, PersistentStateCompon painter.withShadow(true, new JBColor(Gray._200.withAlpha(100), Gray._0.withAlpha(255))); painter.appendLine("No files are open");//.underlined(new JBColor(Gray._150, Gray._180)); - painter.draw(g, new PairFunction>() { - @Override - public Couple fun(Integer width, Integer height) { - Dimension s = EmptyStatePanel.this.getSize(); - return Couple.of((s.width - width) / 2, (s.height - height) / 2); - } + painter.draw(g, (width, height) -> { + Dimension s = EmptyStatePanel.this.getSize(); + return Couple.of((s.width - width) / 2, (s.height - height) / 2); }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundSynchronousInvisibleComputable.java b/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundSynchronousInvisibleComputable.java index 4f62bcbd3f3f..bf951f2a9148 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundSynchronousInvisibleComputable.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundSynchronousInvisibleComputable.java @@ -32,15 +32,12 @@ public abstract class BackgroundSynchronousInvisibleComputable { final Semaphore semaphore = new Semaphore(); semaphore.down(); final AtomicReference reference = new AtomicReference(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - reference.set(runImpl()); - } - finally { - semaphore.up(); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + reference.set(runImpl()); + } + finally { + semaphore.up(); } }); semaphore.waitFor(); diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundTaskQueue.java b/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundTaskQueue.java index 0ba38058ba84..3436410db2e1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundTaskQueue.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/BackgroundTaskQueue.java @@ -130,13 +130,10 @@ public class BackgroundTaskQueue { final ProgressIndicator[] pi = new ProgressIndicator[1]; final boolean taskTitleIsEmpty = StringUtil.isEmptyOrSpaces(backgroundable.getTitle()); - final Runnable wrappedTask = new Runnable() { - @Override - public void run() { - // calls task's run and onCancel() or onSuccess(); call continuation after task.run() - RunBackgroundable.runIfBackgroundThread(backgroundable, - pi[0] == null ? ProgressManager.getInstance().getProgressIndicator() : pi[0], runnable); - } + final Runnable wrappedTask = () -> { + // calls task's run and onCancel() or onSuccess(); call continuation after task.run() + RunBackgroundable.runIfBackgroundThread(backgroundable, + pi[0] == null ? ProgressManager.getInstance().getProgressIndicator() : pi[0], runnable); }; final ProgressManager pm = ProgressManager.getInstance(); diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java index c5bb29fc714c..bff00c54c35f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java @@ -138,11 +138,8 @@ public class ProgressManagerImpl extends CoreProgressManager implements Disposab final long time = end - start; if (canceled || progressIndicator.isCanceled()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - task.onCancel(); - } + ApplicationManager.getApplication().invokeLater(() -> { + task.onCancel(); }, modalityState); } else { @@ -153,11 +150,8 @@ public class ProgressManagerImpl extends CoreProgressManager implements Disposab systemNotify(notificationInfo); } } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - task.onSuccess(); - } + ApplicationManager.getApplication().invokeLater(() -> { + task.onSuccess(); }, modalityState); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorExBase.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorExBase.java index a4f2cb6aba8e..ed1dd13f7796 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorExBase.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorExBase.java @@ -105,12 +105,7 @@ public class AbstractProgressIndicatorExBase extends AbstractProgressIndicatorBa protected final void enterModality() { if (myModalityProgress == this) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - doEnterModality(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> doEnterModality()); } } @@ -130,12 +125,7 @@ public class AbstractProgressIndicatorExBase extends AbstractProgressIndicatorBa protected final void exitModality() { if (myModalityProgress == this) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - doExitModality(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> doExitModality()); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/BackgroundTaskUtil.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/BackgroundTaskUtil.java index 2901fd1a5fd6..b5f7e878c2d1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/BackgroundTaskUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/BackgroundTaskUtil.java @@ -94,32 +94,21 @@ public class BackgroundTaskUtil { } } else { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { - @Override - public void run() { - final Runnable callback = backgroundTask.fun(indicator); + ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().executeProcessUnderProgress(() -> { + final Runnable callback = backgroundTask.fun(indicator); - if (indicator.isCanceled()) { - semaphore.release(); - return; - } - - if (!resultRef.compareAndSet(null, callback)) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - finish(callback, indicator); - } - }, modality); - } - semaphore.release(); - } - }, indicator); + if (indicator.isCanceled()) { + semaphore.release(); + return; } - }); + + if (!resultRef.compareAndSet(null, callback)) { + ApplicationManager.getApplication().invokeLater(() -> { + finish(callback, indicator); + }, modality); + } + semaphore.release(); + }, indicator)); try { semaphore.tryAcquire(waitMillis, TimeUnit.MILLISECONDS); @@ -150,17 +139,9 @@ public class BackgroundTaskUtil { public static T tryComputeFast(@NotNull final Function backgroundTask, final int waitMillis) { final Ref resultRef = new Ref(); - ProgressIndicator indicator = executeAndTryWait(new Function() { - @Override - public Runnable fun(final ProgressIndicator indicator) { - final T result = backgroundTask.fun(indicator); - return new Runnable() { - @Override - public void run() { - resultRef.set(result); - } - }; - } + ProgressIndicator indicator = executeAndTryWait(indicator1 -> { + final T result = backgroundTask.fun(indicator1); + return () -> resultRef.set(result); }, null, waitMillis, false); indicator.cancel(); @@ -177,12 +158,7 @@ public class BackgroundTaskUtil { @NotNull @CalledInAny public static ProgressIndicator executeOnPooledThread(@NotNull final Runnable runnable, @NotNull Disposable parent) { - return executeOnPooledThread(new Consumer() { - @Override - public void consume(@Nullable ProgressIndicator indicator) { - runnable.run(); - } - }, parent, ModalityState.NON_MODAL); + return executeOnPooledThread(indicator -> runnable.run(), parent, ModalityState.NON_MODAL); } @NotNull @@ -207,23 +183,15 @@ public class BackgroundTaskUtil { Disposer.register(parent, disposable); indicator.start(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().executeProcessUnderProgress(new Runnable() { - @Override - public void run() { - try { - task.consume(indicator); - } - finally { - indicator.stop(); - Disposer.dispose(disposable); - } - } - }, indicator); + ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().executeProcessUnderProgress(() -> { + try { + task.consume(indicator); } - }); + finally { + indicator.stop(); + Disposer.dispose(disposable); + } + }, indicator)); return indicator; } diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/ColorProgressBar.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/ColorProgressBar.java index 562c9c60d80a..855ff00c42ac 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/ColorProgressBar.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/ColorProgressBar.java @@ -39,25 +39,17 @@ import java.awt.geom.Rectangle2D; public class ColorProgressBar extends JComponent { private static final Dimension PREFERRED_SIZE = new Dimension(146, 17); - public static final Color GREEN = new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - UISettings settings = UISettings.getInstance(); - return settings == null || null == settings.COLOR_BLINDNESS - ? new JBColor(new Color(0x6cad74), new Color(0x4a8c53)) - : new JBColor(new Color(0x6ca69c), new Color(0x639990)); - } + public static final Color GREEN = new JBColor(() -> { + UISettings settings = UISettings.getInstance(); + return settings == null || null == settings.COLOR_BLINDNESS + ? new JBColor(new Color(0x6cad74), new Color(0x4a8c53)) + : new JBColor(new Color(0x6ca69c), new Color(0x639990)); }); - public static final Color RED = new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - UISettings settings = UISettings.getInstance(); - return settings == null || null == settings.COLOR_BLINDNESS - ? new JBColor(new Color(0xd67b76), new Color(0xe55757)) - : new JBColor(new Color(0xcc7447), new Color(0xcc7447)); - } + public static final Color RED = new JBColor(() -> { + UISettings settings = UISettings.getInstance(); + return settings == null || null == settings.COLOR_BLINDNESS + ? new JBColor(new Color(0xd67b76), new Color(0xe55757)) + : new JBColor(new Color(0xcc7447), new Color(0xcc7447)); }); public static final Color RED_TEXT = new JBColor(new Color(0xb81708), new Color(0xdb5c5c)); public static final Color BLUE = new JBColor(new Color(1, 68, 208), JBColor.blue); diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.java index ae7b925e9b87..c2694b0c631b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.java @@ -87,12 +87,7 @@ class ProgressDialog implements Disposable { return fullText; } - private final Runnable myUpdateRequest = new Runnable() { - @Override - public void run() { - update(); - } - }; + private final Runnable myUpdateRequest = () -> update(); JPanel myPanel; private JLabel myTextLabel; @@ -199,12 +194,9 @@ class ProgressDialog implements Disposable { void setShouldShowBackground(final boolean shouldShowBackground) { myShouldShowBackground = shouldShowBackground; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myBackgroundButton.setVisible(shouldShowBackground); - myPanel.revalidate(); - } + SwingUtilities.invokeLater(() -> { + myBackgroundButton.setVisible(shouldShowBackground); + myPanel.revalidate(); }); } @@ -224,11 +216,8 @@ class ProgressDialog implements Disposable { void enableCancelButtonIfNeeded(final boolean enable) { if (myProgressWindow.myShouldShowCancel) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myCancelButton.setEnabled(enable); - } + ApplicationManager.getApplication().invokeLater(() -> { + myCancelButton.setEnabled(enable); }, ModalityState.any()); } } @@ -265,12 +254,9 @@ class ProgressDialog implements Disposable { else { // later to avoid concurrent dispose/addRequest if (!myUpdateAlarm.isDisposed() && myUpdateAlarm.getActiveRequestCount() == 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!myUpdateAlarm.isDisposed() && myUpdateAlarm.getActiveRequestCount() == 0) { - myUpdateAlarm.addRequest(myUpdateRequest, 500, myProgressWindow.getModalityState()); - } + SwingUtilities.invokeLater(() -> { + if (!myUpdateAlarm.isDisposed() && myUpdateAlarm.getActiveRequestCount() == 0) { + myUpdateAlarm.addRequest(myUpdateRequest, 500, myProgressWindow.getModalityState()); } }); } @@ -287,13 +273,10 @@ class ProgressDialog implements Disposable { } void hide() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myPopup != null) { - myPopup.close(DialogWrapper.CANCEL_EXIT_CODE); - myPopup = null; - } + SwingUtilities.invokeLater(() -> { + if (myPopup != null) { + myPopup.close(DialogWrapper.CANCEL_EXIT_CODE); + myPopup = null; } }); } @@ -320,19 +303,16 @@ class ProgressDialog implements Disposable { } myPopup.pack(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myPopup != null) { - if (myPopup.getPeer() instanceof FocusTrackbackProvider) { - final FocusTrackback focusTrackback = ((FocusTrackbackProvider)myPopup.getPeer()).getFocusTrackback(); - if (focusTrackback != null) { - focusTrackback.consume(); - } + SwingUtilities.invokeLater(() -> { + if (myPopup != null) { + if (myPopup.getPeer() instanceof FocusTrackbackProvider) { + final FocusTrackback focusTrackback = ((FocusTrackbackProvider)myPopup.getPeer()).getFocusTrackback(); + if (focusTrackback != null) { + focusTrackback.consume(); } - - myProgressWindow.getFocusManager().requestFocus(myCancelButton, true).doWhenDone(myRepaintRunnable); } + + myProgressWindow.getFocusManager().requestFocus(myCancelButton, true).doWhenDone(myRepaintRunnable); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressWindow.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressWindow.java index 7906c26260b7..207bfc94a7f9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressWindow.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressWindow.java @@ -161,29 +161,26 @@ public class ProgressWindow extends ProgressIndicatorBase implements BlockingPro Timer timer = UIUtil.createNamedTimer("Progress window timer",myDelayInMillis, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (isRunning()) { - if (myDialog != null) { - final DialogWrapper popup = myDialog.myPopup; - if (popup != null) { - myFocusTrackback.registerFocusComponent(new FocusTrackback.ComponentQuery() { - @Override - public Component getComponent() { - return popup.getPreferredFocusedComponent(); - } - }); - if (popup.isShowing()) { - myDialog.myWasShown = true; + ApplicationManager.getApplication().invokeLater(() -> { + if (isRunning()) { + if (myDialog != null) { + final DialogWrapper popup = myDialog.myPopup; + if (popup != null) { + myFocusTrackback.registerFocusComponent(new FocusTrackback.ComponentQuery() { + @Override + public Component getComponent() { + return popup.getPreferredFocusedComponent(); } + }); + if (popup.isShowing()) { + myDialog.myWasShown = true; } } - showDialog(); - } - else { - Disposer.dispose(ProgressWindow.this); } + showDialog(); + } + else { + Disposer.dispose(ProgressWindow.this); } }, getModalityState()); } @@ -215,12 +212,7 @@ public class ProgressWindow extends ProgressIndicatorBase implements BlockingPro object.getID() == KeyEvent.KEY_PRESSED && ((KeyEvent)object).getKeyCode() == KeyEvent.VK_ESCAPE && ((KeyEvent)object).getModifiers() == 0) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - cancel(); - } - }); + SwingUtilities.invokeLater(() -> cancel()); } return isStarted() && !isRunning(); } @@ -283,29 +275,26 @@ public class ProgressWindow extends ProgressIndicatorBase implements BlockingPro } } - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - boolean wasShowing = isDialogShowing(); - if (myDialog != null) { - myDialog.hide(); - } - - if (myFocusTrackback != null) { - if (wasShowing) { - myFocusTrackback.restoreFocus(); - } - else { - myFocusTrackback.consume(); - } - } - - synchronized (ProgressWindow.this) { - myStoppedAlready = true; - } - - Disposer.dispose(ProgressWindow.this); + UIUtil.invokeLaterIfNeeded(() -> { + boolean wasShowing = isDialogShowing(); + if (myDialog != null) { + myDialog.hide(); } + + if (myFocusTrackback != null) { + if (wasShowing) { + myFocusTrackback.restoreFocus(); + } + else { + myFocusTrackback.consume(); + } + } + + synchronized (ProgressWindow.this) { + myStoppedAlready = true; + } + + Disposer.dispose(ProgressWindow.this); }); SwingUtilities.invokeLater(EmptyRunnable.INSTANCE); // Just to give blocking dispatching a chance to go out. diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/SmoothProgressAdapter.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/SmoothProgressAdapter.java index 2a27cd681a71..e60997e0f9aa 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/SmoothProgressAdapter.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/SmoothProgressAdapter.java @@ -150,15 +150,12 @@ public class SmoothProgressAdapter extends AbstractProgressIndicatorExBase imple semaphore.down(); SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - semaphore.waitFor(); - if (myDialog != null){ - //System.out.println("myDialog.destroyProcess()"); - myDialog.close(DialogWrapper.OK_EXIT_CODE); - myDialog = null; - } + () -> { + semaphore.waitFor(); + if (myDialog != null){ + //System.out.println("myDialog.destroyProcess()"); + myDialog.close(DialogWrapper.OK_EXIT_CODE); + myDialog = null; } } ); diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/StatusBarProgress.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/StatusBarProgress.java index f90662e862b1..9cde715923b0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/StatusBarProgress.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/StatusBarProgress.java @@ -42,22 +42,19 @@ public class StatusBarProgress extends ProgressIndicatorBase { super.start(); //noinspection SSBasedInspection SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - if (ApplicationManager.getApplication().isDisposed()) return; - WindowManager windowManager = WindowManager.getInstance(); - if (windowManager == null) return; + () -> { + if (ApplicationManager.getApplication().isDisposed()) return; + WindowManager windowManager = WindowManager.getInstance(); + if (windowManager == null) return; - Project[] projects = ProjectManager.getInstance().getOpenProjects(); - if (projects.length == 0) projects = new Project[]{null}; + Project[] projects = ProjectManager.getInstance().getOpenProjects(); + if (projects.length == 0) projects = new Project[]{null}; - for (Project project : projects) { - StatusBar statusBar = windowManager.getStatusBar(project); - if (statusBar != null) { - String info = notNull(statusBar.getInfo(), ""); - myStatusBar2SavedText.put(statusBar, pair(info, info)); // initial value - } + for (Project project : projects) { + StatusBar statusBar = windowManager.getStatusBar(project); + if (statusBar != null) { + String info = notNull(statusBar.getInfo(), ""); + myStatusBar2SavedText.put(statusBar, pair(info, info)); // initial value } } } @@ -69,15 +66,12 @@ public class StatusBarProgress extends ProgressIndicatorBase { super.stop(); //noinspection SSBasedInspection SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - for (StatusBar statusBar : myStatusBar2SavedText.keySet()) { - String textToRestore = updateRestoreText(statusBar); - statusBar.setInfo(textToRestore); - } - myStatusBar2SavedText.clear(); + () -> { + for (StatusBar statusBar : myStatusBar2SavedText.keySet()) { + String textToRestore = updateRestoreText(statusBar); + statusBar.setInfo(textToRestore); } + myStatusBar2SavedText.clear(); } ); } @@ -109,12 +103,9 @@ public class StatusBarProgress extends ProgressIndicatorBase { final String _text = text; //noinspection SSBasedInspection SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - for (StatusBar statusBarEx : myStatusBar2SavedText.keySet()) { - setStatusBarText(statusBarEx, _text); - } + () -> { + for (StatusBar statusBarEx : myStatusBar2SavedText.keySet()) { + setStatusBarText(statusBarEx, _text); } } ); diff --git a/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java b/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java index 9004e5113471..7481a0ab742f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/CacheUpdateRunner.java @@ -110,12 +110,7 @@ public class CacheUpdateRunner { } }; final Application application = ApplicationManager.getApplication(); - application.invokeAndWait(new Runnable() { - @Override - public void run() { - application.addApplicationListener(canceller); - } - }, ModalityState.any()); + application.invokeAndWait(() -> application.addApplicationListener(canceller), ModalityState.any()); final AtomicBoolean isFinished = new AtomicBoolean(); try { @@ -214,43 +209,37 @@ public class CacheUpdateRunner { return; } - final Runnable action = new Runnable() { - @Override - public void run() { - myInnerIndicator.checkCanceled(); - if (!myProject.isDisposed()) { - final VirtualFile file = fileContent.getVirtualFile(); - try { - myProgressUpdater.consume(file); - if (!file.isDirectory() && !Boolean.TRUE.equals(file.getUserData(FAILED_TO_INDEX))) { - myProcessor.consume(fileContent); - } - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - LOG.error("Error while indexing " + file.getPresentableUrl() + "\n" + "To reindex this file IDEA has to be restarted", e); - file.putUserData(FAILED_TO_INDEX, Boolean.TRUE); + final Runnable action = () -> { + myInnerIndicator.checkCanceled(); + if (!myProject.isDisposed()) { + final VirtualFile file = fileContent.getVirtualFile(); + try { + myProgressUpdater.consume(file); + if (!file.isDirectory() && !Boolean.TRUE.equals(file.getUserData(FAILED_TO_INDEX))) { + myProcessor.consume(fileContent); } } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + LOG.error("Error while indexing " + file.getPresentableUrl() + "\n" + "To reindex this file IDEA has to be restarted", e); + file.putUserData(FAILED_TO_INDEX, Boolean.TRUE); + } } }; try { ProgressManager.getInstance().runProcess( - new Runnable() { - @Override - public void run() { - if (myProcessInReadAction) { - // in wait methods we don't want to deadlock by grabbing write lock (or having it in queue) and trying to run read action in separate thread - if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(action)) { - throw new ProcessCanceledException(); - } - } - else { - action.run(); + () -> { + if (myProcessInReadAction) { + // in wait methods we don't want to deadlock by grabbing write lock (or having it in queue) and trying to run read action in separate thread + if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(action)) { + throw new ProcessCanceledException(); } } + else { + action.run(); + } }, ProgressWrapper.wrap(myInnerIndicator) ); diff --git a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java index c07e78b23ad8..ca7a7c45cbd1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java @@ -185,71 +185,62 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica return; } - Runnable runnable = new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) { - return; + Runnable runnable = () -> { + if (myProject.isDisposed()) { + return; + } + + final DumbModePermission permission = schedulerPermission != null ? schedulerPermission : getEdtPermission(); + + myProgresses.put(task, new ProgressIndicatorBase()); + Disposer.register(task, new Disposable() { + @Override + public void dispose() { + application.assertIsDispatchThread(); + myProgresses.remove(task); + } + }); + myUpdatesQueue.addLast(task); + // ok to test and set the flag like this, because the change is always done from dispatch thread + if (!myDumb) { + if (permission == null) { + LOG.info("Dumb mode not permitted in modal environment; see DumbService.allowStartingDumbModeInside documentation", trace); + } + else if (permission == DumbModePermission.MAY_START_MODAL) { + LOG.debug("Starting modal dumb mode, caused by the following trace", trace); } - final DumbModePermission permission = schedulerPermission != null ? schedulerPermission : getEdtPermission(); - - myProgresses.put(task, new ProgressIndicatorBase()); - Disposer.register(task, new Disposable() { - @Override - public void dispose() { - application.assertIsDispatchThread(); - myProgresses.remove(task); + // always change dumb status inside write action. + // This will ensure all active read actions are completed before the app goes dumb + application.runWriteAction(() -> { + synchronized (myRunWhenSmartQueue) { + myDumb = true; + } + myDumbStart = trace; + myDumbStartTransaction = contextTransaction; + myModificationCount++; + if (!myUpdateFinishedQueued) { + try { + myPublisher.enteredDumbMode(); + } + catch (Throwable e) { + LOG.error(e); + } } }); - myUpdatesQueue.addLast(task); - // ok to test and set the flag like this, because the change is always done from dispatch thread - if (!myDumb) { - if (permission == null) { - LOG.info("Dumb mode not permitted in modal environment; see DumbService.allowStartingDumbModeInside documentation", trace); - } - else if (permission == DumbModePermission.MAY_START_MODAL) { - LOG.debug("Starting modal dumb mode, caused by the following trace", trace); - } - // always change dumb status inside write action. - // This will ensure all active read actions are completed before the app goes dumb - application.runWriteAction(new Runnable() { - @Override - public void run() { - synchronized (myRunWhenSmartQueue) { - myDumb = true; - } - myDumbStart = trace; - myDumbStartTransaction = contextTransaction; - myModificationCount++; - if (!myUpdateFinishedQueued) { - try { - myPublisher.enteredDumbMode(); - } - catch (Throwable e) { - LOG.error(e); - } - } - } - }); - - // later because we're likely in a write action and can't start a modal progress immediately - // and for a background progress, it doesn't matter if it starts several milliseconds later; dumb mode is already on - application.invokeLater(new Runnable() { - @Override - public void run() { - boolean modal = permission != DumbModePermission.MAY_START_BACKGROUND; - try { - startBackgroundProcess(modal); - } - catch (Throwable e) { - queueUpdateFinished(modal); - LOG.error("Failed to start background index update task", e); - } - } - }, ModalityState.any(), myProject.getDisposed()); - } + // later because we're likely in a write action and can't start a modal progress immediately + // and for a background progress, it doesn't matter if it starts several milliseconds later; dumb mode is already on + application.invokeLater(() -> { + boolean modal = permission != DumbModePermission.MAY_START_BACKGROUND; + try { + startBackgroundProcess(modal); + } + catch (Throwable e) { + queueUpdateFinished(modal); + LOG.error("Failed to start background index update task", e); + } + }, ModalityState.any(), myProject.getDisposed()); } }; if (application.isDispatchThread()) { @@ -312,11 +303,8 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica // some listeners might start yet another dumb mode // allow that whatever the current modality is, because it won't harm anyone - allowStartingDumbModeInside(modal ? DumbModePermission.MAY_START_MODAL : DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - public void run() { - notifyUpdateFinished(); - } - }); + allowStartingDumbModeInside(modal ? DumbModePermission.MAY_START_MODAL : DumbModePermission.MAY_START_BACKGROUND, + () -> notifyUpdateFinished()); } private void notifyUpdateFinished() { @@ -350,14 +338,11 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica @Override public void showDumbModeNotification(@NotNull final String message) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - final IdeFrame ideFrame = WindowManager.getInstance().getIdeFrame(myProject); - if (ideFrame != null) { - StatusBarEx statusBar = (StatusBarEx)ideFrame.getStatusBar(); - statusBar.notifyProgressByBalloon(MessageType.WARNING, message, null, null); - } + UIUtil.invokeLaterIfNeeded(() -> { + final IdeFrame ideFrame = WindowManager.getInstance().getIdeFrame(myProject); + if (ideFrame != null) { + StatusBarEx statusBar = (StatusBarEx)ideFrame.getStatusBar(); + statusBar.notifyProgressByBalloon(MessageType.WARNING, message, null, null); } }); } @@ -375,12 +360,7 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica final Semaphore semaphore = new Semaphore(); semaphore.down(); - runWhenSmart(new Runnable() { - @Override - public void run() { - semaphore.up(); - } - }); + runWhenSmart(() -> semaphore.up()); while (true) { if (semaphore.waitFor(50)) { return; @@ -483,52 +463,46 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica if (ApplicationManager.getApplication().isInternal()) LOG.info("Running dumb mode task: " + task); // nested runProcess is needed for taskIndicator to be honored in ProgressManager.checkCanceled calls deep inside tasks - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - try { - taskIndicator.checkCanceled(); + ProgressManager.getInstance().runProcess(() -> { + try { + taskIndicator.checkCanceled(); - taskIndicator.setIndeterminate(true); - taskIndicator.setText(IdeBundle.message("progress.indexing.scanning")); + taskIndicator.setIndeterminate(true); + taskIndicator.setText(IdeBundle.message("progress.indexing.scanning")); - task.performInDumbMode(taskIndicator); - } - catch (ProcessCanceledException ignored) { - } - catch (Throwable unexpected) { - LOG.error(unexpected); - } + task.performInDumbMode(taskIndicator); + } + catch (ProcessCanceledException ignored) { + } + catch (Throwable unexpected) { + LOG.error(unexpected); } }, taskIndicator); } @Nullable private Pair getNextTask(@Nullable final DumbModeTask prevTask, final boolean modal) { final Ref> result = Ref.create(); - invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - if (prevTask != null) { - Disposer.dispose(prevTask); - } + invokeAndWaitIfNeeded(() -> { + if (myProject.isDisposed()) return; + if (prevTask != null) { + Disposer.dispose(prevTask); + } - while (true) { - if (myUpdatesQueue.isEmpty()) { - queueUpdateFinished(modal); - return; - } - - DumbModeTask queuedTask = myUpdatesQueue.pullFirst(); - ProgressIndicatorEx indicator = myProgresses.get(queuedTask); - if (indicator.isCanceled()) { - Disposer.dispose(queuedTask); - continue; - } - - result.set(Pair.create(queuedTask, indicator)); + while (true) { + if (myUpdatesQueue.isEmpty()) { + queueUpdateFinished(modal); return; } + + DumbModeTask queuedTask = myUpdatesQueue.pullFirst(); + ProgressIndicatorEx indicator = myProgresses.get(queuedTask); + if (indicator.isCanceled()) { + Disposer.dispose(queuedTask); + continue; + } + + result.set(Pair.create(queuedTask, indicator)); + return; } }); return result.get(); @@ -577,25 +551,18 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica public void setFraction(final double fraction) { if (fraction - lastFraction < 0.01d) return; lastFraction = fraction; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - AppIcon.getInstance().setProgress(myProject, "indexUpdate", AppIconScheme.Progress.INDEXING, fraction, true); - } - }); + UIUtil.invokeLaterIfNeeded( + () -> AppIcon.getInstance().setProgress(myProject, "indexUpdate", AppIconScheme.Progress.INDEXING, fraction, true)); } @Override public void finish(@NotNull TaskInfo task) { if (lastFraction != 0) { // we should call setProgress at least once before - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - AppIcon appIcon = AppIcon.getInstance(); - if (appIcon.hideProgress(myProject, "indexUpdate")) { - appIcon.requestAttention(myProject, false); - appIcon.setOkBadge(myProject, true); - } + UIUtil.invokeLaterIfNeeded(() -> { + AppIcon appIcon = AppIcon.getInstance(); + if (appIcon.hideProgress(myProject, "indexUpdate")) { + appIcon.requestAttention(myProject, false); + appIcon.setOkBadge(myProject, true); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/project/FileContentQueue.java b/platform/platform-impl/src/com/intellij/openapi/project/FileContentQueue.java index 6d955b2ff106..d8a822ec3bcc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/FileContentQueue.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/FileContentQueue.java @@ -76,19 +76,16 @@ public class FileContentQueue { for (int i = 0; i < ourTasksNumber; ++i) { ourContentLoadingQueues.addLast(this); - Runnable task = new Runnable() { - @Override - public void run() { - FileContentQueue contentQueue = ourContentLoadingQueues.pollFirst(); - while (contentQueue != null) { - if (contentQueue.loadNextContent()) { - ourContentLoadingQueues.addLast(contentQueue); - } - if (myContentsToLoad.get() == 0) { - return; - } - contentQueue = ourContentLoadingQueues.pollFirst(); + Runnable task = () -> { + FileContentQueue contentQueue = ourContentLoadingQueues.pollFirst(); + while (contentQueue != null) { + if (contentQueue.loadNextContent()) { + ourContentLoadingQueues.addLast(contentQueue); } + if (myContentsToLoad.get() == 0) { + return; + } + contentQueue = ourContentLoadingQueues.pollFirst(); } }; ourExecutor.submit(task); diff --git a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectMacrosUtil.java b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectMacrosUtil.java index a22b7c785d52..b770b05c1f3f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectMacrosUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectMacrosUtil.java @@ -83,12 +83,7 @@ public class ProjectMacrosUtil { // there are undefined macros, need to define them before loading components final boolean[] result = new boolean[1]; - WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(new Runnable() { - @Override - public void run() { - result[0] = showMacrosConfigurationDialog(project, usedMacros); - } - }, ModalityState.NON_MODAL); + WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(() -> result[0] = showMacrosConfigurationDialog(project, usedMacros), ModalityState.NON_MODAL); return result[0]; } diff --git a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java index 65e0713df9d7..9d57ca55a261 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java @@ -279,16 +279,13 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable { public synchronized Project getDefaultProject() { LOG.assertTrue(!myDefaultProjectWasDisposed, "Default project has been already disposed!"); if (myDefaultProject == null) { - ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { - @Override - public void run() { - try { - myDefaultProject = createProject(null, "", true); - initProject(myDefaultProject, null); - } - catch (Throwable t) { - PluginManager.processException(t); - } + ProgressManager.getInstance().executeNonCancelableSection(() -> { + try { + myDefaultProject = createProject(null, "", true); + initProject(myDefaultProject, null); + } + catch (Throwable t) { + PluginManager.processException(t); } }); } @@ -340,35 +337,29 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable { }) ); - Runnable process = new Runnable() { - @Override - public void run() { - TransactionGuard.getInstance().submitTransactionAndWait(() -> fireProjectOpened(project)); + Runnable process = () -> { + TransactionGuard.getInstance().submitTransactionAndWait(() -> fireProjectOpened(project)); - StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(project); - startupManager.runStartupActivities(); + StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(project); + startupManager.runStartupActivities(); - // Startup activities (e.g. the one in FileBasedIndexProjectHandler) have scheduled dumb mode to begin "later" - // Now we schedule-and-wait to the same event queue to guarantee that the dumb mode really begins now: - // Post-startup activities should not ever see unindexed and at the same time non-dumb state - TransactionGuard.getInstance().submitTransactionAndWait(startupManager::startCacheUpdate); + // Startup activities (e.g. the one in FileBasedIndexProjectHandler) have scheduled dumb mode to begin "later" + // Now we schedule-and-wait to the same event queue to guarantee that the dumb mode really begins now: + // Post-startup activities should not ever see unindexed and at the same time non-dumb state + TransactionGuard.getInstance().submitTransactionAndWait(startupManager::startCacheUpdate); - startupManager.runPostStartupActivitiesFromExtensions(); + startupManager.runPostStartupActivitiesFromExtensions(); - GuiUtils.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - startupManager.runPostStartupActivities(); + GuiUtils.invokeLaterIfNeeded(() -> { + if (!project.isDisposed()) { + startupManager.runPostStartupActivities(); - Application application = ApplicationManager.getApplication(); - if (!(application.isHeadlessEnvironment() || application.isUnitTestMode())) { - StorageUtil.checkUnknownMacros(project, true); - } - } + Application application = ApplicationManager.getApplication(); + if (!(application.isHeadlessEnvironment() || application.isUnitTestMode())) { + StorageUtil.checkUnknownMacros(project, true); } - }, ModalityState.NON_MODAL); - } + } + }, ModalityState.NON_MODAL); }; if (myProgressManager.getProgressIndicator() != null) { process.run(); @@ -450,11 +441,8 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable { } if (!project.isOpen()) { WelcomeFrame.showIfNoProjectOpened(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Disposer.dispose(project); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Disposer.dispose(project); }); } return project; @@ -489,12 +477,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable { } if (!conversionResult.conversionNotNeeded()) { - StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - conversionResult.postStartupActivity(project); - } - }); + StartupManager.getInstance(project).registerPostStartupActivity(() -> conversionResult.postStartupActivity(project)); } return project; } @@ -560,26 +543,23 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable { public static void doReloadProject(@NotNull Project project) { final Ref projectRef = Ref.create(project); ProjectReloadState.getInstance(project).onBeforeAutomaticProjectReload(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - LOG.debug("Reloading project."); - Project project = projectRef.get(); - // Let it go - projectRef.set(null); + ApplicationManager.getApplication().invokeLater(() -> { + LOG.debug("Reloading project."); + Project project1 = projectRef.get(); + // Let it go + projectRef.set(null); - if (project.isDisposed()) { - return; - } - - // must compute here, before project dispose - String presentableUrl = project.getPresentableUrl(); - if (!ProjectUtil.closeAndDispose(project)) { - return; - } - - ProjectUtil.openProject(presentableUrl, null, true); + if (project1.isDisposed()) { + return; } + + // must compute here, before project dispose + String presentableUrl = project1.getPresentableUrl(); + if (!ProjectUtil.closeAndDispose(project1)) { + return; + } + + ProjectUtil.openProject(presentableUrl, null, true); }, ModalityState.NON_MODAL); } @@ -616,16 +596,13 @@ public class ProjectManagerImpl extends ProjectManagerEx implements Disposable { fireProjectClosing(project); // somebody can start progress here, do not wrap in write action - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - removeFromOpened(project); + ApplicationManager.getApplication().runWriteAction(() -> { + removeFromOpened(project); - fireProjectClosed(project); + fireProjectClosed(project); - if (dispose) { - Disposer.dispose(project); - } + if (dispose) { + Disposer.dispose(project); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/ex/MessagesEx.java b/platform/platform-impl/src/com/intellij/openapi/ui/ex/MessagesEx.java index b51b5d1eca88..57de3a1cf991 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/ex/MessagesEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/ex/MessagesEx.java @@ -163,12 +163,9 @@ public class MessagesEx extends Messages { } public void showLater() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showNow(); - } - }, ApplicationManager.getApplication().getDisposed()); + ApplicationManager.getApplication().invokeLater(() -> { + showNow(); + }, ApplicationManager.getApplication().getDisposed()); } @YesNoResult diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java b/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java index 63e028c809de..9c3c823ef043 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/impl/DialogWrapperPeerImpl.java @@ -279,21 +279,15 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra runnable.run(); } myDisposeActions.clear(); - Runnable disposer = new Runnable() { - @Override - public void run() { - Disposer.dispose(myDialog); - myProject = null; + Runnable disposer = () -> { + Disposer.dispose(myDialog); + myProject = null; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myDialog != null && myDialog.getRootPane() != null) { - myDialog.remove(myDialog.getRootPane()); - } - } - }); - } + SwingUtilities.invokeLater(() -> { + if (myDialog != null && myDialog.getRootPane() != null) { + myDialog.remove(myDialog.getRootPane()); + } + }); }; UIUtil.invokeLaterIfNeeded(disposer); @@ -435,12 +429,7 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra final AnCancelAction anCancelAction = new AnCancelAction(); final JRootPane rootPane = getRootPane(); anCancelAction.registerCustomShortcutSet(CommonShortcuts.ESCAPE, rootPane); - myDisposeActions.add(new Runnable() { - @Override - public void run() { - anCancelAction.unregisterCustomShortcutSet(rootPane); - } - }); + myDisposeActions.add(() -> anCancelAction.unregisterCustomShortcutSet(rootPane)); if (!myCanBeParent && myWindowManager != null) { myWindowManager.doNotSuggestAsParent(myDialog.getWindow()); @@ -481,12 +470,7 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra if (!SystemInfo.isMac) return; StackingPopupDispatcher.getInstance().hidePersistentPopups(); - myDisposeActions.add(new Runnable() { - @Override - public void run() { - StackingPopupDispatcher.getInstance().restorePersistentPopups(); - } - }); + myDisposeActions.add(() -> StackingPopupDispatcher.getInstance().restorePersistentPopups()); } @Override @@ -739,12 +723,7 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra Project project = getProject(); if (project != null && !project.isDisposed()) { focusManager.set(getFocusManager()); - focusManager.get().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get()); - } - }); + focusManager.get().doWhenFocusSettlesDown(() -> disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get())); } else { disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get()); @@ -838,12 +817,9 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra if (myFocusTrackback != null && !(myFocusTrackback.isSheduledForRestore() || myFocusTrackback.isWillBeSheduledForRestore())) { myFocusTrackback.setWillBeSheduledForRestore(); IdeFocusManager mgr = getFocusManager(); - Runnable r = new Runnable() { - @Override - public void run() { - if (myFocusTrackback != null) myFocusTrackback.restoreFocus(); - myFocusTrackback = null; - } + Runnable r = () -> { + if (myFocusTrackback != null) myFocusTrackback.restoreFocus(); + myFocusTrackback = null; }; mgr.doWhenFocusSettlesDown(r); } @@ -955,62 +931,56 @@ public class DialogWrapperPeerImpl extends DialogWrapperPeer implements FocusTra @Override public void windowOpened(final WindowEvent e) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myOpened = true; - final DialogWrapper activeWrapper = getActiveWrapper(); - for (JComponent c : UIUtil.uiTraverser(e.getWindow()).filter(JComponent.class)) { - c.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent()); - } - if (activeWrapper == null) { - myFocusedCallback.setRejected(); - myTypeAheadDone.setRejected(); - } + SwingUtilities.invokeLater(() -> { + myOpened = true; + final DialogWrapper activeWrapper = getActiveWrapper(); + for (JComponent c : UIUtil.uiTraverser(e.getWindow()).filter(JComponent.class)) { + c.putClientProperty(SwingUtilities2.AA_TEXT_PROPERTY_KEY, AntialiasingType.getAAHintForSwingComponent()); + } + if (activeWrapper == null) { + myFocusedCallback.setRejected(); + myTypeAheadDone.setRejected(); } }); } @Override public void windowActivated(final WindowEvent e) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final DialogWrapper wrapper = getActiveWrapper(); - if (wrapper == null && !myFocusedCallback.isProcessed()) { - myFocusedCallback.setRejected(); - myTypeAheadDone.setRejected(); - return; - } + SwingUtilities.invokeLater(() -> { + final DialogWrapper wrapper = getActiveWrapper(); + if (wrapper == null && !myFocusedCallback.isProcessed()) { + myFocusedCallback.setRejected(); + myTypeAheadDone.setRejected(); + return; + } - if (myActivated) { - return; - } - myActivated = true; - JComponent toFocus = wrapper == null ? null : wrapper.getPreferredFocusedComponent(); - if (getRootPane() != null && toFocus == null) { - toFocus = getRootPane().getDefaultButton(); - } + if (myActivated) { + return; + } + myActivated = true; + JComponent toFocus = wrapper == null ? null : wrapper.getPreferredFocusedComponent(); + if (getRootPane() != null && toFocus == null) { + toFocus = getRootPane().getDefaultButton(); + } - if (getRootPane() != null) { - IJSwingUtilities.moveMousePointerOn(getRootPane().getDefaultButton()); - } - setupSelectionOnPreferredComponent(toFocus); + if (getRootPane() != null) { + IJSwingUtilities.moveMousePointerOn(getRootPane().getDefaultButton()); + } + setupSelectionOnPreferredComponent(toFocus); - if (toFocus != null) { - if (isShowing() && isActive()) { - getFocusManager().requestFocus(toFocus, true); - notifyFocused(wrapper); - } - } else { - if (isShowing()) { - notifyFocused(wrapper); - } + if (toFocus != null) { + if (isShowing() && isActive()) { + getFocusManager().requestFocus(toFocus, true); + notifyFocused(wrapper); } - if (myTypeAheadCallback != null) { - myTypeAheadCallback.setDone(); + } else { + if (isShowing()) { + notifyFocused(wrapper); } } + if (myTypeAheadCallback != null) { + myTypeAheadCallback.setDone(); + } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java b/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java index 0b604957de35..b2fdd1707c62 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java @@ -604,12 +604,7 @@ public class GlassPaneDialogWrapperPeer extends DialogWrapperPeer implements Foc remove(getContentPane()); repaint(); - final Runnable disposer = new Runnable() { - @Override - public void run() { - setVisible(false); - } - }; + final Runnable disposer = () -> setVisible(false); if (EventQueue.isDispatchThread()) { disposer.run(); diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackContext.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackContext.java index 0a458abc524d..2b41f80f550f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackContext.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackContext.java @@ -89,12 +89,9 @@ public abstract class PlaybackContext { public void flushAwtAndRunInEdt(final Runnable runnable) { if (EventQueue.isDispatchThread()) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - getRobot().waitForIdle(); - SwingUtilities.invokeLater(runnable); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + getRobot().waitForIdle(); + SwingUtilities.invokeLater(runnable); }); } else { getRobot().waitForIdle(); @@ -103,17 +100,14 @@ public abstract class PlaybackContext { } public void delayAndRunInEdt(final Runnable runnable, final long delay) { - runPooledThread(new Runnable() { - @Override - public void run() { - try { - Thread.currentThread().sleep(delay); - } - catch (InterruptedException e) { - - } - SwingUtilities.invokeLater(runnable); + runPooledThread(() -> { + try { + Thread.currentThread().sleep(delay); } + catch (InterruptedException e) { + + } + SwingUtilities.invokeLater(runnable); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java index 988dabaf0993..21293386a2a5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java @@ -98,19 +98,13 @@ public class PlaybackRunner { try { myActionCallback = new ActionCallback(); - myActionCallback.doWhenProcessed(new Runnable() { - @Override - public void run() { - stop(); + myActionCallback.doWhenProcessed(() -> { + stop(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - activityMonitor.setActive(false); - restoreRegistryValues(); - } - }); - } + SwingUtilities.invokeLater(() -> { + activityMonitor.setActive(false); + restoreRegistryValues(); + }); }); myRobot = new Robot(); @@ -124,11 +118,7 @@ public class PlaybackRunner { executeFrom(0, getScriptDir()); } else { - IdeEventQueue.getInstance().doWhenReady(new Runnable() { - public void run() { - executeFrom(0, getScriptDir()); - } - }); + IdeEventQueue.getInstance().doWhenReady(() -> executeFrom(0, getScriptDir())); } } }.start(); @@ -194,21 +184,17 @@ public class PlaybackRunner { } }; final ActionCallback cmdCallback = cmd.execute(context); - cmdCallback.doWhenDone(new Runnable() { - public void run() { - if (cmd.canGoFurther()) { - executeFrom(cmdIndex + 1, context.getBaseDir()); - } - else { - myCallback.message(null, "Stopped", StatusCallback.Type.message); - myActionCallback.setDone(); - } + cmdCallback.doWhenDone(() -> { + if (cmd.canGoFurther()) { + executeFrom(cmdIndex + 1, context.getBaseDir()); } - }).doWhenRejected(new Runnable() { - public void run() { + else { myCallback.message(null, "Stopped", StatusCallback.Type.message); - myActionCallback.setRejected(); + myActionCallback.setDone(); } + }).doWhenRejected(() -> { + myCallback.message(null, "Stopped", StatusCallback.Type.message); + myActionCallback.setRejected(); }); } else { @@ -347,11 +333,7 @@ public class PlaybackRunner { messageEdt(context, text, type); } else { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - messageEdt(context, text, type); - } - }); + SwingUtilities.invokeLater(() -> messageEdt(context, text, type)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java index e393cd17508e..3a4c8728738e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java @@ -61,16 +61,13 @@ public abstract class AbstractCommand implements PlaybackCommand { dumpCommand(context); } final ActionCallback result = new ActionCallback(); - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - _execute(context).notify(result); - } - catch (Throwable e) { - context.error(e.getMessage(), getLine()); - result.setRejected(); - } + Runnable runnable = () -> { + try { + _execute(context).notify(result); + } + catch (Throwable e) { + context.error(e.getMessage(), getLine()); + result.setRejected(); } }; diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java index 79ae07d343d3..bbe066b66e15 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java @@ -75,40 +75,29 @@ public class ActionCommand extends TypeCommand { final KeyStroke finalStroke = stroke; - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - final Ref listener = new Ref(); - listener.set(new AnActionListener.Adapter() { + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { + final Ref listener = new Ref(); + listener.set(new AnActionListener.Adapter() { - @Override - public void beforeActionPerformed(final AnAction action, DataContext dataContext, AnActionEvent event) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (context.isDisposed()) { - am.removeAnActionListener(listener.get()); - return; - } + @Override + public void beforeActionPerformed(final AnAction action, DataContext dataContext, AnActionEvent event) { + SwingUtilities.invokeLater(() -> { + if (context.isDisposed()) { + am.removeAnActionListener(listener.get()); + return; + } - if (targetAction.equals(action)) { - context.message("Performed action: " + actionName, context.getCurrentLine()); - am.removeAnActionListener(listener.get()); - result.setDone(); - } - } - }); - } - }); - am.addAnActionListener(listener.get()); + if (targetAction.equals(action)) { + context.message("Performed action: " + actionName, context.getCurrentLine()); + am.removeAnActionListener(listener.get()); + result.setDone(); + } + }); + } + }); + am.addAnActionListener(listener.get()); - context.runPooledThread(new Runnable() { - @Override - public void run() { - type(context.getRobot(), finalStroke); - } - }); - } + context.runPooledThread(() -> type(context.getRobot(), finalStroke)); }); return result; @@ -120,11 +109,8 @@ public class ActionCommand extends TypeCommand { final ActionCallback result = new ActionCallback(); context.getRobot().delay(Registry.intValue("actionSystem.playback.delay")); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - am.tryToExecute(targetAction, input, null, null, false).doWhenProcessed(result.createSetDoneRunnable()); - } - }); + SwingUtilities.invokeLater( + () -> am.tryToExecute(targetAction, input, null, null, false).doWhenProcessed(result.createSetDoneRunnable())); return result; } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AlphaNumericTypeCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AlphaNumericTypeCommand.java index a07aa2fefd72..abfc60a24ab7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AlphaNumericTypeCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AlphaNumericTypeCommand.java @@ -39,19 +39,14 @@ public class AlphaNumericTypeCommand extends TypeCommand { protected ActionCallback type(final PlaybackContext context, final String text) { final ActionCallback result = new ActionCallback(); - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - TypingTarget typingTarget = findTarget(context); - if (typingTarget != null) { - typingTarget.type(text).doWhenDone(result.createSetDoneRunnable()).doWhenRejected(new Runnable() { - public void run() { - typeByRobot(context.getRobot(), text).notify(result); - } - }); - } else { + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { + TypingTarget typingTarget = findTarget(context); + if (typingTarget != null) { + typingTarget.type(text).doWhenDone(result.createSetDoneRunnable()).doWhenRejected(() -> { typeByRobot(context.getRobot(), text).notify(result); - } + }); + } else { + typeByRobot(context.getRobot(), text).notify(result); } }); @@ -61,37 +56,35 @@ public class AlphaNumericTypeCommand extends TypeCommand { private ActionCallback typeByRobot(final Robot robot, final String text) { final ActionCallback result = new ActionCallback(); - Runnable typeRunnable = new Runnable() { - public void run() { - for (int i = 0; i < text.length(); i++) { - final char each = text.charAt(i); - if ('\\' == each && i + 1 < text.length()) { - final char next = text.charAt(i + 1); - boolean processed = true; - switch (next) { - case 'n': - type(robot, KeyEvent.VK_ENTER, 0); - break; - case 't': - type(robot, KeyEvent.VK_TAB, 0); - break; - case 'r': - type(robot, KeyEvent.VK_ENTER, 0); - break; - default: - processed = false; - } - - if (processed) { - i++; - continue; - } + Runnable typeRunnable = () -> { + for (int i = 0; i < text.length(); i++) { + final char each = text.charAt(i); + if ('\\' == each && i + 1 < text.length()) { + final char next = text.charAt(i + 1); + boolean processed = true; + switch (next) { + case 'n': + type(robot, KeyEvent.VK_ENTER, 0); + break; + case 't': + type(robot, KeyEvent.VK_TAB, 0); + break; + case 'r': + type(robot, KeyEvent.VK_ENTER, 0); + break; + default: + processed = false; } - type(robot, get(each)); - } - result.setDone(); + if (processed) { + i++; + continue; + } + } + type(robot, get(each)); } + + result.setDone(); }; if (SwingUtilities.isEventDispatchThread()) { diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AssertFocused.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AssertFocused.java index 657f39d1b15d..35059a368b76 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AssertFocused.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AssertFocused.java @@ -51,16 +51,14 @@ public class AssertFocused extends AbstractCommand { } } - IdeFocusManager.findInstance().doWhenFocusSettlesDown(new Runnable() { - public void run() { - try { - doAssert(expected, context); - result.setDone(); - } - catch (AssertionError error) { - context.error("Assertion failed: " + error.getMessage(), getLine()); - result.setRejected(); - } + IdeFocusManager.findInstance().doWhenFocusSettlesDown(() -> { + try { + doAssert(expected, context); + result.setDone(); + } + catch (AssertionError error) { + context.error("Assertion failed: " + error.getMessage(), getLine()); + result.setRejected(); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java index 1cb672fcfcd8..7145651cae41 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java @@ -98,12 +98,9 @@ public class CallCommand extends AbstractCommand { } cmdResult.setDone(); } - }).doWhenRejected(new Consumer() { - @Override - public void consume(String s) { - context.error(s, getLine()); - cmdResult.setRejected(); - } + }).doWhenRejected(s -> { + context.error(s, getLine()); + cmdResult.setRejected(); }); } catch (InvocationTargetException ignored) { diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyCodeTypeCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyCodeTypeCommand.java index 5d05af1d1a4d..18e239a948cc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyCodeTypeCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyCodeTypeCommand.java @@ -60,19 +60,14 @@ public class KeyCodeTypeCommand extends AlphaNumericTypeCommand { final ActionCallback result = new ActionCallback(); - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - TypingTarget typingTarget = findTarget(context); - if (typingTarget != null) { - typingTarget.type(unicode).doWhenDone(result.createSetDoneRunnable()).doWhenRejected(new Runnable() { - public void run() { - typeCodes(context, context.getRobot(), codes).notify(result); - } - }); - } else { + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { + TypingTarget typingTarget = findTarget(context); + if (typingTarget != null) { + typingTarget.type(unicode).doWhenDone(result.createSetDoneRunnable()).doWhenRejected(() -> { typeCodes(context, context.getRobot(), codes).notify(result); - } + }); + } else { + typeCodes(context, context.getRobot(), codes).notify(result); } }); @@ -82,25 +77,23 @@ public class KeyCodeTypeCommand extends AlphaNumericTypeCommand { private ActionCallback typeCodes(final PlaybackContext context, final Robot robot, final String codes) { final ActionCallback result = new ActionCallback(); - Runnable runnable = new Runnable() { - public void run() { - String[] pairs = codes.split(CODE_DELIMITER); - for (String eachPair : pairs) { - try { - String[] splits = eachPair.split(MODIFIER_DELIMITER); - Integer code = Integer.valueOf(splits[0]); - Integer modifier = Integer.valueOf(splits[1]); - type(robot, code.intValue(), modifier.intValue()); - } - catch (NumberFormatException e) { - dumpError(context, "Invalid code: " + eachPair); - result.setRejected(); - return; - } + Runnable runnable = () -> { + String[] pairs = codes.split(CODE_DELIMITER); + for (String eachPair : pairs) { + try { + String[] splits = eachPair.split(MODIFIER_DELIMITER); + Integer code = Integer.valueOf(splits[0]); + Integer modifier = Integer.valueOf(splits[1]); + type(robot, code.intValue(), modifier.intValue()); + } + catch (NumberFormatException e) { + dumpError(context, "Invalid code: " + eachPair); + result.setRejected(); + return; } - - result.setDone(); } + + result.setDone(); }; diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java index ba32a4d85742..b34ee8d2a750 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java @@ -81,24 +81,21 @@ public class ToggleActionCommand extends AbstractCommand { context.getRobot().delay(Registry.intValue("actionSystem.playback.delay")); IdeFocusManager fm = IdeFocusManager.getGlobalInstance(); - fm.doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - final Presentation presentation = (Presentation)action.getTemplatePresentation().clone(); - AnActionEvent event = - new AnActionEvent(inputEvent, DataManager.getInstance() - .getDataContext(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()), ActionPlaces.UNKNOWN, - presentation, ActionManager.getInstance(), 0); + fm.doWhenFocusSettlesDown(() -> { + final Presentation presentation = (Presentation)action.getTemplatePresentation().clone(); + AnActionEvent event = + new AnActionEvent(inputEvent, DataManager.getInstance() + .getDataContext(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()), ActionPlaces.UNKNOWN, + presentation, ActionManager.getInstance(), 0); - ActionUtil.performDumbAwareUpdate(action, event, false); + ActionUtil.performDumbAwareUpdate(action, event, false); - Boolean state = (Boolean)event.getPresentation().getClientProperty(ToggleAction.SELECTED_PROPERTY); - if (state.booleanValue() != on) { - ActionManager.getInstance().tryToExecute(action, inputEvent, null, ActionPlaces.UNKNOWN, true).doWhenProcessed(result.createSetDoneRunnable()); - } - else { - result.setDone(); - } + Boolean state = (Boolean)event.getPresentation().getClientProperty(ToggleAction.SELECTED_PROPERTY); + if (state.booleanValue() != on) { + ActionManager.getInstance().tryToExecute(action, inputEvent, null, ActionPlaces.UNKNOWN, true).doWhenProcessed(result.createSetDoneRunnable()); + } + else { + result.setDone(); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java index f486d0469745..b30378bb6ac3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java @@ -33,32 +33,29 @@ public class EditorPlaybackCall { public static AsyncResult assertEditorLine(final PlaybackContext context, final String expected) { final AsyncResult result = new AsyncResult(); - WindowSystemPlaybackCall.getUiReady(context).doWhenDone(new Runnable() { - @Override - public void run() { - Editor editor = CommonDataKeys.EDITOR.getData(DataManager.getInstance().getDataContextFromFocus().getResult()); - if (editor == null) { - editor = CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(DataManager.getInstance().getDataContextFromFocus().getResult()); - } + WindowSystemPlaybackCall.getUiReady(context).doWhenDone(() -> { + Editor editor = CommonDataKeys.EDITOR.getData(DataManager.getInstance().getDataContextFromFocus().getResult()); + if (editor == null) { + editor = CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(DataManager.getInstance().getDataContextFromFocus().getResult()); + } - if (editor == null) { - result.setRejected("Cannot find editor"); - return; - } + if (editor == null) { + result.setRejected("Cannot find editor"); + return; + } - final int line = editor.getCaretModel().getLogicalPosition().line; - final int caret = editor.getCaretModel().getOffset(); - final int start = editor.getDocument().getLineStartOffset(line); - final int end = editor.getDocument().getLineEndOffset(line); + final int line = editor.getCaretModel().getLogicalPosition().line; + final int caret = editor.getCaretModel().getOffset(); + final int start = editor.getDocument().getLineStartOffset(line); + final int end = editor.getDocument().getLineEndOffset(line); - final StringBuffer actualText = new StringBuffer(editor.getDocument().getText(new TextRange(start, caret))); - actualText.append("").append(editor.getDocument().getText(new TextRange(caret, end))); - if (expected.equals(actualText.toString())) { - result.setDone(); - } else { - result.setRejected("Expected:" + expected + " but was:" + actualText); - } + final StringBuffer actualText = new StringBuffer(editor.getDocument().getText(new TextRange(start, caret))); + actualText.append("").append(editor.getDocument().getText(new TextRange(caret, end))); + if (expected.equals(actualText.toString())) { + result.setDone(); + } else { + result.setRejected("Expected:" + expected + " but was:" + actualText); } }); @@ -69,11 +66,8 @@ public class EditorPlaybackCall { public static AsyncResult waitDaemonForFinish(final PlaybackContext context) { final AsyncResult result = new AsyncResult(); final Disposable connection = Disposer.newDisposable(); - result.doWhenProcessed(new Runnable() { - @Override - public void run() { - Disposer.dispose(connection); - } + result.doWhenProcessed(() -> { + Disposer.dispose(connection); }); @@ -93,11 +87,8 @@ public class EditorPlaybackCall { } }); } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected("Cannot find project"); - } + }).doWhenRejected(() -> { + result.setRejected("Cannot find project"); }); return result; diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/ProjectPlaybackCall.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/ProjectPlaybackCall.java index 7b5ae6007263..ff89eba236ed 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/ProjectPlaybackCall.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/ProjectPlaybackCall.java @@ -54,32 +54,21 @@ public class ProjectPlaybackCall { listener.set(new ProjectManagerAdapter() { @Override public void projectOpened(final Project project) { - StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - pm.removeProjectManagerListener(listener.get()); - DumbService.getInstance(project).runWhenSmart(new Runnable() { - @Override - public void run() { - result.setDone("Opened successfully: " + project.getPresentableUrl()); - } - }); - } + StartupManager.getInstance(project).registerPostStartupActivity(() -> { + pm.removeProjectManagerListener(listener.get()); + DumbService.getInstance(project).runWhenSmart(() -> result.setDone("Opened successfully: " + project.getPresentableUrl())); }); } }); pm.addProjectManagerListener(listener.get()); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - try { - pm.loadAndOpenProject(path); - } - catch (Exception e) { - context.error(e.getMessage(), context.getCurrentLine()); - result.setRejected(); - } + UIUtil.invokeLaterIfNeeded(() -> { + try { + pm.loadAndOpenProject(path); + } + catch (Exception e) { + context.error(e.getMessage(), context.getCurrentLine()); + result.setRejected(); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/WindowSystemPlaybackCall.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/WindowSystemPlaybackCall.java index fe8ea086b56a..d8d8fe863a7e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/WindowSystemPlaybackCall.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/WindowSystemPlaybackCall.java @@ -46,25 +46,22 @@ public class WindowSystemPlaybackCall { public static AsyncResult printFocus(final PlaybackContext context) { final AsyncResult result = new AsyncResult(); - getUiReady(context).doWhenProcessed(new Runnable() { - @Override - public void run() { - final LinkedHashMap focusInfo = getFocusInfo(); - if (focusInfo == null) { - result.setRejected("No component focused"); - return; - } - - StringBuffer text = new StringBuffer(); - for (Iterator iterator = focusInfo.keySet().iterator(); iterator.hasNext(); ) { - String key = iterator.next(); - text.append(key + "=" + focusInfo.get(key)); - if (iterator.hasNext()) { - text.append("|"); - } - } - result.setDone(text.toString()); + getUiReady(context).doWhenProcessed(() -> { + final LinkedHashMap focusInfo = getFocusInfo(); + if (focusInfo == null) { + result.setRejected("No component focused"); + return; } + + StringBuffer text = new StringBuffer(); + for (Iterator iterator = focusInfo.keySet().iterator(); iterator.hasNext(); ) { + String key = iterator.next(); + text.append(key + "=" + focusInfo.get(key)); + if (iterator.hasNext()) { + text.append("|"); + } + } + result.setDone(text.toString()); }); return result; @@ -83,12 +80,7 @@ public class WindowSystemPlaybackCall { if (wnd instanceof JDialog) { if (title.equals(((JDialog)wnd).getTitle())) { Toolkit.getDefaultToolkit().removeAWTEventListener(listener.get()); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - getUiReady(context).notify(result); - } - }); + SwingUtilities.invokeLater(() -> getUiReady(context).notify(result)); } } } @@ -97,13 +89,10 @@ public class WindowSystemPlaybackCall { Toolkit.getDefaultToolkit().addAWTEventListener(listener.get(), WindowEvent.WINDOW_EVENT_MASK); - SimpleTimer.getInstance().setUp(new Runnable() { - @Override - public void run() { - Toolkit.getDefaultToolkit().removeAWTEventListener(listener.get()); - if (!result.isProcessed()) { - result.setRejected("Timed out waiting for window: " + title); - } + SimpleTimer.getInstance().setUp(() -> { + Toolkit.getDefaultToolkit().removeAWTEventListener(listener.get()); + if (!result.isProcessed()) { + result.setRejected("Timed out waiting for window: " + title); } }, Registry.intValue("actionSystem.commandProcessingTimeout")); @@ -127,15 +116,12 @@ public class WindowSystemPlaybackCall { } } - getUiReady(context).doWhenDone(new Runnable() { - @Override - public void run() { - try { - doAssert(expectedMap, result, context); - } - catch (AssertionError error) { - result.setRejected("Assertion failed: " + error.getMessage()); - } + getUiReady(context).doWhenDone(() -> { + try { + doAssert(expectedMap, result, context); + } + catch (AssertionError error) { + result.setRejected("Assertion failed: " + error.getMessage()); } }); @@ -154,18 +140,12 @@ public class WindowSystemPlaybackCall { return; } - toolWindow.getReady(context).doWhenDone(result.createSetDoneRunnable()).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected("Cannot activate tool window with id:" + id); - } + toolWindow.getReady(context).doWhenDone(result.createSetDoneRunnable()).doWhenRejected(() -> { + result.setRejected("Cannot activate tool window with id:" + id); }); } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected("Cannot retrieve open project"); - } + }).doWhenRejected(() -> { + result.setRejected("Cannot retrieve open project"); }); return result; @@ -174,20 +154,17 @@ public class WindowSystemPlaybackCall { public static AsyncResult findProject() { final AsyncResult project = new AsyncResult(); final IdeFocusManager fm = IdeFocusManager.getGlobalInstance(); - fm.doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - Component parent = UIUtil.findUltimateParent(fm.getFocusOwner()); - if (parent instanceof IdeFrame) { - IdeFrame frame = (IdeFrame)parent; - if (frame.getProject() != null) { - project.setDone(frame.getProject()); - return; - } + fm.doWhenFocusSettlesDown(() -> { + Component parent = UIUtil.findUltimateParent(fm.getFocusOwner()); + if (parent instanceof IdeFrame) { + IdeFrame frame = (IdeFrame)parent; + if (frame.getProject() != null) { + project.setDone(frame.getProject()); + return; } - - project.setRejected(); } + + project.setRejected(); }); return project; @@ -197,46 +174,32 @@ public class WindowSystemPlaybackCall { final AsyncResult result = new AsyncResult(); final IdeFocusManager fm = IdeFocusManager.getGlobalInstance(); - fm.doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - Component owner = fm.getFocusOwner(); - if (owner == null) { - result.setRejected("No component focused"); - return; - } - - ActionManager am = ActionManager.getInstance(); - AnAction showPopupMenu = am.getAction("ShowPopupMenu"); - if (showPopupMenu == null) { - result.setRejected("Cannot find action: ShowPopupMenu"); - return; - } - - am.tryToExecute(showPopupMenu, new MouseEvent(owner, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, 0, 0, 1, true), null, - null, false).doWhenDone( - new Runnable() { - @Override - public void run() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - MenuElement[] selectedPath = MenuSelectionManager.defaultManager().getSelectedPath(); - if (selectedPath.length == 0) { - result.setRejected("Failed to find active popup menu"); - return; - } - selectNext(context, path.split("\\|"), 0, selectedPath[0].getSubElements(), result); - } - }); - } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected("Cannot invoke popup menu from the ShowPopupMenu action, action call rejected"); - } - }); + fm.doWhenFocusSettlesDown(() -> { + Component owner = fm.getFocusOwner(); + if (owner == null) { + result.setRejected("No component focused"); + return; } + + ActionManager am = ActionManager.getInstance(); + AnAction showPopupMenu = am.getAction("ShowPopupMenu"); + if (showPopupMenu == null) { + result.setRejected("Cannot find action: ShowPopupMenu"); + return; + } + + am.tryToExecute(showPopupMenu, new MouseEvent(owner, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, 0, 0, 1, true), null, + null, false).doWhenDone( + () -> SwingUtilities.invokeLater(() -> { + MenuElement[] selectedPath = MenuSelectionManager.defaultManager().getSelectedPath(); + if (selectedPath.length == 0) { + result.setRejected("Failed to find active popup menu"); + return; + } + selectNext(context, path.split("\\|"), 0, selectedPath[0].getSubElements(), result); + })).doWhenRejected(() -> { + result.setRejected("Cannot invoke popup menu from the ShowPopupMenu action, action call rejected"); + }); }); return result; @@ -262,12 +225,9 @@ public class WindowSystemPlaybackCall { public void consume(MenuElement[] menuElements) { selectNext(context, toSelect, toSelectIndex + 1, menuElements, result); } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected("Cannot activate menu element: " + eachButton.getText()); - return; - } + }).doWhenRejected(() -> { + result.setRejected("Cannot activate menu element: " + eachButton.getText()); + return; }); return; } @@ -285,52 +245,37 @@ public class WindowSystemPlaybackCall { final AsyncResult result = new AsyncResult(); final AbstractButton c = (AbstractButton)element.getComponent(); - final Runnable pressRunnable = new Runnable() { - @Override - public void run() { - Robot robot = context.getRobot(); - Point location = c.getLocationOnScreen(); - Dimension size = c.getSize(); - Point point = new Point(location.x + size.width / 2, location.y + size.height / 2); - robot.mouseMove(point.x, point.y); - robot.delay(90); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.delay(90); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - robot.delay(90); - context.flushAwtAndRunInEdt(new Runnable() { - @Override - public void run() { - - context.flushAwtAndRunInEdt(new Runnable() { - @Override - public void run() { - MenuElement[] subElements = element.getSubElements(); - if (subElements == null || subElements.length == 0) { - result.setDone(); - } - else { - MenuElement[] menuElements = subElements[0].getSubElements(); - result.setDone(menuElements); - } - } - }); - } - }); - } + final Runnable pressRunnable = () -> { + Robot robot = context.getRobot(); + Point location = c.getLocationOnScreen(); + Dimension size = c.getSize(); + Point point = new Point(location.x + size.width / 2, location.y + size.height / 2); + robot.mouseMove(point.x, point.y); + robot.delay(90); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(90); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(90); + context.flushAwtAndRunInEdt(() -> context.flushAwtAndRunInEdt(() -> { + MenuElement[] subElements = element.getSubElements(); + if (subElements == null || subElements.length == 0) { + result.setDone(); + } + else { + MenuElement[] menuElements = subElements[0].getSubElements(); + result.setDone(menuElements); + } + })); }; if (c.isShowing()) { context.runPooledThread(pressRunnable); } else { - context.delayAndRunInEdt(new Runnable() { - @Override - public void run() { - if (c.isShowing()) { - context.runPooledThread(pressRunnable); - } else { - result.setRejected(); - } + context.delayAndRunInEdt(() -> { + if (c.isShowing()) { + context.runPooledThread(pressRunnable); + } else { + result.setRejected(); } }, 1000); } @@ -340,12 +285,7 @@ public class WindowSystemPlaybackCall { public static ActionCallback getUiReady(final PlaybackContext context) { final ActionCallback result = new ActionCallback(); - context.flushAwtAndRunInEdt(new Runnable() { - @Override - public void run() { - UiActivityMonitor.getInstance().getBusy().getReady(context).notify(result); - } - }); + context.flushAwtAndRunInEdt(() -> UiActivityMonitor.getInstance().getBusy().getReady(context).notify(result)); return result; } diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java index 273183fa2854..89653b9d4e67 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java @@ -152,12 +152,7 @@ public class PluginDownloader { if (ApplicationManager.getApplication() != null) { final String text = IdeBundle.message("error.plugin.was.not.installed", getPluginName(), errorMessage); final String title = IdeBundle.message("title.failed.to.download"); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(text, title); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(text, title)); } return false; } diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateCheckerComponent.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateCheckerComponent.java index d69b675c29ff..ad7fdb6b52ce 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateCheckerComponent.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateCheckerComponent.java @@ -48,17 +48,7 @@ public class UpdateCheckerComponent implements ApplicationComponent { private static final long CHECK_INTERVAL = DateFormatUtil.DAY; private final Alarm myCheckForUpdatesAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); - private final Runnable myCheckRunnable = new Runnable() { - @Override - public void run() { - UpdateChecker.updateAndShowResult().doWhenDone(new Runnable() { - @Override - public void run() { - queueNextCheck(CHECK_INTERVAL); - } - }); - } - }; + private final Runnable myCheckRunnable = () -> UpdateChecker.updateAndShowResult().doWhenDone(() -> queueNextCheck(CHECK_INTERVAL)); private final UpdateSettings mySettings; public UpdateCheckerComponent(@NotNull Application app, @NotNull UpdateSettings settings) { @@ -99,11 +89,8 @@ public class UpdateCheckerComponent implements ApplicationComponent { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { notification.expire(); - app.invokeLater(new Runnable() { - @Override - public void run() { - ShowSettingsUtil.getInstance().showSettingsDialog(null, UpdateSettingsConfigurable.class); - } + app.invokeLater(() -> { + ShowSettingsUtil.getInstance().showSettingsDialog(null, UpdateSettingsConfigurable.class); }, ModalityState.NON_MODAL); } }).notify(null); diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java index 1a9a6fa47c85..3744f4d8124a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java @@ -74,11 +74,8 @@ class UpdateInfoDialog extends AbstractUpdateDialog { init(); if (incompatiblePlugins != null && !incompatiblePlugins.isEmpty()) { - String list = StringUtil.join(incompatiblePlugins, new Function() { - @Override - public String fun(IdeaPluginDescriptor downloader) { - return downloader.getName(); - } + String list = StringUtil.join(incompatiblePlugins, downloader -> { + return downloader.getName(); }, "
      "); setErrorText(IdeBundle.message("updates.incompatible.plugins.found", incompatiblePlugins.size(), list)); } diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java index 350a209aa5d9..3c570f85caef 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java @@ -94,29 +94,21 @@ public class PluginAdvertiserEditorNotificationProvider extends EditorNotificati panel.setText("Plugins supporting " + extension + " files are found"); final IdeaPluginDescriptor disabledPlugin = PluginsAdvertiser.getDisabledPlugin(plugins); if (disabledPlugin != null) { - panel.createActionLabel("Enable " + disabledPlugin.getName() + " plugin", new Runnable() { - @Override - public void run() { - myEnabledExtensions.add(extension); - myNotifications.updateAllNotifications(); - PluginsAdvertiser.enablePlugins(myProject, Collections.singletonList(disabledPlugin)); - } + panel.createActionLabel("Enable " + disabledPlugin.getName() + " plugin", () -> { + myEnabledExtensions.add(extension); + myNotifications.updateAllNotifications(); + PluginsAdvertiser.enablePlugins(myProject, Collections.singletonList(disabledPlugin)); }); } else if (hasNonBundledPlugin(plugins)) { - panel.createActionLabel("Install plugins", new Runnable() { - @Override - public void run() { - Set pluginIds = new HashSet(); - for (PluginsAdvertiser.Plugin plugin : plugins) { - pluginIds.add(plugin.myPluginId); - } - PluginsAdvertiser.installAndEnablePlugins(pluginIds, new Runnable() { - public void run() { - myEnabledExtensions.add(extension); - myNotifications.updateAllNotifications(); - } - }); + panel.createActionLabel("Install plugins", () -> { + Set pluginIds = new HashSet(); + for (PluginsAdvertiser.Plugin plugin : plugins) { + pluginIds.add(plugin.myPluginId); } + PluginsAdvertiser.installAndEnablePlugins(pluginIds, () -> { + myEnabledExtensions.add(extension); + myNotifications.updateAllNotifications(); + }); }); } else if (PluginsAdvertiser.hasBundledPluginToInstall(plugins) != null){ if (PropertiesComponent.getInstance().isTrueValue(PluginsAdvertiser.IGNORE_ULTIMATE_EDITION)) { @@ -124,30 +116,21 @@ public class PluginAdvertiserEditorNotificationProvider extends EditorNotificati } panel.setText(extension + " files are supported by " + PluginsAdvertiser.IDEA_ULTIMATE_EDITION); - panel.createActionLabel(PluginsAdvertiser.CHECK_ULTIMATE_EDITION_TITLE, new Runnable() { - @Override - public void run() { - myEnabledExtensions.add(extension); - PluginsAdvertiser.openDownloadPage(); - } + panel.createActionLabel(PluginsAdvertiser.CHECK_ULTIMATE_EDITION_TITLE, () -> { + myEnabledExtensions.add(extension); + PluginsAdvertiser.openDownloadPage(); }); - panel.createActionLabel(PluginsAdvertiser.ULTIMATE_EDITION_SUGGESTION, new Runnable() { - @Override - public void run() { - PropertiesComponent.getInstance().setValue(PluginsAdvertiser.IGNORE_ULTIMATE_EDITION, "true"); - myNotifications.updateAllNotifications(); - } + panel.createActionLabel(PluginsAdvertiser.ULTIMATE_EDITION_SUGGESTION, () -> { + PropertiesComponent.getInstance().setValue(PluginsAdvertiser.IGNORE_ULTIMATE_EDITION, "true"); + myNotifications.updateAllNotifications(); }); } else { return null; } - panel.createActionLabel("Ignore extension", new Runnable() { - @Override - public void run() { - UnknownFeaturesCollector.getInstance(myProject).ignoreFeature(createExtensionFeature(extension)); - myNotifications.updateAllNotifications(); - } + panel.createActionLabel("Ignore extension", () -> { + UnknownFeaturesCollector.getInstance(myProject).ignoreFeature(createExtensionFeature(extension)); + myNotifications.updateAllNotifications(); }); return panel; } diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java index f3e51470f44a..1b4266f57e16 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java @@ -191,14 +191,11 @@ public class PluginsAdvertiser implements StartupActivity { final PluginManagerConfigurable managerConfigurable = new PluginManagerConfigurable(PluginManagerUISettings.getInstance()); final PluginManagerMain createPanel = managerConfigurable.getOrCreatePanel(); ShowSettingsUtil.getInstance() - .editConfigurable(project, managerConfigurable, new Runnable() { - @Override - public void run() { - final InstalledPluginsTableModel pluginsModel = (InstalledPluginsTableModel)createPanel.getPluginsModel(); - final IdeaPluginDescriptor[] descriptors = disabledPlugins.toArray(new IdeaPluginDescriptor[disabledPlugins.size()]); - pluginsModel.enableRows(descriptors, Boolean.TRUE); - createPanel.getPluginTable().select(descriptors); - } + .editConfigurable(project, managerConfigurable, () -> { + final InstalledPluginsTableModel pluginsModel = (InstalledPluginsTableModel)createPanel.getPluginsModel(); + final IdeaPluginDescriptor[] descriptors = disabledPlugins.toArray(new IdeaPluginDescriptor[disabledPlugins.size()]); + pluginsModel.enableRows(descriptors, Boolean.TRUE); + createPanel.getPluginTable().select(descriptors); }); } @@ -271,133 +268,122 @@ public class PluginsAdvertiser implements StartupActivity { final Set unknownFeatures = collectorSuggester.getUnknownFeatures(); final KnownExtensions extensions = loadExtensions(); if (extensions != null && unknownFeatures.isEmpty()) return; - final Runnable runnable = new Runnable() { - @Override - public void run() { - final Application application = ApplicationManager.getApplication(); - if (application.isUnitTestMode() || application.isHeadlessEnvironment()) return; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - private final Set myPlugins = new HashSet(); - private List myAllPlugins; + final Runnable runnable = () -> { + final Application application = ApplicationManager.getApplication(); + if (application.isUnitTestMode() || application.isHeadlessEnvironment()) return; + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + private final Set myPlugins = new HashSet(); + private List myAllPlugins; - private final Map myDisabledPlugins = new HashMap(); - private List myBundledPlugin; - private final MultiMap myFeatures = new MultiMap(); + private final Map myDisabledPlugins = new HashMap(); + private List myBundledPlugin; + private final MultiMap myFeatures = new MultiMap(); - @Override - public void run() { - try { - myAllPlugins = RepositoryHelper.loadPluginsFromAllRepositories(null); + @Override + public void run() { + try { + myAllPlugins = RepositoryHelper.loadPluginsFromAllRepositories(null); + if (project.isDisposed()) return; + if (extensions == null) { + loadSupportedExtensions(myAllPlugins); if (project.isDisposed()) return; - if (extensions == null) { - loadSupportedExtensions(myAllPlugins); - if (project.isDisposed()) return; - EditorNotifications.getInstance(project).updateAllNotifications(); - } - final Map ids = new HashMap(); - for (UnknownFeature feature : unknownFeatures) { - ProgressManager.checkCanceled(); - final List pluginId = retrieve(feature); - if (pluginId != null) { - for (Plugin plugin : pluginId) { - ids.put(plugin.myPluginId, plugin); - myFeatures.putValue(plugin.myPluginId, feature); - } - } - } - - final List disabledPlugins = PluginManagerCore.getDisabledPlugins(); - //include disabled plugins - for (String id : ids.keySet()) { - Plugin plugin = ids.get(id); - if (disabledPlugins.contains(id)) { - final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(PluginId.getId(id)); - if (pluginDescriptor != null) { - myDisabledPlugins.put(plugin, pluginDescriptor); - } - } - } - - myBundledPlugin = hasBundledPluginToInstall(ids.values()); - - for (IdeaPluginDescriptor loadedPlugin : myAllPlugins) { - final PluginId pluginId = loadedPlugin.getPluginId(); - if (ids.containsKey(pluginId.getIdString()) && - !disabledPlugins.contains(pluginId.getIdString()) && - !PluginManagerCore.isBrokenPlugin(loadedPlugin)) { - myPlugins.add(PluginDownloader.createDownloader(loadedPlugin)); - } - } - - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - onSuccess(); - } - }, ModalityState.NON_MODAL); - + EditorNotifications.getInstance(project).updateAllNotifications(); } - catch (Exception e) { - LOG.info(e); + final Map ids = new HashMap(); + for (UnknownFeature feature : unknownFeatures) { + ProgressManager.checkCanceled(); + final List pluginId = retrieve(feature); + if (pluginId != null) { + for (Plugin plugin : pluginId) { + ids.put(plugin.myPluginId, plugin); + myFeatures.putValue(plugin.myPluginId, feature); + } + } } + + final List disabledPlugins = PluginManagerCore.getDisabledPlugins(); + //include disabled plugins + for (String id : ids.keySet()) { + Plugin plugin = ids.get(id); + if (disabledPlugins.contains(id)) { + final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(PluginId.getId(id)); + if (pluginDescriptor != null) { + myDisabledPlugins.put(plugin, pluginDescriptor); + } + } + } + + myBundledPlugin = hasBundledPluginToInstall(ids.values()); + + for (IdeaPluginDescriptor loadedPlugin : myAllPlugins) { + final PluginId pluginId = loadedPlugin.getPluginId(); + if (ids.containsKey(pluginId.getIdString()) && + !disabledPlugins.contains(pluginId.getIdString()) && + !PluginManagerCore.isBrokenPlugin(loadedPlugin)) { + myPlugins.add(PluginDownloader.createDownloader(loadedPlugin)); + } + } + + ApplicationManager.getApplication().invokeLater(() -> { + onSuccess(); + }, ModalityState.NON_MODAL); + + } + catch (Exception e) { + LOG.info(e); + } + } + + private void onSuccess() { + String message = null; + if (!myPlugins.isEmpty() || !myDisabledPlugins.isEmpty()) { + message = getAddressedMessagePresentation(); + if (!myDisabledPlugins.isEmpty()) { + message += "Enable plugins...
      "; + } + else { + message += "Configure plugins...
      "; + } + + message += "Ignore Unknown Features"; + } + else if (myBundledPlugin != null && !PropertiesComponent.getInstance().isTrueValue(IGNORE_ULTIMATE_EDITION)) { + message = "Features covered by " + IDEA_ULTIMATE_EDITION + + " (" + StringUtil.join(myBundledPlugin, ", ") + ") are detected.
      " + + "" + CHECK_ULTIMATE_EDITION_TITLE + "
      " + + "" + ULTIMATE_EDITION_SUGGESTION + ""; } - private void onSuccess() { - String message = null; - if (!myPlugins.isEmpty() || !myDisabledPlugins.isEmpty()) { - message = getAddressedMessagePresentation(); - if (!myDisabledPlugins.isEmpty()) { - message += "Enable plugins...
      "; - } - else { - message += "Configure plugins...
      "; - } + if (message != null) { + final ConfigurePluginsListener notificationListener = new ConfigurePluginsListener(unknownFeatures, project, PluginManagerMain.mapToPluginIds(myAllPlugins), myPlugins, myDisabledPlugins); + NOTIFICATION_GROUP.createNotification(DISPLAY_ID, message, NotificationType.INFORMATION, notificationListener).notify(project); + } + } - message += "Ignore Unknown Features"; - } - else if (myBundledPlugin != null && !PropertiesComponent.getInstance().isTrueValue(IGNORE_ULTIMATE_EDITION)) { - message = "Features covered by " + IDEA_ULTIMATE_EDITION + - " (" + StringUtil.join(myBundledPlugin, ", ") + ") are detected.
      " + - "" + CHECK_ULTIMATE_EDITION_TITLE + "
      " + - "" + ULTIMATE_EDITION_SUGGESTION + ""; - } - - if (message != null) { - final ConfigurePluginsListener notificationListener = new ConfigurePluginsListener(unknownFeatures, project, PluginManagerMain.mapToPluginIds(myAllPlugins), myPlugins, myDisabledPlugins); - NOTIFICATION_GROUP.createNotification(DISPLAY_ID, message, NotificationType.INFORMATION, notificationListener).notify(project); + @NotNull + private String getAddressedMessagePresentation() { + final MultiMap addressedFeatures = MultiMap.createSet(); + final Set ids = new LinkedHashSet(); + for (PluginDownloader plugin : myPlugins) { + ids.add(plugin.getPluginId()); + } + for (Plugin plugin : myDisabledPlugins.keySet()) { + ids.add(plugin.myPluginId); + } + for (String id : ids) { + for (UnknownFeature feature : myFeatures.get(id)) { + addressedFeatures.putValue(feature.getFeatureDisplayName(), feature.getImplementationName()); } } - - @NotNull - private String getAddressedMessagePresentation() { - final MultiMap addressedFeatures = MultiMap.createSet(); - final Set ids = new LinkedHashSet(); - for (PluginDownloader plugin : myPlugins) { - ids.add(plugin.getPluginId()); - } - for (Plugin plugin : myDisabledPlugins.keySet()) { - ids.add(plugin.myPluginId); - } - for (String id : ids) { - for (UnknownFeature feature : myFeatures.get(id)) { - addressedFeatures.putValue(feature.getFeatureDisplayName(), feature.getImplementationName()); - } - } - final String addressedFeaturesPresentation = StringUtil.join(addressedFeatures.entrySet(), - new Function>, String>() { - @Override - public String fun(Map.Entry> entry) { - return entry.getKey() + "[" + StringUtil.join(entry.getValue(), ", ") + "]"; - } - }, ", "); - final int addressedFeaturesNumber = addressedFeatures.keySet().size(); - final int pluginsNumber = ids.size(); - return "Unknown feature" + (addressedFeaturesNumber == 1 ? "" : "s") + - " (" + addressedFeaturesPresentation + ") covered by " + (myPlugins.isEmpty() ? "disabled" : "non-bundled") + " plugin" + (pluginsNumber == 1 ? "" : "s") + - " detected.
      "; - } - }); - } + final String addressedFeaturesPresentation = StringUtil.join(addressedFeatures.entrySet(), + entry -> entry.getKey() + "[" + StringUtil.join(entry.getValue(), ", ") + "]", ", "); + final int addressedFeaturesNumber = addressedFeatures.keySet().size(); + final int pluginsNumber = ids.size(); + return "Unknown feature" + (addressedFeaturesNumber == 1 ? "" : "s") + + " (" + addressedFeaturesPresentation + ") covered by " + (myPlugins.isEmpty() ? "disabled" : "non-bundled") + " plugin" + (pluginsNumber == 1 ? "" : "s") + + " detected.
      "; + } + }); }; SwingUtilities.invokeLater(runnable); diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java index c60f5d4316d7..338715dc5f5f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java @@ -45,12 +45,7 @@ public class PluginsAdvertiserDialog extends DialogWrapper { PluginsAdvertiserDialog(@Nullable Project project, PluginDownloader[] plugins, List allPlugins) { super(project); myProject = project; - Arrays.sort(plugins, new Comparator() { - @Override - public int compare(PluginDownloader o1, PluginDownloader o2) { - return o1.getPluginName().compareToIgnoreCase(o2.getPluginName()); - } - }); + Arrays.sort(plugins, (o1, o2) -> o1.getPluginName().compareToIgnoreCase(o2.getPluginName())); myUploadedPlugins = plugins; myAllPlugins = allPlugins; setTitle("Choose Plugins to Install or Enable"); @@ -93,12 +88,7 @@ public class PluginsAdvertiserDialog extends DialogWrapper { PluginManagerMain.suggestToEnableInstalledDependantPlugins(pluginHelper, nodes); - final Runnable notifyRunnable = new Runnable() { - @Override - public void run() { - PluginManagerMain.notifyPluginsUpdated(myProject); - } - }; + final Runnable notifyRunnable = () -> PluginManagerMain.notifyPluginsUpdated(myProject); for (String pluginId : pluginsToEnable) { PluginManagerCore.enablePlugin(pluginId); } diff --git a/platform/platform-impl/src/com/intellij/openapi/util/RequestsMerger.java b/platform/platform-impl/src/com/intellij/openapi/util/RequestsMerger.java index 4a09b07aa958..c38697b60e5a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/util/RequestsMerger.java +++ b/platform/platform-impl/src/com/intellij/openapi/util/RequestsMerger.java @@ -114,11 +114,8 @@ public class RequestsMerger { LOG.debug("doAction: oldState: " + oldState.name() + ", newState: " + myState.name()); if (LOG.isDebugEnabled() && exitActions != null) { - final String debugExitActions = StringUtil.join(exitActions, new Function() { - @Override - public String fun(MyExitAction exitAction) { - return exitAction.name(); - } + final String debugExitActions = StringUtil.join(exitActions, exitAction -> { + return exitAction.name(); }, " "); LOG.debug("exit actions: " + debugExitActions); } diff --git a/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java index d7284f8590ea..c8dd36f4a181 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java @@ -107,24 +107,21 @@ public class FileStatusManagerImpl extends FileStatusManager implements ProjectC } }, myProject); - startupManager.registerPreStartupActivity(new Runnable() { - @Override - public void run() { - DocumentAdapter documentListener = new DocumentAdapter() { - @Override - public void documentChanged(DocumentEvent event) { - if (event.getOldLength() == 0 && event.getNewLength() == 0) return; - VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument()); - if (file != null) { - refreshFileStatusFromDocument(file, event.getDocument()); - } + startupManager.registerPreStartupActivity(() -> { + DocumentAdapter documentListener = new DocumentAdapter() { + @Override + public void documentChanged(DocumentEvent event) { + if (event.getOldLength() == 0 && event.getNewLength() == 0) return; + VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument()); + if (file != null) { + refreshFileStatusFromDocument(file, event.getDocument()); } - }; - - final EditorFactory factory = EditorFactory.getInstance(); - if (factory != null) { - factory.getEventMulticaster().addDocumentListener(documentListener, myProject); } + }; + + final EditorFactory factory = EditorFactory.getInstance(); + if (factory != null) { + factory.getEventMulticaster().addDocumentListener(documentListener, myProject); } }); startupManager.registerPostStartupActivity(new DumbAwareRunnable() { diff --git a/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/HandleType.java b/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/HandleType.java index a6949cc420af..b7dd73ea9eab 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/HandleType.java +++ b/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/HandleType.java @@ -35,22 +35,19 @@ public abstract class HandleType { public static final HandleType USE_FILE_SYSTEM = new HandleType(VcsBundle.message("handle.ro.file.status.type.using.file.system"), false) { @Override public void processFiles(final Collection files, String changelist) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - List toRefresh = ContainerUtil.newArrayListWithCapacity(files.size()); + ApplicationManager.getApplication().runWriteAction(() -> { + List toRefresh = ContainerUtil.newArrayListWithCapacity(files.size()); - for (VirtualFile file : files) { - try { - ReadOnlyAttributeUtil.setReadOnlyAttribute(file, false); - toRefresh.add(file); - } - catch (IOException ignored) { } + for (VirtualFile file : files) { + try { + ReadOnlyAttributeUtil.setReadOnlyAttribute(file, false); + toRefresh.add(file); } + catch (IOException ignored) { } + } - if (!toRefresh.isEmpty()) { - RefreshQueue.getInstance().refresh(false, false, null, toRefresh); - } + if (!toRefresh.isEmpty()) { + RefreshQueue.getInstance().refresh(false, false, null, toRefresh); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/ReadOnlyStatusDialog.java b/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/ReadOnlyStatusDialog.java index 67ef8fe69121..2bbf1943946a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/ReadOnlyStatusDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/vcs/readOnlyHandler/ReadOnlyStatusDialog.java @@ -173,11 +173,8 @@ public class ReadOnlyStatusDialog extends OptionsDialog { super.doOKAction(); } else { - String list = StringUtil.join(files, new Function() { - @Override - public String fun(FileInfo info) { - return info.getFile().getPresentableUrl(); - } + String list = StringUtil.join(files, info -> { + return info.getFile().getPresentableUrl(); }, "
      "); String message = VcsBundle.message("handle.ro.file.status.failed", list); Messages.showErrorDialog(getRootPane(), message, VcsBundle.message("dialog.title.clear.read.only.file.status")); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/ChangeFileEncodingAction.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/ChangeFileEncodingAction.java index be87a940896d..9e4064036a9f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/ChangeFileEncodingAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/ChangeFileEncodingAction.java @@ -121,18 +121,15 @@ public class ChangeFileEncodingAction extends AnAction implements DumbAware { @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { - return createCharsetsActionGroup(clearItemText, null, new Function() { - @Override - public String fun(Charset charset) { - assert myFile.isDirectory() || text != null : charset; - EncodingUtil.Magic8 safeToReload = myFile.isDirectory() ? EncodingUtil.Magic8.ABSOLUTELY : EncodingUtil.isSafeToReloadIn(myFile, text, bytes, charset); - boolean enabled = safeToReload != EncodingUtil.Magic8.NO_WAY; - if (!enabled) { - EncodingUtil.Magic8 safeToConvert = myFile.isDirectory() ? EncodingUtil.Magic8.ABSOLUTELY : EncodingUtil.isSafeToConvertTo(myFile, text, bytes, charset); - enabled = safeToConvert != EncodingUtil.Magic8.NO_WAY; - } - return enabled ? "Change encoding to '"+charset.displayName()+"'" : null; + return createCharsetsActionGroup(clearItemText, null, charset -> { + assert myFile.isDirectory() || text != null : charset; + EncodingUtil.Magic8 safeToReload = myFile.isDirectory() ? EncodingUtil.Magic8.ABSOLUTELY : EncodingUtil.isSafeToReloadIn(myFile, text, bytes, charset); + boolean enabled = safeToReload != EncodingUtil.Magic8.NO_WAY; + if (!enabled) { + EncodingUtil.Magic8 safeToConvert = myFile.isDirectory() ? EncodingUtil.Magic8.ABSOLUTELY : EncodingUtil.isSafeToConvertTo(myFile, text, bytes, charset); + enabled = safeToConvert != EncodingUtil.Magic8.NO_WAY; } + return enabled ? "Change encoding to '"+charset.displayName()+"'" : null; }); // no 'clear' } @@ -164,49 +161,19 @@ public class ChangeFileEncodingAction extends AnAction implements DumbAware { if (isSafeToConvert == EncodingUtil.Magic8.ABSOLUTELY && isSafeToReload == EncodingUtil.Magic8.ABSOLUTELY) { //change and forget - undo = new Runnable() { - @Override - public void run() { - EncodingManager.getInstance().setEncoding(virtualFile, oldCharset); - } - }; - redo = new Runnable() { - @Override - public void run() { - EncodingManager.getInstance().setEncoding(virtualFile, charset); - } - }; + undo = () -> EncodingManager.getInstance().setEncoding(virtualFile, oldCharset); + redo = () -> EncodingManager.getInstance().setEncoding(virtualFile, charset); } else { IncompatibleEncodingDialog dialog = new IncompatibleEncodingDialog(virtualFile, charset, isSafeToReload, isSafeToConvert); dialog.show(); if (dialog.getExitCode() == IncompatibleEncodingDialog.RELOAD_EXIT_CODE) { - undo = new Runnable() { - @Override - public void run() { - EncodingUtil.reloadIn(virtualFile, oldCharset); - } - }; - redo = new Runnable() { - @Override - public void run() { - EncodingUtil.reloadIn(virtualFile, charset); - } - }; + undo = () -> EncodingUtil.reloadIn(virtualFile, oldCharset); + redo = () -> EncodingUtil.reloadIn(virtualFile, charset); } else if (dialog.getExitCode() == IncompatibleEncodingDialog.CONVERT_EXIT_CODE) { - undo = new Runnable() { - @Override - public void run() { - EncodingUtil.saveIn(document, editor, virtualFile, oldCharset); - } - }; - redo = new Runnable() { - @Override - public void run() { - EncodingUtil.saveIn(document, editor, virtualFile, charset); - } - }; + undo = () -> EncodingUtil.saveIn(document, editor, virtualFile, oldCharset); + redo = () -> EncodingUtil.saveIn(document, editor, virtualFile, charset); } else { return false; @@ -230,12 +197,9 @@ public class ChangeFileEncodingAction extends AnAction implements DumbAware { }; redo.run(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - UndoManager undoManager = project == null ? UndoManager.getGlobalInstance() : UndoManager.getInstance(project); - undoManager.undoableActionPerformed(action); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + UndoManager undoManager = project == null ? UndoManager.getGlobalInstance() : UndoManager.getInstance(project); + undoManager.undoableActionPerformed(action); }, "Change encoding for '" + virtualFile.getName() + "'", null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); return true; diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java index bfd79212eb88..cc5c960a9ddb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java @@ -80,12 +80,7 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement Element element = new Element("x"); if (!myMapping.isEmpty()) { List files = new ArrayList(myMapping.keySet()); - ContainerUtil.quickSort(files, new Comparator() { - @Override - public int compare(@NotNull final VirtualFile o1, @NotNull final VirtualFile o2) { - return o1.getPath().compareTo(o2.getPath()); - } - }); + ContainerUtil.quickSort(files, (o1, o2) -> o1.getPath().compareTo(o2.getPath())); for (VirtualFile file : files) { Charset charset = myMapping.get(file); Element child = new Element("file"); @@ -201,13 +196,10 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement } private static void reload(@NotNull final VirtualFile virtualFile) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileDocumentManager documentManager = FileDocumentManager.getInstance(); - ((VirtualFileListener)documentManager) - .contentsChanged(new VirtualFileEvent(null, virtualFile, virtualFile.getName(), virtualFile.getParent())); - } + ApplicationManager.getApplication().runWriteAction(() -> { + FileDocumentManager documentManager = FileDocumentManager.getInstance(); + ((VirtualFileListener)documentManager) + .contentsChanged(new VirtualFileEvent(null, virtualFile, virtualFile.getName(), virtualFile.getParent())); }); } @@ -246,37 +238,34 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement final Map oldMap = new THashMap(myMapping); // ChangeFileEncodingAction should not start progress "reload files..." - suppressReloadDuring(new Runnable() { - @Override - public void run() { - ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); - for (Map.Entry entry : mapping.entrySet()) { - VirtualFile virtualFile = entry.getKey(); - Charset charset = entry.getValue(); - if (charset == null) throw new IllegalArgumentException("Null charset for " + virtualFile + "; mapping: " + mapping); - if (virtualFile == null) { - myProjectCharset = charset; - } - else { - if (!fileIndex.isInContent(virtualFile)) continue; - if (!virtualFile.isDirectory() && !Comparing.equal(charset, oldMap.get(virtualFile))) { - Document document; - byte[] bytes; - try { - document = FileDocumentManager.getInstance().getDocument(virtualFile); - if (document == null) throw new IOException(); - bytes = virtualFile.contentsToByteArray(); - } - catch (IOException e) { - continue; - } - // ask whether to reload/convert when in doubt - boolean changed = new ChangeFileEncodingAction().chosen(document, null, virtualFile, bytes, charset); - - if (!changed) continue; + suppressReloadDuring(() -> { + ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); + for (Map.Entry entry : mapping.entrySet()) { + VirtualFile virtualFile = entry.getKey(); + Charset charset = entry.getValue(); + if (charset == null) throw new IllegalArgumentException("Null charset for " + virtualFile + "; mapping: " + mapping); + if (virtualFile == null) { + myProjectCharset = charset; + } + else { + if (!fileIndex.isInContent(virtualFile)) continue; + if (!virtualFile.isDirectory() && !Comparing.equal(charset, oldMap.get(virtualFile))) { + Document document; + byte[] bytes; + try { + document = FileDocumentManager.getInstance().getDocument(virtualFile); + if (document == null) throw new IOException(); + bytes = virtualFile.contentsToByteArray(); } - newMap.put(virtualFile, charset); + catch (IOException e) { + continue; + } + // ask whether to reload/convert when in doubt + boolean changed = new ChangeFileEncodingAction().chosen(document, null, virtualFile, bytes, charset); + + if (!changed) continue; } + newMap.put(virtualFile, charset); } } }); @@ -306,18 +295,15 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement if (!changed.isEmpty()) { final Processor reloadProcessor = createChangeCharsetProcessor(); - tryStartReloadWithProgress(new Runnable() { - @Override - public void run() { - Set processed = new THashSet(); - next: - for (VirtualFile changedFile : changed) { - for (VirtualFile processedFile : processed) { - if (VfsUtilCore.isAncestor(processedFile, changedFile, false)) continue next; - } - processSubFiles(changedFile, reloadProcessor); - processed.add(changedFile); + tryStartReloadWithProgress(() -> { + Set processed = new THashSet(); + next: + for (VirtualFile changedFile : changed) { + for (VirtualFile processedFile : processed) { + if (VfsUtilCore.isAncestor(processedFile, changedFile, false)) continue next; } + processSubFiles(changedFile, reloadProcessor); + processed.add(changedFile); } }); } @@ -326,16 +312,13 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement } private static Processor createChangeCharsetProcessor() { - return new Processor() { - @Override - public boolean process(final VirtualFile file) { - if (!(file instanceof VirtualFileSystemEntry)) return false; - Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); - if (cachedDocument == null) return true; - ProgressManager.progress("Reloading files...", file.getPresentableUrl()); - TransactionGuard.submitTransaction(ApplicationManager.getApplication(), () -> clearAndReload(file)); - return true; - } + return file -> { + if (!(file instanceof VirtualFileSystemEntry)) return false; + Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); + if (cachedDocument == null) return true; + ProgressManager.progress("Reloading files...", file.getPresentableUrl()); + TransactionGuard.submitTransaction(ApplicationManager.getApplication(), () -> clearAndReload(file)); + return true; }; } @@ -385,36 +368,23 @@ public class EncodingProjectManagerImpl extends EncodingProjectManager implement Boolean suppress = SUPPRESS_RELOAD.get(); if (suppress == Boolean.TRUE) return false; FileDocumentManager.getInstance().saveAllDocuments(); // consider all files as unmodified - return ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - suppressReloadDuring(reloadAction); - } - }, "Reload Files", false, myProject); + return ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> suppressReloadDuring(reloadAction), "Reload Files", false, myProject); } private void reloadAllFilesUnder(@Nullable final VirtualFile root) { - tryStartReloadWithProgress(new Runnable() { - @Override - public void run() { - processSubFiles(root, new Processor() { - @Override - public boolean process(final VirtualFile file) { - if (!(file instanceof VirtualFileSystemEntry)) return true; - Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); - if (cachedDocument != null) { - ProgressManager.progress("Reloading file...", file.getPresentableUrl()); - TransactionGuard.submitTransaction(myProject, () -> reload(file)); - } - // for not loaded files deep under project, reset encoding to give them chance re-detect the right one later - else if (file.isCharsetSet() && !file.equals(root)) { - file.setCharset(null); - } - return true; - } - }); + tryStartReloadWithProgress(() -> processSubFiles(root, file -> { + if (!(file instanceof VirtualFileSystemEntry)) return true; + Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file); + if (cachedDocument != null) { + ProgressManager.progress("Reloading file...", file.getPresentableUrl()); + TransactionGuard.submitTransaction(myProject, () -> reload(file)); } - }); + // for not loaded files deep under project, reset encoding to give them chance re-detect the right one later + else if (file.isCharsetSet() && !file.equals(root)) { + file.setCharset(null); + } + return true; + })); } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java index f3951f289a49..8195af3a26c1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java @@ -59,17 +59,8 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp private final Set myContainers = ContainerUtil.newIdentityTroveSet(); @NotNull private final VirtualFileManager myVirtualFileManager; @NotNull private final MessageBus myBus; - private static final Comparator URL_COMPARATOR = SystemInfo.isFileSystemCaseSensitive ? new Comparator() { - @Override - public int compare(@NotNull String url1, @NotNull String url2) { - return url1.compareTo(url2); - } - } : new Comparator() { - @Override - public int compare(@NotNull String url1, @NotNull String url2) { - return url1.compareToIgnoreCase(url2); - } - }; + private static final Comparator URL_COMPARATOR = SystemInfo.isFileSystemCaseSensitive ? (Comparator)(url1, url2) -> url1.compareTo(url2) + : (Comparator)(url1, url2) -> url1.compareToIgnoreCase(url2); VirtualFilePointerManagerImpl(@NotNull VirtualFileManager virtualFileManager, @NotNull MessageBus bus, diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java index c3b81522c35b..c0912904d376 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java @@ -54,12 +54,7 @@ public class DefaultRemoteContentProvider extends RemoteContentProvider { @Override public void saveContent(@NotNull final Url url, @NotNull final File file, @NotNull final DownloadingCallback callback) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - downloadContent(url, file, callback); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> downloadContent(url, file, callback)); } private static void downloadContent(@NotNull final Url url, final File file, final DownloadingCallback callback) { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpVirtualFileImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpVirtualFileImpl.java index a8a1a447d66c..8609ea5df8a8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpVirtualFileImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpVirtualFileImpl.java @@ -60,14 +60,11 @@ class HttpVirtualFileImpl extends HttpVirtualFile { myFileInfo.addDownloadingListener(new FileDownloadingAdapter() { @Override public void fileDownloaded(final VirtualFile localFile) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - HttpVirtualFileImpl file = HttpVirtualFileImpl.this; - FileDocumentManager.getInstance().reloadFiles(file); - if (!localFile.getFileType().equals(myInitialFileType)) { - FileContentUtilCore.reparseFiles(file); - } + ApplicationManager.getApplication().invokeLater(() -> { + HttpVirtualFileImpl file = HttpVirtualFileImpl.this; + FileDocumentManager.getInstance().reloadFiles(file); + if (!localFile.getFileType().equals(myInitialFileType)) { + FileContentUtilCore.reparseFiles(file); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java index 7a5d57c91e8b..922244c86214 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java @@ -110,11 +110,8 @@ public class JarFileSystemImpl extends JarFileSystem { @NotNull @Override protected JarHandler getHandler(@NotNull VirtualFile entryFile) { - return VfsImplUtil.getHandler(this, entryFile, new Function() { - @Override - public JarHandler fun(String localPath) { - return new JarHandler(localPath); - } + return VfsImplUtil.getHandler(this, entryFile, localPath -> { + return new JarHandler(localPath); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java index 4a2fed3d442c..c8a39f9af252 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java @@ -303,19 +303,9 @@ public class JarHandler extends ZipHandler { assert info != null; ourCachedLibraryInfo = info; - FlushingDaemon.everyFiveSeconds(new Runnable() { - @Override - public void run() { - flushCachedLibraryInfos(); - } - }); + FlushingDaemon.everyFiveSeconds(() -> flushCachedLibraryInfos()); - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - flushCachedLibraryInfos(); - } - }); + ShutDownTracker.getInstance().registerShutdownTask(() -> flushCachedLibraryInfos()); } @NotNull diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java index 0e28e42813f1..c61781f6a09a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java @@ -376,12 +376,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem { } } - auxNotifyCompleted(new ThrowableConsumer() { - @Override - public void consume(LocalFileOperationsHandler handler) throws IOException { - handler.createDirectory(parent, dir); - } - }); + auxNotifyCompleted(handler -> handler.createDirectory(parent, dir)); return new FakeVirtualFile(parent, dir); } @@ -412,12 +407,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem { } } - auxNotifyCompleted(new ThrowableConsumer() { - @Override - public void consume(LocalFileOperationsHandler handler) throws IOException { - handler.createFile(parent, file); - } - }); + auxNotifyCompleted(handler -> handler.createFile(parent, file)); return new FakeVirtualFile(parent, file); } @@ -435,12 +425,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem { } } - auxNotifyCompleted(new ThrowableConsumer() { - @Override - public void consume(LocalFileOperationsHandler handler) throws IOException { - handler.delete(file); - } - }); + auxNotifyCompleted(handler -> handler.delete(file)); } @Override @@ -553,12 +538,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem { } } - auxNotifyCompleted(new ThrowableConsumer() { - @Override - public void consume(LocalFileOperationsHandler handler) throws IOException { - handler.move(file, newParent); - } - }); + auxNotifyCompleted(handler -> handler.move(file, newParent)); } @Override @@ -595,12 +575,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem { } } - auxNotifyCompleted(new ThrowableConsumer() { - @Override - public void consume(LocalFileOperationsHandler handler) throws IOException { - handler.rename(file, newName); - } - }); + auxNotifyCompleted(handler -> handler.rename(file, newName)); } @NotNull @@ -650,12 +625,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem { } } - auxNotifyCompleted(new ThrowableConsumer() { - @Override - public void consume(LocalFileOperationsHandler handler) throws IOException { - handler.copy(file, newParent, copyName); - } - }); + auxNotifyCompleted(handler -> handler.copy(file, newParent, copyName)); return new FakeVirtualFile(newParent, copyName); } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java index 8f9f1c733468..a664ba649912 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java @@ -158,24 +158,18 @@ public final class LocalFileSystemImpl extends LocalFileSystemBase implements Ap if (currentNode.watchRequest.isToWatchRecursively() && !currentNode.nodes.isEmpty()) { // since we are watching this node recursively, we can remove it's children - visitTree(currentNode, new Consumer() { - @Override - public void consume(final TreeNode node) { - if (node.watchRequest != null) { - node.watchRequest.myDominated = true; - } + visitTree(currentNode, node -> { + if (node.watchRequest != null) { + node.watchRequest.myDominated = true; } }); currentNode.nodes.clear(); } } - visitTree(rootNode, new Consumer() { - @Override - public void consume(final TreeNode node) { - if (node.watchRequest != null) { - result.add(node.watchRequest); - } + visitTree(rootNode, node -> { + if (node.watchRequest != null) { + result.add(node.watchRequest); } }); myNormalizedTree = rootNode; diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshProgress.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshProgress.java index 2400415f60d3..a430a8f1ee5e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshProgress.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshProgress.java @@ -60,24 +60,22 @@ public class RefreshProgress extends ProgressIndicatorBase { private void updateIndicators(final boolean start) { // wrapping in invokeLater here reduces the number of events posted to EDT in case of multiple IDE frames - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - if (ApplicationManager.getApplication().isDisposed()) return; + UIUtil.invokeLaterIfNeeded(() -> { + if (ApplicationManager.getApplication().isDisposed()) return; - WindowManager windowManager = WindowManager.getInstance(); - if (windowManager == null) return; + WindowManager windowManager = WindowManager.getInstance(); + if (windowManager == null) return; - Project[] projects = ProjectManager.getInstance().getOpenProjects(); - if (projects.length == 0) projects = NULL_ARRAY; - for (Project project : projects) { - StatusBarEx statusBar = (StatusBarEx)windowManager.getStatusBar(project); - if (statusBar != null) { - if (start) { - statusBar.startRefreshIndication(myMessage); - } - else { - statusBar.stopRefreshIndication(); - } + Project[] projects = ProjectManager.getInstance().getOpenProjects(); + if (projects.length == 0) projects = NULL_ARRAY; + for (Project project : projects) { + StatusBarEx statusBar = (StatusBarEx)windowManager.getStatusBar(project); + if (statusBar != null) { + if (start) { + statusBar.startRefreshIndication(myMessage); + } + else { + statusBar.stopRefreshIndication(); } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java index cb5744b16c3b..63cf2969859c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java @@ -206,15 +206,12 @@ public class VfsImplUtil { ourHandlers.put(localPath, record); final String finalRootPath = localPath; - forEachDirectoryComponent(localPath, new Consumer() { - @Override - public void consume(String containingDirectoryPath) { - Set handlers = ourDominatorsMap.get(containingDirectoryPath); - if (handlers == null) { - ourDominatorsMap.put(containingDirectoryPath, handlers = ContainerUtil.newTroveSet()); - } - handlers.add(finalRootPath); + forEachDirectoryComponent(localPath, containingDirectoryPath -> { + Set handlers = ourDominatorsMap.get(containingDirectoryPath); + if (handlers == null) { + ourDominatorsMap.put(containingDirectoryPath, handlers = ContainerUtil.newTroveSet()); } + handlers.add(finalRootPath); }); } handler = record.second; @@ -290,13 +287,10 @@ public class VfsImplUtil { Pair handlerPair = ourHandlers.remove(path); if (handlerPair != null) { handlerPair.second.dispose(); - forEachDirectoryComponent(path, new Consumer() { - @Override - public void consume(String containingDirectoryPath) { - Set handlers = ourDominatorsMap.get(containingDirectoryPath); - if (handlers != null && handlers.remove(path) && handlers.isEmpty()) { - ourDominatorsMap.remove(containingDirectoryPath); - } + forEachDirectoryComponent(path, containingDirectoryPath -> { + Set handlers = ourDominatorsMap.get(containingDirectoryPath); + if (handlers != null && handlers.remove(path) && handlers.isEmpty()) { + ourDominatorsMap.remove(containingDirectoryPath); } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java index 415b42f9d3a0..fca58a026646 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java @@ -308,23 +308,20 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { result = ArrayUtil.EMPTY_INT_ARRAY; } else { - Arrays.sort(childrenIds, new Comparator() { - @Override - public int compare(FSRecords.NameId o1, FSRecords.NameId o2) { - CharSequence name1 = o1.name; - CharSequence name2 = o2.name; - int cmp = compareNames(name1, name2, ignoreCase); - if (cmp == 0 && name1 != name2) { - LOG.error(ourPersistence + " returned duplicate file names("+name1+","+name2+")" + - " ignoreCase: "+ignoreCase+ - " SystemInfo.isFileSystemCaseSensitive: "+ SystemInfo.isFileSystemCaseSensitive+ - " SystemInfo.OS: "+ SystemInfo.OS_NAME+" "+SystemInfo.OS_VERSION+ - " wasChildrenLoaded: "+wasChildrenLoaded+ - " in the dir: "+VirtualDirectoryImpl.this+";" + - " children: "+Arrays.toString(childrenIds)); - } - return cmp; + Arrays.sort(childrenIds, (o1, o2) -> { + CharSequence name1 = o1.name; + CharSequence name2 = o2.name; + int cmp = compareNames(name1, name2, ignoreCase); + if (cmp == 0 && name1 != name2) { + LOG.error(ourPersistence + " returned duplicate file names("+name1+","+name2+")" + + " ignoreCase: "+ignoreCase+ + " SystemInfo.isFileSystemCaseSensitive: "+ SystemInfo.isFileSystemCaseSensitive+ + " SystemInfo.OS: "+ SystemInfo.OS_NAME+" "+SystemInfo.OS_VERSION+ + " wasChildrenLoaded: "+wasChildrenLoaded+ + " in the dir: "+VirtualDirectoryImpl.this+";" + + " children: "+Arrays.toString(childrenIds)); } + return cmp; }); TIntHashSet prevChildren = new TIntHashSet(myData.myChildrenIds); result = new int[childrenIds.length]; @@ -373,32 +370,24 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { } } - private static final Function verboseToString = new Function() { - @Override - public String fun(VirtualFileSystemEntry file) { - if (file == null) return "null"; - return file + " (name: '" + file.getName() - + "', " + file.getClass() - + ", parent: "+file.getParent() - + "; id: "+file.getId() - + "; FS: " +file.getFileSystem() - + "; delegate.attrs: " +file.getFileSystem().getAttributes(file) - + "; caseSensitive: " +file.getFileSystem().isCaseSensitive() - + "; canonical: " +file.getFileSystem().getCanonicallyCasedName(file) - + ") "; - } + private static final Function verboseToString = file -> { + if (file == null) return "null"; + return file + " (name: '" + file.getName() + + "', " + file.getClass() + + ", parent: "+file.getParent() + + "; id: "+file.getId() + + "; FS: " +file.getFileSystem() + + "; delegate.attrs: " +file.getFileSystem().getAttributes(file) + + "; caseSensitive: " +file.getFileSystem().isCaseSensitive() + + "; canonical: " +file.getFileSystem().getCanonicallyCasedName(file) + + ") "; }; private static void error(String message, VirtualFileSystemEntry[] array, Object... details) { String children = StringUtil.join(array, verboseToString, ","); throw new AssertionError( message + "; children: " + children + "\nDetails: " + ContainerUtil.map( - details, new Function() { - @Override - public Object fun(Object o) { - return o instanceof Object[] ? Arrays.toString((Object[])o) : o; - } - })); + details, o -> o instanceof Object[] ? Arrays.toString((Object[])o) : o)); } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java index 24ac3accbc49..c77d6d8bc566 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java @@ -324,26 +324,23 @@ public class FSRecords implements Forceable { } } catch (final IOException e1) { - final Runnable warnAndShutdown = new Runnable() { - @Override - public void run() { - if (ApplicationManager.getApplication().isUnitTestMode()) { - //noinspection CallToPrintStackTrace - e1.printStackTrace(); + final Runnable warnAndShutdown = () -> { + if (ApplicationManager.getApplication().isUnitTestMode()) { + //noinspection CallToPrintStackTrace + e1.printStackTrace(); + } + else { + final String message = "Files in " + basePath.getPath() + " are locked.\n" + + ApplicationNamesInfo.getInstance().getProductName() + " will not be able to start up."; + if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { + JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), message, "Fatal Error", JOptionPane.ERROR_MESSAGE); } else { - final String message = "Files in " + basePath.getPath() + " are locked.\n" + - ApplicationNamesInfo.getInstance().getProductName() + " will not be able to start up."; - if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { - JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), message, "Fatal Error", JOptionPane.ERROR_MESSAGE); - } - else { - //noinspection UseOfSystemOutOrSystemErr - System.err.println(message); - } + //noinspection UseOfSystemOutOrSystemErr + System.err.println(message); } - Runtime.getRuntime().halt(1); } + Runtime.getRuntime().halt(1); }; if (EventQueue.isDispatchThread()) { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java index 3a3231de0f5e..3c11eb142bd9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java @@ -64,22 +64,12 @@ public class PersistentFSImpl extends PersistentFS implements ApplicationCompone private final AtomicBoolean myShutDown = new AtomicBoolean(false); @SuppressWarnings({"FieldCanBeLocal", "unused"}) - private final LowMemoryWatcher myWatcher = LowMemoryWatcher.register(new Runnable() { - @Override - public void run() { - clearIdCache(); - } - }); + private final LowMemoryWatcher myWatcher = LowMemoryWatcher.register(() -> clearIdCache()); private volatile int myStructureModificationCount; public PersistentFSImpl(@NotNull MessageBus bus) { myEventBus = bus; - ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { - performShutdown(); - } - }); + ShutDownTracker.getInstance().registerShutdownTask(() -> performShutdown()); } @Override @@ -136,11 +126,8 @@ public class PersistentFSImpl extends PersistentFS implements ApplicationCompone if (!areChildrenLoaded(id)) { nameIds = persistAllChildren(file, id, nameIds); } - return ContainerUtil.map2Array(nameIds, String.class, new Function() { - @Override - public String fun(FSRecords.NameId id) { - return id.name.toString(); - } + return ContainerUtil.map2Array(nameIds, String.class, id1 -> { + return id1.name.toString(); }); } @@ -693,12 +680,7 @@ public class PersistentFSImpl extends PersistentFS implements ApplicationCompone } } - @NotNull private static final Comparator DEPTH_COMPARATOR = new Comparator() { - @Override - public int compare(@NotNull final EventWrapper o1, @NotNull final EventWrapper o2) { - return o1.event.getFileDepth() - o2.event.getFileDepth(); - } - }; + @NotNull private static final Comparator DEPTH_COMPARATOR = (o1, o2) -> o1.event.getFileDepth() - o2.event.getFileDepth(); @NotNull private static List validateEvents(@NotNull List events) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/CommandProcessor.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/CommandProcessor.java index 746030e68abd..7356c740004e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/CommandProcessor.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/CommandProcessor.java @@ -81,11 +81,9 @@ public final class CommandProcessor implements Runnable { final boolean queueNext = myCommandCount > 0; Application application = ApplicationManager.getApplication(); ModalityState modalityState = Registry.is("ide.perProjectModality") ? ModalityState.defaultModalityState() : ModalityState.NON_MODAL; - application.getInvokator().invokeLater(command, modalityState, expire == null ? application.getDisposed() : expire).doWhenDone(new Runnable() { - public void run() { - if (queueNext) { - CommandProcessor.this.run(); - } + application.getInvokator().invokeLater(command, modalityState, expire == null ? application.getDisposed() : expire).doWhenDone(() -> { + if (queueNext) { + CommandProcessor.this.run(); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FloatingDecorator.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FloatingDecorator.java index 4a52861a8e64..c75f22821f06 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FloatingDecorator.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FloatingDecorator.java @@ -148,12 +148,7 @@ public final class FloatingDecorator extends JDialog { Disposer.dispose(myDisposable); } else { if (isShowing()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - show(); - } - }); + SwingUtilities.invokeLater(() -> show()); } } super.dispose(); @@ -176,16 +171,14 @@ public final class FloatingDecorator extends JDialog { myFrameTicker.addRequest(myAnimator,DELAY); }else{ // make window transparent myDelayAlarm.addRequest( - new Runnable(){ - public void run(){ - myFrameTicker.cancelAllRequests(); - myStartRatio=getCurrentAlphaRatio(); - if(myCurrentFrame>0){ - myCurrentFrame=TOTAL_FRAME_COUNT-myCurrentFrame; - } - myEndRatio=uiSettings.ALPHA_MODE_RATIO; - myFrameTicker.addRequest(myAnimator,DELAY); + () -> { + myFrameTicker.cancelAllRequests(); + myStartRatio=getCurrentAlphaRatio(); + if(myCurrentFrame>0){ + myCurrentFrame=TOTAL_FRAME_COUNT-myCurrentFrame; } + myEndRatio=uiSettings.ALPHA_MODE_RATIO; + myFrameTicker.addRequest(myAnimator,DELAY); }, uiSettings.ALPHA_MODE_DELAY ); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java index 7c8b0847c6a7..751a0f2462f5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java @@ -217,24 +217,16 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { } }); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - resetUnforcedCommand(command); - _requestFocus(command, forced, result); - } + SwingUtilities.invokeLater(() -> { + resetUnforcedCommand(command); + _requestFocus(command, forced, result); }); } else { _requestFocus(command, forced, result); } - result.doWhenProcessed(new Runnable() { - @Override - public void run() { - restartIdleAlarm(); - } - }); + result.doWhenProcessed(() -> restartIdleAlarm()); return result; } @@ -258,12 +250,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { } private void _requestFocus(@NotNull final FocusCommand command, final boolean forced, @NotNull final ActionCallback result) { - result.doWhenProcessed(new Runnable() { - @Override - public void run() { - maybeRemoveFocusActivity(); - } - }); + result.doWhenProcessed(() -> maybeRemoveFocusActivity()); if (checkForRejectOrByPass(command, forced, result)) return; @@ -275,62 +262,45 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { setLastEffectiveForcedRequest(command); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (checkForRejectOrByPass(command, forced, result)) return; + SwingUtilities.invokeLater(() -> { + if (checkForRejectOrByPass(command, forced, result)) return; - if (myRequestFocusCmd == command) { - final TimedOutCallback focusTimeout = - new TimedOutCallback(Registry.intValue("actionSystem.commandProcessingTimeout"), - "Focus command timed out, cmd=" + command, command.getAllocation(), true) { - @Override - protected void onTimeout() { - forceFinishFocusSettleDown(command, result); - } - }; + if (myRequestFocusCmd == command) { + final TimedOutCallback focusTimeout = + new TimedOutCallback(Registry.intValue("actionSystem.commandProcessingTimeout"), + "Focus command timed out, cmd=" + command, command.getAllocation(), true) { + @Override + protected void onTimeout() { + forceFinishFocusSettleDown(command, result); + } + }; + if (command.invalidatesRequestors()) { + myCmdTimestamp++; + } + revalidateFurtherRequestors(); + if (forced) { if (command.invalidatesRequestors()) { - myCmdTimestamp++; + myForcedCmdTimestamp++; } revalidateFurtherRequestors(); - if (forced) { - if (command.invalidatesRequestors()) { - myForcedCmdTimestamp++; - } - revalidateFurtherRequestors(); - } + } - command.setForced(forced); - command.run().doWhenDone(new Runnable() { - @Override - public void run() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - resetCommand(command, false); - result.setDone(); - } - }); - } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - result.setRejected(); - resetCommand(command, true); - } - }).doWhenProcessed(new Runnable() { - @Override - public void run() { - if (forced) { - myForcedFocusRequestsAlarm.addRequest(new SetLastEffectiveRunnable(), 250); - } - } - }).notify(focusTimeout); - } - else { - rejectCommand(command, result); - } + command.setForced(forced); + command.run().doWhenDone(() -> UIUtil.invokeLaterIfNeeded(() -> { + resetCommand(command, false); + result.setDone(); + })).doWhenRejected(() -> { + result.setRejected(); + resetCommand(command, true); + }).doWhenProcessed(() -> { + if (forced) { + myForcedFocusRequestsAlarm.addRequest(new SetLastEffectiveRunnable(), 250); + } + }).notify(focusTimeout); + } + else { + rejectCommand(command, result); } }); } @@ -477,12 +447,9 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { @Override public void dispatch(@NotNull final List events) { - doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - myToDispatchOnDone.addAll(events); - restartIdleAlarm(); - } + doWhenFocusSettlesDown(() -> { + myToDispatchOnDone.addAll(events); + restartIdleAlarm(); }); } } @@ -494,34 +461,31 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { @Override public void doWhenFocusSettlesDown(@NotNull final Runnable runnable) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (isFlushingIdleRequests()) { - myIdleRequests.add(runnable); - return; - } + UIUtil.invokeLaterIfNeeded(() -> { + if (isFlushingIdleRequests()) { + myIdleRequests.add(runnable); + return; + } - if (myRunContext != null) { - flushRequest(runnable); - return; - } + if (myRunContext != null) { + flushRequest(runnable); + return; + } - final boolean needsRestart = isIdleQueueEmpty(); - if (myIdleRequests.contains(runnable)) { - myIdleRequests.remove(runnable); - myIdleRequests.add(runnable); - } else { - myIdleRequests.add(runnable); - } + final boolean needsRestart = isIdleQueueEmpty(); + if (myIdleRequests.contains(runnable)) { + myIdleRequests.remove(runnable); + myIdleRequests.add(runnable); + } else { + myIdleRequests.add(runnable); + } - if (canFlushIdleRequests()) { - flushIdleRequests(); - } - else { - if (needsRestart) { - restartIdleAlarm(); - } + if (canFlushIdleRequests()) { + flushIdleRequests(); + } + else { + if (needsRestart) { + restartIdleAlarm(); } } }); @@ -774,19 +738,13 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { final SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:ss:SSS", Locale.US); LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tStarted: " + id); done = new ActionCallback(); - callback.doWhenDone(new Runnable() { - @Override - public void run() { - done.setDone(); - LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tDone: " + id); - } + callback.doWhenDone(() -> { + done.setDone(); + LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tDone: " + id); }); - callback.doWhenRejected(new Runnable() { - @Override - public void run() { - done.setRejected(); - LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tRejected: " + id); - } + callback.doWhenRejected(() -> { + done.setRejected(); + LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tRejected: " + id); }); } assertDispatchThread(); @@ -800,14 +758,11 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { return "Time: " + (System.currentTimeMillis() - currentTime); } }, - true).doWhenProcessed(new Runnable() { - @Override - public void run() { - if (myTypeAheadRequestors.remove(done)) { - restartIdleAlarm(); - } - } - })); + true).doWhenProcessed(() -> { + if (myTypeAheadRequestors.remove(done)) { + restartIdleAlarm(); + } + })); } private boolean isFlushingIdleRequests() { @@ -907,12 +862,9 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { @Override public void revalidateFocus(@NotNull final ExpirableRunnable runnable) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myFocusRevalidator = runnable; - restartIdleAlarm(); - } + SwingUtilities.invokeLater(() -> { + myFocusRevalidator = runnable; + restartIdleAlarm(); }); } @@ -979,15 +931,12 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { final Window window = UIUtil.getParentOfType(Window.class, c); if (window != null && window.isShowing()) { - doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - if (ApplicationManager.getApplication().isActive()) { - if (window instanceof JFrame && ((JFrame)window).getState() == Frame.ICONIFIED) { - ((JFrame)window).setState(Frame.NORMAL); - } else { - window.toFront(); - } + doWhenFocusSettlesDown(() -> { + if (ApplicationManager.getApplication().isActive()) { + if (window instanceof JFrame && ((JFrame)window).getState() == Frame.ICONIFIED) { + ((JFrame)window).setState(Frame.NORMAL); + } else { + window.toFront(); } } }); @@ -1012,12 +961,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { @Override public ActionCallback requestFocus(@NotNull Component c, boolean forced) { final ActionCallback result = isExpired() ? ActionCallback.REJECTED : myManager.requestFocus(c, forced); - result.doWhenProcessed(new Runnable() { - @Override - public void run() { - Disposer.dispose(FurtherRequestor.this); - } - }); + result.doWhenProcessed(() -> Disposer.dispose(FurtherRequestor.this)); return result; } @@ -1106,12 +1050,9 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { if (policy != null) { policy.setNoDefaultComponent(true, FocusManagerImpl.this); } - requestFocus(c, false).doWhenProcessed(new Runnable() { - @Override - public void run() { - if (policy != null) { - policy.setNoDefaultComponent(false, FocusManagerImpl.this); - } + requestFocus(c, false).doWhenProcessed(() -> { + if (policy != null) { + policy.setNoDefaultComponent(false, FocusManagerImpl.this); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeBackgroundUtil.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeBackgroundUtil.java index 79abf2d64467..e723e5d84ee3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeBackgroundUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeBackgroundUtil.java @@ -147,12 +147,9 @@ public class IdeBackgroundUtil { public static void createTemporaryBackgroundTransform(JPanel root, String tmp, Disposable disposable) { PaintersHelper paintersHelper = new PaintersHelper(root); PaintersHelper.initWallpaperPainter(tmp, paintersHelper); - Disposer.register(disposable, JBSwingUtilities.addGlobalCGTransform(new PairFunction() { - @Override - public Graphics2D fun(JComponent t, Graphics2D v) { - if (!UIUtil.isAncestor(root, t)) return v; - return MyGraphics.wrap(v, paintersHelper, t); - } + Disposer.register(disposable, JBSwingUtilities.addGlobalCGTransform((t, v) -> { + if (!UIUtil.isAncestor(root, t)) return v; + return MyGraphics.wrap(v, paintersHelper, t); })); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java index 3e9490c5ac5e..b60c1c27faf8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java @@ -233,12 +233,7 @@ public class IdeFrameImpl extends JFrame implements IdeFrameEx, AccessibleContex @Override public void show() { super.show(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - setFocusableWindowState(true); - } - }); + SwingUtilities.invokeLater(() -> setFocusableWindowState(true)); } /** @@ -413,15 +408,12 @@ public class IdeFrameImpl extends JFrame implements IdeFrameEx, AccessibleContex super.setVisible(b); if (b && myRestoreFullScreen) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - toggleFullScreen(true); - if (SystemInfo.isMacOSLion) { - setBounds(ScreenUtil.getScreenRectangle(getLocationOnScreen())); - } - myRestoreFullScreen = false; + SwingUtilities.invokeLater(() -> { + toggleFullScreen(true); + if (SystemInfo.isMacOSLion) { + setBounds(ScreenUtil.getScreenRectangle(getLocationOnScreen())); } + myRestoreFullScreen = false; }); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java index 7a6693086222..a92c02840950 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeGlassPaneImpl.java @@ -50,19 +50,16 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent private static final String PREPROCESSED_CURSOR_KEY = "SuperCursor"; private final List myMouseListeners = new ArrayList(); - private final Set mySortedMouseListeners = new TreeSet(new Comparator() { - @Override - public int compare(EventListener o1, EventListener o2) { - double weight1 = 0; - double weight2 = 0; - if (o1 instanceof Weighted) { - weight1 = ((Weighted)o1).getWeight(); - } - if (o2 instanceof Weighted) { - weight2 = ((Weighted)o2).getWeight(); - } - return weight1 > weight2 ? 1 : weight1 < weight2 ? -1 : myMouseListeners.indexOf(o1) - myMouseListeners.indexOf(o2); + private final Set mySortedMouseListeners = new TreeSet((o1, o2) -> { + double weight1 = 0; + double weight2 = 0; + if (o1 instanceof Weighted) { + weight1 = ((Weighted)o1).getWeight(); } + if (o2 instanceof Weighted) { + weight2 = ((Weighted)o2).getWeight(); + } + return weight1 > weight2 ? 1 : weight1 < weight2 ? -1 : myMouseListeners.indexOf(o1) - myMouseListeners.indexOf(o2); }); private final JRootPane myRootPane; @@ -442,11 +439,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent activateIfNeeded(); Disposer.register(parent, new Disposable() { public void dispose() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - removeListener(listener); - } - }); + UIUtil.invokeLaterIfNeeded(() -> removeListener(listener)); } }); } @@ -524,11 +517,7 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent activateIfNeeded(); Disposer.register(parent, new Disposable() { public void dispose() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - removePainter(painter); - } - }); + SwingUtilities.invokeLater(() -> removePainter(painter)); } }); } @@ -543,24 +532,14 @@ public class IdeGlassPaneImpl extends JPanel implements IdeGlassPaneEx, IdeEvent protected void addImpl(Component comp, Object constraints, int index) { super.addImpl(comp, constraints, index); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - activateIfNeeded(); - } - }); + SwingUtilities.invokeLater(() -> activateIfNeeded()); } @Override public void remove(final Component comp) { super.remove(comp); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - deactivateIfNeeded(); - } - }); + SwingUtilities.invokeLater(() -> deactivateIfNeeded()); } public boolean isInModalContext() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java index 34161f56edcc..7516352675e2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java @@ -192,14 +192,11 @@ public class IdeMenuBar extends JMenuBar implements IdeEventQueue.EventDispatche revalidate(); repaint(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - JMenu menu = getMenu(getSelectionModel().getSelectedIndex()); - if (menu.isPopupMenuVisible()) { - menu.setPopupMenuVisible(false); - menu.setPopupMenuVisible(true); - } + SwingUtilities.invokeLater(() -> { + JMenu menu = getMenu(getSelectionModel().getSelectedIndex()); + if (menu.isPopupMenuVisible()) { + menu.setPopupMenuVisible(false); + menu.setPopupMenuVisible(true); } }); } @@ -574,11 +571,7 @@ public class IdeMenuBar extends JMenuBar implements IdeEventQueue.EventDispatche public static void installAppMenuIfNeeded(@NotNull final JFrame frame) { if (SystemInfo.isLinux && Registry.is("linux.native.menu") && "Unity".equals(System.getenv("XDG_CURRENT_DESKTOP"))) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - ApplicationMenu.tryInstall(frame); - } - }); + SwingUtilities.invokeLater(() -> ApplicationMenu.tryInstall(frame)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/InternalDecorator.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/InternalDecorator.java index e81264ebef8b..4b67e604e91a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/InternalDecorator.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/InternalDecorator.java @@ -103,11 +103,8 @@ public final class InternalDecorator extends JPanel implements Queryable, DataPr setFocusable(false); setFocusTraversalPolicy(new LayoutFocusTraversalPolicy()); - myHeader = new ToolWindowHeader(toolWindow, info, new Producer() { - @Override - public ActionGroup produce() { - return /*createGearPopupGroup()*/createPopupGroup(true); - } + myHeader = new ToolWindowHeader(toolWindow, info, () -> { + return /*createGearPopupGroup()*/createPopupGroup(true); }) { @Override protected boolean isActive() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java index 15f30a184924..e47110482a5b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java @@ -35,13 +35,11 @@ public class LibraryDependentToolWindowManager extends AbstractProjectComponent } }; - StartupManager.getInstance(myProject).runWhenProjectIsInitialized(new Runnable() { - public void run() { - if (!myProject.isDisposed()) { - checkToolWindowStatuses(myProject); - final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); - connection.subscribe(ProjectTopics.PROJECT_ROOTS, rootListener); - } + StartupManager.getInstance(myProject).runWhenProjectIsInitialized(() -> { + if (!myProject.isDisposed()) { + checkToolWindowStatuses(myProject); + final MessageBusConnection connection = myProject.getMessageBus().connect(myProject); + connection.subscribe(ProjectTopics.PROJECT_ROOTS, rootListener); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/Stripe.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/Stripe.java index 332f001fb6df..c6b12a23d46f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/Stripe.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/Stripe.java @@ -494,12 +494,7 @@ final class Stripe extends JPanel { myManager.setSideToolAndAnchor(info.getId(), ToolWindowAnchor.get(myAnchor), myLastLayoutData.dragInsertPosition, myLastLayoutData.dragToSide); - myManager.invokeLater(new Runnable() { - @Override - public void run() { - resetDrop(); - } - }); + myManager.invokeLater(() -> resetDrop()); } public void resetDrop() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java index 1bb565448564..3e1cb7106ea9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java @@ -227,12 +227,8 @@ public abstract class ToolWindowHeader extends JPanel implements Disposable, UIS westPanel.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(final MouseEvent e) { - Runnable runnable = new Runnable() { - @Override - public void run() { - ToolWindowHeader.this.dispatchEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, ToolWindowHeader.this)); - } - }; + Runnable runnable = + () -> ToolWindowHeader.this.dispatchEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, ToolWindowHeader.this)); //noinspection SSBasedInspection SwingUtilities.invokeLater(runnable); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java index e12451f3c641..92f54608885c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java @@ -204,20 +204,12 @@ public final class ToolWindowImpl implements ToolWindowEx { myToolWindowManager.activateToolWindow(myId, forced, autoFocusContents); - getActivation().doWhenDone(new Runnable() { - @Override - public void run() { - myToolWindowManager.invokeLater(new Runnable() { - @Override - public void run() { - if (runnable != null) { - runnable.run(); - } - UiActivityMonitor.getInstance().removeActivity(myToolWindowManager.getProject(), activity); - } - }); + getActivation().doWhenDone(() -> myToolWindowManager.invokeLater(() -> { + if (runnable != null) { + runnable.run(); } - }); + UiActivityMonitor.getInstance().removeActivity(myToolWindowManager.getProject(), activity); + })); } @Override @@ -231,24 +223,18 @@ public final class ToolWindowImpl implements ToolWindowEx { @Override public ActionCallback getReady(@NotNull final Object requestor) { final ActionCallback result = new ActionCallback(); - myShowing.getReady(this).doWhenDone(new Runnable() { - @Override - public void run() { - ArrayList cmd = new ArrayList(); - cmd.add(new FinalizableCommand(null) { - @Override - public void run() { - IdeFocusManager.getInstance(myToolWindowManager.getProject()).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - if (myContentManager.isDisposed()) return; - myContentManager.getReady(requestor).notify(result); - } - }); - } - }); - myToolWindowManager.execute(cmd); - } + myShowing.getReady(this).doWhenDone(() -> { + ArrayList cmd = new ArrayList(); + cmd.add(new FinalizableCommand(null) { + @Override + public void run() { + IdeFocusManager.getInstance(myToolWindowManager.getProject()).doWhenFocusSettlesDown(() -> { + if (myContentManager.isDisposed()) return; + myContentManager.getReady(requestor).notify(result); + }); + } + }); + myToolWindowManager.execute(cmd); }); return result; } @@ -258,12 +244,7 @@ public final class ToolWindowImpl implements ToolWindowEx { ApplicationManager.getApplication().assertIsDispatchThread(); myToolWindowManager.showToolWindow(myId); if (runnable != null) { - getActivation().doWhenDone(new Runnable() { - @Override - public void run() { - myToolWindowManager.invokeLater(runnable); - } - }); + getActivation().doWhenDone(() -> myToolWindowManager.invokeLater(runnable)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java index 3cdb4464cc8c..72169ddc01f4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java @@ -132,12 +132,9 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements private KeyState myCurrentState = KeyState.waiting; private final Alarm myWaiterForSecondPress = new Alarm(); - private final Runnable mySecondPressRunnable = new Runnable() { - @Override - public void run() { - if (myCurrentState != KeyState.hold) { - resetHoldState(); - } + private final Runnable mySecondPressRunnable = () -> { + if (myCurrentState != KeyState.hold) { + resetHoldState(); } }; private final PropertyChangeListener myFocusListener; @@ -151,12 +148,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements } private final Alarm myUpdateHeadersAlarm = new Alarm(); - private final Runnable myUpdateHeadersRunnable = new Runnable() { - @Override - public void run() { - updateToolWindowHeaders(); - } - }; + private final Runnable myUpdateHeadersRunnable = () -> updateToolWindowHeaders(); /** * invoked by reflection @@ -566,12 +558,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements runnable.run(); } else { - UiNotifyConnector.doWhenFirstShown(label, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(runnable); - } - }); + UiNotifyConnector.doWhenFirstShown(label, () -> ApplicationManager.getApplication().invokeLater(runnable)); } } @@ -683,50 +670,44 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements private void activateEditorComponentImpl(List commandList, final boolean forced) { final String active = getActiveToolWindowId(); // Now we have to request focus into most recent focused editor - appendRequestFocusInEditorComponentCmd(commandList, forced).doWhenDone(new Runnable() { - @Override - public void run() { - final ArrayList commandList = new ArrayList(); + appendRequestFocusInEditorComponentCmd(commandList, forced).doWhenDone(() -> { + final ArrayList commandList12 = new ArrayList(); - if (LOG.isDebugEnabled()) { - LOG.debug("editor activated"); - } - deactivateWindows(null, commandList); - myActiveStack.clear(); - - execute(commandList); + if (LOG.isDebugEnabled()) { + LOG.debug("editor activated"); } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - if (forced) { - getFocusManagerImpl(myProject).requestFocus(new FocusCommand() { - @NotNull - @Override - public ActionCallback run() { - final ArrayList commandList = new ArrayList(); + deactivateWindows(null, commandList12); + myActiveStack.clear(); - final WindowInfoImpl toReactivate = getInfo(active); - final boolean reactivateLastActive = toReactivate != null && !isToHideOnDeactivation(toReactivate); - deactivateWindows(reactivateLastActive ? active : null, commandList); - execute(commandList); + execute(commandList12); + }).doWhenRejected(() -> { + if (forced) { + getFocusManagerImpl(myProject).requestFocus(new FocusCommand() { + @NotNull + @Override + public ActionCallback run() { + final ArrayList commandList1 = new ArrayList(); - if (reactivateLastActive) { - activateToolWindow(active, false, true); - } - else { - if (active != null) { - myActiveStack.remove(active, false); - } + final WindowInfoImpl toReactivate = getInfo(active); + final boolean reactivateLastActive = toReactivate != null && !isToHideOnDeactivation(toReactivate); + deactivateWindows(reactivateLastActive ? active : null, commandList1); + execute(commandList1); - if (!myActiveStack.isEmpty()) { - activateToolWindow(myActiveStack.peek(), false, true); - } - } - return ActionCallback.DONE; + if (reactivateLastActive) { + activateToolWindow(active, false, true); } - }, false); - } + else { + if (active != null) { + myActiveStack.remove(active, false); + } + + if (!myActiveStack.isEmpty()) { + activateToolWindow(myActiveStack.peek(), false, true); + } + } + return ActionCallback.DONE; + } + }, false); } }); } @@ -1488,18 +1469,12 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(text.replace("\n", "
      "), icon, type.getPopupBackground(), listenerWrapper) .setHideOnClickOutside(false).setHideOnFrameResize(false).createBalloon(); - FrameStateManager.getInstance().getApplicationActive().doWhenDone(new Runnable() { - @Override - public void run() { - final Alarm alarm = new Alarm(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - ((BalloonImpl)balloon).setHideOnClickOutside(true); - Disposer.dispose(alarm); - } - }, 100); - } + FrameStateManager.getInstance().getApplicationActive().doWhenDone(() -> { + final Alarm alarm = new Alarm(); + alarm.addRequest(() -> { + ((BalloonImpl)balloon).setHideOnClickOutside(true); + Disposer.dispose(alarm); + }, 100); }); listenerWrapper.myBalloon = balloon; myWindow2Balloon.put(toolWindowId, balloon); @@ -1527,61 +1502,53 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements type); if (button == null) return; - final Runnable show = new Runnable() { - @Override - public void run() { - if (button.isShowing()) { - PositionTracker tracker = new PositionTracker(button) { - @Override - @Nullable - public RelativePoint recalculateLocation(Balloon object) { - Stripe twStripe = myToolWindowsPane.getStripeFor(toolWindowId); - StripeButton twButton = twStripe != null ? twStripe.getButtonFor(toolWindowId) : null; + final Runnable show = () -> { + if (button.isShowing()) { + PositionTracker tracker = new PositionTracker(button) { + @Override + @Nullable + public RelativePoint recalculateLocation(Balloon object) { + Stripe twStripe = myToolWindowsPane.getStripeFor(toolWindowId); + StripeButton twButton = twStripe != null ? twStripe.getButtonFor(toolWindowId) : null; - if (twButton == null) return null; + if (twButton == null) return null; - if (getToolWindow(toolWindowId).getAnchor() != anchor) { - object.hide(); - return null; - } - - final Point point = new Point(twButton.getBounds().width / 2, twButton.getHeight() / 2 - 2); - return new RelativePoint(twButton, point); + if (getToolWindow(toolWindowId).getAnchor() != anchor) { + object.hide(); + return null; } - }; - if (!balloon.isDisposed()) { - balloon.show(tracker, position.get()); + + final Point point = new Point(twButton.getBounds().width / 2, twButton.getHeight() / 2 - 2); + return new RelativePoint(twButton, point); } + }; + if (!balloon.isDisposed()) { + balloon.show(tracker, position.get()); } - else { - final Rectangle bounds = myToolWindowsPane.getBounds(); - final Point target = UIUtil.getCenterPoint(bounds, new Dimension(1, 1)); - if (ToolWindowAnchor.TOP == anchor) { - target.y = 0; - } - else if (ToolWindowAnchor.BOTTOM == anchor) { - target.y = bounds.height - 3; - } - else if (ToolWindowAnchor.LEFT == anchor) { - target.x = 0; - } - else if (ToolWindowAnchor.RIGHT == anchor) { - target.x = bounds.width; - } - if (!balloon.isDisposed()) { - balloon.show(new RelativePoint(myToolWindowsPane, target), position.get()); - } + } + else { + final Rectangle bounds = myToolWindowsPane.getBounds(); + final Point target = UIUtil.getCenterPoint(bounds, new Dimension(1, 1)); + if (ToolWindowAnchor.TOP == anchor) { + target.y = 0; + } + else if (ToolWindowAnchor.BOTTOM == anchor) { + target.y = bounds.height - 3; + } + else if (ToolWindowAnchor.LEFT == anchor) { + target.x = 0; + } + else if (ToolWindowAnchor.RIGHT == anchor) { + target.x = bounds.width; + } + if (!balloon.isDisposed()) { + balloon.show(new RelativePoint(myToolWindowsPane, target), position.get()); } } }; if (!button.isValid()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - show.run(); - } - }); + SwingUtilities.invokeLater(() -> show.run()); } else { show.run(); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java index 3cb5c702b751..659a86cb443f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java @@ -101,23 +101,21 @@ public final class RequestFocusInEditorComponentCmd extends FinalizableCommand{ if(myComponent != null){ final boolean forced = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == null; - myFocusManager.requestFocus(myComponent, myForced || forced).notifyWhenDone(myDoneCallback).doWhenDone(new Runnable() { - public void run() { - if (SystemInfo.isLinux && Registry.is("suppress.focus.stealing")) return; - // if owner is active window or it has active child window which isn't floating decorator then - // don't bring owner window to font. If we will make toFront every time then it's possible - // the following situation: - // 1. user perform refactoring - // 2. "Do not show preview" dialog is popping up. - // 3. At that time "preview" tool window is being activated and modal "don't show..." dialog - // isn't active. - if(!owner.isActive()){ - final Window activeWindow=getActiveWindow(owner.getOwnedWindows()); - if(activeWindow == null || (activeWindow instanceof FloatingDecorator)){ - //Thread.dumpStack(); - //System.out.println("------------------------------------------------------"); - owner.toFront(); - } + myFocusManager.requestFocus(myComponent, myForced || forced).notifyWhenDone(myDoneCallback).doWhenDone(() -> { + if (SystemInfo.isLinux && Registry.is("suppress.focus.stealing")) return; + // if owner is active window or it has active child window which isn't floating decorator then + // don't bring owner window to font. If we will make toFront every time then it's possible + // the following situation: + // 1. user perform refactoring + // 2. "Do not show preview" dialog is popping up. + // 3. At that time "preview" tool window is being activated and modal "don't show..." dialog + // isn't active. + if(!owner.isActive()){ + final Window activeWindow=getActiveWindow(owner.getOwnedWindows()); + if(activeWindow == null || (activeWindow instanceof FloatingDecorator)){ + //Thread.dumpStack(); + //System.out.println("------------------------------------------------------"); + owner.toFront(); } } }); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java index 62d6cc4978a8..a274e91f9fd3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java @@ -57,12 +57,7 @@ public final class RequestFocusInToolWindowCmd extends FinalizableCommand { @Override public final void run() { - myToolWindow.getActivation().doWhenDone(new Runnable() { - @Override - public void run() { - processRequestFocus(); - } - }); + myToolWindow.getActivation().doWhenDone(() -> processRequestFocus()); } private void processRequestFocus() { @@ -102,22 +97,12 @@ public final class RequestFocusInToolWindowCmd extends FinalizableCommand { // Try to focus component which is preferred one for the tool window if (preferredFocusedComponent != null) { - requestFocus(preferredFocusedComponent).doWhenDone(new Runnable() { - @Override - public void run() { - bringOwnerToFront(); - } - }); + requestFocus(preferredFocusedComponent).doWhenDone(() -> bringOwnerToFront()); } else { // If there is no preferred component then try to focus tool window itself final JComponent componentToFocus = myToolWindow.getComponent(); - requestFocus(componentToFocus).doWhenDone(new Runnable() { - @Override - public void run() { - bringOwnerToFront(); - } - }); + requestFocus(componentToFocus).doWhenDone(() -> bringOwnerToFront()); } } finally { @@ -176,21 +161,11 @@ public final class RequestFocusInToolWindowCmd extends FinalizableCommand { public ActionCallback run() { return ActionCallback.DONE; } - }, myForced).doWhenProcessed(new Runnable() { - @Override - public void run() { - updateToolWindow(c); - } - }).notify(result); + }, myForced).doWhenProcessed(() -> updateToolWindow(c)).notify(result); } else { myManager.getFocusManager().requestFocus(new FocusCommand.ByComponent(c, myToolWindow.getComponent(), new Exception()), myForced) - .doWhenProcessed(new Runnable() { - @Override - public void run() { - updateToolWindow(c); - } - }).notify(result); + .doWhenProcessed(() -> updateToolWindow(c)).notify(result); } } else { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/TabbedContentTabLabel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/TabbedContentTabLabel.java index 7aa3bf9b8759..8ca58626482c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/TabbedContentTabLabel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/TabbedContentTabLabel.java @@ -86,13 +86,10 @@ public class TabbedContentTabLabel extends ContentTabLabel implements Disposable } }); final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - int index = list.getSelectedIndex(); - if (index != -1) { - myContent.selectContent(index); - } + .setItemChoosenCallback(() -> { + int index = list.getSelectedIndex(); + if (index != -1) { + myContent.selectContent(index); } }).createPopup(); Disposer.register(this, popup); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java index 1e5b0c4e6511..840d855b8f91 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java @@ -585,11 +585,7 @@ public class ToolWindowContentUi extends JPanel implements ContentUI, PropertyCh getCurrentLayout().showContentPopup(popup); if (selectedContent instanceof TabbedContent) { - new Alarm(Alarm.ThreadToUse.SWING_THREAD, popup).addRequest(new Runnable() { - public void run() { - popup.handleSelect(true); - } - }, 30); + new Alarm(Alarm.ThreadToUse.SWING_THREAD, popup).addRequest(() -> popup.handleSelect(true), 30); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/AddTestProcessAction.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/AddTestProcessAction.java index d7f099c37401..6a4060fa581b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/AddTestProcessAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/AddTestProcessAction.java @@ -127,11 +127,7 @@ public class AddTestProcessAction extends AnAction implements DumbAware { // ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); // task.run(indicator != null ? indicator : new EmptyProgressIndicator()); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - task.queue(); - } - }); + SwingUtilities.invokeLater(() -> task.queue()); } private void countTo(int top, Count count) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ClockPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ClockPanel.java index 1d109f616757..85dec22950d1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ClockPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ClockPanel.java @@ -53,12 +53,7 @@ public class ClockPanel extends JComponent { protected final Calendar myCalendar; private final boolean is24Hours; private ScheduledFuture myScheduledFuture; - private final Runnable myRepaintRunnable = new Runnable() { - @Override - public void run() { - ClockPanel.this.repaint(); - } - }; + private final Runnable myRepaintRunnable = () -> ClockPanel.this.repaint(); public ClockPanel() { myCalendar = getInstance(); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java index 9749a866b61e..1c2596ae8a3d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/EncodingPanel.java @@ -218,68 +218,65 @@ public class EncodingPanel extends EditorBasedWidget implements StatusBarWidget. if (update.isDisposed()) return; update.cancelAllRequests(); - update.addRequest(new Runnable() { - @Override - public void run() { - if (isDisposed()) return; + update.addRequest(() -> { + if (isDisposed()) return; - VirtualFile file = getSelectedFile(); - actionEnabled = false; - String charsetName = null; - Pair check = null; + VirtualFile file = getSelectedFile(); + actionEnabled = false; + String charsetName = null; + Pair check = null; - if (file != null) { - check = EncodingUtil.checkSomeActionEnabled(file); - Charset charset = null; + if (file != null) { + check = EncodingUtil.checkSomeActionEnabled(file); + Charset charset = null; - if (LoadTextUtil.wasCharsetDetectedFromBytes(file) != null) { - charset = cachedCharsetFromContent(file); - } - - if (charset == null) { - charset = file.getCharset(); - } - - actionEnabled = check == null || check.second == null; - - if (!actionEnabled) { - charset = check.first; - } - - if (charset != null) { - charsetName = charset.displayName(); - } + if (LoadTextUtil.wasCharsetDetectedFromBytes(file) != null) { + charset = cachedCharsetFromContent(file); } - if (charsetName == null) { - charsetName = "n/a"; + if (charset == null) { + charset = file.getCharset(); } - String toolTipText; + actionEnabled = check == null || check.second == null; - if (actionEnabled) { - toolTipText = String.format( - "File Encoding%n%s", charsetName); - - myComponent.setForeground(UIUtil.getActiveTextColor()); - myComponent.setTextAlignment(Component.LEFT_ALIGNMENT); - } - else { - String failReason = check == null ? "" : check.second; - toolTipText = String.format("File encoding is disabled%n%s", - failReason); - - myComponent.setForeground(UIUtil.getInactiveTextColor()); - myComponent.setTextAlignment(Component.CENTER_ALIGNMENT); + if (!actionEnabled) { + charset = check.first; } - myComponent.setToolTipText(toolTipText); - myComponent.setText(charsetName); - - if (myStatusBar != null) { - myStatusBar.updateWidget(ID()); + if (charset != null) { + charsetName = charset.displayName(); } } + + if (charsetName == null) { + charsetName = "n/a"; + } + + String toolTipText; + + if (actionEnabled) { + toolTipText = String.format( + "File Encoding%n%s", charsetName); + + myComponent.setForeground(UIUtil.getActiveTextColor()); + myComponent.setTextAlignment(Component.LEFT_ALIGNMENT); + } + else { + String failReason = check == null ? "" : check.second; + toolTipText = String.format("File encoding is disabled%n%s", + failReason); + + myComponent.setForeground(UIUtil.getInactiveTextColor()); + myComponent.setTextAlignment(Component.CENTER_ALIGNMENT); + } + + myComponent.setToolTipText(toolTipText); + myComponent.setText(charsetName); + + if (myStatusBar != null) { + myStatusBar.updateWidget(ID()); + } }, 200, ModalityState.any()); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java index 346e0f724bbb..621f286ee6de 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java @@ -195,31 +195,16 @@ public class IdeStatusBarImpl extends JComponent implements Accessible, StatusBa @Override public void addWidget(@NotNull final StatusBarWidget widget) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - addWidget(widget, Position.RIGHT, "__AUTODETECT__"); - } - }); + UIUtil.invokeLaterIfNeeded(() -> addWidget(widget, Position.RIGHT, "__AUTODETECT__")); } @Override public void addWidget(@NotNull final StatusBarWidget widget, @NotNull final String anchor) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - addWidget(widget, Position.RIGHT, anchor); - } - }); + UIUtil.invokeLaterIfNeeded(() -> addWidget(widget, Position.RIGHT, anchor)); } private void addWidget(@NotNull final StatusBarWidget widget, @NotNull final Position pos) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - addWidget(widget, pos, "__IGNORED__"); - } - }); + UIUtil.invokeLaterIfNeeded(() -> addWidget(widget, pos, "__IGNORED__")); } @Override @@ -440,12 +425,9 @@ public class IdeStatusBarImpl extends JComponent implements Accessible, StatusBa updateChildren(new ChildAction() { @Override public void update(final IdeStatusBarImpl child) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - StatusBarWidget widgetCopy = mfw.copy(); - child.addWidget(widgetCopy, pos, anchor); - } + UIUtil.invokeLaterIfNeeded(() -> { + StatusBarWidget widgetCopy = mfw.copy(); + child.addWidget(widgetCopy, pos, anchor); }); } }); @@ -482,14 +464,11 @@ public class IdeStatusBarImpl extends JComponent implements Accessible, StatusBa @Override public void setInfo(@Nullable final String s, @Nullable final String requestor) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myInfoAndProgressPanel != null) { - Couple pair = myInfoAndProgressPanel.setText(s, requestor); - myInfo = pair.first; - myRequestor = pair.second; - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myInfoAndProgressPanel != null) { + Couple pair = myInfoAndProgressPanel.setText(s, requestor); + myInfo = pair.first; + myRequestor = pair.second; } }); } @@ -693,25 +672,22 @@ public class IdeStatusBarImpl extends JComponent implements Accessible, StatusBa @Override public void updateWidget(@NotNull final String id) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - final WidgetBean bean = myWidgetMap.get(id); - if (bean != null) { - if (bean.component instanceof StatusBarWrapper) { - ((StatusBarWrapper)bean.component).beforeUpdate(); - } - - bean.component.repaint(); + UIUtil.invokeLaterIfNeeded(() -> { + final WidgetBean bean = myWidgetMap.get(id); + if (bean != null) { + if (bean.component instanceof StatusBarWrapper) { + ((StatusBarWrapper)bean.component).beforeUpdate(); } - updateChildren(new ChildAction() { - @Override - public void update(IdeStatusBarImpl child) { - child.updateWidget(id); - } - }); + bean.component.repaint(); } + + updateChildren(new ChildAction() { + @Override + public void update(IdeStatusBarImpl child) { + child.updateWidget(id); + } + }); }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java index e2e74262e0f0..905bfa71028e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java @@ -476,24 +476,18 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge } public void setRefreshVisible(final boolean visible) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myRefreshAlarm.cancelAllRequests(); - myRefreshAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (visible) { - myRefreshIcon.resume(); - } - else { - myRefreshIcon.suspend(); - } - myRefreshIcon.revalidate(); - myRefreshIcon.repaint(); - } - }, visible ? 100 : 300); - } + UIUtil.invokeLaterIfNeeded(() -> { + myRefreshAlarm.cancelAllRequests(); + myRefreshAlarm.addRequest(() -> { + if (visible) { + myRefreshIcon.resume(); + } + else { + myRefreshIcon.suspend(); + } + myRefreshIcon.revalidate(); + myRefreshIcon.repaint(); + }, visible ? 100 : 300); }); } @@ -508,23 +502,20 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge type.getPopupBackground(), listener).createBalloon(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Component comp = InfoAndProgressPanel.this; - if (comp.isShowing()) { - int offset = comp.getHeight() / 2; - Point point = new Point(comp.getWidth() - offset, comp.getHeight() - offset); - balloon.show(new RelativePoint(comp, point), Balloon.Position.above); - } else { - final JRootPane rootPane = SwingUtilities.getRootPane(comp); - if (rootPane != null && rootPane.isShowing()) { - final Container contentPane = rootPane.getContentPane(); - final Rectangle bounds = contentPane.getBounds(); - final Point target = UIUtil.getCenterPoint(bounds, JBUI.size(1, 1)); - target.y = bounds.height - 3; - balloon.show(new RelativePoint(contentPane, target), Balloon.Position.above); - } + SwingUtilities.invokeLater(() -> { + Component comp = InfoAndProgressPanel.this; + if (comp.isShowing()) { + int offset = comp.getHeight() / 2; + Point point = new Point(comp.getWidth() - offset, comp.getHeight() - offset); + balloon.show(new RelativePoint(comp, point), Balloon.Position.above); + } else { + final JRootPane rootPane = SwingUtilities.getRootPane(comp); + if (rootPane != null && rootPane.isShowing()) { + final Container contentPane = rootPane.getContentPane(); + final Rectangle bounds = contentPane.getBounds(); + final Point target = UIUtil.getCenterPoint(bounds, JBUI.size(1, 1)); + target.y = bounds.height - 3; + balloon.show(new RelativePoint(contentPane, target), Balloon.Position.above); } } }); @@ -532,12 +523,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge return new BalloonHandler() { @Override public void hide() { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - balloon.hide(); - } - }); + SwingUtilities.invokeLater(() -> balloon.hide()); } }; } @@ -689,12 +675,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge @Override public void finish(@NotNull final TaskInfo task) { super.finish(task); - queueRunningUpdate(new Runnable() { - @Override - public void run() { - removeProgress(MyInlineProgressIndicator.this); - } - }); + queueRunningUpdate(() -> removeProgress(MyInlineProgressIndicator.this)); } @Override @@ -737,12 +718,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge each.updateProgress(); } myQueryAlarm.cancelAllRequests(); - myQueryAlarm.addRequest(new Runnable() { - @Override - public void run() { - runQuery(); - } - }, 2000); + myQueryAlarm.addRequest(() -> runQuery(), 2000); } @NotNull diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/LineSeparatorPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/LineSeparatorPanel.java index ff8a2a230b03..0fcd39666ddb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/LineSeparatorPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/LineSeparatorPanel.java @@ -87,58 +87,55 @@ public class LineSeparatorPanel extends EditorBasedWidget implements StatusBarWi } private void update() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - VirtualFile file = getSelectedFile(); + UIUtil.invokeLaterIfNeeded(() -> { + VirtualFile file = getSelectedFile(); + myActionEnabled = false; + String lineSeparator = null; + String toolTipText = null; + String panelText = null; + + if (file != null) { + myActionEnabled = file.isWritable(); + + lineSeparator = + LoadTextUtil.detectLineSeparator(file, true); + + if (lineSeparator != null) { + toolTipText = String.format("Line separator: %s", + StringUtil.escapeLineBreak(lineSeparator)); + panelText = LineSeparator.fromString(lineSeparator).toString(); + } + } + + if (lineSeparator == null) { + toolTipText = "No line separator"; + panelText = "n/a"; myActionEnabled = false; - String lineSeparator = null; - String toolTipText = null; - String panelText = null; + } - if (file != null) { - myActionEnabled = file.isWritable(); + myComponent.resetColor(); - lineSeparator = - LoadTextUtil.detectLineSeparator(file, true); + String toDoComment; - if (lineSeparator != null) { - toolTipText = String.format("Line separator: %s", - StringUtil.escapeLineBreak(lineSeparator)); - panelText = LineSeparator.fromString(lineSeparator).toString(); - } - } + if (myActionEnabled) { + toDoComment = "Click to change"; + myComponent.setForeground(UIUtil.getActiveTextColor()); + myComponent.setTextAlignment(Component.LEFT_ALIGNMENT); + } else { + toDoComment = ""; + myComponent.setForeground(UIUtil.getInactiveTextColor()); + myComponent.setTextAlignment(Component.CENTER_ALIGNMENT); + } - if (lineSeparator == null) { - toolTipText = "No line separator"; - panelText = "n/a"; - myActionEnabled = false; - } - - myComponent.resetColor(); - - String toDoComment; - - if (myActionEnabled) { - toDoComment = "Click to change"; - myComponent.setForeground(UIUtil.getActiveTextColor()); - myComponent.setTextAlignment(Component.LEFT_ALIGNMENT); - } else { - toDoComment = ""; - myComponent.setForeground(UIUtil.getInactiveTextColor()); - myComponent.setTextAlignment(Component.CENTER_ALIGNMENT); - } - - myComponent.setToolTipText(String.format("%s%n%s", - toolTipText, - toDoComment)); - myComponent.setText(panelText); + myComponent.setToolTipText(String.format("%s%n%s", + toolTipText, + toDoComment)); + myComponent.setText(panelText); - if (myStatusBar != null) { - myStatusBar.updateWidget(ID()); - } + if (myStatusBar != null) { + myStatusBar.updateWidget(ID()); } }); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java index 7eb2ff2fc307..5035b90c5ffe 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PositionPanel.java @@ -77,25 +77,21 @@ public class PositionPanel extends EditorBasedWidget implements StatusBarWidget. } public Consumer getClickConsumer() { - return new Consumer() { - public void consume(MouseEvent mouseEvent) { - final Project project = getProject(); - if (project == null) return; - final Editor editor = getEditor(); - if (editor == null) return; - final CommandProcessor processor = CommandProcessor.getInstance(); - processor.executeCommand( - project, new Runnable() { - public void run() { - final GotoLineNumberDialog dialog = new GotoLineNumberDialog(project, editor); - dialog.show(); - IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); - } - }, - UIBundle.message("go.to.line.command.name"), - null - ); - } + return mouseEvent -> { + final Project project = getProject(); + if (project == null) return; + final Editor editor = getEditor(); + if (editor == null) return; + final CommandProcessor processor = CommandProcessor.getInstance(); + processor.executeCommand( + project, () -> { + final GotoLineNumberDialog dialog = new GotoLineNumberDialog(project, editor); + dialog.show(); + IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); + }, + UIBundle.message("go.to.line.command.name"), + null + ); }; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java index 3087c4611497..a40bddb57819 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToggleReadOnlyAttributePanel.java @@ -84,26 +84,22 @@ public class ToggleReadOnlyAttributePanel extends FileEditorManagerAdapter imple } public Consumer getClickConsumer() { - return new Consumer() { - public void consume(MouseEvent mouseEvent) { - final VirtualFile file = getCurrentFile(); - if (!isReadOnlyApplicableForFile(file)) { - return; - } - FileDocumentManager.getInstance().saveAllDocuments(); - - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - ReadOnlyAttributeUtil.setReadOnlyAttribute(file, file.isWritable()); - myStatusBar.updateWidget(ID()); - } - catch (IOException e) { - Messages.showMessageDialog(getProject(), e.getMessage(), UIBundle.message("error.dialog.title"), Messages.getErrorIcon()); - } - } - }); + return mouseEvent -> { + final VirtualFile file = getCurrentFile(); + if (!isReadOnlyApplicableForFile(file)) { + return; } + FileDocumentManager.getInstance().saveAllDocuments(); + + ApplicationManager.getApplication().runWriteAction(() -> { + try { + ReadOnlyAttributeUtil.setReadOnlyAttribute(file, file.isWritable()); + myStatusBar.updateWidget(ID()); + } + catch (IOException e) { + Messages.showMessageDialog(getProject(), e.getMessage(), UIBundle.message("error.dialog.title"), Messages.getErrorIcon()); + } + }); }; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java index 2e6b61afb7b4..b80345d11975 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java @@ -113,12 +113,9 @@ class ToolWindowsWidget extends JLabel implements CustomStatusBarWidget, StatusB final Rectangle popupScreenRect = new Rectangle(screen.x, screen.y, popup.getSize().width, popup.getSize().height); if (! popupScreenRect.contains(currentLocationOnScreen)) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (popup != null && popup.isVisible()) { - popup.cancel(); - } + myAlarm.addRequest(() -> { + if (popup != null && popup.isVisible()) { + popup.cancel(); } }, 300); return true; @@ -129,74 +126,63 @@ class ToolWindowsWidget extends JLabel implements CustomStatusBarWidget, StatusB public void mouseEntered() { if (myAlarm.getActiveRequestCount() == 0) { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - final IdeFrameImpl frame = UIUtil.getParentOfType(IdeFrameImpl.class, ToolWindowsWidget.this); - if (frame == null) return; + myAlarm.addRequest(() -> { + final IdeFrameImpl frame = UIUtil.getParentOfType(IdeFrameImpl.class, ToolWindowsWidget.this); + if (frame == null) return; - List toolWindows = new ArrayList(); - final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(frame.getProject()); - for (String id : toolWindowManager.getToolWindowIds()) { - final ToolWindow tw = toolWindowManager.getToolWindow(id); - if (tw.isAvailable() && tw.isShowStripeButton()) { - toolWindows.add(tw); - } + List toolWindows = new ArrayList(); + final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(frame.getProject()); + for (String id : toolWindowManager.getToolWindowIds()) { + final ToolWindow tw = toolWindowManager.getToolWindow(id); + if (tw.isAvailable() && tw.isShowStripeButton()) { + toolWindows.add(tw); } - Collections.sort(toolWindows, new Comparator() { - @Override - public int compare(ToolWindow o1, ToolWindow o2) { - return StringUtil.naturalCompare(o1.getStripeTitle(), o2.getStripeTitle()); - } - }); - - final JBList list = new JBList(toolWindows); - list.setCellRenderer(new ListCellRenderer() { - final JBLabel label = new JBLabel(); - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - final ToolWindow toolWindow = (ToolWindow)value; - label.setText(toolWindow.getStripeTitle()); - label.setIcon(toolWindow.getIcon()); - label.setBorder(IdeBorderFactory.createEmptyBorder(4, 10, 4, 10)); - label.setForeground(UIUtil.getListForeground(isSelected)); - label.setBackground(UIUtil.getListBackground(isSelected)); - final JPanel panel = new JPanel(new BorderLayout()); - panel.add(label, BorderLayout.CENTER); - panel.setBackground(UIUtil.getListBackground(isSelected)); - return panel; - } - }); - - final Dimension size = list.getPreferredSize(); - final JComponent c = ToolWindowsWidget.this; - final Insets padding = UIUtil.getListViewportPadding(); - final RelativePoint point = new RelativePoint(c, new Point(-4, -padding.top - padding.bottom -4 - size.height + (SystemInfo.isMac ? 2 : 0))); - - if (popup != null && popup.isVisible()) { - return; - } - - list.setSelectedIndex(list.getItemsCount() - 1); - PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list); - popup = builder - .setAutoselectOnMouseMove(true) - .setRequestFocus(false) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - if (popup != null) popup.closeOk(null); - final Object value = list.getSelectedValue(); - if (value instanceof ToolWindow) { - ((ToolWindow)value).activate(null, true, true); - } - } - }) - .createPopup(); - - popup.show(point); } + Collections.sort(toolWindows, (o1, o2) -> StringUtil.naturalCompare(o1.getStripeTitle(), o2.getStripeTitle())); + + final JBList list = new JBList(toolWindows); + list.setCellRenderer(new ListCellRenderer() { + final JBLabel label = new JBLabel(); + + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + final ToolWindow toolWindow = (ToolWindow)value; + label.setText(toolWindow.getStripeTitle()); + label.setIcon(toolWindow.getIcon()); + label.setBorder(IdeBorderFactory.createEmptyBorder(4, 10, 4, 10)); + label.setForeground(UIUtil.getListForeground(isSelected)); + label.setBackground(UIUtil.getListBackground(isSelected)); + final JPanel panel = new JPanel(new BorderLayout()); + panel.add(label, BorderLayout.CENTER); + panel.setBackground(UIUtil.getListBackground(isSelected)); + return panel; + } + }); + + final Dimension size = list.getPreferredSize(); + final JComponent c = ToolWindowsWidget.this; + final Insets padding = UIUtil.getListViewportPadding(); + final RelativePoint point = new RelativePoint(c, new Point(-4, -padding.top - padding.bottom -4 - size.height + (SystemInfo.isMac ? 2 : 0))); + + if (popup != null && popup.isVisible()) { + return; + } + + list.setSelectedIndex(list.getItemsCount() - 1); + PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list); + popup = builder + .setAutoselectOnMouseMove(true) + .setRequestFocus(false) + .setItemChoosenCallback(() -> { + if (popup != null) popup.closeOk(null); + final Object value = list.getSelectedValue(); + if (value instanceof ToolWindow) { + ((ToolWindow)value).activate(null, true, true); + } + }) + .createPopup(); + + popup.show(point); }, 300); } } @@ -208,15 +194,12 @@ class ToolWindowsWidget extends JLabel implements CustomStatusBarWidget, StatusB if (UISettings.getInstance().HIDE_TOOL_STRIPES && !PropertiesComponent.getInstance().isTrueValue(key)) { PropertiesComponent.getInstance().setValue(key, String.valueOf(true)); final Alarm alarm = new Alarm(); - alarm.addRequest(new Runnable() { - @Override - public void run() { - GotItMessage.createMessage(UIBundle.message("tool.window.quick.access.title"), UIBundle.message( - "tool.window.quick.access.message")) - .setDisposable(ToolWindowsWidget.this) - .show(new RelativePoint(ToolWindowsWidget.this, new Point(10, 0)), Balloon.Position.above); - Disposer.dispose(alarm); - } + alarm.addRequest(() -> { + GotItMessage.createMessage(UIBundle.message("tool.window.quick.access.title"), UIBundle.message( + "tool.window.quick.access.message")) + .setDisposable(ToolWindowsWidget.this) + .show(new RelativePoint(ToolWindowsWidget.this, new Point(10, 0)), Balloon.Position.above); + Disposer.dispose(alarm); }, 20000); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/FlatWelcomeFrame.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/FlatWelcomeFrame.java index 3984fff7d7be..7f07f1e5c581 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/FlatWelcomeFrame.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/FlatWelcomeFrame.java @@ -93,11 +93,7 @@ public class FlatWelcomeFrame extends JFrame implements IdeFrame, AccessibleCont public void addNotify() { super.addNotify(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - JBProtocolCommand.handleCurrentCommand(); - } - }); + SwingUtilities.invokeLater(() -> JBProtocolCommand.handleCurrentCommand()); } }; @@ -312,26 +308,23 @@ public class FlatWelcomeFrame extends JFrame implements IdeFrame, AccessibleCont } }); panel.setVisible(false); - myEventListener = new ParameterizedRunnable>() { - @Override - public void run(List types) { - NotificationType type = null; - for (NotificationType t : types) { - if (NotificationType.ERROR == t) { - type = NotificationType.ERROR; - break; - } - if (NotificationType.WARNING == t) { - type = NotificationType.WARNING; - } - else if (type == null && NotificationType.INFORMATION == t) { - type = NotificationType.INFORMATION; - } + myEventListener = types -> { + NotificationType type1 = null; + for (NotificationType t : types) { + if (NotificationType.ERROR == t) { + type1 = NotificationType.ERROR; + break; + } + if (NotificationType.WARNING == t) { + type1 = NotificationType.WARNING; + } + else if (type1 == null && NotificationType.INFORMATION == t) { + type1 = NotificationType.INFORMATION; } - - actionLinkRef.get().setIcon(IdeNotificationArea.createIconWithNotificationCount(actionLinkRef.get(), type, types.size())); - panel.setVisible(true); } + + actionLinkRef.get().setIcon(IdeNotificationArea.createIconWithNotificationCount(actionLinkRef.get(), type1, types.size())); + panel.setVisible(true); }; myEventLocation = new Computable() { @Override @@ -423,27 +416,19 @@ public class FlatWelcomeFrame extends JFrame implements IdeFrame, AccessibleCont private AnAction wrapGroups(AnAction action) { if (action instanceof ActionGroup && ((ActionGroup)action).isPopup()) { - final Pair panel = createActionGroupPanel((ActionGroup)action, mySlidingPanel, new Runnable() { - @Override - public void run() { - goBack(); - } - }); - final Runnable onDone = new Runnable() { - @Override - public void run() { - setTitle("New Project"); - final JBList list = panel.second; - ScrollingUtil.ensureSelectionExists(list); - final ListSelectionListener[] listeners = - ((DefaultListSelectionModel)list.getSelectionModel()).getListeners(ListSelectionListener.class); + final Pair panel = createActionGroupPanel((ActionGroup)action, mySlidingPanel, () -> goBack()); + final Runnable onDone = () -> { + setTitle("New Project"); + final JBList list = panel.second; + ScrollingUtil.ensureSelectionExists(list); + final ListSelectionListener[] listeners = + ((DefaultListSelectionModel)list.getSelectionModel()).getListeners(ListSelectionListener.class); - //avoid component cashing. This helps in case of LaF change - for (ListSelectionListener listener : listeners) { - listener.valueChanged(new ListSelectionEvent(list, list.getSelectedIndex(), list.getSelectedIndex(), true)); - } - list.requestFocus(); + //avoid component cashing. This helps in case of LaF change + for (ListSelectionListener listener : listeners) { + listener.valueChanged(new ListSelectionEvent(list, list.getSelectedIndex(), list.getSelectedIndex(), true)); } + list.requestFocus(); }; final String name = action.getClass().getName(); mySlidingPanel.add(name, panel.first); @@ -459,12 +444,9 @@ public class FlatWelcomeFrame extends JFrame implements IdeFrame, AccessibleCont } protected void goBack() { - mySlidingPanel.swipe("root", JBCardLayout.SwipeDirection.BACKWARD).doWhenDone(new Runnable() { - @Override - public void run() { - mySlidingPanel.getRootPane().setDefaultButton(null); - setTitle(getWelcomeFrameTitle()); - } + mySlidingPanel.swipe("root", JBCardLayout.SwipeDirection.BACKWARD).doWhenDone(() -> { + mySlidingPanel.getRootPane().setDefaultButton(null); + setTitle(getWelcomeFrameTitle()); }); } @@ -678,12 +660,7 @@ public class FlatWelcomeFrame extends JFrame implements IdeFrame, AccessibleCont } private static Runnable createUsageTracker(final AnAction action) { - return new Runnable() { - @Override - public void run() { - UsageTrigger.trigger("welcome.screen." + ActionManager.getInstance().getId(action)); - } - }; + return () -> UsageTrigger.trigger("welcome.screen." + ActionManager.getInstance().getId(action)); } private static JLabel createArrow(final ActionLink link) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/MoveProjectToGroupActionGroup.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/MoveProjectToGroupActionGroup.java index 84ebf1dedd1b..e9148ac04f1d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/MoveProjectToGroupActionGroup.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/MoveProjectToGroupActionGroup.java @@ -36,12 +36,7 @@ public class MoveProjectToGroupActionGroup extends DefaultActionGroup implements public void update(AnActionEvent e) { removeAll(); final List groups = new ArrayList(RecentProjectsManager.getInstance().getGroups()); - Collections.sort(groups, new Comparator() { - @Override - public int compare(ProjectGroup o1, ProjectGroup o2) { - return StringUtil.naturalCompare(o1.getName(), o2.getName()); - } - }); + Collections.sort(groups, (o1, o2) -> StringUtil.naturalCompare(o1.getName(), o2.getName())); for (ProjectGroup group : groups) { add(new MoveProjectToGroupAction(group)); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/RecentProjectPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/RecentProjectPanel.java index c28d1427600f..bb2657158e14 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/RecentProjectPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/RecentProjectPanel.java @@ -154,11 +154,8 @@ public class RecentProjectPanel extends JPanel { if (selection != null && selection.length > 0) { final int rc = Messages.showOkCancelDialog(RecentProjectPanel.this, - "Remove '" + StringUtil.join(selection, new Function() { - @Override - public String fun(Object action) { - return ((AnAction)action).getTemplatePresentation().getText(); - } + "Remove '" + StringUtil.join(selection, action -> { + return ((AnAction)action).getTemplatePresentation().getText(); }, "'\n'") + "' from recent projects list?", "Remove Recent Project", @@ -188,22 +185,19 @@ public class RecentProjectPanel extends JPanel { JComponent list = recentProjectActions.length == 0 ? myList - : ListWithFilter.wrap(myList, scroll, new Function() { - @Override - public String fun(Object o) { - if (o instanceof ReopenProjectAction) { - ReopenProjectAction item = (ReopenProjectAction)o; - String home = SystemProperties.getUserHome(); - String path = item.getProjectPath(); - if (FileUtil.startsWith(path, home)) { - path = path.substring(home.length()); - } - return item.getProjectName() + " " + path; - } else if (o instanceof ProjectGroupActionGroup) { - return ((ProjectGroupActionGroup)o).getGroup().getName(); + : ListWithFilter.wrap(myList, scroll, o -> { + if (o instanceof ReopenProjectAction) { + ReopenProjectAction item = (ReopenProjectAction)o; + String home = SystemProperties.getUserHome(); + String path = item.getProjectPath(); + if (FileUtil.startsWith(path, home)) { + path = path.substring(home.length()); } - return o.toString(); + return item.getProjectName() + " " + path; + } else if (o instanceof ProjectGroupActionGroup) { + return ((ProjectGroupActionGroup)o).getGroup().getName(); } + return o.toString(); }); add(list, BorderLayout.CENTER); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/WelcomeBalloonLayoutImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/WelcomeBalloonLayoutImpl.java index 6182af7a250a..16fa51d68f62 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/WelcomeBalloonLayoutImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/WelcomeBalloonLayoutImpl.java @@ -112,12 +112,7 @@ public class WelcomeBalloonLayoutImpl extends BalloonLayoutImpl { myPopupBalloon.setAnimationEnabled(false); myPopupBalloon.setShadowBorderProvider( new NotificationBalloonShadowBorderProvider(FILL_COLOR, BORDER_COLOR)); - myPopupBalloon.setHideListener(new Runnable() { - @Override - public void run() { - myPopupBalloon.getComponent().setVisible(false); - } - }); + myPopupBalloon.setHideListener(() -> myPopupBalloon.getComponent().setVisible(false)); myPopupBalloon.setActionProvider(new BalloonImpl.ActionProvider() { private BalloonImpl.ActionButton myAction; diff --git a/platform/platform-impl/src/com/intellij/patterns/compiler/PatternCompilerImpl.java b/platform/platform-impl/src/com/intellij/patterns/compiler/PatternCompilerImpl.java index 2123cd631870..e830d723c523 100644 --- a/platform/platform-impl/src/com/intellij/patterns/compiler/PatternCompilerImpl.java +++ b/platform/platform-impl/src/com/intellij/patterns/compiler/PatternCompilerImpl.java @@ -333,11 +333,9 @@ public class PatternCompilerImpl implements PatternCompiler { throw e.getTargetException(); } } - throw new NoSuchMethodException("unknown symbol: "+methodName + "(" + StringUtil.join(arguments, new Function() { - public String fun(Object o) { - return String.valueOf(o); - } - }, ", ")+")"); + throw new NoSuchMethodException("unknown symbol: " + methodName + "(" + StringUtil.join(arguments, o -> { + return String.valueOf(o); + }, ", ") + ")"); } @Nullable diff --git a/platform/platform-impl/src/com/intellij/platform/OpenDirectoryProjectAction.java b/platform/platform-impl/src/com/intellij/platform/OpenDirectoryProjectAction.java index 32f874b0ca69..f59fb8fe89f7 100644 --- a/platform/platform-impl/src/com/intellij/platform/OpenDirectoryProjectAction.java +++ b/platform/platform-impl/src/com/intellij/platform/OpenDirectoryProjectAction.java @@ -36,11 +36,8 @@ public class OpenDirectoryProjectAction extends AnAction implements DumbAware { final FileChooserDescriptor descriptor = new OpenProjectFileChooserDescriptor(false); final Project project = e.getData(CommonDataKeys.PROJECT); - FileChooser.chooseFiles(descriptor, project, null, new Consumer>() { - @Override - public void consume(final List files) { - PlatformProjectOpenProcessor.getInstance().doOpenProject(files.get(0), project, false); - } + FileChooser.chooseFiles(descriptor, project, null, files -> { + PlatformProjectOpenProcessor.getInstance().doOpenProject(files.get(0), project, false); }); } } diff --git a/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java b/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java index 5b4ff7f0272a..e9537c2ecc7b 100644 --- a/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java +++ b/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java @@ -201,13 +201,10 @@ public class PlatformProjectOpenProcessor extends ProjectOpenProcessor { Module module = runConfigurators ? runDirectoryProjectConfigurators(baseDir, project) : ModuleManager.getInstance(project).getModules()[0]; if (runConfigurators && dummyProject) { // add content root for chosen (single) file - ModuleRootModificationUtil.updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - ContentEntry[] entries = model.getContentEntries(); - if (entries.length == 1) model.removeContentEntry(entries[0]); // remove custom content entry created for temp directory - model.addContentEntry(virtualFile); - } + ModuleRootModificationUtil.updateModel(module, model -> { + ContentEntry[] entries = model.getContentEntries(); + if (entries.length == 1) model.removeContentEntry(entries[0]); // remove custom content entry created for temp directory + model.addContentEntry(virtualFile); }); } @@ -220,11 +217,8 @@ public class PlatformProjectOpenProcessor extends ProjectOpenProcessor { if (!projectManager.openProject(project)) { WelcomeFrame.showIfNoProjectOpened(); final Project finalProject = project; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Disposer.dispose(finalProject); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Disposer.dispose(finalProject); }); return project; } @@ -263,16 +257,13 @@ public class PlatformProjectOpenProcessor extends ProjectOpenProcessor { StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() { @Override public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!project.isDisposed() && file.isValid() && !file.isDirectory()) { - if (line > 0) { - new OpenFileDescriptor(project, file, line - 1, 0).navigate(true); - } - else { - new OpenFileDescriptor(project, file).navigate(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!project.isDisposed() && file.isValid() && !file.isDirectory()) { + if (line > 0) { + new OpenFileDescriptor(project, file, line - 1, 0).navigate(true); + } + else { + new OpenFileDescriptor(project, file).navigate(true); } } }, ModalityState.NON_MODAL); diff --git a/platform/platform-impl/src/com/intellij/platform/ProjectSetReader.java b/platform/platform-impl/src/com/intellij/platform/ProjectSetReader.java index a2d475cc3fe1..4df25b39d51e 100644 --- a/platform/platform-impl/src/com/intellij/platform/ProjectSetReader.java +++ b/platform/platform-impl/src/com/intellij/platform/ProjectSetReader.java @@ -64,32 +64,21 @@ public class ProjectSetReader { if (object.entrySet().size() == 1 && object.entrySet().iterator().next().getValue().isJsonArray()) { final Map.Entry next = object.entrySet().iterator().next(); list = ContainerUtil.map(next.getValue().getAsJsonArray(), - new Function>() { - @Override - public Pair fun(JsonElement o) { - return Pair.create(next.getKey(), getString(o)); - } + o -> { + return Pair.create(next.getKey(), getString(o)); }); } else { - list = ContainerUtil.map(object.entrySet(), new Function, Pair>() { - @Override - public Pair fun(Map.Entry entry) { - JsonElement value = entry.getValue(); - return Pair.create(entry.getKey(), getString(value)); - } + list = ContainerUtil.map(object.entrySet(), entry1 -> { + JsonElement value = entry1.getValue(); + return Pair.create(entry1.getKey(), getString(value)); }); } } else { list = Collections.singletonList(Pair.create(entry.getKey(), entry.getValue().getAsString())); } - processor.processEntries(list, context, new Runnable() { - @Override - public void run() { - runProcessor(processors, context, iterator); - } - }); + processor.processEntries(list, context, () -> runProcessor(processors, context, iterator)); } public static String getString(JsonElement value) { diff --git a/platform/platform-impl/src/com/intellij/psi/statistics/impl/StatisticsManagerImpl.java b/platform/platform-impl/src/com/intellij/psi/statistics/impl/StatisticsManagerImpl.java index a62832a6e18b..b25e130ea5e4 100644 --- a/platform/platform-impl/src/com/intellij/psi/statistics/impl/StatisticsManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/psi/statistics/impl/StatisticsManagerImpl.java @@ -116,11 +116,8 @@ public class StatisticsManagerImpl extends StatisticsManager { synchronized (LOCK) { strings = getUnit(getUnitNumber(context)).getKeys2(context); } - return ContainerUtil.map2Array(strings, StatisticsInfo.class, new NotNullFunction() { - @NotNull - public StatisticsInfo fun(final String s) { - return new StatisticsInfo(context, s); - } + return ContainerUtil.map2Array(strings, StatisticsInfo.class, (NotNullFunction)s -> { + return new StatisticsInfo(context, s); }); } diff --git a/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java b/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java index 7f0415b58a4d..3ddc4637951b 100644 --- a/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java +++ b/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java @@ -102,19 +102,16 @@ public class BaseRemoteProcessHandler extends AbstractR } }; - myWaitFor.setTerminationCallback(new Consumer() { - @Override - public void consume(Integer exitCode) { + myWaitFor.setTerminationCallback(exitCode -> { + try { try { - try { - stderrReader.waitFor(); - stdoutReader.waitFor(); - } - catch (InterruptedException ignore) { } - } - finally { - onOSProcessTerminated(exitCode); + stderrReader.waitFor(); + stdoutReader.waitFor(); } + catch (InterruptedException ignore) { } + } + finally { + onOSProcessTerminated(exitCode); } }); } @@ -146,14 +143,11 @@ public class BaseRemoteProcessHandler extends AbstractR @Override protected void detachProcessImpl() { - final Runnable runnable = new Runnable() { - @Override - public void run() { - closeStreams(); + final Runnable runnable = () -> { + closeStreams(); - myWaitFor.detach(); - notifyProcessDetached(); - } + myWaitFor.detach(); + notifyProcessDetached(); }; executeOnPooledThread(runnable); diff --git a/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java b/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java index 898aaacd2468..71d3ffc6c0cf 100644 --- a/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java +++ b/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java @@ -42,13 +42,8 @@ public abstract class VagrantSupport { @Nullable String machineName); public static void showMissingVagrantSupportMessage(final @Nullable Project project) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(project, "Enable Vagrant Support plugin", - "Vagrant Support Disabled"); - } - }); + UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(project, "Enable Vagrant Support plugin", + "Vagrant Support Disabled")); } @NotNull diff --git a/platform/platform-impl/src/com/intellij/ui/AbstractExpandableItemsHandler.java b/platform/platform-impl/src/com/intellij/ui/AbstractExpandableItemsHandler.java index a5c73fd62cdf..43585ec5c82c 100644 --- a/platform/platform-impl/src/com/intellij/ui/AbstractExpandableItemsHandler.java +++ b/platform/platform-impl/src/com/intellij/ui/AbstractExpandableItemsHandler.java @@ -223,12 +223,7 @@ public abstract class AbstractExpandableItemsHandler doHandleSelectionChange(selected, processIfUnfocused), 10); } private boolean isHandleSelectionEnabled(@NotNull KeyType selected, boolean processIfUnfocused) { diff --git a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java index b703401cff83..bb6a51122d5a 100644 --- a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java @@ -550,12 +550,7 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { myLayeredPane.repaint(); if (mnemonicsFix) { - proxyFocusRequest.get().doWhenDone(new Runnable() { - @Override - public void run() { - myFocusManager.requestFocus(originalFocusOwner.get(), true); - } - }); + proxyFocusRequest.get().doWhenDone(() -> myFocusManager.requestFocus(originalFocusOwner.get(), true)); } Toolkit.getDefaultToolkit().addAWTEventListener( @@ -668,17 +663,9 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { myShowPointer ? myPosition.createBorder(this) : getPointlessBorder()); if (myActionProvider == null) { - final Consumer listener = new Consumer() { - @Override - public void consume(MouseEvent event) { - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - hide(); - } - }); - } + final Consumer listener = event -> { + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> hide()); }; myActionProvider = new ActionProvider() { @@ -863,12 +850,7 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { myFadeoutAlarm.cancelAllRequests(); myFadeoutRequestMillis = System.currentTimeMillis(); myFadeoutRequestDelay = fadeoutDelay; - myFadeoutAlarm.addRequest(new Runnable() { - @Override - public void run() { - hide(); - } - }, fadeoutDelay, null); + myFadeoutAlarm.addRequest(() -> hide(), fadeoutDelay, null); } } @@ -938,23 +920,20 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { myDisposed = true; hideComboBoxPopups(); - final Runnable disposeRunnable = new Runnable() { - @Override - public void run() { - myFadedOut = true; - if (myRequestFocus) { - if (myOriginalFocusOwner != null) { - myFocusManager.requestFocus(myOriginalFocusOwner, false); - } + final Runnable disposeRunnable = () -> { + myFadedOut = true; + if (myRequestFocus) { + if (myOriginalFocusOwner != null) { + myFocusManager.requestFocus(myOriginalFocusOwner, false); } - - for (JBPopupListener each : myListeners) { - each.onClosed(new LightweightWindowEvent(BalloonImpl.this, ok)); - } - - Disposer.dispose(BalloonImpl.this); - onDisposed(); } + + for (JBPopupListener each : myListeners) { + each.onClosed(new LightweightWindowEvent(BalloonImpl.this, ok)); + } + + Disposer.dispose(BalloonImpl.this); + onDisposed(); }; Toolkit.getDefaultToolkit().removeAWTEventListener(myAwtActivityListener); @@ -1735,12 +1714,9 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { myActionButtons = null; if (buttons != null) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - for (ActionButton button : buttons) { - disposeButton(button); - } + SwingUtilities.invokeLater(() -> { + for (ActionButton button : buttons) { + disposeButton(button); } }); } diff --git a/platform/platform-impl/src/com/intellij/ui/BalloonLayoutImpl.java b/platform/platform-impl/src/com/intellij/ui/BalloonLayoutImpl.java index dc21221ad716..67bdd02de379 100644 --- a/platform/platform-impl/src/com/intellij/ui/BalloonLayoutImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/BalloonLayoutImpl.java @@ -52,28 +52,21 @@ public class BalloonLayoutImpl implements BalloonLayout { private Integer myWidth; private final Alarm myRelayoutAlarm = new Alarm(); - private final Runnable myRelayoutRunnable = new Runnable() { - public void run() { - relayout(); - fireRelayout(); - } + private final Runnable myRelayoutRunnable = () -> { + relayout(); + fireRelayout(); }; private final JRootPane myParent; - private final Runnable myCloseAll = new Runnable() { - @Override - public void run() { - for (Balloon balloon : new ArrayList(myBalloons)) { - remove(balloon, true); - } + private final Runnable myCloseAll = () -> { + for (Balloon balloon : new ArrayList(myBalloons)) { + remove(balloon, true); } }; - private final Runnable myLayoutRunnable = new Runnable() { - public void run() { - calculateSize(); - relayout(); - fireRelayout(); - } + private final Runnable myLayoutRunnable = () -> { + calculateSize(); + relayout(); + fireRelayout(); }; private LafManagerListener myLafListener; diff --git a/platform/platform-impl/src/com/intellij/ui/CardLayoutPanel.java b/platform/platform-impl/src/com/intellij/ui/CardLayoutPanel.java index 09602952bc3b..f7bb0492a395 100644 --- a/platform/platform-impl/src/com/intellij/ui/CardLayoutPanel.java +++ b/platform/platform-impl/src/com/intellij/ui/CardLayoutPanel.java @@ -123,24 +123,18 @@ public abstract class CardLayoutPanel extends JCompo } private void selectLater(final ActionCallback callback, final K key) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - if (!myDisposed) { - final UI ui = prepare(key); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - HeavyProcessLatch.INSTANCE.prioritizeUiActivity(); - if (!myDisposed) { - select(callback, key, ui); - } - else callback.setRejected(); - } - }, ModalityState.stateForComponent(CardLayoutPanel.this)); - } - else callback.setRejected(); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + if (!myDisposed) { + final UI ui1 = prepare(key); + ApplicationManager.getApplication().invokeLater(() -> { + HeavyProcessLatch.INSTANCE.prioritizeUiActivity(); + if (!myDisposed) { + select(callback, key, ui1); + } + else callback.setRejected(); + }, ModalityState.stateForComponent(CardLayoutPanel.this)); } + else callback.setRejected(); }); } diff --git a/platform/platform-impl/src/com/intellij/ui/ColorPicker.java b/platform/platform-impl/src/com/intellij/ui/ColorPicker.java index e6ff9e9aa209..13d3c641c578 100644 --- a/platform/platform-impl/src/com/intellij/ui/ColorPicker.java +++ b/platform/platform-impl/src/com/intellij/ui/ColorPicker.java @@ -246,12 +246,7 @@ public class ColorPicker extends JPanel implements ColorListener, DocumentListen private void update(final JTextField src) { myUpdateQueue.cancelAllRequests(); - myUpdateQueue.addRequest(new Runnable() { - @Override - public void run() { - validateAndUpdatePreview(src); - } - }, 300); + myUpdateQueue.addRequest(() -> validateAndUpdatePreview(src), 300); } @Override @@ -459,12 +454,9 @@ public class ColorPicker extends JPanel implements ColorListener, DocumentListen myBrightnessComponent = new SlideComponent("Brightness", true); myBrightnessComponent.setToolTipText("Brightness"); - myBrightnessComponent.addListener(new Consumer() { - @Override - public void consume(Integer value) { - myColorWheel.setBrightness(1f - (value / 255f)); - myColorWheel.repaint(); - } + myBrightnessComponent.addListener(value -> { + myColorWheel.setBrightness(1f - (value / 255f)); + myColorWheel.repaint(); }); add(myBrightnessComponent, BorderLayout.EAST); @@ -473,12 +465,9 @@ public class ColorPicker extends JPanel implements ColorListener, DocumentListen myOpacityComponent = new SlideComponent("Opacity", false); myOpacityComponent.setUnits(opacityInPercent ? SlideComponent.Unit.PERCENT : SlideComponent.Unit.LEVEL); myOpacityComponent.setToolTipText("Opacity"); - myOpacityComponent.addListener(new Consumer() { - @Override - public void consume(Integer integer) { - myColorWheel.setOpacity(integer.intValue()); - myColorWheel.repaint(); - } + myOpacityComponent.addListener(integer -> { + myColorWheel.setOpacity(integer.intValue()); + myColorWheel.repaint(); }); add(myOpacityComponent, BorderLayout.SOUTH); diff --git a/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java b/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java index f1949805d2a8..4afe9bdb16d7 100644 --- a/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java +++ b/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java @@ -130,12 +130,9 @@ public class ComboboxEditorTextField extends EditorTextField { private void repaintComboBox() { // TODO: if (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF() || (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel())) { - IdeFocusManager.getInstance(getProject()).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - final Container parent = getParent(); - if (parent != null) parent.repaint(); - } + IdeFocusManager.getInstance(getProject()).doWhenFocusSettlesDown(() -> { + final Container parent1 = getParent(); + if (parent1 != null) parent1.repaint(); }); } } diff --git a/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java b/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java index 5fb3f704047f..8cf9259d139e 100644 --- a/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java +++ b/platform/platform-impl/src/com/intellij/ui/EditorComboBox.java @@ -177,19 +177,13 @@ public class EditorComboBox extends JComboBox implements DocumentListener { } public void setText(final String text) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - myDocument.replaceString(0, myDocument.getTextLength(), text); - if (myEditorField != null && myEditorField.getEditor() != null) { - myEditorField.getCaretModel().moveToOffset(myDocument.getTextLength()); - } - } - }, null, myDocument); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + myDocument.replaceString(0, myDocument.getTextLength(), text); + if (myEditorField != null && myEditorField.getEditor() != null) { + myEditorField.getCaretModel().moveToOffset(myDocument.getTextLength()); + } + }, null, myDocument); }); } diff --git a/platform/platform-impl/src/com/intellij/ui/EditorTextField.java b/platform/platform-impl/src/com/intellij/ui/EditorTextField.java index 63b7e6575b01..65ceeaf1fb9b 100644 --- a/platform/platform-impl/src/com/intellij/ui/EditorTextField.java +++ b/platform/platform-impl/src/com/intellij/ui/EditorTextField.java @@ -244,22 +244,16 @@ public class EditorTextField extends NonOpaquePanel implements DocumentListener, } public void setText(@Nullable final String text) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - myDocument.replaceString(0, myDocument.getTextLength(), text == null ? "" : text); - if (myEditor != null) { - final CaretModel caretModel = myEditor.getCaretModel(); - if (caretModel.getOffset() >= myDocument.getTextLength()) { - caretModel.moveToOffset(myDocument.getTextLength()); - } - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + myDocument.replaceString(0, myDocument.getTextLength(), text == null ? "" : text); + if (myEditor != null) { + final CaretModel caretModel = myEditor.getCaretModel(); + if (caretModel.getOffset() >= myDocument.getTextLength()) { + caretModel.moveToOffset(myDocument.getTextLength()); } - }, null, null, UndoConfirmationPolicy.DEFAULT, getDocument()); - } + } + }, null, null, UndoConfirmationPolicy.DEFAULT, getDocument()); }); } @@ -342,12 +336,9 @@ public class EditorTextField extends NonOpaquePanel implements DocumentListener, editor.getContentComponent().removeFocusListener(this); final Application application = ApplicationManager.getApplication(); - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (!editor.isDisposed()) { - EditorFactory.getInstance().releaseEditor(editor); - } + final Runnable runnable = () -> { + if (!editor.isDisposed()) { + EditorFactory.getInstance().releaseEditor(editor); } }; @@ -406,12 +397,7 @@ public class EditorTextField extends NonOpaquePanel implements DocumentListener, // removeNotify(), so we need to let swing complete its removeNotify() chain // and only then execute another removal from the hierarchy. Otherwise // swing goes nuts because of nested removals and indices get corrupted - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - releaseEditor(editor); - } - }); + SwingUtilities.invokeLater(() -> releaseEditor(editor)); } @Override diff --git a/platform/platform-impl/src/com/intellij/ui/FieldPanelWithChangeSupport.java b/platform/platform-impl/src/com/intellij/ui/FieldPanelWithChangeSupport.java index b9604ffd6c28..97101129672a 100644 --- a/platform/platform-impl/src/com/intellij/ui/FieldPanelWithChangeSupport.java +++ b/platform/platform-impl/src/com/intellij/ui/FieldPanelWithChangeSupport.java @@ -19,11 +19,7 @@ import com.intellij.openapi.options.BaseConfigurableWithChangeSupport; public class FieldPanelWithChangeSupport { public static AbstractFieldPanel createPanel(AbstractFieldPanel panel, final BaseConfigurableWithChangeSupport configurable) { - panel.setChangeListener(new Runnable() { - public void run() { - configurable.fireStateChanged(); - } - }); + panel.setChangeListener(() -> configurable.fireStateChanged()); return panel; } diff --git a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java index d2bed47b7693..d310481611a2 100644 --- a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java +++ b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java @@ -517,40 +517,29 @@ public abstract class FinderRecursivePanel extends JBSplitter implements Data final T oldValue = getSelectedValue(); final int oldIndex = myList.getSelectedIndex(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - DumbService.getInstance(getProject()).runReadActionInSmartMode(new Runnable() { - @Override - public void run() { - try { - final List listItems = getListItems(); + ApplicationManager.getApplication().executeOnPooledThread(() -> DumbService.getInstance(getProject()).runReadActionInSmartMode(() -> { + try { + final List listItems = getListItems(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - mergeListItems(myListModel, myList, listItems); + SwingUtilities.invokeLater(() -> { + mergeListItems(myListModel, myList, listItems); - if (myList.isEmpty()) { - createRightComponent(true); - } - else if (myList.getSelectedIndex() < 0) { - myList.setSelectedIndex(myListModel.getSize() > oldIndex ? oldIndex : 0); - } - else { - Object newValue = myList.getSelectedValue(); - updateRightComponent(oldValue == null || !oldValue.equals(newValue) || myList.isEmpty()); - } - } - }); - } - finally { - myList.setPaintBusy(false); - } + if (myList.isEmpty()) { + createRightComponent(true); + } + else if (myList.getSelectedIndex() < 0) { + myList.setSelectedIndex(myListModel.getSize() > oldIndex ? oldIndex : 0); + } + else { + Object newValue = myList.getSelectedValue(); + updateRightComponent(oldValue == null || !oldValue.equals(newValue) || myList.isEmpty()); } }); } - }); + finally { + myList.setPaintBusy(false); + } + })); } }); } diff --git a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java index b9bc4de59b62..86a3498ea930 100644 --- a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java +++ b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java @@ -216,32 +216,23 @@ public class FocusTrackback { final IdeFocusManager focusManager = IdeFocusManager.getInstance(project); cleanParentWindow(); final Project finalProject = project; - focusManager.requestFocus(new MyFocusCommand(), myForcedRestore).doWhenProcessed(new Runnable() { - public void run() { - dispose(); - } - }).doWhenRejected(new Runnable() { - @Override - public void run() { - focusManager.revalidateFocus(new ExpirableRunnable.ForProject(finalProject) { - @Override - public void run() { - if (UIUtil.isMeaninglessFocusOwner(focusManager.getFocusOwner())) { - focusManager.requestDefaultFocus(false); - } + focusManager.requestFocus(new MyFocusCommand(), myForcedRestore).doWhenProcessed(() -> dispose()).doWhenRejected(() -> { + focusManager.revalidateFocus(new ExpirableRunnable.ForProject(finalProject) { + @Override + public void run() { + if (UIUtil.isMeaninglessFocusOwner(focusManager.getFocusOwner())) { + focusManager.requestDefaultFocus(false); } - }); - } + } + }); }); } else { // no ide focus manager, so no way -- do just later //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - _restoreFocus(); - dispose(); - } + SwingUtilities.invokeLater(() -> { + _restoreFocus(); + dispose(); }); } } diff --git a/platform/platform-impl/src/com/intellij/ui/FontComboBox.java b/platform/platform-impl/src/com/intellij/ui/FontComboBox.java index e5c20fdf389f..7c8d38eda29b 100644 --- a/platform/platform-impl/src/com/intellij/ui/FontComboBox.java +++ b/platform/platform-impl/src/com/intellij/ui/FontComboBox.java @@ -86,18 +86,12 @@ public final class FontComboBox extends ComboBox { setFonts(FontInfo.getAll(withAllStyles)); } else { - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - List allFonts = FontInfo.getAll(withAllStyles); - application.invokeLater(new Runnable() { - @Override - public void run() { - setFonts(allFonts); - updateSelectedItem(); - } - }, application.getAnyModalityState()); - } + application.executeOnPooledThread(() -> { + List allFonts = FontInfo.getAll(withAllStyles); + application.invokeLater(() -> { + setFonts(allFonts); + updateSelectedItem(); + }, application.getAnyModalityState()); }); } } diff --git a/platform/platform-impl/src/com/intellij/ui/HideableDecorator.java b/platform/platform-impl/src/com/intellij/ui/HideableDecorator.java index 52f66702a3b4..0a040e2129f4 100644 --- a/platform/platform-impl/src/com/intellij/ui/HideableDecorator.java +++ b/platform/platform-impl/src/com/intellij/ui/HideableDecorator.java @@ -157,11 +157,9 @@ public class HideableDecorator { newSize = new Dimension(size.width, size.height - contentSize.height); } if (!newSize.equals(size)) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (window.isShowing()) { - window.setSize(newSize); - } + SwingUtilities.invokeLater(() -> { + if (window.isShowing()) { + window.setSize(newSize); } }); } diff --git a/platform/platform-impl/src/com/intellij/ui/NotificationBalloonActionProvider.java b/platform/platform-impl/src/com/intellij/ui/NotificationBalloonActionProvider.java index af1f2f910e9f..90d6f24dca6e 100644 --- a/platform/platform-impl/src/com/intellij/ui/NotificationBalloonActionProvider.java +++ b/platform/platform-impl/src/com/intellij/ui/NotificationBalloonActionProvider.java @@ -69,18 +69,12 @@ public class NotificationBalloonActionProvider implements BalloonImpl.ActionProv mySettingButton = myBalloon.new ActionButton( AllIcons.Ide.Notification.Gear, AllIcons.Ide.Notification.GearHover, "Configure Notification", - new Consumer() { - @Override - public void consume(MouseEvent event) { - final NotificationsConfigurable configurable = new NotificationsConfigurable(); - ShowSettingsUtil.getInstance().editConfigurable(myLayoutData.project, configurable, new Runnable() { - @Override - public void run() { - //noinspection ConstantConditions - configurable.enableSearch(myDisplayGroupId).run(); - } - }); - } + event -> { + final NotificationsConfigurable configurable = new NotificationsConfigurable(); + ShowSettingsUtil.getInstance().editConfigurable(myLayoutData.project, configurable, () -> { + //noinspection ConstantConditions + configurable.enableSearch(myDisplayGroupId).run(); + }); }) { @Override public void repaint() { @@ -110,23 +104,17 @@ public class NotificationBalloonActionProvider implements BalloonImpl.ActionProv myCloseButton = myBalloon.new ActionButton( AllIcons.Ide.Notification.Close, AllIcons.Ide.Notification.CloseHover, "Close Notification (Alt-Click close all notifications)", - new Consumer() { - @Override - public void consume(MouseEvent event) { - final int modifiers = event.getModifiers(); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if ((modifiers & InputEvent.ALT_MASK) != 0) { - myLayoutData.closeAll.run(); - } - else { - myBalloon.hide(); - } - } - }); - } + event -> { + final int modifiers = event.getModifiers(); + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + if ((modifiers & InputEvent.ALT_MASK) != 0) { + myLayoutData.closeAll.run(); + } + else { + myBalloon.hide(); + } + }); }) { @Override protected void paintIcon(@NotNull Graphics g, @NotNull Icon icon) { diff --git a/platform/platform-impl/src/com/intellij/ui/ShowUIDefaultsAction.java b/platform/platform-impl/src/com/intellij/ui/ShowUIDefaultsAction.java index 575a3e49ea30..47f4ec25eb43 100644 --- a/platform/platform-impl/src/com/intellij/ui/ShowUIDefaultsAction.java +++ b/platform/platform-impl/src/com/intellij/ui/ShowUIDefaultsAction.java @@ -56,12 +56,7 @@ public class ShowUIDefaultsAction extends AnAction implements DumbAware { i++; } - Arrays.sort(data, new Comparator() { - @Override - public int compare(Object[] o1, Object[] o2) { - return StringUtil.naturalCompare(o1[0 ].toString(), o2[0].toString()); - } - }); + Arrays.sort(data, (o1, o2) -> StringUtil.naturalCompare(o1[0 ].toString(), o2[0].toString())); final Project project = getEventProject(e); new DialogWrapper(project) { @@ -147,13 +142,7 @@ public class ShowUIDefaultsAction extends AnAction implements DumbAware { } }); final JBScrollPane pane = new JBScrollPane(table); - new TableSpeedSearch(table, new PairFunction() { - @Nullable - @Override - public String fun(Object o, Cell cell) { - return cell.column == 1 ? null : String.valueOf(o); - } - }); + new TableSpeedSearch(table, (o, cell) -> cell.column == 1 ? null : String.valueOf(o)); table.setShowGrid(false); final JPanel panel = new JPanel(new BorderLayout()); panel.add(pane, BorderLayout.CENTER); diff --git a/platform/platform-impl/src/com/intellij/ui/SplitterWithSecondHideable.java b/platform/platform-impl/src/com/intellij/ui/SplitterWithSecondHideable.java index 132c07586a9b..77d8230e1726 100644 --- a/platform/platform-impl/src/com/intellij/ui/SplitterWithSecondHideable.java +++ b/platform/platform-impl/src/com/intellij/ui/SplitterWithSecondHideable.java @@ -75,14 +75,11 @@ public abstract class SplitterWithSecondHideable { mySplitter.setSecondComponent(myDetailsComponent.getPanel()); mySuperDivider.setResizeEnabled(true); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - mySplitter.fixFirst(proportion); - mySplitter.invalidate(); - mySplitter.validate(); - mySplitter.repaint(); - } + SwingUtilities.invokeLater(() -> { + mySplitter.fixFirst(proportion); + mySplitter.invalidate(); + mySplitter.validate(); + mySplitter.repaint(); }); } diff --git a/platform/platform-impl/src/com/intellij/ui/TabbedPaneImpl.java b/platform/platform-impl/src/com/intellij/ui/TabbedPaneImpl.java index 1a3aadaed450..8f1714c2f168 100644 --- a/platform/platform-impl/src/com/intellij/ui/TabbedPaneImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/TabbedPaneImpl.java @@ -230,12 +230,9 @@ public class TabbedPaneImpl extends JBTabbedPane implements TabbedPane { if (each.getClass().getName().contains("apple.laf.CUIAquaTabbedPane")) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - revalidate(); - repaint(); - } + SwingUtilities.invokeLater(() -> { + revalidate(); + repaint(); }); continue; diff --git a/platform/platform-impl/src/com/intellij/ui/TableExpandableItemsHandler.java b/platform/platform-impl/src/com/intellij/ui/TableExpandableItemsHandler.java index 26d9908c932c..a4d21516bad8 100644 --- a/platform/platform-impl/src/com/intellij/ui/TableExpandableItemsHandler.java +++ b/platform/platform-impl/src/com/intellij/ui/TableExpandableItemsHandler.java @@ -72,12 +72,7 @@ public class TableExpandableItemsHandler extends AbstractExpandableItemsHandler< public void tableChanged(final TableModelEvent e) { // This method may be called from TableModelListener (before selection model update) // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4730055 - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - updateSelection(table); - } - }); + SwingUtilities.invokeLater(() -> updateSelection(table)); } }; diff --git a/platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java b/platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java index 5567e5a60be0..68d8bd86a2e1 100644 --- a/platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java +++ b/platform/platform-impl/src/com/intellij/ui/TableSpeedSearch.java @@ -23,12 +23,7 @@ import javax.swing.*; import java.util.ListIterator; public class TableSpeedSearch extends SpeedSearchBase { - private static final PairFunction TO_STRING = new PairFunction() { - @Override - public String fun(Object o, Cell cell) { - return o == null || o instanceof Boolean ? "" : o.toString(); - } - }; + private static final PairFunction TO_STRING = (o, cell) -> o == null || o instanceof Boolean ? "" : o.toString(); private final PairFunction myToStringConvertor; public TableSpeedSearch(JTable table) { @@ -36,11 +31,8 @@ public class TableSpeedSearch extends SpeedSearchBase { } public TableSpeedSearch(JTable table, final Convertor toStringConvertor) { - this(table, new PairFunction() { - @Override - public String fun(Object o, Cell c) { - return toStringConvertor.convert(o); - } + this(table, (o, c) -> { + return toStringConvertor.convert(o); }); } diff --git a/platform/platform-impl/src/com/intellij/ui/components/SliderSelectorAction.java b/platform/platform-impl/src/com/intellij/ui/components/SliderSelectorAction.java index f854c41af059..514f6cbedaa0 100644 --- a/platform/platform-impl/src/com/intellij/ui/components/SliderSelectorAction.java +++ b/platform/platform-impl/src/com/intellij/ui/components/SliderSelectorAction.java @@ -100,12 +100,9 @@ public class SliderSelectorAction extends DumbAwareAction { result.add(slider, BorderLayout.CENTER); } - final Runnable saveSelection = new Runnable() { - @Override - public void run() { - int value = slider.getModel().getValue(); - myConfiguration.getResultConsumer().consume(value); - } + final Runnable saveSelection = () -> { + int value = slider.getModel().getValue(); + myConfiguration.getResultConsumer().consume(value); }; final Ref popupRef = new Ref(null); final JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(result, slider) diff --git a/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java b/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java index 4037f2c40133..65cc051a5cbc 100644 --- a/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java @@ -216,22 +216,19 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene @Override public ActionCallback removeContent(@NotNull Content content, boolean dispose, final boolean trackFocus, final boolean forcedFocus) { final ActionCallback result = new ActionCallback(); - removeContent(content, true, dispose).doWhenDone(new Runnable() { - @Override - public void run() { - if (trackFocus) { - Content current = getSelectedContent(); - if (current != null) { - setSelectedContent(current, true, true, !forcedFocus); - } - else { - result.setDone(); - } + removeContent(content, true, dispose).doWhenDone(() -> { + if (trackFocus) { + Content current = getSelectedContent(); + if (current != null) { + setSelectedContent(current, true, true, !forcedFocus); } else { result.setDone(); } } + else { + result.setDone(); + } }); return result; @@ -522,12 +519,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene boolean enabledFocus = getFocusManager().isFocusTransferEnabled(); if (focused || requestFocus) { if (enabledFocus) { - return getFocusManager().requestFocus(myComponent, true).doWhenProcessed(new Runnable() { - @Override - public void run() { - selection.run().notify(result); - } - }); + return getFocusManager().requestFocus(myComponent, true).doWhenProcessed(() -> selection.run().notify(result)); } return selection.run().notify(result); } diff --git a/platform/platform-impl/src/com/intellij/ui/content/impl/MessageViewImpl.java b/platform/platform-impl/src/com/intellij/ui/content/impl/MessageViewImpl.java index c5f46efcff4f..de9021695c4d 100644 --- a/platform/platform-impl/src/com/intellij/ui/content/impl/MessageViewImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/content/impl/MessageViewImpl.java @@ -38,26 +38,20 @@ public class MessageViewImpl implements MessageView { private final List myPostponedRunnables = new ArrayList(); public MessageViewImpl(final Project project, final StartupManager startupManager, final ToolWindowManager toolWindowManager) { - final Runnable runnable = new Runnable() { - public void run() { - myToolWindow = toolWindowManager.registerToolWindow(ToolWindowId.MESSAGES_WINDOW, true, ToolWindowAnchor.BOTTOM, project, true); - myToolWindow.setIcon(AllIcons.Toolwindows.ToolWindowMessages); - new ContentManagerWatcher(myToolWindow, getContentManager()); - for (Runnable postponedRunnable : myPostponedRunnables) { - postponedRunnable.run(); - } - myPostponedRunnables.clear(); + final Runnable runnable = () -> { + myToolWindow = toolWindowManager.registerToolWindow(ToolWindowId.MESSAGES_WINDOW, true, ToolWindowAnchor.BOTTOM, project, true); + myToolWindow.setIcon(AllIcons.Toolwindows.ToolWindowMessages); + new ContentManagerWatcher(myToolWindow, getContentManager()); + for (Runnable postponedRunnable : myPostponedRunnables) { + postponedRunnable.run(); } + myPostponedRunnables.clear(); }; if (project.isInitialized()) { runnable.run(); } else { - startupManager.registerPostStartupActivity(new Runnable(){ - public void run() { - runnable.run(); - } - }); + startupManager.registerPostStartupActivity(() -> runnable.run()); } } diff --git a/platform/platform-impl/src/com/intellij/ui/docking/impl/DockManagerImpl.java b/platform/platform-impl/src/com/intellij/ui/docking/impl/DockManagerImpl.java index c3be4f7171b7..4870d9c8f500 100644 --- a/platform/platform-impl/src/com/intellij/ui/docking/impl/DockManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/docking/impl/DockManagerImpl.java @@ -392,12 +392,7 @@ public class DockManagerImpl extends DockManager implements PersistentStateCompo container.add(content, new RelativePoint(target.getLocation())); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - window.myUiContainer.setPreferredSize(null); - } - }); + SwingUtilities.invokeLater(() -> window.myUiContainer.setPreferredSize(null)); } @NotNull @@ -412,12 +407,7 @@ public class DockManagerImpl extends DockManager implements PersistentStateCompo final Pair result = fileEditorManager.openFileImpl2(editorWindow, file, true); container.add(EditorTabbedContainer.createDockableEditor(myProject, null, file, new Presentation(file.getName()), editorWindow), null); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - window.myUiContainer.setPreferredSize(null); - } - }); + SwingUtilities.invokeLater(() -> window.myUiContainer.setPreferredSize(null)); return result; } @@ -477,12 +467,9 @@ public class DockManagerImpl extends DockManager implements PersistentStateCompo myContainer.addListener(new DockContainer.Listener.Adapter() { @Override public void contentRemoved(Object key) { - getReady().doWhenDone(new Runnable() { - @Override - public void run() { - if (myContainer.isEmpty()) { - close(); - } + getReady().doWhenDone(() -> { + if (myContainer.isEmpty()) { + close(); } }); } @@ -649,12 +636,7 @@ public class DockManagerImpl extends DockManager implements PersistentStateCompo register(container); final DockWindow window = createWindowFor(eachId, container); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - window.show(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> window.show()); } } } diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java b/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java index c29a29c2454d..376dbbe13d49 100644 --- a/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java @@ -136,39 +136,27 @@ public class MacFileChooserDialogImpl implements PathChooserDialog { try { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final IdeMenuBar bar = getMenuBar(); - if (bar != null) { - bar.enableUpdates(); - } + SwingUtilities.invokeLater(() -> { + final IdeMenuBar bar = getMenuBar(); + if (bar != null) { + bar.enableUpdates(); } }); final List resultPaths = processResult(returnCode, openPanelDidEnd); if (resultPaths.size() > 0) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - final List files = getChosenFiles(resultPaths); - if (files.size() > 0) { - FileChooserUtil.setLastOpenedFile(impl.myProject, files.get(files.size() - 1)); - impl.myCallback.consume(files); - } - } - }); - } + ApplicationManager.getApplication().invokeLater(() -> { + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> { + final List files = getChosenFiles(resultPaths); + if (files.size() > 0) { + FileChooserUtil.setLastOpenedFile(impl.myProject, files.get(files.size() - 1)); + impl.myCallback.consume(files); + } + }); }, impl.myModalityState); } else if (impl.myCallback instanceof FileChooser.FileChooserConsumer) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ((FileChooser.FileChooserConsumer)impl.myCallback).cancelled(); - } + ApplicationManager.getApplication().invokeLater(() -> { + ((FileChooser.FileChooserConsumer)impl.myCallback).cancelled(); }, impl.myModalityState); } } @@ -333,12 +321,7 @@ public class MacFileChooserDialogImpl implements PathChooserDialog { final String selectPath = selectFile != null ? FileUtil.toSystemDependentName(selectFile.getPath()) : null; //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - showNativeChooserAsSheet(MacFileChooserDialogImpl.this, selectPath); - } - }); + SwingUtilities.invokeLater(() -> showNativeChooserAsSheet(MacFileChooserDialogImpl.this, selectPath)); } @Nullable diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java index ad820e64d048..6e36b81a682e 100644 --- a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java +++ b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java @@ -156,22 +156,16 @@ public class MacMainFrameDecorator extends IdeFrameDecorator implements UISettin private static AtomicInteger UNIQUE_COUNTER = new AtomicInteger(0); - public static final Runnable TOOLBAR_SETTER = new Runnable() { - @Override - public void run() { - final UISettings settings = UISettings.getInstance(); - settings.SHOW_MAIN_TOOLBAR = SHOWN; - settings.fireUISettingsChanged(); - } + public static final Runnable TOOLBAR_SETTER = () -> { + final UISettings settings = UISettings.getInstance(); + settings.SHOW_MAIN_TOOLBAR = SHOWN; + settings.fireUISettingsChanged(); }; - public static final Runnable NAVBAR_SETTER = new Runnable() { - @Override - public void run() { - final UISettings settings = UISettings.getInstance(); - settings.SHOW_NAVIGATION_BAR = SHOWN; - settings.fireUISettingsChanged(); - } + public static final Runnable NAVBAR_SETTER = () -> { + final UISettings settings = UISettings.getInstance(); + settings.SHOW_NAVIGATION_BAR = SHOWN; + settings.fireUISettingsChanged(); }; @SuppressWarnings("Convert2Lambda") @@ -274,12 +268,9 @@ public class MacMainFrameDecorator extends IdeFrameDecorator implements UISettin Foundation.addMethod(ownToolbar, Foundation.createSelector("setVisible:"), SET_VISIBLE_CALLBACK, "v*"); Foundation.addMethod(ownToolbar, Foundation.createSelector("isVisible"), IS_VISIBLE, "B*"); - Foundation.executeOnMainThread(new Runnable() { - @Override - public void run() { - invoke(window, "setToolbar:", toolbar); - invoke(window, "setShowsToolbarButton:", 1); - } + Foundation.executeOnMainThread(() -> { + invoke(window, "setToolbar:", toolbar); + invoke(window, "setShowsToolbarButton:", 1); }, true, true); } } @@ -357,12 +348,7 @@ public class MacMainFrameDecorator extends IdeFrameDecorator implements UISettin } }); - myFullscreenQueue.runOrEnqueue(new Runnable() { - @Override - public void run() { - toggleFullScreenNow(); - } - }); + myFullscreenQueue.runOrEnqueue(() -> toggleFullScreenNow()); return callback; } diff --git a/platform/platform-impl/src/com/intellij/ui/messages/SheetController.java b/platform/platform-impl/src/com/intellij/ui/messages/SheetController.java index 3511604c6631..76a0d017edd4 100755 --- a/platform/platform-impl/src/com/intellij/ui/messages/SheetController.java +++ b/platform/platform-impl/src/com/intellij/ui/messages/SheetController.java @@ -184,14 +184,11 @@ public class SheetController { } void requestFocus() { - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - if (myFocusedComponent != null) { - myFocusedComponent.requestFocus(); - } else { - LOG.debug("My focused component is null for the next message: " + messageTextPane.getText()); - } + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { + if (myFocusedComponent != null) { + myFocusedComponent.requestFocus(); + } else { + LOG.debug("My focused component is null for the next message: " + messageTextPane.getText()); } }); } diff --git a/platform/platform-impl/src/com/intellij/ui/picker/ColorPipetteBase.java b/platform/platform-impl/src/com/intellij/ui/picker/ColorPipetteBase.java index 247cfc0f946c..3d6897374bc5 100644 --- a/platform/platform-impl/src/com/intellij/ui/picker/ColorPipetteBase.java +++ b/platform/platform-impl/src/com/intellij/ui/picker/ColorPipetteBase.java @@ -168,12 +168,7 @@ public abstract class ColorPipetteBase implements ColorPipette { protected void notifyListener(@NotNull final Color c, int delayMillis) { if (!myColorListenersNotifier.isDisposed()) { myColorListenersNotifier.cancelAllRequests(); - myColorListenersNotifier.addRequest(new Runnable() { - @Override - public void run() { - myColorListener.colorChanged(c, ColorPipetteBase.this); - } - }, delayMillis); + myColorListenersNotifier.addRequest(() -> myColorListener.colorChanged(c, ColorPipetteBase.this), delayMillis); } } diff --git a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java index 8439f9180e94..20e1a8cc81d8 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java @@ -936,21 +936,18 @@ public class AbstractPopup implements JBPopup { setMinimumSize(myMinSize); - final Runnable afterShow = new Runnable() { - @Override - public void run() { - if (myPreferredFocusedComponent != null && myInStack && myFocusable) { - myFocusTrackback.registerFocusComponent(myPreferredFocusedComponent); - if (myPreferredFocusedComponent instanceof JTextComponent) { - IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent); - } + final Runnable afterShow = () -> { + if (myPreferredFocusedComponent != null && myInStack && myFocusable) { + myFocusTrackback.registerFocusComponent(myPreferredFocusedComponent); + if (myPreferredFocusedComponent instanceof JTextComponent) { + IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent); } - - removeActivity(); - - afterShow(); - } + + removeActivity(); + + afterShow(); + }; if (myRequestFocus) { @@ -967,45 +964,34 @@ public class AbstractPopup implements JBPopup { final ActionCallback result = new ActionCallback(); - final Runnable afterShowRunnable = new Runnable() { - @Override - public void run() { - afterShow.run(); - result.setDone(); - } + final Runnable afterShowRunnable = () -> { + afterShow.run(); + result.setDone(); }; if (myNativePopup) { final FocusRequestor furtherRequestor = getFocusManager().getFurtherRequestor(); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isDisposed()) { - result.setRejected(); - return; - } - - furtherRequestor.requestFocus(new FocusCommand() { - @NotNull - @Override - public ActionCallback run() { - if (isDisposed()) { - return ActionCallback.REJECTED; - } - - _requestFocus(); - - afterShowRunnable.run(); - - return ActionCallback.DONE; - } - }, true).notify(result).doWhenProcessed(new Runnable() { - @Override - public void run() { - removeActivity(); - } - }); + SwingUtilities.invokeLater(() -> { + if (isDisposed()) { + result.setRejected(); + return; } + + furtherRequestor.requestFocus(new FocusCommand() { + @NotNull + @Override + public ActionCallback run() { + if (isDisposed()) { + return ActionCallback.REJECTED; + } + + _requestFocus(); + + afterShowRunnable.run(); + + return ActionCallback.DONE; + } + }, true).notify(result).doWhenProcessed(() -> removeActivity()); }); } else { afterShowRunnable.run(); @@ -1013,36 +999,27 @@ public class AbstractPopup implements JBPopup { return result; } - }, true).doWhenRejected(new Runnable() { - @Override - public void run() { - afterShow.run(); - } + }, true).doWhenRejected(() -> { + afterShow.run(); }); } else { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isDisposed()) { - removeActivity(); - return; - } - - if (X_WINDOW_FOCUS_BUG && !myRequestFocus && prevOwner != null && - Registry.is("actionSystem.xWindow.remove.focus.from.nonFocusable.popups")) { - new Alarm().addRequest(new Runnable() { - @Override - public void run() { - if (isFocused()) { - IdeFocusManager.getInstance(myProject).requestFocus(prevOwner, false); - } - } - }, Registry.intValue("actionSystem.xWindow.remove.focus.from.nonFocusable.popups.delay")); - } - - afterShow.run(); + SwingUtilities.invokeLater(() -> { + if (isDisposed()) { + removeActivity(); + return; } + + if (X_WINDOW_FOCUS_BUG && !myRequestFocus && prevOwner != null && + Registry.is("actionSystem.xWindow.remove.focus.from.nonFocusable.popups")) { + new Alarm().addRequest(() -> { + if (isFocused()) { + IdeFocusManager.getInstance(myProject).requestFocus(prevOwner, false); + } + }, Registry.intValue("actionSystem.xWindow.remove.focus.from.nonFocusable.popups.delay")); + } + + afterShow.run(); }); } debugState("popup shown", State.SHOWING); @@ -1077,12 +1054,7 @@ public class AbstractPopup implements JBPopup { private static void installWindowHook(final AbstractPopup popup) { if (popup.myCancelOnWindow) { popup.myCancelOnWindow = false; - new Alarm(popup).addRequest(new Runnable() { - @Override - public void run() { - popup.myCancelOnWindow = true; - } - }, 100); + new Alarm(popup).addRequest(() -> popup.myCancelOnWindow = true, 100); } } diff --git a/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java b/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java index 64fcd0c6c9f9..5d47fbce983b 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/PopupComponent.java @@ -164,11 +164,7 @@ public interface PopupComponent { myDialog.setVisible(true); AwtPopupWrapper.fixFlickering(myDialog, true); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - myDialog.setFocusableWindowState(true); - } - }); + SwingUtilities.invokeLater(() -> myDialog.setFocusableWindowState(true)); } } diff --git a/platform/platform-impl/src/com/intellij/ui/popup/PopupFactoryImpl.java b/platform/platform-impl/src/com/intellij/ui/popup/PopupFactoryImpl.java index 5050b3df09a0..fd858b29046d 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/PopupFactoryImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/PopupFactoryImpl.java @@ -359,11 +359,8 @@ public class PopupFactoryImpl extends JBPopupFactory { final ActionPopupStep actionPopupStep = ObjectUtils.tryCast(listStep, ActionPopupStep.class); if (actionPopupStep == null) return; - List filtered = ContainerUtil.mapNotNull(selectedValues, new Function() { - @Override - public ToggleAction fun(Object o) { - return getActionByClass(o, actionPopupStep, ToggleAction.class); - } + List filtered = ContainerUtil.mapNotNull(selectedValues, o -> { + return getActionByClass(o, actionPopupStep, ToggleAction.class); }); for (ToggleAction action : filtered) { @@ -869,12 +866,7 @@ public class PopupFactoryImpl extends JBPopupFactory { myPreselectActionCondition, false); } else { - myFinalRunnable = new Runnable() { - @Override - public void run() { - performAction(action, eventModifiers); - } - }; + myFinalRunnable = () -> performAction(action, eventModifiers); return FINAL_CHOICE; } } diff --git a/platform/platform-impl/src/com/intellij/util/BufferedListConsumer.java b/platform/platform-impl/src/com/intellij/util/BufferedListConsumer.java index 7d563f4fc517..5753923fa09d 100644 --- a/platform/platform-impl/src/com/intellij/util/BufferedListConsumer.java +++ b/platform/platform-impl/src/com/intellij/util/BufferedListConsumer.java @@ -83,19 +83,16 @@ public class BufferedListConsumer implements Consumer> { @NotNull private Runnable createConsumerRunnable(final long ts) { - return new Runnable() { - @Override - public void run() { - myTs = ts; - final List list; - synchronized (myFlushLock) { - myPendingFlush = false; - if (myBuffer.isEmpty()) return; - list = myBuffer; - myBuffer = new ArrayList(mySize); - } - myConsumer.consume(list); + return () -> { + myTs = ts; + final List list; + synchronized (myFlushLock) { + myPendingFlush = false; + if (myBuffer.isEmpty()) return; + list = myBuffer; + myBuffer = new ArrayList(mySize); } + myConsumer.consume(list); }; } @@ -113,11 +110,6 @@ public class BufferedListConsumer implements Consumer> { } public Consumer asConsumer() { - return new Consumer() { - @Override - public void consume(T t) { - consumeOne(t); - } - }; + return t -> consumeOne(t); } } diff --git a/platform/platform-impl/src/com/intellij/util/MergingBackgroundExecutor.java b/platform/platform-impl/src/com/intellij/util/MergingBackgroundExecutor.java index 79382f578ae0..4c896ee3722b 100644 --- a/platform/platform-impl/src/com/intellij/util/MergingBackgroundExecutor.java +++ b/platform/platform-impl/src/com/intellij/util/MergingBackgroundExecutor.java @@ -40,21 +40,11 @@ public class MergingBackgroundExecutor { public void queue(@NotNull final T t) { - myExecutorService.execute(new Runnable() { - @Override - public void run() { - myConsumer.consume(t); - } - }); + myExecutorService.execute(() -> myConsumer.consume(t)); } @NotNull public static MergingBackgroundExecutor newRunnableExecutor(int maxThreads) { - return new MergingBackgroundExecutor(maxThreads, new Consumer() { - @Override - public void consume(Runnable runnable) { - runnable.run(); - } - }); + return new MergingBackgroundExecutor(maxThreads, runnable -> runnable.run()); } } diff --git a/platform/platform-impl/src/com/intellij/util/MessageBusUtil.java b/platform/platform-impl/src/com/intellij/util/MessageBusUtil.java index df27ebfc35a4..467c1f70b846 100644 --- a/platform/platform-impl/src/com/intellij/util/MessageBusUtil.java +++ b/platform/platform-impl/src/com/intellij/util/MessageBusUtil.java @@ -33,12 +33,9 @@ import org.jetbrains.annotations.NotNull; public class MessageBusUtil { private static Runnable createPublisherRunnable(final Project project, final Topic topic, final Consumer listener) { - return new Runnable() { - @Override - public void run() { - if (project.isDisposed()) throw new ProcessCanceledException(); - listener.consume(project.getMessageBus().syncPublisher(topic)); - } + return () -> { + if (project.isDisposed()) throw new ProcessCanceledException(); + listener.consume(project.getMessageBus().syncPublisher(topic)); }; } diff --git a/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ResponseProcessor.java b/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ResponseProcessor.java index 90b242961dd4..b444a292aac5 100644 --- a/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ResponseProcessor.java +++ b/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ResponseProcessor.java @@ -35,31 +35,29 @@ public class ResponseProcessor { } public void startReading(final ResponseReader reader) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - myThread = Thread.currentThread(); - try { - while (true) { - final R r = reader.readResponse(); - if (r == null) break; - if (r instanceof ResponseToRequest) { - final int requestId = ((ResponseToRequest)r).getRequestId(); - processResponse(requestId, r); - } - else { - processResponse(r); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + myThread = Thread.currentThread(); + try { + while (true) { + final R r = reader.readResponse(); + if (r == null) break; + if (r instanceof ResponseToRequest) { + final int requestId = ((ResponseToRequest)r).getRequestId(); + processResponse(requestId, r); + } + else { + processResponse(r); } } - catch (InterruptedException ignored) { - } - catch (IOException e) { - LOG.info(e); - } - finally { - synchronized (myLock) { - myStopped = true; - } + } + catch (InterruptedException ignored) { + } + catch (IOException e) { + LOG.info(e); + } + finally { + synchronized (myLock) { + myStopped = true; } } }); @@ -162,11 +160,7 @@ public class ResponseProcessor { LOG.debug("schedule timeout check in " + delay + "ms"); if (delay > 10) { myTimeoutAlarm.cancelAllRequests(); - myTimeoutAlarm.addRequest(new Runnable() { - public void run() { - checkTimeout(); - } - }, delay); + myTimeoutAlarm.addRequest(() -> checkTimeout(), delay); } else { checkTimeout(); diff --git a/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ServerSocketConnectionImpl.java b/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ServerSocketConnectionImpl.java index 76f30d2ed83a..7347397e1c03 100644 --- a/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ServerSocketConnectionImpl.java +++ b/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/ServerSocketConnectionImpl.java @@ -47,15 +47,13 @@ public class ServerSocketConnectionImpl { + try { + waitForConnection(); + } + catch (IOException e) { + LOG.info(e); + setStatus(ConnectionStatus.CONNECTION_FAILED, "Connection failed: " + e.getMessage()); } }); } diff --git a/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/SocketConnectionImpl.java b/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/SocketConnectionImpl.java index 5fc8fa284a29..2848028a5bc8 100644 --- a/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/SocketConnectionImpl.java +++ b/platform/platform-impl/src/com/intellij/util/io/socketConnection/impl/SocketConnectionImpl.java @@ -49,16 +49,13 @@ public class SocketConnectionImpl { + try { + attachToSocket(socket); + } + catch (IOException e) { + LOG.info(e); + setStatus(ConnectionStatus.CONNECTION_FAILED, "Connection failed: " + e.getMessage()); } }); } @@ -91,81 +88,75 @@ public class SocketConnectionImpl { + Exception exception = null; + InetAddress host = myHost; + if (host == null) { + host = InetAddress.getLoopbackAddress(); } + + for (int attempt = 0; attempt < MAX_CONNECTION_ATTEMPTS; attempt++) { + for (int i = 0; i < myPortsNumberToTry; i++) { + Socket socket; + try { + //noinspection SocketOpenedButNotSafelyClosed + socket = new Socket(host, myInitialPort + i); + } + catch (IOException e) { + LOG.debug(e); + exception = e; + continue; + } + + setPort(socket.getPort()); + try { + attachToSocket(socket); + } + catch (IOException e) { + LOG.info(e); + } + return; + } + + try { + //noinspection BusyWait + Thread.sleep(CONNECTION_ATTEMPT_DELAY); + } + catch (InterruptedException e) { + exception = e; + break; + } + } + + setStatus(ConnectionStatus.CONNECTION_FAILED, + exception == null ? "Connection failed" : "Connection failed: " + exception.getMessage()); }); } @Override public void startPolling() { setStatus(ConnectionStatus.WAITING_FOR_CONNECTION, null); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - addThreadToInterrupt(); - try { - for (int attempt = 0; attempt < MAX_CONNECTION_ATTEMPTS; attempt++) { - try { - open(); - return; - } - catch (IOException e) { - LOG.debug(e); - } - - //noinspection BusyWait - Thread.sleep(CONNECTION_ATTEMPT_DELAY); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + addThreadToInterrupt(); + try { + for (int attempt = 0; attempt < MAX_CONNECTION_ATTEMPTS; attempt++) { + try { + open(); + return; } - setStatus(ConnectionStatus.CONNECTION_FAILED, "Cannot connect to " + (myHost != null ? myHost : "localhost") + ", the maximum number of connection attempts exceeded"); - } - catch (InterruptedException ignored) { - } - finally { - removeThreadToInterrupt(); + catch (IOException e) { + LOG.debug(e); + } + + //noinspection BusyWait + Thread.sleep(CONNECTION_ATTEMPT_DELAY); } + setStatus(ConnectionStatus.CONNECTION_FAILED, "Cannot connect to " + (myHost != null ? myHost : "localhost") + ", the maximum number of connection attempts exceeded"); + } + catch (InterruptedException ignored) { + } + finally { + removeThreadToInterrupt(); } }); } diff --git a/platform/platform-impl/src/com/intellij/util/ui/CheckBoxListModelEditor.java b/platform/platform-impl/src/com/intellij/util/ui/CheckBoxListModelEditor.java index 8ed38dca15d0..2b0432efb152 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/CheckBoxListModelEditor.java +++ b/platform/platform-impl/src/com/intellij/util/ui/CheckBoxListModelEditor.java @@ -50,17 +50,14 @@ public class CheckBoxListModelEditor { @NotNull public CheckBoxListModelEditor editAction(final @NotNull Function consumer) { - final Runnable action = new Runnable() { - @Override - public void run() { - T item = getSelectedItem(); - if (item != null) { - T newItem = consumer.fun(item); - if (newItem != null) { - list.updateItem(item, newItem, StringUtil.notNullize(toNameConverter.fun(newItem))); - } - list.requestFocus(); + final Runnable action = () -> { + T item = getSelectedItem(); + if (item != null) { + T newItem = consumer.fun(item); + if (newItem != null) { + list.updateItem(item, newItem, StringUtil.notNullize(toNameConverter.fun(newItem))); } + list.requestFocus(); } }; toolbarDecorator.setEditAction(new AnActionButtonRunnable() { diff --git a/platform/platform-impl/src/com/intellij/util/ui/ListModelEditor.java b/platform/platform-impl/src/com/intellij/util/ui/ListModelEditor.java index e90d938b6323..fc9cc4841597 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/ListModelEditor.java +++ b/platform/platform-impl/src/com/intellij/util/ui/ListModelEditor.java @@ -88,12 +88,9 @@ public class ListModelEditor extends ListModelEditorBase { // todo should we really do this? //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!model.isEmpty()) { - list.setSelectedIndex(0); - } + SwingUtilities.invokeLater(() -> { + if (!model.isEmpty()) { + list.setSelectedIndex(0); } }); } diff --git a/platform/platform-impl/src/com/intellij/util/ui/LocalPathCellEditor.java b/platform/platform-impl/src/com/intellij/util/ui/LocalPathCellEditor.java index 8fac2563e0ca..f198e70cbca2 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/LocalPathCellEditor.java +++ b/platform/platform-impl/src/com/intellij/util/ui/LocalPathCellEditor.java @@ -88,15 +88,12 @@ public class LocalPathCellEditor extends AbstractTableCellEditor { public void actionPerformed(ActionEvent e) { String initial = (String)getCellEditorValue(); VirtualFile initialFile = StringUtil.isNotEmpty(initial) ? LocalFileSystem.getInstance().findFileByPath(initial) : null; - FileChooser.chooseFile(getFileChooserDescriptor(), myProject, table, initialFile, new Consumer() { - @Override - public void consume(VirtualFile file) { - String path = file.getPresentableUrl(); - if (SystemInfo.isWindows && path.length() == 2 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':') { - path += "\\"; // make path absolute - } - myComponent.getChildComponent().setText(path); + FileChooser.chooseFile(getFileChooserDescriptor(), myProject, table, initialFile, file -> { + String path = file.getPresentableUrl(); + if (SystemInfo.isWindows && path.length() == 2 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':') { + path += "\\"; // make path absolute } + myComponent.getChildComponent().setText(path); }); } }; diff --git a/platform/platform-impl/src/com/intellij/util/ui/ReloadablePanel.java b/platform/platform-impl/src/com/intellij/util/ui/ReloadablePanel.java index 0b8341555126..ea28881b7ee1 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/ReloadablePanel.java +++ b/platform/platform-impl/src/com/intellij/util/ui/ReloadablePanel.java @@ -120,14 +120,11 @@ public abstract class ReloadablePanel { } public final void onValuesUpdateError(@NotNull final String errorMessage) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (getSelectedValue() == null) { - myErrorMessage.setText(errorMessage); - } - changeUpdateStatus(UpdateStatus.IDLE); + UIUtil.invokeLaterIfNeeded(() -> { + if (getSelectedValue() == null) { + myErrorMessage.setText(errorMessage); } + changeUpdateStatus(UpdateStatus.IDLE); }); } diff --git a/platform/platform-impl/src/com/intellij/util/ui/SwingHelper.java b/platform/platform-impl/src/com/intellij/util/ui/SwingHelper.java index 7eff39958f33..96157243ac3d 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/SwingHelper.java +++ b/platform/platform-impl/src/com/intellij/util/ui/SwingHelper.java @@ -211,55 +211,43 @@ public class SwingHelper { public static void resizeDialogToFitTextFor(@NotNull final JComponent... components) { if (components.length == 0) return; - doWithDialogWrapper(components[0], new Consumer() { - @Override - public void consume(final DialogWrapper dialogWrapper) { - if (dialogWrapper instanceof SettingsDialog || dialogWrapper instanceof SingleConfigurableEditor) { - for (Component component : components) { - if (component instanceof TextFieldWithHistoryWithBrowseButton) { - setPreferredWidthToFitText((TextFieldWithHistoryWithBrowseButton)component); - } - else if (component instanceof TextFieldWithBrowseButton) { - setPreferredWidthToFitText((TextFieldWithBrowseButton)component); - } - else if (component instanceof JTextField) { - setPreferredWidthToFitText((JTextField)component); - } + doWithDialogWrapper(components[0], dialogWrapper -> { + if (dialogWrapper instanceof SettingsDialog || dialogWrapper instanceof SingleConfigurableEditor) { + for (Component component : components) { + if (component instanceof TextFieldWithHistoryWithBrowseButton) { + setPreferredWidthToFitText((TextFieldWithHistoryWithBrowseButton)component); + } + else if (component instanceof TextFieldWithBrowseButton) { + setPreferredWidthToFitText((TextFieldWithBrowseButton)component); + } + else if (component instanceof JTextField) { + setPreferredWidthToFitText((JTextField)component); } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - adjustDialogSizeToFitPreferredSize(dialogWrapper); - } - }, ModalityState.any()); } + ApplicationManager.getApplication().invokeLater(() -> { + adjustDialogSizeToFitPreferredSize(dialogWrapper); + }, ModalityState.any()); } }); } private static void doWithDialogWrapper(@NotNull final JComponent component, @NotNull final Consumer consumer) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (component.getClientProperty(DIALOG_RESIZED_TO_FIT_TEXT) != null) { - return; - } - component.putClientProperty(DIALOG_RESIZED_TO_FIT_TEXT, true); - DialogWrapper dialogWrapper = DialogWrapper.findInstance(component); - if (dialogWrapper != null) { - consumer.consume(dialogWrapper); - } - else { - UiNotifyConnector.doWhenFirstShown(component, new Runnable() { - @Override - public void run() { - DialogWrapper dialogWrapper = DialogWrapper.findInstance(component); - if (dialogWrapper != null) { - consumer.consume(dialogWrapper); - } - } - }); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (component.getClientProperty(DIALOG_RESIZED_TO_FIT_TEXT) != null) { + return; + } + component.putClientProperty(DIALOG_RESIZED_TO_FIT_TEXT, true); + DialogWrapper dialogWrapper = DialogWrapper.findInstance(component); + if (dialogWrapper != null) { + consumer.consume(dialogWrapper); + } + else { + UiNotifyConnector.doWhenFirstShown(component, () -> { + DialogWrapper dialogWrapper1 = DialogWrapper.findInstance(component); + if (dialogWrapper1 != null) { + consumer.consume(dialogWrapper1); + } + }); } }); } diff --git a/platform/platform-impl/src/com/intellij/util/ui/table/TableModelEditor.java b/platform/platform-impl/src/com/intellij/util/ui/table/TableModelEditor.java index 7dc1579b98ba..e5230d5152cc 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/table/TableModelEditor.java +++ b/platform/platform-impl/src/com/intellij/util/ui/table/TableModelEditor.java @@ -116,12 +116,7 @@ public class TableModelEditor extends CollectionModelEditor() { - @Override - public T fun(T item) { - return helper.getMutable(item, selectedRow); - } - }; + mutator = item12 -> helper.getMutable(item12, selectedRow); } ((DialogItemEditor)itemEditor).edit(item, mutator, false); table.requestFocus(); @@ -140,12 +135,9 @@ public class TableModelEditor extends CollectionModelEditor)itemEditor).edit(item, new Function() { - @Override - public T fun(T item) { - model.addRow(item); - return item; - } + ((DialogItemEditor)itemEditor).edit(item, item1 -> { + model.addRow(item1); + return item1; }, true); } }); diff --git a/platform/platform-impl/src/org/jetbrains/io/PowerSupplyKit.java b/platform/platform-impl/src/org/jetbrains/io/PowerSupplyKit.java index 084281ab006f..b34f5534b33b 100644 --- a/platform/platform-impl/src/org/jetbrains/io/PowerSupplyKit.java +++ b/platform/platform-impl/src/org/jetbrains/io/PowerSupplyKit.java @@ -130,13 +130,8 @@ public class PowerSupplyKit { //final Notification powerSafeModeSwitchedNotification = // new Notification(POWER_SUPPLY_GROUP_ID, "\"Power Save\" mode ", message, type, listener); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().getMessageBus(). - syncPublisher(Notifications.TOPIC).notify(automaticPowerSafeModeSwitchNotification); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> ApplicationManager.getApplication().getMessageBus(). + syncPublisher(Notifications.TOPIC).notify(automaticPowerSafeModeSwitchNotification)); powerSupplyKitHasBeenInitialized = true; } diff --git a/platform/platform-main/src/com/intellij/idea/MainImpl.java b/platform/platform-main/src/com/intellij/idea/MainImpl.java index abb1948773d5..4532035af55e 100644 --- a/platform/platform-main/src/com/intellij/idea/MainImpl.java +++ b/platform/platform-main/src/com/intellij/idea/MainImpl.java @@ -35,24 +35,16 @@ public class MainImpl { @Override public void start(final boolean newConfigFolder) { //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - PluginManager.installExceptionHandler(); + SwingUtilities.invokeLater(() -> { + PluginManager.installExceptionHandler(); - if (newConfigFolder && !ConfigImportHelper.isConfigImported()) { - StartupUtil.runStartupWizard(); - } - - final IdeaApplication app = new IdeaApplication(args); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - app.run(); - } - }); + if (newConfigFolder && !ConfigImportHelper.isConfigImported()) { + StartupUtil.runStartupWizard(); } + + final IdeaApplication app = new IdeaApplication(args); + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> app.run()); }); } }); diff --git a/platform/platform-tests/testSrc/com/intellij/application/options/codeInsight/editor/quotes/SelectionQuotingTypedHandlerTest.java b/platform/platform-tests/testSrc/com/intellij/application/options/codeInsight/editor/quotes/SelectionQuotingTypedHandlerTest.java index 0092d115c8c1..08f095c3c6ab 100644 --- a/platform/platform-tests/testSrc/com/intellij/application/options/codeInsight/editor/quotes/SelectionQuotingTypedHandlerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/application/options/codeInsight/editor/quotes/SelectionQuotingTypedHandlerTest.java @@ -40,11 +40,8 @@ public class SelectionQuotingTypedHandlerTest extends LightPlatformCodeInsightFi * @param action Runnable to be executed */ public static void performAction(final Project project, final Runnable action) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(project, action, "test command", null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, action, "test command", null); }); } @@ -115,13 +112,10 @@ public class SelectionQuotingTypedHandlerTest extends LightPlatformCodeInsightFi myFixture.configureByText(FileTypes.PLAIN_TEXT, before); final TypedAction typedAction = EditorActionManager.getInstance().getTypedAction(); - performAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - for (int i = 0, max = cs.length(); i < max; i++) { - final char c = cs.charAt(i); - typedAction.actionPerformed(myFixture.getEditor(), c, ((EditorEx)myFixture.getEditor()).getDataContext()); - } + performAction(myFixture.getProject(), () -> { + for (int i = 0, max = cs.length(); i < max; i++) { + final char c = cs.charAt(i); + typedAction.actionPerformed(myFixture.getEditor(), c, ((EditorEx)myFixture.getEditor()).getDataContext()); } }); myFixture.checkResult(expected); @@ -132,22 +126,15 @@ public class SelectionQuotingTypedHandlerTest extends LightPlatformCodeInsightFi myFixture.getEditor().getCaretModel().moveToOffset(0); myFixture.getEditor().getSelectionModel().setSelection(0, 5); final TypedAction typedAction = EditorActionManager.getInstance().getTypedAction(); - performAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - typedAction.actionPerformed(myFixture.getEditor(), '\'', ((EditorEx)myFixture.getEditor()).getDataContext()); - } - }); + performAction(myFixture.getProject(), + () -> typedAction.actionPerformed(myFixture.getEditor(), '\'', ((EditorEx)myFixture.getEditor()).getDataContext())); myFixture.getEditor().getSelectionModel().removeSelection(); myFixture.checkResult("'aaa'\nbbb\n\n"); myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getDocument().getLineStartOffset(3)); - performAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - typedAction.actionPerformed(myFixture.getEditor(), 'A', ((EditorEx)myFixture.getEditor()).getDataContext()); - typedAction.actionPerformed(myFixture.getEditor(), 'B', ((EditorEx)myFixture.getEditor()).getDataContext()); - } + performAction(myFixture.getProject(), () -> { + typedAction.actionPerformed(myFixture.getEditor(), 'A', ((EditorEx)myFixture.getEditor()).getDataContext()); + typedAction.actionPerformed(myFixture.getEditor(), 'B', ((EditorEx)myFixture.getEditor()).getDataContext()); }); myFixture.checkResult("'aaa'\nbbb\n\nAB"); } diff --git a/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/ReformatOnlyVcsChangedTextTest.java b/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/ReformatOnlyVcsChangedTextTest.java index edc724385f13..06045a49a535 100644 --- a/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/ReformatOnlyVcsChangedTextTest.java +++ b/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/ReformatOnlyVcsChangedTextTest.java @@ -356,12 +356,7 @@ public class ReformatOnlyVcsChangedTextTest extends LightPlatformTestCase { private void assertFormattedRangesEqualsTo(@NotNull PsiFile file, ChangedLines... expected) { ChangedLines[] formatted = myMockCodeStyleManager.getFormattedLinesFor(file); - Comparator cmp = new Comparator() { - @Override - public int compare(ChangedLines o1, ChangedLines o2) { - return o1.from < o2.from ? -1 : 1; - } - }; + Comparator cmp = (o1, o2) -> o1.from < o2.from ? -1 : 1; Arrays.sort(expected, cmp); Arrays.sort(formatted, cmp); diff --git a/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/TestFileStructure.java b/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/TestFileStructure.java index ba6e321239fd..3787a2185d4a 100644 --- a/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/TestFileStructure.java +++ b/platform/platform-tests/testSrc/com/intellij/codeInsight/actions/TestFileStructure.java @@ -100,30 +100,24 @@ public class TestFileStructure { public static PsiDirectory createDirectory(@NotNull Project project, @NotNull final VirtualFile parent, @NotNull final String name) throws IOException { final VirtualFile[] dir = new VirtualFile[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - dir[0] = parent.createChildDirectory(null, name); - } - catch (IOException e) { - e.printStackTrace(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + dir[0] = parent.createChildDirectory(null, name); + } + catch (IOException e) { + e.printStackTrace(); } }); return PsiDirectoryFactory.getInstance(project).createDirectory(dir[0]); } public static void delete(@NotNull final VirtualFile file) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - file.delete(null); - } - catch (IOException e) { - e.printStackTrace(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + file.delete(null); + } + catch (IOException e) { + e.printStackTrace(); } }); } diff --git a/platform/platform-tests/testSrc/com/intellij/execution/process/AnsiEscapeDecoderTest.java b/platform/platform-tests/testSrc/com/intellij/execution/process/AnsiEscapeDecoderTest.java index 94bd81c9bb44..17255780614b 100644 --- a/platform/platform-tests/testSrc/com/intellij/execution/process/AnsiEscapeDecoderTest.java +++ b/platform/platform-tests/testSrc/com/intellij/execution/process/AnsiEscapeDecoderTest.java @@ -57,11 +57,8 @@ public class AnsiEscapeDecoderTest extends PlatformTestCase { @NotNull private static List> toListWithKeyName(@NotNull Collection> list) { - return ContainerUtil.map(list, new Function, Pair>() { - @Override - public Pair fun(Pair pair) { - return Pair.create(pair.first, pair.second.toString()); - } + return ContainerUtil.map(list, pair -> { + return Pair.create(pair.first, pair.second.toString()); }); } diff --git a/platform/platform-tests/testSrc/com/intellij/formatting/TestFormattingModel.java b/platform/platform-tests/testSrc/com/intellij/formatting/TestFormattingModel.java index d720ecec23fc..9dc7bf9e4a8e 100644 --- a/platform/platform-tests/testSrc/com/intellij/formatting/TestFormattingModel.java +++ b/platform/platform-tests/testSrc/com/intellij/formatting/TestFormattingModel.java @@ -65,11 +65,8 @@ public class TestFormattingModel implements FormattingModel, FormattingDocumentM final String whiteSpace ) { if (ApplicationManager.getApplication() != null) { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myDocument.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), whiteSpace); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myDocument.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), whiteSpace); }); } else { myDocument.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), whiteSpace); diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/ActionsTest.java b/platform/platform-tests/testSrc/com/intellij/history/integration/ActionsTest.java index fc5c260a344d..7977a349d227 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/ActionsTest.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/ActionsTest.java @@ -58,13 +58,10 @@ public class ActionsTest extends IntegrationTestCase { setContent(f, "file"); setDocumentTextFor(f, "doc1"); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - LocalHistoryAction a = LocalHistory.getInstance().startAction("action"); - setDocumentTextFor(f, "doc2"); - a.finish(); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + LocalHistoryAction a = LocalHistory.getInstance().startAction("action"); + setDocumentTextFor(f, "doc2"); + a.finish(); }, "command", null); List rr = getRevisionsFor(f); diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/BasicsTest.java b/platform/platform-tests/testSrc/com/intellij/history/integration/BasicsTest.java index 63fd088de00f..8ed0a32c0f17 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/BasicsTest.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/BasicsTest.java @@ -38,18 +38,15 @@ public class BasicsTest extends IntegrationTestCase { public void testProcessingCommands() throws Exception { final VirtualFile[] f = new VirtualFile[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new RunnableAdapter() { - @Override - public void doRun() throws IOException { - f[0] = createChildData(myRoot, "f1.txt"); - f[0].setBinaryContent(new byte[]{1}); - f[0].setBinaryContent(new byte[]{2}); - } - }, "name", null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(myProject, new RunnableAdapter() { + @Override + public void doRun() throws IOException { + f[0] = createChildData(myRoot, "f1.txt"); + f[0].setBinaryContent(new byte[]{1}); + f[0].setBinaryContent(new byte[]{2}); + } + }, "name", null); }); diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/FileListeningTest.java b/platform/platform-tests/testSrc/com/intellij/history/integration/FileListeningTest.java index 28b99bf02678..a45195b10b0e 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/FileListeningTest.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/FileListeningTest.java @@ -104,12 +104,7 @@ public class FileListeningTest extends IntegrationTestCase { private static StringBuilder buildDBFileStructure(@NotNull VirtualFile from, int level, @NotNull StringBuilder builder) { List children = ContainerUtil.newArrayList(((NewVirtualFile)from).getCachedChildren()); - Collections.sort(children, new Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(children, (o1, o2) -> o1.getName().compareTo(o2.getName())); for (VirtualFile eachChild : children) { builder.append(StringUtil.repeat(" ", level)).append(eachChild.getName()).append("\n"); buildDBFileStructure(eachChild, level + 1, builder); @@ -332,11 +327,6 @@ public class FileListeningTest extends IntegrationTestCase { } private static void sortEntries(final List entries) { - Collections.sort(entries, new Comparator() { - @Override - public int compare(@NotNull Entry o1, @NotNull Entry o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(entries, (o1, o2) -> o1.getName().compareTo(o2.getName())); } } diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java b/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java index 47009cf110f8..3f03a3e9d2cb 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/IntegrationTestCase.java @@ -144,11 +144,8 @@ public abstract class IntegrationTestCase extends PlatformTestCase { protected void setDocumentTextFor(VirtualFile f, String text) { Document document = FileDocumentManager.getInstance().getDocument(f); assertNotNull(f.getPath(), document); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.setText(text); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.setText(text); }); } @@ -177,24 +174,20 @@ public abstract class IntegrationTestCase extends PlatformTestCase { } protected static void addContentRoot(final Module module, final String path) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ModuleRootModificationUtil.addContentRoot(module, FileUtil.toSystemIndependentName(path)); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ModuleRootModificationUtil.addContentRoot(module, FileUtil.toSystemIndependentName(path)); }); } protected void addExcludedDir(final String path) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ModuleRootManager rm = ModuleRootManager.getInstance(myModule); - ModifiableRootModel m = rm.getModifiableModel(); - for (ContentEntry e : m.getContentEntries()) { - if (!Comparing.equal(e.getFile(), myRoot)) continue; - e.addExcludeFolder(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(path))); - } - m.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + ModuleRootManager rm = ModuleRootManager.getInstance(myModule); + ModifiableRootModel m = rm.getModifiableModel(); + for (ContentEntry e : m.getContentEntries()) { + if (!Comparing.equal(e.getFile(), myRoot)) continue; + e.addExcludeFolder(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(path))); } + m.commit(); }); } diff --git a/platform/platform-tests/testSrc/com/intellij/ide/ActivityMonitorTest.java b/platform/platform-tests/testSrc/com/intellij/ide/ActivityMonitorTest.java index 8e0a0b1e9aa3..d3e9f0d6b373 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/ActivityMonitorTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/ActivityMonitorTest.java @@ -181,12 +181,7 @@ public class ActivityMonitorTest extends LightPlatformTestCase { assertTrue("Must be READY, but was: BUSY", busy.isReady()); final boolean[] done = {false}; - busy.getReady(this).doWhenDone(new Runnable() { - @Override - public void run() { - done[0] = true; - } - }); + busy.getReady(this).doWhenDone(() -> done[0] = true); assertTrue(done[0]); } diff --git a/platform/platform-tests/testSrc/com/intellij/ide/codeStyleSettings/CodeSamplesCorrectnessTest.java b/platform/platform-tests/testSrc/com/intellij/ide/codeStyleSettings/CodeSamplesCorrectnessTest.java index 48febfe65daa..c4e1f48a0769 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/codeStyleSettings/CodeSamplesCorrectnessTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/codeStyleSettings/CodeSamplesCorrectnessTest.java @@ -99,11 +99,8 @@ public class CodeSamplesCorrectnessTest extends LightPlatformCodeInsightFixtureT @NotNull private static String formReport(@NotNull List errorReports) { - return StringUtil.join(errorReports, new Function() { - @Override - public String fun(CodeErrorReport report) { - return report.createReport(); - } + return StringUtil.join(errorReports, report -> { + return report.createReport(); }, "\n"); } } diff --git a/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java b/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java index c8ea1b86fbeb..35329f6e6793 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java @@ -141,11 +141,8 @@ public class LightFileTemplatesTest extends LightPlatformTestCase { private static void closeProject(final Project project) { if (project != null && !project.isDisposed()) { ProjectManager.getInstance().closeProject(project); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Disposer.dispose(project); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Disposer.dispose(project); }); } } diff --git a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderCrashTest.java b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderCrashTest.java index c9a2ffdb0ae0..63bbc98cee45 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderCrashTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderCrashTest.java @@ -20,22 +20,16 @@ public abstract class AbstractTreeBuilderCrashTest extends BaseTreeTestCase { } public void testElementMovedButNodeIsStillInStructure() throws Exception { - assertNodeMove(new Runnable() { - @Override - public void run() { - getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder1")); - getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder2")); - } + assertNodeMove(() -> { + getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder1")); + getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder2")); }); } public void testElementMovedButNodeIsStillInStructure2() throws Exception { - assertNodeMove(new Runnable() { - @Override - public void run() { - getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder2")); - getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder1")); - } + assertNodeMove(() -> { + getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder2")); + getBuilder().addSubtreeToUpdateByElement(myRoot.getChild("folder1")); }); } diff --git a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java index 05b791c078e2..5d92ec50939b 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/AbstractTreeBuilderTest.java @@ -191,43 +191,30 @@ abstract class AbstractTreeBuilderTest extends BaseTreeTestCase { + myCom = root.addChild("com"); + myIntellij = myCom.addChild("intellij"); + myOpenApi = myIntellij.addChild("openapi"); + myFabrique = root.addChild("jetbrains").addChild("fabrique"); + myIde = myFabrique.addChild("ide"); + myRunner = root.addChild("xUnit").addChild("runner"); + myRcp = root.addChild("org").addChild("eclipse").addChild("rcp"); - if (activate) { - getBuilder().getUi().activate(true); - } + if (activate) { + getBuilder().getUi().activate(true); } }); } protected void activate() throws Exception { - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().getUi().activate(true); - } - }); + doAndWaitForBuilder(() -> getBuilder().getUi().activate(true)); } void hideTree() throws Exception { Assert.assertFalse(getMyBuilder().myWasCleanedUp); - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().getUi().deactivate(); - } - }); + invokeLaterIfNeeded(() -> getBuilder().getUi().deactivate()); final WaitFor waitFor = new WaitFor() { @Override @@ -261,24 +248,11 @@ abstract class AbstractTreeBuilderTest extends BaseTreeTestCase { + if (select) { + getBuilder().select(element, () -> done[0] = true, addToSelection); + } else { + getBuilder().expand(element, () -> done[0] = true); } }, new Condition() { @Override diff --git a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java index fc5c5edec615..902539ae62d4 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java @@ -69,12 +69,9 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { void doAndWaitForBuilder(final Runnable runnable, final Condition condition) throws Exception { final AtomicBoolean started = new AtomicBoolean(); - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - started.set(true); - runnable.run(); - } + invokeLaterIfNeeded(() -> { + started.set(true); + runnable.run(); }); waitBuilderToCome(new Condition() { @@ -99,17 +96,14 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { @Override protected boolean condition() { final boolean[] ready = {false}; - invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - AbstractTreeUi ui = getBuilder().getUi(); - if (ui == null) { - ready[0] = true; - return; - } - - ready[0] = myCancelRequest != null || myReadyRequest || condition.value(null) && ui.isReady(); + invokeAndWaitIfNeeded(() -> { + AbstractTreeUi ui = getBuilder().getUi(); + if (ui == null) { + ready[0] = true; + return; } + + ready[0] = myCancelRequest != null || myReadyRequest || condition.value(null) && ui.isReady(); }); return ready[0]; @@ -130,22 +124,12 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { } void expand(final TreePath p) throws Exception { - invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - myTree.expandPath(p); - } - }); + invokeAndWaitIfNeeded(() -> myTree.expandPath(p)); waitBuilderToCome(); } void collapsePath(final TreePath p) throws Exception { - invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - myTree.collapsePath(p); - } - }); + invokeAndWaitIfNeeded(() -> myTree.collapsePath(p)); waitBuilderToCome(); } @@ -346,12 +330,9 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { @Override protected void tearDown() throws Exception { - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (getBuilder() != null) { - Disposer.dispose(getBuilder()); - } + invokeLaterIfNeeded(() -> { + if (getBuilder() != null) { + Disposer.dispose(getBuilder()); } }); @@ -384,12 +365,7 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { } void updateFromRoot(final boolean withStructure) throws Exception { - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().queueUpdate(withStructure); - } - }); + doAndWaitForBuilder(() -> getBuilder().queueUpdate(withStructure)); } void updateFrom(final NodeElement element) throws Exception { @@ -397,21 +373,11 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { } void updateFrom(final NodeElement element, final boolean forceResort) throws Exception { - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().queueUpdateFrom(element, forceResort); - } - }); + doAndWaitForBuilder(() -> getBuilder().queueUpdateFrom(element, forceResort)); } void showTree() throws Exception { - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().getUi().activate(true); - } - }); + doAndWaitForBuilder(() -> getBuilder().getUi().activate(true)); } void select(final Object element, final boolean addToSelection) throws Exception { @@ -424,17 +390,7 @@ abstract class BaseTreeTestCase extends FlyIdeaTestCase { void select(final Object[] elements, final boolean addToSelection, final boolean canBeInterrupted) throws Exception { final AtomicBoolean done = new AtomicBoolean(); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().select(elements, new Runnable() { - @Override - public void run() { - done.set(true); - } - }, addToSelection); - } - }, new Condition() { + doAndWaitForBuilder(() -> getBuilder().select(elements, () -> done.set(true), addToSelection), new Condition() { @Override public boolean value(Object o) { return done.get() || canBeInterrupted && getBuilder().getUi().isCancelledReady(); diff --git a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java index 28754501eb10..7fcf562e5385 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/TreeUiTest.java @@ -86,15 +86,12 @@ public class TreeUiTest extends AbstractTreeBuilderTest { public void testDoubleCancelUpdate() throws Exception { buildStructure(myRoot); - runAndInterrupt(new Runnable() { - @Override - public void run() { - try { - select(new Object[] {new NodeElement("openapi")}, false, true); - } - catch (Exception e) { - fail(); - } + runAndInterrupt(() -> { + try { + select(new Object[] {new NodeElement("openapi")}, false, true); + } + catch (Exception e) { + fail(); } }, "getChildren", new NodeElement("intellij"), Interruption.invokeCancel); @@ -147,18 +144,13 @@ public class TreeUiTest extends AbstractTreeBuilderTest { } }; - invokeLaterIfNeeded(new Runnable() { + invokeLaterIfNeeded(() -> getBuilder().batch(new Progressive() { @Override - public void run() { - getBuilder().batch(new Progressive() { - @Override - public void run(@NotNull ProgressIndicator indicator) { - indicatorRef.set(indicator); - expandNext(toExpand, 0, indicator, done); - } - }).notify(done); + public void run(@NotNull ProgressIndicator indicator) { + indicatorRef.set(indicator); + expandNext(toExpand, 0, indicator, done); } - }); + }).notify(done)); waitBuilderToCome(new Condition() { @Override @@ -296,12 +288,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { } }; - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().expand(new NodeElement("fabrique"), null); - } - }); + invokeLaterIfNeeded(() -> getBuilder().expand(new NodeElement("fabrique"), null)); waitBuilderToCome(new Condition() { @Override @@ -413,18 +400,13 @@ public class TreeUiTest extends AbstractTreeBuilderTest { final ActionCallback done = new ActionCallback(); final Ref indicatorRef = new Ref(); - invokeLaterIfNeeded(new Runnable() { + invokeLaterIfNeeded(() -> getBuilder().batch(new Progressive() { @Override - public void run() { - getBuilder().batch(new Progressive() { - @Override - public void run(@NotNull ProgressIndicator indicator) { - indicatorRef.set(indicator); - expandNext(toExpand, 0, indicator, done); - } - }).notify(done); + public void run(@NotNull ProgressIndicator indicator) { + indicatorRef.set(indicator); + expandNext(toExpand, 0, indicator, done); } - }); + }).notify(done)); waitBuilderToCome(new Condition() { @Override @@ -446,17 +428,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { assertTree("+/\n"); final Ref done = new Ref(); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().expandAll(new Runnable() { - @Override - public void run() { - done.set(true); - } - }); - } - }); + doAndWaitForBuilder(() -> getBuilder().expandAll(() -> done.set(true))); assertTree("-/\n" + " -com\n" @@ -606,12 +578,9 @@ public class TreeUiTest extends AbstractTreeBuilderTest { activate(); expand(getPath("/")); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myTree.expandPath(getPath("org")); - myTree.setSelectionPath(myTree.getPathForRow(5)); - } + doAndWaitForBuilder(() -> { + myTree.expandPath(getPath("org")); + myTree.setSelectionPath(myTree.getPathForRow(5)); }); assertTree("-/\n" @@ -622,12 +591,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { + " +[jetbrains]\n" + " +xUnit\n"); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myTree.expandPath(myTree.getPathForRow(5)); - } - }); + doAndWaitForBuilder(() -> myTree.expandPath(myTree.getPathForRow(5))); assertTree("-/\n" + " +com\n" @@ -638,12 +602,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { + " +community\n" + " +xUnit\n"); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myTree.expandPath(myTree.getPathForRow(6)); - } - }); + doAndWaitForBuilder(() -> myTree.expandPath(myTree.getPathForRow(6))); assertTree("-/\n" + " +com\n" @@ -655,12 +614,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { + " ide\n" + " +xUnit\n"); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myTree.collapsePath(myTree.getPathForRow(5)); - } - }); + doAndWaitForBuilder(() -> myTree.collapsePath(myTree.getPathForRow(5))); assertTree("-/\n" + " +com\n" @@ -670,12 +624,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { + " +[jetbrains]\n" + " +xUnit\n"); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myTree.expandPath(myTree.getPathForRow(5)); - } - }); + doAndWaitForBuilder(() -> myTree.expandPath(myTree.getPathForRow(5))); assertTree("-/\n" + " +com\n" @@ -895,12 +844,9 @@ public class TreeUiTest extends AbstractTreeBuilderTest { myAutoExpand.add(myRoot.getElement()); - invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().getUi().activate(true); - getBuilder().select(new NodeElement("com")); - } + invokeAndWaitIfNeeded(() -> { + getBuilder().getUi().activate(true); + getBuilder().select(new NodeElement("com")); }); waitBuilderToCome(); @@ -958,36 +904,28 @@ public class TreeUiTest extends AbstractTreeBuilderTest { public void testNoInfiniteAutoExpand() throws Exception { mySmartExpand = false; - assertNoInfiniteAutoExpand(new Runnable() { - @Override - public void run() { - myAutoExpand.add(new NodeElement("level2")); - myAutoExpand.add(new NodeElement("level3")); - myAutoExpand.add(new NodeElement("level4")); - myAutoExpand.add(new NodeElement("level5")); - myAutoExpand.add(new NodeElement("level6")); - myAutoExpand.add(new NodeElement("level7")); - myAutoExpand.add(new NodeElement("level8")); - myAutoExpand.add(new NodeElement("level9")); - myAutoExpand.add(new NodeElement("level10")); - myAutoExpand.add(new NodeElement("level11")); - myAutoExpand.add(new NodeElement("level12")); - myAutoExpand.add(new NodeElement("level13")); - myAutoExpand.add(new NodeElement("level14")); - myAutoExpand.add(new NodeElement("level15")); - } + assertNoInfiniteAutoExpand(() -> { + myAutoExpand.add(new NodeElement("level2")); + myAutoExpand.add(new NodeElement("level3")); + myAutoExpand.add(new NodeElement("level4")); + myAutoExpand.add(new NodeElement("level5")); + myAutoExpand.add(new NodeElement("level6")); + myAutoExpand.add(new NodeElement("level7")); + myAutoExpand.add(new NodeElement("level8")); + myAutoExpand.add(new NodeElement("level9")); + myAutoExpand.add(new NodeElement("level10")); + myAutoExpand.add(new NodeElement("level11")); + myAutoExpand.add(new NodeElement("level12")); + myAutoExpand.add(new NodeElement("level13")); + myAutoExpand.add(new NodeElement("level14")); + myAutoExpand.add(new NodeElement("level15")); }); } public void testNoInfiniteSmartExpand() throws Exception { mySmartExpand = false; - assertNoInfiniteAutoExpand(new Runnable() { - @Override - public void run() { - mySmartExpand = true; - } - }); + assertNoInfiniteAutoExpand(() -> mySmartExpand = true); } private void assertNoInfiniteAutoExpand(final Runnable enableExpand) throws Exception { @@ -1050,18 +988,10 @@ public class TreeUiTest extends AbstractTreeBuilderTest { private void assertCallbackOnce(final TreeAction action) { final int[] notifyCount = new int[1]; final boolean[] done = new boolean[1]; - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - action.run(new Runnable() { - @Override - public void run() { - notifyCount[0]++; - done[0] = true; - } - }); - } - }); + invokeLaterIfNeeded(() -> action.run(() -> { + notifyCount[0]++; + done[0] = true; + })); new WaitFor(2000) { @Override @@ -1193,18 +1123,10 @@ public class TreeUiTest extends AbstractTreeBuilderTest { collapsePath(getPath("/")); final Ref done = new Ref(); - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().expand(new NodeElement("com"), new Runnable() { - @Override - public void run() { - notNull(getBuilder().getTree()).collapsePath(getPath("com")); - done.set(Boolean.TRUE); - } - }); - } - }); + invokeLaterIfNeeded(() -> getBuilder().expand(new NodeElement("com"), () -> { + notNull(getBuilder().getTree()).collapsePath(getPath("com")); + done.set(Boolean.TRUE); + })); waitBuilderToCome(new Condition() { @Override @@ -1265,12 +1187,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { getBuilder().addSubtreeToUpdateByElement(new NodeElement("intellij")); getBuilder().addSubtreeToUpdateByElement(new NodeElement("xUnit")); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - notNull(getBuilder().getUpdater()).performUpdate(); - } - }); + doAndWaitForBuilder(() -> notNull(getBuilder().getUpdater()).performUpdate()); assertTree( "-/\n" + @@ -1338,22 +1255,14 @@ public class TreeUiTest extends AbstractTreeBuilderTest { final Ref queued = new Ref(false); final Ref intellijSelected = new Ref(false); final Ref jetbrainsSelected = new Ref(false); - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - try { - getBuilder().select(new NodeElement("intellij"), new Runnable() { - @Override - public void run() { - intellijSelected.set(true); - } - }, true); - queued.set(true); - } - catch (Exception e) { - e.printStackTrace(); - fail(); - } + invokeLaterIfNeeded(() -> { + try { + getBuilder().select(new NodeElement("intellij"), () -> intellijSelected.set(true), true); + queued.set(true); + } + catch (Exception e) { + e.printStackTrace(); + fail(); } }); @@ -1368,17 +1277,9 @@ public class TreeUiTest extends AbstractTreeBuilderTest { assertTreeNow("+null\n"); assertNull(((DefaultMutableTreeNode)notNull(getBuilder().getTreeModel()).getRoot()).getUserObject()); - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().getUi().activate(true); - getBuilder().select(new NodeElement("jetbrains"), new Runnable() { - @Override - public void run() { - jetbrainsSelected.set(true); - } - }, true); - } + invokeLaterIfNeeded(() -> { + getBuilder().getUi().activate(true); + getBuilder().select(new NodeElement("jetbrains"), () -> jetbrainsSelected.set(true), true); }); waitBuilderToCome(new Condition() { @@ -1407,12 +1308,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { return; } - getBuilder().expand(elements[index], new Runnable() { - @Override - public void run() { - expandNext(elements, index + 1, indicator, callback); - } - }); + getBuilder().expand(elements[index], () -> expandNext(elements, index + 1, indicator, callback)); } public void testSelectAfterCancelledUpdate() throws Exception { @@ -1488,12 +1384,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { buildSiblings(msg, 0, 1, null, null); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().getUi().activate(true); - } - }); + doAndWaitForBuilder(() -> getBuilder().getUi().activate(true)); buildNode("Messages", false); @@ -1506,12 +1397,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { " message 1 for 1\n" + " message 2 for 1\n"); - buildSiblings(msg, 2, 1000, new Runnable() { - @Override - public void run() { - getBuilder().queueUpdate(); - } - }, null); + buildSiblings(msg, 2, 1000, () -> getBuilder().queueUpdate(), null); waitBuilderToCome(); } @@ -1670,12 +1556,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { myCom.addChild("ibm").addChild("alphaWorks"); myCom.addChild("apple").addChild("cocoa"); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - getBuilder().getUi().activate(true); - } - }); + doAndWaitForBuilder(() -> getBuilder().getUi().activate(true)); buildNode("/", false); assertTree("-/\n" + @@ -1695,12 +1576,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { } }; - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myTree.expandPath(getPath("com")); - } - }); + doAndWaitForBuilder(() -> myTree.expandPath(getPath("com"))); assertTree("-/\n" + " -com\n" + @@ -1998,24 +1874,16 @@ public class TreeUiTest extends AbstractTreeBuilderTest { } public void testElementMove1() throws Exception { - assertMove(new Runnable() { - @SuppressWarnings("deprecation") - @Override - public void run() { - notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("com")); - notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("jetbrains")); - } + assertMove(() -> { + notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("com")); + notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("jetbrains")); }); } public void testElementMove2() throws Exception { - assertMove(new Runnable() { - @SuppressWarnings("deprecation") - @Override - public void run() { - notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("jetbrains")); - notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("com")); - } + assertMove(() -> { + notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("jetbrains")); + notNull(getBuilder().getUpdater()).addSubtreeToUpdateByElement(new NodeElement("com")); }); } @@ -2079,13 +1947,10 @@ public class TreeUiTest extends AbstractTreeBuilderTest { final NodeElement ide = new NodeElement("ide"); fabrique.setForcedParent(myRoot.getElement()); - doAndWaitForBuilder(new Runnable() { - @Override - public void run() { - myRoot.addChild(com).addChild(actionSystem); - myRoot.addChild(fabrique).addChild(ide); - getBuilder().getUi().activate(true); - } + doAndWaitForBuilder(() -> { + myRoot.addChild(com).addChild(actionSystem); + myRoot.addChild(fabrique).addChild(ide); + getBuilder().getUi().activate(true); }); select(actionSystem, false); @@ -2329,12 +2194,7 @@ public class TreeUiTest extends AbstractTreeBuilderTest { myElementUpdate.clear(); - invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().queueUpdateFrom(new NodeElement("openapi"), false); - } - }); + invokeAndWaitIfNeeded(() -> getBuilder().queueUpdateFrom(new NodeElement("openapi"), false)); waitBuilderToCome(); assertUpdates("openapi: update"); @@ -2412,15 +2272,12 @@ public class TreeUiTest extends AbstractTreeBuilderTest { } public void testReleaseBuilderDuringUpdate() throws Exception { - assertReleaseDuringBuilding("update", "fabrique", new Runnable() { - @Override - public void run() { - try { - select(new NodeElement("ide"), false); - } - catch (Exception e) { - myCancelRequest = e; - } + assertReleaseDuringBuilding("update", "fabrique", () -> { + try { + select(new NodeElement("ide"), false); + } + catch (Exception e) { + myCancelRequest = e; } }); } @@ -2429,22 +2286,8 @@ public class TreeUiTest extends AbstractTreeBuilderTest { buildStructure(myRoot); final boolean[] done = new boolean[] {false}; - invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - getBuilder().select(new NodeElement("jetbrains"), new Runnable() { - @Override - public void run() { - getBuilder().expand(new NodeElement("fabrique"), new Runnable() { - @Override - public void run() { - done[0] = true; - } - }); - } - }); - } - }); + invokeLaterIfNeeded( + () -> getBuilder().select(new NodeElement("jetbrains"), () -> getBuilder().expand(new NodeElement("fabrique"), () -> done[0] = true))); waitBuilderToCome(new Condition() { @Override @@ -2505,15 +2348,12 @@ public class TreeUiTest extends AbstractTreeBuilderTest { } public void testReleaseBuilderDuringGetChildren() throws Exception { - assertReleaseDuringBuilding("getChildren", "fabrique", new Runnable() { - @Override - public void run() { - try { - select(new NodeElement("ide"), false); - } - catch (Exception e) { - myCancelRequest = e; - } + assertReleaseDuringBuilding("getChildren", "fabrique", () -> { + try { + select(new NodeElement("ide"), false); + } + catch (Exception e) { + myCancelRequest = e; } }); } @@ -2549,12 +2389,9 @@ public class TreeUiTest extends AbstractTreeBuilderTest { public void onElementAction(String action, Object element) { if (!element.toString().equals(actionElement.toString())) return; - Runnable runnable = new Runnable() { - @Override - public void run() { - myReadyRequest = true; - Disposer.dispose(getBuilder()); - } + Runnable runnable = () -> { + myReadyRequest = true; + Disposer.dispose(getBuilder()); }; if (actionAction.equals(action)) { diff --git a/platform/platform-tests/testSrc/com/intellij/lang/PsiBuilderQuickTest.java b/platform/platform-tests/testSrc/com/intellij/lang/PsiBuilderQuickTest.java index da9273fcbc65..777fd1e37426 100644 --- a/platform/platform-tests/testSrc/com/intellij/lang/PsiBuilderQuickTest.java +++ b/platform/platform-tests/testSrc/com/intellij/lang/PsiBuilderQuickTest.java @@ -565,19 +565,16 @@ public class PsiBuilderQuickTest extends LightPlatformTestCase { } private static void doFailTest(@NonNls final String text, final Parser parser, @NonNls final String expected) { - PlatformTestUtil.withStdErrSuppressed(new Runnable() { - @Override - public void run() { - try { - PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(new PlainTextParserDefinition(), new MyTestLexer(), text); - builder.setDebugMode(true); - parser.parse(builder); - builder.getLightTree(); - fail("should fail"); - } - catch (AssertionError e) { - assertEquals(expected, e.getMessage()); - } + PlatformTestUtil.withStdErrSuppressed(() -> { + try { + PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(new PlainTextParserDefinition(), new MyTestLexer(), text); + builder.setDebugMode(true); + parser.parse(builder); + builder.getLightTree(); + fail("should fail"); + } + catch (AssertionError e) { + assertEquals(expected, e.getMessage()); } }); } diff --git a/platform/platform-tests/testSrc/com/intellij/module/ModulePointerTest.java b/platform/platform-tests/testSrc/com/intellij/module/ModulePointerTest.java index ca128cbaea0c..dc143d77f4cb 100644 --- a/platform/platform-tests/testSrc/com/intellij/module/ModulePointerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/module/ModulePointerTest.java @@ -79,11 +79,8 @@ public class ModulePointerTest extends PlatformTestCase { assertSame(module, pointer.getModule()); assertEquals("xxx", pointer.getModuleName()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifiableModel.dispose(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + modifiableModel.dispose(); }); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/DocumentTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/DocumentTest.java index 4d6e91bbb667..766e014dbd1d 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/DocumentTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/DocumentTest.java @@ -82,47 +82,20 @@ public class DocumentTest extends LightPlatformTestCase { final Document doc = new DocumentImpl("xxx"); - mustThrow(new Runnable(){ - @Override - public void run() { - doc.insertString(1,"x"); - } + mustThrow(() -> doc.insertString(1, "x")); + mustThrow(() -> doc.deleteString(1, 2)); + mustThrow(() -> doc.replaceString(1, 2, "s")); + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + doc.insertString(1,"s"); }); - mustThrow(new Runnable(){ - @Override - public void run() { - doc.deleteString(1, 2); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + doc.deleteString(1,2); }); - mustThrow(new Runnable(){ - @Override - public void run() { - doc.replaceString(1, 2, "s"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + doc.replaceString(1,2,"xxx"); }); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - doc.insertString(1,"s"); - } - }); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - doc.deleteString(1,2); - } - }); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - doc.replaceString(1,2,"xxx"); - } - }); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - doc.setText("sss"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + doc.setText("sss"); }); DocumentImpl console = new DocumentImpl("xxxx", true); @@ -136,16 +109,13 @@ public class DocumentTest extends LightPlatformTestCase { } public void testEmptyDocumentLineCount() { - WriteCommandAction.runWriteCommandAction(ourProject, new Runnable() { - @Override - public void run() { - DocumentImpl document = new DocumentImpl(""); - assertEquals(0, document.getLineCount()); - document.insertString(0, "a"); - assertEquals(1, document.getLineCount()); - document.deleteString(0, 1); - assertEquals(0, document.getLineCount()); - } + WriteCommandAction.runWriteCommandAction(ourProject, () -> { + DocumentImpl document = new DocumentImpl(""); + assertEquals(0, document.getLineCount()); + document.insertString(0, "a"); + assertEquals(1, document.getLineCount()); + document.deleteString(0, 1); + assertEquals(0, document.getLineCount()); }); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java index c5b086c193fb..d4231f3f2564 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java @@ -21,11 +21,8 @@ import com.intellij.testFramework.LightPlatformCodeInsightTestCase; public class EditorModificationUtilTest extends LightPlatformCodeInsightTestCase { public void testInsertStringAtCaretNotMovingCaret() throws Exception { configureFromFileText(getTestName(false) + ".txt", "text "); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - EditorModificationUtil.insertStringAtCaret(myEditor, " ", false, false); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + EditorModificationUtil.insertStringAtCaret(myEditor, " ", false, false); }); checkResultByText("text "); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretTest.java index 9ac97b044422..f3207ac14596 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretTest.java @@ -72,25 +72,19 @@ public class EditorMultiCaretTest extends AbstractEditorTest { } public void testCustomShortcut() throws Throwable { - doWithAltClickShortcut(new ThrowableRunnable() { - @Override - public void run() throws IOException { - initText("text"); - mouse().alt().clickAt(0, 2); - checkResultByText("text"); - } + doWithAltClickShortcut(() -> { + initText("text"); + mouse().alt().clickAt(0, 2); + checkResultByText("text"); }); } public void testCaretRemovalWithCustomShortcutDoesntAffectOtherSelections() throws Throwable { - doWithAltClickShortcut(new ThrowableRunnable() { - @Override - public void run() throws IOException { - initText("some text"); - mouse().alt().clickAt(0, 6); - mouse().alt().clickAt(0, 6); - checkResultByText("some text"); - } + doWithAltClickShortcut(() -> { + initText("some text"); + mouse().alt().clickAt(0, 6); + mouse().alt().clickAt(0, 6); + checkResultByText("some text"); }); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretUndoRedoTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretUndoRedoTest.java index f79d88eea574..c8a0b28a07cd 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretUndoRedoTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorMultiCaretUndoRedoTest.java @@ -107,12 +107,7 @@ public class EditorMultiCaretUndoRedoTest extends AbstractEditorTest { } private void checkResult(final String text) { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - checkResultByText(text); - } - }); + CommandProcessor.getInstance().runUndoTransparentAction(() -> checkResultByText(text)); } private static void undo() { diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingStressTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingStressTest.java index 4048b5ca9765..5c5e8df33c37 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingStressTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingStressTest.java @@ -31,12 +31,9 @@ public class FoldingStressTest extends LightPlatformTestCase { Editor editor = EditorFactory.getInstance().createEditor(doc); try { final FoldingModel model = editor.getFoldingModel(); - model.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - addAndCollapseFoldRegion(model, 0, 8, "/*...*/"); - addAndCollapseFoldRegion(model, 10, 12, "/*...*/"); - } + model.runBatchFoldingOperation(() -> { + addAndCollapseFoldRegion(model, 0, 8, "/*...*/"); + addAndCollapseFoldRegion(model, 10, 12, "/*...*/"); }); assertEquals(10, editor.logicalPositionToOffset(new LogicalPosition(0, 10))); @@ -58,12 +55,9 @@ public class FoldingStressTest extends LightPlatformTestCase { Editor editor = EditorFactory.getInstance().createEditor(doc); try { final FoldingModel model = editor.getFoldingModel(); - model.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - addAndCollapseFoldRegion(model, 0, len, "/*...*/"); - addAndCollapseFoldRegion(model, len + 2, len + 4, "/*...*/"); - } + model.runBatchFoldingOperation(() -> { + addAndCollapseFoldRegion(model, 0, len, "/*...*/"); + addAndCollapseFoldRegion(model, len + 2, len + 4, "/*...*/"); }); for (int line = 0; line <= 3; line++) { diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java index 15217f2cd386..5e9488e60b61 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java @@ -41,56 +41,44 @@ public class FoldingTest extends AbstractEditorTest { } public void testCleanupInvalidRegions() { - myModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - myModel.addFoldRegion(0, 4, "/*...*/"); - myModel.addFoldRegion(5, 9, "/*...*/"); - } + myModel.runBatchFoldingOperation(() -> { + myModel.addFoldRegion(0, 4, "/*...*/"); + myModel.addFoldRegion(5, 9, "/*...*/"); }); assertSize(2, myModel.getAllFoldRegions()); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().deleteString(0, 5); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().deleteString(0, 5); }); assertSize(1, myModel.getAllFoldRegions()); } public void testIntersects () throws Exception { - myModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion region = myModel.addFoldRegion(5, 10, "."); - assertNotNull(region); - region = myModel.addFoldRegion(7, 11, "."); - assertNull(region); - region = myModel.addFoldRegion(20, 30, "."); - assertNotNull(region); - region = myModel.addFoldRegion(9, 12, "."); - assertNull(region); - region = myModel.addFoldRegion(7, 10, "."); - assertNotNull(region); - region = myModel.addFoldRegion(7, 10, "."); - assertNull(region); - region = myModel.addFoldRegion(5, 30, "."); - assertNotNull(region); - } + myModel.runBatchFoldingOperation(() -> { + FoldRegion region = myModel.addFoldRegion(5, 10, "."); + assertNotNull(region); + region = myModel.addFoldRegion(7, 11, "."); + assertNull(region); + region = myModel.addFoldRegion(20, 30, "."); + assertNotNull(region); + region = myModel.addFoldRegion(9, 12, "."); + assertNull(region); + region = myModel.addFoldRegion(7, 10, "."); + assertNotNull(region); + region = myModel.addFoldRegion(7, 10, "."); + assertNull(region); + region = myModel.addFoldRegion(5, 30, "."); + assertNotNull(region); }); } public void testIntersectsWithRegionFarInStorageOrder() { - myModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion region = myModel.addFoldRegion(0, 10, "."); - assertNotNull(region); - region = myModel.addFoldRegion(1, 5, "."); - assertNotNull(region); - region = myModel.addFoldRegion(6, 11, "."); - assertNull(region); - } + myModel.runBatchFoldingOperation(() -> { + FoldRegion region = myModel.addFoldRegion(0, 10, "."); + assertNotNull(region); + region = myModel.addFoldRegion(1, 5, "."); + assertNotNull(region); + region = myModel.addFoldRegion(6, 11, "."); + assertNull(region); }); } @@ -184,11 +172,8 @@ public class FoldingTest extends AbstractEditorTest { addCollapsedFoldRegion(0, 10, "..."); addCollapsedFoldRegion(1, 9, "..."); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().deleteString(0, 1); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().deleteString(0, 1); }); addFoldRegion(20, 21, "..."); // an arbitrary action to rebuild folding caches @@ -201,11 +186,8 @@ public class FoldingTest extends AbstractEditorTest { addFoldRegion(0, 4, "..."); assertNumberOfValidFoldRegions(2); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().deleteString(4, 5); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().deleteString(4, 5); }); @@ -215,11 +197,8 @@ public class FoldingTest extends AbstractEditorTest { public void testTopLevelRegionRemainsTopLevelAfterMergingIdenticalRegions() { addCollapsedFoldRegion(10, 15, "..."); addCollapsedFoldRegion(10, 14, "..."); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().deleteString(14, 15); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().deleteString(14, 15); }); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/SelectUnselectOccurrenceActionsTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/SelectUnselectOccurrenceActionsTest.java index c1cc85768aed..2bab6a25686e 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/SelectUnselectOccurrenceActionsTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/SelectUnselectOccurrenceActionsTest.java @@ -161,13 +161,10 @@ public class SelectUnselectOccurrenceActionsTest extends LightPlatformCodeInsigh "collapsed line"); final FoldingModel foldingModel = myFixture.getEditor().getFoldingModel(); final Document document = myFixture.getEditor().getDocument(); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion foldRegion = foldingModel.addFoldRegion(document.getLineStartOffset(1), document.getLineEndOffset(1), "..."); - assertNotNull(foldRegion); - foldRegion.setExpanded(false); - } + foldingModel.runBatchFoldingOperation(() -> { + FoldRegion foldRegion = foldingModel.addFoldRegion(document.getLineStartOffset(1), document.getLineEndOffset(1), "..."); + assertNotNull(foldRegion); + foldRegion.setExpanded(false); }); executeAction(); checkResult("normal line\n" + diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/FoldingAnchorsOverlayStrategyTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/FoldingAnchorsOverlayStrategyTest.java index 94803191efd6..1bb0865f5fe1 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/FoldingAnchorsOverlayStrategyTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/FoldingAnchorsOverlayStrategyTest.java @@ -75,12 +75,7 @@ public class FoldingAnchorsOverlayStrategyTest extends LightPlatformCodeInsightF public void testWithEmptyLastLine() { myFixture.configureByText(FileTypes.PLAIN_TEXT, "some text\n"); final FoldingModel foldingModel = myFixture.getEditor().getFoldingModel(); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - foldingModel.addFoldRegion(0, 10, "..."); - } - }); + foldingModel.runBatchFoldingOperation(() -> foldingModel.addFoldRegion(0, 10, "...")); verifyAnchors(null, 0, Type.EXPANDED_TOP, 1, Type.EXPANDED_BOTTOM); @@ -94,24 +89,14 @@ public class FoldingAnchorsOverlayStrategyTest extends LightPlatformCodeInsightF private void collapseFoldingRegion(int n) { FoldingModel foldingModel = myFixture.getEditor().getFoldingModel(); final FoldRegion foldRegion = foldingModel.getAllFoldRegions()[n]; - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - foldRegion.setExpanded(false); - } - }); + foldingModel.runBatchFoldingOperation(() -> foldRegion.setExpanded(false)); } private void verifyAnchors(FoldRegion activeFoldRegion, Object... expectedAnchorParameters) { Collection actualAnchors = new FoldingAnchorsOverlayStrategy((EditorImpl)myFixture.getEditor()) .getAnchorsToDisplay(0, myFixture.getEditor().getDocument().getTextLength(), activeFoldRegion); List sortedActualAnchors = new ArrayList(actualAnchors); - Collections.sort(sortedActualAnchors, new Comparator() { - @Override - public int compare(DisplayedFoldingAnchor o1, DisplayedFoldingAnchor o2) { - return o1.visualLine - o2.visualLine; - } - }); + Collections.sort(sortedActualAnchors, (o1, o2) -> o1.visualLine - o2.visualLine); assertEquals("Wrong number of anchors", expectedAnchorParameters.length / 2, sortedActualAnchors.size()); int i = 0; diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java index 1ae73beecbb0..6e46c2cba85b 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/RangeMarkerTest.java @@ -1042,12 +1042,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { try { final FoldRegion[] fold = new FoldRegion[1]; - editor.getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - fold[0] = editor.getFoldingModel().addFoldRegion(0, 2, ""); - } - }); + editor.getFoldingModel().runBatchFoldingOperation(() -> fold[0] = editor.getFoldingModel().addFoldRegion(0, 2, "")); RangeMarker marker = document.createRangeMarker(0, 2); document.deleteString(1,2); @@ -1138,16 +1133,13 @@ public class RangeMarkerTest extends LightPlatformTestCase { } markupModel.addRangeHighlighter(N / 2, N / 2 + 1, 0, null, HighlighterTargetArea.LINES_IN_RANGE); - PlatformTestUtil.startPerformanceTest("slow highlighters lookup", (int)(N*Math.log(N)/1000), new ThrowableRunnable() { - @Override - public void run() { - List list = new ArrayList(); - CommonProcessors.CollectProcessor coll = new CommonProcessors.CollectProcessor(list); - for (int i=0; i { + List list = new ArrayList(); + CommonProcessors.CollectProcessor coll = new CommonProcessors.CollectProcessor(list); + for (int i=0; i { + TrailingSpacesStripper.stripIfNotCurrentLine(getEditor().getDocument(), true); }); } @@ -177,12 +174,9 @@ public class TrailingSpacesStripperTest extends LightPlatformCodeInsightTestCase Document document = configureFromFileText("x.txt", "xxx \nyyy\n\t\t\t"); // make any modification, so that Document and file content differ. Otherwise save won't be, and "on-save" actions won't be called. WriteCommandAction.runWriteCommandAction(getProject(), - new Runnable() { - @Override - public void run() { - document.insertString(0, " "); - } - }); + () -> { + document.insertString(0, " "); + }); FileDocumentManager.getInstance().saveAllDocuments(); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapperTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapperTest.java index cb3d798a5d5c..62e9eed93b5e 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapperTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/CachingSoftWrapDataMapperTest.java @@ -47,42 +47,36 @@ import java.util.List; */ public class CachingSoftWrapDataMapperTest { - private static final Comparator LOGICAL_POSITIONS_COMPARATOR = new Comparator() { - @Override - public int compare(DataEntry o1, DataEntry o2) { - LogicalPosition logical1 = o1.logical; - LogicalPosition logical2 = o2.logical; - if (logical1.line != logical2.line) { - return logical1.line - logical2.line; - } - - // There is a possible case that multiple logical positions match to the same visual position (e.g. logical - // positions for folded text match to the same visual position). We want to match to the logical position of - // folding region start if we search by logical position from folded text. - if (o1.foldedSpace && o2.foldedSpace && logical1.column + logical1.foldingColumnDiff == logical2.foldingColumnDiff) { - return o1.foldedSpace ? 1 : -1; - } - return logical1.column - logical2.column; + private static final Comparator LOGICAL_POSITIONS_COMPARATOR = (o1, o2) -> { + LogicalPosition logical1 = o1.logical; + LogicalPosition logical2 = o2.logical; + if (logical1.line != logical2.line) { + return logical1.line - logical2.line; } + + // There is a possible case that multiple logical positions match to the same visual position (e.g. logical + // positions for folded text match to the same visual position). We want to match to the logical position of + // folding region start if we search by logical position from folded text. + if (o1.foldedSpace && o2.foldedSpace && logical1.column + logical1.foldingColumnDiff == logical2.foldingColumnDiff) { + return o1.foldedSpace ? 1 : -1; + } + return logical1.column - logical2.column; }; - private static final Comparator OFFSETS_COMPARATOR = new Comparator() { - @Override - public int compare(DataEntry o1, DataEntry o2) { - if (o1.offset != o2.offset) { - return o1.offset - o2.offset; - } - // There are numerous situations when multiple visual positions share the same offset (e.g. all soft wrap-introduced virtual - // spaces share offset with the first document symbol after soft wrap or all virtual spaces after line end share the same offset - // as the last line symbol). We want to ignore such positions during lookup by offset. - if (o1.virtualSpace ^ o2.virtualSpace) { - return o1.virtualSpace ? 1 : -1; - } - if (o1.insideTab ^ o2.insideTab) { - return o1.insideTab ? 1 : -1; - } - return 0; + private static final Comparator OFFSETS_COMPARATOR = (o1, o2) -> { + if (o1.offset != o2.offset) { + return o1.offset - o2.offset; } + // There are numerous situations when multiple visual positions share the same offset (e.g. all soft wrap-introduced virtual + // spaces share offset with the first document symbol after soft wrap or all virtual spaces after line end share the same offset + // as the last line symbol). We want to ignore such positions during lookup by offset. + if (o1.virtualSpace ^ o2.virtualSpace) { + return o1.virtualSpace ? 1 : -1; + } + if (o1.insideTab ^ o2.insideTab) { + return o1.insideTab ? 1 : -1; + } + return 0; }; private static final String SOFT_WRAP_START_MARKER = ""; diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java index 3063d45e2b97..0cb8d8022c60 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java @@ -727,11 +727,8 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT addCollapsedFoldRegion(foldStartOffset, foldEndOffset, "..."); // Simulate addition of the new import that modifies existing fold region. - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().insertString(foldEndOffset, "\nimport java.util.Date;\n"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().insertString(foldEndOffset, "\nimport java.util.Date;\n"); }); final FoldingModel foldingModel = myEditor.getFoldingModel(); @@ -764,11 +761,8 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT addCollapsedFoldRegion(foldStartOffset, foldEndOffset, "..."); int modificationOffset = text.indexOf("java.util.Set"); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().insertString(modificationOffset, "import java.util.HashSet;\n"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().insertString(modificationOffset, "import java.util.HashSet;\n"); }); // Used to get StackOverflowError here, hence, no additional checking is performed. @@ -846,11 +840,8 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT final EditorSettings settings = getEditor().getSettings(); settings.setUseSoftWraps(false); int startOffset = text.indexOf("\t third") - 1; - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - getEditor().getDocument().deleteString(startOffset, text.length()); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + getEditor().getDocument().deleteString(startOffset, text.length()); }); @@ -1063,11 +1054,8 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT addCollapsedFoldRegion(4, 8, "..."); addCollapsedFoldRegion(13, 15, "..."); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - myEditor.getDocument().insertString(10, "C"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + myEditor.getDocument().insertString(10, "C"); }); @@ -1145,11 +1133,8 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT configureSoftWraps(100); addCollapsedFoldRegion(0, 4, "..."); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - ((DocumentEx)myEditor.getDocument()).moveText(0, 4, 12); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + ((DocumentEx)myEditor.getDocument()).moveText(0, 4, 12); }); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java index e06804609ad9..0598cb58443c 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java @@ -93,11 +93,8 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { Document document = editor.getDocument(); int offset = random.nextInt(document.getTextLength() + 1); CharSequence text = generateText(random); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - document.insertString(offset, text); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + document.insertString(offset, text); }); } } @@ -110,11 +107,8 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { if (textLength <= 0) return; int from = random.nextInt(textLength + 1); int to = random.nextInt(textLength + 1); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - document.deleteString(Math.min(from, to), Math.max(from, to)); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + document.deleteString(Math.min(from, to), Math.max(from, to)); }); } } @@ -128,11 +122,8 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { int from = random.nextInt(textLength + 1); int to = random.nextInt(textLength + 1); CharSequence text = generateText(random); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - document.replaceString(Math.min(from, to), Math.max(from, to), text); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + document.replaceString(Math.min(from, to), Math.max(from, to), text); }); } } @@ -146,15 +137,12 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { int[] offsets = new int[] {random.nextInt(textLength + 1), random.nextInt(textLength + 1), random.nextInt(textLength + 1)}; Arrays.sort(offsets); if (offsets[0] == offsets[1] || offsets[1] == offsets[2]) return; - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - if (random.nextBoolean()) { - ((DocumentEx)document).moveText(offsets[0], offsets[1], offsets[2]); - } - else { - ((DocumentEx)document).moveText(offsets[1], offsets[2], offsets[0]); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + if (random.nextBoolean()) { + ((DocumentEx)document).moveText(offsets[0], offsets[1], offsets[2]); + } + else { + ((DocumentEx)document).moveText(offsets[1], offsets[2], offsets[0]); } }); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java index 5a8f646e0f87..cb0a0b795e49 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java @@ -380,11 +380,8 @@ public class SyntaxInfoConstructionTest extends LightPlatformCodeInsightFixtureT myFixture.configureByText(getTestName(true) + ".java", ""); final DocumentImpl document = (DocumentImpl)myFixture.getEditor().getDocument(); document.setAcceptSlashR(true); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.setText(text); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.setText(text); }); myFixture.doHighlighting(); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileChooser/ex/FileChooserCompletionTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileChooser/ex/FileChooserCompletionTest.java index fe4e22df26e9..9b86c9627f5d 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileChooser/ex/FileChooserCompletionTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileChooser/ex/FileChooserCompletionTest.java @@ -140,12 +140,7 @@ public class FileChooserCompletionTest extends FlyIdeaTestCase { final List expectedList = Arrays.asList(expected); - Collections.sort(result.myToComplete, new Comparator() { - @Override - public int compare(final FileLookup.LookupFile o1, final FileLookup.LookupFile o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(result.myToComplete, (o1, o2) -> o1.getName().compareTo(o2.getName())); Collections.sort(expectedList); assertEquals(asString(expectedList, result), asString(result.myToComplete, result)); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java index f8e5e92b08b3..5c6ecae86442 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/FileEditorManagerTest.java @@ -128,12 +128,9 @@ public class FileEditorManagerTest extends FileEditorManagerTestCase { Editor editor = ((TextEditor)editors[0]).getEditor(); final FoldingModel foldingModel = editor.getFoldingModel(); assertEquals(2, foldingModel.getAllFoldRegions().length); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldRegion region : foldingModel.getAllFoldRegions()) { - region.setExpanded(false); - } + foldingModel.runBatchFoldingOperation(() -> { + for (FoldRegion region : foldingModel.getAllFoldRegions()) { + region.setExpanded(false); } }); int textLength = editor.getDocument().getTextLength(); @@ -212,11 +209,8 @@ public class FileEditorManagerTest extends FileEditorManagerTestCase { private void assertOpenFiles(String... fileNames) { EditorWithProviderComposite[] files = myManager.getSplitters().getEditorsComposites(); - List names = ContainerUtil.map(files, new Function() { - @Override - public String fun(EditorWithProviderComposite composite) { - return composite.getFile().getName(); - } + List names = ContainerUtil.map(files, composite -> { + return composite.getFile().getName(); }); assertEquals(Arrays.asList(fileNames), names); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java index cf4a21e1e4e5..bab06fd044b3 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java @@ -341,13 +341,7 @@ public class NonProjectFileAccessTest extends HeavyFileEditorManagerTestCase { Editor editor = getEditor(file); NullableFunction, NonProjectFileWritingAccessProvider.UnlockOption> unlocker = - new NullableFunction, NonProjectFileWritingAccessProvider.UnlockOption>() { - @Nullable - @Override - public NonProjectFileWritingAccessProvider.UnlockOption fun(List files) { - return option; - } - }; + files -> option; NonProjectFileWritingAccessProvider.setCustomUnlocker(unlocker); String before = editor.getDocument().getText(); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeUsagesCollectorTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeUsagesCollectorTest.java index 2f11676d7df7..7ac62db1a66e 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeUsagesCollectorTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeUsagesCollectorTest.java @@ -37,19 +37,11 @@ public class FileTypeUsagesCollectorTest extends LightPlatformCodeInsightFixture assertEquals(1, usage.getValue()); } assertEquals( - ContainerUtil.map2Set(fileTypes, new NotNullFunction() { - @NotNull - @Override - public String fun(FileType fileType) { - return fileType.getName(); - } + ContainerUtil.map2Set(fileTypes, (NotNullFunction)fileType -> { + return fileType.getName(); }), - ContainerUtil.map2Set(usages, new NotNullFunction() { - @NotNull - @Override - public String fun(UsageDescriptor usageDescriptor) { - return usageDescriptor.getKey(); - } + ContainerUtil.map2Set(usages, (NotNullFunction)usageDescriptor -> { + return usageDescriptor.getKey(); }) ); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/util/io/FileUtilPerformanceTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/util/io/FileUtilPerformanceTest.java index 7a15b7c7f26c..22109b2a7cc8 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/util/io/FileUtilPerformanceTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/util/io/FileUtilPerformanceTest.java @@ -31,13 +31,10 @@ public class FileUtilPerformanceTest { public void toCanonicalPath() throws Exception { assertEquals(myCanonicalPath, FileUtil.toCanonicalPath(myTestPath)); - PlatformTestUtil.startPerformanceTest("", 1000, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - for (int i = 0; i < 1000000; ++i) { - final String canonicalPath = FileUtil.toCanonicalPath(myTestPath, '/'); - assert canonicalPath != null && canonicalPath.length() == 18 : canonicalPath; - } + PlatformTestUtil.startPerformanceTest("", 1000, () -> { + for (int i = 0; i < 1000000; ++i) { + final String canonicalPath = FileUtil.toCanonicalPath(myTestPath, '/'); + assert canonicalPath != null && canonicalPath.length() == 18 : canonicalPath; } }).cpuBound().useLegacyScaling().assertTiming(); } @@ -46,13 +43,10 @@ public class FileUtilPerformanceTest { public void toCanonicalPathSimple() throws Exception { assertEquals(mySimpleTestPath, FileUtil.toCanonicalPath(mySimpleTestPath)); - PlatformTestUtil.startPerformanceTest("", 50, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - for (int i = 0; i < 1000000; ++i) { - final String canonicalPath = FileUtil.toCanonicalPath(mySimpleTestPath, '/'); - assert canonicalPath != null && canonicalPath.length() == 8 : canonicalPath; - } + PlatformTestUtil.startPerformanceTest("", 50, () -> { + for (int i = 0; i < 1000000; ++i) { + final String canonicalPath = FileUtil.toCanonicalPath(mySimpleTestPath, '/'); + assert canonicalPath != null && canonicalPath.length() == 8 : canonicalPath; } }).cpuBound().useLegacyScaling().assertTiming(); } @@ -61,13 +55,10 @@ public class FileUtilPerformanceTest { public void isAncestor() throws Exception { assertTrue(FileUtil.isAncestor(myTestPath, myCanonicalPath, false)); - PlatformTestUtil.startPerformanceTest("", 4000, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - for (int i = 0; i < 1000000; ++i) { - assert FileUtil.isAncestor(myTestPath, myCanonicalPath, false); - assert !FileUtil.isAncestor(myTestPath, myCanonicalPath, true); - } + PlatformTestUtil.startPerformanceTest("", 4000, () -> { + for (int i = 0; i < 1000000; ++i) { + assert FileUtil.isAncestor(myTestPath, myCanonicalPath, false); + assert !FileUtil.isAncestor(myTestPath, myCanonicalPath, true); } }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/util/text/StringUtilPerformanceTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/util/text/StringUtilPerformanceTest.java index fe14fc7e42ed..189252fa06d6 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/util/text/StringUtilPerformanceTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/util/text/StringUtilPerformanceTest.java @@ -31,13 +31,10 @@ public class StringUtilPerformanceTest { public void containsAnyChar() throws Exception { assertTrue(StringUtil.containsAnyChar(TEST_STRING, Integer.toString(new Random().nextInt()))); - PlatformTestUtil.startPerformanceTest("StringUtil.containsAnyChar()", SystemInfo.isWindows ? 500 : 200, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - for (int i = 0; i < 1000000; i++) { - StringUtil.containsAnyChar(TEST_STRING, "XYZ"); - StringUtil.containsAnyChar("XYZ", TEST_STRING); - } + PlatformTestUtil.startPerformanceTest("StringUtil.containsAnyChar()", SystemInfo.isWindows ? 500 : 200, () -> { + for (int i = 0; i < 1000000; i++) { + StringUtil.containsAnyChar(TEST_STRING, "XYZ"); + StringUtil.containsAnyChar("XYZ", TEST_STRING); } }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/newvfs/impl/FileNameCacheMicroBenchmark.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/newvfs/impl/FileNameCacheMicroBenchmark.java index 4c8402401957..d84e5fbe325d 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/newvfs/impl/FileNameCacheMicroBenchmark.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/newvfs/impl/FileNameCacheMicroBenchmark.java @@ -38,24 +38,21 @@ import java.util.concurrent.Future; public class FileNameCacheMicroBenchmark { public static void main(String[] args) throws Exception { //noinspection SSBasedInspection - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - try { - IdeaTestFixture fixture = IdeaTestFixtureFactory.getFixtureFactory().createLightFixtureBuilder(LightProjectDescriptor.EMPTY_PROJECT_DESCRIPTOR).getFixture(); - fixture.setUp(); - long start = System.currentTimeMillis(); - runTest(200, "All names in cache"); - runTest(50000, "Cache almost overflows"); - runTest(120000, "Cache certain overflow"); - long elapsed = System.currentTimeMillis() - start; - System.out.println("Total elapsed: " + elapsed/1000.0 +"s"); + SwingUtilities.invokeAndWait(() -> { + try { + IdeaTestFixture fixture = IdeaTestFixtureFactory.getFixtureFactory().createLightFixtureBuilder(LightProjectDescriptor.EMPTY_PROJECT_DESCRIPTOR).getFixture(); + fixture.setUp(); + long start = System.currentTimeMillis(); + runTest(200, "All names in cache"); + runTest(50000, "Cache almost overflows"); + runTest(120000, "Cache certain overflow"); + long elapsed = System.currentTimeMillis() - start; + System.out.println("Total elapsed: " + elapsed/1000.0 +"s"); - fixture.tearDown(); - } - catch (Exception e) { - throw new RuntimeException(e); - } + fixture.tearDown(); + } + catch (Exception e) { + throw new RuntimeException(e); } }); @@ -200,12 +197,8 @@ public class FileNameCacheMicroBenchmark { for (int i = 0; i < threadCount; i++) { final Random threadRandom = new Random(seedRandom.nextInt()); final int finalI = i; - futures.add(ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - testIteration.doTest(finalI, ids, threadRandom, queryCount); - } - })); + futures.add(ApplicationManager.getApplication().executeOnPooledThread( + () -> testIteration.doTest(finalI, ids, threadRandom, queryCount))); } for (Future future : futures) { future.get(); diff --git a/platform/platform-tests/testSrc/com/intellij/platform/ProjectSetTest.java b/platform/platform-tests/testSrc/com/intellij/platform/ProjectSetTest.java index faf397c3f0a1..c748d5cebfd0 100644 --- a/platform/platform-tests/testSrc/com/intellij/platform/ProjectSetTest.java +++ b/platform/platform-tests/testSrc/com/intellij/platform/ProjectSetTest.java @@ -95,12 +95,7 @@ public class ProjectSetTest extends LightPlatformTestCase { context.directoryName = "newDir"; context.directory = getSourceRoot(); readDescriptor(new File(getTestDataPath() + "vcs.json"), context); - Collections.sort(pairs, new Comparator>() { - @Override - public int compare(@NotNull Pair o1, @NotNull Pair o2) { - return o2.first.compareTo(o1.first); - } - }); + Collections.sort(pairs, (o1, o2) -> o2.first.compareTo(o1.first)); assertEquals(Pair.create("schema://foo.bar/path", "test"), pairs.get(1)); assertEquals(Pair.create("schema://foo.bar1/path1", "test/custom"), pairs.get(0)); } diff --git a/platform/platform-tests/testSrc/com/intellij/psi/tree/IElementTypeTest.java b/platform/platform-tests/testSrc/com/intellij/psi/tree/IElementTypeTest.java index ca882888e895..333df7656066 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/tree/IElementTypeTest.java +++ b/platform/platform-tests/testSrc/com/intellij/psi/tree/IElementTypeTest.java @@ -88,12 +88,7 @@ public class IElementTypeTest extends LightPlatformCodeInsightFixtureTestCase { // Show per-plugin statistics Object[] keys = map.keys(); - Arrays.sort(keys, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return map.get((String)o2) - map.get((String)o1); - } - }); + Arrays.sort(keys, (o1, o2) -> map.get((String)o2) - map.get((String)o1)); int sum = 0; for (Object key : keys) { int value = map.get((String)key); @@ -152,21 +147,18 @@ public class IElementTypeTest extends LightPlatformCodeInsightFixtureTestCase { } public void testInitialRegisterPerformance() { - PlatformTestUtil.startPerformanceTest("IElementType add", 100, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - Language language = Language.ANY; - IElementType[] old = IElementType.push(new IElementType[0]); - try { - for (short i = 0; i < 15000; i++) { - IElementType type = new IElementType("i " + i, language); - assertEquals(i, type.getIndex()); - } - } - finally { - IElementType.push(old); + PlatformTestUtil.startPerformanceTest("IElementType add", 100, () -> { + Language language = Language.ANY; + IElementType[] old = IElementType.push(new IElementType[0]); + try { + for (short i = 0; i < 15000; i++) { + IElementType type = new IElementType("i " + i, language); + assertEquals(i, type.getIndex()); } } + finally { + IElementType.push(old); + } }).useLegacyScaling().assertTiming(); } } diff --git a/platform/platform-tests/testSrc/com/intellij/psi/tree/TokenSetTest.java b/platform/platform-tests/testSrc/com/intellij/psi/tree/TokenSetTest.java index 1995f21497a8..03eeabc5d55e 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/tree/TokenSetTest.java +++ b/platform/platform-tests/testSrc/com/intellij/psi/tree/TokenSetTest.java @@ -124,13 +124,10 @@ public class TokenSetTest { final TokenSet set = TokenSet.create(); final int shift = new Random().nextInt(500000); - PlatformTestUtil.startPerformanceTest("TokenSet.contains() performance", 25, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - for (int i = 0; i < 1000000; i++) { - final IElementType next = elementTypes[((i + shift) % elementTypes.length)]; - assertFalse(set.contains(next)); - } + PlatformTestUtil.startPerformanceTest("TokenSet.contains() performance", 25, () -> { + for (int i = 0; i < 1000000; i++) { + final IElementType next = elementTypes[((i + shift) % elementTypes.length)]; + assertFalse(set.contains(next)); } }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.java b/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.java index 29f597381431..46bd176d528c 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.java @@ -669,42 +669,33 @@ public class NameUtilMatchingTest extends UsefulTestCase { nonMatching.add(NameUtil.buildMatcher(s, NameUtil.MatchingCaseSensitivity.NONE)); } - PlatformTestUtil.startPerformanceTest("Matcher is slow", 4500, new ThrowableRunnable() { - @Override - public void run() { - for (int i = 0; i < 100000; i++) { - for (MinusculeMatcher matcher : matching) { - Assert.assertTrue(matcher.toString(), matcher.matches(longName)); - matcher.matchingDegree(longName); - } - for (MinusculeMatcher matcher : nonMatching) { - Assert.assertFalse(matcher.toString(), matcher.matches(longName)); - } + PlatformTestUtil.startPerformanceTest("Matcher is slow", 4500, () -> { + for (int i = 0; i < 100000; i++) { + for (MinusculeMatcher matcher : matching) { + Assert.assertTrue(matcher.toString(), matcher.matches(longName)); + matcher.matchingDegree(longName); + } + for (MinusculeMatcher matcher : nonMatching) { + Assert.assertFalse(matcher.toString(), matcher.matches(longName)); } } }).cpuBound().useLegacyScaling().assertTiming(); } public void testOnlyUnderscoresPerformance() { - PlatformTestUtil.startPerformanceTest("Matcher is exponential", 300, new ThrowableRunnable() { - @Override - public void run() { - String small = StringUtil.repeat("_", 50); - String big = StringUtil.repeat("_", small.length() + 1); - assertMatches("*" + small, big); - assertDoesntMatch("*" + big, small); - } + PlatformTestUtil.startPerformanceTest("Matcher is exponential", 300, () -> { + String small = StringUtil.repeat("_", 50); + String big = StringUtil.repeat("_", small.length() + 1); + assertMatches("*" + small, big); + assertDoesntMatch("*" + big, small); }).cpuBound().useLegacyScaling().assertTiming(); } public void testRepeatedLetterPerformance() { - PlatformTestUtil.startPerformanceTest("Matcher is exponential", 300, new ThrowableRunnable() { - @Override - public void run() { - String big = StringUtil.repeat("Aaaaaa", 50); - assertMatches("aaaaaaaaaaaaaaaaaaaaaaaa", big); - assertDoesntMatch("aaaaaaaaaaaaaaaaaaaaaaaab", big); - } + PlatformTestUtil.startPerformanceTest("Matcher is exponential", 300, () -> { + String big = StringUtil.repeat("Aaaaaa", 50); + assertMatches("aaaaaaaaaaaaaaaaaaaaaaaa", big); + assertDoesntMatch("aaaaaaaaaaaaaaaaaaaaaaaab", big); }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/platform/platform-tests/testSrc/com/intellij/structureView/SmartTreeStructureTest.java b/platform/platform-tests/testSrc/com/intellij/structureView/SmartTreeStructureTest.java index b7a244e2d8df..8d7d85dd0615 100644 --- a/platform/platform-tests/testSrc/com/intellij/structureView/SmartTreeStructureTest.java +++ b/platform/platform-tests/testSrc/com/intellij/structureView/SmartTreeStructureTest.java @@ -120,13 +120,10 @@ public class SmartTreeStructureTest extends LightPlatformCodeInsightFixtureTestC @NotNull @Override public Comparator getComparator() { - return new Comparator() { - @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof Group && !(o2 instanceof Group)) return -1; - if (!(o1 instanceof Group) && o2 instanceof Group) return 1; - return 0; - } + return (o1, o2) -> { + if (o1 instanceof Group && !(o2 instanceof Group)) return -1; + if (!(o1 instanceof Group) && o2 instanceof Group) return 1; + return 0; }; } @@ -152,12 +149,7 @@ public class SmartTreeStructureTest extends LightPlatformCodeInsightFixtureTestC @NotNull @Override public Comparator getComparator() { - return new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return o1.toString().compareTo(o2.toString()); - } - }; + return (o1, o2) -> o1.toString().compareTo(o2.toString()); } @Override diff --git a/platform/platform-tests/testSrc/com/intellij/ui/FileNameSplittingTest.java b/platform/platform-tests/testSrc/com/intellij/ui/FileNameSplittingTest.java index 0cb4e2fe51ce..01f3336b754e 100644 --- a/platform/platform-tests/testSrc/com/intellij/ui/FileNameSplittingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ui/FileNameSplittingTest.java @@ -119,13 +119,10 @@ public class FileNameSplittingTest extends TestCase { public void testPerformance() { myPolicy = FilePathSplittingPolicy.SPLIT_BY_SEPARATOR; - PlatformTestUtil.startPerformanceTest("FileNameSplitting performance", 70, new ThrowableRunnable() { - @Override - public void run() throws Exception { - for (int i = 0; i < 100; i++) { - for (int j = 0; j < FILE.getPath().length(); j++) - myPolicy.getPresentableName(FILE, j); - } + PlatformTestUtil.startPerformanceTest("FileNameSplitting performance", 70, () -> { + for (int i = 0; i < 100; i++) { + for (int j = 0; j < FILE.getPath().length(); j++) + myPolicy.getPresentableName(FILE, j); } }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/platform/platform-tests/testSrc/com/intellij/usages/impl/UsageNodeTreeBuilderTest.java b/platform/platform-tests/testSrc/com/intellij/usages/impl/UsageNodeTreeBuilderTest.java index 74d493d1a133..11ec56ee91e2 100644 --- a/platform/platform-tests/testSrc/com/intellij/usages/impl/UsageNodeTreeBuilderTest.java +++ b/platform/platform-tests/testSrc/com/intellij/usages/impl/UsageNodeTreeBuilderTest.java @@ -91,12 +91,7 @@ public class UsageNodeTreeBuilderTest extends LightPlatformTestCase { model.setRoot(rootNode); UsageNodeTreeBuilder usageNodeTreeBuilder = new UsageNodeTreeBuilder(UsageTarget.EMPTY_ARRAY, rules, UsageFilteringRule.EMPTY_ARRAY, rootNode, ourProject); for (Usage usage : usages) { - usageNodeTreeBuilder.appendUsage(usage, new Consumer() { - @Override - public void consume(Runnable runnable) { - runnable.run(); - } - }); + usageNodeTreeBuilder.appendUsage(usage, runnable -> runnable.run()); UIUtil.dispatchAllInvocationEvents(); } diff --git a/platform/platform-tests/testSrc/com/intellij/util/StringBuilderSpinAllocatorTest.java b/platform/platform-tests/testSrc/com/intellij/util/StringBuilderSpinAllocatorTest.java index 2d7f613e455d..e137dfe34355 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/StringBuilderSpinAllocatorTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/StringBuilderSpinAllocatorTest.java @@ -46,20 +46,14 @@ public class StringBuilderSpinAllocatorTest extends PlatformTestCase { } private static long concurrentTime(int count, final Runnable action) { - return time(count, new Runnable() { - @Override - public void run() { - boolean ok = - JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Collections.nCopies(THREADS, null), null, true, new Processor() { - @Override - public boolean process(Object o) { - action.run(); - return true; - } - }); + return time(count, () -> { + boolean ok = + JobLauncher.getInstance().invokeConcurrentlyUnderProgress(Collections.nCopies(THREADS, null), null, true, o -> { + action.run(); + return true; + }); - assertTrue(ok); - } + assertTrue(ok); }); } diff --git a/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java b/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java index bbeaa1d15fdb..44aee37f7195 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java @@ -97,40 +97,15 @@ public class TreeTraverserTest extends TestCase { }; } - public static final Function> WRAP_TO_LIST = new Function>() { - @Override - public List fun(Integer integer) { - return ContainerUtil.newArrayList(integer); - } - }; + public static final Function> WRAP_TO_LIST = integer -> ContainerUtil.newArrayList(integer); - public static final Function DIV_2 = new Function() { - @Override - public Integer fun(Integer k) { - return k / 2; - } - }; + public static final Function DIV_2 = k -> k / 2; - private static final Function INCREMENT = new Function() { - @Override - public Integer fun(Integer k) { - return k + 1; - } - }; + private static final Function INCREMENT = k -> k + 1; - private static final Function SQUARE = new Function() { - @Override - public Integer fun(Integer k) { - return k * k; - } - }; + private static final Function SQUARE = k -> k * k; - private static final PairFunction FIBONACCI = new PairFunction() { - @Override - public Integer fun(Integer k1, Integer k2) { - return k2 + k1; - } - }; + private static final PairFunction FIBONACCI = (k1, k2) -> k2 + k1; private static final Function FIBONACCI2 = new JBIterable.StatefulTransform() { int k0; @@ -371,12 +346,7 @@ public class TreeTraverserTest extends TestCase { //return it.append(JBIterable.generate(integer, Functions.id())); } }); - JBIterable counts = JBIterable.generate(1, INCREMENT).transform(new Function() { - @Override - public Integer fun(Integer integer) { - return traversal.fun(1).takeWhile(UP_TO(integer)).size(); - } - }); + JBIterable counts = JBIterable.generate(1, INCREMENT).transform(integer -> traversal.fun(1).takeWhile(UP_TO(integer)).size()); // 1: no repeat assertEquals(Arrays.asList(1, 4, 13, 39, 117, 359, 1134, 3686, 12276, 41708), counts.take(10).toList()); // 2: repeat all seq @@ -468,12 +438,7 @@ public class TreeTraverserTest extends TestCase { Integer cur = it.current().get(0); result.add(cur); assertEquals(JBIterable.generate(cur, DIV_2).takeWhile(IS_POSITIVE).toList(), it.backtrace().transform( - new Function, Integer>() { - @Override - public Integer fun(List integers) { - return integers.get(0); - } - } + integers -> integers.get(0) ).toList()); if (cur > 4) continue; it.current().add(cur*2); @@ -489,18 +454,15 @@ public class TreeTraverserTest extends TestCase { return new Function.Mono>() { @Override public TreeTraversal.GuidedIt fun(TreeTraversal.GuidedIt it) { - return it.setGuide(new Consumer>() { - @Override - public void consume(TreeTraversal.GuidedIt it) { - if (traversal == TreeTraversal.PRE_ORDER_DFS) { - it.queueNext(it.curChild).result(it.curChild); - } - else if (traversal == TreeTraversal.POST_ORDER_DFS) { - it.queueNext(it.curChild).result(it.curChild == null ? it.curParent : null); - } - else if (traversal == TreeTraversal.PLAIN_BFS) { - it.queueLast(it.curChild).result(it.curChild); - } + return it.setGuide(it1 -> { + if (traversal == TreeTraversal.PRE_ORDER_DFS) { + it1.queueNext(it1.curChild).result(it1.curChild); + } + else if (traversal == TreeTraversal.POST_ORDER_DFS) { + it1.queueNext(it1.curChild).result(it1.curChild == null ? it1.curParent : null); + } + else if (traversal == TreeTraversal.PLAIN_BFS) { + it1.queueLast(it1.curChild).result(it1.curChild); } }); } diff --git a/platform/platform-tests/testSrc/com/intellij/util/io/BTreeEnumeratorTest.java b/platform/platform-tests/testSrc/com/intellij/util/io/BTreeEnumeratorTest.java index 8298acd1d9fe..cf8c814399d2 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/io/BTreeEnumeratorTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/io/BTreeEnumeratorTest.java @@ -173,17 +173,14 @@ public class BTreeEnumeratorTest extends TestCase { } }; - PlatformTestUtil.startPerformanceTest("PersistentStringEnumerator performance failed", 2500, new ThrowableRunnable() { - @Override - public void run() throws Exception { - stringCache.addDeletedPairsListener(listener); - for (int i = 0; i < 100000; ++i) { - final String string = createRandomString(); - stringCache.cacheObject(myEnumerator.enumerate(string), string); - } - stringCache.removeDeletedPairsListener(listener); - stringCache.removeAll(); + PlatformTestUtil.startPerformanceTest("PersistentStringEnumerator performance failed", 2500, () -> { + stringCache.addDeletedPairsListener(listener); + for (int i = 0; i < 100000; ++i) { + final String string = createRandomString(); + stringCache.cacheObject(myEnumerator.enumerate(string), string); } + stringCache.removeDeletedPairsListener(listener); + stringCache.removeAll(); }).useLegacyScaling().assertTiming(); myEnumerator.close(); System.out.printf("File size = %d bytes\n", myFile.length()); diff --git a/platform/platform-tests/testSrc/com/intellij/util/io/StringEnumeratorTest.java b/platform/platform-tests/testSrc/com/intellij/util/io/StringEnumeratorTest.java index 6fa9c74383b7..2ebac533f2de 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/io/StringEnumeratorTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/io/StringEnumeratorTest.java @@ -162,17 +162,14 @@ public class StringEnumeratorTest extends TestCase { } }; - PlatformTestUtil.startPerformanceTest("PersistentStringEnumerator performance failed", 2500, new ThrowableRunnable() { - @Override - public void run() throws Exception { - stringCache.addDeletedPairsListener(listener); - for (int i = 0; i < 100000; ++i) { - final String string = createRandomString(); - stringCache.cacheObject(myEnumerator.enumerate(string), string); - } - stringCache.removeDeletedPairsListener(listener); - stringCache.removeAll(); + PlatformTestUtil.startPerformanceTest("PersistentStringEnumerator performance failed", 2500, () -> { + stringCache.addDeletedPairsListener(listener); + for (int i = 0; i < 100000; ++i) { + final String string = createRandomString(); + stringCache.cacheObject(myEnumerator.enumerate(string), string); } + stringCache.removeDeletedPairsListener(listener); + stringCache.removeAll(); }).cpuBound().useLegacyScaling().assertTiming(); myEnumerator.close(); System.out.printf("File size = %d bytes\n", myFile.length()); diff --git a/platform/platform-tests/testSrc/com/intellij/util/net/ssl/CertificateTest.java b/platform/platform-tests/testSrc/com/intellij/util/net/ssl/CertificateTest.java index 4f6d87ab64a9..a52d09b6e0e9 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/net/ssl/CertificateTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/net/ssl/CertificateTest.java @@ -128,43 +128,34 @@ public class CertificateTest extends LightPlatformTestCase { final long interruptionTimeout = CertificateManager.DIALOG_VISIBILITY_TIMEOUT + 1000; // Will be interrupted after at most interruptionTimeout (6 seconds originally) Thread[] t = {null}; - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - final Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - boolean accepted = CertificateManager.showAcceptDialog(new Callable() { - @Override - public DialogWrapper call() throws Exception { - // this dialog will be attempted to show only if blocking thread was forcibly interrupted after timeout - throw new AssertionError("Deadlock was not detected in time"); - } - }); - // should be rejected after 5 seconds - assertFalse("Certificate should be rejected", accepted); - } - catch (Throwable e) { - throwableRef.set(e); - } - } - }, "Test EDT-blocking thread"); - thread.start(); + ApplicationManager.getApplication().invokeAndWait(() -> { + final Thread thread = new Thread(() -> { try { - thread.join(interruptionTimeout); + boolean accepted = CertificateManager.showAcceptDialog(() -> { + // this dialog will be attempted to show only if blocking thread was forcibly interrupted after timeout + throw new AssertionError("Deadlock was not detected in time"); + }); + // should be rejected after 5 seconds + assertFalse("Certificate should be rejected", accepted); } - catch (InterruptedException ignored) { - // No one will attempt to interrupt EDT, right? + catch (Throwable e) { + throwableRef.set(e); } - finally { - if (thread.isAlive()) { - thread.interrupt(); - fail("Deadlock was not detected in time"); - } - } - t[0] = thread; + }, "Test EDT-blocking thread"); + thread.start(); + try { + thread.join(interruptionTimeout); } + catch (InterruptedException ignored) { + // No one will attempt to interrupt EDT, right? + } + finally { + if (thread.isAlive()) { + thread.interrupt(); + fail("Deadlock was not detected in time"); + } + } + t[0] = thread; }, ModalityState.any()); if (!throwableRef.isNull()) { throw new AssertionError(throwableRef.get()); diff --git a/platform/platform-tests/testSrc/com/intellij/util/ui/tree/TreeUtilTest.java b/platform/platform-tests/testSrc/com/intellij/util/ui/tree/TreeUtilTest.java index bb3536cec3b9..e2dc8261a6c3 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/ui/tree/TreeUtilTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/ui/tree/TreeUtilTest.java @@ -138,23 +138,17 @@ public class TreeUtilTest extends PlatformTestCase { DefaultMutableTreeNode node1_1 = new DefaultMutableTreeNode("1_1"); node1.add(node1_1); DefaultTreeModel model = new DefaultTreeModel(root); - TreeUtil.sort(model, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return o1.toString().compareTo(o2.toString()); - } + TreeUtil.sort(model, (o1, o2) -> { + return o1.toString().compareTo(o2.toString()); }); assertEquals(node1, root.getChildAt(0)); assertEquals(node2, root.getChildAt(1)); assertEquals(node1_1, node1.getChildAt(0)); assertEquals(node1_2, node1.getChildAt(1)); - TreeUtil.sort(model, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - TreeNode n1 = (TreeNode) o1; - TreeNode n2 = (TreeNode) o2; - return n1.getChildCount() - n2.getChildCount(); - } + TreeUtil.sort(model, (o1, o2) -> { + TreeNode n1 = (TreeNode) o1; + TreeNode n2 = (TreeNode) o2; + return n1.getChildCount() - n2.getChildCount(); }); assertEquals(node2, root.getChildAt(0)); assertEquals(node1, root.getChildAt(1)); diff --git a/platform/projectModel-api/src/com/intellij/lang/PerFileMappingsBase.java b/platform/projectModel-api/src/com/intellij/lang/PerFileMappingsBase.java index ab93381f7fa6..f7b45ddacb06 100644 --- a/platform/projectModel-api/src/com/intellij/lang/PerFileMappingsBase.java +++ b/platform/projectModel-api/src/com/intellij/lang/PerFileMappingsBase.java @@ -196,12 +196,9 @@ public abstract class PerFileMappingsBase implements PersistentStateComponent cleanup(); final Element element = new Element("x"); final List files = new ArrayList(myMappings.keySet()); - Collections.sort(files, new Comparator() { - @Override - public int compare(final VirtualFile o1, final VirtualFile o2) { - if (o1 == null || o2 == null) return o1 == null ? o2 == null ? 0 : 1 : -1; - return o1.getPath().compareTo(o2.getPath()); - } + Collections.sort(files, (o1, o2) -> { + if (o1 == null || o2 == null) return o1 == null ? o2 == null ? 0 : 1 : -1; + return o1.getPath().compareTo(o2.getPath()); }); for (VirtualFile file : files) { final T dialect = myMappings.get(file); diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/ModuleRootModificationUtil.java b/platform/projectModel-api/src/com/intellij/openapi/roots/ModuleRootModificationUtil.java index 8b3f56976eba..0ae750a5f29b 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/ModuleRootModificationUtil.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/ModuleRootModificationUtil.java @@ -37,12 +37,7 @@ import java.util.List; */ public class ModuleRootModificationUtil { public static void addContentRoot(@NotNull Module module, final @NotNull String path) { - updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - model.addContentEntry(VfsUtilCore.pathToUrl(path)); - } - }); + updateModel(module, model -> model.addContentEntry(VfsUtilCore.pathToUrl(path))); } public static void addModuleLibrary(@NotNull Module module, @Nullable String libName, @NotNull List classesRoots, @NotNull List sourceRoots) { @@ -69,34 +64,26 @@ public class ModuleRootModificationUtil { final @NotNull List excludedRoots, final @NotNull DependencyScope scope, final boolean exported) { - updateModel(module, new Consumer() { - @Override - public void consume(final ModifiableRootModel model) { - final LibraryEx library = (LibraryEx)model.getModuleLibraryTable().createLibrary(libName); - final LibraryEx.ModifiableModelEx libraryModel = library.getModifiableModel(); + updateModel(module, model -> { + final LibraryEx library = (LibraryEx)model.getModuleLibraryTable().createLibrary(libName); + final LibraryEx.ModifiableModelEx libraryModel = library.getModifiableModel(); - for (String root : classesRoots) { - libraryModel.addRoot(root, OrderRootType.CLASSES); - } - for (String root : sourceRoots) { - libraryModel.addRoot(root, OrderRootType.SOURCES); - } - for (String excluded : excludedRoots) { - libraryModel.addExcludedRoot(excluded); - } - - LibraryOrderEntry entry = model.findLibraryOrderEntry(library); - assert entry != null : library; - entry.setScope(scope); - entry.setExported(exported); - - doWriteAction(new Runnable() { - @Override - public void run() { - libraryModel.commit(); - } - }); + for (String root : classesRoots) { + libraryModel.addRoot(root, OrderRootType.CLASSES); } + for (String root : sourceRoots) { + libraryModel.addRoot(root, OrderRootType.SOURCES); + } + for (String excluded : excludedRoots) { + libraryModel.addExcludedRoot(excluded); + } + + LibraryOrderEntry entry = model.findLibraryOrderEntry(library); + assert entry != null : library; + entry.setScope(scope); + entry.setExported(exported); + + doWriteAction(() -> libraryModel.commit()); }); } @@ -109,32 +96,19 @@ public class ModuleRootModificationUtil { } public static void addDependency(@NotNull Module module, final @NotNull Library library, final @NotNull DependencyScope scope, final boolean exported) { - updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - LibraryOrderEntry entry = model.addLibraryEntry(library); - entry.setExported(exported); - entry.setScope(scope); - } + updateModel(module, model -> { + LibraryOrderEntry entry = model.addLibraryEntry(library); + entry.setExported(exported); + entry.setScope(scope); }); } public static void setModuleSdk(@NotNull Module module, @Nullable final Sdk sdk) { - updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - model.setSdk(sdk); - } - }); + updateModel(module, model -> model.setSdk(sdk)); } public static void setSdkInherited(@NotNull Module module) { - updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - model.inheritSdk(); - } - }); + updateModel(module, model -> model.inheritSdk()); } public static void addDependency(final @NotNull Module from, final @NotNull Module to) { @@ -142,13 +116,10 @@ public class ModuleRootModificationUtil { } public static void addDependency(@NotNull Module from, @NotNull final Module to, @NotNull final DependencyScope scope, final boolean exported) { - updateModel(from, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - ModuleOrderEntry entry = model.addModuleOrderEntry(to); - entry.setScope(scope); - entry.setExported(exported); - } + updateModel(from, model -> { + ModuleOrderEntry entry = model.addModuleOrderEntry(to); + entry.setScope(scope); + entry.setExported(exported); }); } @@ -161,12 +132,7 @@ public class ModuleRootModificationUtil { }); try { task.consume(model); - doWriteAction(new Runnable() { - @Override - public void run() { - model.commit(); - } - }); + doWriteAction(() -> model.commit()); } catch (RuntimeException e) { model.dispose(); @@ -182,19 +148,16 @@ public class ModuleRootModificationUtil { @NotNull final VirtualFile contentRoot, @NotNull final Collection urlsToUnExclude, @NotNull final Collection urlsToExclude) { - updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel modifiableModel) { - for (final ContentEntry contentEntry : modifiableModel.getContentEntries()) { - if (contentRoot.equals(contentEntry.getFile())) { - for (String url : urlsToUnExclude) { - contentEntry.removeExcludeFolder(url); - } - for (String url : urlsToExclude) { - contentEntry.addExcludeFolder(url); - } - break; + updateModel(module, modifiableModel -> { + for (final ContentEntry contentEntry : modifiableModel.getContentEntries()) { + if (contentRoot.equals(contentEntry.getFile())) { + for (String url : urlsToUnExclude) { + contentEntry.removeExcludeFolder(url); } + for (String url : urlsToExclude) { + contentEntry.addExcludeFolder(url); + } + break; } } }); @@ -202,11 +165,6 @@ public class ModuleRootModificationUtil { private static void doWriteAction(final Runnable action) { final Application application = ApplicationManager.getApplication(); - application.invokeAndWait(new Runnable() { - @Override - public void run() { - application.runWriteAction(action); - } - }, application.getDefaultModalityState()); + application.invokeAndWait(() -> application.runWriteAction(action), application.getDefaultModalityState()); } } diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/OrderRootType.java b/platform/projectModel-api/src/com/intellij/openapi/roots/OrderRootType.java index 83ceea1f823b..d5967e16bc9d 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/OrderRootType.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/OrderRootType.java @@ -111,12 +111,7 @@ public class OrderRootType { public static List getSortedRootTypes() { List allTypes = new ArrayList(); Collections.addAll(allTypes, getAllPersistentTypes()); - Collections.sort(allTypes, new Comparator() { - @Override - public int compare(@NotNull final PersistentOrderRootType o1, @NotNull final PersistentOrderRootType o2) { - return o1.name().compareToIgnoreCase(o2.name()); - } - }); + Collections.sort(allTypes, (o1, o2) -> o1.name().compareToIgnoreCase(o2.name())); return allTypes; } diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java b/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java index 3dd21fe8ee95..c035bda2ee4d 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java @@ -137,15 +137,12 @@ public class LibraryUtil { @Nullable public static Library findLibrary(@NotNull Module module, @NotNull final String name) { final Ref result = Ref.create(null); - OrderEnumerator.orderEntries(module).forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - if (name.equals(library.getName())) { - result.set(library); - return false; - } - return true; + OrderEnumerator.orderEntries(module).forEachLibrary(library -> { + if (name.equals(library.getName())) { + result.set(library); + return false; } + return true; }); return result.get(); } diff --git a/platform/projectModel-impl/src/com/intellij/application/options/ReplacePathToMacroMap.java b/platform/projectModel-impl/src/com/intellij/application/options/ReplacePathToMacroMap.java index 67278c21510a..0fa287501796 100644 --- a/platform/projectModel-impl/src/com/intellij/application/options/ReplacePathToMacroMap.java +++ b/platform/projectModel-impl/src/com/intellij/application/options/ReplacePathToMacroMap.java @@ -199,17 +199,9 @@ public class ReplacePathToMacroMap extends PathMacroMap { weights.put(entry, getIndex(entry) * 512 + stripPrefix(entry.getKey())); } - ContainerUtil.sort(entries, new Comparator>() { - @Override - public int compare(final Map.Entry o1, final Map.Entry o2) { - return weights.get(o2) - weights.get(o1); - } - }); - myPathsIndex = ContainerUtil.map2List(entries, new Function, String>() { - @Override - public String fun(Map.Entry entry) { - return entry.getKey(); - } + ContainerUtil.sort(entries, (o1, o2) -> weights.get(o2) - weights.get(o1)); + myPathsIndex = ContainerUtil.map2List(entries, entry -> { + return entry.getKey(); }); } return myPathsIndex; diff --git a/platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModuleManagerImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModuleManagerImpl.java index 69c7375cc495..54bdf498a8d1 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModuleManagerImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModuleManagerImpl.java @@ -178,11 +178,8 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project loadModules((ModuleModelImpl)model); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + model.commit(); }); } } @@ -314,12 +311,7 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project protected void fireModulesRenamed(@NotNull List modules, @NotNull final Map oldNames) { if (!modules.isEmpty()) { - myMessageBus.syncPublisher(ProjectTopics.MODULES).modulesRenamed(myProject, modules, new Function() { - @Override - public String fun(Module module) { - return oldNames.get(module); - } - }); + myMessageBus.syncPublisher(ProjectTopics.MODULES).modulesRenamed(myProject, modules, module -> oldNames.get(module)); } } @@ -331,11 +323,8 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project final Module module = myModuleModel.getModuleByFilePath(FileUtil.toSystemIndependentName(error.getModulePath().getPath())); if (module != null) { myModuleModel.myModules.remove(module.getName()); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Disposer.dispose(module); - } + ApplicationManager.getApplication().invokeLater(() -> { + Disposer.dispose(module); }, module.getDisposed()); } } @@ -459,12 +448,7 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project } if (!sorted.isEmpty()) { - Collections.sort(sorted, new Comparator() { - @Override - public int compare(SaveItem item1, SaveItem item2) { - return item1.getModuleName().compareTo(item2.getModuleName()); - } - }); + Collections.sort(sorted, (item1, item2) -> item1.getModuleName().compareTo(item2.getModuleName())); Element modules = new Element(ELEMENT_MODULES); for (SaveItem saveItem : sorted) { @@ -496,13 +480,10 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project @Override public void disposeModule(@NotNull final Module module) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final ModifiableModuleModel modifiableModel = getModifiableModel(); - modifiableModel.disposeModule(module); - modifiableModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final ModifiableModuleModel modifiableModel = getModifiableModel(); + modifiableModel.disposeModule(module); + modifiableModel.commit(); }); } @@ -590,12 +571,9 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project } protected void fireModuleAddedInWriteAction(@NotNull final Module module) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ((ModuleEx)module).moduleAdded(); - fireModuleAdded(module); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ((ModuleEx)module).moduleAdded(); + fireModuleAdded(module); }); } @@ -712,14 +690,11 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project if (module == null) { module = createModule(filePath); final ModuleEx newModule = module; - initModule(module, filePath, new Runnable() { - @Override - public void run() { - newModule.setOption(Module.ELEMENT_TYPE, moduleTypeId); - if (options != null) { - for (Map.Entry option : options.entrySet()) { - newModule.setOption(option.getKey(), option.getValue()); - } + initModule(module, filePath, () -> { + newModule.setOption(Module.ELEMENT_TYPE, moduleTypeId); + if (options != null) { + for (Map.Entry option : options.entrySet()) { + newModule.setOption(option.getKey(), option.getValue()); } } }); @@ -773,12 +748,7 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project String path = moduleFile.getPath(); ModuleEx module = getModuleByFilePath(path); if (module == null) { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - moduleFile.refresh(false, false); - } - }, ModalityState.any()); + ApplicationManager.getApplication().invokeAndWait(() -> moduleFile.refresh(false, false), ModalityState.any()); module = createAndLoadModule(path); initModule(module, path, null); } @@ -947,59 +917,56 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project final List addedModules = new ArrayList(newModules); addedModules.removeAll(oldModules); - ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange(new Runnable() { - @Override - public void run() { - for (Module removedModule : removedModules) { - fireBeforeModuleRemoved(removedModule); - cleanCachedStuff(); - } - - List neverAddedModules = new ArrayList(moduleModel.myModulesToDispose); - neverAddedModules.removeAll(myModuleModel.myModules.values()); - for (final Module neverAddedModule : neverAddedModules) { - neverAddedModule.putUserData(DISPOSED_MODULE_NAME, neverAddedModule.getName()); - Disposer.dispose(neverAddedModule); - } - - if (runnable != null) { - runnable.run(); - } - - final Map modulesToNewNamesMap = moduleModel.myModuleToNewName; - final Set modulesToBeRenamed = modulesToNewNamesMap.keySet(); - modulesToBeRenamed.removeAll(moduleModel.myModulesToDispose); - - List modules = new ArrayList(); - Map oldNames = ContainerUtil.newHashMap(); - for (final Module module : modulesToBeRenamed) { - oldNames.put(module, module.getName()); - moduleModel.myModules.remove(module.getName()); - modules.add(module); - ((ModuleEx)module).rename(modulesToNewNamesMap.get(module)); - moduleModel.myModules.put(module.getName(), module); - } - - moduleModel.myIsWritable = false; - myModuleModel = moduleModel; - - for (Module module : removedModules) { - fireModuleRemoved(module); - cleanCachedStuff(); - Disposer.dispose(module); - cleanCachedStuff(); - } - - for (Module addedModule : addedModules) { - ((ModuleEx)addedModule).moduleAdded(); - cleanCachedStuff(); - fireModuleAdded(addedModule); - cleanCachedStuff(); - } - cleanCachedStuff(); - fireModulesRenamed(modules, oldNames); + ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange(() -> { + for (Module removedModule : removedModules) { + fireBeforeModuleRemoved(removedModule); cleanCachedStuff(); } + + List neverAddedModules = new ArrayList(moduleModel.myModulesToDispose); + neverAddedModules.removeAll(myModuleModel.myModules.values()); + for (final Module neverAddedModule : neverAddedModules) { + neverAddedModule.putUserData(DISPOSED_MODULE_NAME, neverAddedModule.getName()); + Disposer.dispose(neverAddedModule); + } + + if (runnable != null) { + runnable.run(); + } + + final Map modulesToNewNamesMap = moduleModel.myModuleToNewName; + final Set modulesToBeRenamed = modulesToNewNamesMap.keySet(); + modulesToBeRenamed.removeAll(moduleModel.myModulesToDispose); + + List modules = new ArrayList(); + Map oldNames = ContainerUtil.newHashMap(); + for (final Module module : modulesToBeRenamed) { + oldNames.put(module, module.getName()); + moduleModel.myModules.remove(module.getName()); + modules.add(module); + ((ModuleEx)module).rename(modulesToNewNamesMap.get(module)); + moduleModel.myModules.put(module.getName(), module); + } + + moduleModel.myIsWritable = false; + myModuleModel = moduleModel; + + for (Module module : removedModules) { + fireModuleRemoved(module); + cleanCachedStuff(); + Disposer.dispose(module); + cleanCachedStuff(); + } + + for (Module addedModule : addedModules) { + ((ModuleEx)addedModule).moduleAdded(); + cleanCachedStuff(); + fireModuleAdded(addedModule); + cleanCachedStuff(); + } + cleanCachedStuff(); + fireModulesRenamed(modules, oldNames); + cleanCachedStuff(); }, false, true); } @@ -1008,12 +975,8 @@ public abstract class ModuleManagerImpl extends ModuleManager implements Project LOG.assertTrue(moduleInMap == null || moduleInMap == module); myModuleModel.myModules.put(module.getName(), module); - ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange(new Runnable() { - @Override - public void run() { - fireModulesRenamed(Collections.singletonList(module), Collections.singletonMap(module, oldName)); - } - }, false, true); + ProjectRootManagerEx.getInstanceEx(myProject).makeRootsChange( + () -> fireModulesRenamed(Collections.singletonList(module), Collections.singletonMap(module, oldName)), false, true); } @Override diff --git a/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkImpl.java index 88703b89c236..274c1a9ab3ba 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkImpl.java @@ -320,11 +320,8 @@ public class ProjectJdkImpl extends UserDataHolderBase implements Sdk, SdkModifi if (myListeners.isEmpty()) { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - fireRootSetChanged(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + fireRootSetChanged(); }); } } diff --git a/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectRootContainerImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectRootContainerImpl.java index 85813cee6827..b083c19afc8d 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectRootContainerImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/projectRoots/impl/ProjectRootContainerImpl.java @@ -163,17 +163,14 @@ public class ProjectRootContainerImpl implements JDOMExternalizable, ProjectRoot read(element, type); } - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - myFiles = new HashMap(); - for (OrderRootType rootType : myRoots.keySet()) { - CompositeProjectRoot root = myRoots.get(rootType); - if (myNoCopyJars) { - setNoCopyJars(root); - } - myFiles.put(rootType, root.getVirtualFiles()); + ApplicationManager.getApplication().runReadAction(() -> { + myFiles = new HashMap(); + for (OrderRootType rootType : myRoots.keySet()) { + CompositeProjectRoot root = myRoots.get(rootType); + if (myNoCopyJars) { + setNoCopyJars(root); } + myFiles.put(rootType, root.getVirtualFiles()); } }); diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/LibraryOrderEntryBaseImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/LibraryOrderEntryBaseImpl.java index 11d9fc3be301..4bc86e994565 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/LibraryOrderEntryBaseImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/LibraryOrderEntryBaseImpl.java @@ -81,12 +81,7 @@ abstract class LibraryOrderEntryBaseImpl extends OrderEntryBaseImpl implements L } protected void updateFromRootProviderAndSubscribe() { - getRootModel().makeExternalChange(new Runnable() { - @Override - public void run() { - resubscribe(getRootProvider()); - } - }); + getRootModel().makeExternalChange(() -> resubscribe(getRootProvider())); } private void resubscribe(RootProvider wrapper) { diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java index b39ba50001e5..121a40093908 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java @@ -45,15 +45,12 @@ public class ModifiableModelCommitter { final List modelsToDispose = ContainerUtil.newArrayList(rootModels); modelsToDispose.removeAll(modelsToCommit); - ModuleManagerImpl.commitModelWithRunnable(moduleModel, new Runnable() { - @Override - public void run() { - for (RootModelImpl model : modelsToCommit) { - ModuleRootManagerImpl.doCommit(model); - } - for (ModifiableRootModel model : modelsToDispose) { - model.dispose(); - } + ModuleManagerImpl.commitModelWithRunnable(moduleModel, () -> { + for (RootModelImpl model : modelsToCommit) { + ModuleRootManagerImpl.doCommit(model); + } + for (ModifiableRootModel model : modelsToDispose) { + model.dispose(); } }); } diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModuleRootManagerImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModuleRootManagerImpl.java index 033e7d285660..b6a3c0212171 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModuleRootManagerImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModuleRootManagerImpl.java @@ -351,12 +351,7 @@ public class ModuleRootManagerImpl extends ModuleRootManager implements ModuleCo final RootModelImpl newModel = new RootModelImpl(object.getRootModelElement(), this, myProjectRootManager, myFilePointerManager, throwEvent); if (throwEvent) { - makeRootsChange(new Runnable() { - @Override - public void run() { - doCommit(newModel); - } - }); + makeRootsChange(() -> doCommit(newModel)); } else { myRootModel.dispose(); diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderEnumeratorBase.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderEnumeratorBase.java index 52edb8cc3c50..96c67a4820c0 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderEnumeratorBase.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderEnumeratorBase.java @@ -325,11 +325,8 @@ abstract class OrderEnumeratorBase extends OrderEnumerator implements OrderEnume @Override public void forEach(@NotNull final Processor processor) { - forEach(new PairProcessor>() { - @Override - public boolean process(OrderEntry entry, List handlers) { - return processor.process(entry); - } + forEach((entry, handlers) -> { + return processor.process(entry); }); } @@ -337,37 +334,31 @@ abstract class OrderEnumeratorBase extends OrderEnumerator implements OrderEnume @Override public void forEachLibrary(@NotNull final Processor processor) { - forEach(new PairProcessor>() { - @Override - public boolean process(OrderEntry entry, List handlers) { - if (entry instanceof LibraryOrderEntry) { - final Library library = ((LibraryOrderEntry)entry).getLibrary(); - if (library != null) { - return processor.process(library); - } + forEach((entry, handlers) -> { + if (entry instanceof LibraryOrderEntry) { + final Library library = ((LibraryOrderEntry)entry).getLibrary(); + if (library != null) { + return processor.process(library); } - return true; } + return true; }); } @Override public void forEachModule(@NotNull final Processor processor) { - forEach(new PairProcessor>() { - @Override - public boolean process(OrderEntry orderEntry, List customHandlers) { - if (myRecursively && orderEntry instanceof ModuleSourceOrderEntry) { - final Module module = ((ModuleSourceOrderEntry)orderEntry).getRootModel().getModule(); + forEach((orderEntry, customHandlers) -> { + if (myRecursively && orderEntry instanceof ModuleSourceOrderEntry) { + final Module module = ((ModuleSourceOrderEntry)orderEntry).getRootModel().getModule(); + return processor.process(module); + } + if (orderEntry instanceof ModuleOrderEntry && (!myRecursively || !shouldProcessRecursively(customHandlers))) { + final Module module = ((ModuleOrderEntry)orderEntry).getModule(); + if (module != null) { return processor.process(module); } - if (orderEntry instanceof ModuleOrderEntry && (!myRecursively || !shouldProcessRecursively(customHandlers))) { - final Module module = ((ModuleOrderEntry)orderEntry).getModule(); - if (module != null) { - return processor.process(module); - } - } - return true; } + return true; }); } diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderRootsEnumeratorImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderRootsEnumeratorImpl.java index 2a533c9626f3..9f60534a0d7c 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderRootsEnumeratorImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/OrderRootsEnumeratorImpl.java @@ -104,40 +104,37 @@ public class OrderRootsEnumeratorImpl implements OrderRootsEnumerator { private Collection computeRoots() { final Collection result = new LinkedHashSet(); - myOrderEnumerator.forEach(new PairProcessor>() { - @Override - public boolean process(OrderEntry orderEntry, List customHandlers) { - OrderRootType type = getRootType(orderEntry); + myOrderEnumerator.forEach((orderEntry, customHandlers) -> { + OrderRootType type = getRootType(orderEntry); - if (orderEntry instanceof ModuleSourceOrderEntry) { - collectModuleRoots(type, ((ModuleSourceOrderEntry)orderEntry).getRootModel(), result, true, !myOrderEnumerator.isProductionOnly(), - customHandlers); - } - else if (orderEntry instanceof ModuleOrderEntry) { - ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry; - final Module module = moduleOrderEntry.getModule(); - if (module != null) { - ModuleRootModel rootModel = myOrderEnumerator.getRootModel(module); - boolean productionOnTests = orderEntry instanceof ModuleOrderEntryImpl - && ((ModuleOrderEntryImpl)orderEntry).isProductionOnTestDependency(); - boolean includeTests = !myOrderEnumerator.isProductionOnly() - && myOrderEnumerator.shouldIncludeTestsFromDependentModulesToTestClasspath(customHandlers) - || productionOnTests; - collectModuleRoots(type, rootModel, result, !productionOnTests, includeTests, customHandlers); - } - } - else { - if (myCustomRootProvider != null) { - Collections.addAll(result, myCustomRootProvider.fun(orderEntry)); - return true; - } - if (myOrderEnumerator.addCustomRootsForLibrary(orderEntry, type, result, customHandlers)) { - return true; - } - Collections.addAll(result, orderEntry.getFiles(type)); - } - return true; + if (orderEntry instanceof ModuleSourceOrderEntry) { + collectModuleRoots(type, ((ModuleSourceOrderEntry)orderEntry).getRootModel(), result, true, !myOrderEnumerator.isProductionOnly(), + customHandlers); } + else if (orderEntry instanceof ModuleOrderEntry) { + ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry; + final Module module = moduleOrderEntry.getModule(); + if (module != null) { + ModuleRootModel rootModel = myOrderEnumerator.getRootModel(module); + boolean productionOnTests = orderEntry instanceof ModuleOrderEntryImpl + && ((ModuleOrderEntryImpl)orderEntry).isProductionOnTestDependency(); + boolean includeTests = !myOrderEnumerator.isProductionOnly() + && myOrderEnumerator.shouldIncludeTestsFromDependentModulesToTestClasspath(customHandlers) + || productionOnTests; + collectModuleRoots(type, rootModel, result, !productionOnTests, includeTests, customHandlers); + } + } + else { + if (myCustomRootProvider != null) { + Collections.addAll(result, myCustomRootProvider.fun(orderEntry)); + return true; + } + if (myOrderEnumerator.addCustomRootsForLibrary(orderEntry, type, result, customHandlers)) { + return true; + } + Collections.addAll(result, orderEntry.getFiles(type)); + } + return true; }); return result; } @@ -145,34 +142,31 @@ public class OrderRootsEnumeratorImpl implements OrderRootsEnumerator { @NotNull private Collection computeRootsUrls() { final Collection result = new LinkedHashSet(); - myOrderEnumerator.forEach(new PairProcessor>() { - @Override - public boolean process(OrderEntry orderEntry, List customHandlers) { - OrderRootType type = getRootType(orderEntry); + myOrderEnumerator.forEach((orderEntry, customHandlers) -> { + OrderRootType type = getRootType(orderEntry); - if (orderEntry instanceof ModuleSourceOrderEntry) { - collectModuleRootsUrls(type, ((ModuleSourceOrderEntry)orderEntry).getRootModel(), result, true, !myOrderEnumerator.isProductionOnly()); - } - else if (orderEntry instanceof ModuleOrderEntry) { - ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry; - final Module module = moduleOrderEntry.getModule(); - if (module != null) { - ModuleRootModel rootModel = myOrderEnumerator.getRootModel(module); - boolean productionOnTests = orderEntry instanceof ModuleOrderEntryImpl - && ((ModuleOrderEntryImpl)orderEntry).isProductionOnTestDependency(); - boolean includeTests = !myOrderEnumerator.isProductionOnly() && myOrderEnumerator.shouldIncludeTestsFromDependentModulesToTestClasspath(customHandlers) - || productionOnTests; - collectModuleRootsUrls(type, rootModel, result, !productionOnTests, includeTests); - } - } - else { - if (myOrderEnumerator.addCustomRootUrlsForLibrary(orderEntry, type, result, customHandlers)) { - return true; - } - Collections.addAll(result, orderEntry.getUrls(type)); - } - return true; + if (orderEntry instanceof ModuleSourceOrderEntry) { + collectModuleRootsUrls(type, ((ModuleSourceOrderEntry)orderEntry).getRootModel(), result, true, !myOrderEnumerator.isProductionOnly()); } + else if (orderEntry instanceof ModuleOrderEntry) { + ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)orderEntry; + final Module module = moduleOrderEntry.getModule(); + if (module != null) { + ModuleRootModel rootModel = myOrderEnumerator.getRootModel(module); + boolean productionOnTests = orderEntry instanceof ModuleOrderEntryImpl + && ((ModuleOrderEntryImpl)orderEntry).isProductionOnTestDependency(); + boolean includeTests = !myOrderEnumerator.isProductionOnly() && myOrderEnumerator.shouldIncludeTestsFromDependentModulesToTestClasspath(customHandlers) + || productionOnTests; + collectModuleRootsUrls(type, rootModel, result, !productionOnTests, includeTests); + } + } + else { + if (myOrderEnumerator.addCustomRootUrlsForLibrary(orderEntry, type, result, customHandlers)) { + return true; + } + Collections.addAll(result, orderEntry.getUrls(type)); + } + return true; }); return result; } diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectOrderEnumerator.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectOrderEnumerator.java index 49ba859798a3..f8c539db5b06 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectOrderEnumerator.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectOrderEnumerator.java @@ -52,12 +52,9 @@ public class ProjectOrderEnumerator extends OrderEnumeratorBase { myRecursively = false; myWithoutDepModules = true; final THashSet processed = new THashSet(); - processRootModules(new Processor() { - @Override - public boolean process(Module module) { - processEntries(getRootModel(module), processor, processed, true, getCustomHandlers(module)); - return true; - } + processRootModules(module -> { + processEntries(getRootModel(module), processor, processed, true, getCustomHandlers(module)); + return true; }); } diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java index b4a149ad3281..65d68f158cd5 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java @@ -240,12 +240,7 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Pers } private void projectJdkChanged() { - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - myProjectJdkEventDispatcher.getMulticaster().projectJdkChanged(); - } - }); + mergeRootsChangesDuring(() -> myProjectJdkEventDispatcher.getMulticaster().projectJdkChanged()); Sdk sdk = getProjectSdk(); for (ProjectExtension extension : Extensions.getExtensions(ProjectExtension.EP_NAME, myProject)) { extension.projectSdkChanged(sdk); @@ -518,12 +513,9 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Pers @Override public void afterLibraryAdded(final Library newLibrary) { incModificationCount(); - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (LibraryTable.Listener listener : getListeners()) { - listener.afterLibraryAdded(newLibrary); - } + mergeRootsChangesDuring(() -> { + for (LibraryTable.Listener listener : getListeners()) { + listener.afterLibraryAdded(newLibrary); } }); } @@ -538,12 +530,9 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Pers @Override public void afterLibraryRenamed(final Library library) { incModificationCount(); - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (LibraryTable.Listener listener : getListeners()) { - listener.afterLibraryRenamed(library); - } + mergeRootsChangesDuring(() -> { + for (LibraryTable.Listener listener : getListeners()) { + listener.afterLibraryRenamed(library); } }); } @@ -551,12 +540,9 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Pers @Override public void beforeLibraryRemoved(final Library library) { incModificationCount(); - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (LibraryTable.Listener listener : getListeners()) { - listener.beforeLibraryRemoved(library); - } + mergeRootsChangesDuring(() -> { + for (LibraryTable.Listener listener : getListeners()) { + listener.beforeLibraryRemoved(library); } }); } @@ -564,12 +550,9 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Pers @Override public void afterLibraryRemoved(final Library library) { incModificationCount(); - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (LibraryTable.Listener listener : getListeners()) { - listener.afterLibraryRemoved(library); - } + mergeRootsChangesDuring(() -> { + for (LibraryTable.Listener listener : getListeners()) { + listener.afterLibraryRemoved(library); } }); } @@ -606,36 +589,27 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Pers @Override public void jdkAdded(final Sdk jdk) { - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (ProjectJdkTable.Listener listener : getListeners()) { - listener.jdkAdded(jdk); - } + mergeRootsChangesDuring(() -> { + for (ProjectJdkTable.Listener listener : getListeners()) { + listener.jdkAdded(jdk); } }); } @Override public void jdkRemoved(final Sdk jdk) { - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (ProjectJdkTable.Listener listener : getListeners()) { - listener.jdkRemoved(jdk); - } + mergeRootsChangesDuring(() -> { + for (ProjectJdkTable.Listener listener : getListeners()) { + listener.jdkRemoved(jdk); } }); } @Override public void jdkNameChanged(final Sdk jdk, final String previousName) { - mergeRootsChangesDuring(new Runnable() { - @Override - public void run() { - for (ProjectJdkTable.Listener listener : getListeners()) { - listener.jdkNameChanged(jdk, previousName); - } + mergeRootsChangesDuring(() -> { + for (ProjectJdkTable.Listener listener : getListeners()) { + listener.jdkNameChanged(jdk, previousName); } }); String currentName = getProjectSdkName(); diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java index 649ac03176d2..84ce2f749f74 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootIndex.java @@ -43,13 +43,10 @@ import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import java.util.*; public class RootIndex { - public static final Comparator BY_OWNER_MODULE = new Comparator() { - @Override - public int compare(OrderEntry o1, OrderEntry o2) { - String name1 = o1.getOwnerModule().getName(); - String name2 = o2.getOwnerModule().getName(); - return name1.compareTo(name2); - } + public static final Comparator BY_OWNER_MODULE = (o1, o2) -> { + String name1 = o1.getOwnerModule().getName(); + String name2 = o2.getOwnerModule().getName(); + return name1.compareTo(name2); }; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.RootIndex"); diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/ServerType.java b/platform/remote-servers/api/src/com/intellij/remoteServer/ServerType.java index df82845f36e7..3402920719ea 100644 --- a/platform/remote-servers/api/src/com/intellij/remoteServer/ServerType.java +++ b/platform/remote-servers/api/src/com/intellij/remoteServer/ServerType.java @@ -74,13 +74,7 @@ public abstract class ServerType { @NotNull public Comparator getDeploymentComparator() { - return new Comparator() { - - @Override - public int compare(Deployment o1, Deployment o2) { - return o1.getName().compareTo(o2.getName()); - } - }; + return (o1, o2) -> o1.getName().compareTo(o2.getName()); } @Nullable diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/agent/impl/ThreadInvocationHandler.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/agent/impl/ThreadInvocationHandler.java index a133ae782340..da7d459c6023 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/agent/impl/ThreadInvocationHandler.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/agent/impl/ThreadInvocationHandler.java @@ -51,21 +51,17 @@ public class ThreadInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { - final Callable taskCallable = new Callable() { - - @Override - public Object call() { - try { - return method.invoke(myTarget, args); - } - catch (IllegalAccessException e) { - LOG.error(e); - return null; - } - catch (InvocationTargetException e) { - LOG.error(e); - return null; - } + final Callable taskCallable = () -> { + try { + return method.invoke(myTarget, args); + } + catch (IllegalAccessException e) { + LOG.error(e); + return null; + } + catch (InvocationTargetException e) { + LOG.error(e); + return null; } }; @@ -103,16 +99,12 @@ public class ThreadInvocationHandler implements InvocationHandler { boolean asyncCall = method.getAnnotation(AsyncCall.class) != null; if (asyncCall) { - myTaskExecutor.submit(new Runnable() { - - @Override - public void run() { - try { - taskCallable.call(); - } - catch (Exception e) { - LOG.error(e); // should never happen - } + myTaskExecutor.submit(() -> { + try { + taskCallable.call(); + } + catch (Exception e) { + LOG.error(e); // should never happen } }); return null; diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java index 2e598581dfa4..533676c4ae1a 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java @@ -71,12 +71,9 @@ public class RemoteServerListConfigurable extends MasterDetailsComponent impleme @Override protected String getEmptySelectionString() { final String typeNames = StringUtil.join(ServerType.EP_NAME.getExtensions(), - new Function() { - @Override - public String fun(ServerType type) { - return type.getPresentableName(); - } - }, ", "); + type -> { + return type.getPresentableName(); + }, ", "); if (typeNames.length() > 0) { return CloudBundle.getText("clouds.configure.empty.selection.string", typeNames); @@ -128,12 +125,7 @@ public class RemoteServerListConfigurable extends MasterDetailsComponent impleme @Nullable @Override public Runnable enableSearch(final String option) { - return new Runnable() { - @Override - public void run() { - ObjectUtils.assertNotNull(SpeedSearchSupply.getSupply(myTree, true)).findAndSelectElement(option); - } - }; + return () -> ObjectUtils.assertNotNull(SpeedSearchSupply.getSupply(myTree, true)).findAndSelectElement(option); } @Override diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/SingleRemoteServerConfigurable.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/SingleRemoteServerConfigurable.java index 1ce2b43eac43..6031309cafd9 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/SingleRemoteServerConfigurable.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/SingleRemoteServerConfigurable.java @@ -242,13 +242,9 @@ public class SingleRemoteServerConfigurable extends NamedConfigurable { + if (myConnectionTester == ConnectionTester.this) { + setConnectionStatus(!connected, connected, connected ? "Connection successful" : "Cannot connect: " + connection.getStatusText()); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java index 80dba20e58ae..f1a0fa0ea957 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java @@ -93,12 +93,8 @@ public class DeployToServerSettingsEditor(new Comparator() { - @Override - public int compare(DeploymentSource o1, DeploymentSource o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }); + mySourceListModel = new SortedComboBoxModel( + (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName())); mySourceListModel.addAll(deploymentConfigurator.getAvailableDeploymentSources()); mySourceComboBox = new ComboBox(mySourceListModel); mySourceComboBox.setRenderer(new ListCellRendererWrapper() { diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java index 0a8ed6672f66..fb463f34d4fd 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java @@ -275,15 +275,12 @@ public class ServerConnectionImpl implements myEventDispatcher.queueDeploymentsChanged(this); DeploymentLogManagerImpl logManager = myLogManagers.get(deploymentName); final LoggingHandlerImpl loggingHandler = logManager == null ? null : logManager.getMainLoggingHandler(); - final Consumer logConsumer = new Consumer() { - @Override - public void consume(String message) { - if (loggingHandler == null) { - LOG.info(message); - } - else { - loggingHandler.printlnSystemMessage(message); - } + final Consumer logConsumer = message -> { + if (loggingHandler == null) { + LOG.info(message); + } + else { + loggingHandler.printlnSystemMessage(message); } }; @@ -435,15 +432,13 @@ public class ServerConnectionImpl implements @NotNull DeploymentRuntime runtime) { try { final D debugInfo = debugConnector.getConnectionData((R)runtime); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - try { - debugConnector.getLauncher().startDebugSession(debugInfo, myDeploymentTask.getExecutionEnvironment(), myServer); - } - catch (ExecutionException e) { - myLoggingHandler.print("Cannot start debugger: " + e.getMessage() + "\n"); - LOG.info(e); - } + ApplicationManager.getApplication().invokeLater(() -> { + try { + debugConnector.getLauncher().startDebugSession(debugInfo, myDeploymentTask.getExecutionEnvironment(), myServer); + } + catch (ExecutionException e) { + myLoggingHandler.print("Cannot start debugger: " + e.getMessage() + "\n"); + LOG.info(e); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerTaskExecutorImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerTaskExecutorImpl.java index 9421b4f5f87a..7afe28aa7b73 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerTaskExecutorImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerTaskExecutorImpl.java @@ -47,16 +47,13 @@ public class ServerTaskExecutorImpl implements ServerTaskExecutor { @Override public void submit(@NotNull final ThrowableRunnable command, @NotNull final RemoteOperationCallback callback) { - execute(new Runnable() { - @Override - public void run() { - try { - command.run(); - } - catch (Throwable e) { - LOG.info(e); - callback.errorOccurred(e.getMessage()); - } + execute(() -> { + try { + command.run(); + } + catch (Throwable e) { + LOG.info(e); + callback.errorOccurred(e.getMessage()); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/clientLibrary/ClientLibraryManagerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/clientLibrary/ClientLibraryManagerImpl.java index 72c31e5c3bfc..e42c9ba4eead 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/clientLibrary/ClientLibraryManagerImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/clientLibrary/ClientLibraryManagerImpl.java @@ -110,12 +110,7 @@ public class ClientLibraryManagerImpl extends ClientLibraryManager implements Pe public void checkConfiguration(@NotNull final ClientLibraryDescription description, final @Nullable Project project, final @Nullable JComponent component) throws RuntimeConfigurationError { if (!isDownloaded(description)) { - throw new RuntimeConfigurationError("Client libraries were not downloaded", new Runnable() { - @Override - public void run() { - download(description, project, component); - } - }); + throw new RuntimeConfigurationError("Client libraries were not downloaded", () -> download(description, project, component)); } } @@ -134,15 +129,12 @@ public class ClientLibraryManagerImpl extends ClientLibraryManager implements Pe public void download(@NotNull final ClientLibraryDescription libraryDescription, @Nullable Project project, @Nullable JComponent component) { final Ref exc = Ref.create(null); ProgressManager.getInstance().runProcessWithProgressSynchronously( - new Runnable() { - @Override - public void run() { - try { - download(libraryDescription); - } - catch (IOException e) { - exc.set(e); - } + () -> { + try { + download(libraryDescription); + } + catch (IOException e) { + exc.set(e); } }, "Downloading Client Libraries", false, project, component); if (exc.isNull()) { diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/deployment/DeploymentImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/deployment/DeploymentImpl.java index c12a69371263..9eb4b821a473 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/deployment/DeploymentImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/deployment/DeploymentImpl.java @@ -69,13 +69,7 @@ public class DeploymentImpl implements Deploy @Override public void setStatus(@NotNull final DeploymentStatus status, @Nullable final String statusText) { - myConnection.changeDeploymentState(new Runnable() { - - @Override - public void run() { - changeState(myState.getStatus(), status, statusText, getRuntime()); - } - }); + myConnection.changeDeploymentState(() -> changeState(myState.getStatus(), status, statusText, getRuntime())); } @NotNull diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java index efca1b899fc0..c6db114cb641 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/log/ConsoleTerminalHandlerImpl.java @@ -63,30 +63,26 @@ public class ConsoleTerminalHandlerImpl extends TerminalHandlerBase { Disposer.register(this, myLoggingHandler); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - - @Override - public void run() { - BufferedReader outputReader = new BufferedReader(new InputStreamReader(terminalOutput)); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + BufferedReader outputReader = new BufferedReader(new InputStreamReader(terminalOutput)); + try { + while (!isClosed()) { + String line = outputReader.readLine(); + if (line == null) { + break; + } + myLoggingHandler.print(line + "\n"); + } + } + catch (IOException e) { + LOG.debug(e); + } + finally { try { - while (!isClosed()) { - String line = outputReader.readLine(); - if (line == null) { - break; - } - myLoggingHandler.print(line + "\n"); - } + outputReader.close(); } - catch (IOException e) { - LOG.debug(e); - } - finally { - try { - outputReader.close(); - } - catch (IOException ignored) { + catch (IOException ignored) { - } } } }); diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/RemoteServersViewImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/RemoteServersViewImpl.java index ae6d2c91374a..e4bd3b0f7cd8 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/RemoteServersViewImpl.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/RemoteServersViewImpl.java @@ -23,13 +23,10 @@ public class RemoteServersViewImpl extends RemoteServersView { public void showServerConnection(@NotNull final ServerConnection connection) { final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(getToolWindowId(connection)); if (toolWindow != null) { - toolWindow.activate(new Runnable() { - @Override - public void run() { - ServersToolWindowContent content = getServersViewComponent(toolWindow); - if (content != null) { - content.select(connection); - } + toolWindow.activate(() -> { + ServersToolWindowContent content = getServersViewComponent(toolWindow); + if (content != null) { + content.select(connection); } }); } @@ -45,13 +42,10 @@ public class RemoteServersViewImpl extends RemoteServersView { ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); final ToolWindow toolWindow = toolWindowManager.getToolWindow(getToolWindowId(connection)); if (toolWindow != null) { - toolWindowManager.invokeLater(new Runnable() { - @Override - public void run() { - ServersToolWindowContent component = getServersViewComponent(toolWindow); - if (component != null) { - component.select(connection, deploymentName); - } + toolWindowManager.invokeLater(() -> { + ServersToolWindowContent component = getServersViewComponent(toolWindow); + if (component != null) { + component.select(connection, deploymentName); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java index 63566d069159..1dcd6904d75f 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowContent.java @@ -252,21 +252,11 @@ public class ServersToolWindowContent extends JPanel implements Disposable, Serv } private static void pollDeployments(final ServerConnection connection) { - connection.computeDeployments(new Runnable() { - - @Override - public void run() { - new Alarm().addRequest(new Runnable() { - - @Override - public void run() { - if (connection == ServerConnectionManager.getInstance().getConnection(connection.getServer())) { - pollDeployments(connection); - } - } - }, POLL_DEPLOYMENTS_DELAY, ModalityState.any()); + connection.computeDeployments(() -> new Alarm().addRequest(() -> { + if (connection == ServerConnectionManager.getInstance().getConnection(connection.getServer())) { + pollDeployments(connection); } - }); + }, POLL_DEPLOYMENTS_DELAY, ModalityState.any())); } private JComponent createToolbar() { @@ -319,28 +309,20 @@ public class ServersToolWindowContent extends JPanel implements Disposable, Serv } public void select(@NotNull final ServerConnection connection, @NotNull final String deploymentName) { - myBuilder.getUi().queueUpdate(connection).doWhenDone(new Runnable() { + myBuilder.getUi().queueUpdate(connection).doWhenDone(() -> myBuilder.select(ServersTreeStructure.DeploymentNodeImpl.class, new TreeVisitor() { @Override - public void run() { - myBuilder.select(ServersTreeStructure.DeploymentNodeImpl.class, new TreeVisitor() { - @Override - public boolean visit(@NotNull ServersTreeStructure.DeploymentNodeImpl node) { - return isDeploymentNodeMatch(node, connection, deploymentName); - } - }, null, false); + public boolean visit(@NotNull ServersTreeStructure.DeploymentNodeImpl node) { + return isDeploymentNodeMatch(node, connection, deploymentName); } - }); + }, null, false)); } public void select(@NotNull final ServerConnection connection, @NotNull final String deploymentName, @NotNull final String logName) { - myBuilder.getUi().queueUpdate(connection).doWhenDone(new Runnable() { - @Override - public void run() { - TreeNodeSelector nodeSelector = myContribution.createLogNodeSelector(connection, deploymentName, logName); - myBuilder.select(nodeSelector.getNodeClass(), nodeSelector, null, false); - } + myBuilder.getUi().queueUpdate(connection).doWhenDone(() -> { + TreeNodeSelector nodeSelector = myContribution.createLogNodeSelector(connection, deploymentName, logName); + myBuilder.select(nodeSelector.getNodeClass(), nodeSelector, null, false); }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowManager.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowManager.java index 1679d8bed5e7..86445372484c 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowManager.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/ServersToolWindowManager.java @@ -36,20 +36,11 @@ public abstract class ServersToolWindowManager extends AbstractProjectComponent } public void projectOpened() { - StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() { - public void run() { - setupListeners(); - } - }); + StartupManager.getInstance(myProject).registerPostStartupActivity(() -> setupListeners()); } public void setupListeners() { - getFactory().getContribution().setupAvailabilityListener(myProject, new Runnable() { - @Override - public void run() { - updateWindowAvailable(true); - } - }); + getFactory().getContribution().setupAvailabilityListener(myProject, () -> updateWindowAvailable(true)); myProject.getMessageBus().connect().subscribe(RemoteServerListener.TOPIC, new RemoteServerListener() { @Override public void serverAdded(@NotNull RemoteServer server) { @@ -66,29 +57,25 @@ public abstract class ServersToolWindowManager extends AbstractProjectComponent private void updateWindowAvailable(final boolean showIfAvailable) { final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); - toolWindowManager.invokeLater(new Runnable() { + toolWindowManager.invokeLater(() -> { + boolean available = getFactory().getContribution().canContribute(myProject); - @Override - public void run() { - boolean available = getFactory().getContribution().canContribute(myProject); + final ToolWindow toolWindow = toolWindowManager.getToolWindow(myWindowId); - final ToolWindow toolWindow = toolWindowManager.getToolWindow(myWindowId); - - if (toolWindow == null) { - if (available) { - createToolWindow(myProject, toolWindowManager).show(null); - } - return; + if (toolWindow == null) { + if (available) { + createToolWindow(myProject, toolWindowManager).show(null); } + return; + } - boolean doShow = !toolWindow.isAvailable() && available; - if (toolWindow.isAvailable() && !available) { - toolWindow.hide(null); - } - toolWindow.setAvailable(available, null); - if (showIfAvailable && doShow) { - toolWindow.show(null); - } + boolean doShow = !toolWindow.isAvailable() && available; + if (toolWindow.isAvailable() && !available) { + toolWindow.hide(null); + } + toolWindow.setAvailable(available, null); + if (showIfAvailable && doShow) { + toolWindow.show(null); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java index 807680d89bb8..d6ff7cd261a5 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ui/tree/ServersTreeStructure.java @@ -136,11 +136,8 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { public Collection getChildren() { List> result = new ArrayList>(); result.addAll(myContribution.createServerNodes(doGetProject())); - result.addAll(ContainerUtil.map(myContribution.getRemoteServers(), new Function, AbstractTreeNode>() { - @Override - public AbstractTreeNode fun(RemoteServer server) { - return new RemoteServerNode(server); - } + result.addAll(ContainerUtil.map(myContribution.getRemoteServers(), (Function, AbstractTreeNode>)server -> { + return new RemoteServerNode(server); })); return result; } @@ -237,15 +234,12 @@ public class ServersTreeStructure extends AbstractTreeStructureBase { @Override public PopupStep onChosen(final RunnerAndConfigurationSettings selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - if (selectedValue != null) { - ProgramRunnerUtil.executeConfiguration(doGetProject(), selectedValue, executor); - } - else { - configurationManager.createAndRunConfiguration(serverType, RemoteServerNode.this.getValue()); - } + return doFinalStep(() -> { + if (selectedValue != null) { + ProgramRunnerUtil.executeConfiguration(doGetProject(), selectedValue, executor); + } + else { + configurationManager.createAndRunConfiguration(serverType, RemoteServerNode.this.getValue()); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/ApplicationActionBase.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/ApplicationActionBase.java index 4e7a53ccfb21..fa9899816f94 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/ApplicationActionBase.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/ApplicationActionBase.java @@ -88,13 +88,7 @@ public abstract class ApplicationActionBase e return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - - @Override - public void run() { - myContent.select(connection, deployment.getName(), myLogName); - } - }); + ApplicationManager.getApplication().invokeLater(() -> myContent.select(connection, deployment.getName(), myLogName)); } private Deployment findDeployment(ServerConnection connection) { diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudAccountSelectionEditor.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudAccountSelectionEditor.java index 0bff85272189..f1df8b3613b5 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudAccountSelectionEditor.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudAccountSelectionEditor.java @@ -130,12 +130,7 @@ public class CloudAccountSelectionEditor { if (!new SingleConfigurableEditor(myMainPanel, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable), false) { { - errorConsumerRef.set(new Consumer() { - @Override - public void consume(String s) { - setErrorText(s); - } - }); + errorConsumerRef.set(s -> setErrorText(s)); } }.showAndGet()) { return; diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntime.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntime.java index 1bc9f8620253..12ada8fca33d 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntime.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntime.java @@ -75,35 +75,31 @@ public abstract class CloudApplicationRuntime extends DeploymentRuntime { protected abstract class LoggingTask { public void perform(final Project project, final Runnable onDone) { - getTaskExecutor().submit(new Runnable() { + getTaskExecutor().submit(() -> { + try { + getAgentTaskExecutor().execute(new Computable() { - @Override - public void run() { - try { - getAgentTaskExecutor().execute(new Computable() { + @Override + public Object compute() { + Deployment deployment = getDeploymentModel(); + CloudAgentLoggingHandler loggingHandler + = deployment == null + ? null + : new CloudLoggingHandlerImpl(deployment.getOrCreateLogManager(project)) { - @Override - public Object compute() { - Deployment deployment = getDeploymentModel(); - CloudAgentLoggingHandler loggingHandler - = deployment == null - ? null - : new CloudLoggingHandlerImpl(deployment.getOrCreateLogManager(project)) { - - @Override - public void println(String message) { - LOG.info(message); - } - }; - LoggingTask.this.run(loggingHandler); - return null; - } - }); - onDone.run(); - } - catch (ServerRuntimeException e) { - getCloudNotifier().showMessage(e.getMessage(), MessageType.ERROR); - } + @Override + public void println(String message) { + LOG.info(message); + } + }; + LoggingTask.this.run(loggingHandler); + return null; + } + }); + onDone.run(); + } + catch (ServerRuntimeException e) { + getCloudNotifier().showMessage(e.getMessage(), MessageType.ERROR); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntimeBase.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntimeBase.java index e35ed0848065..7d8a62e03854 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntimeBase.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudApplicationRuntimeBase.java @@ -33,23 +33,17 @@ public abstract class CloudApplicationRuntimeBase extends CloudApplicationRuntim @Override public void undeploy(@NotNull final UndeploymentTaskCallback callback) { - myTaskExecutor.submit(new ThrowableRunnable() { + myTaskExecutor.submit(() -> getApplication().undeploy(new CloudAgentDeploymentCallback() { + @Override + public void succeeded() { + callback.succeeded(); + } @Override - public void run() throws Exception { - getApplication().undeploy(new CloudAgentDeploymentCallback() { - @Override - public void succeeded() { - callback.succeeded(); - } - - @Override - public void errorOccurred(String errorMessage) { - callback.errorOccurred(errorMessage); - } - }); + public void errorOccurred(String errorMessage) { + callback.errorOccurred(errorMessage); } - }, callback); + }), callback); } protected ServerTaskExecutor getTaskExecutor() { diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudConnectionTask.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudConnectionTask.java index 82492e130f0e..4bb2b416228e 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudConnectionTask.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudConnectionTask.java @@ -68,13 +68,7 @@ public abstract class CloudConnectionTask< run((SR)serverRuntimeInstance, semaphore, result); } finally { - ApplicationManager.getApplication().invokeLater(new Runnable() { - - @Override - public void run() { - connection.disconnect(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> connection.disconnect()); } } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudGitApplicationRuntime.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudGitApplicationRuntime.java index 5157d5bd8b5a..8c69f8e23baf 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudGitApplicationRuntime.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudGitApplicationRuntime.java @@ -79,22 +79,18 @@ public class CloudGitApplicationRuntime extends CloudApplicationRuntime { @Override public void undeploy(final @NotNull UndeploymentTaskCallback callback) { - getTaskExecutor().submit(new ThrowableRunnable() { - - @Override - public void run() throws Exception { - try { - if (!confirmUndeploy()) { - throw new ServerRuntimeException("Undeploy cancelled"); - } - - undeploy(); - - callback.succeeded(); - } - catch (ServerRuntimeException e) { - callback.errorOccurred(e.getMessage()); + getTaskExecutor().submit(() -> { + try { + if (!confirmUndeploy()) { + throw new ServerRuntimeException("Undeploy cancelled"); } + + undeploy(); + + callback.succeeded(); + } + catch (ServerRuntimeException e) { + callback.errorOccurred(e.getMessage()); } }, callback); } @@ -113,22 +109,18 @@ public class CloudGitApplicationRuntime extends CloudApplicationRuntime { private boolean confirmUndeploy() { final Ref confirmed = new Ref(false); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - - @Override - public void run() { - String title = CloudBundle.getText("cloud.undeploy.confirm.title"); - while (true) { - String password = Messages.showPasswordDialog(CloudBundle.getText("cloud.undeploy.confirm.message", getApplicationName()), title); - if (password == null) { - return; - } - if (password.equals(getServerRuntime().getConfiguration().getPassword())) { - confirmed.set(true); - return; - } - Messages.showErrorDialog(CloudBundle.getText("cloud.undeploy.confirm.password.incorrect"), title); + ApplicationManager.getApplication().invokeAndWait(() -> { + String title = CloudBundle.getText("cloud.undeploy.confirm.title"); + while (true) { + String password = Messages.showPasswordDialog(CloudBundle.getText("cloud.undeploy.confirm.message", getApplicationName()), title); + if (password == null) { + return; } + if (password.equals(getServerRuntime().getConfiguration().getPassword())) { + confirmed.set(true); + return; + } + Messages.showErrorDialog(CloudBundle.getText("cloud.undeploy.confirm.password.incorrect"), title); } }, ModalityState.defaultModalityState()); return confirmed.get(); diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudMultiSourceServerRuntimeInstance.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudMultiSourceServerRuntimeInstance.java index 2f6663698f2e..7785588e5b2e 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudMultiSourceServerRuntimeInstance.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudMultiSourceServerRuntimeInstance.java @@ -108,24 +108,12 @@ public abstract class CloudMultiSourceServerRuntimeInstance< public void deploy(@NotNull final DeploymentTask task, @NotNull final DeploymentLogManager logManager, @NotNull final ServerRuntimeInstance.DeploymentOperationCallback callback) { - getTaskExecutor().submit(new ThrowableRunnable() { - - @Override - public void run() throws Exception { - createDeploymentRuntime(task, logManager).deploy(callback); - } - }, callback); + getTaskExecutor().submit(() -> createDeploymentRuntime(task, logManager).deploy(callback), callback); } @Override public void disconnect() { - getTaskExecutor().submit(new Runnable() { - - @Override - public void run() { - getAgent().disconnect(); - } - }); + getTaskExecutor().submit(() -> getAgent().disconnect()); } public CloudDeploymentRuntime createDeploymentRuntime(final DeployToServerRunConfiguration runConfiguration) diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudRuntimeTask.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudRuntimeTask.java index c8109dce3d29..7f1bcab332b3 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudRuntimeTask.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudRuntimeTask.java @@ -75,13 +75,9 @@ public abstract class CloudRuntimeTask< while (!indicator.isCanceled()) { if (semaphore.waitFor(500)) { if (mySuccess.get()) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - - @Override - public void run() { - if (disposable == null || !Disposer.isDisposed(disposable)) { - postPerform(result.get()); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (disposable == null || !Disposer.isDisposed(disposable)) { + postPerform(result.get()); } }); } @@ -144,20 +140,16 @@ public abstract class CloudRuntimeTask< } protected void run(final SR serverRuntime, final Semaphore semaphore, final AtomicReference result) { - serverRuntime.getTaskExecutor().submit(new Runnable() { - - @Override - public void run() { - try { - result.set(CloudRuntimeTask.this.run(serverRuntime)); - mySuccess.set(true); - } - catch (ServerRuntimeException e) { - runtimeErrorOccurred(e.getMessage()); - } - finally { - semaphore.up(); - } + serverRuntime.getTaskExecutor().submit(() -> { + try { + result.set(CloudRuntimeTask.this.run(serverRuntime)); + mySuccess.set(true); + } + catch (ServerRuntimeException e) { + runtimeErrorOccurred(e.getMessage()); + } + finally { + semaphore.up(); } }); } diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudServerRuntimeInstance.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudServerRuntimeInstance.java index 1472e08106e6..987be8ad6171 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudServerRuntimeInstance.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/CloudServerRuntimeInstance.java @@ -90,24 +90,20 @@ public abstract class CloudServerRuntimeInstance @Override public void computeDeployments(@NotNull final ComputeDeploymentsCallback callback) { - getTaskExecutor().submit(new ThrowableRunnable() { - - @Override - public void run() throws Exception { - try { - for (CloudApplicationRuntime application : getApplications()) { - Deployment deployment - = callback.addDeployment(application.getApplicationName(), - application, - application.getStatus(), - application.getStatusText()); - application.setDeploymentModel(deployment); - } - callback.succeeded(); - } - catch (ServerRuntimeException e) { - callback.errorOccurred(e.getMessage()); + getTaskExecutor().submit(() -> { + try { + for (CloudApplicationRuntime application : getApplications()) { + Deployment deployment + = callback.addDeployment(application.getApplicationName(), + application, + application.getStatus(), + application.getStatusText()); + application.setDeploymentModel(deployment); } + callback.succeeded(); + } + catch (ServerRuntimeException e) { + callback.errorOccurred(e.getMessage()); } }, callback); } @@ -121,11 +117,8 @@ public abstract class CloudServerRuntimeInstance if (applications == null) { return Collections.emptyList(); } - return ContainerUtil.map(applications, new Function() { - @Override - public CloudApplicationRuntime fun(CloudRemoteApplication application) { - return createApplicationRuntime(application); - } + return ContainerUtil.map(applications, application -> { + return createApplicationRuntime(application); }); } }); diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DelayedRunner.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DelayedRunner.java index 8ece5b9b3551..56fee900821c 100644 --- a/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DelayedRunner.java +++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/util/DelayedRunner.java @@ -41,13 +41,9 @@ public abstract class DelayedRunner implements Disposable { if (myAlarm.isDisposed()) { return; } - myAlarm.addRequest(new Runnable() { - - @Override - public void run() { - checkChanges(); - queueChangesCheck(); - } + myAlarm.addRequest(() -> { + checkChanges(); + queueChangesCheck(); }, CHANGES_CHECK_TIME, ModalityState.any()); } diff --git a/platform/script-debugger/debugger-ui/testSrc/org/jetbrains/debugger/TestValueNode.java b/platform/script-debugger/debugger-ui/testSrc/org/jetbrains/debugger/TestValueNode.java index 5b6885ebac4e..086297a87c45 100644 --- a/platform/script-debugger/debugger-ui/testSrc/org/jetbrains/debugger/TestValueNode.java +++ b/platform/script-debugger/debugger-ui/testSrc/org/jetbrains/debugger/TestValueNode.java @@ -28,12 +28,7 @@ public class TestValueNode extends XTestValueNode { TestCompositeNode childrenNode = new TestCompositeNode(); value.computeChildren(childrenNode); return childrenNode.loadContent(Conditions.alwaysFalse(), Conditions.alwaysFalse()) - .done(new Consumer() { - @Override - public void consume(Content content) { - children = content; - } - }); + .done(content -> children = content); } @Nullable diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java index 2646cceaa08d..44f234d8a5cc 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java @@ -55,51 +55,43 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP } public void onStartTesting() { - addToInvokeLater(new Runnable() { - public void run() { - myTestsRootNode.setState(State.RUNNING, GeneralIdBasedToSMTRunnerEventsConvertor.this); - myTestsRootProxy.setStarted(); - fireOnTestingStarted(myTestsRootProxy); - } + addToInvokeLater(() -> { + myTestsRootNode.setState(State.RUNNING, GeneralIdBasedToSMTRunnerEventsConvertor.this); + myTestsRootProxy.setStarted(); + fireOnTestingStarted(myTestsRootProxy); }); } @Override public void onTestsReporterAttached() { - addToInvokeLater(new Runnable() { - public void run() { - fireOnTestsReporterAttached(myTestsRootProxy); - } - }); + addToInvokeLater(() -> fireOnTestsReporterAttached(myTestsRootProxy)); } public void onFinishTesting() { - addToInvokeLater(new Runnable() { - public void run() { - if (myIsTestingFinished) { - // has been already invoked! - return; - } - myIsTestingFinished = true; - - // We don't know whether process was destroyed by user - // or it finished after all tests have been run - // Lets assume, if at finish all nodes except root suite have final state (passed, failed or ignored), - // then all is ok otherwise process was terminated by user - boolean completeTree = isTreeComplete(myRunningTestNodes, myTestsRootProxy); - if (completeTree) { - myTestsRootProxy.setFinished(); - } else { - myTestsRootProxy.setTerminated(); - } - if (!myRunningTestNodes.isEmpty()) { - logProblem("Unexpected running nodes: " + myRunningTestNodes); - } - myNodeByIdMap.clear(); - myRunningTestNodes.clear(); - - fireOnTestingFinished(myTestsRootProxy); + addToInvokeLater(() -> { + if (myIsTestingFinished) { + // has been already invoked! + return; } + myIsTestingFinished = true; + + // We don't know whether process was destroyed by user + // or it finished after all tests have been run + // Lets assume, if at finish all nodes except root suite have final state (passed, failed or ignored), + // then all is ok otherwise process was terminated by user + boolean completeTree = isTreeComplete(myRunningTestNodes, myTestsRootProxy); + if (completeTree) { + myTestsRootProxy.setFinished(); + } else { + myTestsRootProxy.setTerminated(); + } + if (!myRunningTestNodes.isEmpty()) { + logProblem("Unexpected running nodes: " + myRunningTestNodes); + } + myNodeByIdMap.clear(); + myRunningTestNodes.clear(); + + fireOnTestingFinished(myTestsRootProxy); }); stopEventProcessing(); } @@ -110,19 +102,11 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP } public void onTestStarted(@NotNull final TestStartedEvent testStartedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - doStartNode(testStartedEvent, false); - } - }); + addToInvokeLater(() -> doStartNode(testStartedEvent, false)); } public void onSuiteStarted(@NotNull final TestSuiteStartedEvent suiteStartedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - doStartNode(suiteStartedEvent, true); - } - }); + addToInvokeLater(() -> doStartNode(suiteStartedEvent, true)); } private void doStartNode(@NotNull BaseStartedNodeEvent startedNodeEvent, boolean suite) { @@ -187,31 +171,27 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP } public void onTestFinished(@NotNull final TestFinishedEvent testFinishedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - Node node = findNodeToTerminate(testFinishedEvent); - if (node != null) { - SMTestProxy testProxy = node.getProxy(); - testProxy.setDuration(testFinishedEvent.getDuration()); - testProxy.setFrameworkOutputFile(testFinishedEvent.getOutputFile()); - testProxy.setFinished(); - fireOnTestFinished(testProxy); - terminateNode(node, State.FINISHED); - } + addToInvokeLater(() -> { + Node node = findNodeToTerminate(testFinishedEvent); + if (node != null) { + SMTestProxy testProxy = node.getProxy(); + testProxy.setDuration(testFinishedEvent.getDuration()); + testProxy.setFrameworkOutputFile(testFinishedEvent.getOutputFile()); + testProxy.setFinished(); + fireOnTestFinished(testProxy); + terminateNode(node, State.FINISHED); } }); } public void onSuiteFinished(@NotNull final TestSuiteFinishedEvent suiteFinishedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - Node node = findNodeToTerminate(suiteFinishedEvent); - if (node != null) { - SMTestProxy suiteProxy = node.getProxy(); - suiteProxy.setFinished(); - fireOnSuiteFinished(suiteProxy); - terminateNode(node, State.FINISHED); - } + addToInvokeLater(() -> { + Node node = findNodeToTerminate(suiteFinishedEvent); + if (node != null) { + SMTestProxy suiteProxy = node.getProxy(); + suiteProxy.setFinished(); + fireOnSuiteFinished(suiteProxy); + terminateNode(node, State.FINISHED); } }); } @@ -227,17 +207,15 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP } public void onUncapturedOutput(@NotNull final String text, final Key outputType) { - addToInvokeLater(new Runnable() { - public void run() { - Node activeNode = findActiveNode(); - SMTestProxy activeProxy = activeNode.getProxy(); - if (ProcessOutputTypes.STDERR.equals(outputType)) { - activeProxy.addStdErr(text); - } else if (ProcessOutputTypes.SYSTEM.equals(outputType)) { - activeProxy.addSystemOutput(text); - } else { - activeProxy.addStdOutput(text, outputType); - } + addToInvokeLater(() -> { + Node activeNode = findActiveNode(); + SMTestProxy activeProxy = activeNode.getProxy(); + if (ProcessOutputTypes.STDERR.equals(outputType)) { + activeProxy.addStdErr(text); + } else if (ProcessOutputTypes.SYSTEM.equals(outputType)) { + activeProxy.addSystemOutput(text); + } else { + activeProxy.addStdOutput(text, outputType); } }); } @@ -245,96 +223,84 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP public void onError(@NotNull final String localizedMessage, @Nullable final String stackTrace, final boolean isCritical) { - addToInvokeLater(new Runnable() { - public void run() { - Node activeNode = findActiveNode(); - SMTestProxy activeProxy = activeNode.getProxy(); - activeProxy.addError(localizedMessage, stackTrace, isCritical); - } + addToInvokeLater(() -> { + Node activeNode = findActiveNode(); + SMTestProxy activeProxy = activeNode.getProxy(); + activeProxy.addError(localizedMessage, stackTrace, isCritical); }); } public void onTestFailure(@NotNull final TestFailedEvent testFailedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - Node node = findNodeToTerminate(testFailedEvent); - if (node == null) { - return; - } - - SMTestProxy testProxy = node.getProxy(); - - String comparisonFailureActualText = testFailedEvent.getComparisonFailureActualText(); - String comparisonFailureExpectedText = testFailedEvent.getComparisonFailureExpectedText(); - String failureMessage = testFailedEvent.getLocalizedFailureMessage(); - String stackTrace = testFailedEvent.getStacktrace(); - if (comparisonFailureActualText != null && comparisonFailureExpectedText != null) { - testProxy.setTestComparisonFailed(failureMessage, stackTrace, - comparisonFailureActualText, comparisonFailureExpectedText, - testFailedEvent.getExpectedFilePath(), - testFailedEvent.getActualFilePath()); - } else if (comparisonFailureActualText == null && comparisonFailureExpectedText == null) { - testProxy.setTestFailed(failureMessage, stackTrace, testFailedEvent.isTestError()); - } else { - logProblem("Comparison failure actual and expected texts should be both null or not null.\n" - + "Expected:\n" - + comparisonFailureExpectedText + "\n" - + "Actual:\n" - + comparisonFailureActualText); - } - long duration = testFailedEvent.getDurationMillis(); - if (duration >= 0) { - testProxy.setDuration(duration); - } - - // fire event - fireOnTestFailed(testProxy); - - terminateNode(node, State.FAILED); + addToInvokeLater(() -> { + Node node = findNodeToTerminate(testFailedEvent); + if (node == null) { + return; } + + SMTestProxy testProxy = node.getProxy(); + + String comparisonFailureActualText = testFailedEvent.getComparisonFailureActualText(); + String comparisonFailureExpectedText = testFailedEvent.getComparisonFailureExpectedText(); + String failureMessage = testFailedEvent.getLocalizedFailureMessage(); + String stackTrace = testFailedEvent.getStacktrace(); + if (comparisonFailureActualText != null && comparisonFailureExpectedText != null) { + testProxy.setTestComparisonFailed(failureMessage, stackTrace, + comparisonFailureActualText, comparisonFailureExpectedText, + testFailedEvent.getExpectedFilePath(), + testFailedEvent.getActualFilePath()); + } else if (comparisonFailureActualText == null && comparisonFailureExpectedText == null) { + testProxy.setTestFailed(failureMessage, stackTrace, testFailedEvent.isTestError()); + } else { + logProblem("Comparison failure actual and expected texts should be both null or not null.\n" + + "Expected:\n" + + comparisonFailureExpectedText + "\n" + + "Actual:\n" + + comparisonFailureActualText); + } + long duration = testFailedEvent.getDurationMillis(); + if (duration >= 0) { + testProxy.setDuration(duration); + } + + // fire event + fireOnTestFailed(testProxy); + + terminateNode(node, State.FAILED); }); } public void onTestIgnored(@NotNull final TestIgnoredEvent testIgnoredEvent) { - addToInvokeLater(new Runnable() { - public void run() { - Node node = findNodeToTerminate(testIgnoredEvent); - if (node != null) { - SMTestProxy testProxy = node.getProxy(); - testProxy.setTestIgnored(testIgnoredEvent.getIgnoreComment(), testIgnoredEvent.getStacktrace()); - // fire event - fireOnTestIgnored(testProxy); - terminateNode(node, State.IGNORED); - } + addToInvokeLater(() -> { + Node node = findNodeToTerminate(testIgnoredEvent); + if (node != null) { + SMTestProxy testProxy = node.getProxy(); + testProxy.setTestIgnored(testIgnoredEvent.getIgnoreComment(), testIgnoredEvent.getStacktrace()); + // fire event + fireOnTestIgnored(testProxy); + terminateNode(node, State.IGNORED); } }); } public void onTestOutput(@NotNull final TestOutputEvent testOutputEvent) { - addToInvokeLater(new Runnable() { - public void run() { - Node node = findNode(testOutputEvent); - if (node == null) { - logProblem("Test wasn't started! But " + testOutputEvent + "!"); - return; - } - SMTestProxy testProxy = node.getProxy(); + addToInvokeLater(() -> { + Node node = findNode(testOutputEvent); + if (node == null) { + logProblem("Test wasn't started! But " + testOutputEvent + "!"); + return; + } + SMTestProxy testProxy = node.getProxy(); - if (testOutputEvent.isStdOut()) { - testProxy.addStdOutput(testOutputEvent.getText(), ProcessOutputTypes.STDOUT); - } else { - testProxy.addStdErr(testOutputEvent.getText()); - } + if (testOutputEvent.isStdOut()) { + testProxy.addStdOutput(testOutputEvent.getText(), ProcessOutputTypes.STDOUT); + } else { + testProxy.addStdErr(testOutputEvent.getText()); } }); } public void onTestsCountInSuite(final int count) { - addToInvokeLater(new Runnable() { - public void run() { - fireOnTestsCountInSuite(count); - } - }); + addToInvokeLater(() -> fireOnTestsCountInSuite(count)); } private boolean validateNodeId(@NotNull TreeNodeEvent treeNodeEvent) { @@ -365,19 +331,17 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP */ public void dispose() { super.dispose(); - addToInvokeLater(new Runnable() { - public void run() { - disconnectListeners(); + addToInvokeLater(() -> { + disconnectListeners(); - if (!myRunningTestNodes.isEmpty()) { - Application application = ApplicationManager.getApplication(); - if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { - logProblem("Not all events were processed!"); - } + if (!myRunningTestNodes.isEmpty()) { + Application application = ApplicationManager.getApplication(); + if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { + logProblem("Not all events were processed!"); } - myRunningTestNodes.clear(); - myNodeByIdMap.clear(); } + myRunningTestNodes.clear(); + myNodeByIdMap.clear(); }); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java index d379acc356e7..a6c4d92deaa8 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java @@ -54,12 +54,9 @@ public abstract class GeneralTestEventsProcessor implements Disposable { myProject = project; myEventPublisher = project.getMessageBus().syncPublisher(SMTRunnerEventsListener.TEST_STATUS); myTestFrameworkName = testFrameworkName; - myTransferToEDTQueue = new TransferToEDTQueue("SM queue", new Processor() { - @Override - public boolean process(Runnable runnable) { - runnable.run(); - return true; - } + myTransferToEDTQueue = new TransferToEDTQueue("SM queue", runnable -> { + runnable.run(); + return true; }, project.getDisposed(), 300); } // tree construction events @@ -166,45 +163,37 @@ public abstract class GeneralTestEventsProcessor implements Disposable { */ public void onCustomProgressTestsCategory(@Nullable final String categoryName, final int testCount) { - addToInvokeLater(new Runnable() { - public void run() { - myEventPublisher.onCustomProgressTestsCategory(categoryName, testCount); - for (SMTRunnerEventsListener adapter : myListenerAdapters) { - adapter.onCustomProgressTestsCategory(categoryName, testCount); - } + addToInvokeLater(() -> { + myEventPublisher.onCustomProgressTestsCategory(categoryName, testCount); + for (SMTRunnerEventsListener adapter : myListenerAdapters) { + adapter.onCustomProgressTestsCategory(categoryName, testCount); } }); } public void onCustomProgressTestStarted() { - addToInvokeLater(new Runnable() { - public void run() { - myEventPublisher.onCustomProgressTestStarted(); - for (SMTRunnerEventsListener adapter : myListenerAdapters) { - adapter.onCustomProgressTestStarted(); - } + addToInvokeLater(() -> { + myEventPublisher.onCustomProgressTestStarted(); + for (SMTRunnerEventsListener adapter : myListenerAdapters) { + adapter.onCustomProgressTestStarted(); } }); } public void onCustomProgressTestFinished() { - addToInvokeLater(new Runnable() { - public void run() { - myEventPublisher.onCustomProgressTestFinished(); - for (SMTRunnerEventsListener adapter : myListenerAdapters) { - adapter.onCustomProgressTestFinished(); - } + addToInvokeLater(() -> { + myEventPublisher.onCustomProgressTestFinished(); + for (SMTRunnerEventsListener adapter : myListenerAdapters) { + adapter.onCustomProgressTestFinished(); } }); } public void onCustomProgressTestFailed() { - addToInvokeLater(new Runnable() { - public void run() { - myEventPublisher.onCustomProgressTestFailed(); - for (SMTRunnerEventsListener adapter : myListenerAdapters) { - adapter.onCustomProgressTestFailed(); - } + addToInvokeLater(() -> { + myEventPublisher.onCustomProgressTestFailed(); + for (SMTRunnerEventsListener adapter : myListenerAdapters) { + adapter.onCustomProgressTestFailed(); } }); } @@ -255,12 +244,7 @@ public abstract class GeneralTestEventsProcessor implements Disposable { } public void stopEventProcessing() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myTransferToEDTQueue.drain(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myTransferToEDTQueue.drain()); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java index d254e3679704..7b8e338a4309 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java @@ -60,65 +60,54 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso } public void onStartTesting() { - addToInvokeLater(new Runnable() { - public void run() { - mySuitesStack.pushSuite(myTestsRootNode); - myTestsRootNode.setStarted(); + addToInvokeLater(() -> { + mySuitesStack.pushSuite(myTestsRootNode); + myTestsRootNode.setStarted(); - //fire - fireOnTestingStarted(myTestsRootNode); - } + //fire + fireOnTestingStarted(myTestsRootNode); }); } @Override public void onTestsReporterAttached() { - addToInvokeLater(new Runnable() { - public void run() { - fireOnTestsReporterAttached(myTestsRootNode); - } - }); + addToInvokeLater(() -> fireOnTestsReporterAttached(myTestsRootNode)); } public void onFinishTesting() { - addToInvokeLater(new Runnable() { - public void run() { - if (myIsTestingFinished) { - // has been already invoked! - return; - } - myIsTestingFinished = true; - - // We don't know whether process was destroyed by user - // or it finished after all tests have been run - // Lets assume, if at finish all suites except root suite are passed - // then all is ok otherwise process was terminated by user - if (!isTreeComplete(myRunningTestsFullNameToProxy.keySet(), myTestsRootNode)) { - myTestsRootNode.setTerminated(); - myRunningTestsFullNameToProxy.clear(); - } - mySuitesStack.clear(); - myTestsRootNode.setFinished(); - - - //fire events - fireOnTestingFinished(myTestsRootNode); + addToInvokeLater(() -> { + if (myIsTestingFinished) { + // has been already invoked! + return; } + myIsTestingFinished = true; + + // We don't know whether process was destroyed by user + // or it finished after all tests have been run + // Lets assume, if at finish all suites except root suite are passed + // then all is ok otherwise process was terminated by user + if (!isTreeComplete(myRunningTestsFullNameToProxy.keySet(), myTestsRootNode)) { + myTestsRootNode.setTerminated(); + myRunningTestsFullNameToProxy.clear(); + } + mySuitesStack.clear(); + myTestsRootNode.setFinished(); + + + //fire events + fireOnTestingFinished(myTestsRootNode); }); stopEventProcessing(); } @Override public void onRootPresentationAdded(final String rootName, final String comment, final String rootLocation) { - addToInvokeLater(new Runnable() { - @Override - public void run() { - myTestsRootNode.setPresentation(rootName); - myTestsRootNode.setComment(comment); - myTestsRootNode.setRootLocationUrl(rootLocation); - if (myLocator != null) { - myTestsRootNode.setLocator(myLocator); - } + addToInvokeLater(() -> { + myTestsRootNode.setPresentation(rootName); + myTestsRootNode.setComment(comment); + myTestsRootNode.setRootLocationUrl(rootLocation); + if (myLocator != null) { + myTestsRootNode.setLocator(myLocator); } }); } @@ -128,18 +117,15 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso @Override public void onSuiteTreeNodeAdded(final String testName, final String locationHint) { myTreeBuildBeforeStart = true; - myBuildTreeRunnables.add(new Runnable() { - @Override - public void run() { - final SMTestProxy testProxy = new SMTestProxy(testName, false, locationHint); - if (myLocator != null) { - testProxy.setLocator(myLocator); - } - getCurrentSuite().addChild(testProxy); - myEventPublisher.onSuiteTreeNodeAdded(testProxy); - for (SMTRunnerEventsListener adapter : myListenerAdapters) { - adapter.onSuiteTreeNodeAdded(testProxy); - } + myBuildTreeRunnables.add(() -> { + final SMTestProxy testProxy = new SMTestProxy(testName, false, locationHint); + if (myLocator != null) { + testProxy.setLocator(myLocator); + } + getCurrentSuite().addChild(testProxy); + myEventPublisher.onSuiteTreeNodeAdded(testProxy); + for (SMTRunnerEventsListener adapter : myListenerAdapters) { + adapter.onSuiteTreeNodeAdded(testProxy); } }); } @@ -147,34 +133,26 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso @Override public void onSuiteTreeStarted(final String suiteName, final String locationHint) { myTreeBuildBeforeStart = true; - myBuildTreeRunnables.add(new Runnable() { - @Override - public void run() { - final SMTestProxy parentSuite = getCurrentSuite(); - final SMTestProxy newSuite = new SMTestProxy(suiteName, true, locationHint); - if (myLocator != null) { - newSuite.setLocator(myLocator); - } - parentSuite.addChild(newSuite); + myBuildTreeRunnables.add(() -> { + final SMTestProxy parentSuite = getCurrentSuite(); + final SMTestProxy newSuite = new SMTestProxy(suiteName, true, locationHint); + if (myLocator != null) { + newSuite.setLocator(myLocator); + } + parentSuite.addChild(newSuite); - mySuitesStack.pushSuite(newSuite); + mySuitesStack.pushSuite(newSuite); - myEventPublisher.onSuiteTreeStarted(newSuite); - for (SMTRunnerEventsListener adapter : myListenerAdapters) { - adapter.onSuiteTreeStarted(newSuite); - } + myEventPublisher.onSuiteTreeStarted(newSuite); + for (SMTRunnerEventsListener adapter : myListenerAdapters) { + adapter.onSuiteTreeStarted(newSuite); } }); } @Override public void onSuiteTreeEnded(final String suiteName) { - myBuildTreeRunnables.add(new Runnable() { - @Override - public void run() { - mySuitesStack.popSuite(suiteName); - } - }); + myBuildTreeRunnables.add(() -> mySuitesStack.popSuite(suiteName)); if (myBuildTreeRunnables.size() > 100) { final ArrayList runnables = new ArrayList(myBuildTreeRunnables); @@ -189,14 +167,11 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso } private void processTreeBuildEvents(final List runnables) { - addToInvokeLater(new Runnable() { - @Override - public void run() { - for (Runnable runnable : runnables) { - runnable.run(); - } - runnables.clear(); + addToInvokeLater(() -> { + for (Runnable runnable : runnables) { + runnable.run(); } + runnables.clear(); }); } @@ -205,86 +180,82 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso } public void onTestStarted(@NotNull final TestStartedEvent testStartedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String testName = testStartedEvent.getName(); - final String locationUrl = testStartedEvent.getLocationUrl(); - final boolean isConfig = testStartedEvent.isConfig(); - final String fullName = getFullTestName(testName); + addToInvokeLater(() -> { + final String testName = testStartedEvent.getName(); + final String locationUrl = testStartedEvent.getLocationUrl(); + final boolean isConfig = testStartedEvent.isConfig(); + final String fullName = getFullTestName(testName); - if (myRunningTestsFullNameToProxy.containsKey(fullName)) { - //Duplicated event - logProblem("Test [" + fullName + "] has been already started"); - if (SMTestRunnerConnectionUtil.isInDebugMode()) { - return; - } + if (myRunningTestsFullNameToProxy.containsKey(fullName)) { + //Duplicated event + logProblem("Test [" + fullName + "] has been already started"); + if (SMTestRunnerConnectionUtil.isInDebugMode()) { + return; } - - SMTestProxy parentSuite = getCurrentSuite(); - SMTestProxy testProxy = locationUrl != null ? findChildByLocation(parentSuite, locationUrl) - : findChildByName(parentSuite, fullName); - if (testProxy == null) { - // creates test - testProxy = new SMTestProxy(testName, false, locationUrl); - testProxy.setConfig(isConfig); - - if (myLocator != null) { - testProxy.setLocator(myLocator); - } - - parentSuite.addChild(testProxy); - - if (myTreeBuildBeforeStart && myGetChildren) { - for (SMTestProxy proxy : parentSuite.getChildren()) { - if (!proxy.isFinal()) { - myCurrentChildren.add(proxy); - } - } - myGetChildren = false; - } - } - - // adds to running tests map - myRunningTestsFullNameToProxy.put(fullName, testProxy); - - //Progress started - testProxy.setStarted(); - - //fire events - fireOnTestStarted(testProxy); } + + SMTestProxy parentSuite = getCurrentSuite(); + SMTestProxy testProxy = locationUrl != null ? findChildByLocation(parentSuite, locationUrl) + : findChildByName(parentSuite, fullName); + if (testProxy == null) { + // creates test + testProxy = new SMTestProxy(testName, false, locationUrl); + testProxy.setConfig(isConfig); + + if (myLocator != null) { + testProxy.setLocator(myLocator); + } + + parentSuite.addChild(testProxy); + + if (myTreeBuildBeforeStart && myGetChildren) { + for (SMTestProxy proxy : parentSuite.getChildren()) { + if (!proxy.isFinal()) { + myCurrentChildren.add(proxy); + } + } + myGetChildren = false; + } + } + + // adds to running tests map + myRunningTestsFullNameToProxy.put(fullName, testProxy); + + //Progress started + testProxy.setStarted(); + + //fire events + fireOnTestStarted(testProxy); }); } public void onSuiteStarted(@NotNull final TestSuiteStartedEvent suiteStartedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String suiteName = suiteStartedEvent.getName(); - final String locationUrl = suiteStartedEvent.getLocationUrl(); + addToInvokeLater(() -> { + final String suiteName = suiteStartedEvent.getName(); + final String locationUrl = suiteStartedEvent.getLocationUrl(); - SMTestProxy parentSuite = getCurrentSuite(); - SMTestProxy newSuite = locationUrl != null ? findChildByLocation(parentSuite, locationUrl) - : findChildByName(parentSuite, suiteName); - if (newSuite == null) { - //new suite - newSuite = new SMTestProxy(suiteName, true, locationUrl, parentSuite.isPreservePresentableName()); + SMTestProxy parentSuite = getCurrentSuite(); + SMTestProxy newSuite = locationUrl != null ? findChildByLocation(parentSuite, locationUrl) + : findChildByName(parentSuite, suiteName); + if (newSuite == null) { + //new suite + newSuite = new SMTestProxy(suiteName, true, locationUrl, parentSuite.isPreservePresentableName()); - if (myLocator != null) { - newSuite.setLocator(myLocator); - } - - parentSuite.addChild(newSuite); + if (myLocator != null) { + newSuite.setLocator(myLocator); } - myGetChildren = true; - mySuitesStack.pushSuite(newSuite); - - //Progress started - newSuite.setSuiteStarted(); - - //fire event - fireOnSuiteStarted(newSuite); + parentSuite.addChild(newSuite); } + + myGetChildren = true; + mySuitesStack.pushSuite(newSuite); + + //Progress started + newSuite.setSuiteStarted(); + + //fire event + fireOnSuiteStarted(newSuite); }); } @@ -309,60 +280,54 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso } public void onTestFinished(@NotNull final TestFinishedEvent testFinishedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String testName = testFinishedEvent.getName(); - final long duration = testFinishedEvent.getDuration(); - final String fullTestName = getFullTestName(testName); - final SMTestProxy testProxy = getProxyByFullTestName(fullTestName); + addToInvokeLater(() -> { + final String testName = testFinishedEvent.getName(); + final long duration = testFinishedEvent.getDuration(); + final String fullTestName = getFullTestName(testName); + final SMTestProxy testProxy = getProxyByFullTestName(fullTestName); - if (testProxy == null) { - logProblem("Test wasn't started! TestFinished event: name = {" + testName + "}. " + - cannotFindFullTestNameMsg(fullTestName)); - return; - } - - testProxy.setDuration(duration); - testProxy.setFrameworkOutputFile(testFinishedEvent.getOutputFile()); - testProxy.setFinished(); - myRunningTestsFullNameToProxy.remove(fullTestName); - myCurrentChildren.remove(testProxy); - - //fire events - fireOnTestFinished(testProxy); + if (testProxy == null) { + logProblem("Test wasn't started! TestFinished event: name = {" + testName + "}. " + + cannotFindFullTestNameMsg(fullTestName)); + return; } + + testProxy.setDuration(duration); + testProxy.setFrameworkOutputFile(testFinishedEvent.getOutputFile()); + testProxy.setFinished(); + myRunningTestsFullNameToProxy.remove(fullTestName); + myCurrentChildren.remove(testProxy); + + //fire events + fireOnTestFinished(testProxy); }); } public void onSuiteFinished(@NotNull final TestSuiteFinishedEvent suiteFinishedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String suiteName = suiteFinishedEvent.getName(); - final SMTestProxy mySuite = mySuitesStack.popSuite(suiteName); - if (mySuite != null) { - mySuite.setFinished(); - myCurrentChildren.clear(); - myGetChildren = true; + addToInvokeLater(() -> { + final String suiteName = suiteFinishedEvent.getName(); + final SMTestProxy mySuite = mySuitesStack.popSuite(suiteName); + if (mySuite != null) { + mySuite.setFinished(); + myCurrentChildren.clear(); + myGetChildren = true; - //fire events - fireOnSuiteFinished(mySuite); - } + //fire events + fireOnSuiteFinished(mySuite); } }); } public void onUncapturedOutput(@NotNull final String text, final Key outputType) { - addToInvokeLater(new Runnable() { - public void run() { - final SMTestProxy currentProxy = findCurrentTestOrSuite(); + addToInvokeLater(() -> { + final SMTestProxy currentProxy = findCurrentTestOrSuite(); - if (ProcessOutputTypes.STDERR.equals(outputType)) { - currentProxy.addStdErr(text); - } else if (ProcessOutputTypes.SYSTEM.equals(outputType)) { - currentProxy.addSystemOutput(text); - } else { - currentProxy.addStdOutput(text, outputType); - } + if (ProcessOutputTypes.STDERR.equals(outputType)) { + currentProxy.addStdErr(text); + } else if (ProcessOutputTypes.SYSTEM.equals(outputType)) { + currentProxy.addSystemOutput(text); + } else { + currentProxy.addStdOutput(text, outputType); } }); } @@ -370,143 +335,131 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso public void onError(@NotNull final String localizedMessage, @Nullable final String stackTrace, final boolean isCritical) { - addToInvokeLater(new Runnable() { - public void run() { - final SMTestProxy currentProxy = findCurrentTestOrSuite(); - currentProxy.addError(localizedMessage, stackTrace, isCritical); - } + addToInvokeLater(() -> { + final SMTestProxy currentProxy = findCurrentTestOrSuite(); + currentProxy.addError(localizedMessage, stackTrace, isCritical); }); } public void onTestFailure(@NotNull final TestFailedEvent testFailedEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String testName = testFailedEvent.getName(); - if (testName == null) { - logProblem("No test name specified in " + testFailedEvent); + addToInvokeLater(() -> { + final String testName = testFailedEvent.getName(); + if (testName == null) { + logProblem("No test name specified in " + testFailedEvent); + return; + } + final String localizedMessage = testFailedEvent.getLocalizedFailureMessage(); + final String stackTrace = testFailedEvent.getStacktrace(); + final boolean isTestError = testFailedEvent.isTestError(); + final String comparisionFailureActualText = testFailedEvent.getComparisonFailureActualText(); + final String comparisionFailureExpectedText = testFailedEvent.getComparisonFailureExpectedText(); + final boolean inDebugMode = SMTestRunnerConnectionUtil.isInDebugMode(); + + final String fullTestName = getFullTestName(testName); + SMTestProxy testProxy = getProxyByFullTestName(fullTestName); + if (testProxy == null) { + logProblem("Test wasn't started! TestFailure event: name = {" + testName + "}" + + ", message = {" + localizedMessage + "}" + + ", stackTrace = {" + stackTrace + "}. " + + cannotFindFullTestNameMsg(fullTestName)); + if (inDebugMode) { return; } - final String localizedMessage = testFailedEvent.getLocalizedFailureMessage(); - final String stackTrace = testFailedEvent.getStacktrace(); - final boolean isTestError = testFailedEvent.isTestError(); - final String comparisionFailureActualText = testFailedEvent.getComparisonFailureActualText(); - final String comparisionFailureExpectedText = testFailedEvent.getComparisonFailureExpectedText(); - final boolean inDebugMode = SMTestRunnerConnectionUtil.isInDebugMode(); - - final String fullTestName = getFullTestName(testName); - SMTestProxy testProxy = getProxyByFullTestName(fullTestName); - if (testProxy == null) { - logProblem("Test wasn't started! TestFailure event: name = {" + testName + "}" + - ", message = {" + localizedMessage + "}" + - ", stackTrace = {" + stackTrace + "}. " + - cannotFindFullTestNameMsg(fullTestName)); - if (inDebugMode) { - return; - } - else { - // if hasn't been already reported - // 1. report - onTestStarted(new TestStartedEvent(testName, null)); - // 2. add failure - testProxy = getProxyByFullTestName(fullTestName); - } - } - - if (testProxy == null) { - return; - } - - if (comparisionFailureActualText != null && comparisionFailureExpectedText != null) { - testProxy.setTestComparisonFailed(localizedMessage, stackTrace, - comparisionFailureActualText, comparisionFailureExpectedText, - testFailedEvent.getExpectedFilePath(), testFailedEvent.getActualFilePath()); - } - else if (comparisionFailureActualText == null && comparisionFailureExpectedText == null) { - testProxy.setTestFailed(localizedMessage, stackTrace, isTestError); - } else { - logProblem("Comparison failure actual and expected texts should be both null or not null.\n" - + "Expected:\n" - + comparisionFailureExpectedText + "\n" - + "Actual:\n" - + comparisionFailureActualText); + // if hasn't been already reported + // 1. report + onTestStarted(new TestStartedEvent(testName, null)); + // 2. add failure + testProxy = getProxyByFullTestName(fullTestName); } - - // fire event - fireOnTestFailed(testProxy); } + + if (testProxy == null) { + return; + } + + if (comparisionFailureActualText != null && comparisionFailureExpectedText != null) { + testProxy.setTestComparisonFailed(localizedMessage, stackTrace, + comparisionFailureActualText, comparisionFailureExpectedText, + testFailedEvent.getExpectedFilePath(), testFailedEvent.getActualFilePath()); + } + else if (comparisionFailureActualText == null && comparisionFailureExpectedText == null) { + testProxy.setTestFailed(localizedMessage, stackTrace, isTestError); + } + else { + logProblem("Comparison failure actual and expected texts should be both null or not null.\n" + + "Expected:\n" + + comparisionFailureExpectedText + "\n" + + "Actual:\n" + + comparisionFailureActualText); + } + + // fire event + fireOnTestFailed(testProxy); }); } public void onTestIgnored(@NotNull final TestIgnoredEvent testIgnoredEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String testName = ObjectUtils.assertNotNull(testIgnoredEvent.getName()); - String ignoreComment = testIgnoredEvent.getIgnoreComment(); - final String stackTrace = testIgnoredEvent.getStacktrace(); - final String fullTestName = getFullTestName(testName); - SMTestProxy testProxy = getProxyByFullTestName(fullTestName); - if (testProxy == null) { - final boolean debugMode = SMTestRunnerConnectionUtil.isInDebugMode(); - logProblem("Test wasn't started! " + - "TestIgnored event: name = {" + testName + "}, " + - "message = {" + ignoreComment + "}. " + - cannotFindFullTestNameMsg(fullTestName)); - if (debugMode) { - return; - } else { - // try to fix - // 1. report test opened - onTestStarted(new TestStartedEvent(testName, null)); + addToInvokeLater(() -> { + final String testName = ObjectUtils.assertNotNull(testIgnoredEvent.getName()); + String ignoreComment = testIgnoredEvent.getIgnoreComment(); + final String stackTrace = testIgnoredEvent.getStacktrace(); + final String fullTestName = getFullTestName(testName); + SMTestProxy testProxy = getProxyByFullTestName(fullTestName); + if (testProxy == null) { + final boolean debugMode = SMTestRunnerConnectionUtil.isInDebugMode(); + logProblem("Test wasn't started! " + + "TestIgnored event: name = {" + testName + "}, " + + "message = {" + ignoreComment + "}. " + + cannotFindFullTestNameMsg(fullTestName)); + if (debugMode) { + return; + } else { + // try to fix + // 1. report test opened + onTestStarted(new TestStartedEvent(testName, null)); - // 2. report failure - testProxy = getProxyByFullTestName(fullTestName); - } + // 2. report failure + testProxy = getProxyByFullTestName(fullTestName); + } - } - if (testProxy == null) { - return; - } - testProxy.setTestIgnored(ignoreComment, stackTrace); + } + if (testProxy == null) { + return; + } + testProxy.setTestIgnored(ignoreComment, stackTrace); - // fire event - fireOnTestIgnored(testProxy); - } - }); + // fire event + fireOnTestIgnored(testProxy); + }); } public void onTestOutput(@NotNull final TestOutputEvent testOutputEvent) { - addToInvokeLater(new Runnable() { - public void run() { - final String testName = testOutputEvent.getName(); - final String text = testOutputEvent.getText(); - final boolean stdOut = testOutputEvent.isStdOut(); - final String fullTestName = getFullTestName(testName); - final SMTestProxy testProxy = getProxyByFullTestName(fullTestName); - if (testProxy == null) { - logProblem("Test wasn't started! TestOutput event: name = {" + testName + "}, " + - "isStdOut = " + stdOut + ", " + - "text = {" + text + "}. " + - cannotFindFullTestNameMsg(fullTestName)); - return; - } + addToInvokeLater(() -> { + final String testName = testOutputEvent.getName(); + final String text = testOutputEvent.getText(); + final boolean stdOut = testOutputEvent.isStdOut(); + final String fullTestName = getFullTestName(testName); + final SMTestProxy testProxy = getProxyByFullTestName(fullTestName); + if (testProxy == null) { + logProblem("Test wasn't started! TestOutput event: name = {" + testName + "}, " + + "isStdOut = " + stdOut + ", " + + "text = {" + text + "}. " + + cannotFindFullTestNameMsg(fullTestName)); + return; + } - if (stdOut) { - testProxy.addStdOutput(text, ProcessOutputTypes.STDOUT); - } else { - testProxy.addStdErr(text); - } - } - }); + if (stdOut) { + testProxy.addStdOutput(text, ProcessOutputTypes.STDOUT); + } else { + testProxy.addStdErr(text); + } + }); } public void onTestsCountInSuite(final int count) { - addToInvokeLater(new Runnable() { - public void run() { - fireOnTestsCountInSuite(count); - } - }); + addToInvokeLater(() -> fireOnTestsCountInSuite(count)); } @NotNull @@ -566,20 +519,18 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso */ public void dispose() { super.dispose(); - addToInvokeLater(new Runnable() { - public void run() { + addToInvokeLater(() -> { - disconnectListeners(); - if (!myRunningTestsFullNameToProxy.isEmpty()) { - final Application application = ApplicationManager.getApplication(); - if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { - logProblem("Not all events were processed! " + dumpRunningTestsNames()); - } - } - myRunningTestsFullNameToProxy.clear(); - mySuitesStack.clear(); - } - }); + disconnectListeners(); + if (!myRunningTestsFullNameToProxy.isEmpty()) { + final Application application = ApplicationManager.getApplication(); + if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { + logProblem("Not all events were processed! " + dumpRunningTestsNames()); + } + } + myRunningTestsFullNameToProxy.clear(); + mySuitesStack.clear(); + }); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java index 87491f1628d0..ef279c6cbd3b 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTestProxy.java @@ -562,12 +562,9 @@ public class SMTestProxy extends AbstractTestProxy { } private static void printState(final AbstractState oldState, final Printer rightPrinter) { - invokeInAlarm(new Runnable() { - @Override - public void run() { - //Tests State, that provide and formats additional output - oldState.printOn(rightPrinter); - } + invokeInAlarm(() -> { + //Tests State, that provide and formats additional output + oldState.printOn(rightPrinter); }); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java index a0ae043f64ae..cf5346d92bca 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/TestSuiteStack.java @@ -143,12 +143,7 @@ public class TestSuiteStack { return EMPTY; } - return StringUtil.join(names, new Function() { - @Override - public String fun(String s) { - return "[" + s + "]"; - } - }, "->"); + return StringUtil.join(names, s -> "[" + s + "]", "->"); } public void clear() { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java index 2c21befffb18..b5c49de67fd1 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedToGeneralTestEventsConverter.java @@ -49,12 +49,9 @@ public class ImportedToGeneralTestEventsConverter extends OutputToGeneralTestEve @Override public void onStartTesting() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - parseTestResults(); - myHandler.detachProcess(); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + parseTestResults(); + myHandler.detachProcess(); }); } @@ -64,12 +61,8 @@ public class ImportedToGeneralTestEventsConverter extends OutputToGeneralTestEve } catch (IOException e) { final String message = e.getMessage(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(myConsoleProperties.getProject(), message, "Failed to Parse " + myFile.getName()); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(myConsoleProperties.getProject(), message, "Failed to Parse " + myFile.getName())); } } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/actions/ImportTestsGroup.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/actions/ImportTestsGroup.java index 941323c4a17f..cbb98da7ffc6 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/actions/ImportTestsGroup.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/actions/ImportTestsGroup.java @@ -53,18 +53,10 @@ public class if (project == null) return EMPTY_ARRAY; final Collection filePaths = TestHistoryConfiguration.getInstance(project).getFiles(); final File testHistoryRoot = TestStateStorage.getTestHistoryRoot(project); - final List fileNames = ContainerUtil.map(filePaths, new Function() { - @Override - public File fun(String fileName) { - return new File(testHistoryRoot, fileName); - } - }); - Collections.sort(fileNames, new Comparator() { - @Override - public int compare(File f1, File f2) { - return f1.lastModified() > f2.lastModified() ? -1 : 1; - } + final List fileNames = ContainerUtil.map(filePaths, fileName -> { + return new File(testHistoryRoot, fileName); }); + Collections.sort(fileNames, (f1, f2) -> f1.lastModified() > f2.lastModified() ? -1 : 1); final int historySize = fileNames.size(); final AnAction[] actions = new AnAction[historySize + 2]; for (int i = 0; i < historySize; i++) { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/states/TestComparisonFailedStates.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/states/TestComparisonFailedStates.java index e065548d66ce..49dc9df76af7 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/states/TestComparisonFailedStates.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/states/TestComparisonFailedStates.java @@ -48,11 +48,8 @@ public class TestComparisonFailedStates extends TestFailedState { @NotNull public List getHyperlinks() { - return ContainerUtil.map(myStates, new Function() { - @Override - public DiffHyperlink fun(TestComparisionFailedState state) { - return state.getHyperlink(); - } + return ContainerUtil.map(myStates, state -> { + return state.getHyperlink(); }); } } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerConsoleView.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerConsoleView.java index c5b11f98b6fb..d165dcb35239 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerConsoleView.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTRunnerConsoleView.java @@ -96,12 +96,7 @@ public class SMTRunnerConsoleView extends BaseTestsOutputConsoleView { } // print selected content - SMRunnerUtil.runInEventDispatchThread(new Runnable() { - @Override - public void run() { - getPrinter().updateOnTestSelected(selectedTestProxy); - } - }, ModalityState.NON_MODAL); + SMRunnerUtil.runInEventDispatchThread(() -> getPrinter().updateOnTestSelected(selectedTestProxy), ModalityState.NON_MODAL); } }); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java index c00936ac07b2..2b55131dd632 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java @@ -160,11 +160,7 @@ public class SMTestRunnerResultsForm extends TestResultsPanel if (Registry.is("tests.view.old.statistics.panel")) { final KeyStroke shiftEnterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK); SMRunnerUtil.registerAsAction(shiftEnterKey, "show-statistics-for-test-proxy", - new Runnable() { - public void run() { - showStatisticsForSelectedProxy(); - } - }, + () -> showStatisticsForSelectedProxy(), myTreeView); } } @@ -314,14 +310,11 @@ public class SMTestRunnerResultsForm extends TestResultsPanel LvcsHelper.addLabel(this); - final Runnable onDone = new Runnable() { - @Override - public void run() { - myTestsRunning = false; - final boolean sortByDuration = TestConsoleProperties.SORT_BY_DURATION.value(myProperties); - if (sortByDuration) { - myTreeBuilder.setStatisticsComparator(myProperties, sortByDuration); - } + final Runnable onDone = () -> { + myTestsRunning = false; + final boolean sortByDuration = TestConsoleProperties.SORT_BY_DURATION.value(myProperties); + if (sortByDuration) { + myTreeBuilder.setStatisticsComparator(myProperties, sortByDuration); } }; if (myLastSelected == null) { @@ -656,13 +649,11 @@ public class SMTestRunnerResultsForm extends TestResultsPanel return; } - SMRunnerUtil.runInEventDispatchThread(new Runnable() { - public void run() { - if (myTreeBuilder.isDisposed()) { - return; - } - myTreeBuilder.select(testProxy, onDone); + SMRunnerUtil.runInEventDispatchThread(() -> { + if (myTreeBuilder.isDisposed()) { + return; } + myTreeBuilder.select(testProxy, onDone); }, ModalityState.NON_MODAL); } @@ -724,15 +715,13 @@ public class SMTestRunnerResultsForm extends TestResultsPanel return new PropagateSelectionHandler() { public void handlePropagateSelectionRequest(@Nullable final SMTestProxy selectedTestProxy, @NotNull final Object sender, final boolean requestFocus) { - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - selectWithoutNotify(selectedTestProxy, null); + SMRunnerUtil.addToInvokeLater(() -> { + selectWithoutNotify(selectedTestProxy, null); - // Request focus if necessary - if (requestFocus) { - //myTreeView.requestFocusInWindow(); - IdeFocusManager.getInstance(myProject).requestFocus(myTreeView, true); - } + // Request focus if necessary + if (requestFocus) { + //myTreeView.requestFocusInWindow(); + IdeFocusManager.getInstance(myProject).requestFocus(myTreeView, true); } }); } @@ -850,18 +839,15 @@ public class SMTestRunnerResultsForm extends TestResultsPanel private void writeState() { // read action to prevent project (and storage) from being disposed - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - Project project = getProject(); - if (project.isDisposed()) return; - TestStateStorage storage = TestStateStorage.getInstance(project); - List tests = myRoot.getAllTests(); - for (SMTestProxy proxy : tests) { - String url = proxy instanceof SMTestProxy.SMRootTestProxy ? ((SMTestProxy.SMRootTestProxy)proxy).getRootLocation() : proxy.getLocationUrl(); - if (url != null) { - storage.writeState(url, new TestStateStorage.Record(proxy.getMagnitude(), new Date())); - } + ApplicationManager.getApplication().runReadAction(() -> { + Project project = getProject(); + if (project.isDisposed()) return; + TestStateStorage storage = TestStateStorage.getInstance(project); + List tests = myRoot.getAllTests(); + for (SMTestProxy proxy : tests) { + String url = proxy instanceof SMTestProxy.SMRootTestProxy ? ((SMTestProxy.SMRootTestProxy)proxy).getRootLocation() : proxy.getLocationUrl(); + if (url != null) { + storage.writeState(url, new TestStateStorage.Record(proxy.getMagnitude(), new Date())); } } }); diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsPanel.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsPanel.java index 564a26ce29e8..2fefd7a31de8 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsPanel.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsPanel.java @@ -81,11 +81,7 @@ public class StatisticsPanel implements DataProvider { // Fire selection changed and move focus on SHIFT+ENTER final KeyStroke shiftEnterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK); SMRunnerUtil.registerAsAction(shiftEnterKey, "select-test-proxy-in-test-view", - new Runnable() { - public void run() { - showSelectedProxyInTestsTree(); - } - }, + () -> showSelectedProxyInTestsTree(), myStatisticsTableView); // Expand selected or go to parent on ENTER @@ -138,21 +134,19 @@ public class StatisticsPanel implements DataProvider { } private void updateAndRestoreSelection() { - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - BaseTableView.restore(myStorage, myStatisticsTableView); - // statisticsTableView can be null in JUnit tests - final SMTestProxy oldSelection = myStatisticsTableView.getSelectedObject(); + SMRunnerUtil.addToInvokeLater(() -> { + BaseTableView.restore(myStorage, myStatisticsTableView); + // statisticsTableView can be null in JUnit tests + final SMTestProxy oldSelection = myStatisticsTableView.getSelectedObject(); - // update module - myTableModel.updateModel(); + // update module + myTableModel.updateModel(); - // restore selection if it is possible - if (oldSelection != null) { - final int newRow = myTableModel.getIndexOf(oldSelection); - if (newRow > -1) { - myStatisticsTableView.setRowSelectionInterval(newRow, newRow); - } + // restore selection if it is possible + if (oldSelection != null) { + final int newRow = myTableModel.getIndexOf(oldSelection); + if (newRow > -1) { + myStatisticsTableView.setRowSelectionInterval(newRow, newRow); } } }); @@ -189,16 +183,14 @@ public class StatisticsPanel implements DataProvider { public void selectProxy(@Nullable final SMTestProxy selectedTestProxy, @NotNull final Object sender, final boolean requestFocus) { - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - // Select tab if focus was requested - if (requestFocus) { - IdeFocusManager.getInstance(myProject).requestFocus(myStatisticsTableView, true); - } - - // Select proxy in table - selectProxy(selectedTestProxy); + SMRunnerUtil.addToInvokeLater(() -> { + // Select tab if focus was requested + if (requestFocus) { + IdeFocusManager.getInstance(myProject).requestFocus(myStatisticsTableView, true); } + + // Select proxy in table + selectProxy(selectedTestProxy); }); } @@ -214,21 +206,19 @@ public class StatisticsPanel implements DataProvider { protected Runnable createGotoSuiteOrParentAction() { // Expand selected or go to parent - return new Runnable() { - public void run() { - final SMTestProxy selectedProxy = getSelectedItem(); - if (selectedProxy == null) { - return; - } + return () -> { + final SMTestProxy selectedProxy = getSelectedItem(); + if (selectedProxy == null) { + return; + } - final int i = myStatisticsTableView.getSelectedRow(); - assert i >= 0; //because something is selected + final int i = myStatisticsTableView.getSelectedRow(); + assert i >= 0; //because something is selected - // if selected element is suite - we should expand it - if (selectedProxy.isSuite()) { - // expand and select first (Total) row - showInTableAndSelectRow(selectedProxy, selectedProxy); - } + // if selected element is suite - we should expand it + if (selectedProxy.isSuite()) { + // expand and select first (Total) row + showInTableAndSelectRow(selectedProxy, selectedProxy); } }; } @@ -247,14 +237,12 @@ public class StatisticsPanel implements DataProvider { * @param rowIndex Row's index */ protected void selectRow(final int rowIndex) { - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - // updates model - myStatisticsTableView.setRowSelectionInterval(rowIndex, rowIndex); + SMRunnerUtil.addToInvokeLater(() -> { + // updates model + myStatisticsTableView.setRowSelectionInterval(rowIndex, rowIndex); - // Scroll to visible - TableUtil.scrollSelectionToVisible(myStatisticsTableView); - } + // Scroll to visible + TableUtil.scrollSelectionToVisible(myStatisticsTableView); }); } @@ -262,15 +250,13 @@ public class StatisticsPanel implements DataProvider { * Selects row in table */ protected void selectRowOf(final SMTestProxy proxy) { - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - final int indexOf = myTableModel.getIndexOf(proxy); - if (indexOf > -1) { - final int rowIndex = myStatisticsTableView.convertRowIndexToView(indexOf); - myStatisticsTableView.setRowSelectionInterval(rowIndex, rowIndex >= 0 ? rowIndex : 0); - // Scroll to visible - TableUtil.scrollSelectionToVisible(myStatisticsTableView); - } + SMRunnerUtil.addToInvokeLater(() -> { + final int indexOf = myTableModel.getIndexOf(proxy); + if (indexOf > -1) { + final int rowIndex = myStatisticsTableView.convertRowIndexToView(indexOf); + myStatisticsTableView.setRowSelectionInterval(rowIndex, rowIndex >= 0 ? rowIndex : 0); + // Scroll to visible + TableUtil.scrollSelectionToVisible(myStatisticsTableView); } }); } @@ -285,13 +271,11 @@ public class StatisticsPanel implements DataProvider { } private void findAndSelectInTable(final SMTestProxy proxy) { - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - final int rowIndex = myTableModel.getIndexOf(proxy); - if (rowIndex >= 0) { - final int rowIndexToView = myStatisticsTableView.convertRowIndexToView(rowIndex); - myStatisticsTableView.setRowSelectionInterval(rowIndexToView, rowIndexToView); - } + SMRunnerUtil.addToInvokeLater(() -> { + final int rowIndex = myTableModel.getIndexOf(proxy); + if (rowIndex >= 0) { + final int rowIndexToView = myStatisticsTableView.convertRowIndexToView(rowIndex); + myStatisticsTableView.setRowSelectionInterval(rowIndexToView, rowIndexToView); } }); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java index edab544952d5..ac102cb24e73 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/statistics/StatisticsTableModel.java @@ -47,11 +47,7 @@ public class StatisticsTableModel extends ListTableModel { myCurrentSuite = newCurrentSuite; } // update model to show new items in it - SMRunnerUtil.addToInvokeLater(new Runnable() { - public void run() { - updateModel(); - } - }); + SMRunnerUtil.addToInvokeLater(() -> updateModel()); } @Nullable diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/OutputLineSplitterTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/OutputLineSplitterTest.java index 35bc91d2837e..a6ef42a15ad2 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/OutputLineSplitterTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/OutputLineSplitterTest.java @@ -68,25 +68,22 @@ public class OutputLineSplitterTest extends PlatformTestCase { final Map> written = new ConcurrentHashMap>(); for (final Key each : ALL_TYPES) { written.put(each, new ArrayList()); - execute(new Runnable() { - @Override - public void run() { - Random r = new Random(); - for (int i = 0; i < 1000; i++) { - String s = StringUtil.repeat("A", 100 + r.nextInt(1000)); - if (r.nextInt(1) == 1) s += "\n"; + execute(() -> { + Random r = new Random(); + for (int i = 0; i < 1000; i++) { + String s = StringUtil.repeat("A", 100 + r.nextInt(1000)); + if (r.nextInt(1) == 1) s += "\n"; - mySplitter.process(s, each); - List list = written.get(each); - if (!list.isEmpty()) { - String last = list.get(list.size() - 1); - if (!last.endsWith("\n")) { - list.set(list.size() - 1, last + s); - continue; - } + mySplitter.process(s, each); + List list = written.get(each); + if (!list.isEmpty()) { + String last = list.get(list.size() - 1); + if (!last.endsWith("\n")) { + list.set(list.size() - 1, last + s); + continue; } - list.add(s); } + list.add(s); } }).get(); } @@ -102,21 +99,18 @@ public class OutputLineSplitterTest extends PlatformTestCase { final Map> written = new ConcurrentHashMap>(); for (final Key each : ALL_TYPES) { written.put(each, new ArrayList()); - execute(new Runnable() { - @Override - public void run() { - Random r = new Random(); - for (int i = 0; i < 1000; i++) { - String s = StringUtil.repeat("A", 100 + r.nextInt(1000)) + "\n"; + execute(() -> { + Random r = new Random(); + for (int i = 0; i < 1000; i++) { + String s = StringUtil.repeat("A", 100 + r.nextInt(1000)) + "\n"; - if (each == ProcessOutputTypes.STDOUT) { - mySplitter.process(s, ALL_COLORS.get(r.nextInt(2))); - } - else { - mySplitter.process(s, each); - } - written.get(each).add(s); + if (each == ProcessOutputTypes.STDOUT) { + mySplitter.process(s, ALL_COLORS.get(r.nextInt(2))); } + else { + mySplitter.process(s, each); + } + written.get(each).add(s); } }).get(); } @@ -136,20 +130,18 @@ public class OutputLineSplitterTest extends PlatformTestCase { List> futures = new ArrayList>(); for (final Key each : ALL_TYPES) { - futures.add(execute(new Runnable() { - public void run() { - int i = 0; - while (!isFinished.get()) { - mySplitter.process(StringUtil.repeat("A", 100), each); - i++; - if (i % 10 == 0) { - written.release(); - try { - if (!read.tryAcquire(10, TimeUnit.SECONDS)) throw new TimeoutException(); - } - catch (Exception e) { - throw new RuntimeException(e); - } + futures.add(execute(() -> { + int i = 0; + while (!isFinished.get()) { + mySplitter.process(StringUtil.repeat("A", 100), each); + i++; + if (i % 10 == 0) { + written.release(); + try { + if (!read.tryAcquire(10, TimeUnit.SECONDS)) throw new TimeoutException(); + } + catch (Exception e) { + throw new RuntimeException(e); } } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java index 296942efd5d5..c861b1470f2d 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/MatcherImpl.java @@ -180,17 +180,14 @@ public class MatcherImpl { final MatchOptions matchOptions = configuration.getMatchOptions(); matchContext.setOptions(matchOptions); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - try { - final CompiledPattern compiledPattern = PatternCompiler.compilePattern(project, matchOptions); - matchContext.setPattern(compiledPattern); - out.put(configuration, matchContext); - } - catch (UnsupportedPatternException ignored) {} - catch (MalformedPatternException ignored) {} + ApplicationManager.getApplication().runReadAction(() -> { + try { + final CompiledPattern compiledPattern = PatternCompiler.compilePattern(project, matchOptions); + matchContext.setPattern(compiledPattern); + out.put(configuration, matchContext); } + catch (UnsupportedPatternException ignored) {} + catch (MalformedPatternException ignored) {} }); } } @@ -236,12 +233,7 @@ public class MatcherImpl { if (scheduler.getTaskQueueEndAction()==null) { scheduler.setTaskQueueEndAction( - new Runnable() { - @Override - public void run() { - matchContext.getSink().matchingFinished(); - } - } + () -> matchContext.getSink().matchingFinished() ); } @@ -267,11 +259,8 @@ public class MatcherImpl { } }; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - FileBasedIndex.getInstance().iterateIndexableFiles(ci, project, progress); - } + ApplicationManager.getApplication().runReadAction(() -> { + FileBasedIndex.getInstance().iterateIndexableFiles(ci, project, progress); }); progress.setText2(""); } @@ -524,17 +513,14 @@ public class MatcherImpl { matchContext.getSink().processFile((PsiFile)file); } - myDumbService.runReadActionInSmartMode(new Runnable() { - @Override - public void run() { - if (!file.isValid()) return; - final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(file.getLanguage()); - if (profile == null) { - return; - } - match(profile.extendMatchOnePsiFile(file), patternLanguage); - } + myDumbService.runReadActionInSmartMode(() -> { + if (!file.isValid()) return; + final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(file.getLanguage()); + if (profile == null) { + return; } + match(profile.extendMatchOnePsiFile(file), patternLanguage); + } ); } } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/highlightTemplate/SSBasedInspection.java b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/highlightTemplate/SSBasedInspection.java index 8e0d4935bfef..e671bab73b80 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/highlightTemplate/SSBasedInspection.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/inspection/highlightTemplate/SSBasedInspection.java @@ -100,17 +100,14 @@ public class SSBasedInspection extends LocalInspectionTool { return new PsiElementVisitor() { final Matcher matcher = new Matcher(holder.getManager().getProject()); - final PairProcessor processor = new PairProcessor() { - @Override - public boolean process(MatchResult matchResult, Configuration configuration) { - PsiElement element = matchResult.getMatch(); - String name = configuration.getName(); - LocalQuickFix fix = createQuickFix(holder.getManager().getProject(), matchResult, configuration); - holder.registerProblem( - holder.getManager().createProblemDescriptor(element, name, fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly) - ); - return true; - } + final PairProcessor processor = (matchResult, configuration) -> { + PsiElement element = matchResult.getMatch(); + String name = configuration.getName(); + LocalQuickFix fix = createQuickFix(holder.getManager().getProject(), matchResult, configuration); + holder.registerProblem( + holder.getManager().createProblemDescriptor(element, name, fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly) + ); + return true; }; @Override diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java index 29189c1d7fb6..19f33abd3821 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/impl/Replacer.java @@ -190,17 +190,13 @@ public class Replacer { //noinspection HardCodedStringLiteral CommandProcessor.getInstance().executeCommand( project, - new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction( - new Runnable() { - public void run() { - doReplace(element, replacementInfo); - } - } - ); - PsiDocumentManager.getInstance(project).commitAllDocuments(); - } + () -> { + ApplicationManager.getApplication().runWriteAction( + () -> { + doReplace(element, replacementInfo); + } + ); + PsiDocumentManager.getInstance(project).commitAllDocuments(); }, "ssreplace", "test" @@ -215,33 +211,27 @@ public class Replacer { private void reformatAndPostProcess(final PsiElement elementParent) { if (elementParent == null) return; - final Runnable action = new Runnable() { - public void run() { - final PsiFile containingFile = elementParent.getContainingFile(); + final Runnable action = () -> { + final PsiFile containingFile = elementParent.getContainingFile(); - if (containingFile != null && options.isToReformatAccordingToStyle()) { - if (containingFile.getVirtualFile() != null) { - PsiDocumentManager.getInstance(project) - .commitDocument(FileDocumentManager.getInstance().getDocument(containingFile.getVirtualFile())); - } + if (containingFile != null && options.isToReformatAccordingToStyle()) { + if (containingFile.getVirtualFile() != null) { + PsiDocumentManager.getInstance(project) + .commitDocument(FileDocumentManager.getInstance().getDocument(containingFile.getVirtualFile())); + } - final int parentOffset = elementParent.getTextRange().getStartOffset(); - CodeStyleManager.getInstance(project) - .reformatRange(containingFile, parentOffset, parentOffset + elementParent.getTextLength(), true); - } - if (replaceHandler != null) { - replaceHandler.postProcess(elementParent, options); - } + final int parentOffset = elementParent.getTextRange().getStartOffset(); + CodeStyleManager.getInstance(project) + .reformatRange(containingFile, parentOffset, parentOffset + elementParent.getTextLength(), true); + } + if (replaceHandler != null) { + replaceHandler.postProcess(elementParent, options); } }; CommandProcessor.getInstance().executeCommand( project, - new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(action); - } - }, + () -> ApplicationManager.getApplication().runWriteAction(action), "reformat and shorten refs after ssr", "test" ); diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java index af0d230edbfb..13eaabc87204 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceCommand.java @@ -24,12 +24,7 @@ public class ReplaceCommand extends SearchCommand { } protected UsageViewContext createUsageViewContext() { - final Runnable searchStarter = new Runnable() { - @Override - public void run() { - new ReplaceCommand(myConfiguration, mySearchContext).startSearching(); - } - }; + final Runnable searchStarter = () -> new ReplaceCommand(myConfiguration, mySearchContext).startSearching(); myReplaceUsageViewContext = new ReplaceUsageViewContext(mySearchContext, myConfiguration, searchStarter); return myReplaceUsageViewContext; } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java index bf5c9401f55c..2eafc90a2317 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/replace/ui/ReplaceUsageViewContext.java @@ -58,43 +58,39 @@ class ReplaceUsageViewContext extends UsageViewContext { @Override protected void configureActions() { - final Runnable replaceRunnable = new Runnable() { - public void run() { - LocalHistoryAction labelAction = LocalHistory.getInstance().startAction(SSRBundle.message("structural.replace.title")); + final Runnable replaceRunnable = () -> { + LocalHistoryAction labelAction = LocalHistory.getInstance().startAction(SSRBundle.message("structural.replace.title")); - doReplace(); - myUsageView.close(); + doReplace(); + myUsageView.close(); - labelAction.finish(); - } + labelAction.finish(); }; //noinspection HardCodedStringLiteral myUsageView.addPerformOperationAction(replaceRunnable, "Replace All", null, SSRBundle.message("do.replace.all.button")); - final Runnable replaceSelected = new Runnable() { - public void run() { - final Set infos = myUsageView.getSelectedUsages(); - if (infos == null || infos.isEmpty()) return; + final Runnable replaceSelected = () -> { + final Set infos = myUsageView.getSelectedUsages(); + if (infos == null || infos.isEmpty()) return; - LocalHistoryAction labelAction = LocalHistory.getInstance().startAction(SSRBundle.message("structural.replace.title")); + LocalHistoryAction labelAction = LocalHistory.getInstance().startAction(SSRBundle.message("structural.replace.title")); - for (final Usage info : infos) { - final UsageInfo2UsageAdapter usage = (UsageInfo2UsageAdapter)info; + for (final Usage info : infos) { + final UsageInfo2UsageAdapter usage = (UsageInfo2UsageAdapter)info; - if (isValid(usage)) { - replaceOne(usage, false); - } + if (isValid(usage)) { + replaceOne(usage, false); } + } - labelAction.finish(); + labelAction.finish(); - if (myUsageView.getUsagesCount() > 0) { - for (Usage usage : myUsageView.getSortedUsages()) { - if (!isExcluded(usage)) { - myUsageView.selectUsages(new Usage[]{usage}); - return; - } + if (myUsageView.getUsagesCount() > 0) { + for (Usage usage : myUsageView.getSortedUsages()) { + if (!isExcluded(usage)) { + myUsageView.selectUsages(new Usage[]{usage}); + return; } } } @@ -102,16 +98,14 @@ class ReplaceUsageViewContext extends UsageViewContext { myUsageView.addButtonToLowerPane(replaceSelected, SSRBundle.message("replace.selected.button")); - final Runnable previewReplacement = new Runnable() { - public void run() { - Set selection = myUsageView.getSelectedUsages(); + final Runnable previewReplacement = () -> { + Set selection = myUsageView.getSelectedUsages(); - if (selection != null && !selection.isEmpty()) { - UsageInfo2UsageAdapter usage = (UsageInfo2UsageAdapter)selection.iterator().next(); + if (selection != null && !selection.isEmpty()) { + UsageInfo2UsageAdapter usage = (UsageInfo2UsageAdapter)selection.iterator().next(); - if (isValid(usage)) { - replaceOne(usage, true); - } + if (isValid(usage)) { + replaceOne(usage, true); } } }; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/EditVarConstraintsDialog.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/EditVarConstraintsDialog.java index e7417979d883..ca530caa5d22 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/EditVarConstraintsDialog.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/EditVarConstraintsDialog.java @@ -245,7 +245,7 @@ class EditVarConstraintsDialog extends DialogWrapper { final Variable var = variables.get(parameterList.getSelectedIndex()); if (validateParameters()) { if (current!=null) copyValuesFromUI(current); - ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { copyValuesToUI(var); }}); + ApplicationManager.getApplication().runWriteAction(() -> { copyValuesToUI(var); }); current = var; } else { rollingBackSelection = true; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java index 71118f1e4030..855a0b0f34c0 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchCommand.java @@ -43,12 +43,7 @@ public class SearchCommand { } protected UsageViewContext createUsageViewContext() { - final Runnable searchStarter = new Runnable() { - @Override - public void run() { - new SearchCommand(myConfiguration, mySearchContext).startSearching(); - } - }; + final Runnable searchStarter = () -> new SearchCommand(myConfiguration, mySearchContext).startSearching(); return new UsageViewContext(myConfiguration, mySearchContext, searchStarter); } @@ -181,13 +176,8 @@ public class SearchCommand { catch (final StructuralSearchException e) { final Alarm alarm = new Alarm(); alarm.addRequest( - new Runnable() { - @Override - public void run() { - NotificationGroup.toolWindowGroup("Structural Search", ToolWindowId.FIND) - .createNotification(SSRBundle.message("problem", e.getMessage()), MessageType.ERROR).notify(mySearchContext.getProject()); - } - }, + () -> NotificationGroup.toolWindowGroup("Structural Search", ToolWindowId.FIND) + .createNotification(SSRBundle.message("problem", e.getMessage()), MessageType.ERROR).notify(mySearchContext.getProject()), 100, ModalityState.NON_MODAL ); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java index 120e058391c8..5bd3feb24de0 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SearchDialog.java @@ -169,36 +169,26 @@ public class SearchDialog extends DialogWrapper { private void initiateValidation() { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - - @Override - public void run() { - try { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final boolean valid = isValid(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!valid) { - getOKAction().setEnabled(false); - } - else { - getOKAction().setEnabled(true); - reportMessage(null, null); - } - } - }); + myAlarm.addRequest(() -> { + try { + ApplicationManager.getApplication().runReadAction(() -> { + final boolean valid = isValid(); + ApplicationManager.getApplication().invokeLater(() -> { + if (!valid) { + getOKAction().setEnabled(false); + } + else { + getOKAction().setEnabled(true); + reportMessage(null, null); } }); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (RuntimeException e) { - Logger.getInstance(SearchDialog.class).error(e); - } + }); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (RuntimeException e) { + Logger.getInstance(SearchDialog.class).error(e); } }, 500); } @@ -219,12 +209,7 @@ public class SearchDialog extends DialogWrapper { types.add(fileType); } } - Collections.sort(types, new Comparator() { - @Override - public int compare(FileType o1, FileType o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Collections.sort(types, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); final DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel(types.toArray(new FileType[types.size()])); comboBoxModel.setSelectedItem(ourFtSearchVariant); @@ -323,12 +308,7 @@ public class SearchDialog extends DialogWrapper { if (fileType instanceof LanguageFileType) { Language language = ((LanguageFileType)fileType).getLanguage(); Language[] languageDialects = LanguageUtil.getLanguageDialects(language); - Arrays.sort(languageDialects, new Comparator() { - @Override - public int compare(Language o1, Language o2) { - return o1.getDisplayName().compareTo(o2.getDisplayName()); - } - }); + Arrays.sort(languageDialects, (o1, o2) -> o1.getDisplayName().compareTo(o2.getDisplayName())); Language[] variants = new Language[languageDialects.length + 1]; variants[0] = null; System.arraycopy(languageDialects, 0, variants, 1, languageDialects.length); @@ -505,13 +485,7 @@ public class SearchDialog extends DialogWrapper { final JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0)); labelPanel.add(new JLabel(SSRBundle.message("search.template"))); - labelPanel.add(UIUtil.createCompleteMatchInfo(new Producer() { - @Nullable - @Override - public Configuration produce() { - return model.getConfig(); - } - })); + labelPanel.add(UIUtil.createCompleteMatchInfo(() -> model.getConfig())); result.add(BorderLayout.NORTH, labelPanel); return result; @@ -870,15 +844,12 @@ public class SearchDialog extends DialogWrapper { } protected void reportMessage(@NonNls final String messageId, final Editor editor, final Object... params) { - com.intellij.util.ui.UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - final String message = messageId != null ? SSRBundle.message(messageId, params) : ""; - status.setText(message); - status.setToolTipText(message); - status.revalidate(); - statusText.setLabelFor(editor != null ? editor.getContentComponent() : null); - } + com.intellij.util.ui.UIUtil.invokeLaterIfNeeded(() -> { + final String message = messageId != null ? SSRBundle.message(messageId, params) : ""; + status.setText(message); + status.setToolTipText(message); + status.revalidate(); + statusText.setLabelFor(editor != null ? editor.getContentComponent() : null); }); } diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SelectTemplateDialog.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SelectTemplateDialog.java index 901b70cf653c..848943826b15 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SelectTemplateDialog.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/SelectTemplateDialog.java @@ -156,13 +156,9 @@ public class SelectTemplateDialog extends DialogWrapper { final JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0)); labelPanel.add(new JLabel(SSRBundle.message("selecttemplate.template.preview"))); - labelPanel.add(UIUtil.createCompleteMatchInfo(new Producer() { - @Nullable - @Override - public Configuration produce() { - final Configuration[] configurations = getSelectedConfigurations(); - return configurations.length != 1 ? null : configurations[0]; - } + labelPanel.add(UIUtil.createCompleteMatchInfo(() -> { + final Configuration[] configurations = getSelectedConfigurations(); + return configurations.length != 1 ? null : configurations[0]; })); panel.add(BorderLayout.NORTH, labelPanel); return centerPanel; diff --git a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java index 2386c765bd70..446c48ca2703 100644 --- a/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java +++ b/platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UIUtil.java @@ -118,15 +118,9 @@ public class UIUtil { public static void setContent(final Editor editor, String val, final int from, final int end, final Project project) { final String value = val != null ? val : ""; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - editor.getDocument().replaceString(from, (end == -1) ? editor.getDocument().getTextLength() : end, value); - } - }); - } - }, MODIFY_EDITOR_CONTENT, SS_GROUP); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + editor.getDocument().replaceString(from, (end == -1) ? editor.getDocument().getTextLength() : end, value); + }), MODIFY_EDITOR_CONTENT, SS_GROUP); } static String getShortParamString(Configuration config, String varname) { diff --git a/platform/testFramework/src/com/intellij/TestCaseLoader.java b/platform/testFramework/src/com/intellij/TestCaseLoader.java index 505f3320b739..b136e17b342d 100644 --- a/platform/testFramework/src/com/intellij/TestCaseLoader.java +++ b/platform/testFramework/src/com/intellij/TestCaseLoader.java @@ -215,12 +215,7 @@ public class TestCaseLoader { } if (!ourRankList.isEmpty()) { - Collections.sort(result, new Comparator() { - @Override - public int compare(final Class o1, final Class o2) { - return getRank(o1) - getRank(o2); - } - }); + Collections.sort(result, (o1, o2) -> getRank(o1) - getRank(o2)); } return result; diff --git a/platform/testFramework/src/com/intellij/psi/codeStyle/arrangement/AbstractRearrangerTest.java b/platform/testFramework/src/com/intellij/psi/codeStyle/arrangement/AbstractRearrangerTest.java index 04bb3c688946..fd07fe3b9570 100644 --- a/platform/testFramework/src/com/intellij/psi/codeStyle/arrangement/AbstractRearrangerTest.java +++ b/platform/testFramework/src/com/intellij/psi/codeStyle/arrangement/AbstractRearrangerTest.java @@ -116,11 +116,8 @@ public abstract class AbstractRearrangerTest extends LightPlatformCodeInsightFix @NotNull protected static StdArrangementMatchRule rule(@NotNull ArrangementSettingsToken... conditions) { - return rule(ContainerUtil.map(conditions, new Function() { - @Override - public ArrangementAtomMatchCondition fun(ArrangementSettingsToken it) { - return atom(it); - } + return rule(ContainerUtil.map(conditions, it -> { + return atom(it); })); } @@ -171,12 +168,9 @@ public abstract class AbstractRearrangerTest extends LightPlatformCodeInsightFix final FoldingModel foldingModel = myFixture.getEditor().getFoldingModel(); for (final FoldingInfo foldingInfo : info.foldings) { - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion region = foldingModel.addFoldRegion(foldingInfo.start, foldingInfo.end, foldingInfo.placeholder); - if (region != null) region.setExpanded(false); - } + foldingModel.runBatchFoldingOperation(() -> { + FoldRegion region = foldingModel.addFoldRegion(foldingInfo.start, foldingInfo.end, foldingInfo.placeholder); + if (region != null) region.setExpanded(false); }); } diff --git a/platform/testFramework/src/com/intellij/psi/formatter/FormatterTestCase.java b/platform/testFramework/src/com/intellij/psi/formatter/FormatterTestCase.java index 0048492d34a2..85970fcf4810 100644 --- a/platform/testFramework/src/com/intellij/psi/formatter/FormatterTestCase.java +++ b/platform/testFramework/src/com/intellij/psi/formatter/FormatterTestCase.java @@ -155,20 +155,11 @@ public abstract class FormatterTestCase extends LightPlatformTestCase { @SuppressWarnings({"UNUSED_SYMBOL"}) private void restoreFileContent(final PsiFile file, final String text) { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file); - document.replaceString(0, document.getTextLength(), text); - PsiDocumentManager.getInstance(getProject()).commitDocument(document); - } - }); - - } - }, "test", null); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file); + document.replaceString(0, document.getTextLength(), text); + PsiDocumentManager.getInstance(getProject()).commitDocument(document); + }), "test", null); } protected boolean doCheckDocumentUpdate() { @@ -192,29 +183,26 @@ public abstract class FormatterTestCase extends LightPlatformTestCase { editor = null; } - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - @Override - public void run() { - document.replaceString(0, document.getTextLength(), text); - PsiDocumentManager.getInstance(getProject()).commitDocument(document); - assertEquals(file.getText(), document.getText()); + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + document.replaceString(0, document.getTextLength(), text); + PsiDocumentManager.getInstance(getProject()).commitDocument(document); + assertEquals(file.getText(), document.getText()); - try { - if (doReformatRangeTest) { - CodeStyleManager.getInstance(getProject()) - .reformatRange(file, file.getTextRange().getStartOffset(), file.getTextRange().getEndOffset()); - } - else if (myTextRange != null) { - CodeStyleManager.getInstance(getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset()); - } - else { - CodeStyleManager.getInstance(getProject()) - .reformatText(file, file.getTextRange().getStartOffset(), file.getTextRange().getEndOffset()); - } + try { + if (doReformatRangeTest) { + CodeStyleManager.getInstance(getProject()) + .reformatRange(file, file.getTextRange().getStartOffset(), file.getTextRange().getEndOffset()); } - catch (IncorrectOperationException e) { - fail(); + else if (myTextRange != null) { + CodeStyleManager.getInstance(getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset()); } + else { + CodeStyleManager.getInstance(getProject()) + .reformatText(file, file.getTextRange().getStartOffset(), file.getTextRange().getEndOffset()); + } + } + catch (IncorrectOperationException e) { + fail(); } }); @@ -225,17 +213,9 @@ public abstract class FormatterTestCase extends LightPlatformTestCase { @SuppressWarnings({"UNUSED_SYMBOL"}) private void checkPsi(final PsiFile file, String textAfter) { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - performFormatting(file); - } - }); - } - }, "", ""); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + performFormatting(file); + }), "", ""); String fileText = file.getText(); @@ -381,31 +361,23 @@ public abstract class FormatterTestCase extends LightPlatformTestCase { final PsiFile file = PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, getFileType(fileName), StringUtil.convertLineSeparators(text), LocalTimeCounter.currentTime(), true); try { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - if (formatWithPsi) { - performFormatting(file); - } - else { - performFormattingWithDocument(file); - } - } - catch (Throwable e) { - //noinspection CallToPrintStackTrace - e.printStackTrace(); - failedFiles.add(subFile); - } - //noinspection UseOfSystemOutOrSystemErr - System.out.println(subFile.getPath() + ": finished"); - } - }); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + if (formatWithPsi) { + performFormatting(file); + } + else { + performFormattingWithDocument(file); + } } - }, "", null); + catch (Throwable e) { + //noinspection CallToPrintStackTrace + e.printStackTrace(); + failedFiles.add(subFile); + } + //noinspection UseOfSystemOutOrSystemErr + System.out.println(subFile.getPath() + ": finished"); + }), "", null); } finally { final VirtualFile virtualFile = file.getVirtualFile(); diff --git a/platform/testFramework/src/com/intellij/testFramework/BombedProgressIndicator.java b/platform/testFramework/src/com/intellij/testFramework/BombedProgressIndicator.java index eb230958352b..a71c6b157a9a 100644 --- a/platform/testFramework/src/com/intellij/testFramework/BombedProgressIndicator.java +++ b/platform/testFramework/src/com/intellij/testFramework/BombedProgressIndicator.java @@ -66,39 +66,30 @@ public class BombedProgressIndicator extends AbstractProgressIndicatorBase { // ProgressManager invokes indicator.checkCanceled only when there's at least one canceled indicator. So we have to create a mock one // on an unrelated thread and cancel it immediately. - Future future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final ProgressIndicatorBase mockIndicator = new ProgressIndicatorBase(); - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - mockIndicator.cancel(); - canStart.up(); - finished.waitFor(); - try { - ProgressManager.checkCanceled(); - TestCase.fail(); - } - catch (ProcessCanceledException ignored) { - } - } - }, mockIndicator); - } + Future future = ApplicationManager.getApplication().executeOnPooledThread(() -> { + final ProgressIndicatorBase mockIndicator = new ProgressIndicatorBase(); + ProgressManager.getInstance().runProcess(() -> { + mockIndicator.cancel(); + canStart.up(); + finished.waitFor(); + try { + ProgressManager.checkCanceled(); + TestCase.fail(); + } + catch (ProcessCanceledException ignored) { + } + }, mockIndicator); }); - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - canStart.waitFor(); - try { - runnable.run(); - } - catch (ProcessCanceledException ignore) { - } - finally { - finished.up(); - } + ProgressManager.getInstance().runProcess(() -> { + canStart.waitFor(); + try { + runnable.run(); + } + catch (ProcessCanceledException ignore) { + } + finally { + finished.up(); } }, this); diff --git a/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java index 3ab1b4fb92ae..33dd5fbb1aa5 100644 --- a/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java @@ -444,14 +444,11 @@ public class EditorTestUtil { public static FoldRegion addFoldRegion(@NotNull Editor editor, final int startOffset, final int endOffset, final String placeholder, final boolean collapse) { final FoldingModel foldingModel = editor.getFoldingModel(); final Ref ref = new Ref(); - foldingModel.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - FoldRegion region = foldingModel.addFoldRegion(startOffset, endOffset, placeholder); - assertNotNull(region); - region.setExpanded(!collapse); - ref.set(region); - } + foldingModel.runBatchFoldingOperation(() -> { + FoldRegion region = foldingModel.addFoldRegion(startOffset, endOffset, placeholder); + assertNotNull(region); + region.setExpanded(!collapse); + ref.set(region); }); return ref.get(); } diff --git a/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java b/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java index b2100962ec23..f2f637b631d0 100644 --- a/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java +++ b/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java @@ -190,12 +190,7 @@ public class ExpectedHighlightingData { assert element != null : value; TextRange range = new TextRange(startOffset, endOffset); final String tooltip = value.getLineMarkerTooltip(); - LineMarkerInfo markerInfo = new LineMarkerInfo(element, range, null, value.updatePass, new Function() { - @Override - public String fun(PsiElement e) { - return tooltip; - } - }, null, GutterIconRenderer.Alignment.RIGHT); + LineMarkerInfo markerInfo = new LineMarkerInfo(element, range, null, value.updatePass, e -> tooltip, null, GutterIconRenderer.Alignment.RIGHT); entry.setValue(markerInfo); } } @@ -475,18 +470,16 @@ public class ExpectedHighlightingData { public static String composeText(final Map types, Collection infos, String text) { // filter highlighting data and map each highlighting to a tag name - List> list = ContainerUtil.mapNotNull(infos, new NullableFunction>() { - @Override - public Pair fun(HighlightInfo info) { - for (Map.Entry entry : types.entrySet()) { - final ExpectedHighlightingSet set = entry.getValue(); - if (set.enabled && set.severity == info.getSeverity() && set.endOfLine == info.isAfterEndOfLine()) { - return Pair.create(entry.getKey(), info); - } - } - return null; - } - }); + List> list = ContainerUtil.mapNotNull(infos, + (NullableFunction>)info -> { + for (Map.Entry entry : types.entrySet()) { + final ExpectedHighlightingSet set = entry.getValue(); + if (set.enabled && set.severity == info.getSeverity() && set.endOfLine == info.isAfterEndOfLine()) { + return Pair.create(entry.getKey(), info); + } + } + return null; + }); boolean showAttributesKeys = false; for (ExpectedHighlightingSet eachSet : types.values()) { @@ -499,29 +492,26 @@ public class ExpectedHighlightingData { } // sort filtered highlighting data by end offset in descending order - Collections.sort(list, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - HighlightInfo i1 = o1.second; - HighlightInfo i2 = o2.second; + Collections.sort(list, (o1, o2) -> { + HighlightInfo i1 = o1.second; + HighlightInfo i2 = o2.second; - int byEnds = i2.endOffset - i1.endOffset; - if (byEnds != 0) return byEnds; + int byEnds = i2.endOffset - i1.endOffset; + if (byEnds != 0) return byEnds; - if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) { - int byStarts = i1.startOffset - i2.startOffset; - if (byStarts != 0) return byStarts; - } - else { - int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine()); - if (byEOL != 0) return byEOL; - } - - int bySeverity = i2.getSeverity().compareTo(i1.getSeverity()); - if (bySeverity != 0) return bySeverity; - - return Comparing.compare(i1.getDescription(), i2.getDescription()); + if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) { + int byStarts = i1.startOffset - i2.startOffset; + if (byStarts != 0) return byStarts; } + else { + int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine()); + if (byEOL != 0) return byEOL; + } + + int bySeverity = i2.getSeverity().compareTo(i1.getSeverity()); + if (bySeverity != 0) return bySeverity; + + return Comparing.compare(i1.getDescription(), i2.getDescription()); }); // combine highlighting data with original text diff --git a/platform/testFramework/src/com/intellij/testFramework/FileEditorManagerTestCase.java b/platform/testFramework/src/com/intellij/testFramework/FileEditorManagerTestCase.java index bf087b9071b0..732cf900ccca 100644 --- a/platform/testFramework/src/com/intellij/testFramework/FileEditorManagerTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/FileEditorManagerTestCase.java @@ -102,12 +102,7 @@ public abstract class FileEditorManagerTestCase extends LightPlatformCodeInsight myManager.loadState(rootElement); - Future future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - myManager.getMainSplitters().openFiles(); - } - }); + Future future = ApplicationManager.getApplication().executeOnPooledThread(() -> myManager.getMainSplitters().openFiles()); while (true) { try { future.get(100, TimeUnit.MILLISECONDS); diff --git a/platform/testFramework/src/com/intellij/testFramework/FileStructureTestFixture.java b/platform/testFramework/src/com/intellij/testFramework/FileStructureTestFixture.java index 43caa794a149..e49bdce7d12b 100644 --- a/platform/testFramework/src/com/intellij/testFramework/FileStructureTestFixture.java +++ b/platform/testFramework/src/com/intellij/testFramework/FileStructureTestFixture.java @@ -47,16 +47,13 @@ public class FileStructureTestFixture implements Disposable { public FilteringTreeStructure.FilteringNode update() { final Ref nodeRef = new Ref(); final FileStructurePopup popup = getPopup(); - popup.getTreeBuilder().refilter().doWhenProcessed(new Runnable() { - @Override - public void run() { - getStructure().rebuild(); - updateTree(); - getBuilder().updateFromRoot(); - TreeUtil.expandAll(getTree()); - nodeRef.set(popup.selectPsiElement(popup.getCurrentElement(myFile))); - getBuilder().getUi().select(nodeRef.get(), null); - } + popup.getTreeBuilder().refilter().doWhenProcessed(() -> { + getStructure().rebuild(); + updateTree(); + getBuilder().updateFromRoot(); + TreeUtil.expandAll(getTree()); + nodeRef.set(popup.selectPsiElement(popup.getCurrentElement(myFile))); + getBuilder().getUi().select(nodeRef.get(), null); }); return nodeRef.get(); } diff --git a/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java b/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java index ee7ffa897cdc..3fd578b63a6d 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java +++ b/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java @@ -57,18 +57,15 @@ public class LeakHunter { final BackLink backLink = toVisit.pullFirst(); Object root = backLink.value; if (!visited.add(System.identityHashCode(root))) continue; - DebugReflectionUtil.processStronglyReferencedValues(root, new PairProcessor() { - @Override - public boolean process(Object value, Field field) { - Class valueClass = value.getClass(); - if (lookFor.isAssignableFrom(valueClass) && isReallyLeak(value)) { - leakProcessor.process(new BackLink(value, field, backLink)); - } - else { - toVisit.addLast(new BackLink(value, field, backLink)); - } - return true; + DebugReflectionUtil.processStronglyReferencedValues(root, (value, field) -> { + Class valueClass = value.getClass(); + if (lookFor.isAssignableFrom(valueClass) && isReallyLeak(value)) { + leakProcessor.process(new BackLink(value, field, backLink)); } + else { + toVisit.addLast(new BackLink(value, field, backLink)); + } + return true; }); } } @@ -84,12 +81,7 @@ public class LeakHunter { private static final Key REPORTED_LEAKED = Key.create("REPORTED_LEAKED"); @TestOnly public static void checkProjectLeak() throws Exception { - Processor isReallyLeak = new Processor() { - @Override - public boolean process(Project project) { - return !project.isDefault() && !((ProjectImpl)project).isLight(); - } - }; + Processor isReallyLeak = project -> !project.isDefault() && !((ProjectImpl)project).isLight(); Collection roots = new ArrayList(allRoots()); ClassLoader classLoader = LeakHunter.class.getClassLoader(); Vector allLoadedClasses = ReflectionUtil.getField(classLoader.getClass(), classLoader, Vector.class, "classes"); diff --git a/platform/testFramework/src/com/intellij/testFramework/ParsingTestCase.java b/platform/testFramework/src/com/intellij/testFramework/ParsingTestCase.java index c1d98ef5b45e..4e7cb289c73b 100644 --- a/platform/testFramework/src/com/intellij/testFramework/ParsingTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/ParsingTestCase.java @@ -114,12 +114,8 @@ public abstract class ParsingTestCase extends PlatformLiteFixture { registerComponentInstance(appContainer, SchemesManagerFactory.class, new MockSchemesManagerFactory()); final MockEditorFactory editorFactory = new MockEditorFactory(); registerComponentInstance(appContainer, EditorFactory.class, editorFactory); - registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(new Function() { - @Override - public Document fun(CharSequence charSequence) { - return editorFactory.createDocument(charSequence); - } - }, FileDocumentManagerImpl.HARD_REF_TO_DOCUMENT_KEY)); + registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl( + charSequence -> editorFactory.createDocument(charSequence), FileDocumentManagerImpl.HARD_REF_TO_DOCUMENT_KEY)); registerComponentInstance(appContainer, PsiDocumentManager.class, new MockPsiDocumentManager()); registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl()); diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index 9775eb241b08..a880f6120b56 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -259,22 +259,7 @@ public class PlatformTestUtil { final AtomicBoolean invoked = new AtomicBoolean(); final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); - alarm.addRequest(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - alarm.addRequest(new Runnable() { - @Override - public void run() { - invoked.set(true); - } - }, delay); - } - }); - } - }, delay); + alarm.addRequest(() -> ApplicationManager.getApplication().invokeLater(() -> alarm.addRequest(() -> invoked.set(true), delay)), delay); UIUtil.dispatchAllInvocationEvents(); @@ -802,12 +787,9 @@ public class PlatformTestUtil { Assert.assertNotNull(tempDirectory1.toString(), dirAfter); final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); Assert.assertNotNull(tempDirectory2.toString(), dirBefore); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - dirAfter.refresh(false, true); - dirBefore.refresh(false, true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + dirAfter.refresh(false, true); + dirBefore.refresh(false, true); }); assertDirectoriesEqual(dirAfter, dirBefore); } @@ -847,13 +829,10 @@ public class PlatformTestUtil { public static Comparator createComparator(final Queryable.PrintInfo printInfo) { - return new Comparator() { - @Override - public int compare(final AbstractTreeNode o1, final AbstractTreeNode o2) { - String displayText1 = o1.toTestString(printInfo); - String displayText2 = o2.toTestString(printInfo); - return Comparing.compare(displayText1, displayText2); - } + return (o1, o2) -> { + String displayText1 = o1.toTestString(printInfo); + String displayText2 = o2.toTestString(printInfo); + return Comparing.compare(displayText1, displayText2); }; } diff --git a/platform/testFramework/src/com/intellij/testFramework/TestRunnerUtil.java b/platform/testFramework/src/com/intellij/testFramework/TestRunnerUtil.java index b3f422507163..3577fbdcd6d1 100644 --- a/platform/testFramework/src/com/intellij/testFramework/TestRunnerUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/TestRunnerUtil.java @@ -59,12 +59,7 @@ public class TestRunnerUtil { // in JDK 1.6 java.awt.EventQueue.push() causes slow painful death of current EDT // so we have to wait through its agony to termination try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - IdeEventQueue.getInstance(); - } - }); + SwingUtilities.invokeAndWait(() -> IdeEventQueue.getInstance()); SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); } diff --git a/platform/testFramework/src/com/intellij/testFramework/VfsTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/VfsTestUtil.java index 0d7de9d4753e..759af32d0f87 100644 --- a/platform/testFramework/src/com/intellij/testFramework/VfsTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/VfsTestUtil.java @@ -107,15 +107,12 @@ public class VfsTestUtil { } public static void clearContent(@NotNull final VirtualFile file) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - VfsUtil.saveText(file, ""); - } - catch (IOException e) { - throw new RuntimeException(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + VfsUtil.saveText(file, ""); + } + catch (IOException e) { + throw new RuntimeException(e); } }); } diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java index 7d07c15d161f..e542c08fe017 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java @@ -128,12 +128,7 @@ import java.util.*; */ @SuppressWarnings({"TestMethodWithIncorrectSignature", "JUnitTestCaseWithNoTests", "JUnitTestClassNamingConvention", "TestOnlyProblems"}) public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsightTestFixture { - private static final Function INTENTION_NAME_FUN = new Function() { - @Override - public String fun(final IntentionAction intentionAction) { - return "\"" + intentionAction.getText() + "\""; - } - }; + private static final Function INTENTION_NAME_FUN = intentionAction -> "\"" + intentionAction.getText() + "\""; private static final String START_FOLD = ""; private static final String END_FOLD = ""; @@ -242,12 +237,9 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig } private static void removeDuplicatedRangesForInjected(@NotNull List infos) { - Collections.sort(infos, new Comparator() { - @Override - public int compare(@NotNull HighlightInfo o1, @NotNull HighlightInfo o2) { - final int i = o2.startOffset - o1.startOffset; - return i != 0 ? i : o1.getSeverity().myVal - o2.getSeverity().myVal; - } + Collections.sort(infos, (o1, o2) -> { + final int i = o2.startOffset - o1.startOffset; + return i != 0 ? i : o1.getSeverity().myVal - o2.getSeverity().myVal; }); HighlightInfo prevInfo = null; for (Iterator it = infos.iterator(); it.hasNext();) { @@ -538,17 +530,14 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig final boolean checkWeakWarnings, @NotNull VirtualFile[] files) { final List> datas = - ContainerUtil.map2List(files, new Function>() { - @Override - public Trinity fun(final VirtualFile file) { - final PsiFile psiFile = myPsiManager.findFile(file); - Assert.assertNotNull(psiFile); - final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile); - Assert.assertNotNull(document); - ExpectedHighlightingData data = new ExpectedHighlightingData(document, checkWarnings, checkWeakWarnings, checkInfos, psiFile); - data.init(); - return Trinity.create(psiFile, createEditor(file), data); - } + ContainerUtil.map2List(files, file -> { + final PsiFile psiFile = myPsiManager.findFile(file); + Assert.assertNotNull(psiFile); + final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile); + Assert.assertNotNull(document); + ExpectedHighlightingData data = new ExpectedHighlightingData(document, checkWarnings, checkWeakWarnings, checkInfos, psiFile); + data.init(); + return Trinity.create(psiFile, createEditor(file), data); }); long elapsed = 0; for (Trinity trinity : datas) { @@ -723,11 +712,8 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig List intentions = getAvailableIntentions(filePaths); IntentionAction action = CodeInsightTestUtil.findIntentionByText(intentions, intentionName); if (action == null) { - System.out.println(intentionName + " not found among " + StringUtil.join(intentions, new Function() { - @Override - public String fun(IntentionAction action) { - return action.getText(); - } + System.out.println(intentionName + " not found among " + StringUtil.join(intentions, action1 -> { + return action1.getText(); }, ",")); } return action; @@ -800,22 +786,15 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig final LookupElement[] elements = getLookupElements(); if (elements == null) return null; - return ContainerUtil.map(elements, new Function() { - @Override - public String fun(final LookupElement lookupItem) { - return lookupItem.getLookupString(); - } + return ContainerUtil.map(elements, lookupItem -> { + return lookupItem.getLookupString(); }); } @Override public void finishLookup(final char completionChar) { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ((LookupImpl)LookupManager.getActiveLookup(getEditor())).finishLookup(completionChar); - } - }, null, null); + CommandProcessor.getInstance().executeCommand(getProject(), + () -> ((LookupImpl)LookupManager.getActiveLookup(getEditor())).finishLookup(completionChar), null, null); } @Override @@ -940,13 +919,10 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig } } - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().setCurrentCommandGroupId(myEditor.getDocument()); - ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, getEditorDataContext()); - actionManager.getTypedAction().actionPerformed(getEditor(), c, getEditorDataContext()); - } + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + CommandProcessor.getInstance().setCurrentCommandGroupId(myEditor.getDocument()); + ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, getEditorDataContext()); + actionManager.getTypedAction().actionPerformed(getEditor(), c, getEditorDataContext()); }, null, DocCommandGroupId.noneGroupId(myEditor.getDocument())); } }); diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/ModuleFixtureBuilderImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/ModuleFixtureBuilderImpl.java index d9627f61e806..96b538a2d9c4 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/ModuleFixtureBuilderImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/ModuleFixtureBuilderImpl.java @@ -111,12 +111,9 @@ public abstract class ModuleFixtureBuilderImpl implemen Module buildModule() { final Module[] module = {null}; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - module[0] = createModule(); - initModule(module[0]); - } + ApplicationManager.getApplication().runWriteAction(() -> { + module[0] = createModule(); + initModule(module[0]); }); return module[0]; diff --git a/platform/testFramework/testSrc/com/intellij/openapi/keymap/KeymapsTestCase.java b/platform/testFramework/testSrc/com/intellij/openapi/keymap/KeymapsTestCase.java index 5aabe2930c83..a23d985d2c69 100644 --- a/platform/testFramework/testSrc/com/intellij/openapi/keymap/KeymapsTestCase.java +++ b/platform/testFramework/testSrc/com/intellij/openapi/keymap/KeymapsTestCase.java @@ -431,12 +431,7 @@ public abstract class KeymapsTestCase extends PlatformTestCase { } } List sorted = new ArrayList(shortcuts); - Collections.sort(sorted, new Comparator() { - @Override - public int compare(Shortcut o1, Shortcut o2) { - return getText(o1).compareTo(getText(o2)); - } - }); + Collections.sort(sorted, (o1, o2) -> getText(o1).compareTo(getText(o2))); if (OUTPUT_TEST_DATA) { System.out.println("put(\"" + keymap.getName() + "\", new String[][] {"); @@ -583,11 +578,8 @@ public abstract class KeymapsTestCase extends PlatformTestCase { Map>> duplicates = getKnownDuplicates(); THashSet allMaps = - new THashSet(ContainerUtil.map(KeymapManagerEx.getInstanceEx().getAllKeymaps(), new Function() { - @Override - public String fun(Keymap keymap) { - return keymap.getName(); - } + new THashSet(ContainerUtil.map(KeymapManagerEx.getInstanceEx().getAllKeymaps(), keymap -> { + return keymap.getName(); })); TestCase.assertTrue("Modify 'known duplicates list' test data. Keymaps were added: " + ContainerUtil.subtract(allMaps, duplicates.keySet()), @@ -650,11 +642,8 @@ public abstract class KeymapsTestCase extends PlatformTestCase { .append(". Please modify known duplicates list:\n"); for (Shortcut eachShortcut : keymapToShortcuts.getValue()) { message.append(" { ").append(StringUtil.wrapWithDoubleQuote(getText(eachShortcut))).append(",\t") - .append(StringUtil.join(keymap.getActionIds(eachShortcut), new Function() { - @Override - public String fun(String s) { - return StringUtil.wrapWithDoubleQuote(s); - } + .append(StringUtil.join(keymap.getActionIds(eachShortcut), s -> { + return StringUtil.wrapWithDoubleQuote(s); }, ", ")) .append("},\n"); } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/CompositePrintable.java b/platform/testRunner/src/com/intellij/execution/testframework/CompositePrintable.java index 8fef9564b9bf..fc0760797667 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/CompositePrintable.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/CompositePrintable.java @@ -141,17 +141,15 @@ public class CompositePrintable implements Printable, Disposable { public void printFromFrameworkOutputFile(final Printer console) { if (myFrameworkOutputFile != null) { - final Runnable runnable = new Runnable() { - public void run() { - final File inputFile = new File(myFrameworkOutputFile); - if (inputFile.exists()) { - try { - final String fileText = FileUtil.loadFile(inputFile); - console.print(fileText, ConsoleViewContentType.NORMAL_OUTPUT); - } - catch (IOException e) { - LOG.error(e); - } + final Runnable runnable = () -> { + final File inputFile = new File(myFrameworkOutputFile); + if (inputFile.exists()) { + try { + final String fileText = FileUtil.loadFile(inputFile); + console.print(fileText, ConsoleViewContentType.NORMAL_OUTPUT); + } + catch (IOException e) { + LOG.error(e); } } }; @@ -201,48 +199,45 @@ public class CompositePrintable implements Printable, Disposable { if (printables.isEmpty()) return; final ArrayList currentPrintables = new ArrayList(printables); //move out from AWT thread - final Runnable request = new Runnable() { - @Override - public void run() { - synchronized (myFileLock) { - for (final Printable printable : currentPrintables) { - printable.printOn(myPrinter); - } - myPrinter.close(); + final Runnable request = () -> { + synchronized (myFileLock) { + for (final Printable printable : currentPrintables) { + printable.printOn(myPrinter); } - if (myOutputFile != null && new File(myOutputFile).exists()) { + myPrinter.close(); + } + if (myOutputFile != null && new File(myOutputFile).exists()) { + try { + final PrintStream printStream = new PrintStream(new FileOutputStream(new File(myOutputFile), true)); try { - final PrintStream printStream = new PrintStream(new FileOutputStream(new File(myOutputFile), true)); - try { - for (Printable currentPrintable : currentPrintables) { - currentPrintable.printOn(new Printer() { - @Override - public void print(String text, ConsoleViewContentType contentType) { - if (contentType != ConsoleViewContentType.SYSTEM_OUTPUT) { - printStream.print(text); - } - } - - @Override - public void printHyperlink(String text, HyperlinkInfo info) { + for (Printable currentPrintable : currentPrintables) { + currentPrintable.printOn(new Printer() { + @Override + public void print(String text, ConsoleViewContentType contentType) { + if (contentType != ConsoleViewContentType.SYSTEM_OUTPUT) { printStream.print(text); } - - @Override - public void onNewAvailable(@NotNull Printable printable) {} - @Override - public void mark() {} - }); - } - } - finally { - printStream.close(); + } + + @Override + public void printHyperlink(String text, HyperlinkInfo info) { + printStream.print(text); + } + + @Override + public void onNewAvailable(@NotNull Printable printable) {} + @Override + public void mark() {} + }); } } - catch (IOException e) { - LOG.error(e); + finally { + printStream.close(); } } + catch (IOException e) { + LOG.error(e); + } } }; invokeInAlarm(request, ApplicationManager.getApplication().isUnitTestMode()); @@ -253,17 +248,14 @@ public class CompositePrintable implements Printable, Disposable { } public void printOn(final Printer console, final List printables, final boolean skipFileContent) { - final Runnable request = new Runnable() { - @Override - public void run() { - if (skipFileContent) { - readFileContentAndPrint(console, null, printables); - return; - } - final File file = hasOutput() ? getFile() : null; - synchronized (myFileLock) { - readFileContentAndPrint(console, file, printables); - } + final Runnable request = () -> { + if (skipFileContent) { + readFileContentAndPrint(console, null, printables); + return; + } + final File file = hasOutput() ? getFile() : null; + synchronized (myFileLock) { + readFileContentAndPrint(console, file, printables); } }; invokeInAlarm(request); diff --git a/platform/testRunner/src/com/intellij/execution/testframework/actions/AbstractRerunFailedTestsAction.java b/platform/testRunner/src/com/intellij/execution/testframework/actions/AbstractRerunFailedTestsAction.java index d64ec0f9eebb..c7dcf1065334 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/actions/AbstractRerunFailedTestsAction.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/actions/AbstractRerunFailedTestsAction.java @@ -198,14 +198,11 @@ public class AbstractRerunFailedTestsAction extends AnAction implements AnAction .setMovable(false) .setResizable(false) .setRequestFocus(true) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof Executor) { - //noinspection ConstantConditions - performAction(environmentBuilder.runner(availableRunners.get(value)).executor((Executor)value)); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof Executor) { + //noinspection ConstantConditions + performAction(environmentBuilder.runner(availableRunners.get(value)).executor((Executor)value)); } }).createPopup().showUnderneathOf(event.getComponent()); } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/autotest/AutoTestManager.java b/platform/testRunner/src/com/intellij/execution/testframework/autotest/AutoTestManager.java index fc00a8e667e8..2ec4c53f5bc9 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/autotest/AutoTestManager.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/autotest/AutoTestManager.java @@ -84,12 +84,7 @@ public class AutoTestManager implements PersistentStateComponent() { - @Override - public void consume(Integer modificationStamp) { - restartAllAutoTests(modificationStamp); - } - }, new Condition() { + return new DelayedDocumentWatcher(myProject, myDelayMillis, modificationStamp -> restartAllAutoTests(modificationStamp), new Condition() { @Override public boolean value(VirtualFile file) { if (ScratchFileService.getInstance().getRootType(file) != null) { @@ -199,12 +194,9 @@ public class AutoTestManager implements PersistentStateComponent { + if (isAutoTestEnabledForDescriptor(descriptor) && documentWatcher.isUpToDate(modificationStamp)) { + restart(descriptor); } }, ModalityState.any()); } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/export/ExportTestResultsAction.java b/platform/testRunner/src/com/intellij/execution/testframework/export/ExportTestResultsAction.java index 331ee9e8791b..0a7f43d2c3e9 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/export/ExportTestResultsAction.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/export/ExportTestResultsAction.java @@ -260,15 +260,12 @@ public class ExportTestResultsAction extends DumbAwareAction { } private static void openEditorOrBrowser(final VirtualFile result, final Project project, final boolean editor) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (editor) { - FileEditorManager.getInstance(project).openFile(result, true); - } - else { - BrowserUtil.browse(result); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (editor) { + FileEditorManager.getInstance(project).openFile(result, true); + } + else { + BrowserUtil.browse(result); } }); } @@ -316,12 +313,10 @@ public class ExportTestResultsAction extends DumbAwareAction { } private void showBalloon(final Project project, final MessageType type, final String text, @Nullable final HyperlinkListener listener) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (project.isDisposed()) return; - if (ToolWindowManager.getInstance(project).getToolWindow(myToolWindowId) != null) { - ToolWindowManager.getInstance(project).notifyByBalloon(myToolWindowId, type, text, null, listener); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; + if (ToolWindowManager.getInstance(project).getToolWindow(myToolWindowId) != null) { + ToolWindowManager.getInstance(project).notifyByBalloon(myToolWindowId, type, text, null, listener); } }); } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/export/TestResultsXmlFormatter.java b/platform/testRunner/src/com/intellij/execution/testframework/export/TestResultsXmlFormatter.java index 92d65eb0bbc7..b4e29cb0b2a5 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/export/TestResultsXmlFormatter.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/export/TestResultsXmlFormatter.java @@ -95,13 +95,10 @@ public class TestResultsXmlFormatter { private void execute() throws SAXException { myResultHandler.startDocument(); - TreeMap counts = new TreeMap(new Comparator() { - @Override - public int compare(String o1, String o2) { - if (TOTAL_STATUS.equals(o1) && !TOTAL_STATUS.equals(o2)) return -1; - if (TOTAL_STATUS.equals(o2) && !TOTAL_STATUS.equals(o1)) return 1; - return o1.compareTo(o2); - } + TreeMap counts = new TreeMap((o1, o2) -> { + if (TOTAL_STATUS.equals(o1) && !TOTAL_STATUS.equals(o2)) return -1; + if (TOTAL_STATUS.equals(o2) && !TOTAL_STATUS.equals(o1)) return 1; + return o1.compareTo(o2); }); for (AbstractTestProxy node : myTestRoot.getAllTests()) { if (!node.isLeaf()) continue; diff --git a/platform/testRunner/src/com/intellij/execution/testframework/ui/AbstractTestTreeBuilder.java b/platform/testRunner/src/com/intellij/execution/testframework/ui/AbstractTestTreeBuilder.java index 8519919b0f14..62dcbc4eb035 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/ui/AbstractTestTreeBuilder.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/ui/AbstractTestTreeBuilder.java @@ -79,19 +79,16 @@ public abstract class AbstractTestTreeBuilder extends AbstractTreeBuilder { setTestsComparator(TestConsoleProperties.SORT_ALPHABETICALLY.value(properties)); } else { - setNodeDescriptorComparator(new Comparator() { - @Override - public int compare(NodeDescriptor o1, NodeDescriptor o2) { - if (o1.getParentDescriptor() == o2.getParentDescriptor() && - o1 instanceof BaseTestProxyNodeDescriptor && - o2 instanceof BaseTestProxyNodeDescriptor) { - final Long d1 = ((BaseTestProxyNodeDescriptor)o1).getElement().getDuration(); - final Long d2 = ((BaseTestProxyNodeDescriptor)o2).getElement().getDuration(); - return Comparing.compare(d2, d1); - } - return 0; - } - }); + setNodeDescriptorComparator((o1, o2) -> { + if (o1.getParentDescriptor() == o2.getParentDescriptor() && + o1 instanceof BaseTestProxyNodeDescriptor && + o2 instanceof BaseTestProxyNodeDescriptor) { + final Long d1 = ((BaseTestProxyNodeDescriptor)o1).getElement().getDuration(); + final Long d2 = ((BaseTestProxyNodeDescriptor)o2).getElement().getDuration(); + return Comparing.compare(d2, d1); + } + return 0; + }); } queueUpdate(); } diff --git a/platform/testRunner/src/com/intellij/execution/testframework/ui/TestResultsPanel.java b/platform/testRunner/src/com/intellij/execution/testframework/ui/TestResultsPanel.java index 9abeb1460423..8ef23dc537d7 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/ui/TestResultsPanel.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/ui/TestResultsPanel.java @@ -99,13 +99,7 @@ public abstract class TestResultsPanel extends JPanel implements Disposable, Dat mySplitterDefaultProportion, splitVertically); if (mySplitter instanceof OnePixelSplitter) { - ((OnePixelSplitter)mySplitter).setBlindZone(new Producer() { - @Nullable - @Override - public Insets produce() { - return new Insets(myToolbarPanel.getHeight(), 0, 0, 0); - } - }); + ((OnePixelSplitter)mySplitter).setBlindZone(() -> new Insets(myToolbarPanel.getHeight(), 0, 0, 0)); } Disposer.register(this, new Disposable(){ @Override diff --git a/platform/testRunner/src/com/intellij/execution/testframework/ui/TestsOutputConsolePrinter.java b/platform/testRunner/src/com/intellij/execution/testframework/ui/TestsOutputConsolePrinter.java index 4f5b0cb2e3a9..b238ad25c014 100644 --- a/platform/testRunner/src/com/intellij/execution/testframework/ui/TestsOutputConsolePrinter.java +++ b/platform/testRunner/src/com/intellij/execution/testframework/ui/TestsOutputConsolePrinter.java @@ -89,11 +89,7 @@ public class TestsOutputConsolePrinter implements Printer, Disposable { myCurrentTest.setPrinter(null); } myMarkOffset = 0; - final Runnable clearRunnable = new Runnable() { - public void run() { - myConsole.clear(); - } - }; + final Runnable clearRunnable = () -> myConsole.clear(); if (test == null) { myCurrentTest = null; CompositePrintable.invokeInAlarm(clearRunnable); @@ -101,12 +97,7 @@ public class TestsOutputConsolePrinter implements Printer, Disposable { } myCurrentTest = test; myCurrentTest.setPrinter(this); - final Runnable scrollRunnable = new Runnable() { - @Override - public void run() { - scrollToBeginning(); - } - }; + final Runnable scrollRunnable = () -> scrollToBeginning(); final AbstractTestProxy currentProxyOrRoot = getCurrentProxyOrRoot(); CompositePrintable.invokeInAlarm(clearRunnable); currentProxyOrRoot.printOn(this); @@ -145,13 +136,11 @@ public class TestsOutputConsolePrinter implements Printer, Disposable { } protected void scrollToBeginning() { - myConsole.performWhenNoDeferredOutput(new Runnable() { - public void run() { - final AbstractTestProxy currentProxyOrRoot = getCurrentProxyOrRoot(); - if (currentProxyOrRoot != null && !currentProxyOrRoot.isInProgress()) { - //do not scroll to any mark during run - myConsole.scrollTo(myMarkOffset); - } + myConsole.performWhenNoDeferredOutput(() -> { + final AbstractTestProxy currentProxyOrRoot = getCurrentProxyOrRoot(); + if (currentProxyOrRoot != null && !currentProxyOrRoot.isInProgress()) { + //do not scroll to any mark during run + myConsole.scrollTo(myMarkOffset); } }); } diff --git a/platform/usageView/src/com/intellij/usages/ChunkExtractor.java b/platform/usageView/src/com/intellij/usages/ChunkExtractor.java index 80e1e942f7d3..01e86c7e195c 100644 --- a/platform/usageView/src/com/intellij/usages/ChunkExtractor.java +++ b/platform/usageView/src/com/intellij/usages/ChunkExtractor.java @@ -245,25 +245,22 @@ public class ChunkExtractor { } final int[] lastOffset = {hiStart}; - usageInfo2UsageAdapter.processRangeMarkers(new Processor() { - @Override - public boolean process(Segment segment) { - int usageStart = segment.getStartOffset(); - int usageEnd = segment.getEndOffset(); - if (rangeIntersect(lastOffset[0], hiEnd, usageStart, usageEnd)) { - addChunk(chars, lastOffset[0], Math.max(lastOffset[0], usageStart), originalAttrs, false, null, result); + usageInfo2UsageAdapter.processRangeMarkers(segment -> { + int usageStart = segment.getStartOffset(); + int usageEnd = segment.getEndOffset(); + if (rangeIntersect(lastOffset[0], hiEnd, usageStart, usageEnd)) { + addChunk(chars, lastOffset[0], Math.max(lastOffset[0], usageStart), originalAttrs, false, null, result); - UsageType usageType = isHighlightedAsString(tokenHighlights) - ? UsageType.LITERAL_USAGE - : isHighlightedAsComment(tokenHighlights) ? UsageType.COMMENT_USAGE : null; - addChunk(chars, Math.max(lastOffset[0], usageStart), Math.min(hiEnd, usageEnd), originalAttrs, selectUsageWithBold, usageType, result); - lastOffset[0] = usageEnd; - if (usageEnd > hiEnd) { - return false; - } + UsageType usageType = isHighlightedAsString(tokenHighlights) + ? UsageType.LITERAL_USAGE + : isHighlightedAsComment(tokenHighlights) ? UsageType.COMMENT_USAGE : null; + addChunk(chars, Math.max(lastOffset[0], usageStart), Math.min(hiEnd, usageEnd), originalAttrs, selectUsageWithBold, usageType, result); + lastOffset[0] = usageEnd; + if (usageEnd > hiEnd) { + return false; } - return true; } + return true; }); if (lastOffset[0] < hiEnd) { addChunk(chars, lastOffset[0], hiEnd, originalAttrs, false, null, result); diff --git a/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java b/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java index db5aa7917890..5e03aed82461 100644 --- a/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java +++ b/platform/usageView/src/com/intellij/usages/UsageInfo2UsageAdapter.java @@ -55,19 +55,8 @@ public class UsageInfo2UsageAdapter implements UsageInModule, UsageInLibrary, UsageInFile, PsiElementUsage, MergeableUsage, Comparable, RenameableUsage, TypeSafeDataProvider, UsagePresentation { - public static final NotNullFunction CONVERTER = new NotNullFunction() { - @Override - @NotNull - public Usage fun(UsageInfo usageInfo) { - return new UsageInfo2UsageAdapter(usageInfo); - } - }; - private static final Comparator BY_NAVIGATION_OFFSET = new Comparator() { - @Override - public int compare(UsageInfo o1, UsageInfo o2) { - return o1.getNavigationOffset() - o2.getNavigationOffset(); - } - }; + public static final NotNullFunction CONVERTER = usageInfo -> new UsageInfo2UsageAdapter(usageInfo); + private static final Comparator BY_NAVIGATION_OFFSET = (o1, o2) -> o1.getNavigationOffset() - o2.getNavigationOffset(); private final UsageInfo myUsageInfo; @NotNull diff --git a/platform/usageView/src/com/intellij/usages/UsageInfoSearcherAdapter.java b/platform/usageView/src/com/intellij/usages/UsageInfoSearcherAdapter.java index 36544a632602..9ed8b4aa961d 100644 --- a/platform/usageView/src/com/intellij/usages/UsageInfoSearcherAdapter.java +++ b/platform/usageView/src/com/intellij/usages/UsageInfoSearcherAdapter.java @@ -29,15 +29,12 @@ public abstract class UsageInfoSearcherAdapter implements UsageSearcher { protected void processUsages(final @NotNull Processor processor, @NotNull Project project) { final Ref refUsages = new Ref(); final Ref dumbModeOccurred = new Ref(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - try { - refUsages.set(findUsages()); - } - catch (IndexNotReadyException e) { - dumbModeOccurred.set(true); - } + ApplicationManager.getApplication().runReadAction(() -> { + try { + refUsages.set(findUsages()); + } + catch (IndexNotReadyException e) { + dumbModeOccurred.set(true); } }); if (!dumbModeOccurred.isNull()) { @@ -52,11 +49,8 @@ public abstract class UsageInfoSearcherAdapter implements UsageSearcher { }); for (final Usage usage : usages) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - processor.process(usage); - } + ApplicationManager.getApplication().runReadAction(() -> { + processor.process(usage); }); } } diff --git a/platform/usageView/src/com/intellij/usages/UsageLimitUtil.java b/platform/usageView/src/com/intellij/usages/UsageLimitUtil.java index fbee3a7b9316..d1a043c21825 100644 --- a/platform/usageView/src/com/intellij/usages/UsageLimitUtil.java +++ b/platform/usageView/src/com/intellij/usages/UsageLimitUtil.java @@ -63,12 +63,7 @@ public class UsageLimitUtil { private static int runOrInvokeAndWait(@NotNull final Computable f) { final int[] answer = new int[1]; try { - GuiUtils.runOrInvokeAndWait(new Runnable() { - @Override - public void run() { - answer[0] = f.compute(); - } - }); + GuiUtils.runOrInvokeAndWait(() -> answer[0] = f.compute()); } catch (Exception e) { answer[0] = 0; diff --git a/platform/usageView/src/com/intellij/usages/impl/GroupNode.java b/platform/usageView/src/com/intellij/usages/impl/GroupNode.java index aaf9574ede9e..4592f0f06702 100644 --- a/platform/usageView/src/com/intellij/usages/impl/GroupNode.java +++ b/platform/usageView/src/com/intellij/usages/impl/GroupNode.java @@ -85,12 +85,7 @@ public class GroupNode extends Node implements Navigatable, Comparable edtQueue) { if (!getBuilder().isDetachedMode()) { - edtQueue.consume(new Runnable() { - @Override - public void run() { - myTreeModel.insertNodeInto(node, GroupNode.this, getNodeInsertionIndex(node)); - } - }); + edtQueue.consume(() -> myTreeModel.insertNodeInto(node, GroupNode.this, getNodeInsertionIndex(node))); } } @@ -205,12 +200,9 @@ public class GroupNode extends Node implements Navigatable, Comparable { + myTreeModel.insertNodeInto(node, GroupNode.this, getNodeIndex(node)); + incrementUsageCount(); }); } return node; diff --git a/platform/usageView/src/com/intellij/usages/impl/Node.java b/platform/usageView/src/com/intellij/usages/impl/Node.java index be93bf35f43b..abe0b905810d 100644 --- a/platform/usageView/src/com/intellij/usages/impl/Node.java +++ b/platform/usageView/src/com/intellij/usages/impl/Node.java @@ -110,12 +110,7 @@ public abstract class Node extends DefaultMutableTreeNode { myCachedText = text; updateNotify(); - edtQueue.consume(new Runnable() { - @Override - public void run() { - myTreeModel.nodeChanged(Node.this); - } - }); + edtQueue.consume(() -> myTreeModel.nodeChanged(Node.this)); } setFlag(UPDATED_MASK, true); } diff --git a/platform/usageView/src/com/intellij/usages/impl/SearchForUsagesRunnable.java b/platform/usageView/src/com/intellij/usages/impl/SearchForUsagesRunnable.java index 47ff347332d0..40481060cbef 100644 --- a/platform/usageView/src/com/intellij/usages/impl/SearchForUsagesRunnable.java +++ b/platform/usageView/src/com/intellij/usages/impl/SearchForUsagesRunnable.java @@ -136,15 +136,12 @@ class SearchForUsagesRunnable implements Runnable { + UsageViewBundle.message("large.files.were.ignored", largeFiles.size()) + ")"; resultLines.add(shortMessage); - resultListener = addHrefHandling(resultListener, LARGE_FILES_HREF_TARGET, new Runnable() { - @Override - public void run() { - String detailedMessage = detailedLargeFilesMessage(largeFiles); - List strings = new ArrayList(lines); - strings.add(detailedMessage); - //noinspection SSBasedInspection - ToolWindowManager.getInstance(project).notifyByBalloon(ToolWindowId.FIND, info, wrapInHtml(strings), AllIcons.Actions.Find, listener); - } + resultListener = addHrefHandling(resultListener, LARGE_FILES_HREF_TARGET, () -> { + String detailedMessage = detailedLargeFilesMessage(largeFiles); + List strings = new ArrayList(lines); + strings.add(detailedMessage); + //noinspection SSBasedInspection + ToolWindowManager.getInstance(project).notifyByBalloon(ToolWindowId.FIND, info, wrapInHtml(strings), AllIcons.Actions.Find, listener); }); } @@ -287,11 +284,8 @@ class SearchForUsagesRunnable implements Runnable { final Usage firstUsage = myFirstUsage.get(); if (firstUsage != null) { final UsageViewImpl finalUsageView = usageView; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - finalUsageView.appendUsage(firstUsage); - } + ApplicationManager.getApplication().runReadAction(() -> { + finalUsageView.appendUsage(firstUsage); }); } } @@ -304,16 +298,13 @@ class SearchForUsagesRunnable implements Runnable { } private void openView(@NotNull final UsageViewImpl usageView) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - myUsageViewManager.addContent(usageView, myPresentation); - if (myListener != null) { - myListener.usageViewCreated(usageView); - } - myUsageViewManager.showToolWindow(false); + SwingUtilities.invokeLater(() -> { + if (myProject.isDisposed()) return; + myUsageViewManager.addContent(usageView, myPresentation); + if (myListener != null) { + myListener.usageViewCreated(usageView); } + myUsageViewManager.showToolWindow(false); }); } @@ -333,72 +324,57 @@ class SearchForUsagesRunnable implements Runnable { assert indicator != null : "must run find usages under progress"; TooManyUsagesStatus.createFor(indicator); Alarm findUsagesStartedBalloon = new Alarm(); - findUsagesStartedBalloon.addRequest(new Runnable() { - @Override - public void run() { - notifyByFindBalloon(null, MessageType.WARNING, myProcessPresentation, myProject, - Collections.singletonList(StringUtil.escapeXml(UsageViewManagerImpl.getProgressTitle(myPresentation)))); - findStartedBalloonShown.set(true); - } + findUsagesStartedBalloon.addRequest(() -> { + notifyByFindBalloon(null, MessageType.WARNING, myProcessPresentation, myProject, + Collections.singletonList(StringUtil.escapeXml(UsageViewManagerImpl.getProgressTitle(myPresentation)))); + findStartedBalloonShown.set(true); }, 300, ModalityState.NON_MODAL); UsageSearcher usageSearcher = mySearcherFactory.create(); - usageSearcher.generate(new Processor() { - @Override - public boolean process(final Usage usage) { - ProgressIndicator indicator = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator()); - assert indicator != null : "must run find usages under progress"; - if (indicator.isCanceled()) return false; + usageSearcher.generate(usage -> { + ProgressIndicator indicator1 = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator()); + assert indicator1 != null : "must run find usages under progress"; + if (indicator1.isCanceled()) return false; - if (!UsageViewManagerImpl.isInScope(usage, mySearchScopeToWarnOfFallingOutOf)) { - myOutOfScopeUsages.incrementAndGet(); - return true; - } - - boolean incrementCounter = !UsageViewManager.isSelfUsage(usage, mySearchFor); - - if (incrementCounter) { - final int usageCount = myUsageCountWithoutDefinition.incrementAndGet(); - if (usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage()) { - myFirstUsage.compareAndSet(null, usage); - } - - final UsageViewImpl usageView = getUsageView(indicator); - - TooManyUsagesStatus tooManyUsagesStatus; - if (usageCount > UsageLimitUtil.USAGES_LIMIT && (tooManyUsagesStatus = TooManyUsagesStatus.getFrom(indicator)).switchTooManyUsagesStatus()) { - UsageViewManagerImpl.showTooManyUsagesWarning(myProject, tooManyUsagesStatus, indicator, myPresentation, usageCount, usageView); - } - - if (usageView != null) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - usageView.appendUsage(usage); - } - }); - } - } - return !indicator.isCanceled(); + if (!UsageViewManagerImpl.isInScope(usage, mySearchScopeToWarnOfFallingOutOf)) { + myOutOfScopeUsages.incrementAndGet(); + return true; } + + boolean incrementCounter = !UsageViewManager.isSelfUsage(usage, mySearchFor); + + if (incrementCounter) { + final int usageCount = myUsageCountWithoutDefinition.incrementAndGet(); + if (usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage()) { + myFirstUsage.compareAndSet(null, usage); + } + + final UsageViewImpl usageView = getUsageView(indicator1); + + TooManyUsagesStatus tooManyUsagesStatus; + if (usageCount > UsageLimitUtil.USAGES_LIMIT && (tooManyUsagesStatus = TooManyUsagesStatus.getFrom(indicator1)).switchTooManyUsagesStatus()) { + UsageViewManagerImpl.showTooManyUsagesWarning(myProject, tooManyUsagesStatus, indicator1, myPresentation, usageCount, usageView); + } + + if (usageView != null) { + ApplicationManager.getApplication().runReadAction(() -> { + usageView.appendUsage(usage); + }); + } + } + return !indicator1.isCanceled(); }); if (getUsageView(indicator) != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myUsageViewManager.showToolWindow(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + myUsageViewManager.showToolWindow(true); }, myProject.getDisposed()); } Disposer.dispose(findUsagesStartedBalloon); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (findStartedBalloonShown.get()) { - Balloon balloon = ToolWindowManager.getInstance(myProject).getToolWindowBalloon(ToolWindowId.FIND); - if (balloon != null) { - balloon.hide(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (findStartedBalloonShown.get()) { + Balloon balloon = ToolWindowManager.getInstance(myProject).getToolWindowBalloon(ToolWindowId.FIND); + if (balloon != null) { + balloon.hide(); } } }, myProject.getDisposed()); @@ -459,26 +435,23 @@ class SearchForUsagesRunnable implements Runnable { }, ModalityState.NON_MODAL, myProject.getDisposed()); } else if (usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Usage usage = myFirstUsage.get(); - if (usage.canNavigate()) { - usage.navigate(true); - flashUsageScriptaculously(usage); - } - List lines = new ArrayList(); - - lines.add("Only one usage found."); - if (myOutOfScopeUsages.get() != 0) { - lines.add(UsageViewManagerImpl.outOfScopeMessage(myOutOfScopeUsages.get(), mySearchScopeToWarnOfFallingOutOf)); - } - lines.add(createOptionsHtml(mySearchFor)); - MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; - notifyByFindBalloon(createGotToOptionsListener(mySearchFor), - type, myProcessPresentation, myProject, - lines); + ApplicationManager.getApplication().invokeLater(() -> { + Usage usage = myFirstUsage.get(); + if (usage.canNavigate()) { + usage.navigate(true); + flashUsageScriptaculously(usage); } + List lines = new ArrayList(); + + lines.add("Only one usage found."); + if (myOutOfScopeUsages.get() != 0) { + lines.add(UsageViewManagerImpl.outOfScopeMessage(myOutOfScopeUsages.get(), mySearchScopeToWarnOfFallingOutOf)); + } + lines.add(createOptionsHtml(mySearchFor)); + MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; + notifyByFindBalloon(createGotToOptionsListener(mySearchFor), + type, myProcessPresentation, myProject, + lines); }, ModalityState.NON_MODAL, myProject.getDisposed()); } else { @@ -502,12 +475,9 @@ class SearchForUsagesRunnable implements Runnable { if (!myProcessPresentation.getLargeFiles().isEmpty() || myOutOfScopeUsages.get() != 0 || myProcessPresentation.searchIncludingProjectFileUsages() != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; - notifyByFindBalloon(hyperlinkListener, type, myProcessPresentation, myProject, lines); - } + ApplicationManager.getApplication().invokeLater(() -> { + MessageType type = myOutOfScopeUsages.get() == 0 ? MessageType.INFO : MessageType.WARNING; + notifyByFindBalloon(hyperlinkListener, type, myProcessPresentation, myProject, lines); }, ModalityState.NON_MODAL, myProject.getDisposed()); } } diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageContextPanelBase.java b/platform/usageView/src/com/intellij/usages/impl/UsageContextPanelBase.java index cd9efc9ed795..2eb81a51ad6b 100644 --- a/platform/usageView/src/com/intellij/usages/impl/UsageContextPanelBase.java +++ b/platform/usageView/src/com/intellij/usages/impl/UsageContextPanelBase.java @@ -58,12 +58,9 @@ public abstract class UsageContextPanelBase extends JPanel implements UsageConte @Override public final void updateLayout(@Nullable final List infos) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (isDisposed || myProject.isDisposed()) return; - updateLayoutLater(infos); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (isDisposed || myProject.isDisposed()) return; + updateLayoutLater(infos); }); } diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java index 4c14009aff0f..085db51c1a3f 100644 --- a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java +++ b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java @@ -111,32 +111,29 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra private final JComponent myAdditionalComponent = new JPanel(new BorderLayout()); private volatile boolean isDisposed; private volatile boolean myChangesDetected; - public static final Comparator USAGE_COMPARATOR = new Comparator() { - @Override - public int compare(final Usage o1, final Usage o2) { - if (o1 == o2) return 0; - if (o1 == NULL_NODE) return -1; - if (o2 == NULL_NODE) return 1; - if (o1 instanceof Comparable && o2 instanceof Comparable) { - final int selfcompared = ((Comparable)o1).compareTo(o2); - if (selfcompared != 0) return selfcompared; + public static final Comparator USAGE_COMPARATOR = (o1, o2) -> { + if (o1 == o2) return 0; + if (o1 == NULL_NODE) return -1; + if (o2 == NULL_NODE) return 1; + if (o1 instanceof Comparable && o2 instanceof Comparable) { + final int selfcompared = ((Comparable)o1).compareTo(o2); + if (selfcompared != 0) return selfcompared; - if (o1 instanceof UsageInFile && o2 instanceof UsageInFile) { - UsageInFile u1 = (UsageInFile)o1; - UsageInFile u2 = (UsageInFile)o2; + if (o1 instanceof UsageInFile && o2 instanceof UsageInFile) { + UsageInFile u1 = (UsageInFile)o1; + UsageInFile u2 = (UsageInFile)o2; - VirtualFile f1 = u1.getFile(); - VirtualFile f2 = u2.getFile(); + VirtualFile f1 = u1.getFile(); + VirtualFile f2 = u2.getFile(); - if (f1 != null && f1.isValid() && f2 != null && f2.isValid()) { - return f1.getPresentableUrl().compareTo(f2.getPresentableUrl()); - } + if (f1 != null && f1.isValid() && f2 != null && f2.isValid()) { + return f1.getPresentableUrl().compareTo(f2.getPresentableUrl()); } - - return 0; } - return o1.toString().compareTo(o2.toString()); + + return 0; } + return o1.toString().compareTo(o2.toString()); }; @NonNls private static final String HELP_ID = "ideaInterface.find"; private UsageContextPanel myCurrentUsageContextPanel; @@ -201,81 +198,62 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra myBuilder = new UsageNodeTreeBuilder(myTargets, getActiveGroupingRules(project), getActiveFilteringRules(project), myRoot, myProject); final MessageBusConnection messageBusConnection = myProject.getMessageBus().connect(this); - messageBusConnection.subscribe(UsageFilteringRuleProvider.RULES_CHANGED, new Runnable() { - @Override - public void run() { - rulesChanged(); - } - }); + messageBusConnection.subscribe(UsageFilteringRuleProvider.RULES_CHANGED, () -> rulesChanged()); myUsageViewTreeCellRenderer = new UsageViewTreeCellRenderer(this); if (!myPresentation.isDetachedMode()) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - // lock here to avoid concurrent execution of this init and dispose in other thread - synchronized (lock) { - if (isDisposed) return; - myTree.setModel(myModel); + UIUtil.invokeLaterIfNeeded(() -> { + // lock here to avoid concurrent execution of this init and dispose in other thread + synchronized (lock) { + if (isDisposed) return; + myTree.setModel(myModel); - myRootPanel.setLayout(new BorderLayout()); + myRootPanel.setLayout(new BorderLayout()); - SimpleToolWindowPanel toolWindowPanel = new SimpleToolWindowPanel(false, true); - myRootPanel.add(toolWindowPanel, BorderLayout.CENTER); + SimpleToolWindowPanel toolWindowPanel = new SimpleToolWindowPanel(false, true); + myRootPanel.add(toolWindowPanel, BorderLayout.CENTER); - JPanel toolbarPanel = new JPanel(new BorderLayout()); - toolbarPanel.add(createActionsToolbar(), BorderLayout.WEST); - toolbarPanel.add(createFiltersToolbar(), BorderLayout.CENTER); - toolWindowPanel.setToolbar(toolbarPanel); + JPanel toolbarPanel = new JPanel(new BorderLayout()); + toolbarPanel.add(createActionsToolbar(), BorderLayout.WEST); + toolbarPanel.add(createFiltersToolbar(), BorderLayout.CENTER); + toolWindowPanel.setToolbar(toolbarPanel); - myCentralPanel = new JPanel(new BorderLayout()); - setupCentralPanel(); + myCentralPanel = new JPanel(new BorderLayout()); + setupCentralPanel(); - initTree(); - toolWindowPanel.setContent(myCentralPanel); + initTree(); + toolWindowPanel.setContent(myCentralPanel); - myTree.setCellRenderer(myUsageViewTreeCellRenderer); - collapseAll(); + myTree.setCellRenderer(myUsageViewTreeCellRenderer); + collapseAll(); - myModelTracker.addListener(UsageViewImpl.this); + myModelTracker.addListener(UsageViewImpl.this); - if (myPresentation.isShowCancelButton()) { - addButtonToLowerPane(new Runnable() { - @Override - public void run() { - close(); - } - }, UsageViewBundle.message("usage.view.cancel.button")); - } - - myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(final TreeSelectionEvent e) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isDisposed || myProject.isDisposed()) return; - updateOnSelectionChanged(); - } - }); - } - }); + if (myPresentation.isShowCancelButton()) { + addButtonToLowerPane(() -> close(), UsageViewBundle.message("usage.view.cancel.button")); } + + myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(final TreeSelectionEvent e) { + SwingUtilities.invokeLater(() -> { + if (isDisposed || myProject.isDisposed()) return; + updateOnSelectionChanged(); + }); + } + }); } }); } - myTransferToEDTQueue = new TransferToEDTQueue("Insert usages", new Processor() { - @Override - public boolean process(Runnable runnable) { - runnable.run(); - return true; - } + myTransferToEDTQueue = new TransferToEDTQueue("Insert usages", runnable -> { + runnable.run(); + return true; }, new Condition() { @Override public boolean value(Object o) { return isDisposed || project.isDisposed(); } - },200); + }, 200); myExclusionHandler = new ExclusionHandler() { @Override public boolean isNodeExcluded(@NotNull Node node) { @@ -749,31 +727,25 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra reset(); myBuilder.setGroupingRules(getActiveGroupingRules(myProject)); myBuilder.setFilteringRules(getActiveFilteringRules(myProject)); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (Usage usage : allUsages) { - if (!usage.isValid()) { - continue; - } - if (usage instanceof MergeableUsage) { - ((MergeableUsage)usage).reset(); - } - appendUsage(usage); + ApplicationManager.getApplication().runReadAction(() -> { + for (Usage usage : allUsages) { + if (!usage.isValid()) { + continue; } + if (usage instanceof MergeableUsage) { + ((MergeableUsage)usage).reset(); + } + appendUsage(usage); } }); excludeUsages(excludedUsages.toArray(new Usage[excludedUsages.size()])); if (myCentralPanel != null) { setupCentralPanel(); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isDisposed) return; - restoreUsageExpandState(states); - updateImmediately(); - } + SwingUtilities.invokeLater(() -> { + if (isDisposed) return; + restoreUsageExpandState(states); + updateImmediately(); }); } @@ -901,32 +873,26 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra setSearchInProgress(true); associateProgress(indicator); - Processor processor = new Processor() { - @Override - public boolean process(final Usage usage) { - if (searchHasBeenCancelled()) return false; - TooManyUsagesStatus.getFrom(indicator).pauseProcessingIfTooManyUsages(); + Processor processor = usage -> { + if (searchHasBeenCancelled()) return false; + TooManyUsagesStatus.getFrom(indicator).pauseProcessingIfTooManyUsages(); - boolean incrementCounter = !com.intellij.usages.UsageViewManager.isSelfUsage(usage, myTargets); + boolean incrementCounter = !com.intellij.usages.UsageViewManager.isSelfUsage(usage, myTargets); - if (incrementCounter) { - final int usageCount = usageCountWithoutDefinition.incrementAndGet(); - if (usageCount > UsageLimitUtil.USAGES_LIMIT) { - if (tooManyUsagesStatus.switchTooManyUsagesStatus()) { - UsageViewManagerImpl - .showTooManyUsagesWarning(project, tooManyUsagesStatus, indicator, getPresentation(), usageCountWithoutDefinition.get(), - UsageViewImpl.this); - } + if (incrementCounter) { + final int usageCount = usageCountWithoutDefinition.incrementAndGet(); + if (usageCount > UsageLimitUtil.USAGES_LIMIT) { + if (tooManyUsagesStatus.switchTooManyUsagesStatus()) { + UsageViewManagerImpl + .showTooManyUsagesWarning(project, tooManyUsagesStatus, indicator, getPresentation(), usageCountWithoutDefinition.get(), + UsageViewImpl.this); } - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - appendUsage(usage); - } - }); } - return !indicator.isCanceled(); + ApplicationManager.getApplication().runReadAction(() -> { + appendUsage(usage); + }); } + return !indicator.isCanceled(); }; myChangesDetected = false; @@ -949,12 +915,9 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra myUsageNodes.clear(); myModel.reset(); if (!myPresentation.isDetachedMode()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (isDisposed) return; - TreeUtil.expand(myTree, 2); - } + SwingUtilities.invokeLater(() -> { + if (isDisposed) return; + TreeUtil.expand(myTree, 2); }); } } @@ -1003,14 +966,11 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra public void removeUsage(@NotNull Usage usage) { final UsageNode node = myUsageNodes.remove(usage); if (node != NULL_NODE && node != null && !myPresentation.isDetachedMode()) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (isDisposed) return; - TreeModel treeModel = myTree.getModel(); - ((DefaultTreeModel)treeModel).removeNodeFromParent(node); - ((GroupNode)myTree.getModel().getRoot()).removeUsage(node); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (isDisposed) return; + TreeModel treeModel = myTree.getModel(); + ((DefaultTreeModel)treeModel).removeNodeFromParent(node); + ((GroupNode)myTree.getModel().getRoot()).removeUsage(node); }); } } @@ -1025,22 +985,19 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra } } if (!nodes.isEmpty() && !myPresentation.isDetachedMode()) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (isDisposed) return; - DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel(); - for (UsageNode node : nodes) { - MutableTreeNode parent = (MutableTreeNode)node.getParent(); - int childIndex = parent.getIndex(node); - if (childIndex != -1) { - parent.remove(childIndex); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (isDisposed) return; + DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel(); + for (UsageNode node : nodes) { + MutableTreeNode parent = (MutableTreeNode)node.getParent(); + int childIndex = parent.getIndex(node); + if (childIndex != -1) { + parent.remove(childIndex); } - ((GroupNode)myTree.getModel().getRoot()).removeUsagesBulk(nodes); - - treeModel.reload(); } + ((GroupNode)myTree.getModel().getRoot()).removeUsagesBulk(nodes); + + treeModel.reload(); }); } } @@ -1171,18 +1128,10 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra private void updateLater() { myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject); - documentManager.cancelAndRunWhenAllCommitted("UpdateUsageView", new Runnable() { - @Override - public void run() { - updateImmediately(); - } - }); - } + myUpdateAlarm.addRequest(() -> { + if (myProject.isDisposed()) return; + PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject); + documentManager.cancelAndRunWhenAllCommitted("UpdateUsageView", () -> updateImmediately()); }, 300); } @@ -1226,22 +1175,19 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra public void setSearchInProgress(boolean searchInProgress) { mySearchInProgress = searchInProgress; if (!myPresentation.isDetachedMode()) { - myTransferToEDTQueue.offer(new Runnable() { - @Override - public void run() { - if (isDisposed) return; - final UsageNode firstUsageNode = myModel.getFirstUsageNode(); - if (firstUsageNode == null) return; + myTransferToEDTQueue.offer(() -> { + if (isDisposed) return; + final UsageNode firstUsageNode = myModel.getFirstUsageNode(); + if (firstUsageNode == null) return; - Node node = getSelectedNode(); - if (node != null && !Comparing.equal(new TreePath(node.getPath()), TreeUtil.getFirstNodePath(myTree))) { - // user has selected node already - return; - } - showNode(firstUsageNode); - if (UsageViewSettings.getInstance().isExpanded() && myUsageNodes.size() < 10000) { - expandAll(); - } + Node node = getSelectedNode(); + if (node != null && !Comparing.equal(new TreePath(node.getPath()), TreeUtil.getFirstNodePath(myTree))) { + // user has selected node already + return; + } + showNode(firstUsageNode); + if (UsageViewSettings.getInstance().isExpanded() && myUsageNodes.size() < 10000) { + expandAll(); } }); } @@ -1253,14 +1199,11 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra private void showNode(@NotNull final UsageNode node) { if (!myPresentation.isDetachedMode()) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (isDisposed) return; - TreePath usagePath = new TreePath(node.getPath()); - myTree.expandPath(usagePath.getParentPath()); - TreeUtil.selectPath(myTree, usagePath); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (isDisposed) return; + TreePath usagePath = new TreePath(node.getPath()); + myTree.expandPath(usagePath.getParentPath()); + TreeUtil.selectPath(myTree, usagePath); }); } } @@ -1771,12 +1714,7 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra close(); CommandProcessor.getInstance().executeCommand( - myProject, new Runnable() { - @Override - public void run() { - myProcessRunnable.run(); - } - }, + myProject, () -> myProcessRunnable.run(), myCommandName, null ); diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageViewManagerImpl.java b/platform/usageView/src/com/intellij/usages/impl/UsageViewManagerImpl.java index f295e593992d..f5ac066cf8b4 100644 --- a/platform/usageView/src/com/intellij/usages/impl/UsageViewManagerImpl.java +++ b/platform/usageView/src/com/intellij/usages/impl/UsageViewManagerImpl.java @@ -193,12 +193,9 @@ public class UsageViewManagerImpl extends UsageViewManager { } private static void appendUsages(@NotNull final Usage[] foundUsages, @NotNull final UsageViewImpl usageView) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (Usage foundUsage : foundUsages) { - usageView.appendUsage(foundUsage); - } + ApplicationManager.getApplication().runReadAction(() -> { + for (Usage foundUsage : foundUsages) { + usageView.appendUsage(foundUsage); } }); } @@ -210,31 +207,25 @@ public class UsageViewManagerImpl extends UsageViewManager { @NotNull final UsageViewPresentation presentation, final int usageCount, @Nullable final UsageViewImpl usageView) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (usageView != null && usageView.searchHasBeenCancelled() || indicator.isCanceled()) return; - String message = UsageViewBundle.message("find.excessive.usage.count.prompt", usageCount, StringUtil.pluralize(presentation.getUsagesWord())); - UsageLimitUtil.Result ret = UsageLimitUtil.showTooManyUsagesWarning(project, message, presentation); - if (ret == UsageLimitUtil.Result.ABORT) { - if (usageView != null) { - usageView.cancelCurrentSearch(); - } - indicator.cancel(); + UIUtil.invokeLaterIfNeeded(() -> { + if (usageView != null && usageView.searchHasBeenCancelled() || indicator.isCanceled()) return; + String message = UsageViewBundle.message("find.excessive.usage.count.prompt", usageCount, StringUtil.pluralize(presentation.getUsagesWord())); + UsageLimitUtil.Result ret = UsageLimitUtil.showTooManyUsagesWarning(project, message, presentation); + if (ret == UsageLimitUtil.Result.ABORT) { + if (usageView != null) { + usageView.cancelCurrentSearch(); } - tooManyUsagesStatus.userResponded(); + indicator.cancel(); } + tooManyUsagesStatus.userResponded(); }); } public static long getFileLength(@NotNull final VirtualFile virtualFile) { final long[] length = {-1L}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (!virtualFile.isValid()) return; - length[0] = virtualFile.getLength(); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (!virtualFile.isValid()) return; + length[0] = virtualFile.getLength(); }); return length[0]; } diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageViewTreeModelBuilder.java b/platform/usageView/src/com/intellij/usages/impl/UsageViewTreeModelBuilder.java index 59ed6ff0d3cc..321690e41082 100644 --- a/platform/usageView/src/com/intellij/usages/impl/UsageViewTreeModelBuilder.java +++ b/platform/usageView/src/com/intellij/usages/impl/UsageViewTreeModelBuilder.java @@ -71,12 +71,7 @@ public class UsageViewTreeModelBuilder extends DefaultTreeModel { myTargetsNode.add(targetNode); myTargetNodes[i] = targetNode; } - myRootNode.addNode(myTargetsNode, new Consumer() { - @Override - public void consume(Runnable runnable) { - UIUtil.invokeLaterIfNeeded(runnable); - } - }); + myRootNode.addNode(myTargetsNode, runnable -> UIUtil.invokeLaterIfNeeded(runnable)); } public UsageNode getFirstUsageNode() { diff --git a/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilHeavyTest.java b/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilHeavyTest.java index 63b35e7faf0d..5f2cbd7cf2ee 100644 --- a/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilHeavyTest.java +++ b/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilHeavyTest.java @@ -70,13 +70,10 @@ public class FileUtilHeavyTest { @Test public void testProcessSimple() { final Map result = new HashMap(); - FileUtil.processFilesRecursively(myVisitorTestDirectory, new Processor() { - @Override - public boolean process(File file) { - Integer integer = result.get(file.getName()); - result.put(file.getName(), integer == null ? 1 : (integer + 1)); - return true; - } + FileUtil.processFilesRecursively(myVisitorTestDirectory, file -> { + Integer integer = result.get(file.getName()); + result.put(file.getName(), integer == null ? 1 : (integer + 1)); + return true; }); assertEquals(6, result.size()); @@ -89,12 +86,9 @@ public class FileUtilHeavyTest { @Test public void testProcessStops() { final int[] cnt = new int[]{0}; - FileUtil.processFilesRecursively(myVisitorTestDirectory, new Processor() { - @Override - public boolean process(File file) { - ++cnt[0]; - return false; - } + FileUtil.processFilesRecursively(myVisitorTestDirectory, file -> { + ++cnt[0]; + return false; }); assertEquals(1, cnt[0]); @@ -103,19 +97,11 @@ public class FileUtilHeavyTest { @Test public void testProcessDirectoryFilter() { final Map result = new HashMap(); - FileUtil.processFilesRecursively(myVisitorTestDirectory, new Processor() { - @Override - public boolean process(File file) { - Integer integer = result.get(file.getName()); - result.put(file.getName(), integer == null ? 1 : (integer + 1)); - return true; - } - }, new Processor() { - @Override - public boolean process(File file) { - return ! "dir2".equals(file.getName()); - } - }); + FileUtil.processFilesRecursively(myVisitorTestDirectory, file -> { + Integer integer = result.get(file.getName()); + result.put(file.getName(), integer == null ? 1 : (integer + 1)); + return true; + }, file -> ! "dir2".equals(file.getName())); assertEquals(5, result.size()); assertEquals(1, result.get(myVisitorTestDirectory.getName()).intValue()); diff --git a/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java b/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java index 43bc1432f5b3..4019832581f6 100644 --- a/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java +++ b/platform/util/testSrc/com/intellij/openapi/util/io/IoTestUtil.java @@ -164,11 +164,8 @@ public class IoTestUtil { } private static char getFirstFreeDriveLetter() { - final Set roots = ContainerUtil.map2Set(File.listRoots(), new Function() { - @Override - public Character fun(File root) { - return root.getPath().toUpperCase(Locale.US).charAt(0); - } + final Set roots = ContainerUtil.map2Set(File.listRoots(), root -> { + return root.getPath().toUpperCase(Locale.US).charAt(0); }); char drive = 0; @@ -217,26 +214,23 @@ public class IoTestUtil { private static int runCommand(final ProcessBuilder command) throws IOException, InterruptedException { command.redirectErrorStream(true); final Process process = command.start(); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { + Thread thread = new Thread(() -> { + try { + final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); try { - final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); - try { - //noinspection StatementWithEmptyBody - String line; - while ((line = reader.readLine()) != null) { - System.out.println(line); - } - } - finally { - reader.close(); + //noinspection StatementWithEmptyBody + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); } } - catch (IOException e) { - throw new RuntimeException(e); + finally { + reader.close(); } } + catch (IOException e) { + throw new RuntimeException(e); + } }, "io test"); thread.start(); int ret = process.waitFor(); @@ -289,22 +283,19 @@ public class IoTestUtil { public static File createTestJar(@NotNull File jarFile, @NotNull final File root) throws IOException { final ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(jarFile)); try { - FileUtil.visitFiles(root, new Processor() { - @Override - public boolean process(File file) { - if (file.isFile()) { - String path = FileUtil.toSystemIndependentName(ObjectUtils.assertNotNull(FileUtil.getRelativePath(root, file))); - try { - stream.putNextEntry(new ZipEntry(path)); - stream.write(FileUtil.loadFileBytes(file)); - stream.closeEntry(); - } - catch (IOException e) { - throw new RuntimeException(e); - } + FileUtil.visitFiles(root, file -> { + if (file.isFile()) { + String path = FileUtil.toSystemIndependentName(ObjectUtils.assertNotNull(FileUtil.getRelativePath(root, file))); + try { + stream.putNextEntry(new ZipEntry(path)); + stream.write(FileUtil.loadFileBytes(file)); + stream.closeEntry(); + } + catch (IOException e) { + throw new RuntimeException(e); } - return true; } + return true; }); } finally { diff --git a/platform/util/testSrc/com/intellij/ui/SortedListModelTest.java b/platform/util/testSrc/com/intellij/ui/SortedListModelTest.java index 2fc6b449c4fb..ab8604f0eaf5 100644 --- a/platform/util/testSrc/com/intellij/ui/SortedListModelTest.java +++ b/platform/util/testSrc/com/intellij/ui/SortedListModelTest.java @@ -26,12 +26,7 @@ import java.util.Comparator; import java.util.Iterator; public class SortedListModelTest extends TestCase { - private final SortedListModel myModel = new SortedListModel(new Comparator() { - @Override - public int compare(final Object o1, final Object o2) { - return ((Comparable) o1).compareTo((Comparable) o2); - } - } + private final SortedListModel myModel = new SortedListModel((o1, o2) -> ((Comparable) o1).compareTo((Comparable) o2) ); private final Assertion CHECK = new Assertion(); diff --git a/platform/util/testSrc/com/intellij/util/concurrency/BlockingSetTest.java b/platform/util/testSrc/com/intellij/util/concurrency/BlockingSetTest.java index 02bffded1d39..b7f385aecda6 100644 --- a/platform/util/testSrc/com/intellij/util/concurrency/BlockingSetTest.java +++ b/platform/util/testSrc/com/intellij/util/concurrency/BlockingSetTest.java @@ -41,21 +41,18 @@ public class BlockingSetTest { List> taskList = new ArrayList>(tasks); final AtomicBoolean check = new AtomicBoolean(false); for (int i = 0; i < tasks; i++) { - taskList.add(new Callable() { - @Override - public Void call() throws Exception { - lock.put("key"); - try { - Assert.assertFalse(check.get()); - check.set(true); - Thread.sleep(1); - check.set(false); - } - finally { - lock.remove("key"); - } - return null; + taskList.add(() -> { + lock.put("key"); + try { + Assert.assertFalse(check.get()); + check.set(true); + Thread.sleep(1); + check.set(false); } + finally { + lock.remove("key"); + } + return null; }); } List> futures = service.invokeAll(taskList); diff --git a/platform/util/testSrc/com/intellij/util/containers/ConcurrentBitSetTest.java b/platform/util/testSrc/com/intellij/util/containers/ConcurrentBitSetTest.java index f5fb2d43332a..de84af7eb145 100644 --- a/platform/util/testSrc/com/intellij/util/containers/ConcurrentBitSetTest.java +++ b/platform/util/testSrc/com/intellij/util/containers/ConcurrentBitSetTest.java @@ -76,16 +76,13 @@ public class ConcurrentBitSetTest extends TestCase { Thread[] threads = new Thread[N]; for (int i=0; i { + for (int i1 = 0; i1 < 10000; i1++) { + for (int j = 0; j < L; j++) { + bitSet.flip(j); } } - },"conc bit set"); + }, "conc bit set"); threads[i] = thread; thread.start(); } @@ -102,16 +99,13 @@ public class ConcurrentBitSetTest extends TestCase { Thread[] threads = new Thread[N]; for (int i=0; i { + for (int i1 = 0; i1 < 100; i1++) { + for (int j = 0; j < L; j++) { + bitSet.flip(j); } } - },"conc bit stress"); + }, "conc bit stress"); threads[i] = thread; thread.start(); } diff --git a/platform/util/testSrc/com/intellij/util/containers/PathInternerTest.java b/platform/util/testSrc/com/intellij/util/containers/PathInternerTest.java index a63576753801..67958f1830ec 100644 --- a/platform/util/testSrc/com/intellij/util/containers/PathInternerTest.java +++ b/platform/util/testSrc/com/intellij/util/containers/PathInternerTest.java @@ -69,12 +69,9 @@ public class PathInternerTest extends TestCase { @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") public static void main(String[] args) throws InterruptedException, IOException { final HashSet hs = new HashSet(); - FileUtil.processFilesRecursively(new File(PathManager.getHomePath()), new Processor() { - @Override - public boolean process(File file) { - hs.add(file.getPath()); - return true; - } + FileUtil.processFilesRecursively(new File(PathManager.getHomePath()), file -> { + hs.add(file.getPath()); + return true; }); THashSet thm = new THashSet(); PathInterner.PathEnumerator interner = new PathInterner.PathEnumerator(); diff --git a/platform/util/testSrc/com/intellij/util/diff/DiffTreeTest.java b/platform/util/testSrc/com/intellij/util/diff/DiffTreeTest.java index d6deb37b9cb5..d69a8a9f942a 100644 --- a/platform/util/testSrc/com/intellij/util/diff/DiffTreeTest.java +++ b/platform/util/testSrc/com/intellij/util/diff/DiffTreeTest.java @@ -60,11 +60,8 @@ public class DiffTreeTest extends TestCase { @Override public String toString() { - return getChildren().length == 0 ? String.valueOf(myId) : StringUtil.join(myChildren, new Function() { - @Override - public String fun(Node node) { - return node.toString(); - } + return getChildren().length == 0 ? String.valueOf(myId) : StringUtil.join(myChildren, node -> { + return node.toString(); }, ""); } diff --git a/platform/util/testSrc/com/intellij/util/text/StringUtilTest.java b/platform/util/testSrc/com/intellij/util/text/StringUtilTest.java index a476be2f2e57..0a2b3e0bea28 100644 --- a/platform/util/testSrc/com/intellij/util/text/StringUtilTest.java +++ b/platform/util/testSrc/com/intellij/util/text/StringUtilTest.java @@ -130,12 +130,7 @@ public class StringUtilTest { assertEquals(1, StringUtil.naturalCompare("test10a", "test010")); final List strings = new ArrayList(Arrays.asList("Test99", "tes0", "test0", "testing", "test", "test99", "test011", "test1", "test 3", "test2", "test10a", "test10", "1.2.10.5", "1.2.9.1")); - final Comparator c = new Comparator() { - @Override - public int compare(String o1, String o2) { - return StringUtil.naturalCompare(o1, o2); - } - }; + final Comparator c = (o1, o2) -> StringUtil.naturalCompare(o1, o2); Collections.sort(strings, c); assertEquals(Arrays.asList("1.2.9.1", "1.2.10.5", "tes0", "test", "test0", "test1", "test2", "test 3", "test10", "test10a", "test011", "Test99", "test99", "testing"), strings); diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java index e25b10ca033e..a41635140e74 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java @@ -185,12 +185,7 @@ public abstract class XBreakpointType, P extends XBreak @NotNull public Comparator getBreakpointComparator() { - return new Comparator() { - @Override - public int compare(B b, B b1) { - return (int)(b1.getTimeStamp() - b.getTimeStamp()); - } - }; + return (b, b1) -> (int)(b1.getTimeStamp() - b.getTimeStamp()); //return XDebuggerUtil.getInstance().getDefaultBreakpointComparator(this); } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java index 5631b9c3fd8a..dd9ae5e2cd1b 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java @@ -28,12 +28,9 @@ import java.util.Comparator; * @author nik */ public abstract class XBreakpointGroupingRule { - public static final Comparator PRIORITY_COMPARATOR = new Comparator() { - @Override - public int compare(XBreakpointGroupingRule o1, XBreakpointGroupingRule o2) { - final int res = o2.getPriority() - o1.getPriority(); - return res != 0 ? res : (o1.getId().compareTo(o2.getId())); - } + public static final Comparator PRIORITY_COMPARATOR = (o1, o2) -> { + final int res = o2.getPriority() - o1.getPriority(); + return res != 0 ? res : (o1.getId().compareTo(o2.getId())); }; private final String myId; diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java index 9e70f0f94202..399fc5420537 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointUtil.java @@ -104,12 +104,7 @@ public class XBreakpointUtil { for (DebuggerSupport debuggerSupport : DebuggerSupport.getDebuggerSupports()) { panelProviders.add(debuggerSupport.getBreakpointPanelProvider()); } - Collections.sort(panelProviders, new Comparator() { - @Override - public int compare(BreakpointPanelProvider o1, BreakpointPanelProvider o2) { - return o2.getPriority() - o1.getPriority(); - } - }); + Collections.sort(panelProviders, (o1, o2) -> o2.getPriority() - o1.getPriority()); return panelProviders; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsDialog.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsDialog.java index 47e418339766..70bbfa38a93e 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsDialog.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsDialog.java @@ -420,11 +420,8 @@ public class BreakpointsDialog extends DialogWrapper { } }); - dialogState.setSelectedGroupingRules(new HashSet<>(ContainerUtil.map(rulesEnabled, new Function() { - @Override - public String fun(XBreakpointGroupingRule rule) { - return rule.getId(); - } + dialogState.setSelectedGroupingRules(new HashSet<>(ContainerUtil.map(rulesEnabled, rule -> { + return rule.getId(); }))); getBreakpointManager().setBreakpointsDialogSettings(dialogState); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/XValueHint.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/XValueHint.java index 12a74c5043b1..813de6fb0e83 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/XValueHint.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/XValueHint.java @@ -205,12 +205,7 @@ public class XValueHint extends AbstractValueHint { SimpleTextAttributes.GRAYED_ATTRIBUTES); } - JComponent component = createExpandableHintComponent(text, new Runnable() { - @Override - public void run() { - showTree(result); - } - }); + JComponent component = createExpandableHintComponent(text, () -> showTree(result)); showHint(component); } myShown = true; @@ -231,12 +226,7 @@ public class XValueHint extends AbstractValueHint { @Override public void errorOccurred(@NotNull final String errorMessage) { if (getType() == ValueHintType.MOUSE_CLICK_HINT) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - showHint(HintUtil.createErrorLabel(errorMessage)); - } - }); + ApplicationManager.getApplication().invokeLater(() -> showHint(HintUtil.createErrorLabel(errorMessage))); } LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryContainer.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryContainer.java index 3454e2ffe8b1..b3e86bc24a9d 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryContainer.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryContainer.java @@ -161,12 +161,9 @@ abstract class DebuggerTreeWithHistoryContainer { @Override public void onSuccess(final D value) { if (value != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - addToHistory(value); - updateTree(value); - } + ApplicationManager.getApplication().invokeLater(() -> { + addToHistory(value); + updateTree(value); }); } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPanel.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPanel.java index 71ad8821832a..7c717edb79f7 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPanel.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPanel.java @@ -58,12 +58,7 @@ public class DebuggerTreeWithHistoryPanel extends DebuggerTreeWithHistoryCont } public void rebuild() { - myTree.getLaterInvocator().offer(new Runnable() { - @Override - public void run() { - myTree.rebuildAndRestore(XDebuggerTreeState.saveState(myTree)); - } - }); + myTree.getLaterInvocator().offer(() -> myTree.rebuildAndRestore(XDebuggerTreeState.saveState(myTree))); } public XDebuggerTree getTree() { diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPopup.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPopup.java index 22ad193e8daa..8c8356743bc8 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPopup.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/DebuggerTreeWithHistoryPopup.java @@ -90,16 +90,13 @@ class DebuggerTreeWithHistoryPopup extends DebuggerTreeWithHistoryContainer() { - @Override - public boolean fun(KeyEvent event) { - if (AbstractPopup.isCloseRequest(event)) { - // Do not process a close request if the tree shows a speed search popup - SpeedSearchSupply supply = SpeedSearchSupply.getSupply(tree); - return supply != null && StringUtil.isEmpty(supply.getEnteredPrefix()); - } - return false; + .setKeyEventHandler(event -> { + if (AbstractPopup.isCloseRequest(event)) { + // Do not process a close request if the tree shows a speed search popup + SpeedSearchSupply supply = SpeedSearchSupply.getSupply(tree); + return supply != null && StringUtil.isEmpty(supply.getEnteredPrefix()); } + return false; }) .addListener(new JBPopupAdapter() { @Override diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/ValueLookupManager.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/ValueLookupManager.java index b8b22a35be39..f04df3abb554 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/ValueLookupManager.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/ValueLookupManager.java @@ -110,12 +110,9 @@ public class ValueLookupManager extends EditorMouseAdapter implements EditorMous myAlarm.cancelAllRequests(); if (type == ValueHintType.MOUSE_OVER_HINT) { if (Registry.is("debugger.valueTooltipAutoShow")) { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (area.equals(editor.getScrollingModel().getVisibleArea())) { - showHint(handler, editor, point, type); - } + myAlarm.addRequest(() -> { + if (area.equals(editor.getScrollingModel().getVisibleArea())) { + showHint(handler, editor, point, type); } }, getDelay(handler)); } @@ -162,12 +159,9 @@ public class ValueLookupManager extends EditorMouseAdapter implements EditorMous hideHint(); myRequest = request; - myRequest.invokeHint(new Runnable() { - @Override - public void run() { - if (myRequest != null && myRequest == request) { - myRequest = null; - } + myRequest.invokeHint(() -> { + if (myRequest != null && myRequest == request) { + myRequest = null; } }); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebugView.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebugView.java index e11316512d80..41140c142e6d 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebugView.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebugView.java @@ -41,12 +41,7 @@ public abstract class XDebugView implements Disposable { private static final int VIEW_CLEAR_DELAY = 100; //ms public XDebugView() { - myClearAlarm = new SingleAlarm(new Runnable() { - @Override - public void run() { - clear(); - } - }, VIEW_CLEAR_DELAY, this); + myClearAlarm = new SingleAlarm(() -> clear(), VIEW_CLEAR_DELAY, this); } protected final void requestClear() { diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebuggerFramesList.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebuggerFramesList.java index 557a67451408..25994d43eefb 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebuggerFramesList.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebuggerFramesList.java @@ -129,12 +129,7 @@ public class XDebuggerFramesList extends DebuggerFramesList { @Override protected void onFrameChanged(final Object selectedValue) { if (mySelectedFrame != selectedValue) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - repaint(); - } - }); + SwingUtilities.invokeLater(() -> repaint()); if (selectedValue instanceof XStackFrame) { mySelectedFrame = (XStackFrame)selectedValue; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XFramesView.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XFramesView.java index 61c1fd0cb795..159719b9a2d4 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XFramesView.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XFramesView.java @@ -141,16 +141,13 @@ public class XFramesView extends XDebugView { context.computeExecutionStacks(new XSuspendContext.XExecutionStackContainer() { @Override public void addExecutionStack(@NotNull final List executionStacks, boolean last) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myThreadComboBox.removeItem(null); - addExecutionStacks(executionStacks); - ComboPopup popup = myThreadComboBox.getPopup(); - if (popup != null && popup.isVisible()) { - popup.hide(); - popup.show(); - } + ApplicationManager.getApplication().invokeLater(() -> { + myThreadComboBox.removeItem(null); + addExecutionStacks(executionStacks); + ComboPopup popup = myThreadComboBox.getPopup(); + if (popup != null && popup.isVisible()) { + popup.hide(); + popup.show(); } }); } @@ -332,22 +329,19 @@ public class XFramesView extends XDebugView { @Override public void addStackFrames(@NotNull final List stackFrames, final boolean last) { if (isObsolete()) return; - myLaterInvocator.offer(new Runnable() { - @Override - public void run() { - if (isObsolete()) return; - myStackFrames.addAll(stackFrames); - addFrameListElements(stackFrames, last); - selectCurrentFrame(); - myNextFrameIndex += stackFrames.size(); - myAllFramesLoaded = last; - if (last) { - if (myVisibleRect != null) { - myFramesList.scrollRectToVisible(myVisibleRect); - } - myRunning = false; - myListenersEnabled = true; + myLaterInvocator.offer(() -> { + if (isObsolete()) return; + myStackFrames.addAll(stackFrames); + addFrameListElements(stackFrames, last); + selectCurrentFrame(); + myNextFrameIndex += stackFrames.size(); + myAllFramesLoaded = last; + if (last) { + if (myVisibleRect != null) { + myFramesList.scrollRectToVisible(myVisibleRect); } + myRunning = false; + myListenersEnabled = true; } }); } @@ -355,16 +349,13 @@ public class XFramesView extends XDebugView { @Override public void errorOccurred(@NotNull final String errorMessage) { if (isObsolete()) return; - myLaterInvocator.offer(new Runnable() { - @Override - public void run() { - if (isObsolete()) return; - if (myErrorMessage == null) { - myErrorMessage = errorMessage; - addFrameListElements(Collections.singletonList(errorMessage), true); - myRunning = false; - myListenersEnabled = true; - } + myLaterInvocator.offer(() -> { + if (isObsolete()) return; + if (myErrorMessage == null) { + myErrorMessage = errorMessage; + addFrameListElements(Collections.singletonList(errorMessage), true); + myRunning = false; + myListenersEnabled = true; } }); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XVariablesView.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XVariablesView.java index 3a3d399c3bae..44acf99d72a7 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XVariablesView.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XVariablesView.java @@ -142,12 +142,7 @@ public class XVariablesView extends XVariablesViewBase implements DataProvider { synchronized (myData) { Set entries = myData.get(Pair.create(file, line)); if (entries == null) return null; - return ContainerUtil.map(entries, new Function() { - @Override - public XValueNodeImpl fun(Entry entry) { - return entry.myNode; - } - }); + return ContainerUtil.map(entries, entry -> entry.myNode); } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XWatchesViewImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XWatchesViewImpl.java index 1178f11b5e1a..b7cca9760064 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XWatchesViewImpl.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XWatchesViewImpl.java @@ -191,12 +191,7 @@ public class XWatchesViewImpl extends XVariablesView implements DnDNativeTarget, Presentation presentation = editWatchAction.getTemplatePresentation().clone(); DataContext context = DataManager.getInstance().getDataContext(watchTree); final AnActionEvent actionEvent = new AnActionEvent(null, context, "WATCH_TREE", presentation, ActionManager.getInstance(), 0); - Runnable runnable = new Runnable() { - @Override - public void run() { - editWatchAction.actionPerformed(actionEvent); - } - }; + Runnable runnable = () -> editWatchAction.actionPerformed(actionEvent); if (editAlarm.isEmpty() && quitePeriod.isEmpty()) { editAlarm.addRequest(runnable, UIUtil.getMultiClickInterval()); } else { @@ -417,13 +412,10 @@ public class XWatchesViewImpl extends XVariablesView implements DnDNativeTarget, if (object instanceof XValueNodeImpl[]) { final XValueNodeImpl[] nodes = (XValueNodeImpl[])object; for (XValueNodeImpl node : nodes) { - node.getValueContainer().calculateEvaluationExpression().done(new Consumer() { - @Override - public void consume(XExpression expression) { - if (expression != null) { - //noinspection ConstantConditions - addWatchExpression(expression, -1, false); - } + node.getValueContainer().calculateEvaluationExpression().done(expression -> { + if (expression != null) { + //noinspection ConstantConditions + addWatchExpression(expression, -1, false); } }); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/settings/DebuggerConfigurable.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/settings/DebuggerConfigurable.java index e91451bd0722..9464b5e51ce6 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/settings/DebuggerConfigurable.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/settings/DebuggerConfigurable.java @@ -124,12 +124,9 @@ public class DebuggerConfigurable implements SearchableConfigurable.Parent { Configurable[] mergedRootConfigurables = rootConfigurables.toArray(new Configurable[rootConfigurables.size()]); // move unnamed to top - Arrays.sort(mergedRootConfigurables, new Comparator() { - @Override - public int compare(@NotNull Configurable o1, @NotNull Configurable o2) { - boolean c1e = StringUtil.isEmpty(o1.getDisplayName()); - return c1e == StringUtil.isEmpty(o2.getDisplayName()) ? 0 : (c1e ? -1 : 1); - } + Arrays.sort(mergedRootConfigurables, (o1, o2) -> { + boolean c1e = StringUtil.isEmpty(o1.getDisplayName()); + return c1e == StringUtil.isEmpty(o2.getDisplayName()) ? 0 : (c1e ? -1 : 1); }); return new MergedCompositeConfigurable("", "", mergedRootConfigurables); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/EvaluateInConsoleFromTreeAction.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/EvaluateInConsoleFromTreeAction.java index d0266111dba9..b3d0db635e0b 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/EvaluateInConsoleFromTreeAction.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/EvaluateInConsoleFromTreeAction.java @@ -51,12 +51,9 @@ class EvaluateInConsoleFromTreeAction extends XAddToWatchesAction { protected void perform(XValueNodeImpl node, @NotNull String nodeName, AnActionEvent e) { final ConsoleExecuteAction action = getConsoleExecuteAction(e); if (action != null) { - node.getValueContainer().calculateEvaluationExpression().done(new Consumer() { - @Override - public void consume(XExpression expression) { - if (expression != null) { - action.execute(null, expression.getExpression(), null); - } + node.getValueContainer().calculateEvaluationExpression().done(expression -> { + if (expression != null) { + action.execute(null, expression.getExpression(), null); } }); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/XCompareWithClipboardAction.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/XCompareWithClipboardAction.java index d91810ae924c..788d67386465 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/XCompareWithClipboardAction.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/actions/XCompareWithClipboardAction.java @@ -30,12 +30,9 @@ public class XCompareWithClipboardAction extends XFetchValueActionBase { @Override protected void handle(final Project project, final String value, XDebuggerTree tree) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - DiffRequest request = DiffRequestFactory.getInstance().createClipboardVsValue(value); - DiffManager.getInstance().showDiff(project, request); - } + UIUtil.invokeLaterIfNeeded(() -> { + DiffRequest request = DiffRequestFactory.getInstance().createClipboardVsValue(value); + DiffManager.getInstance().showDiff(project, request); }); } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/HeadlessValueEvaluationCallback.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/HeadlessValueEvaluationCallback.java index 4a9d11904140..a3af93fe7668 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/HeadlessValueEvaluationCallback.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/HeadlessValueEvaluationCallback.java @@ -30,12 +30,7 @@ public class HeadlessValueEvaluationCallback implements XFullValueEvaluator.XFul public void startFetchingValue(@NotNull XFullValueEvaluator fullValueEvaluator) { fullValueEvaluator.startEvaluation(this); - new Alarm().addRequest(new Runnable() { - @Override - public void run() { - showProgress(); - } - }, 500); + new Alarm().addRequest(() -> showProgress(), 500); } @Override diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueGroupNodeImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueGroupNodeImpl.java index 8870d511f434..2dbbe471f15e 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueGroupNodeImpl.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueGroupNodeImpl.java @@ -38,12 +38,9 @@ public class XValueGroupNodeImpl extends XValueContainerNode implem } if (group.isAutoExpand()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!isObsolete()) { - myTree.expandPath(getPath()); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!isObsolete()) { + myTree.expandPath(getPath()); } }); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueNodePresentationConfigurator.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueNodePresentationConfigurator.java index 6a71db7e1e3b..c61885026eac 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueNodePresentationConfigurator.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/tree/nodes/XValueNodePresentationConfigurator.java @@ -95,12 +95,7 @@ public final class XValueNodePresentationConfigurator { node.applyPresentation(icon, presentation, hasChildren); } else { - Runnable updater = new Runnable() { - @Override - public void run() { - node.applyPresentation(icon, presentation, hasChildren); - } - }; + Runnable updater = () -> node.applyPresentation(icon, presentation, hasChildren); if (node instanceof XDebuggerTreeNode) { ((XDebuggerTreeNode)node).invokeNodeUpdate(updater); } diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java index 4ffbfdb74439..4bf8f829d5b9 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointsTestCase.java @@ -68,13 +68,8 @@ public abstract class XBreakpointsTestCase extends XDebuggerTestCase { result.add(breakpoint); } } - Collections.sort(result, new Comparator>() { - @Override - public int compare(XBreakpoint o1, XBreakpoint o2) { - return StringUtil.compare(((MyBreakpointProperties)o1.getProperties()).myOption, - ((MyBreakpointProperties)o2.getProperties()).myOption, true); - } - }); + Collections.sort(result, (o1, o2) -> StringUtil.compare(((MyBreakpointProperties)o1.getProperties()).myOption, + ((MyBreakpointProperties)o2.getProperties()).myOption, true)); return result; } } diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java index 822dd9d40ebf..bc280370a7e0 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java @@ -58,11 +58,8 @@ public abstract class XDebuggerTestCase extends PlatformTestCase { static void removeBreakPoint(final XBreakpointManagerImpl breakpointManager, final XBreakpoint breakpoint) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - breakpointManager.removeBreakpoint(breakpoint); - } + ApplicationManager.getApplication().runWriteAction(() -> { + breakpointManager.removeBreakpoint(breakpoint); }); } diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java index 4d436a2e5371..00b8ba027381 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java @@ -165,11 +165,7 @@ public class XDebuggerTestUtil { public static void waitForSwing() throws InterruptedException, InvocationTargetException { final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore(); s.down(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - s.up(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> s.up()); s.waitForUnsafe(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { public void run() { @@ -335,11 +331,8 @@ public class XDebuggerTestUtil { public static void assertSourcePosition(final XValue value, VirtualFile file, int offset) { final XTestNavigatable n = new XTestNavigatable(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - value.computeSourcePosition(n); - } + ApplicationManager.getApplication().runReadAction(() -> { + value.computeSourcePosition(n); }); assertNotNull(n.myPosition); assertEquals(file, n.myPosition.getFile()); diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/impl/actions/AttachToLocalProcessActionTest.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/impl/actions/AttachToLocalProcessActionTest.java index 55d2a635ecfc..ab1c0d15a691 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/impl/actions/AttachToLocalProcessActionTest.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/impl/actions/AttachToLocalProcessActionTest.java @@ -603,23 +603,20 @@ public class AttachToLocalProcessActionTest extends PlatformTestCase { @NotNull private static List createDebuggers(String... names) { - return ContainerUtil.map(names, new Function() { - @Override - public XLocalAttachDebugger fun(final String s) { - return new XLocalAttachDebugger() { - @NotNull - @Override - public String getDebuggerDisplayName() { - return s; - } + return ContainerUtil.map(names, s -> { + return new XLocalAttachDebugger() { + @NotNull + @Override + public String getDebuggerDisplayName() { + return s; + } - @NotNull - @Override - public XDebugSession attachDebugSession(@NotNull Project project, @NotNull ProcessInfo processInfo) throws ExecutionException { - return null; - } - }; - } + @NotNull + @Override + public XDebugSession attachDebugSession(@NotNull Project project, @NotNull ProcessInfo processInfo) throws ExecutionException { + return null; + } + }; }); } diff --git a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerComponent.java b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerComponent.java index c61a1024682e..060569cea65c 100644 --- a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerComponent.java +++ b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerComponent.java @@ -108,16 +108,13 @@ public class ByteCodeViewerComponent extends JPanel implements Disposable { } public void setText(final String bytecode, final int offset) { - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - Document fragmentDoc = myEditor.getDocument(); - fragmentDoc.setReadOnly(false); - fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), bytecode); - fragmentDoc.setReadOnly(true); - myEditor.getCaretModel().moveToOffset(offset); - myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - } + DocumentUtil.writeInRunUndoTransparentAction(() -> { + Document fragmentDoc = myEditor.getDocument(); + fragmentDoc.setReadOnly(false); + fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), bytecode); + fragmentDoc.setReadOnly(true); + myEditor.getCaretModel().moveToOffset(offset); + myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); }); } diff --git a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java index 17e917b9310c..05f0f0a85e54 100644 --- a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java +++ b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java @@ -126,13 +126,10 @@ public class ShowByteCodeAction extends AnAction { } final ByteCodeViewerComponent component = new ByteCodeViewerComponent(project, null); component.setText(myByteCode, targetElement); - Processor pinCallback = new Processor() { - @Override - public boolean process(JBPopup popup) { - codeViewerManager.recreateToolWindow(targetElement, targetElement); - popup.cancel(); - return false; - } + Processor pinCallback = popup -> { + codeViewerManager.recreateToolWindow(targetElement, targetElement); + popup.cancel(); + return false; }; final JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(component, null) diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/StaticMethodOnlyUsedInOneClassInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/StaticMethodOnlyUsedInOneClassInspectionBase.java index a815d218e928..9d10a449ec4c 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/StaticMethodOnlyUsedInOneClassInspectionBase.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/StaticMethodOnlyUsedInOneClassInspectionBase.java @@ -118,13 +118,10 @@ public class StaticMethodOnlyUsedInOneClassInspectionBase extends BaseInspection == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) { return null; } - progressManager.runProcess(new Runnable() { - @Override - public void run() { - final Query query = MethodReferencesSearch.search(method); - if (!query.forEach(UsageProcessor.this)) { - foundClass.set(null); - } + progressManager.runProcess(() -> { + final Query query = MethodReferencesSearch.search(method); + if (!query.forEach(UsageProcessor.this)) { + foundClass.set(null); } }, null); return foundClass.get(); diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java index 1225684c3f94..f31ea1c772aa 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java @@ -142,12 +142,8 @@ public class ObjectEqualityInspection extends BaseInspection { final GlobalSearchScope scope = GlobalSearchScope.allScope(aClass.getProject()); final PsiElementProcessor.CollectElementsWithLimit processor = new PsiElementProcessor.CollectElementsWithLimit(6); final ProgressManager progressManager = ProgressManager.getInstance(); - progressManager.runProcess(new Runnable() { - @Override - public void run() { - ClassInheritorsSearch.search(aClass, scope, true).forEach(new PsiElementProcessorAdapter(processor)); - } - }, null); + progressManager.runProcess( + (Runnable)() -> ClassInheritorsSearch.search(aClass, scope, true).forEach(new PsiElementProcessorAdapter(processor)), null); if (processor.isOverflow()) { return false; } diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/TrivialIfInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/TrivialIfInspection.java index 7e433e07080e..eb3276796e72 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/TrivialIfInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/TrivialIfInspection.java @@ -154,12 +154,7 @@ public class TrivialIfInspection extends BaseInspection implements CleanupLocalI return; } final Collection comments = ContainerUtil.map(PsiTreeUtil.findChildrenOfType(statement, PsiComment.class), - new Function() { - @Override - public PsiComment fun(PsiComment comment) { - return (PsiComment)comment.copy(); - } - }); + comment -> (PsiComment)comment.copy()); final String conditionText = condition.getText(); final PsiStatement thenBranch = statement.getThenBranch(); final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)ControlFlowUtils.stripBraces(thenBranch); diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/CaughtExceptionImmediatelyRethrownInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/CaughtExceptionImmediatelyRethrownInspection.java index abd120f6efe2..6efba31fbf8b 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/CaughtExceptionImmediatelyRethrownInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/CaughtExceptionImmediatelyRethrownInspection.java @@ -129,12 +129,9 @@ public class CaughtExceptionImmediatelyRethrownInspection extends BaseInspection } final PsiType type = parameter.getType(); final Set parameterClasses = new THashSet(); - processExceptionClasses(type, new Processor() { - @Override - public boolean process(PsiClass aClass) { - parameterClasses.add(aClass); - return true; - } + processExceptionClasses(type, aClass -> { + parameterClasses.add(aClass); + return true; }); if (parameterClasses.isEmpty()) { return false; @@ -147,17 +144,14 @@ public class CaughtExceptionImmediatelyRethrownInspection extends BaseInspection continue; } final PsiType nextType = nextParameter.getType(); - processExceptionClasses(nextType, new Processor() { - @Override - public boolean process(PsiClass aClass) { - for (PsiClass parameterClass : parameterClasses) { - if (parameterClass.isInheritor(aClass, true)) { - superClassExceptionType.set(Boolean.TRUE); - return false; - } + processExceptionClasses(nextType, aClass -> { + for (PsiClass parameterClass : parameterClasses) { + if (parameterClass.isInheritor(aClass, true)) { + superClassExceptionType.set(Boolean.TRUE); + return false; } - return true; } + return true; }); if (superClassExceptionType.get().booleanValue()) { return true; diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/ExceptionFromCatchWhichDoesntWrapInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/ExceptionFromCatchWhichDoesntWrapInspection.java index 3542d9e4b7e7..8503bc051d1e 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/ExceptionFromCatchWhichDoesntWrapInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/ExceptionFromCatchWhichDoesntWrapInspection.java @@ -152,26 +152,23 @@ public class ExceptionFromCatchWhichDoesntWrapInspection extends BaseInspection if (target instanceof PsiLocalVariable) { final PsiLocalVariable variable = (PsiLocalVariable)target; final Query query = ReferencesSearch.search(variable, variable.getUseScope(), false); - query.forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - final PsiElement parent = PsiTreeUtil.skipParentsOfType(element, PsiParenthesizedExpression.class); - if (!(parent instanceof PsiReferenceExpression)) { - return true; - } - final PsiElement grandParent = parent.getParent(); - if (!(grandParent instanceof PsiMethodCallExpression)) { - return true; - } - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; - final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - final PsiExpression[] arguments = argumentList.getExpressions(); - for (PsiExpression argument : arguments) { - argument.accept(ReferenceFinder.this); - } + query.forEach(reference -> { + final PsiElement element = reference.getElement(); + final PsiElement parent = PsiTreeUtil.skipParentsOfType(element, PsiParenthesizedExpression.class); + if (!(parent instanceof PsiReferenceExpression)) { return true; } + final PsiElement grandParent = parent.getParent(); + if (!(grandParent instanceof PsiMethodCallExpression)) { + return true; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + for (PsiExpression argument : arguments) { + argument.accept(ReferenceFinder.this); + } + return true; }); final PsiExpression initializer = variable.getInitializer(); if (initializer != null) { diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/AddToIgnoreIfAnnotatedByListQuickFix.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/AddToIgnoreIfAnnotatedByListQuickFix.java index 2a089098533a..fa235c6d68bc 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/AddToIgnoreIfAnnotatedByListQuickFix.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/AddToIgnoreIfAnnotatedByListQuickFix.java @@ -41,15 +41,12 @@ public class AddToIgnoreIfAnnotatedByListQuickFix { public static List build(final PsiModifierListOwner modifierListOwner, final List configurationList, final List fixes) { - SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(modifierListOwner, new Processor() { - @Override - public boolean process(String qualifiedName) { - fixes.add(new DelegatingFix(SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix( - InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", qualifiedName), - QuickFixBundle.message("fix.add.special.annotation.family"), - configurationList, qualifiedName, modifierListOwner))); - return true; - } + SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(modifierListOwner, qualifiedName -> { + fixes.add(new DelegatingFix(SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix( + InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", qualifiedName), + QuickFixBundle.message("fix.add.special.annotation.family"), + configurationList, qualifiedName, modifierListOwner))); + return true; }); return fixes; } diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java index 9c7dec10b9ca..4ceed8f0b8bb 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java @@ -51,31 +51,28 @@ public class SerialVersionUIDBuilder extends JavaRecursiveElementVisitor { private final Map memberMap = new HashMap(); private static final Comparator INTERFACE_COMPARATOR = - new Comparator() { - @Override - public int compare(PsiClass object1, PsiClass object2) { - if (object1 == null && object2 == null) { - return 0; - } - if (object1 == null) { - return 1; - } - if (object2 == null) { - return -1; - } - final String name1 = object1.getQualifiedName(); - final String name2 = object2.getQualifiedName(); - if (name1 == null && name2 == null) { - return 0; - } - if (name1 == null) { - return 1; - } - if (name2 == null) { - return -1; - } - return name1.compareTo(name2); + (object1, object2) -> { + if (object1 == null && object2 == null) { + return 0; } + if (object1 == null) { + return 1; + } + if (object2 == null) { + return -1; + } + final String name1 = object1.getQualifiedName(); + final String name2 = object2.getQualifiedName(); + if (name1 == null && name2 == null) { + return 0; + } + if (name1 == null) { + return 1; + } + if (name2 == null) { + return -1; + } + return name1.compareTo(name2); }; private SerialVersionUIDBuilder(PsiClass clazz) { @@ -86,14 +83,11 @@ public class SerialVersionUIDBuilder extends JavaRecursiveElementVisitor { if (!method.isConstructor() && !method.hasModifierProperty(PsiModifier.PRIVATE)) { final MemberSignature methodSignature = new MemberSignature(method); nonPrivateMethods.add(methodSignature); - SuperMethodsSearch.search(method, null, true, false).forEach(new Processor() { - @Override - public boolean process(MethodSignatureBackedByPsiMethod method) { - final MemberSignature superSignature = new MemberSignature(methodSignature.getName(), methodSignature.getModifiers(), - MemberSignature.createMethodSignature(method.getMethod())); - nonPrivateMethods.add(superSignature); - return true; - } + SuperMethodsSearch.search(method, null, true, false).forEach(method1 -> { + final MemberSignature superSignature = new MemberSignature(methodSignature.getName(), methodSignature.getModifiers(), + MemberSignature.createMethodSignature(method1.getMethod())); + nonPrivateMethods.add(superSignature); + return true; }); } } diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/inheritance/StaticInheritanceFix.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/inheritance/StaticInheritanceFix.java index 92264af1f9ac..c6c2b2ca263d 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/inheritance/StaticInheritanceFix.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/inheritance/StaticInheritanceFix.java @@ -115,33 +115,27 @@ class StaticInheritanceFix extends InspectionGadgetsFix { }); if (!isInheritor) continue; } - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (!FileModificationService.getInstance().preparePsiElementsForWrite(referenceExpression)) { - return; - } - final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); - final PsiReferenceExpression qualified = - (PsiReferenceExpression)elementFactory - .createExpressionFromText("xxx." + referenceExpression.getText(), referenceExpression); - final PsiReferenceExpression newReference = (PsiReferenceExpression)referenceExpression.replace(qualified); - final PsiReferenceExpression qualifier = (PsiReferenceExpression)newReference.getQualifierExpression(); - assert qualifier != null : DebugUtil.psiToString(newReference, false); - final PsiClass containingClass = field.getContainingClass(); - qualifier.bindToElement(containingClass); + final Runnable runnable = () -> { + if (!FileModificationService.getInstance().preparePsiElementsForWrite(referenceExpression)) { + return; } + final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); + final PsiReferenceExpression qualified = + (PsiReferenceExpression)elementFactory + .createExpressionFromText("xxx." + referenceExpression.getText(), referenceExpression); + final PsiReferenceExpression newReference = (PsiReferenceExpression)referenceExpression.replace(qualified); + final PsiReferenceExpression qualifier = (PsiReferenceExpression)newReference.getQualifierExpression(); + assert qualifier != null : DebugUtil.psiToString(newReference, false); + final PsiClass containingClass = field.getContainingClass(); + qualifier.bindToElement(containingClass); }; invokeWriteAction(runnable, file); } } - final Runnable runnable = new Runnable() { - @Override - public void run() { - PsiClassType classType = JavaPsiFacade.getInstance(project).getElementFactory().createType(iface); - IntentionAction fix = QuickFixFactory.getInstance().createExtendsListFix(implementingClass, classType, false); - fix.invoke(project, null, file); - } + final Runnable runnable = () -> { + PsiClassType classType = JavaPsiFacade.getInstance(project).getElementFactory().createType(iface); + IntentionAction fix = QuickFixFactory.getInstance().createExtendsListFix(implementingClass, classType, false); + fix.invoke(project, null, file); }; invokeWriteAction(runnable, file); } diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java index a1e002d5a987..1fd5a4e4bcfb 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java @@ -209,16 +209,13 @@ public class StringBufferReplaceableByStringBuilderInspection extends BaseInspec if (VariableAccessUtils.variableIsUsedInInnerClass(variable, context)) { return false; } - if (VariableAccessUtils.variableIsPassedAsMethodArgument(variable, context, true, new Processor() { - @Override - public boolean process(PsiCall call) { - final PsiMethod method = call.resolveMethod(); - if (method == null) { - return false; - } - final PsiClass aClass = method.getContainingClass(); - return aClass != null && excludes.contains(aClass.getQualifiedName()); + if (VariableAccessUtils.variableIsPassedAsMethodArgument(variable, context, true, call -> { + final PsiMethod method = call.resolveMethod(); + if (method == null) { + return false; } + final PsiClass aClass = method.getContainingClass(); + return aClass != null && excludes.contains(aClass.getQualifiedName()); })) { return false; } diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java index 499f9c618d19..bfc883881288 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java @@ -410,35 +410,28 @@ public class WeakestTypeFinder { private static List findAllSuperMethods(PsiMethod method) { final List result = new ArrayList(); - SuperMethodsSearch.search(method, null, true, false).forEach(new Processor() { - - @Override - public boolean process(MethodSignatureBackedByPsiMethod method) { - result.add(method.getMethod()); - return true; - } + SuperMethodsSearch.search(method, null, true, false).forEach(method12 -> { + result.add(method12.getMethod()); + return true; }); - Collections.sort(result, new Comparator() { - @Override - public int compare(PsiMethod method1, PsiMethod method2) { - // methods from deepest super classes first - final PsiClass aClass1 = method1.getContainingClass(); - final PsiClass aClass2 = method2.getContainingClass(); - if (aClass1 == null || aClass2 == null || aClass1.equals(aClass2)) { - return 0; - } else if (aClass1.isInterface() && !aClass2.isInterface()) { - return -1; - } else if (!aClass1.isInterface() && aClass2.isInterface()) { - return 1; - } else if (aClass1.isInheritor(aClass2, true)) { - return 1; - } else if (aClass2.isInheritor(aClass1, true)) { - return -1; - } - final String name1 = aClass1.getName(); - final String name2 = aClass2.getName(); - return name1.compareTo(name2); + Collections.sort(result, (method1, method2) -> { + // methods from deepest super classes first + final PsiClass aClass1 = method1.getContainingClass(); + final PsiClass aClass2 = method2.getContainingClass(); + if (aClass1 == null || aClass2 == null || aClass1.equals(aClass2)) { + return 0; + } else if (aClass1.isInterface() && !aClass2.isInterface()) { + return -1; + } else if (!aClass1.isInterface() && aClass2.isInterface()) { + return 1; + } else if (aClass1.isInheritor(aClass2, true)) { + return 1; + } else if (aClass2.isInheritor(aClass1, true)) { + return -1; } + final String name1 = aClass1.getName(); + final String name2 = aClass2.getName(); + return name1.compareTo(name2); }); return result; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ProtectedMemberInFinalClassInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ProtectedMemberInFinalClassInspection.java index 490ee1eae71b..e586c39a9254 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ProtectedMemberInFinalClassInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ProtectedMemberInFinalClassInspection.java @@ -85,45 +85,36 @@ public class ProtectedMemberInFinalClassInspection extends ProtectedMemberInFina if (member instanceof PsiMethod) { final PsiMethod method = (PsiMethod)member; SuperMethodsSearch.search(method, method.getContainingClass(), true, false).forEach( - new Processor() { - @Override - public boolean process(MethodSignatureBackedByPsiMethod methodSignature) { + methodSignature -> { final PsiMethod superMethod = methodSignature.getMethod(); conflicts.putValue(superMethod, InspectionGadgetsBundle.message( "0.will.have.incompatible.access.privileges.with.super.1", RefactoringUIUtil.getDescription(method, false), RefactoringUIUtil.getDescription(superMethod, true))); return true; - } - }); - OverridingMethodsSearch.search(method).forEach(new Processor() { - @Override - public boolean process(PsiMethod overridingMethod) { - conflicts.putValue(overridingMethod, InspectionGadgetsBundle.message( - "0.will.no.longer.be.visible.from.overriding.1", - RefactoringUIUtil.getDescription(method, false), - RefactoringUIUtil.getDescription(overridingMethod, true))); - return false; - } + }); + OverridingMethodsSearch.search(method).forEach(overridingMethod -> { + conflicts.putValue(overridingMethod, InspectionGadgetsBundle.message( + "0.will.no.longer.be.visible.from.overriding.1", + RefactoringUIUtil.getDescription(method, false), + RefactoringUIUtil.getDescription(overridingMethod, true))); + return false; }); } final PsiModifierList modifierListCopy = (PsiModifierList)modifierList.copy(); modifierListCopy.setModifierProperty(PsiModifier.PRIVATE, true); final Query search = ReferencesSearch.search(member, member.getResolveScope()); - search.forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (!JavaResolveUtil.isAccessible(member, member.getContainingClass(), modifierListCopy, element, null, null)) { - final PsiElement context = - PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiField.class, PsiClass.class, PsiFile.class); - conflicts.putValue(element, RefactoringBundle.message("0.with.1.visibility.is.not.accessible.from.2", - RefactoringUIUtil.getDescription(member, false), - PsiBundle.visibilityPresentation(PsiModifier.PRIVATE), - RefactoringUIUtil.getDescription(context, true))); - } - return true; + search.forEach(reference -> { + final PsiElement element1 = reference.getElement(); + if (!JavaResolveUtil.isAccessible(member, member.getContainingClass(), modifierListCopy, element1, null, null)) { + final PsiElement context = + PsiTreeUtil.getParentOfType(element1, PsiMethod.class, PsiField.class, PsiClass.class, PsiFile.class); + conflicts.putValue(element1, RefactoringBundle.message("0.with.1.visibility.is.not.accessible.from.2", + RefactoringUIUtil.getDescription(member, false), + PsiBundle.visibilityPresentation(PsiModifier.PRIVATE), + RefactoringUIUtil.getDescription(context, true))); } + return true; }); final boolean conflictsDialogOK; if (conflicts.isEmpty()) { @@ -132,17 +123,10 @@ public class ProtectedMemberInFinalClassInspection extends ProtectedMemberInFina if (!isOnTheFly()) { return; } - final ConflictsDialog conflictsDialog = new ConflictsDialog(member.getProject(), conflicts, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifierList.setModifierProperty(PRIVATE, true); - } - }); - } - }); + final ConflictsDialog conflictsDialog = new ConflictsDialog(member.getProject(), conflicts, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + modifierList.setModifierProperty(PRIVATE, true); + })); conflictsDialogOK = conflictsDialog.showAndGet(); } if (conflictsDialogOK) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/UtilityClassWithoutPrivateConstructorInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/UtilityClassWithoutPrivateConstructorInspection.java index 866e45ff4ba9..81eddc228626 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/UtilityClassWithoutPrivateConstructorInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/UtilityClassWithoutPrivateConstructorInspection.java @@ -101,14 +101,9 @@ public class UtilityClassWithoutPrivateConstructorInspection extends UtilityClas final PsiElement element = reference.getElement(); final PsiElement context = element.getParent(); if (context instanceof PsiNewExpression) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Messages.showInfoMessage(aClass.getProject(), - "Utility class has instantiations, private constructor will not be created", - "Can't generate constructor"); - } - }); + SwingUtilities.invokeLater(() -> Messages.showInfoMessage(aClass.getProject(), + "Utility class has instantiations, private constructor will not be created", + "Can't generate constructor")); return; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeClassFinalFix.java b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeClassFinalFix.java index 78ea40d37ad3..bf84afa9bc7a 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeClassFinalFix.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeClassFinalFix.java @@ -82,29 +82,19 @@ public class MakeClassFinalFix extends InspectionGadgetsFix { } final MultiMap conflicts = new MultiMap(); final Query search = ClassInheritorsSearch.search(containingClass); - search.forEach(new Processor() { - @Override - public boolean process(PsiClass aClass) { - conflicts.putValue(containingClass, InspectionGadgetsBundle - .message("0.will.no.longer.be.overridable.by.1", RefactoringUIUtil.getDescription(containingClass, false), - RefactoringUIUtil.getDescription(aClass, false))); - return true; - } + search.forEach(aClass -> { + conflicts.putValue(containingClass, InspectionGadgetsBundle + .message("0.will.no.longer.be.overridable.by.1", RefactoringUIUtil.getDescription(containingClass, false), + RefactoringUIUtil.getDescription(aClass, false))); + return true; }); final boolean conflictsDialogOK; if (!conflicts.isEmpty()) { - final ConflictsDialog conflictsDialog = new ConflictsDialog(element.getProject(), conflicts, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifierList.setModifierProperty(FINAL, true); - modifierList.setModifierProperty(ABSTRACT, false); - } - }); - } - }); + final ConflictsDialog conflictsDialog = new ConflictsDialog(element.getProject(), conflicts, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + modifierList.setModifierProperty(FINAL, true); + modifierList.setModifierProperty(ABSTRACT, false); + })); conflictsDialogOK = conflictsDialog.showAndGet(); } else { conflictsDialogOK = true; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/initialization/NonThreadSafeLazyInitializationInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/initialization/NonThreadSafeLazyInitializationInspection.java index 7b2355930287..42765d2c6d94 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/initialization/NonThreadSafeLazyInitializationInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/initialization/NonThreadSafeLazyInitializationInspection.java @@ -60,15 +60,12 @@ public class NonThreadSafeLazyInitializationInspection extends NonThreadSafeLazy return false; } final int[] writeCount = new int[1]; - return ReferencesSearch.search(field).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (!(element instanceof PsiExpression) || !PsiUtil.isAccessedForWriting((PsiExpression)element)) { - return true; - } - return ++writeCount[0] != 2; + return ReferencesSearch.search(field).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (!(element instanceof PsiExpression) || !PsiUtil.isAccessedForWriting((PsiExpression)element)) { + return true; } + return ++writeCount[0] != 2; }); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/HighlightUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/HighlightUtils.java index 6444ff8b0660..00dc27056939 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/HighlightUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/HighlightUtils.java @@ -64,55 +64,52 @@ public class HighlightUtils { return; } final Application application = ApplicationManager.getApplication(); - application.invokeLater(new Runnable() { - @Override - public void run() { - final PsiElement[] elements = - PsiUtilCore.toPsiElementArray(elementCollection); - final PsiElement firstElement = elements[0]; - if (ContainerUtil.exists(elements, new Condition() { - @Override - public boolean value(PsiElement element) { - return !element.isValid(); - } - })) { - return; + application.invokeLater(() -> { + final PsiElement[] elements = + PsiUtilCore.toPsiElementArray(elementCollection); + final PsiElement firstElement = elements[0]; + if (ContainerUtil.exists(elements, new Condition() { + @Override + public boolean value(PsiElement element) { + return !element.isValid(); } - final Project project = firstElement.getProject(); - if (project.isDisposed()) return; - final FileEditorManager editorManager = - FileEditorManager.getInstance(project); - final EditorColorsManager editorColorsManager = - EditorColorsManager.getInstance(); - final Editor editor = editorManager.getSelectedTextEditor(); - if (editor == null) { - return; - } - final EditorColorsScheme globalScheme = - editorColorsManager.getGlobalScheme(); - final TextAttributes textattributes = - globalScheme.getAttributes( - EditorColors.SEARCH_RESULT_ATTRIBUTES); - final HighlightManager highlightManager = - HighlightManager.getInstance(project); - highlightManager.addOccurrenceHighlights( - editor, elements, textattributes, true, null); - final WindowManager windowManager = - WindowManager.getInstance(); - final StatusBar statusBar = - windowManager.getStatusBar(project); - statusBar.setInfo(InspectionGadgetsBundle.message( - "press.escape.to.remove.highlighting.message")); - final FindManager findmanager = - FindManager.getInstance(project); - FindModel findmodel = findmanager.getFindNextModel(); - if (findmodel == null) { - findmodel = findmanager.getFindInFileModel(); - } - findmodel.setSearchHighlighters(true); - findmanager.setFindWasPerformed(); - findmanager.setFindNextModel(findmodel); + })) { + return; } + final Project project = firstElement.getProject(); + if (project.isDisposed()) return; + final FileEditorManager editorManager = + FileEditorManager.getInstance(project); + final EditorColorsManager editorColorsManager = + EditorColorsManager.getInstance(); + final Editor editor = editorManager.getSelectedTextEditor(); + if (editor == null) { + return; + } + final EditorColorsScheme globalScheme = + editorColorsManager.getGlobalScheme(); + final TextAttributes textattributes = + globalScheme.getAttributes( + EditorColors.SEARCH_RESULT_ATTRIBUTES); + final HighlightManager highlightManager = + HighlightManager.getInstance(project); + highlightManager.addOccurrenceHighlights( + editor, elements, textattributes, true, null); + final WindowManager windowManager = + WindowManager.getInstance(); + final StatusBar statusBar = + windowManager.getStatusBar(project); + statusBar.setInfo(InspectionGadgetsBundle.message( + "press.escape.to.remove.highlighting.message")); + final FindManager findmanager = + FindManager.getInstance(project); + FindModel findmodel = findmanager.getFindNextModel(); + if (findmodel == null) { + findmodel = findmanager.getFindInFileModel(); + } + findmodel.setSearchHighlighters(true); + findmanager.setFindWasPerformed(); + findmanager.setFindNextModel(findmodel); }); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/ui/UiUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/ui/UiUtils.java index fd0f8efd0c9d..a2f7b1735bdb 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/ui/UiUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/ui/UiUtils.java @@ -55,12 +55,9 @@ public class UiUtils { public void run(AnActionButton button) { final ListWrappingTableModel tableModel = table.getModel(); tableModel.addRow(); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - final int lastRowIndex = tableModel.getRowCount() - 1; - editTableCell(table, lastRowIndex, 0); - } + EventQueue.invokeLater(() -> { + final int lastRowIndex = tableModel.getRowCount() - 1; + editTableCell(table, lastRowIndex, 0); }); } }).setRemoveAction(new RemoveAction(table)) @@ -120,18 +117,15 @@ public class UiUtils { private static void editTableCell(final ListTable table, final int row, final int column) { final ListSelectionModel selectionModel = table.getSelectionModel(); selectionModel.setSelectionInterval(row, row); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - final ListWrappingTableModel tableModel = table.getModel(); - table.requestFocus(); - final Rectangle rectangle = table.getCellRect(row, column, true); - table.scrollRectToVisible(rectangle); - table.editCellAt(row, column); - final TableCellEditor editor = table.getCellEditor(); - final Component component = editor.getTableCellEditorComponent(table, tableModel.getValueAt(row, column), true, row, column); - component.requestFocus(); - } + EventQueue.invokeLater(() -> { + final ListWrappingTableModel tableModel = table.getModel(); + table.requestFocus(); + final Rectangle rectangle = table.getCellRect(row, column, true); + table.scrollRectToVisible(rectangle); + table.editCellAt(row, column); + final TableCellEditor editor = table.getCellEditor(); + final Component component = editor.getTableCellEditorComponent(table, tableModel.getValueAt(row, column), true, row, column); + component.requestFocus(); }); } @@ -202,38 +196,35 @@ public class UiUtils { @Override public void run(AnActionButton button) { - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - final TableCellEditor editor = table.getCellEditor(); - if (editor != null) { - editor.stopCellEditing(); + EventQueue.invokeLater(() -> { + final TableCellEditor editor = table.getCellEditor(); + if (editor != null) { + editor.stopCellEditing(); + } + final ListSelectionModel selectionModel = table.getSelectionModel(); + final int minIndex = selectionModel.getMinSelectionIndex(); + final int maxIndex = selectionModel.getMaxSelectionIndex(); + if (minIndex == -1 || maxIndex == -1) { + return; + } + final ListWrappingTableModel tableModel = table.getModel(); + for (int i = minIndex; i <= maxIndex; i++) { + if (selectionModel.isSelectedIndex(i)) { + tableModel.removeRow(i); } - final ListSelectionModel selectionModel = table.getSelectionModel(); - final int minIndex = selectionModel.getMinSelectionIndex(); - final int maxIndex = selectionModel.getMaxSelectionIndex(); - if (minIndex == -1 || maxIndex == -1) { - return; - } - final ListWrappingTableModel tableModel = table.getModel(); - for (int i = minIndex; i <= maxIndex; i++) { - if (selectionModel.isSelectedIndex(i)) { - tableModel.removeRow(i); - } - } - final int count = tableModel.getRowCount(); - if (count <= minIndex) { - selectionModel.setSelectionInterval(count - 1, count - 1); - } - else if (minIndex <= 0) { - if (count > 0) { - selectionModel.setSelectionInterval(0, 0); - } - } - else { - selectionModel.setSelectionInterval(minIndex - 1, minIndex - 1); + } + final int count = tableModel.getRowCount(); + if (count <= minIndex) { + selectionModel.setSelectionInterval(count - 1, count - 1); + } + else if (minIndex <= 0) { + if (count > 0) { + selectionModel.setSelectionInterval(0, 0); } } + else { + selectionModel.setSelectionInterval(minIndex - 1, minIndex - 1); + } }); } } diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/AdvancedSettingsUI.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/AdvancedSettingsUI.java index adb4b51057a8..7300143a9c14 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/AdvancedSettingsUI.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/AdvancedSettingsUI.java @@ -148,29 +148,17 @@ public class AdvancedSettingsUI implements SearchableConfigurable { private final ReferenceEditorWithBrowseButton mySubstField; public AdvancedSettingsPanel() { - myAnnotationField = new ReferenceEditorWithBrowseButton(null, myProject, new Function() { - public Document fun(String s) { - return PsiUtilEx.createDocument(s, myProject); - } - }, myConfiguration.getLanguageAnnotationClass()); + myAnnotationField = new ReferenceEditorWithBrowseButton(null, myProject, s -> PsiUtilEx.createDocument(s, myProject), myConfiguration.getLanguageAnnotationClass()); myAnnotationField.addActionListener(new BrowseClassListener(myProject, myAnnotationField)); myAnnotationField.setEnabled(!myProject.isDefault()); addField(myLanguageAnnotationPanel, myAnnotationField); - myPatternField = new ReferenceEditorWithBrowseButton(null, myProject, new Function() { - public Document fun(String s) { - return PsiUtilEx.createDocument(s, myProject); - } - }, myConfiguration.getPatternAnnotationClass()); + myPatternField = new ReferenceEditorWithBrowseButton(null, myProject, s -> PsiUtilEx.createDocument(s, myProject), myConfiguration.getPatternAnnotationClass()); myPatternField.addActionListener(new BrowseClassListener(myProject, myPatternField)); myPatternField.setEnabled(!myProject.isDefault()); addField(myPatternAnnotationPanel, myPatternField); - mySubstField = new ReferenceEditorWithBrowseButton(null, myProject, new Function() { - public Document fun(String s) { - return PsiUtilEx.createDocument(s, myProject); - } - }, myConfiguration.getPatternAnnotationClass()); + mySubstField = new ReferenceEditorWithBrowseButton(null, myProject, s -> PsiUtilEx.createDocument(s, myProject), myConfiguration.getPatternAnnotationClass()); mySubstField.addActionListener(new BrowseClassListener(myProject, mySubstField)); mySubstField.setEnabled(!myProject.isDefault()); addField(mySubstAnnotationPanel, mySubstField); diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java index 0c1cf6408c26..14b4c34438a6 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java @@ -76,18 +76,16 @@ public class MethodParameterPanel extends AbstractInjectionPanel() { - public Document fun(String s) { - final Document document = PsiUtilEx.createDocument(s, project); - document.addDocumentListener(new DocumentAdapter() { - @Override - public void documentChanged(final DocumentEvent e) { - updateParamTree(); - updateTree(); - } - }); - return document; - } + myClassField = new ReferenceEditorWithBrowseButton(new BrowseClassListener(project), project, s -> { + final Document document = PsiUtilEx.createDocument(s, project); + document.addDocumentListener(new DocumentAdapter() { + @Override + public void documentChanged(final DocumentEvent e) { + updateParamTree(); + updateTree(); + } + }); + return document; }, ""); myClassPanel.add(myClassField, BorderLayout.CENTER); myParamsTable.getTree().setShowsRootHandles(true); @@ -181,27 +179,25 @@ public class MethodParameterPanel extends AbstractInjectionPanel visitedSignatures = new THashSet(); - for (PsiClass psiClass : classes) { - for (PsiMethod method : psiClass.getMethods()) { - final PsiModifierList modifiers = method.getModifierList(); - if (modifiers.hasModifierProperty(PsiModifier.PRIVATE) || modifiers.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) continue; - if (MethodParameterInjection.isInjectable(method.getReturnType(), method.getProject()) || - ContainerUtil.find(method.getParameterList().getParameters(), new Condition() { - public boolean value(PsiParameter p) { - return MethodParameterInjection.isInjectable(p.getType(), p.getProject()); - } - }) != null) { - final MethodParameterInjection.MethodInfo info = MethodParameterInjection.createMethodInfo(method); - if (!visitedSignatures.add(info.getMethodSignature())) continue; - myData.put(method, info); - } + ApplicationManager.getApplication().runReadAction(() -> { + final PsiType classType = getClassType(); + final PsiClass[] classes = classType instanceof PsiClassType? JavaPsiFacade.getInstance(myProject). + findClasses(classType.getCanonicalText(), GlobalSearchScope.allScope(myProject)) : PsiClass.EMPTY_ARRAY; + if (classes.length == 0) return; + final THashSet visitedSignatures = new THashSet(); + for (PsiClass psiClass : classes) { + for (PsiMethod method : psiClass.getMethods()) { + final PsiModifierList modifiers = method.getModifierList(); + if (modifiers.hasModifierProperty(PsiModifier.PRIVATE) || modifiers.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) continue; + if (MethodParameterInjection.isInjectable(method.getReturnType(), method.getProject()) || + ContainerUtil.find(method.getParameterList().getParameters(), new Condition() { + public boolean value(PsiParameter p) { + return MethodParameterInjection.isInjectable(p.getType(), p.getProject()); + } + }) != null) { + final MethodParameterInjection.MethodInfo info = MethodParameterInjection.createMethodInfo(method); + if (!visitedSignatures.add(info.getMethodSignature())) continue; + myData.put(method, info); } } } @@ -211,12 +207,10 @@ public class MethodParameterPanel extends AbstractInjectionPanel methods = new ArrayList(myData.keySet()); - Collections.sort(methods, new Comparator() { - public int compare(final PsiMethod o1, final PsiMethod o2) { - final int names = o1.getName().compareTo(o2.getName()); - if (names != 0) return names; - return o1.getParameterList().getParametersCount() - o2.getParameterList().getParametersCount(); - } + Collections.sort(methods, (o1, o2) -> { + final int names = o1.getName().compareTo(o2.getName()); + if (names != 0) return names; + return o1.getParameterList().getParametersCount() - o2.getParameterList().getParametersCount(); }); for (PsiMethod method : methods) { final PsiParameter[] params = method.getParameterList().getParameters(); diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java index 62f8183b113a..ec78e0ee6e4e 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java @@ -183,19 +183,16 @@ public class ConcatenationInjector implements ConcatenationAwareInjector { private void visitVariableUsages(PsiVariable variable) { if (variable == null) return; if (myConfiguration.getAdvancedConfiguration().getDfaOption() != Configuration.DfaOption.OFF && visitedVars.add(variable)) { - ReferencesSearch.search(variable, searchScope).forEach(new Processor() { - @Override - public boolean process(PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - if (element instanceof PsiExpression) { - final PsiExpression refExpression = (PsiExpression)element; - places.add(refExpression); - if (!myUnparsable) { - myUnparsable = checkUnparsableReference(refExpression); - } + ReferencesSearch.search(variable, searchScope).forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + if (element instanceof PsiExpression) { + final PsiExpression refExpression = (PsiExpression)element; + places.add(refExpression); + if (!myUnparsable) { + myUnparsable = checkUnparsableReference(refExpression); } - return true; } + return true; }); } } diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java index b6fd1dba5726..52f65224e7f4 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java @@ -114,15 +114,14 @@ public class JavaLanguageInjectionSupport extends AbstractLanguageInjectionSuppo if (injectionsMap.isEmpty() && annotations.isEmpty()) return false; final ArrayList originalInjections = new ArrayList(injectionsMap.keySet()); - final List newInjections = ContainerUtil.mapNotNull(originalInjections, new NullableFunction() { - public BaseInjection fun(final BaseInjection injection) { - final Pair pair = injectionsMap.get(injection); - final String placeText = getPatternStringForJavaPlace(pair.first, pair.second); - final BaseInjection newInjection = injection.copy(); - newInjection.setPlaceEnabled(placeText, false); - return InjectorUtils.canBeRemoved(newInjection)? null : newInjection; - } - }); + final List newInjections = ContainerUtil.mapNotNull(originalInjections, + (NullableFunction)injection -> { + final Pair pair = injectionsMap.get(injection); + final String placeText = getPatternStringForJavaPlace(pair.first, pair.second); + final BaseInjection newInjection = injection.copy(); + newInjection.setPlaceEnabled(placeText, false); + return InjectorUtils.canBeRemoved(newInjection)? null : newInjection; + }); configuration.replaceInjectionsWithUndo(project, newInjections, originalInjections, annotations); return true; } @@ -161,11 +160,9 @@ public class JavaLanguageInjectionSupport extends AbstractLanguageInjectionSuppo builder.addCancelAction(); builder.setCenterPanel(panel.getComponent()); builder.setTitle(EditInjectionSettingsAction.EDIT_INJECTION_TITLE); - builder.setOkOperation(new Runnable() { - public void run() { - panel.apply(); - builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); - } + builder.setOkOperation(() -> { + panel.apply(); + builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); }); if (builder.show() == DialogWrapper.OK_EXIT_CODE) { return new BaseInjection(methodParameterInjection.getSupportId()).copyFrom(methodParameterInjection); @@ -213,18 +210,15 @@ public class JavaLanguageInjectionSupport extends AbstractLanguageInjectionSuppo final PsiModifierListOwner modifierListOwner, @NotNull PsiLanguageInjectionHost host, final String languageId) { - return doAddLanguageAnnotation(project, modifierListOwner, host, languageId, new Processor() { - @Override - public boolean process(PsiLanguageInjectionHost host) { - final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration(); - boolean allowed = configuration.isSourceModificationAllowed(); - configuration.setSourceModificationAllowed(true); - try { - return doInjectInJava(project, host, host, languageId); - } - finally { - configuration.setSourceModificationAllowed(allowed); - } + return doAddLanguageAnnotation(project, modifierListOwner, host, languageId, host1 -> { + final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration(); + boolean allowed = configuration.isSourceModificationAllowed(); + configuration.setSourceModificationAllowed(true); + try { + return doInjectInJava(project, host1, host1, languageId); + } + finally { + configuration.setSourceModificationAllowed(allowed); } }); } diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java index 09dc40917bf7..f731a98e0f7e 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java @@ -52,12 +52,9 @@ public final class LanguageReference extends StringLiteralReference { @NotNull public Object[] getVariants() { List list = InjectLanguageAction.getAllInjectables(); - return ContainerUtil.map2Array(list, LookupElement.class, new Function() { - @Override - public LookupElement fun(Injectable injectable) { - return LookupElementBuilder.create(injectable.getId()).withIcon(injectable.getIcon()).withTailText( - "(" + injectable.getDisplayName() + ")", true); - } + return ContainerUtil.map2Array(list, LookupElement.class, (Function)injectable -> { + return LookupElementBuilder.create(injectable.getId()).withIcon(injectable.getIcon()).withTailText( + "(" + injectable.getDisplayName() + ")", true); }); } } diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/RegExpEnumReference.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/RegExpEnumReference.java index d81f28336689..b04ee21be154 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/RegExpEnumReference.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/RegExpEnumReference.java @@ -48,10 +48,8 @@ final class RegExpEnumReference extends StringLiteralReference { if (values == null || values.size() == 0) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } - return ContainerUtil.map2Array(values, new Function() { - public Object fun(String s) { - return LookupElementBuilder.create(s).withIcon(PlatformIcons.ENUM_ICON); - } + return ContainerUtil.map2Array(values, s -> { + return LookupElementBuilder.create(s).withIcon(PlatformIcons.ENUM_ICON); }); } diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/Configuration.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/Configuration.java index fe27cac71b81..97cf09f10696 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/Configuration.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/Configuration.java @@ -320,12 +320,7 @@ public class Configuration extends SimpleModificationTracker implements Persiste } protected Element getState(final Element element) { - Comparator comparator = new Comparator() { - @Override - public int compare(final BaseInjection o1, final BaseInjection o2) { - return Comparing.compare(o1.getDisplayName(), o2.getDisplayName()); - } - }; + Comparator comparator = (o1, o2) -> Comparing.compare(o1.getDisplayName(), o2.getDisplayName()); List injectorIds = new ArrayList(myInjections.keySet()); Collections.sort(injectorIds); for (String key : injectorIds) { @@ -410,12 +405,9 @@ public class Configuration extends SimpleModificationTracker implements Persiste } } main: for (BaseInjection other : importingInjections) { - final List matchingInjections = ContainerUtil.concat(other.getInjectionPlaces(), new Function>() { - @Override - public Collection fun(final InjectionPlace o) { - final Collection collection = placeMap.get(o); - return collection == null? Collections.emptyList() : collection; - } + final List matchingInjections = ContainerUtil.concat(other.getInjectionPlaces(), o -> { + final Collection collection = placeMap.get(o); + return collection == null? Collections.emptyList() : collection; }); if (matchingInjections.isEmpty()) { newInjections.add(other); @@ -502,17 +494,13 @@ public class Configuration extends SimpleModificationTracker implements Persiste final List originalInjections, final List psiElementsToRemove) { replaceInjectionsWithUndo(project, newInjections, originalInjections, psiElementsToRemove, - new PairProcessor, List>() { - @Override - public boolean process(final List add, - final List remove) { - replaceInjectionsWithUndoInner(add, remove); - if (ContainerUtil.find(add, LANGUAGE_INJECTION_CONDITION) != null || ContainerUtil.find(remove, - LANGUAGE_INJECTION_CONDITION) != null) { - FileContentUtil.reparseOpenedFiles(); - } - return true; + (add, remove) -> { + replaceInjectionsWithUndoInner(add, remove); + if (ContainerUtil.find(add, LANGUAGE_INJECTION_CONDITION) != null || ContainerUtil.find(remove, + LANGUAGE_INJECTION_CONDITION) != null) { + FileContentUtil.reparseOpenedFiles(); } + return true; }); } diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/InjectionsSettingsUI.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/InjectionsSettingsUI.java index 2725f00678d8..8d05ac48dbab 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/InjectionsSettingsUI.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/InjectionsSettingsUI.java @@ -115,11 +115,7 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract } private void createActions(ToolbarDecorator decorator) { - final Consumer consumer = new Consumer() { - public void consume(final BaseInjection injection) { - addInjection(injection); - } - }; + final Consumer consumer = injection -> addInjection(injection); final Factory producer = new NullableFactory() { public BaseInjection create() { final InjInfo info = getSelectedInjection(); @@ -133,11 +129,8 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract .put(support.getId(), action == null ? AbstractLanguageInjectionSupport.createDefaultEditAction(myProject, producer) : action); mySupports.put(support.getId(), support); } - Collections.sort(myAddActions, new Comparator() { - public int compare(final AnAction o1, final AnAction o2) { - return Comparing.compare(o1.getTemplatePresentation().getText(), o2.getTemplatePresentation().getText()); - } - }); + Collections.sort(myAddActions, + (o1, o2) -> Comparing.compare(o1.getTemplatePresentation().getText(), o2.getTemplatePresentation().getText())); decorator.disableUpDownActions(); decorator.setAddActionUpdater(new AnActionButtonUpdater() { @Override @@ -376,11 +369,7 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) { ContainerUtil.addAll(configurables, support.createSettings(myProject, myConfiguration)); } - Collections.sort(configurables, new Comparator() { - public int compare(final Configurable o1, final Configurable o2) { - return Comparing.compare(o1.getDisplayName(), o2.getDisplayName()); - } - }); + Collections.sort(configurables, (o1, o2) -> Comparing.compare(o1.getDisplayName(), o2.getDisplayName())); return configurables.toArray(new Configurable[configurables.size()]); } @@ -391,14 +380,12 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract } private static void sortInjections(final List injections) { - Collections.sort(injections, new Comparator() { - public int compare(final BaseInjection o1, final BaseInjection o2) { - final int support = Comparing.compare(o1.getSupportId(), o2.getSupportId()); - if (support != 0) return support; - final int lang = Comparing.compare(o1.getInjectedLanguageId(), o2.getInjectedLanguageId()); - if (lang != 0) return lang; - return Comparing.compare(o1.getDisplayName(), o2.getDisplayName()); - } + Collections.sort(injections, (o1, o2) -> { + final int support = Comparing.compare(o1.getSupportId(), o2.getSupportId()); + if (support != 0) return support; + final int lang = Comparing.compare(o1.getInjectedLanguageId(), o2.getInjectedLanguageId()); + if (lang != 0) return lang; + return Comparing.compare(o1.getDisplayName(), o2.getDisplayName()); }); } @@ -481,11 +468,8 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract private void performAdd(AnActionButton e) { DefaultActionGroup group = new DefaultActionGroup(myAddActions); - JBPopupFactory.getInstance().createActionGroupPopup(null, group, e.getDataContext(), JBPopupFactory.ActionSelectionAid.NUMBERING, true, new Runnable() { - public void run() { - updateCountLabel(); - } - }, -1).show(e.getPreferredPopupPoint()); + JBPopupFactory.getInstance().createActionGroupPopup(null, group, e.getDataContext(), JBPopupFactory.ActionSelectionAid.NUMBERING, true, + () -> updateCountLabel(), -1).show(e.getPreferredPopupPoint()); } @Nls @@ -522,21 +506,17 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract }.installOn(this); final String[] maxName = new String[]{""}; - ContainerUtil.process(injections, new Processor() { - public boolean process(final InjInfo injection) { - String languageId = injection.injection.getInjectedLanguageId(); - Language language = InjectedLanguage.findLanguageById(languageId); - String displayName = language == null ? languageId : language.getDisplayName(); - if (maxName[0].length() < displayName.length()) maxName[0] = displayName; - return true; - } + ContainerUtil.process(injections, injection -> { + String languageId = injection.injection.getInjectedLanguageId(); + Language language = InjectedLanguage.findLanguageById(languageId); + String displayName = language == null ? languageId : language.getDisplayName(); + if (maxName[0].length() < displayName.length()) maxName[0] = displayName; + return true; }); - ContainerUtil.process(InjectedLanguage.getAvailableLanguages(), new Processor() { - public boolean process(final Language language) { - String displayName = language.getDisplayName(); - if (maxName[0].length() < displayName.length()) maxName[0] = displayName; - return true; - } + ContainerUtil.process(InjectedLanguage.getAvailableLanguages(), language -> { + String displayName = language.getDisplayName(); + if (maxName[0].length() < displayName.length()) maxName[0] = displayName; + return true; }); Icon icon = FileTypes.PLAIN_TEXT.getIcon(); int preferred = (int)(new JLabel(maxName[0], icon, SwingConstants.LEFT).getPreferredSize().width * 1.1); @@ -558,17 +538,12 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract final TableCellRenderer booleanCellRenderer = createBooleanCellRenderer(); final TableCellRenderer displayNameCellRenderer = createDisplayNameCellRenderer(); final TableCellRenderer languageCellRenderer = createLanguageCellRenderer(); - final Comparator languageComparator = new Comparator() { - public int compare(final InjInfo o1, final InjInfo o2) { - return Comparing.compare(o1.injection.getInjectedLanguageId(), o2.injection.getInjectedLanguageId()); - } - }; - final Comparator displayNameComparator = new Comparator() { - public int compare(final InjInfo o1, final InjInfo o2) { - final int support = Comparing.compare(o1.injection.getSupportId(), o2.injection.getSupportId()); - if (support != 0) return support; - return Comparing.compare(o1.injection.getDisplayName(), o2.injection.getDisplayName()); - } + final Comparator languageComparator = + (o1, o2) -> Comparing.compare(o1.injection.getInjectedLanguageId(), o2.injection.getInjectedLanguageId()); + final Comparator displayNameComparator = (o1, o2) -> { + final int support = Comparing.compare(o1.injection.getSupportId(), o2.injection.getSupportId()); + if (support != 0) return support; + return Comparing.compare(o1.injection.getDisplayName(), o2.injection.getDisplayName()); }; final ColumnInfo[] columnInfos = {new ColumnInfo(" ") { @Override @@ -646,12 +621,7 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract @Override public Comparator getComparator() { - return new Comparator() { - @Override - public int compare(final InjInfo o1, final InjInfo o2) { - return Comparing.compare(valueOf(o1), valueOf(o2)); - } - }; + return (o1, o2) -> Comparing.compare(valueOf(o1), valueOf(o2)); } }); } @@ -837,18 +807,16 @@ public class InjectionsSettingsUI extends SearchableConfigurable.Parent.Abstract this.title = title; bundledInjections.addAll(cfg.getDefaultInjections()); originalInjections = new ArrayList(ContainerUtil - .concat(InjectorUtils.getActiveInjectionSupportIds(), new Function>() { - public Collection fun(final String s) { - List injections = - CfgInfo.this.cfg instanceof Configuration.Prj ? ((Configuration.Prj)CfgInfo.this.cfg).getOwnInjections(s) : CfgInfo.this.cfg - .getInjections(s); - return ContainerUtil.findAll(injections, new Condition() { - public boolean value(final BaseInjection injection) { - String id = injection.getInjectedLanguageId(); - return InjectedLanguage.findLanguageById(id) != null || ReferenceInjector.findById(id) != null; - } - }); - } + .concat(InjectorUtils.getActiveInjectionSupportIds(), s -> { + List injections = + CfgInfo.this.cfg instanceof Configuration.Prj ? ((Configuration.Prj)CfgInfo.this.cfg).getOwnInjections(s) : CfgInfo.this.cfg + .getInjections(s); + return ContainerUtil.findAll(injections, new Condition() { + public boolean value(final BaseInjection injection) { + String id = injection.getInjectedLanguageId(); + return InjectedLanguage.findLanguageById(id) != null || ReferenceInjector.findById(id) != null; + } + }); })); sortInjections(originalInjections); reset(); diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java index 132393737525..925a39621b00 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java @@ -143,17 +143,15 @@ public abstract class AbstractLanguageInjectionSupport extends LanguageInjection builder.setDimensionServiceKey("#org.intellij.plugins.intelliLang.inject.config.ui.BaseInjectionDialog"); builder.setCenterPanel(panel.getComponent()); builder.setTitle(EditInjectionSettingsAction.EDIT_INJECTION_TITLE); - builder.setOkOperation(new Runnable() { - public void run() { - try { - panel.apply(); - builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); - } - catch (Exception e) { - final Throwable cause = e.getCause(); - final String message = e.getMessage() + (cause != null? "\n "+cause.getMessage():""); - Messages.showErrorDialog(project, message, "Unable to Save"); - } + builder.setOkOperation(() -> { + try { + panel.apply(); + builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); + } + catch (Exception e) { + final Throwable cause = e.getCause(); + final String message = e.getMessage() + (cause != null? "\n "+cause.getMessage():""); + Messages.showErrorDialog(project, message, "Unable to Save"); } }); if (builder.show() == DialogWrapper.OK_EXIT_CODE) { diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/EditInjectionSettingsAction.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/EditInjectionSettingsAction.java index cc97dfd8c000..eeaa77cd761a 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/EditInjectionSettingsAction.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/EditInjectionSettingsAction.java @@ -60,10 +60,8 @@ public class EditInjectionSettingsAction implements IntentionAction, LowPriority } public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - invokeImpl(project, editor, file); - } + ApplicationManager.getApplication().runReadAction(() -> { + invokeImpl(project, editor, file); }); } diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java index 46513d219cb9..2f1f3fee5037 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java @@ -112,17 +112,13 @@ public class InjectLanguageAction implements IntentionAction, LowPriorityAction } public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { - doChooseLanguageToInject(editor, new Processor() { - public boolean process(final Injectable injectable) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - if (!project.isDisposed()) { - invokeImpl(project, editor, file, injectable); - } - } - }); - return false; - } + doChooseLanguageToInject(editor, injectable -> { + ApplicationManager.getApplication().runReadAction(() -> { + if (!project.isDisposed()) { + invokeImpl(project, editor, file, injectable); + } + }); + return false; }); } @@ -195,20 +191,13 @@ public class InjectLanguageAction implements IntentionAction, LowPriorityAction Dimension minSize = new JLabel(PlainTextLanguage.INSTANCE.getDisplayName(), EmptyIcon.ICON_16, SwingConstants.LEFT).getMinimumSize(); minSize.height *= 4; list.setMinimumSize(minSize); - JBPopup popup = new PopupChooserBuilder(list).setItemChoosenCallback(new Runnable() { - public void run() { - Injectable value = (Injectable)list.getSelectedValue(); - if (value != null) { - onChosen.process(value); - PropertiesComponent.getInstance().setValue(LAST_INJECTED_LANGUAGE, value.getId()); - } + JBPopup popup = new PopupChooserBuilder(list).setItemChoosenCallback(() -> { + Injectable value = (Injectable)list.getSelectedValue(); + if (value != null) { + onChosen.process(value); + PropertiesComponent.getInstance().setValue(LAST_INJECTED_LANGUAGE, value.getId()); } - }).setFilteringEnabled(new Function() { - @Override - public String fun(Object language) { - return ((Injectable)language).getDisplayName(); - } - }).setMinSize(minSize).createPopup(); + }).setFilteringEnabled(language -> ((Injectable)language).getDisplayName()).setMinSize(minSize).createPopup(); final String lastInjected = PropertiesComponent.getInstance().getValue(LAST_INJECTED_LANGUAGE); if (lastInjected != null) { Injectable injectable = ContainerUtil.find(injectables, new Condition() { diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectorUtils.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectorUtils.java index 2960fc24f486..af81a222bba0 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectorUtils.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectorUtils.java @@ -55,11 +55,9 @@ import java.util.regex.Pattern; * @author Gregory.Shrago */ public class InjectorUtils { - public static final Comparator RANGE_COMPARATOR = new Comparator() { - public int compare(final TextRange o1, final TextRange o2) { - if (o1.intersects(o2)) return 0; - return o1.getStartOffset() - o2.getStartOffset(); - } + public static final Comparator RANGE_COMPARATOR = (o1, o2) -> { + if (o1.intersects(o2)) return 0; + return o1.getStartOffset() - o2.getStartOffset(); }; private InjectorUtils() { diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesRegistry.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesRegistry.java index 56d1e9863320..cf3ff56b40c3 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesRegistry.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesRegistry.java @@ -130,12 +130,9 @@ public class TemporaryPlacesRegistry { TempPlace nextPlace = new TempPlace(null, pointer); Configuration.replaceInjectionsWithUndo( project, nextPlace, place, Collections.emptyList(), - new PairProcessor() { - public boolean process(final TempPlace add, - final TempPlace remove) { - addInjectionPlace(add); - return true; - } + (add, remove) -> { + addInjectionPlace(add); + return true; }); return true; } @@ -148,11 +145,9 @@ public class TemporaryPlacesRegistry { TempPlace place = new TempPlace(language, pointer); Configuration.replaceInjectionsWithUndo( myProject, place, prevPlace, Collections.emptyList(), - new PairProcessor() { - public boolean process(TempPlace add, final TempPlace remove) { - addInjectionPlace(add); - return true; - } + (add, remove) -> { + addInjectionPlace(add); + return true; }); } diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/UnInjectLanguageAction.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/UnInjectLanguageAction.java index 4d27fa305b14..6625851bf0bf 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/UnInjectLanguageAction.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/UnInjectLanguageAction.java @@ -63,10 +63,8 @@ public class UnInjectLanguageAction implements IntentionAction, LowPriorityActio } public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - invokeImpl(project, editor, file); - } + ApplicationManager.getApplication().runReadAction(() -> { + invokeImpl(project, editor, file); }); } diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/BaseInjection.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/BaseInjection.java index f5fddc277c04..1a2e56a7e313 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/BaseInjection.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/BaseInjection.java @@ -137,10 +137,8 @@ public class BaseInjection implements Injection, PersistentStateComponent ranges = getMatchingRanges(myCompiledValuePattern.matcher(StringPattern.newBombedCharSequence(sb)), sb.length()); - return !ranges.isEmpty() ? ContainerUtil.map(ranges, new Function() { - public TextRange fun(TextRange s) { - return new TextRange(textEscaper.getOffsetInHost(s.getStartOffset(), textRange), textEscaper.getOffsetInHost(s.getEndOffset(), textRange)); - } + return !ranges.isEmpty() ? ContainerUtil.map(ranges, s -> { + return new TextRange(textEscaper.getOffsetInHost(s.getStartOffset(), textRange), textEscaper.getOffsetInHost(s.getEndOffset(), textRange)); }) : Collections.emptyList(); } } @@ -278,11 +276,7 @@ public class BaseInjection implements Injection, PersistentStateComponent() { - public int compare(final InjectionPlace o1, final InjectionPlace o2) { - return Comparing.compare(o1.getText(), o2.getText()); - } - }); + Arrays.sort(myPlaces, (o1, o2) -> Comparing.compare(o1.getText(), o2.getText())); for (InjectionPlace place : myPlaces) { final Element child = new Element("place").setContent(new CDATA(place.getText())); if (!place.isEnabled()) child.setAttribute("disabled", "true"); diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/InjectionPlace.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/InjectionPlace.java index 236b24b7c43c..766db641e1c3 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/InjectionPlace.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/config/InjectionPlace.java @@ -29,13 +29,7 @@ public class InjectionPlace { public static final InjectionPlace[] EMPTY_ARRAY = new InjectionPlace[0]; - public static final ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public InjectionPlace[] create(int count) { - return count == 0? EMPTY_ARRAY : new InjectionPlace[count]; - } - }; + public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new InjectionPlace[count]; private final boolean myEnabled; private final ElementPattern myElementPattern; diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/util/StringMatcher.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/util/StringMatcher.java index f6f19c0abd86..d4d4a645b9e8 100644 --- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/util/StringMatcher.java +++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/util/StringMatcher.java @@ -170,10 +170,8 @@ public abstract class StringMatcher { protected MatcherSet(Set target) { super(target); - myPattern = StringUtil.join(target, new Function() { - public String fun(StringMatcher s) { - return s.getPattern(); - } + myPattern = StringUtil.join(target, s -> { + return s.getPattern(); }, "|"); } diff --git a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjectionSupport.java b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjectionSupport.java index abe3349a9c15..f3d4580b6c3a 100644 --- a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjectionSupport.java +++ b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjectionSupport.java @@ -168,11 +168,9 @@ public class XmlLanguageInjectionSupport extends AbstractLanguageInjectionSuppor builder.addCancelAction(); builder.setCenterPanel(panel.getComponent()); builder.setTitle(EditInjectionSettingsAction.EDIT_INJECTION_TITLE); - builder.setOkOperation(new Runnable() { - public void run() { - panel.apply(); - builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); - } + builder.setOkOperation(() -> { + panel.apply(); + builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); }); if (builder.show() == DialogWrapper.OK_EXIT_CODE) { return xmlInjection.copy(); diff --git a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjector.java b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjector.java index fc17ad429936..6516aff81d4d 100644 --- a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjector.java +++ b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/xml/XmlLanguageInjector.java @@ -78,24 +78,22 @@ public final class XmlLanguageInjector implements MultiHostInjector { final TreeSet ranges = new TreeSet(InjectorUtils.RANGE_COMPARATOR); final PsiFile containingFile = xmlElement.getContainingFile(); final Ref unparsableRef = Ref.create(); - getInjectedLanguage(xmlElement, unparsableRef, new PairProcessor>>() { - public boolean process(final Language language, List> list) { - for (Trinity trinity : list) { - if (ranges.contains(trinity.third.shiftRight(trinity.first.getTextRange().getStartOffset()))) return true; - } - for (Trinity trinity : list) { - final PsiLanguageInjectionHost host = trinity.first; - if (host.getContainingFile() != containingFile) continue; - final TextRange textRange = trinity.third; - ranges.add(textRange.shiftRight(host.getTextRange().getStartOffset())); - } - InjectorUtils.registerInjection(language, list, containingFile, registrar); - InjectorUtils.registerSupport(mySupport, true, registrar); - if (Boolean.TRUE.equals(unparsableRef.get())) { - InjectorUtils.putInjectedFileUserData(registrar, InjectedLanguageUtil.FRANKENSTEIN_INJECTION, Boolean.TRUE); - } - return true; + getInjectedLanguage(xmlElement, unparsableRef, (language, list) -> { + for (Trinity trinity : list) { + if (ranges.contains(trinity.third.shiftRight(trinity.first.getTextRange().getStartOffset()))) return true; } + for (Trinity trinity : list) { + final PsiLanguageInjectionHost host1 = trinity.first; + if (host1.getContainingFile() != containingFile) continue; + final TextRange textRange = trinity.third; + ranges.add(textRange.shiftRight(host1.getTextRange().getStartOffset())); + } + InjectorUtils.registerInjection(language, list, containingFile, registrar); + InjectorUtils.registerSupport(mySupport, true, registrar); + if (Boolean.TRUE.equals(unparsableRef.get())) { + InjectorUtils.putInjectedFileUserData(registrar, InjectedLanguageUtil.FRANKENSTEIN_INJECTION, Boolean.TRUE); + } + return true; }); } diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/interfacetoclass/ConvertInterfaceToClassIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/interfacetoclass/ConvertInterfaceToClassIntention.java index 2eff5538fa0f..8a008819837f 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/interfacetoclass/ConvertInterfaceToClassIntention.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/interfacetoclass/ConvertInterfaceToClassIntention.java @@ -107,25 +107,22 @@ public class ConvertInterfaceToClassIntention extends Intention { final SearchScope searchScope = anInterface.getUseScope(); final Query query = ClassInheritorsSearch.search(anInterface, searchScope, false); final MultiMap conflicts = new MultiMap(); - query.forEach(new Processor() { - @Override - public boolean process(PsiClass aClass) { - final PsiReferenceList extendsList = aClass.getExtendsList(); - if (extendsList == null) { - return true; - } - final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); - if (referenceElements.length > 0) { - final PsiElement target = referenceElements[0].resolve(); - if (target != null) { - conflicts.putValue(aClass, IntentionPowerPackBundle.message( - "0.already.extends.1.and.will.not.compile.after.converting.2.to.a.class", - RefactoringUIUtil.getDescription(aClass, true), RefactoringUIUtil.getDescription(target, true), - RefactoringUIUtil.getDescription(anInterface, false))); - } - } + query.forEach(aClass -> { + final PsiReferenceList extendsList = aClass.getExtendsList(); + if (extendsList == null) { return true; } + final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); + if (referenceElements.length > 0) { + final PsiElement target = referenceElements[0].resolve(); + if (target != null) { + conflicts.putValue(aClass, IntentionPowerPackBundle.message( + "0.already.extends.1.and.will.not.compile.after.converting.2.to.a.class", + RefactoringUIUtil.getDescription(aClass, true), RefactoringUIUtil.getDescription(target, true), + RefactoringUIUtil.getDescription(anInterface, false))); + } + } + return true; }); final PsiFunctionalExpression functionalExpression = FunctionalExpressionSearch.search(anInterface, searchScope).findFirst(); @@ -141,17 +138,10 @@ public class ConvertInterfaceToClassIntention extends Intention { if (getApplication().isUnitTestMode()) { throw new BaseRefactoringProcessor.ConflictsInTestsException(conflicts.values()); } - final ConflictsDialog conflictsDialog = new ConflictsDialog(anInterface.getProject(), conflicts, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - convertInterfaceToClass(anInterface); - } - }); - } - }); + final ConflictsDialog conflictsDialog = new ConflictsDialog(anInterface.getProject(), conflicts, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + convertInterfaceToClass(anInterface); + })); conflictsDialogOK = conflictsDialog.showAndGet(); } if (conflictsDialogOK) { diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/modifiers/ModifierIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/modifiers/ModifierIntention.java index fdb492e2c54d..f0081ec10fd4 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/modifiers/ModifierIntention.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/modifiers/ModifierIntention.java @@ -65,17 +65,10 @@ abstract class ModifierIntention extends Intention implements LowPriorityAction if (conflicts.isEmpty()) { conflictsDialogOK = true; } else { - final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifierList.setModifierProperty(getModifier(), true); - } - }); - } - }); + final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + modifierList.setModifierProperty(getModifier(), true); + })); conflictsDialogOK = conflictsDialog.showAndGet(); } if (conflictsDialogOK) { @@ -119,59 +112,49 @@ abstract class ModifierIntention extends Intention implements LowPriorityAction if (member instanceof PsiMethod) { final PsiMethod method = (PsiMethod)member; SuperMethodsSearch.search(method, method.getContainingClass(), true, false).forEach( - new Processor() { - @Override - public boolean process(MethodSignatureBackedByPsiMethod methodSignature) { - final PsiMethod superMethod = methodSignature.getMethod(); - if (!hasCompatibleVisibility(superMethod, true)) { - conflicts.putValue(superMethod, IntentionPowerPackBundle.message( - "0.will.have.incompatible.access.privileges.with.super.1", - RefactoringUIUtil.getDescription(method, false), - RefactoringUIUtil.getDescription(superMethod, true))); - } - return true; + methodSignature -> { + final PsiMethod superMethod = methodSignature.getMethod(); + if (!hasCompatibleVisibility(superMethod, true)) { + conflicts.putValue(superMethod, IntentionPowerPackBundle.message( + "0.will.have.incompatible.access.privileges.with.super.1", + RefactoringUIUtil.getDescription(method, false), + RefactoringUIUtil.getDescription(superMethod, true))); } + return true; }); - OverridingMethodsSearch.search(method).forEach(new Processor() { - @Override - public boolean process(PsiMethod overridingMethod) { - if (!isVisibleFromOverridingMethod(method, overridingMethod)) { - conflicts.putValue(overridingMethod, IntentionPowerPackBundle.message( - "0.will.no.longer.be.visible.from.overriding.1", - RefactoringUIUtil.getDescription(method, false), - RefactoringUIUtil.getDescription(overridingMethod, true))); - } - else if (!hasCompatibleVisibility(overridingMethod, false)) { - conflicts.putValue(overridingMethod, IntentionPowerPackBundle.message( - "0.will.have.incompatible.access.privileges.with.overriding.1", - RefactoringUIUtil.getDescription(method, false), - RefactoringUIUtil.getDescription(overridingMethod, true))); - } - return false; + OverridingMethodsSearch.search(method).forEach(overridingMethod -> { + if (!isVisibleFromOverridingMethod(method, overridingMethod)) { + conflicts.putValue(overridingMethod, IntentionPowerPackBundle.message( + "0.will.no.longer.be.visible.from.overriding.1", + RefactoringUIUtil.getDescription(method, false), + RefactoringUIUtil.getDescription(overridingMethod, true))); } + else if (!hasCompatibleVisibility(overridingMethod, false)) { + conflicts.putValue(overridingMethod, IntentionPowerPackBundle.message( + "0.will.have.incompatible.access.privileges.with.overriding.1", + RefactoringUIUtil.getDescription(method, false), + RefactoringUIUtil.getDescription(overridingMethod, true))); + } + return false; }); } final PsiModifierList modifierListCopy = (PsiModifierList)modifierList.copy(); modifierListCopy.setModifierProperty(getModifier(), true); final Query search = ReferencesSearch.search(member, member.getResolveScope()); - search.forEach(new Processor() { - - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (JavaResolveUtil.isAccessible(member, member.getContainingClass(), modifierListCopy, element, null, null)) { - return true; - } - final PsiElement context = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiField.class, PsiClass.class, PsiFile.class); - if (context == null) { - return true; - } - conflicts.putValue(element, RefactoringBundle.message("0.with.1.visibility.is.not.accessible.from.2", - RefactoringUIUtil.getDescription(member, false), - PsiBundle.visibilityPresentation(getModifier()), - RefactoringUIUtil.getDescription(context, true))); + search.forEach(reference -> { + final PsiElement element = reference.getElement(); + if (JavaResolveUtil.isAccessible(member, member.getContainingClass(), modifierListCopy, element, null, null)) { return true; } + final PsiElement context = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiField.class, PsiClass.class, PsiFile.class); + if (context == null) { + return true; + } + conflicts.putValue(element, RefactoringBundle.message("0.with.1.visibility.is.not.accessible.from.2", + RefactoringUIUtil.getDescription(member, false), + PsiBundle.visibilityPresentation(getModifier()), + RefactoringUIUtil.getDescription(context, true))); + return true; }); return conflicts; } diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/psiutils/HighlightUtil.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/psiutils/HighlightUtil.java index 7b22c615b26b..2d4697323b0e 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/psiutils/HighlightUtil.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/psiutils/HighlightUtil.java @@ -62,43 +62,39 @@ public class HighlightUtil { return; } final Application application = ApplicationManager.getApplication(); - application.invokeLater(new Runnable() { - public void run() { - final PsiElement[] elements = PsiUtilCore.toPsiElementArray(elementCollection); - final PsiElement firstElement = elements[0]; - if (!firstElement.isValid()) { - return; - } - final Project project = firstElement.getProject(); - final FileEditorManager editorManager = FileEditorManager.getInstance(project); - final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance(); - final Editor editor = editorManager.getSelectedTextEditor(); - if (editor == null) { - return; - } - final EditorColorsScheme globalScheme = editorColorsManager.getGlobalScheme(); - final TextAttributes textattributes = globalScheme.getAttributes( - EditorColors.SEARCH_RESULT_ATTRIBUTES); - final HighlightManager highlightManager = HighlightManager.getInstance(project); - highlightManager.addOccurrenceHighlights(editor, elements, textattributes, true, null); - final FindManager findmanager = FindManager.getInstance(project); - FindModel findmodel = findmanager.getFindNextModel(); - if (findmodel == null) { - findmodel = findmanager.getFindInFileModel(); - } - findmodel.setSearchHighlighters(true); - findmanager.setFindWasPerformed(); - findmanager.setFindNextModel(findmodel); - application.invokeLater(new Runnable() { - public void run() { - final WindowManager windowManager = WindowManager.getInstance(); - final StatusBar statusBar = windowManager.getStatusBar(project); - if (statusBar != null) { - statusBar.setInfo(statusBarText); - } - } - }); + application.invokeLater(() -> { + final PsiElement[] elements = PsiUtilCore.toPsiElementArray(elementCollection); + final PsiElement firstElement = elements[0]; + if (!firstElement.isValid()) { + return; } + final Project project = firstElement.getProject(); + final FileEditorManager editorManager = FileEditorManager.getInstance(project); + final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance(); + final Editor editor = editorManager.getSelectedTextEditor(); + if (editor == null) { + return; + } + final EditorColorsScheme globalScheme = editorColorsManager.getGlobalScheme(); + final TextAttributes textattributes = globalScheme.getAttributes( + EditorColors.SEARCH_RESULT_ATTRIBUTES); + final HighlightManager highlightManager = HighlightManager.getInstance(project); + highlightManager.addOccurrenceHighlights(editor, elements, textattributes, true, null); + final FindManager findmanager = FindManager.getInstance(project); + FindModel findmodel = findmanager.getFindNextModel(); + if (findmodel == null) { + findmodel = findmanager.getFindInFileModel(); + } + findmodel.setSearchHighlighters(true); + findmanager.setFindWasPerformed(); + findmanager.setFindNextModel(findmodel); + application.invokeLater(() -> { + final WindowManager windowManager = WindowManager.getInstance(); + final StatusBar statusBar = windowManager.getStatusBar(project); + if (statusBar != null) { + statusBar.setInfo(statusBarText); + } + }); }); } diff --git a/plugins/ant/src/com/intellij/lang/ant/AntIntrospector.java b/plugins/ant/src/com/intellij/lang/ant/AntIntrospector.java index ef0fa80192b1..7d278492daba 100644 --- a/plugins/ant/src/com/intellij/lang/ant/AntIntrospector.java +++ b/plugins/ant/src/com/intellij/lang/ant/AntIntrospector.java @@ -242,11 +242,9 @@ public final class AntIntrospector { private static void scheduleCacheCleaning() { ourCacheCleaner.cancelAllRequests(); - ourCacheCleaner.addRequest(new Runnable() { - public void run() { - synchronized (ourCache) { - ourCache.clear(); - } + ourCacheCleaner.addRequest(() -> { + synchronized (ourCache) { + ourCache.clear(); } }, CACHE_CLEAN_TIMEOUT); } diff --git a/plugins/ant/src/com/intellij/lang/ant/AntSupport.java b/plugins/ant/src/com/intellij/lang/ant/AntSupport.java index d742beb31095..b10aeccb50c9 100644 --- a/plugins/ant/src/com/intellij/lang/ant/AntSupport.java +++ b/plugins/ant/src/com/intellij/lang/ant/AntSupport.java @@ -51,11 +51,7 @@ public class AntSupport { daemon.restart(); } else { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - daemon.restart(); - } - }); + SwingUtilities.invokeLater(() -> daemon.restart()); } } diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java index aa31fadc47c8..cc4858798f86 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java @@ -799,67 +799,55 @@ public final class AntBuildMessageView extends JPanel implements DataProvider, O final AntBuildFileBase buildFile = myBuildFile; final boolean isBackground = buildFile != null && buildFile.isRunInBackground(); final boolean shouldActivate = !isBackground || getErrorCount() > 0; - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - final Runnable finishRunnable = new Runnable() { - public void run() { - final int errorCount = getErrorCount(); - try { - final AntBuildFileBase buildFile = myBuildFile; - if (buildFile != null) { - if (errorCount == 0 && buildFile.isViewClosedWhenNoErrors()) { - close(); - } - else if (errorCount > 0) { - myTreeView.scrollToFirstError(); - } - else { - myTreeView.scrollToStatus(); - } - } - else { - myTreeView.scrollToLastMessage(); - } + UIUtil.invokeLaterIfNeeded(() -> { + final Runnable finishRunnable = () -> { + final int errorCount = getErrorCount(); + try { + final AntBuildFileBase buildFile1 = myBuildFile; + if (buildFile1 != null) { + if (errorCount == 0 && buildFile1.isViewClosedWhenNoErrors()) { + close(); } - finally { - VirtualFileManager.getInstance().asyncRefresh(new Runnable() { - public void run() { - antBuildListener.buildFinished(aborted ? AntBuildListener.ABORTED : AntBuildListener.FINISHED_SUCCESSFULLY, errorCount); - } - }); + else if (errorCount > 0) { + myTreeView.scrollToFirstError(); + } + else { + myTreeView.scrollToStatus(); } - } - }; - if (shouldActivate) { - final ToolWindow toolWindow = !myProject.isDisposed() ? ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW) : null; - if (toolWindow != null) { // can be null if project is closed - toolWindow.activate(finishRunnable, false); } else { - finishRunnable.run(); + myTreeView.scrollToLastMessage(); } } + finally { + VirtualFileManager.getInstance().asyncRefresh( + () -> antBuildListener.buildFinished(aborted ? AntBuildListener.ABORTED : AntBuildListener.FINISHED_SUCCESSFULLY, errorCount)); + } + }; + if (shouldActivate) { + final ToolWindow toolWindow = !myProject.isDisposed() ? ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW) : null; + if (toolWindow != null) { // can be null if project is closed + toolWindow.activate(finishRunnable, false); + } else { finishRunnable.run(); } } + else { + finishRunnable.run(); + } }); } } }); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (!myProject.isDisposed()) { - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - @Override - public void run() { - if (!myIsOutputPaused) { - new OutputFlusher().doFlush(); - } - } - }); - } + SwingUtilities.invokeLater(() -> { + if (!myProject.isDisposed()) { + DumbService.getInstance(myProject).runWhenSmart(() -> { + if (!myIsOutputPaused) { + new OutputFlusher().doFlush(); + } + }); } }); } diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java index b72f284b4523..8aa03817c8d8 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java @@ -188,11 +188,8 @@ public final class ExecutionHandler { handler = JUnitProcessHandler.runCommandLine(commandLine); } catch (final ExecutionException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ExecutionErrorDialog.show(e, AntBundle.message("could.not.start.process.error.dialog.title"), project); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> ExecutionErrorDialog.show(e, AntBundle.message("could.not.start.process.error.dialog.title"), project)); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return null; } diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/HyperlinkUtil.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/HyperlinkUtil.java index 83f735399d92..2f264216a914 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/HyperlinkUtil.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/HyperlinkUtil.java @@ -100,19 +100,17 @@ final class HyperlinkUtil { private static PlaceInfo makePlaceInfo(final String className, final String fileName, final int line, final Project project, final int lparenthIndex, final int rparenthIndex){ final PlaceInfo[] info = new PlaceInfo[1]; ApplicationManager.getApplication().runReadAction( - new Runnable(){ - public void run(){ - PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)); - if (aClass == null) return; - PsiFile file = aClass.getContainingFile(); - String fileName1 = fileName.replace(File.separatorChar, '/'); - int slashIndex = fileName1.lastIndexOf('/'); - String shortFileName = slashIndex < 0 ? fileName : fileName.substring(slashIndex + 1); - final String name = file.getName(); - if (name == null) return; - if (!name.equalsIgnoreCase(shortFileName)) return; - info[0] = new PlaceInfo(file.getVirtualFile(), line, 1, lparenthIndex, rparenthIndex); - } + () -> { + PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)); + if (aClass == null) return; + PsiFile file = aClass.getContainingFile(); + String fileName1 = fileName.replace(File.separatorChar, '/'); + int slashIndex = fileName1.lastIndexOf('/'); + String shortFileName = slashIndex < 0 ? fileName : fileName.substring(slashIndex + 1); + final String name = file.getName(); + if (name == null) return; + if (!name.equalsIgnoreCase(shortFileName)) return; + info[0] = new PlaceInfo(file.getVirtualFile(), line, 1, lparenthIndex, rparenthIndex); } ); return info[0]; @@ -149,15 +147,13 @@ final class HyperlinkUtil { final PsiFile[] psiFile = new PsiFile[1]; final PsiManager psiManager = PsiManager.getInstance(project); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - PsiClass psiClass = - JavaPsiFacade.getInstance(psiManager.getProject()).findClass(possibleTestClassName, GlobalSearchScope.allScope(project)); - if (psiClass == null) return; - PsiElement parent = psiClass.getParent(); - if (parent instanceof PsiFile) { - psiFile[0] = (PsiFile)parent; - } + ApplicationManager.getApplication().runReadAction(() -> { + PsiClass psiClass = + JavaPsiFacade.getInstance(psiManager.getProject()).findClass(possibleTestClassName, GlobalSearchScope.allScope(project)); + if (psiClass == null) return; + PsiElement parent = psiClass.getParent(); + if (parent instanceof PsiFile) { + psiFile[0] = (PsiFile)parent; } }); diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/MessageNode.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/MessageNode.java index 0b584a55400d..d87b12ac9ac4 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/MessageNode.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/MessageNode.java @@ -37,28 +37,26 @@ final class MessageNode extends DefaultMutableTreeNode { private boolean myAllowToShowPosition; public MessageNode(final AntMessage message, final Project project, final boolean allowToShowPosition) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - myMessage = message; - myText = message.getTextLines(); - if(myMessage.getFile() != null) { - PsiFile psiFile = PsiManager.getInstance(project).findFile(myMessage.getFile()); - if (psiFile != null) { - myEditorDocument = PsiDocumentManager.getInstance(project).getDocument(psiFile); - if(myEditorDocument != null) { - int line = myMessage.getLine(); - int column = myMessage.getColumn(); - if(line-1 >= 0 && line < myEditorDocument.getLineCount()) { - int start = myEditorDocument.getLineStartOffset(line-1) + column-1; - if(start >=0 && start < myEditorDocument.getTextLength()) { - myRangeMarker = myEditorDocument.createRangeMarker(start, start); - } + ApplicationManager.getApplication().runReadAction(() -> { + myMessage = message; + myText = message.getTextLines(); + if(myMessage.getFile() != null) { + PsiFile psiFile = PsiManager.getInstance(project).findFile(myMessage.getFile()); + if (psiFile != null) { + myEditorDocument = PsiDocumentManager.getInstance(project).getDocument(psiFile); + if(myEditorDocument != null) { + int line = myMessage.getLine(); + int column = myMessage.getColumn(); + if(line-1 >= 0 && line < myEditorDocument.getLineCount()) { + int start = myEditorDocument.getLineStartOffset(line-1) + column-1; + if(start >=0 && start < myEditorDocument.getTextLength()) { + myRangeMarker = myEditorDocument.createRangeMarker(start, start); } } } } - myAllowToShowPosition = allowToShowPosition; } + myAllowToShowPosition = allowToShowPosition; }); } diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java index 3af6d25c5c82..70ba5e6c016a 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java @@ -240,16 +240,14 @@ public class OutputParser{ for (int idx = 0; tokenizer.hasMoreTokens(); idx++) { strings[idx] = tokenizer.nextToken(); } - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - VirtualFile file = url == null ? null : VirtualFileManager.getInstance().findFileByUrl(url); - messageView.outputJavacMessage(convertCategory(category), strings, file, url, lineNum, columnNum); + ApplicationManager.getApplication().runReadAction(() -> { + VirtualFile file = url == null ? null : VirtualFileManager.getInstance().findFileByUrl(url); + messageView.outputJavacMessage(convertCategory(category), strings, file, url, lineNum, columnNum); - if (file != null && category == CompilerMessageCategory.ERROR) { - final WolfTheProblemSolver wolf = WolfTheProblemSolver.getInstance(project); - final Problem problem = wolf.convertToProblem(file, lineNum, columnNum, strings); - wolf.weHaveGotNonIgnorableProblems(file, Collections.singletonList(problem)); - } + if (file != null && category == CompilerMessageCategory.ERROR) { + final WolfTheProblemSolver wolf = WolfTheProblemSolver.getInstance(project); + final Problem problem = wolf.convertToProblem(file, lineNum, columnNum, strings); + wolf.weHaveGotNonIgnorableProblems(file, Collections.singletonList(problem)); } }); } diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/PathUtilEx.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/PathUtilEx.java index 740a61184c8d..1b339f3f25e4 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/PathUtilEx.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/PathUtilEx.java @@ -40,12 +40,7 @@ import java.util.List; public class PathUtilEx { @NonNls private static final String IDEA_PREPEND_RTJAR = "idea.prepend.rtjar"; - private static final Function MODULE_JDK = new Function() { - @Nullable - public Sdk fun(Module module) { - return ModuleRootManager.getInstance(module).getSdk(); - } - }; + private static final Function MODULE_JDK = module -> ModuleRootManager.getInstance(module).getSdk(); private static final Convertor SDK_VERSION = new Convertor() { public String convert(Sdk sdk) { return sdk.getVersionString(); diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/PlainTextView.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/PlainTextView.java index 5d681fc1d9d1..0ff5b282eb54 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/PlainTextView.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/PlainTextView.java @@ -87,12 +87,10 @@ public final class PlainTextView implements AntOutputView { try { if (file != null) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - String presentableUrl = file.getPresentableUrl(); - builder.append(presentableUrl); - builder.append(' '); - } + ApplicationManager.getApplication().runReadAction(() -> { + String presentableUrl = file.getPresentableUrl(); + builder.append(presentableUrl); + builder.append(' '); }); } else if (url != null) { diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/TreeView.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/TreeView.java index 2c9f1e15b49f..ad09a95feddc 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/TreeView.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/TreeView.java @@ -227,12 +227,10 @@ public final class TreeView implements AntOutputView, OccurenceNavigator { final VirtualFile file = message.getFile(); if (message.getLine() > 0) { if (file != null) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - String presentableUrl = file.getPresentableUrl(); - builder.append(presentableUrl); - builder.append(' '); - } + ApplicationManager.getApplication().runReadAction(() -> { + String presentableUrl = file.getPresentableUrl(); + builder.append(presentableUrl); + builder.append(' '); }); } else if (url != null) { diff --git a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorer.java b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorer.java index 1956fbd7d6c0..cb0cd03de696 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorer.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorer.java @@ -223,38 +223,36 @@ public class AntExplorer extends SimpleToolWindowPanel implements DataProvider, if (files.length == 0) { return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - final AntConfiguration antConfiguration = myConfig; - if (antConfiguration == null) { - return; + ApplicationManager.getApplication().invokeLater(() -> { + final AntConfiguration antConfiguration = myConfig; + if (antConfiguration == null) { + return; + } + final List ignoredFiles = new ArrayList(); + for (VirtualFile file : files) { + try { + antConfiguration.addBuildFile(file); } - final List ignoredFiles = new ArrayList(); - for (VirtualFile file : files) { - try { - antConfiguration.addBuildFile(file); - } - catch (AntNoFileException e) { - ignoredFiles.add(e.getFile()); - } + catch (AntNoFileException e) { + ignoredFiles.add(e.getFile()); } - if (ignoredFiles.size() != 0) { - String messageText; - final StringBuilder message = StringBuilderSpinAllocator.alloc(); - try { - String separator = ""; - for (final VirtualFile virtualFile : ignoredFiles) { - message.append(separator); - message.append(virtualFile.getPresentableUrl()); - separator = "\n"; - } - messageText = message.toString(); + } + if (ignoredFiles.size() != 0) { + String messageText; + final StringBuilder message = StringBuilderSpinAllocator.alloc(); + try { + String separator = ""; + for (final VirtualFile virtualFile : ignoredFiles) { + message.append(separator); + message.append(virtualFile.getPresentableUrl()); + separator = "\n"; } - finally { - StringBuilderSpinAllocator.dispose(message); - } - Messages.showWarningDialog(myProject, messageText, AntBundle.message("cannot.add.ant.files.dialog.title")); + messageText = message.toString(); } + finally { + StringBuilderSpinAllocator.dispose(message); + } + Messages.showWarningDialog(myProject, messageText, AntBundle.message("cannot.add.ant.files.dialog.title")); } }); } @@ -465,25 +463,17 @@ public class AntExplorer extends SimpleToolWindowPanel implements DataProvider, return myProject != null? myTreeExpander : null; } else if (CommonDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) { - final List virtualFiles = collectAntFiles(new Function() { - @Override - public VirtualFile fun(AntBuildFile buildFile) { - final VirtualFile virtualFile = buildFile.getVirtualFile(); - if (virtualFile != null && virtualFile.isValid()) { - return virtualFile; - } - return null; + final List virtualFiles = collectAntFiles(buildFile -> { + final VirtualFile virtualFile = buildFile.getVirtualFile(); + if (virtualFile != null && virtualFile.isValid()) { + return virtualFile; } + return null; }); return virtualFiles == null ? null : virtualFiles.toArray(new VirtualFile[virtualFiles.size()]); } else if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) { - final List elements = collectAntFiles(new Function() { - @Override - public PsiElement fun(AntBuildFile buildFile) { - return buildFile.getAntFile(); - } - }); + final List elements = collectAntFiles(buildFile -> buildFile.getAntFile()); return elements == null ? null : elements.toArray(new PsiElement[elements.size()]); } return super.getData(dataId); @@ -511,11 +501,8 @@ public class AntExplorer extends SimpleToolWindowPanel implements DataProvider, } } final List result = new ArrayList(); - ContainerUtil.addAllNotNull(result, ContainerUtil.map(antFiles, new Function() { - @Override - public T fun(AntBuildFile buildFile) { - return function.fun(buildFile); - } + ContainerUtil.addAllNotNull(result, ContainerUtil.map(antFiles, buildFile -> { + return function.fun(buildFile); })); return result.isEmpty() ? null : result; } diff --git a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java index e5ac5943bf87..10a722f55f86 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/explorer/AntExplorerTreeStructure.java @@ -36,15 +36,12 @@ final class AntExplorerTreeStructure extends AbstractTreeStructure { private final Project myProject; private final Object myRoot = new Object(); private boolean myFilteredTargets = false; - private static final Comparator ourTargetComparator = new Comparator() { - @Override - public int compare(final AntBuildTarget target1, final AntBuildTarget target2) { - final String name1 = target1.getDisplayName(); - if (name1 == null) return Integer.MIN_VALUE; - final String name2 = target2.getDisplayName(); - if (name2 == null) return Integer.MAX_VALUE; - return name1.compareToIgnoreCase(name2); - } + private static final Comparator ourTargetComparator = (target1, target2) -> { + final String name1 = target1.getDisplayName(); + if (name1 == null) return Integer.MIN_VALUE; + final String name2 = target2.getDisplayName(); + if (name2 == null) return Integer.MAX_VALUE; + return name1.compareToIgnoreCase(name2); }; public AntExplorerTreeStructure(final Project project) { diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/AllJarsUnderDirEntry.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/AllJarsUnderDirEntry.java index 74a5d7d342f0..4d183b39480c 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/impl/AllJarsUnderDirEntry.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/AllJarsUnderDirEntry.java @@ -35,11 +35,7 @@ import java.util.List; public class AllJarsUnderDirEntry implements AntClasspathEntry { - private static final Function CREATE_FROM_VIRTUAL_FILE = new Function() { - public AntClasspathEntry fun(VirtualFile file) { - return fromVirtualFile(file); - } - }; + private static final Function CREATE_FROM_VIRTUAL_FILE = file -> fromVirtualFile(file); @NonNls static final String DIR = "dir"; diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java index aef1d61a7946..4af5cb58c78c 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java @@ -145,11 +145,7 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis daemon.restart(); } else { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - daemon.restart(); - } - }); + SwingUtilities.invokeLater(() -> daemon.restart()); } } }); @@ -232,23 +228,17 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis try { indicator.setText(title); incModificationCount(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - result[0] = addBuildFileImpl(file); - updateRegisteredActions(); - } - catch (AntNoFileException e) { - ex[0] = e; - } + ApplicationManager.getApplication().runReadAction(() -> { + try { + result[0] = addBuildFileImpl(file); + updateRegisteredActions(); + } + catch (AntNoFileException e) { + ex[0] = e; } }); if (result[0] != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myEventDispatcher.getMulticaster().buildFileAdded(result[0]); - } - }); + ApplicationManager.getApplication().invokeLater(() -> myEventDispatcher.getMulticaster().buildFileAdded(result[0])); } } finally { @@ -401,27 +391,17 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis myIsInitialized = Boolean.FALSE; myAntWorkspaceConfiguration.loadFromProjectSettings(parentNode); getProperties().readExternal(parentNode); - runWhenInitialized(new Runnable() { - public void run() { - loadBuildFileProjectProperties(parentNode); - } - }); + runWhenInitialized(() -> loadBuildFileProjectProperties(parentNode)); } private void runWhenInitialized(final Runnable runnable) { if (getProject().isInitialized()) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - runnable.run(); - } + ApplicationManager.getApplication().runReadAction(() -> { + runnable.run(); }); } else { - myStartupManager.runWhenProjectIsInitialized(new Runnable() { - public void run() { - runnable.run(); - } - }); + myStartupManager.runWhenProjectIsInitialized(() -> runnable.run()); } } @@ -439,11 +419,7 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis } final List files = new ArrayList(myAntFileToContextFileMap.keySet()); // sort in order to minimize changes - Collections.sort(files, new Comparator() { - public int compare(final VirtualFile o1, final VirtualFile o2) { - return o1.getUrl().compareTo(o2.getUrl()); - } - }); + Collections.sort(files, (o1, o2) -> o1.getUrl().compareTo(o2.getUrl())); for (VirtualFile file : files) { final Element element = new Element(CONTEXT_MAPPING); final VirtualFile contextFile = myAntFileToContextFileMap.get(file); @@ -641,26 +617,24 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis targetDone.down(); final Ref result = Ref.create(Boolean.FALSE); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - try { - final Project project = CommonDataKeys.PROJECT.getData(dataContext); - if (project == null || project.isDisposed()) { - targetDone.up(); - } - else { - target.run(dataContext, additionalProperties, new AntBuildListener() { - public void buildFinished(int state, int errorCount) { - result.set((state == AntBuildListener.FINISHED_SUCCESSFULLY) && (errorCount == 0)); - targetDone.up(); - } - }); - } - } - catch (Throwable e) { + SwingUtilities.invokeLater(() -> { + try { + final Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null || project.isDisposed()) { targetDone.up(); - LOG.error(e); } + else { + target.run(dataContext, additionalProperties, new AntBuildListener() { + public void buildFinished(int state, int errorCount) { + result.set((state == AntBuildListener.FINISHED_SUCCESSFULLY) && (errorCount == 0)); + targetDone.up(); + } + }); + } + } + catch (Throwable e) { + targetDone.up(); + LOG.error(e); } }); targetDone.waitFor(); @@ -717,102 +691,98 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis indicator.pushState(); try { indicator.setText(title); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - myInitThread = Thread.currentThread(); - // first, remove existing files - for (AntBuildFile file : getBuildFiles()) { - removeBuildFileImpl(file); - } - // then fill the configuration with the files configured in xml - List> buildFiles = new ArrayList>(files.size()); - for (Pair pair : files) { - final Element element = pair.getFirst(); - final VirtualFile file = vfManager.findFileByUrl(pair.getSecond()); - if (file == null) { - continue; - } - try { - final AntBuildFileBase buildFile = addBuildFileImpl(file); - buildFile.readProperties(element); - buildFiles.add(Pair.create(element, buildFile)); - } - catch (AntNoFileException ignored) { - } - catch (InvalidDataException e) { - LOG.error(e); - } - } - // updating properties separately to avoid unnecesary building of PSI after clearing caches - for (Pair pair : buildFiles) { - final AntBuildFileBase buildFile = pair.getSecond(); - buildFile.updateProperties(); - final VirtualFile vFile = buildFile.getVirtualFile(); - final String buildFileUrl = vFile != null? vFile.getUrl() : null; - - for (final Object o1 : pair.getFirst().getChildren(EXECUTE_ON_ELEMENT)) { - final Element e = (Element)o1; - final String eventId = e.getAttributeValue(EVENT_ELEMENT); - ExecutionEvent event = null; - final String targetName = e.getAttributeValue(TARGET_ELEMENT); - if (ExecuteBeforeCompilationEvent.TYPE_ID.equals(eventId)) { - event = ExecuteBeforeCompilationEvent.getInstance(); - } - else if (ExecuteAfterCompilationEvent.TYPE_ID.equals(eventId)) { - event = ExecuteAfterCompilationEvent.getInstance(); - } - else if ("beforeRun".equals(eventId)) { - /* - for compatibility with previous format - - - - - */ - final String configType = e.getAttributeValue("runConfigurationType"); - final String configName = e.getAttributeValue("runConfigurationName"); - convertToBeforeRunTask(myProject, buildFileUrl, targetName, configType, configName); - } - else if (ExecuteCompositeTargetEvent.TYPE_ID.equals(eventId)) { - try { - event = new ExecuteCompositeTargetEvent(targetName); - } - catch (WrongNameFormatException e1) { - LOG.info(e1); - event = null; - } - } - if (event != null) { - try { - event.readExternal(e, getProject()); - setTargetForEvent(buildFile, targetName, event); - } - catch (InvalidDataException readFailed) { - LOG.info(readFailed.getMessage()); - } - } - } - } - AntWorkspaceConfiguration.getInstance(getProject()).loadFileProperties(); + ApplicationManager.getApplication().runReadAction(() -> { + try { + myInitThread = Thread.currentThread(); + // first, remove existing files + for (AntBuildFile file : getBuildFiles()) { + removeBuildFileImpl(file); } - catch (InvalidDataException e) { - LOG.error(e); + // then fill the configuration with the files configured in xml + List> buildFiles = new ArrayList>(files.size()); + for (Pair pair : files) { + final Element element = pair.getFirst(); + final VirtualFile file = vfManager.findFileByUrl(pair.getSecond()); + if (file == null) { + continue; + } + try { + final AntBuildFileBase buildFile = addBuildFileImpl(file); + buildFile.readProperties(element); + buildFiles.add(Pair.create(element, buildFile)); + } + catch (AntNoFileException ignored) { + } + catch (InvalidDataException e) { + LOG.error(e); + } + } + // updating properties separately to avoid unnecesary building of PSI after clearing caches + for (Pair pair : buildFiles) { + final AntBuildFileBase buildFile = pair.getSecond(); + buildFile.updateProperties(); + final VirtualFile vFile = buildFile.getVirtualFile(); + final String buildFileUrl = vFile != null? vFile.getUrl() : null; + + for (final Object o1 : pair.getFirst().getChildren(EXECUTE_ON_ELEMENT)) { + final Element e = (Element)o1; + final String eventId = e.getAttributeValue(EVENT_ELEMENT); + ExecutionEvent event = null; + final String targetName = e.getAttributeValue(TARGET_ELEMENT); + if (ExecuteBeforeCompilationEvent.TYPE_ID.equals(eventId)) { + event = ExecuteBeforeCompilationEvent.getInstance(); + } + else if (ExecuteAfterCompilationEvent.TYPE_ID.equals(eventId)) { + event = ExecuteAfterCompilationEvent.getInstance(); + } + else if ("beforeRun".equals(eventId)) { + /* + for compatibility with previous format + + + + + */ + final String configType = e.getAttributeValue("runConfigurationType"); + final String configName = e.getAttributeValue("runConfigurationName"); + convertToBeforeRunTask(myProject, buildFileUrl, targetName, configType, configName); + } + else if (ExecuteCompositeTargetEvent.TYPE_ID.equals(eventId)) { + try { + event = new ExecuteCompositeTargetEvent(targetName); + } + catch (WrongNameFormatException e1) { + LOG.info(e1); + event = null; + } + } + if (event != null) { + try { + event.readExternal(e, getProject()); + setTargetForEvent(buildFile, targetName, event); + } + catch (InvalidDataException readFailed) { + LOG.info(readFailed.getMessage()); + } + } + } + } + AntWorkspaceConfiguration.getInstance(getProject()).loadFileProperties(); + } + catch (InvalidDataException e) { + LOG.error(e); + } + finally { + try { + incModificationCount(); + updateRegisteredActions(); } finally { - try { - incModificationCount(); - updateRegisteredActions(); - } - finally { - myInitThread = null; - myIsInitialized = Boolean.TRUE; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myEventDispatcher.getMulticaster().configurationLoaded(); - } - }, ModalityState.any()); - } + myInitThread = null; + myIsInitialized = Boolean.TRUE; + ApplicationManager.getApplication().invokeLater(() -> { + myEventDispatcher.getMulticaster().configurationLoaded(); + }, ModalityState.any()); } } }); @@ -865,10 +835,8 @@ public class AntConfigurationImpl extends AntConfigurationBase implements Persis if (!app.isDispatchThread() || task.isHeadless()) { // for headless tasks we need to ensure async execution. // Otherwise calls to AntConfiguration.getInstance() from the task will cause SOE - app.invokeLater(new Runnable() { - public void run() { - task.queue(); - } + app.invokeLater(() -> { + task.queue(); }, ModalityState.any()); } else { diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntInstallation.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntInstallation.java index 2e9405564a3d..a46423358e8a 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntInstallation.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntInstallation.java @@ -34,11 +34,8 @@ public class AntInstallation { public static final StringProperty HOME_DIR = new StringProperty("homeDir", ""); public static final AbstractProperty NAME = new StringProperty("name", ""); public static final ListProperty CLASS_PATH = ListProperty.create("classpath"); - public static final Comparator NAME_COMPARATOR = new Comparator() { - public int compare(AntInstallation antInstallation, AntInstallation antInstallation1) { - return String.CASE_INSENSITIVE_ORDER.compare(antInstallation.getName(), antInstallation1.getName()); - } - }; + public static final Comparator NAME_COMPARATOR = + (antInstallation, antInstallation1) -> String.CASE_INSENSITIVE_ORDER.compare(antInstallation.getName(), antInstallation1.getName()); public static final Convertor REFERENCE_TO_ANT = new Convertor() { public AntReference convert(AntInstallation antInstallation) { diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntKeymapExtension.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntKeymapExtension.java index 964deae46c1e..fb4fe96e3fdd 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntKeymapExtension.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntKeymapExtension.java @@ -50,25 +50,23 @@ class AntKeymapExtension implements KeymapExtension { if (project != null) { final AntConfiguration antConfiguration = AntConfiguration.getInstance(project); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (final String id : ids) { - if (filtered != null && !filtered.value(actionManager.getActionOrStub(id))) { - continue; - } - final AntBuildFile buildFile = antConfiguration.findBuildFileByActionId(id); - if (buildFile != null) { - KeymapGroup subGroup = buildFileToGroup.get(buildFile); - if (subGroup == null) { - subGroup = KeymapGroupFactory.getInstance().createGroup(buildFile.getPresentableName()); - buildFileToGroup.put(buildFile, subGroup); - result.addGroup(subGroup); - } - subGroup.addActionId(id); - } - else { - LOG.info("no buildfile found for actionId=" + id); + ApplicationManager.getApplication().runReadAction(() -> { + for (final String id : ids) { + if (filtered != null && !filtered.value(actionManager.getActionOrStub(id))) { + continue; + } + final AntBuildFile buildFile = antConfiguration.findBuildFileByActionId(id); + if (buildFile != null) { + KeymapGroup subGroup = buildFileToGroup.get(buildFile); + if (subGroup == null) { + subGroup = KeymapGroupFactory.getInstance().createGroup(buildFile.getPresentableName()); + buildFileToGroup.put(buildFile, subGroup); + result.addGroup(subGroup); } + subGroup.addActionId(id); + } + else { + LOG.info("no buildfile found for actionId=" + id); } } }); diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/SinglePathEntry.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/SinglePathEntry.java index ac982d676255..606863c44cfd 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/impl/SinglePathEntry.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/SinglePathEntry.java @@ -31,11 +31,8 @@ import java.io.File; import java.util.List; public class SinglePathEntry implements AntClasspathEntry { - private static final Function CREATE_FROM_VIRTUAL_FILE = new Function() { - public AntClasspathEntry fun(VirtualFile singlePathEntry) { - return fromVirtualFile(singlePathEntry); - } - }; + private static final Function CREATE_FROM_VIRTUAL_FILE = + singlePathEntry -> fromVirtualFile(singlePathEntry); @NonNls static final String PATH = "path"; diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/configuration/BuildFilePropertiesPanel.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/configuration/BuildFilePropertiesPanel.java index 6b573da4d172..c258bfc4f202 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/impl/configuration/BuildFilePropertiesPanel.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/configuration/BuildFilePropertiesPanel.java @@ -310,14 +310,12 @@ public class BuildFilePropertiesPanel { } }; - private static final Comparator NAME_COMPARATOR = new Comparator() { - public int compare(TargetFilter o1, TargetFilter o2) { - final String name1 = o1.getTargetName(); - if (name1 == null) return -1; - final String name2 = o2.getTargetName(); - if (name2 == null) return 1; - return name1.compareToIgnoreCase(name2); - } + private static final Comparator NAME_COMPARATOR = (o1, o2) -> { + final String name1 = o1.getTargetName(); + if (name1 == null) return -1; + final String name2 = o2.getTargetName(); + if (name2 == null) return 1; + return name1.compareToIgnoreCase(name2); }; private static final ColumnInfo NAME_COLUMN = new ColumnInfo( AntBundle.message("ant.target")) { @@ -330,18 +328,16 @@ public class BuildFilePropertiesPanel { } }; - private static final Comparator DESCRIPTION_COMPARATOR = new Comparator() { - public int compare(TargetFilter o1, TargetFilter o2) { - String description1 = o1.getDescription(); - if (description1 == null) { - description1 = ""; - } - String description2 = o2.getDescription(); - if (description2 == null) { - description2 = ""; - } - return description1.compareToIgnoreCase(description2); + private static final Comparator DESCRIPTION_COMPARATOR = (o1, o2) -> { + String description1 = o1.getDescription(); + if (description1 == null) { + description1 = ""; } + String description2 = o2.getDescription(); + if (description2 == null) { + description2 = ""; + } + return description1.compareToIgnoreCase(description2); }; private static final ColumnInfo DESCRIPTION = new ColumnInfo( AntBundle.message("edit.ant.properties.description.column.name")) { diff --git a/plugins/ant/src/com/intellij/lang/ant/validation/AntHectorConfigurable.java b/plugins/ant/src/com/intellij/lang/ant/validation/AntHectorConfigurable.java index 43b9c005d435..78deb443c642 100644 --- a/plugins/ant/src/com/intellij/lang/ant/validation/AntHectorConfigurable.java +++ b/plugins/ant/src/com/intellij/lang/ant/validation/AntHectorConfigurable.java @@ -101,11 +101,7 @@ public class AntHectorConfigurable extends HectorComponentPanel { } final List paths = new ArrayList(myPathToFileMap.keySet()); - Collections.sort(paths, new Comparator() { - public int compare(final String o1, final String o2) { - return o1.compareTo(o2); - } - }); + Collections.sort(paths, (o1, o2) -> o1.compareTo(o2)); myCombo.addItem(NONE); for (String path : paths) { diff --git a/plugins/ant/tests/src/com/intellij/lang/ant/AntHighlightingTest.java b/plugins/ant/tests/src/com/intellij/lang/ant/AntHighlightingTest.java index 1ecc36d8bd8b..49089d549351 100644 --- a/plugins/ant/tests/src/com/intellij/lang/ant/AntHighlightingTest.java +++ b/plugins/ant/tests/src/com/intellij/lang/ant/AntHighlightingTest.java @@ -117,12 +117,7 @@ public class AntHighlightingTest extends DaemonAnalyzerTestCase { try { myIgnoreInfos = true; - PlatformTestUtil.startPerformanceTest("Should be quite performant !", 25000, new ThrowableRunnable() { - @Override - public void run() { - doDoTest(true, false); - } - }).cpuBound().useLegacyScaling().assertTiming(); + PlatformTestUtil.startPerformanceTest("Should be quite performant !", 25000, () -> doDoTest(true, false)).cpuBound().useLegacyScaling().assertTiming(); } finally { myIgnoreInfos = false; diff --git a/plugins/commander/src/com/intellij/ide/commander/CommanderSelectInTarget.java b/plugins/commander/src/com/intellij/ide/commander/CommanderSelectInTarget.java index 59bf7427a5ea..521a1a22d5cf 100644 --- a/plugins/commander/src/com/intellij/ide/commander/CommanderSelectInTarget.java +++ b/plugins/commander/src/com/intellij/ide/commander/CommanderSelectInTarget.java @@ -58,11 +58,8 @@ public final class CommanderSelectInTarget extends SelectInTargetPsiWrapper { final PsiElement _element = element.getOriginalElement(); - selectElementInCommander(new Runnable() { - public void run() { - Commander.getInstance(myProject).selectElementInLeftPanel(_element, PsiUtilBase.getVirtualFile(_element)); - } - }, requestFocus); + selectElementInCommander( + () -> Commander.getInstance(myProject).selectElementInLeftPanel(_element, PsiUtilBase.getVirtualFile(_element)), requestFocus); } private void selectElementInCommander(final Runnable runnable, final boolean requestFocus) { @@ -76,11 +73,9 @@ public final class CommanderSelectInTarget extends SelectInTargetPsiWrapper { } protected void select(final Object selector, final VirtualFile virtualFile, final boolean requestFocus) { - selectElementInCommander(new Runnable() { - public void run() { - final Commander commander = Commander.getInstance(myProject); - commander.selectElementInLeftPanel(selector, virtualFile); - } + selectElementInCommander(() -> { + final Commander commander = Commander.getInstance(myProject); + commander.selectElementInLeftPanel(selector, virtualFile); }, requestFocus); } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java b/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java index ccc27bbe934f..ba9e0de84874 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java @@ -77,37 +77,31 @@ public class CopyrightManager extends AbstractProjectComponent implements Persis newFileTracker.clear(); } }); - startupManager.runWhenProjectIsInitialized(new Runnable() { - @Override - public void run() { - DocumentListener listener = new DocumentAdapter() { - @Override - public void documentChanged(DocumentEvent e) { - final Document document = e.getDocument(); - final VirtualFile virtualFile = fileDocumentManager.getFile(document); - if (virtualFile == null) return; - final Module module = projectRootManager.getFileIndex().getModuleForFile(virtualFile); - if (module == null) return; - if (!newFileTracker.poll(virtualFile)) return; - if (!fileTypeUtil.isSupportedFile(virtualFile)) return; - if (psiManager.findFile(virtualFile) == null) return; - application.invokeLater(new Runnable() { - @Override - public void run() { - if (!virtualFile.isValid()) return; - final PsiFile file = psiManager.findFile(virtualFile); - if (file != null && file.isWritable()) { - final CopyrightProfile opts = getCopyrightOptions(file); - if (opts != null) { - new UpdateCopyrightProcessor(myProject, module, file).run(); - } - } + startupManager.runWhenProjectIsInitialized(() -> { + DocumentListener listener = new DocumentAdapter() { + @Override + public void documentChanged(DocumentEvent e) { + final Document document = e.getDocument(); + final VirtualFile virtualFile = fileDocumentManager.getFile(document); + if (virtualFile == null) return; + final Module module = projectRootManager.getFileIndex().getModuleForFile(virtualFile); + if (module == null) return; + if (!newFileTracker.poll(virtualFile)) return; + if (!fileTypeUtil.isSupportedFile(virtualFile)) return; + if (psiManager.findFile(virtualFile) == null) return; + application.invokeLater(() -> { + if (!virtualFile.isValid()) return; + final PsiFile file = psiManager.findFile(virtualFile); + if (file != null && file.isWritable()) { + final CopyrightProfile opts = getCopyrightOptions(file); + if (opts != null) { + new UpdateCopyrightProcessor(myProject, module, file).run(); } - }, ModalityState.NON_MODAL, myProject.getDisposed()); - } - }; - editorFactory.getEventMulticaster().addDocumentListener(listener, myProject); - } + } + }, ModalityState.NON_MODAL, myProject.getDisposed()); + } + }; + editorFactory.getEventMulticaster().addDocumentListener(listener, myProject); }); } } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/AbstractFileProcessor.java b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/AbstractFileProcessor.java index 76506673e0fb..8db3220d1e8d 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/AbstractFileProcessor.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/AbstractFileProcessor.java @@ -122,22 +122,16 @@ public abstract class AbstractFileProcessor { if (!FileModificationService.getInstance().preparePsiElementForWrite(file)) return; final Runnable[] resultRunnable = new Runnable[1]; - execute(new Runnable() { - @Override - public void run() { - try { - resultRunnable[0] = preprocessFile(file, true); - } - catch (IncorrectOperationException incorrectoperationexception) { - logger.error(incorrectoperationexception); - } + execute(() -> { + try { + resultRunnable[0] = preprocessFile(file, true); } - }, new Runnable() { - @Override - public void run() { - if (resultRunnable[0] != null) { - resultRunnable[0].run(); - } + catch (IncorrectOperationException incorrectoperationexception) { + logger.error(incorrectoperationexception); + } + }, () -> { + if (resultRunnable[0] != null) { + resultRunnable[0].run(); } }); } @@ -185,89 +179,63 @@ public abstract class AbstractFileProcessor { indicator.setFraction(fraction); } - return new Runnable() { - @Override - public void run() { - ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - String msg = null; - double fraction = 0.0D; - if (indicator != null) { - msg = indicator.getText(); - fraction = indicator.getFraction(); - indicator.setText(message); - } + return () -> { + ProgressIndicator indicator1 = ProgressManager.getInstance().getProgressIndicator(); + String msg1 = null; + double fraction1 = 0.0D; + if (indicator1 != null) { + msg1 = indicator1.getText(); + fraction1 = indicator1.getFraction(); + indicator1.setText(message); + } - for (int j = 0; j < runnables.length; j++) { - if (indicator != null) { - if (indicator.isCanceled()) { - return; - } - - indicator.setFraction((double)j / (double)runnables.length); + for (int j = 0; j < runnables.length; j++) { + if (indicator1 != null) { + if (indicator1.isCanceled()) { + return; } - Runnable runnable = runnables[j]; - if (runnable != null) { - runnable.run(); - } - runnables[j] = null; + indicator1.setFraction((double)j / (double)runnables.length); } - if (indicator != null) { - indicator.setText(msg); - indicator.setFraction(fraction); + Runnable runnable = runnables[j]; + if (runnable != null) { + runnable.run(); } + runnables[j] = null; + } + + if (indicator1 != null) { + indicator1.setText(msg1); + indicator1.setFraction(fraction1); } }; } private void process(final PsiFile[] files) { final Runnable[] resultRunnable = new Runnable[1]; - execute(new Runnable() { - @Override - public void run() { - resultRunnable[0] = prepareFiles(new ArrayList(Arrays.asList(files))); - } - }, new Runnable() { - @Override - public void run() { - if (resultRunnable[0] != null) { - resultRunnable[0].run(); - } + execute(() -> resultRunnable[0] = prepareFiles(new ArrayList(Arrays.asList(files))), () -> { + if (resultRunnable[0] != null) { + resultRunnable[0].run(); } }); } private void process(final PsiDirectory dir, final boolean subdirs) { final List pfiles = new ArrayList(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - findFiles(pfiles, dir, subdirs); - } - }, title, true, myProject); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> findFiles(pfiles, dir, subdirs), title, true, myProject); handleFiles(pfiles); } private void process(final Project project) { final List pfiles = new ArrayList(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - findFiles(project, pfiles); - } - }, title, true, project); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> findFiles(project, pfiles), title, true, project); handleFiles(pfiles); } private void process(final Module module) { final List pfiles = new ArrayList(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - findFiles(module, pfiles); - } - }, title, true, myProject); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> findFiles(module, pfiles), title, true, myProject); handleFiles(pfiles); } @@ -285,22 +253,19 @@ public abstract class AbstractFileProcessor { final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots(); for (final VirtualFile root : roots) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - idx.iterateContentUnderDirectory(root, new ContentIterator() { - @Override - public boolean processFile(final VirtualFile dir) { - if (dir.isDirectory()) { - final PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(dir); - if (psiDir != null) { - findFiles(files, psiDir, false); - } + ApplicationManager.getApplication().runReadAction(() -> { + idx.iterateContentUnderDirectory(root, new ContentIterator() { + @Override + public boolean processFile(final VirtualFile dir) { + if (dir.isDirectory()) { + final PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(dir); + if (psiDir != null) { + findFiles(files, psiDir, false); } - return true; } - }); - } + return true; + } + }); }); } } @@ -314,17 +279,9 @@ public abstract class AbstractFileProcessor { .hasReadonlyFiles()) { if (!files.isEmpty()) { final Runnable[] resultRunnable = new Runnable[1]; - execute(new Runnable() { - @Override - public void run() { - resultRunnable[0] = prepareFiles(files); - } - }, new Runnable() { - @Override - public void run() { - if (resultRunnable[0] != null) { - resultRunnable[0].run(); - } + execute(() -> resultRunnable[0] = prepareFiles(files), () -> { + if (resultRunnable[0] != null) { + resultRunnable[0].run(); } }); } @@ -352,17 +309,9 @@ public abstract class AbstractFileProcessor { } private void execute(final Runnable readAction, final Runnable writeAction) { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - readAction.run(); - } - }); - } - }, title, true, myProject); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + readAction.run(); + }), title, true, myProject); new WriteCommandAction(myProject, title) { @Override protected void run(@NotNull Result result) throws Throwable { diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java index 396054aad72a..4314c8953185 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightAction.java @@ -160,12 +160,9 @@ public class UpdateCopyrightAction extends BaseAnalysisAction { final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(project, UpdateCopyrightProcessor.TITLE, true); progressTask.setMinIterationTime(200); progressTask.setTask(new UpdateCopyrightSequentialTask(preparations, progressTask)); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); - ProgressManager.getInstance().run(progressTask); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); + ProgressManager.getInstance().run(progressTask); }, getTemplatePresentation().getText(), null); } } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java index 23b037cc343f..e2fc2cdfb9db 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/actions/UpdateCopyrightProcessor.java @@ -90,21 +90,18 @@ public class UpdateCopyrightProcessor extends AbstractFileProcessor if (update instanceof UpdatePsiFileCopyright && !((UpdatePsiFileCopyright)update).hasUpdates()) return EmptyRunnable.getInstance(); - return new Runnable() { - public void run() + return () -> { + try { - try - { - if (update instanceof UpdatePsiFileCopyright) { - ((UpdatePsiFileCopyright)update).complete(allowReplacement); - } else { - update.complete(); - } - } - catch (Exception e) - { - logger.error(e); - } + if (update instanceof UpdatePsiFileCopyright) { + ((UpdatePsiFileCopyright)update).complete(allowReplacement); + } else { + update.complete(); + } + } + catch (Exception e) + { + logger.error(e); } }; } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightConfigurable.java b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightConfigurable.java index 9292cac28fff..d12b68f699c7 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightConfigurable.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightConfigurable.java @@ -139,17 +139,8 @@ public class CopyrightConfigurable extends NamedConfigurable { public void reset() { myDisplayName = myCopyrightProfile.getName(); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - myEditor.getDocument().setText(EntityUtil.decode(myCopyrightProfile.getNotice())); - } - }); - } - }); + SwingUtilities.invokeLater(() -> DocumentUtil.writeInRunUndoTransparentAction( + () -> myEditor.getDocument().setText(EntityUtil.decode(myCopyrightProfile.getNotice())))); myKeywordTf.setText(myCopyrightProfile.getKeyword()); myAllowReplaceTextField.setText(myCopyrightProfile.getAllowReplaceKeyword()); } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProfilesPanel.java b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProfilesPanel.java index 2c220ae2a0cc..3f82480f72dd 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProfilesPanel.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProfilesPanel.java @@ -214,41 +214,33 @@ public class CopyrightProfilesPanel extends MasterDetailsComponent implements Se } }) .withTitle("Choose File Containing Copyright Notice"); - FileChooser.chooseFile(descriptor, myProject, null, new Consumer() { - @Override - public void consume(VirtualFile file) { - final List profiles = ExternalOptionHelper.loadOptions(VfsUtilCore.virtualToIoFile(file)); - if (profiles == null) return; - if (!profiles.isEmpty()) { - if (profiles.size() == 1) { - importProfile(profiles.get(0)); - } - else { - JBPopupFactory.getInstance() - .createListPopup(new BaseListPopupStep("Choose profile to import", profiles) { - @Override - public PopupStep onChosen(final CopyrightProfile selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - importProfile(selectedValue); - } - }); - } - - @NotNull - @Override - public String getTextFor(CopyrightProfile value) { - return value.getName(); - } - }) - .showUnderneathOf(myNorthPanel); - } + FileChooser.chooseFile(descriptor, myProject, null, file -> { + final List profiles = ExternalOptionHelper.loadOptions(VfsUtilCore.virtualToIoFile(file)); + if (profiles == null) return; + if (!profiles.isEmpty()) { + if (profiles.size() == 1) { + importProfile(profiles.get(0)); } else { - Messages.showWarningDialog(myProject, "The selected file does not contain any copyright settings.", "Import Failure"); + JBPopupFactory.getInstance() + .createListPopup(new BaseListPopupStep("Choose profile to import", profiles) { + @Override + public PopupStep onChosen(final CopyrightProfile selectedValue, boolean finalChoice) { + return doFinalStep(() -> importProfile(selectedValue)); + } + + @NotNull + @Override + public String getTextFor(CopyrightProfile value) { + return value.getName(); + } + }) + .showUnderneathOf(myNorthPanel); } } + else { + Messages.showWarningDialog(myProject, "The selected file does not contain any copyright settings.", "Import Failure"); + } }); } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProjectConfigurable.java b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProjectConfigurable.java index 4bf8d7b5f235..6c753fafb4bb 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProjectConfigurable.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/CopyrightProjectConfigurable.java @@ -44,12 +44,7 @@ public class CopyrightProjectConfigurable extends SearchableConfigurable.Parent. public JComponent createComponent() { myOptionsPanel = new ProjectSettingsPanel(project, myProfilesPanel); - myProfilesPanel.setUpdate(new Runnable() { - @Override - public void run() { - reloadProfiles(); - } - }); + myProfilesPanel.setUpdate(() -> reloadProfiles()); return myOptionsPanel.getMainComponent(); } diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java index f1043f0f65af..98f037328220 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java @@ -280,21 +280,11 @@ public class ProjectSettingsPanel { public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { final List copyrights = new ArrayList(myProfilesModel.getAllProfiles().values()); - Collections.sort(copyrights, new Comparator() { - @Override - public int compare(CopyrightProfile o1, CopyrightProfile o2) { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - }); + Collections.sort(copyrights, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); myProfilesChooser.setCell(table, row, column); myProfilesChooser.setOptions(copyrights.toArray()); myProfilesChooser.setDefaultValue(scopeSetting.getProfile()); - myProfilesChooser.setToString(new Function() { - @Override - public String fun(Object o) { - return ((CopyrightProfile)o).getName(); - } - }); + myProfilesChooser.setToString(o -> ((CopyrightProfile)o).getName()); return myProfilesChooser; } }; diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/TemplateCommentPanel.java b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/TemplateCommentPanel.java index c553c97b121a..ad0c56c5c17d 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/TemplateCommentPanel.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/TemplateCommentPanel.java @@ -344,11 +344,7 @@ public class TemplateCommentPanel implements SearchableConfigurable { private void showPreview(LanguageOptions options) { final String defaultCopyrightText = myNoCopyright.isSelected() ? "" : FileTypeUtil .buildComment(fileType, VelocityHelper.evaluate(null, null, null, EntityUtil.decode(CopyrightProfile.DEFAULT_COPYRIGHT_NOTICE)), options); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - preview.setText(defaultCopyrightText); - } - }); + SwingUtilities.invokeLater(() -> preview.setText(defaultCopyrightText)); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/CoverageDataManagerImpl.java b/plugins/coverage-common/src/com/intellij/coverage/CoverageDataManagerImpl.java index 2db8835ff8b2..722054f18e7e 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/CoverageDataManagerImpl.java +++ b/plugins/coverage-common/src/com/intellij/coverage/CoverageDataManagerImpl.java @@ -274,68 +274,64 @@ public class CoverageDataManagerImpl extends CoverageDataManager { } public void coverageGathered(@NotNull final CoverageSuite suite) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (myProject.isDisposed()) return; - if (myCurrentSuitesBundle != null) { - final String message = CodeInsightBundle.message("display.coverage.prompt", suite.getPresentableName()); + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; + if (myCurrentSuitesBundle != null) { + final String message = CodeInsightBundle.message("display.coverage.prompt", suite.getPresentableName()); - final CoverageOptionsProvider coverageOptionsProvider = CoverageOptionsProvider.getInstance(myProject); - final DialogWrapper.DoNotAskOption doNotAskOption = new DialogWrapper.DoNotAskOption() { - @Override - public boolean isToBeShown() { - return coverageOptionsProvider.getOptionToReplace() == 3; - } - - @Override - public void setToBeShown(boolean value, int exitCode) { - coverageOptionsProvider.setOptionsToReplace(value ? 3 : exitCode); - } - - @Override - public boolean canBeHidden() { - return true; - } - - @Override - public boolean shouldSaveOptionsOnCancel() { - return true; - } - - @NotNull - @Override - public String getDoNotShowMessage() { - return CommonBundle.message("dialog.options.do.not.show"); - } - }; - final String[] options = myCurrentSuitesBundle.getCoverageEngine() == suite.getCoverageEngine() ? - new String[] {REPLACE_ACTIVE_SUITES, ADD_TO_ACTIVE_SUITES, DO_NOT_APPLY_COLLECTED_COVERAGE} : - new String[] {REPLACE_ACTIVE_SUITES, DO_NOT_APPLY_COLLECTED_COVERAGE}; - final int answer = doNotAskOption.isToBeShown() ? Messages.showDialog(message, CodeInsightBundle.message("code.coverage"), - options, 1, Messages.getQuestionIcon(), - doNotAskOption) : coverageOptionsProvider.getOptionToReplace(); - if (answer == DialogWrapper.OK_EXIT_CODE) { - chooseSuitesBundle(new CoverageSuitesBundle(suite)); + final CoverageOptionsProvider coverageOptionsProvider = CoverageOptionsProvider.getInstance(myProject); + final DialogWrapper.DoNotAskOption doNotAskOption = new DialogWrapper.DoNotAskOption() { + @Override + public boolean isToBeShown() { + return coverageOptionsProvider.getOptionToReplace() == 3; } - else if (answer == 1) { - chooseSuitesBundle(new CoverageSuitesBundle(ArrayUtil.append(myCurrentSuitesBundle.getSuites(), suite))); + + @Override + public void setToBeShown(boolean value, int exitCode) { + coverageOptionsProvider.setOptionsToReplace(value ? 3 : exitCode); } - } - else { + + @Override + public boolean canBeHidden() { + return true; + } + + @Override + public boolean shouldSaveOptionsOnCancel() { + return true; + } + + @NotNull + @Override + public String getDoNotShowMessage() { + return CommonBundle.message("dialog.options.do.not.show"); + } + }; + final String[] options = myCurrentSuitesBundle.getCoverageEngine() == suite.getCoverageEngine() ? + new String[] {REPLACE_ACTIVE_SUITES, ADD_TO_ACTIVE_SUITES, DO_NOT_APPLY_COLLECTED_COVERAGE} : + new String[] {REPLACE_ACTIVE_SUITES, DO_NOT_APPLY_COLLECTED_COVERAGE}; + final int answer = doNotAskOption.isToBeShown() ? Messages.showDialog(message, CodeInsightBundle.message("code.coverage"), + options, 1, Messages.getQuestionIcon(), + doNotAskOption) : coverageOptionsProvider.getOptionToReplace(); + if (answer == DialogWrapper.OK_EXIT_CODE) { chooseSuitesBundle(new CoverageSuitesBundle(suite)); } + else if (answer == 1) { + chooseSuitesBundle(new CoverageSuitesBundle(ArrayUtil.append(myCurrentSuitesBundle.getSuites(), suite))); + } + } + else { + chooseSuitesBundle(new CoverageSuitesBundle(suite)); } }); } public void triggerPresentationUpdate() { renewInformationInEditors(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - if (myProject.isDisposed()) return; - ProjectView.getInstance(myProject).refresh(); - CoverageViewManager.getInstance(myProject).setReady(true); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myProject.isDisposed()) return; + ProjectView.getInstance(myProject).refresh(); + CoverageViewManager.getInstance(myProject).setReady(true); }); } @@ -672,14 +668,11 @@ public class CoverageDataManagerImpl extends CoverageDataManager { myAnnotators.put(editor, finalAnnotator); } - final Runnable request = new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; - if (myCurrentSuitesBundle != null) { - if (engine.acceptedByFilters(psiFile, myCurrentSuitesBundle)) { - finalAnnotator.showCoverageInformation(myCurrentSuitesBundle); - } + final Runnable request = () -> { + if (myProject.isDisposed()) return; + if (myCurrentSuitesBundle != null) { + if (engine.acceptedByFilters(psiFile, myCurrentSuitesBundle)) { + finalAnnotator.showCoverageInformation(myCurrentSuitesBundle); } } }; diff --git a/plugins/coverage-common/src/com/intellij/coverage/CoverageLineMarkerRenderer.java b/plugins/coverage-common/src/com/intellij/coverage/CoverageLineMarkerRenderer.java index 190c35bf46d3..d01d0cac39c0 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/CoverageLineMarkerRenderer.java +++ b/plugins/coverage-common/src/com/intellij/coverage/CoverageLineMarkerRenderer.java @@ -251,14 +251,12 @@ public class CoverageLineMarkerRenderer implements LineMarkerRendererEx, ActiveG editor.getCaretModel().moveToOffset(firstOffset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); - editor.getScrollingModel().runActionOnScrollingFinished(new Runnable() { - public void run() { - Point p = editor.visualPositionToXY(editor.offsetToVisualPosition(firstOffset)); - EditorGutterComponentEx editorComponent = (EditorGutterComponentEx)editor.getGutter(); - JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); - p = SwingUtilities.convertPoint(editorComponent, THICKNESS, p.y, layeredPane); - showHint(editor, p, lineNumber); - } + editor.getScrollingModel().runActionOnScrollingFinished(() -> { + Point p = editor.visualPositionToXY(editor.offsetToVisualPosition(firstOffset)); + EditorGutterComponentEx editorComponent = (EditorGutterComponentEx)editor.getGutter(); + JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); + p = SwingUtilities.convertPoint(editorComponent, THICKNESS, p.y, layeredPane); + showHint(editor, p, lineNumber); }); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/CoverageSuitesBundle.java b/plugins/coverage-common/src/com/intellij/coverage/CoverageSuitesBundle.java index ad48a4272e64..0e5eaf69bc38 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/CoverageSuitesBundle.java +++ b/plugins/coverage-common/src/com/intellij/coverage/CoverageSuitesBundle.java @@ -138,11 +138,8 @@ public class CoverageSuitesBundle { } public String getPresentableName() { - return StringUtil.join(mySuites, new Function() { - @Override - public String fun(CoverageSuite coverageSuite) { - return coverageSuite.getPresentableName(); - } + return StringUtil.join(mySuites, coverageSuite -> { + return coverageSuite.getPresentableName(); }, ", "); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/SimpleCoverageAnnotator.java b/plugins/coverage-common/src/com/intellij/coverage/SimpleCoverageAnnotator.java index d0cbba803fbf..d52b8834dfc4 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/SimpleCoverageAnnotator.java +++ b/plugins/coverage-common/src/com/intellij/coverage/SimpleCoverageAnnotator.java @@ -297,82 +297,80 @@ public abstract class SimpleCoverageAnnotator extends BaseCoverageAnnotator { return null; } - return new Runnable() { - public void run() { - final Project project = getProject(); + return () -> { + final Project project = getProject(); - final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); + final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); - // find all modules content roots - final VirtualFile[] modulesContentRoots = dataManager.doInReadActionIfProjectOpen(new Computable() { - public VirtualFile[] compute() { - return rootManager.getContentRoots(); + // find all modules content roots + final VirtualFile[] modulesContentRoots = dataManager.doInReadActionIfProjectOpen(new Computable() { + public VirtualFile[] compute() { + return rootManager.getContentRoots(); + } + }); + + if (modulesContentRoots == null) { + return; + } + + // gather coverage from all content roots + for (VirtualFile root : modulesContentRoots) { + annotate(root, suite, dataManager, data, project, new Annotator() { + public void annotateSourceDirectory(final String dirPath, final DirCoverageInfo info) { + myDirCoverageInfos.put(dirPath, info); + } + + public void annotateTestDirectory(final String dirPath, final DirCoverageInfo info) { + myTestDirCoverageInfos.put(dirPath, info); + } + + public void annotateFile(@NotNull final String filePath, @NotNull final FileCoverageInfo info) { + myFileCoverageInfos.put(filePath, info); } }); - - if (modulesContentRoots == null) { - return; - } - - // gather coverage from all content roots - for (VirtualFile root : modulesContentRoots) { - annotate(root, suite, dataManager, data, project, new Annotator() { - public void annotateSourceDirectory(final String dirPath, final DirCoverageInfo info) { - myDirCoverageInfos.put(dirPath, info); - } - - public void annotateTestDirectory(final String dirPath, final DirCoverageInfo info) { - myTestDirCoverageInfos.put(dirPath, info); - } - - public void annotateFile(@NotNull final String filePath, @NotNull final FileCoverageInfo info) { - myFileCoverageInfos.put(filePath, info); - } - }); - } - - //final VirtualFile[] roots = ProjectRootManagerEx.getInstanceEx(project).getContentRootsFromAllModules(); - //index.iterateContentUnderDirectory(roots[0], new ContentIterator() { - // public boolean processFile(final VirtualFile fileOrDir) { - // // TODO support for libraries and sdk - // if (index.isInContent(fileOrDir)) { - // final String normalizedPath = RubyCoverageEngine.rcovalizePath(fileOrDir.getPath(), (RubyCoverageSuite)suite); - // - // // TODO - check filters - // - // if (fileOrDir.isDirectory()) { - // //// process dir - // //if (index.isInTestSourceContent(fileOrDir)) { - // // //myTestDirCoverageInfos.put(RubyCoverageEngine.rcovalizePath(fileOrDir.getPath(), (RubyCoverageSuite)suite), ) - // //} else { - // // myDirCoverageInfos.put(normalizedPath, new FileCoverageInfo()); - // //} - // } else { - // // process file - // final ClassData classData = data.getOrCreateClassData(normalizedPath); - // if (classData != null) { - // final int count = classData.getLines().length; - // if (count != 0) { - // final FileCoverageInfo info = new FileCoverageInfo(); - // info.totalLineCount = count; - // // let's count covered lines - // for (int i = 1; i <= count; i++) { - // final LineData lineData = classData.getLineData(i); - // if (lineData.getStatus() != LineCoverage.NONE){ - // info.coveredLineCount++; - // } - // } - // myFileCoverageInfos.put(normalizedPath, info); - // } - // } - // } - // } - // return true; - // } - //}); - - dataManager.triggerPresentationUpdate(); } + + //final VirtualFile[] roots = ProjectRootManagerEx.getInstanceEx(project).getContentRootsFromAllModules(); + //index.iterateContentUnderDirectory(roots[0], new ContentIterator() { + // public boolean processFile(final VirtualFile fileOrDir) { + // // TODO support for libraries and sdk + // if (index.isInContent(fileOrDir)) { + // final String normalizedPath = RubyCoverageEngine.rcovalizePath(fileOrDir.getPath(), (RubyCoverageSuite)suite); + // + // // TODO - check filters + // + // if (fileOrDir.isDirectory()) { + // //// process dir + // //if (index.isInTestSourceContent(fileOrDir)) { + // // //myTestDirCoverageInfos.put(RubyCoverageEngine.rcovalizePath(fileOrDir.getPath(), (RubyCoverageSuite)suite), ) + // //} else { + // // myDirCoverageInfos.put(normalizedPath, new FileCoverageInfo()); + // //} + // } else { + // // process file + // final ClassData classData = data.getOrCreateClassData(normalizedPath); + // if (classData != null) { + // final int count = classData.getLines().length; + // if (count != 0) { + // final FileCoverageInfo info = new FileCoverageInfo(); + // info.totalLineCount = count; + // // let's count covered lines + // for (int i = 1; i <= count; i++) { + // final LineData lineData = classData.getLineData(i); + // if (lineData.getStatus() != LineCoverage.NONE){ + // info.coveredLineCount++; + // } + // } + // myFileCoverageInfos.put(normalizedPath, info); + // } + // } + // } + // } + // return true; + // } + //}); + + dataManager.triggerPresentationUpdate(); }; } diff --git a/plugins/coverage-common/src/com/intellij/coverage/SrcFileAnnotator.java b/plugins/coverage-common/src/com/intellij/coverage/SrcFileAnnotator.java index 57519beaeeba..77d113d64999 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/SrcFileAnnotator.java +++ b/plugins/coverage-common/src/com/intellij/coverage/SrcFileAnnotator.java @@ -107,12 +107,7 @@ public class SrcFileAnnotator implements Disposable { final List highlighters = myEditor.getUserData(COVERAGE_HIGHLIGHTERS); if (highlighters != null) { for (final RangeHighlighter highlighter : highlighters) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - highlighter.dispose(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> highlighter.dispose()); } myEditor.putUserData(COVERAGE_HIGHLIGHTERS, null); } @@ -146,16 +141,14 @@ public class SrcFileAnnotator implements Disposable { @NotNull private static String[] getUpToDateLines(final Document document) { final Ref linesRef = new Ref(); - final Runnable runnable = new Runnable() { - public void run() { - final int lineCount = document.getLineCount(); - final String[] lines = new String[lineCount]; - final CharSequence chars = document.getCharsSequence(); - for (int i = 0; i < lineCount; i++) { - lines[i] = chars.subSequence(document.getLineStartOffset(i), document.getLineEndOffset(i)).toString(); - } - linesRef.set(lines); + final Runnable runnable = () -> { + final int lineCount = document.getLineCount(); + final String[] lines = new String[lineCount]; + final CharSequence chars = document.getCharsSequence(); + for (int i = 0; i < lineCount; i++) { + lines[i] = chars.subSequence(document.getLineStartOffset(i), document.getLineEndOffset(i)).toString(); } + linesRef.set(lines); }; ApplicationManager.getApplication().runReadAction(runnable); @@ -345,11 +338,7 @@ public class SrcFileAnnotator implements Disposable { } }); if (module != null) { - if (engine.recompileProjectAndRerunAction(module, suite, new Runnable() { - public void run() { - CoverageDataManager.getInstance(myProject).chooseSuitesBundle(suite); - } - })) { + if (engine.recompileProjectAndRerunAction(module, suite, () -> CoverageDataManager.getInstance(myProject).chooseSuitesBundle(suite))) { return; } } @@ -392,14 +381,12 @@ public class SrcFileAnnotator implements Disposable { classLines.put(line, postProcessedLines); classNames.put(line, qualifiedName); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (lineNumberInCurrent >= document.getLineCount()) return; - final RangeHighlighter highlighter = - createRangeHighlighter(suite.getLastCoverageTimeStamp(), markupModel, coverageByTestApplicable, executableLines, - qualifiedName, line, lineNumberInCurrent, suite, postProcessedLines); - highlighters.add(highlighter); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (lineNumberInCurrent >= document.getLineCount()) return; + final RangeHighlighter highlighter = + createRangeHighlighter(suite.getLastCoverageTimeStamp(), markupModel, coverageByTestApplicable, executableLines, + qualifiedName, line, lineNumberInCurrent, suite, postProcessedLines); + highlighters.add(highlighter); }); } } @@ -427,11 +414,9 @@ public class SrcFileAnnotator implements Disposable { collector.collect(null, qName); } } - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (myEditor != null && highlighters.size() > 0) { - editor.putUserData(COVERAGE_HIGHLIGHTERS, highlighters); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myEditor != null && highlighters.size() > 0) { + editor.putUserData(COVERAGE_HIGHLIGHTERS, highlighters); } }); @@ -457,29 +442,24 @@ public class SrcFileAnnotator implements Disposable { final List highlighters = rangeHighlighters; myUpdateAlarm.cancelAllRequests(); if (!myUpdateAlarm.isDisposed()) { - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - final TIntIntHashMap newToOldLineMapping = getNewToOldLineMapping(suite.getLastCoverageTimeStamp()); - if (newToOldLineMapping != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (editor.isDisposed()) return; - for (int line = lineNumber; line <= lastLineNumber; line++) { - final int oldLineNumber = newToOldLineMapping.get(line); - final LineData lineData = executableLines.get(oldLineNumber); - if (lineData != null) { - RangeHighlighter rangeHighlighter = - createRangeHighlighter(suite.getLastCoverageTimeStamp(), markupModel, coverageByTestApplicable, executableLines, - classNames.get(oldLineNumber), oldLineNumber, line, suite, - classLines.get(oldLineNumber)); - highlighters.add(rangeHighlighter); - } - } - editor.putUserData(COVERAGE_HIGHLIGHTERS, highlighters.size() > 0 ? highlighters : null); + myUpdateAlarm.addRequest(() -> { + final TIntIntHashMap newToOldLineMapping = getNewToOldLineMapping(suite.getLastCoverageTimeStamp()); + if (newToOldLineMapping != null) { + ApplicationManager.getApplication().invokeLater(() -> { + if (editor.isDisposed()) return; + for (int line = lineNumber; line <= lastLineNumber; line++) { + final int oldLineNumber = newToOldLineMapping.get(line); + final LineData lineData = executableLines.get(oldLineNumber); + if (lineData != null) { + RangeHighlighter rangeHighlighter = + createRangeHighlighter(suite.getLastCoverageTimeStamp(), markupModel, coverageByTestApplicable, executableLines, + classNames.get(oldLineNumber), oldLineNumber, line, suite, + classLines.get(oldLineNumber)); + highlighters.add(rangeHighlighter); } - }); - } + } + editor.putUserData(COVERAGE_HIGHLIGHTERS, highlighters.size() > 0 ? highlighters : null); + }); } }, 100); } @@ -514,19 +494,15 @@ public class SrcFileAnnotator implements Disposable { final int endOffset = myDocument.getLineEndOffset(lineNumberInCurrent); final RangeHighlighter highlighter = markupModel.addRangeHighlighter(startOffset, endOffset, HighlighterLayer.SELECTION - 1, textAttributes, HighlighterTargetArea.LINES_IN_RANGE); - final Function newToOldConverter = new Function() { - public Integer fun(final Integer newLine) { - if (myEditor == null) return -1; - final TIntIntHashMap oldLineMapping = getNewToOldLineMapping(date); - return oldLineMapping != null ? oldLineMapping.get(newLine.intValue()) : newLine.intValue(); - } + final Function newToOldConverter = newLine -> { + if (myEditor == null) return -1; + final TIntIntHashMap oldLineMapping = getNewToOldLineMapping(date); + return oldLineMapping != null ? oldLineMapping.get(newLine.intValue()) : newLine.intValue(); }; - final Function oldToNewConverter = new Function() { - public Integer fun(final Integer newLine) { - if (myEditor == null) return -1; - final TIntIntHashMap newLineMapping = getOldToNewLineMapping(date); - return newLineMapping != null ? newLineMapping.get(newLine.intValue()) : newLine.intValue(); - } + final Function oldToNewConverter = newLine -> { + if (myEditor == null) return -1; + final TIntIntHashMap newLineMapping = getOldToNewLineMapping(date); + return newLineMapping != null ? newLineMapping.get(newLine.intValue()) : newLine.intValue(); }; final CoverageLineMarkerRenderer markerRenderer = coverageSuite.getCoverageEngine() .getLineMarkerRenderer(line, className, executableLines, coverageByTestApplicable, coverageSuite, newToOldConverter, @@ -544,37 +520,32 @@ public class SrcFileAnnotator implements Disposable { } private void showEditorWarningMessage(final String message) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (myEditor == null) return; - final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject); - final VirtualFile vFile = myFile.getVirtualFile(); - assert vFile != null; - Map map = myFile.getCopyableUserData(NOTIFICATION_PANELS); - if (map == null) { - map = new HashMap(); - myFile.putCopyableUserData(NOTIFICATION_PANELS, map); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myEditor == null) return; + final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject); + final VirtualFile vFile = myFile.getVirtualFile(); + assert vFile != null; + Map map = myFile.getCopyableUserData(NOTIFICATION_PANELS); + if (map == null) { + map = new HashMap(); + myFile.putCopyableUserData(NOTIFICATION_PANELS, map); + } - final FileEditor[] editors = fileEditorManager.getAllEditors(vFile); - for (final FileEditor editor : editors) { - if (isCurrentEditor(editor)) { - final EditorNotificationPanel panel = new EditorNotificationPanel() { - { - myLabel.setIcon(AllIcons.General.ExclMark); - myLabel.setText(message); - } - }; - panel.createActionLabel("Close", new Runnable() { - @Override - public void run() { - fileEditorManager.removeTopComponent(editor, panel); - } - }); - map.put(editor, panel); - fileEditorManager.addTopComponent(editor, panel); - break; - } + final FileEditor[] editors = fileEditorManager.getAllEditors(vFile); + for (final FileEditor editor : editors) { + if (isCurrentEditor(editor)) { + final EditorNotificationPanel panel = new EditorNotificationPanel() { + { + myLabel.setIcon(AllIcons.General.ExclMark); + myLabel.setText(message); + } + }; + panel.createActionLabel("Close", () -> { + fileEditorManager.removeTopComponent(editor, panel); + }); + map.put(editor, panel); + fileEditorManager.addTopComponent(editor, panel); + break; } } }); @@ -632,14 +603,12 @@ public class SrcFileAnnotator implements Disposable { final int lineNumber, final int updatedLineNumber) { executableLines.put(updatedLineNumber, null); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (myEditor == null) return; - final RangeHighlighter highlighter = - createRangeHighlighter(outputFile.lastModified(), markupModel, coverageByTestApplicable, executableLines, null, lineNumber, - updatedLineNumber, coverageSuite, null); - highlighters.add(highlighter); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myEditor == null) return; + final RangeHighlighter highlighter = + createRangeHighlighter(outputFile.lastModified(), markupModel, coverageByTestApplicable, executableLines, null, lineNumber, + updatedLineNumber, coverageSuite, null); + highlighters.add(highlighter); }); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/actions/CoverageSuiteChooserDialog.java b/plugins/coverage-common/src/com/intellij/coverage/actions/CoverageSuiteChooserDialog.java index eab0ea6bcb36..61e58d355229 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/actions/CoverageSuiteChooserDialog.java +++ b/plugins/coverage-common/src/com/intellij/coverage/actions/CoverageSuiteChooserDialog.java @@ -154,12 +154,7 @@ public class CoverageSuiteChooserDialog extends DialogWrapper { groupSuites(grouped, myCoverageManager.getSuites(), myEngine); final CoverageSuitesBundle currentSuite = myCoverageManager.getCurrentSuitesBundle(); final List runners = new ArrayList(grouped.keySet()); - Collections.sort(runners, new Comparator() { - @Override - public int compare(CoverageRunner o1, CoverageRunner o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }); + Collections.sort(runners, (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName())); for (CoverageRunner runner : runners) { final DefaultMutableTreeNode runnerNode = new DefaultMutableTreeNode(getCoverageRunnerTitle(runner)); final Map> providers = grouped.get(runner); @@ -172,12 +167,7 @@ public class CoverageSuiteChooserDialog extends DialogWrapper { runnerNode.add(remoteNode); } final List suites = providers.get(providersKey); - Collections.sort(suites, new Comparator() { - @Override - public int compare(CoverageSuite o1, CoverageSuite o2) { - return o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName()); - } - }); + Collections.sort(suites, (o1, o2) -> o1.getPresentableName().compareToIgnoreCase(o2.getPresentableName())); for (CoverageSuite suite : suites) { final CheckedTreeNode treeNode = new CheckedTreeNode(suite); treeNode.setChecked(currentSuite != null && currentSuite.contains(suite) ? Boolean.TRUE : Boolean.FALSE); @@ -311,20 +301,17 @@ public class CoverageSuiteChooserDialog extends DialogWrapper { final CheckedTreeNode suiteNode = new CheckedTreeNode(coverageSuite); suiteNode.setChecked(true); node.add(suiteNode); - TreeUtil.sort(node, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof CheckedTreeNode && o2 instanceof CheckedTreeNode) { - final Object userObject1 = ((CheckedTreeNode)o1).getUserObject(); - final Object userObject2 = ((CheckedTreeNode)o2).getUserObject(); - if (userObject1 instanceof CoverageSuite && userObject2 instanceof CoverageSuite) { - final String presentableName1 = ((CoverageSuite)userObject1).getPresentableName(); - final String presentableName2 = ((CoverageSuite)userObject2).getPresentableName(); - return presentableName1.compareToIgnoreCase(presentableName2); - } + TreeUtil.sort(node, (o1, o2) -> { + if (o1 instanceof CheckedTreeNode && o2 instanceof CheckedTreeNode) { + final Object userObject1 = ((CheckedTreeNode)o1).getUserObject(); + final Object userObject2 = ((CheckedTreeNode)o2).getUserObject(); + if (userObject1 instanceof CoverageSuite && userObject2 instanceof CoverageSuite) { + final String presentableName1 = ((CoverageSuite)userObject1).getPresentableName(); + final String presentableName2 = ((CoverageSuite)userObject2).getPresentableName(); + return presentableName1.compareToIgnoreCase(presentableName2); } - return 0; } + return 0; }); updateTree(); TreeUtil.selectNode(mySuitesTree, suiteNode); diff --git a/plugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java b/plugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java index 82ed52031cb1..3d5f6a55b1ae 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java +++ b/plugins/coverage-common/src/com/intellij/coverage/actions/ShowCoveringTestsAction.java @@ -64,24 +64,22 @@ public class ShowCoveringTestsAction extends AnAction { final File[] traceFiles = getTraceFiles(project); final Set tests = new HashSet(); - Runnable runnable = new Runnable() { - public void run() { - for (File traceFile : traceFiles) { - DataInputStream in = null; + Runnable runnable = () -> { + for (File traceFile : traceFiles) { + DataInputStream in = null; + try { + in = new DataInputStream(new FileInputStream(traceFile)); + extractTests(traceFile, in, tests); + } + catch (Exception ex) { + LOG.error(traceFile.getName(), ex); + } + finally { try { - in = new DataInputStream(new FileInputStream(traceFile)); - extractTests(traceFile, in, tests); + in.close(); } - catch (Exception ex) { - LOG.error(traceFile.getName(), ex); - } - finally { - try { - in.close(); - } - catch (IOException ex) { - LOG.error(ex); - } + catch (IOException ex) { + LOG.error(ex); } } } @@ -102,13 +100,10 @@ public class ShowCoveringTestsAction extends AnAction { component = new ImplementationViewComponent(PsiUtilCore.toPsiElementArray(elements), 0); popupBuilder = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component.getPreferredFocusableComponent()) .setDimensionServiceKey(project, "ShowTestsPopup", false) - .setCouldPin(new Processor() { - @Override - public boolean process(JBPopup popup) { - component.showInUsageView(); - popup.cancel(); - return false; - } + .setCouldPin(popup -> { + component.showInUsageView(); + popup.cancel(); + return false; }); } else { component = null; diff --git a/plugins/coverage-common/src/com/intellij/coverage/actions/TrackCoverageAction.java b/plugins/coverage-common/src/com/intellij/coverage/actions/TrackCoverageAction.java index e6f8fe849a29..a2420ca81c7b 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/actions/TrackCoverageAction.java +++ b/plugins/coverage-common/src/com/intellij/coverage/actions/TrackCoverageAction.java @@ -154,11 +154,7 @@ public class TrackCoverageAction extends ToggleModelAction { final CoverageSuitesBundle currentSuite = coverageDataManager.getCurrentSuitesBundle(); if (currentSuite != null) { if (ApplicationManager.getApplication().isDispatchThread()) { - myUpdateCoverageAlarm.addRequest(new Runnable() { - public void run() { - selectSubCoverage(); - } - }, 300); + myUpdateCoverageAlarm.addRequest(() -> selectSubCoverage(), 300); } else { if (coverageDataManager.isSubCoverageActive()) coverageDataManager.restoreMergedCoverage(currentSuite); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/view/CoverageListNode.java b/plugins/coverage-common/src/com/intellij/coverage/view/CoverageListNode.java index feecdc8aeb14..a0a9a603c10f 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/view/CoverageListNode.java +++ b/plugins/coverage-common/src/com/intellij/coverage/view/CoverageListNode.java @@ -55,21 +55,19 @@ public class CoverageListNode extends AbstractTreeNode { @Override protected void update(final PresentationData presentation) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final Object value = getValue(); - if (value instanceof PsiNamedElement) { + ApplicationManager.getApplication().runReadAction(() -> { + final Object value = getValue(); + if (value instanceof PsiNamedElement) { - if (value instanceof PsiQualifiedNamedElement && - (myStateBean.myFlattenPackages && ((PsiNamedElement)value).getContainingFile() == null || - getParent() instanceof CoverageListRootNode)) { - presentation.setPresentableText(((PsiQualifiedNamedElement)value).getQualifiedName()); - } - else { - presentation.setPresentableText(((PsiNamedElement)value).getName()); - } - presentation.setIcon(((PsiElement)value).getIcon(0)); + if (value instanceof PsiQualifiedNamedElement && + (myStateBean.myFlattenPackages && ((PsiNamedElement)value).getContainingFile() == null || + getParent() instanceof CoverageListRootNode)) { + presentation.setPresentableText(((PsiQualifiedNamedElement)value).getQualifiedName()); } + else { + presentation.setPresentableText(((PsiNamedElement)value).getName()); + } + presentation.setIcon(((PsiElement)value).getIcon(0)); } }); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/view/CoverageViewManager.java b/plugins/coverage-common/src/com/intellij/coverage/view/CoverageViewManager.java index f0bda99d1244..a3fa2973f7ba 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/view/CoverageViewManager.java +++ b/plugins/coverage-common/src/com/intellij/coverage/view/CoverageViewManager.java @@ -108,13 +108,11 @@ public class CoverageViewManager implements PersistentStateComponent { + if (content != null) { + myContentManager.removeContent(content, true); } + Disposer.dispose(oldView); }; ApplicationManager.getApplication().invokeLater(runnable); } diff --git a/plugins/coverage-common/src/com/intellij/coverage/view/PercentageCoverageColumnInfo.java b/plugins/coverage-common/src/com/intellij/coverage/view/PercentageCoverageColumnInfo.java index 52de0da33d10..4d4dc02f3564 100644 --- a/plugins/coverage-common/src/com/intellij/coverage/view/PercentageCoverageColumnInfo.java +++ b/plugins/coverage-common/src/com/intellij/coverage/view/PercentageCoverageColumnInfo.java @@ -26,36 +26,33 @@ class PercentageCoverageColumnInfo extends ColumnInfo { CoverageViewManager.StateBean stateBean) { super(name); this.myColumnIdx = columnIdx; - myComparator = new Comparator() { - @Override - public int compare(NodeDescriptor o1, NodeDescriptor o2) { - final String val1 = valueOf(o1); - final String val2 = valueOf(o2); - if (val1 != null && val2 != null) { - final int percentageIndex1 = val1.indexOf('%'); - final int percentageIndex2 = val2.indexOf('%'); - if (percentageIndex1 > -1 && percentageIndex2 >-1) { - final String percentage1 = val1.substring(0, percentageIndex1); - final String percentage2 = val2.substring(0, percentageIndex2); - final int compare = Comparing.compare(Integer.parseInt(percentage1), Integer.parseInt(percentage2)); - if (compare == 0) { - final int total1 = val1.indexOf('/'); - final int total2 = val2.indexOf('/'); - if (total1 > -1 && total2 > -1) { - final int r1 = val1.indexOf(')', total1); - final int r2 = val2.indexOf(')', total2); - if (r1 > -1 && r2 > -1) { - return Integer.parseInt(val2.substring(total2 + 1, r2)) - Integer.parseInt(val1.substring(total1 + 1, r1)) ; - } + myComparator = (o1, o2) -> { + final String val1 = valueOf(o1); + final String val2 = valueOf(o2); + if (val1 != null && val2 != null) { + final int percentageIndex1 = val1.indexOf('%'); + final int percentageIndex2 = val2.indexOf('%'); + if (percentageIndex1 > -1 && percentageIndex2 >-1) { + final String percentage1 = val1.substring(0, percentageIndex1); + final String percentage2 = val2.substring(0, percentageIndex2); + final int compare = Comparing.compare(Integer.parseInt(percentage1), Integer.parseInt(percentage2)); + if (compare == 0) { + final int total1 = val1.indexOf('/'); + final int total2 = val2.indexOf('/'); + if (total1 > -1 && total2 > -1) { + final int r1 = val1.indexOf(')', total1); + final int r2 = val2.indexOf(')', total2); + if (r1 > -1 && r2 > -1) { + return Integer.parseInt(val2.substring(total2 + 1, r2)) - Integer.parseInt(val1.substring(total1 + 1, r1)) ; } } - return compare; } - if (percentageIndex1 > -1) return 1; - if (percentageIndex2 > -1) return -1; + return compare; } - return Comparing.compare(val1, val2); + if (percentageIndex1 > -1) return 1; + if (percentageIndex2 > -1) return -1; } + return Comparing.compare(val1, val2); }; mySuitesBundle = suitesBundle; myStateBean = stateBean; diff --git a/plugins/coverage/src/com/intellij/coverage/IDEACoverageRunner.java b/plugins/coverage/src/com/intellij/coverage/IDEACoverageRunner.java index 06809cc56670..30f173b74760 100644 --- a/plugins/coverage/src/com/intellij/coverage/IDEACoverageRunner.java +++ b/plugins/coverage/src/com/intellij/coverage/IDEACoverageRunner.java @@ -80,14 +80,11 @@ public class IDEACoverageRunner extends JavaCoverageRunner { final boolean collectLineInfo, final boolean isSampling, @Nullable String sourceMapPath) { StringBuilder argument = new StringBuilder("-javaagent:"); final String agentPath = PathUtil.getJarPathForClass(ProjectData.class); - final String parentPath = handleSpacesInPath(agentPath, new FileFilter() { - @Override - public boolean accept(File file) { - final String fileName = file.getName(); - return fileName.startsWith("coverage-") || - fileName.startsWith("asm-all") || - fileName.startsWith("trove4j"); - } + final String parentPath = handleSpacesInPath(agentPath, file -> { + final String fileName = file.getName(); + return fileName.startsWith("coverage-") || + fileName.startsWith("asm-all") || + fileName.startsWith("trove4j"); }); argument.append(parentPath).append(File.separator).append(new File(agentPath).getName()); argument.append("="); diff --git a/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java b/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java index 8a5e962a66b2..d3db8c84c6df 100644 --- a/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java +++ b/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java @@ -94,56 +94,52 @@ public class JavaCoverageAnnotator extends BaseCoverageAnnotator { return null; } - return new Runnable() { - public void run() { - final PackageAnnotator.Annotator annotator = new PackageAnnotator.Annotator() { - public void annotatePackage(String packageQualifiedName, PackageAnnotator.PackageCoverageInfo packageCoverageInfo) { - myPackageCoverageInfos.put(packageQualifiedName, packageCoverageInfo); - } + return () -> { + final PackageAnnotator.Annotator annotator = new PackageAnnotator.Annotator() { + public void annotatePackage(String packageQualifiedName, PackageAnnotator.PackageCoverageInfo packageCoverageInfo) { + myPackageCoverageInfos.put(packageQualifiedName, packageCoverageInfo); + } - public void annotatePackage(String packageQualifiedName, - PackageAnnotator.PackageCoverageInfo packageCoverageInfo, - boolean flatten) { - if (flatten) { - myFlattenPackageCoverageInfos.put(packageQualifiedName, packageCoverageInfo); - } - else { - annotatePackage(packageQualifiedName, packageCoverageInfo); - } + public void annotatePackage(String packageQualifiedName, + PackageAnnotator.PackageCoverageInfo packageCoverageInfo, + boolean flatten) { + if (flatten) { + myFlattenPackageCoverageInfos.put(packageQualifiedName, packageCoverageInfo); } - - public void annotateSourceDirectory(VirtualFile dir, - PackageAnnotator.PackageCoverageInfo dirCoverageInfo, - Module module) { - myDirCoverageInfos.put(dir, dirCoverageInfo); + else { + annotatePackage(packageQualifiedName, packageCoverageInfo); } + } - public void annotateTestDirectory(VirtualFile virtualFile, - PackageAnnotator.PackageCoverageInfo packageCoverageInfo, + public void annotateSourceDirectory(VirtualFile dir, + PackageAnnotator.PackageCoverageInfo dirCoverageInfo, Module module) { - myTestDirCoverageInfos.put(virtualFile, packageCoverageInfo); - } + myDirCoverageInfos.put(dir, dirCoverageInfo); + } - public void annotateClass(String classQualifiedName, PackageAnnotator.ClassCoverageInfo classCoverageInfo) { - myClassCoverageInfos.put(classQualifiedName, classCoverageInfo); - } - }; - for (PsiPackage aPackage : packages) { - new PackageAnnotator(aPackage).annotate(suite, annotator); + public void annotateTestDirectory(VirtualFile virtualFile, + PackageAnnotator.PackageCoverageInfo packageCoverageInfo, + Module module) { + myTestDirCoverageInfos.put(virtualFile, packageCoverageInfo); } - for (final PsiClass aClass : classes) { - Runnable runnable = new Runnable() { - public void run() { - final String packageName = ((PsiClassOwner)aClass.getContainingFile()).getPackageName(); - final PsiPackage psiPackage = JavaPsiFacade.getInstance(project).findPackage(packageName); - if (psiPackage == null) return; - new PackageAnnotator(psiPackage).annotateFilteredClass(aClass, suite, annotator); - } - }; - ApplicationManager.getApplication().runReadAction(runnable); + + public void annotateClass(String classQualifiedName, PackageAnnotator.ClassCoverageInfo classCoverageInfo) { + myClassCoverageInfos.put(classQualifiedName, classCoverageInfo); } - dataManager.triggerPresentationUpdate(); + }; + for (PsiPackage aPackage : packages) { + new PackageAnnotator(aPackage).annotate(suite, annotator); } + for (final PsiClass aClass : classes) { + Runnable runnable = () -> { + final String packageName = ((PsiClassOwner)aClass.getContainingFile()).getPackageName(); + final PsiPackage psiPackage = JavaPsiFacade.getInstance(project).findPackage(packageName); + if (psiPackage == null) return; + new PackageAnnotator(psiPackage).annotateFilteredClass(aClass, suite, annotator); + }; + ApplicationManager.getApplication().runReadAction(runnable); + } + dataManager.triggerPresentationUpdate(); }; } diff --git a/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java b/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java index e7ae2b21f66a..4a4fa37e8609 100644 --- a/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java +++ b/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java @@ -204,26 +204,22 @@ public class JavaCoverageEngine extends CoverageEngine { final Project project = module.getProject(); if (suite.isModuleChecked(module)) return false; suite.checkModule(module); - final Runnable runnable = new Runnable() { - public void run() { - if (Messages.showOkCancelDialog( - "Project class files are out of date. Would you like to recompile? The refusal to do it will result in incomplete coverage information", - "Project is out of date", Messages.getWarningIcon()) == Messages.OK) { - final CompilerManager compilerManager = CompilerManager.getInstance(project); - compilerManager.make(compilerManager.createProjectCompileScope(project), new CompileStatusNotification() { - public void finished(final boolean aborted, final int errors, final int warnings, final CompileContext compileContext) { - if (aborted || errors != 0) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (project.isDisposed()) return; - CoverageDataManager.getInstance(project).chooseSuitesBundle(suite); - } - }); - } - }); - } else if (!project.isDisposed()) { - CoverageDataManager.getInstance(project).chooseSuitesBundle(null); - } + final Runnable runnable = () -> { + if (Messages.showOkCancelDialog( + "Project class files are out of date. Would you like to recompile? The refusal to do it will result in incomplete coverage information", + "Project is out of date", Messages.getWarningIcon()) == Messages.OK) { + final CompilerManager compilerManager = CompilerManager.getInstance(project); + compilerManager.make(compilerManager.createProjectCompileScope(project), new CompileStatusNotification() { + public void finished(final boolean aborted, final int errors, final int warnings, final CompileContext compileContext) { + if (aborted || errors != 0) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; + CoverageDataManager.getInstance(project).chooseSuitesBundle(suite); + }); + } + }); + } else if (!project.isDisposed()) { + CoverageDataManager.getInstance(project).chooseSuitesBundle(null); } }; ApplicationManager.getApplication().invokeLater(runnable); diff --git a/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/RequestProcessor.java b/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/RequestProcessor.java index 4d04c6aa31cb..2854b0005560 100644 --- a/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/RequestProcessor.java +++ b/plugins/cvs/javacvs-src/org/netbeans/lib/cvsclient/RequestProcessor.java @@ -183,27 +183,25 @@ public final class RequestProcessor implements IRequestProcessor { final IConnectionStreams connectionStreams, final IRequestsProgressHandler communicationProgressHandler) throws CommandException, IOCommandException { - final Runnable runnable = new Runnable() { - public void run() { - try { - checkCanceled(); - sendRequests(requests, connectionStreams, communicationProgressHandler); - checkCanceled(); + final Runnable runnable = () -> { + try { + checkCanceled(); + sendRequests(requests, connectionStreams, communicationProgressHandler); + checkCanceled(); - sendRequest(requests.getResponseExpectingRequest(), connectionStreams); - connectionStreams.flushForReading(); + sendRequest(requests.getResponseExpectingRequest(), connectionStreams); + connectionStreams.flushForReading(); - myResult = handleResponses(connectionStreams, new DefaultResponseHandler()); - } - catch (IOException e) { - myIOException = e; - } - catch (CommandException e) { - myCommandException = e; - } - finally { - afterInRunnable(); - } + myResult = handleResponses(connectionStreams, new DefaultResponseHandler()); + } + catch (IOException e) { + myIOException = e; + } + catch (CommandException e) { + myCommandException = e; + } + finally { + afterInRunnable(); } }; diff --git a/plugins/devkit/src/actions/GenerateComponentExternalizationAction.java b/plugins/devkit/src/actions/GenerateComponentExternalizationAction.java index f1affb01da18..9c9adb8ee381 100644 --- a/plugins/devkit/src/actions/GenerateComponentExternalizationAction.java +++ b/plugins/devkit/src/actions/GenerateComponentExternalizationAction.java @@ -50,51 +50,45 @@ public class GenerateComponentExternalizationAction extends AnAction { final CodeStyleManager formatter = CodeStyleManager.getInstance(target.getManager().getProject()); final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(target.getProject()); final String qualifiedName = target.getQualifiedName(); - Runnable runnable = new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - final PsiReferenceList implList = target.getImplementsList(); - assert implList != null; - final PsiJavaCodeReferenceElement referenceElement = - factory.createReferenceFromText(PERSISTENCE_STATE_COMPONENT + "<" + qualifiedName + ">", target); - implList.add(styler.shortenClassReferences(referenceElement.copy())); - PsiMethod read = factory.createMethodFromText( - "public void loadState(" + qualifiedName + " state) {\n" + - " com.intellij.util.xmlb.XmlSerializerUtil.copyBean(state, this);\n" + - "}", - target - ); + Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + final PsiReferenceList implList = target.getImplementsList(); + assert implList != null; + final PsiJavaCodeReferenceElement referenceElement = + factory.createReferenceFromText(PERSISTENCE_STATE_COMPONENT + "<" + qualifiedName + ">", target); + implList.add(styler.shortenClassReferences(referenceElement.copy())); + PsiMethod read = factory.createMethodFromText( + "public void loadState(" + qualifiedName + " state) {\n" + + " com.intellij.util.xmlb.XmlSerializerUtil.copyBean(state, this);\n" + + "}", + target + ); - read = (PsiMethod)formatter.reformat(target.add(read)); - styler.shortenClassReferences(read); + read = (PsiMethod)formatter.reformat(target.add(read)); + styler.shortenClassReferences(read); - PsiMethod write = factory.createMethodFromText( - "public " + qualifiedName + " getState() {\n" + - " return this;\n" + - "}\n", - target - ); - write = (PsiMethod)formatter.reformat(target.add(write)); - styler.shortenClassReferences(write); + PsiMethod write = factory.createMethodFromText( + "public " + qualifiedName + " getState() {\n" + + " return this;\n" + + "}\n", + target + ); + write = (PsiMethod)formatter.reformat(target.add(write)); + styler.shortenClassReferences(write); - PsiAnnotation annotation = target.getModifierList().addAnnotation(STATE); + PsiAnnotation annotation = target.getModifierList().addAnnotation(STATE); - annotation = (PsiAnnotation)formatter.reformat(annotation.replace( - factory.createAnnotationFromText("@" + STATE + - "(name = \"" + qualifiedName + "\", " + - "storages = {@" + STORAGE + "(file = \"" + StoragePathMacros.WORKSPACE_FILE + "\"\n )})", - target))); - styler.shortenClassReferences(annotation); - } - catch (IncorrectOperationException e1) { - LOG.error(e1); - } - } - }); + annotation = (PsiAnnotation)formatter.reformat(annotation.replace( + factory.createAnnotationFromText("@" + STATE + + "(name = \"" + qualifiedName + "\", " + + "storages = {@" + STORAGE + "(file = \"" + StoragePathMacros.WORKSPACE_FILE + "\"\n )})", + target))); + styler.shortenClassReferences(annotation); } - }; + catch (IncorrectOperationException e1) { + LOG.error(e1); + } + }); CommandProcessor.getInstance().executeCommand(target.getProject(), runnable, DevKitBundle.message("command.implement.externalizable"), null); diff --git a/plugins/devkit/src/actions/ToggleHighlightingMarkupAction.java b/plugins/devkit/src/actions/ToggleHighlightingMarkupAction.java index 71f605ca6843..9cafd4eabb91 100644 --- a/plugins/devkit/src/actions/ToggleHighlightingMarkupAction.java +++ b/plugins/devkit/src/actions/ToggleHighlightingMarkupAction.java @@ -120,16 +120,13 @@ public class ToggleHighlightingMarkupAction extends AnAction { final ArrayList infos = new ArrayList(); DaemonCodeAnalyzerEx.processHighlights( document, project, HighlightSeverity.WARNING, 0, sequence.length(), - new Processor() { - @Override - public boolean process(HighlightInfo info) { - if (info.getSeverity() != HighlightSeverity.WARNING && info.getSeverity() != HighlightSeverity.ERROR) return true; - if (info.getStartOffset() >= endOffset) return false; - if (info.getEndOffset() > startOffset) { - offset[0] = appendInfo(info, sb, sequence, offset[0], infos, false); - } - return true; + info -> { + if (info.getSeverity() != HighlightSeverity.WARNING && info.getSeverity() != HighlightSeverity.ERROR) return true; + if (info.getStartOffset() >= endOffset) return false; + if (info.getEndOffset() > startOffset) { + offset[0] = appendInfo(info, sb, sequence, offset[0], infos, false); } + return true; }); offset[0] = appendInfo(null, sb, sequence, offset[0], infos, false); sb.append(sequence.subSequence(offset[0], sequence.length())); diff --git a/plugins/devkit/src/build/PluginBuildUtil.java b/plugins/devkit/src/build/PluginBuildUtil.java index 157d31cd0cfa..8e9d0be117bb 100644 --- a/plugins/devkit/src/build/PluginBuildUtil.java +++ b/plugins/devkit/src/build/PluginBuildUtil.java @@ -61,15 +61,12 @@ public class PluginBuildUtil { } public static void getDependencies(Module module, final Set modules) { - productionRuntimeDependencies(module).forEachModule(new Processor() { - @Override - public boolean process(Module dep) { - if (ModuleType.get(dep) == StdModuleTypes.JAVA && !modules.contains(dep)) { - modules.add(dep); - getDependencies(dep, modules); - } - return true; + productionRuntimeDependencies(module).forEachModule(dep -> { + if (ModuleType.get(dep) == StdModuleTypes.JAVA && !modules.contains(dep)) { + modules.add(dep); + getDependencies(dep, modules); } + return true; }); } @@ -89,12 +86,9 @@ public class PluginBuildUtil { } public static void getLibraries(Module module, final Set libs) { - productionRuntimeDependencies(module).forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - libs.add(library); - return true; - } + productionRuntimeDependencies(module).forEachLibrary(library -> { + libs.add(library); + return true; }); } diff --git a/plugins/devkit/src/build/PluginModuleBuildConfEditor.java b/plugins/devkit/src/build/PluginModuleBuildConfEditor.java index 7c686bd8e8e7..2df981da36c8 100644 --- a/plugins/devkit/src/build/PluginModuleBuildConfEditor.java +++ b/plugins/devkit/src/build/PluginModuleBuildConfEditor.java @@ -109,11 +109,7 @@ public class PluginModuleBuildConfEditor implements ModuleConfigurationEditor { DevKitBundle.message("deployment.cleanup", META_INF), null) == Messages.YES) { CommandProcessor.getInstance().executeCommand(myModule.getProject(), - new Runnable() { - public void run() { - FileUtil.delete(plugin.getParentFile()); - } - }, + () -> FileUtil.delete(plugin.getParentFile()), DevKitBundle.message("deployment.cleanup", META_INF), null); } diff --git a/plugins/devkit/src/build/PrepareToDeployAction.java b/plugins/devkit/src/build/PrepareToDeployAction.java index 5942d92802ce..947c7d79f004 100644 --- a/plugins/devkit/src/build/PrepareToDeployAction.java +++ b/plugins/devkit/src/build/PrepareToDeployAction.java @@ -95,31 +95,29 @@ public class PrepareToDeployAction extends AnAction { final int warnings, final CompileContext compileContext) { if (aborted || errors != 0) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - for (Module aModule : pluginModules) { - if (!doPrepare(aModule, errorMessages, successMessages)) { - return; - } + ApplicationManager.getApplication().invokeLater(() -> { + for (Module aModule : pluginModules) { + if (!doPrepare(aModule, errorMessages, successMessages)) { + return; } + } - if (!errorMessages.isEmpty()) { - Messages.showErrorDialog(errorMessages.iterator().next(), DevKitBundle.message("error.occurred")); - } - else if (!successMessages.isEmpty()) { - StringBuilder messageBuf = new StringBuilder(); - for (String message : successMessages) { - if (messageBuf.length() != 0) { - messageBuf.append('\n'); - } - messageBuf.append(message); + if (!errorMessages.isEmpty()) { + Messages.showErrorDialog(errorMessages.iterator().next(), DevKitBundle.message("error.occurred")); + } + else if (!successMessages.isEmpty()) { + StringBuilder messageBuf = new StringBuilder(); + for (String message : successMessages) { + if (messageBuf.length() != 0) { + messageBuf.append('\n'); } - final String title = pluginModules.size() == 1 ? - DevKitBundle.message("success.deployment.message", pluginModules.get(0).getName()) : - DevKitBundle.message("success.deployment.message.all"); - NOTIFICATION_GROUP.createNotification(title, messageBuf.toString(), - NotificationType.INFORMATION, null).notify(project); + messageBuf.append(message); } + final String title = pluginModules.size() == 1 ? + DevKitBundle.message("success.deployment.message", pluginModules.get(0).getName()) : + DevKitBundle.message("success.deployment.message.all"); + NOTIFICATION_GROUP.createNotification(title, messageBuf.toString(), + NotificationType.INFORMATION, null).notify(project); } }, project.getDisposed()); } @@ -153,28 +151,26 @@ public class PrepareToDeployAction extends AnAction { final String dstPath = defaultPath + (isZip ? ZIP_EXTENSION : JAR_EXTENSION); final File dstFile = new File(dstPath); - return clearReadOnly(module.getProject(), dstFile) && ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { + return clearReadOnly(module.getProject(), dstFile) && ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - if (progressIndicator != null) { - progressIndicator.setText(DevKitBundle.message("prepare.for.deployment.common")); - progressIndicator.setIndeterminate(true); + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + if (progressIndicator != null) { + progressIndicator.setText(DevKitBundle.message("prepare.for.deployment.common")); + progressIndicator.setIndeterminate(true); + } + try { + File jarFile = preparePluginsJar(module, modules); + if (isZip) { + processLibrariesAndJpsPlugins(jarFile, dstFile, pluginName, libs, jpsModules, progressIndicator); } - try { - File jarFile = preparePluginsJar(module, modules); - if (isZip) { - processLibrariesAndJpsPlugins(jarFile, dstFile, pluginName, libs, jpsModules, progressIndicator); - } - else { - FileUtil.copy(jarFile, dstFile); - } - LocalFileSystem.getInstance().refreshIoFiles(Collections.singleton(dstFile), true, false, null); - successMessages.add(DevKitBundle.message("saved.message", isZip ? 1 : 2, pluginName, dstPath)); - } - catch (final IOException e) { - errorMessages.add(e.getMessage() + "\n(" + dstPath + ")"); + else { + FileUtil.copy(jarFile, dstFile); } + LocalFileSystem.getInstance().refreshIoFiles(Collections.singleton(dstFile), true, false, null); + successMessages.add(DevKitBundle.message("saved.message", isZip ? 1 : 2, pluginName, dstPath)); + } + catch (final IOException e) { + errorMessages.add(e.getMessage() + "\n(" + dstPath + ")"); } }, DevKitBundle.message("prepare.for.deployment", pluginName), true, module.getProject()); } @@ -227,13 +223,11 @@ public class PrepareToDeployAction extends AnAction { } private static FileFilter createFilter(final ProgressIndicator progressIndicator, @Nullable final FileTypeManager fileTypeManager) { - return new FileFilter() { - public boolean accept(File pathName) { - if (progressIndicator != null) { - progressIndicator.setText2(""); - } - return fileTypeManager == null || !fileTypeManager.isFileIgnored(FileUtil.toSystemIndependentName(pathName.getName())); + return pathName -> { + if (progressIndicator != null) { + progressIndicator.setText2(""); } + return fileTypeManager == null || !fileTypeManager.isFileIgnored(FileUtil.toSystemIndependentName(pathName.getName())); }; } diff --git a/plugins/devkit/src/dom/DependencyConfigFileConverter.java b/plugins/devkit/src/dom/DependencyConfigFileConverter.java index b9cb283a1ac5..06116adaeeae 100644 --- a/plugins/devkit/src/dom/DependencyConfigFileConverter.java +++ b/plugins/devkit/src/dom/DependencyConfigFileConverter.java @@ -76,15 +76,12 @@ public class DependencyConfigFileConverter extends PathReferenceConverter { if (!(file instanceof XmlFile)) return false; final DomFileElement ideaPlugin = DescriptorUtil.getIdeaPlugin((XmlFile)file); if (ideaPlugin == null) return false; - return !ContainerUtil.process(ideaPlugin.getRootElement().getDependencies(), new Processor() { - @Override - public boolean process(Dependency dependency) { - final GenericAttributeValue configFileAttribute = dependency.getConfigFile(); - if (!DomUtil.hasXml(configFileAttribute)) return true; - final PathReference pathReference = configFileAttribute.getValue(); - if (pathReference == null) return true; - return !xmlFile.equals(pathReference.resolve()); - } + return !ContainerUtil.process(ideaPlugin.getRootElement().getDependencies(), dependency -> { + final GenericAttributeValue configFileAttribute = dependency.getConfigFile(); + if (!DomUtil.hasXml(configFileAttribute)) return true; + final PathReference pathReference = configFileAttribute.getValue(); + if (pathReference == null) return true; + return !xmlFile.equals(pathReference.resolve()); }); } diff --git a/plugins/devkit/src/dom/generator/JetBrainsEmitter.java b/plugins/devkit/src/dom/generator/JetBrainsEmitter.java index efc82d6c1dd3..46b4f738f517 100644 --- a/plugins/devkit/src/dom/generator/JetBrainsEmitter.java +++ b/plugins/devkit/src/dom/generator/JetBrainsEmitter.java @@ -232,11 +232,7 @@ public class JetBrainsEmitter implements Emitter { if (fields.length == 0) { Util.logwarn("no fields in: " + td.xsName); } - Arrays.sort(fields, new Comparator() { - public int compare(FieldDesc o1, FieldDesc o2) { - return o1.realIndex - o2.realIndex; - } - }); + Arrays.sort(fields, (o1, o2) -> o1.realIndex - o2.realIndex); out.println(""); for (FieldDesc field : fields) { String tagName = field.tagName; @@ -562,11 +558,7 @@ public class JetBrainsEmitter implements Emitter { for (TypeDesc td : jtList) { ArrayList fields = new ArrayList(td.fdMap.values()); - Collections.sort(fields, new Comparator() { - public int compare(FieldDesc o1, FieldDesc o2) { - return o1.realIndex - o2.realIndex; - } - }); + Collections.sort(fields, (o1, o2) -> o1.realIndex - o2.realIndex); int guessPriority = 0; FieldDesc guessedField = null; for (FieldDesc fd : fields) { diff --git a/plugins/devkit/src/dom/impl/ActionOrGroupResolveConverter.java b/plugins/devkit/src/dom/impl/ActionOrGroupResolveConverter.java index 7f3f8538f655..238e2cc442ab 100644 --- a/plugins/devkit/src/dom/impl/ActionOrGroupResolveConverter.java +++ b/plugins/devkit/src/dom/impl/ActionOrGroupResolveConverter.java @@ -46,14 +46,11 @@ public class ActionOrGroupResolveConverter extends ResolvingConverter getVariants(ConvertContext context) { final List variants = new ArrayList(); - PairProcessor collectProcessor = new PairProcessor() { - @Override - public boolean process(String s, ActionOrGroup actionOrGroup) { - if (isRelevant(actionOrGroup)) { - variants.add(actionOrGroup); - } - return true; + PairProcessor collectProcessor = (s, actionOrGroup) -> { + if (isRelevant(actionOrGroup)) { + variants.add(actionOrGroup); } + return true; }; processActionOrGroup(context, collectProcessor); return variants; @@ -65,16 +62,13 @@ public class ActionOrGroupResolveConverter extends ResolvingConverter findProcessor = new PairProcessor() { - @Override - public boolean process(String s, ActionOrGroup actionOrGroup) { - if (isRelevant(actionOrGroup) && - Comparing.strEqual(value, s)) { - result[0] = actionOrGroup; - return false; - } - return true; + PairProcessor findProcessor = (s, actionOrGroup) -> { + if (isRelevant(actionOrGroup) && + Comparing.strEqual(value, s)) { + result[0] = actionOrGroup; + return false; } + return true; }; processActionOrGroup(context, findProcessor); return result[0]; @@ -156,13 +150,10 @@ public class ActionOrGroupResolveConverter extends ResolvingConverter dependenciesAndLibs = - IdeaPluginConverter.getPlugins(project, module.getModuleRuntimeScope(false)); - return processPlugins(dependenciesAndLibs, processor); - } + return ModuleUtilCore.visitMeAndDependentModules(module, module1 -> { + final Collection dependenciesAndLibs = + IdeaPluginConverter.getPlugins(project, module1.getModuleRuntimeScope(false)); + return processPlugins(dependenciesAndLibs, processor); }); } diff --git a/plugins/devkit/src/dom/impl/IdeaPluginConverter.java b/plugins/devkit/src/dom/impl/IdeaPluginConverter.java index 613bebc4d536..ca59fe0fef4e 100644 --- a/plugins/devkit/src/dom/impl/IdeaPluginConverter.java +++ b/plugins/devkit/src/dom/impl/IdeaPluginConverter.java @@ -128,10 +128,8 @@ public class IdeaPluginConverter extends ResolvingConverter { if (DumbService.isDumb(project)) return Collections.emptyList(); List> files = DomService.getInstance().getFileElements(IdeaPlugin.class, project, scope); - return ContainerUtil.map(files, new Function, IdeaPlugin>() { - public IdeaPlugin fun(DomFileElement ideaPluginDomFileElement) { - return ideaPluginDomFileElement.getRootElement(); - } + return ContainerUtil.map(files, ideaPluginDomFileElement -> { + return ideaPluginDomFileElement.getRootElement(); }); } } diff --git a/plugins/devkit/src/dom/impl/LanguageResolvingUtil.java b/plugins/devkit/src/dom/impl/LanguageResolvingUtil.java index 266880b181fe..ff34a14995af 100644 --- a/plugins/devkit/src/dom/impl/LanguageResolvingUtil.java +++ b/plugins/devkit/src/dom/impl/LanguageResolvingUtil.java @@ -97,55 +97,48 @@ class LanguageResolvingUtil { private static List collectLibraryLanguages(final ConvertContext context, final Collection allLanguages) { - return ContainerUtil.mapNotNull(Language.getRegisteredLanguages(), new NullableFunction() { - @Override - public LanguageDefinition fun(Language language) { - if (language.getID().isEmpty() || language instanceof DependentLanguage) { - return null; - } - final PsiClass psiClass = DomJavaUtil.findClass(language.getClass().getName(), context.getInvocationElement(), true); - if (psiClass == null || !allLanguages.contains(psiClass)) { - return null; - } - final LanguageFileType type = language.getAssociatedFileType(); - final Icon icon = type != null ? type.getIcon() : null; - return new LanguageDefinition(language.getID(), psiClass, icon, language.getDisplayName()); + return ContainerUtil.mapNotNull(Language.getRegisteredLanguages(), (NullableFunction)language -> { + if (language.getID().isEmpty() || language instanceof DependentLanguage) { + return null; } + final PsiClass psiClass = DomJavaUtil.findClass(language.getClass().getName(), context.getInvocationElement(), true); + if (psiClass == null || !allLanguages.contains(psiClass)) { + return null; + } + final LanguageFileType type = language.getAssociatedFileType(); + final Icon icon = type != null ? type.getIcon() : null; + return new LanguageDefinition(language.getID(), psiClass, icon, language.getDisplayName()); }); } private static List collectProjectLanguages(final Collection projectLanguages, final List libraryLanguages) { - return ContainerUtil.mapNotNull(projectLanguages, new NullableFunction() { - @Nullable - @Override - public LanguageDefinition fun(final PsiClass language) { - if (language.hasModifierProperty(PsiModifier.ABSTRACT)) { - return null; - } - - if (ContainerUtil.exists(libraryLanguages, new Condition() { - @Override - public boolean value(LanguageDefinition definition) { - return definition.clazz.equals(language); - } - })) { - return null; - } - - String id = computeConstantSuperCtorCallParameter(language, 0); - if (id == null) { - id = computeConstantSuperCtorCallParameter(language, 1); - } - if (id == null) { - id = computeConstantReturnValue(language, "getID"); - } - if (StringUtil.isEmpty(id)) { - return null; - } - - return new LanguageDefinition(id, language, null, computeConstantReturnValue(language, "getDisplayName")); + return ContainerUtil.mapNotNull(projectLanguages, (NullableFunction)language -> { + if (language.hasModifierProperty(PsiModifier.ABSTRACT)) { + return null; } + + if (ContainerUtil.exists(libraryLanguages, new Condition() { + @Override + public boolean value(LanguageDefinition definition) { + return definition.clazz.equals(language); + } + })) { + return null; + } + + String id = computeConstantSuperCtorCallParameter(language, 0); + if (id == null) { + id = computeConstantSuperCtorCallParameter(language, 1); + } + if (id == null) { + id = computeConstantReturnValue(language, "getID"); + } + if (StringUtil.isEmpty(id)) { + return null; + } + + return new LanguageDefinition(id, language, null, computeConstantReturnValue(language, "getDisplayName")); }); } diff --git a/plugins/devkit/src/dom/impl/PropertyKeyReferenceProvider.java b/plugins/devkit/src/dom/impl/PropertyKeyReferenceProvider.java index dca6fa3ee211..ed7fc81b9c16 100644 --- a/plugins/devkit/src/dom/impl/PropertyKeyReferenceProvider.java +++ b/plugins/devkit/src/dom/impl/PropertyKeyReferenceProvider.java @@ -152,11 +152,8 @@ public class PropertyKeyReferenceProvider extends PsiReferenceProvider { if (!(rootElement instanceof IdeaPlugin)) return Collections.emptyList(); IdeaPlugin plugin = (IdeaPlugin)rootElement; - return ContainerUtil.map(plugin.getResourceBundles(), new Function, String>() { - @Override - public String fun(GenericDomValue value) { - return value.getStringValue(); - } + return ContainerUtil.map(plugin.getResourceBundles(), value -> { + return value.getStringValue(); }); } } diff --git a/plugins/devkit/src/inspections/InspectionMappingConsistencyInspection.java b/plugins/devkit/src/inspections/InspectionMappingConsistencyInspection.java index c0ff4f45d101..b6f84c767940 100644 --- a/plugins/devkit/src/inspections/InspectionMappingConsistencyInspection.java +++ b/plugins/devkit/src/inspections/InspectionMappingConsistencyInspection.java @@ -90,17 +90,13 @@ public class InspectionMappingConsistencyInspection extends DevKitInspectionBase private static void registerProblem(DomElement element, ProblemsHolder holder, String message, String... createAttrs) { final Pair range = DomUtil.getProblemRange(element.getXmlTag()); - holder.registerProblem(range.second, range.first, message, ContainerUtil.map(createAttrs, new Function() { - @Override - public LocalQuickFix fun(final String s) { - return new InsertRequiredAttributeFix(PsiTreeUtil.getParentOfType(range.second, XmlTag.class, false), s) { - @NotNull - @Override - public String getText() { - return MessageFormat.format("Insert ''{0}'' attribute", s); - } - }; - } - }, new LocalQuickFix[createAttrs.length])); + holder.registerProblem(range.second, range.first, message, ContainerUtil.map(createAttrs, + s -> new InsertRequiredAttributeFix(PsiTreeUtil.getParentOfType(range.second, XmlTag.class, false), s) { + @NotNull + @Override + public String getText() { + return MessageFormat.format("Insert ''{0}'' attribute", s); + } + }, new LocalQuickFix[createAttrs.length])); } } diff --git a/plugins/devkit/src/inspections/quickfix/AbstractRegisterFix.java b/plugins/devkit/src/inspections/quickfix/AbstractRegisterFix.java index 7a3be851ce22..e0e2be41567b 100644 --- a/plugins/devkit/src/inspections/quickfix/AbstractRegisterFix.java +++ b/plugins/devkit/src/inspections/quickfix/AbstractRegisterFix.java @@ -79,38 +79,36 @@ abstract class AbstractRegisterFix implements LocalQuickFix, DescriptorUtil.Patc final Module module = ModuleUtil.findModuleForFile(psiFile.getVirtualFile(), project); assert module != null; - Runnable command = new Runnable() { - public void run() { - try { - if (PluginModuleType.isOfType(module)) { - XmlFile pluginXml = PluginModuleType.getPluginXml(module); - if (pluginXml != null) { - DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, element, pluginXml); - } + Runnable command = () -> { + try { + if (PluginModuleType.isOfType(module)) { + XmlFile pluginXml = PluginModuleType.getPluginXml(module); + if (pluginXml != null) { + DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, element, pluginXml); } - else { - List modules = PluginModuleType.getCandidateModules(module); - if (modules.size() > 1) { - ChooseModulesDialog dialog = new ChooseModulesDialog(project, modules, getName()); - if (!dialog.showAndGet()) { - return; - } - modules = dialog.getSelectedModules(); - } - XmlFile[] pluginXmls = new XmlFile[modules.size()]; - for (int i = 0; i < pluginXmls.length; i++) { - pluginXmls[i] = PluginModuleType.getPluginXml(modules.get(i)); + } + else { + List modules = PluginModuleType.getCandidateModules(module); + if (modules.size() > 1) { + ChooseModulesDialog dialog = new ChooseModulesDialog(project, modules, getName()); + if (!dialog.showAndGet()) { + return; } + modules = dialog.getSelectedModules(); + } + XmlFile[] pluginXmls = new XmlFile[modules.size()]; + for (int i = 0; i < pluginXmls.length; i++) { + pluginXmls[i] = PluginModuleType.getPluginXml(modules.get(i)); + } - DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, element, pluginXmls); - } - CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); - } - catch (IncorrectOperationException e) { - Messages.showMessageDialog(project, filterMessage(e.getMessage()), - DevKitBundle.message("inspections.component.not.registered.quickfix.error", getType()), - Messages.getErrorIcon()); + DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, element, pluginXmls); } + CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); + } + catch (IncorrectOperationException e) { + Messages.showMessageDialog(project, filterMessage(e.getMessage()), + DevKitBundle.message("inspections.component.not.registered.quickfix.error", getType()), + Messages.getErrorIcon()); } }; CommandProcessor.getInstance().executeCommand(project, command, getName(), null); diff --git a/plugins/devkit/src/inspections/quickfix/CreateHtmlDescriptionFix.java b/plugins/devkit/src/inspections/quickfix/CreateHtmlDescriptionFix.java index ebc19826b05c..173dbfe2fa58 100644 --- a/plugins/devkit/src/inspections/quickfix/CreateHtmlDescriptionFix.java +++ b/plugins/devkit/src/inspections/quickfix/CreateHtmlDescriptionFix.java @@ -113,10 +113,8 @@ public class CreateHtmlDescriptionFix implements LocalQuickFix, Iconable { final List virtualFiles = getPotentialRoots(myModule, dirs); final VirtualFile[] roots = prepare(VfsUtilCore.toVirtualFileArray(virtualFiles)); if (roots.length == 1) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - createDescription(roots[0]); - } + ApplicationManager.getApplication().runWriteAction(() -> { + createDescription(roots[0]); }); } else { @@ -130,16 +128,12 @@ public class CreateHtmlDescriptionFix implements LocalQuickFix, Iconable { final JBPopup popup = JBPopupFactory.getInstance() .createListPopupBuilder(files) .setTitle(DevKitBundle.message("select.target.location.of.description", myFilename)) - .setItemChoosenCallback(new Runnable() { - public void run() { - final int index = files.getSelectedIndex(); - if (0 <= index && index < roots.length) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - createDescription(roots[index]); - } - }); - } + .setItemChoosenCallback(() -> { + final int index = files.getSelectedIndex(); + if (0 <= index && index < roots.length) { + ApplicationManager.getApplication().runWriteAction(() -> { + createDescription(roots[index]); + }); } }).createPopup(); final Editor editor = FileEditorManager.getInstance(myModule.getProject()).getSelectedTextEditor(); diff --git a/plugins/devkit/src/inspections/quickfix/PluginDescriptorChooser.java b/plugins/devkit/src/inspections/quickfix/PluginDescriptorChooser.java index 94818c998970..b6f8f5446e44 100644 --- a/plugins/devkit/src/inspections/quickfix/PluginDescriptorChooser.java +++ b/plugins/devkit/src/inspections/quickfix/PluginDescriptorChooser.java @@ -156,27 +156,21 @@ public class PluginDescriptorChooser { private static List createCandidates(final Module currentModule, List> elements) { - Collections.sort(elements, new Comparator>() { - @Override - public int compare(DomFileElement o1, DomFileElement o2) { - // current module = first group - final Module module1 = o1.getModule(); - final Module module2 = o2.getModule(); - final int byAlpha = ModulesAlphaComparator.INSTANCE.compare(module1, module2); - if (byAlpha == 0) return 0; + Collections.sort(elements, (o1, o2) -> { + // current module = first group + final Module module1 = o1.getModule(); + final Module module2 = o2.getModule(); + final int byAlpha = ModulesAlphaComparator.INSTANCE.compare(module1, module2); + if (byAlpha == 0) return 0; - if (currentModule.equals(module1)) return -1; - if (currentModule.equals(module2)) return 1; + if (currentModule.equals(module1)) return -1; + if (currentModule.equals(module2)) return 1; - return byAlpha; - } + return byAlpha; }); - Collections.sort(elements, new Comparator>() { - @Override - public int compare(DomFileElement o1, DomFileElement o2) { - if (!Comparing.equal(o1.getModule(), o2.getModule())) return 0; - return o1.getFile().getName().compareTo(o2.getFile().getName()); - } + Collections.sort(elements, (o1, o2) -> { + if (!Comparing.equal(o1.getModule(), o2.getModule())) return 0; + return o1.getFile().getName().compareTo(o2.getFile().getName()); }); return ContainerUtil.map(elements, new Function, PluginDescriptorCandidate>() { diff --git a/plugins/devkit/src/inspections/quickfix/RegisterExtensionFix.java b/plugins/devkit/src/inspections/quickfix/RegisterExtensionFix.java index 45384b271ef2..67bc2114b4d8 100644 --- a/plugins/devkit/src/inspections/quickfix/RegisterExtensionFix.java +++ b/plugins/devkit/src/inspections/quickfix/RegisterExtensionFix.java @@ -79,12 +79,7 @@ public class RegisterExtensionFix implements IntentionAction { @Override public void invoke(@NotNull Project project, final Editor editor, PsiFile file) throws IncorrectOperationException { - PluginDescriptorChooser.show(project, editor, file, new Consumer>() { - @Override - public void consume(DomFileElement element) { - doFix(editor, element); - } - }); + PluginDescriptorChooser.show(project, editor, file, element -> doFix(editor, element)); } private void doFix(Editor editor, final DomFileElement element) { diff --git a/plugins/devkit/src/inspections/quickfix/RegisterInspectionFix.java b/plugins/devkit/src/inspections/quickfix/RegisterInspectionFix.java index fb4fa6893f8d..54a22e093536 100644 --- a/plugins/devkit/src/inspections/quickfix/RegisterInspectionFix.java +++ b/plugins/devkit/src/inspections/quickfix/RegisterInspectionFix.java @@ -68,12 +68,7 @@ class RegisterInspectionFix implements IntentionAction { @Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { - PluginDescriptorChooser.show(project, editor, file, new Consumer>() { - @Override - public void consume(DomFileElement element) { - doFix(element, project, file); - } - }); + PluginDescriptorChooser.show(project, editor, file, element -> doFix(element, project, file)); } private void doFix(final DomFileElement selectedValue, final Project project, final PsiFile file) { diff --git a/plugins/devkit/src/module/PluginModuleBuilder.java b/plugins/devkit/src/module/PluginModuleBuilder.java index e8d47dfe940d..c455c39b971a 100644 --- a/plugins/devkit/src/module/PluginModuleBuilder.java +++ b/plugins/devkit/src/module/PluginModuleBuilder.java @@ -64,17 +64,15 @@ public class PluginModuleBuilder extends JavaModuleBuilder{ final String defaultPluginXMLLocation = resourceRootPath + "/META-INF/plugin.xml"; final Module module = rootModel.getModule(); final Project project = module.getProject(); - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - public void run() { - final PluginBuildConfiguration buildConfiguration = PluginBuildConfiguration.getInstance(module); - if (buildConfiguration != null) { - buildConfiguration.setPluginXmlPathAndCreateDescriptorIfDoesntExist(defaultPluginXMLLocation); - } + StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> { + final PluginBuildConfiguration buildConfiguration = PluginBuildConfiguration.getInstance(module); + if (buildConfiguration != null) { + buildConfiguration.setPluginXmlPathAndCreateDescriptorIfDoesntExist(defaultPluginXMLLocation); + } - VirtualFile file = LocalFileSystem.getInstance().findFileByPath(defaultPluginXMLLocation); - if (file != null) { - FileEditorManager.getInstance(project).openFile(file, true); - } + VirtualFile file = LocalFileSystem.getInstance().findFileByPath(defaultPluginXMLLocation); + if (file != null) { + FileEditorManager.getInstance(project).openFile(file, true); } }); } diff --git a/plugins/devkit/src/navigation/DescriptionTypeRelatedItemLineMarkerProvider.java b/plugins/devkit/src/navigation/DescriptionTypeRelatedItemLineMarkerProvider.java index a5c4fba2db15..deafe63b0130 100644 --- a/plugins/devkit/src/navigation/DescriptionTypeRelatedItemLineMarkerProvider.java +++ b/plugins/devkit/src/navigation/DescriptionTypeRelatedItemLineMarkerProvider.java @@ -45,22 +45,10 @@ import java.util.List; public class DescriptionTypeRelatedItemLineMarkerProvider extends DevkitRelatedLineMarkerProviderBase { private static final NotNullFunction> CONVERTER = - new NotNullFunction>() { - @NotNull - @Override - public Collection fun(PsiFile psiFile) { - return ContainerUtil.createMaybeSingletonList(psiFile); - } - }; + psiFile -> ContainerUtil.createMaybeSingletonList(psiFile); private static final NotNullFunction> RELATED_ITEM_PROVIDER = - new NotNullFunction>() { - @NotNull - @Override - public Collection fun(PsiFile psiFile) { - return GotoRelatedItem.createItems(Collections.singleton(psiFile), "DevKit"); - } - }; + psiFile -> GotoRelatedItem.createItems(Collections.singleton(psiFile), "DevKit"); @Override protected void collectNavigationMarkers(@NotNull PsiElement element, Collection result) { @@ -126,12 +114,7 @@ public class DescriptionTypeRelatedItemLineMarkerProvider extends DevkitRelatedL private static void addBeforeAfterTemplateFilesGutterIcon(PsiElement highlightingElement, PsiDirectory descriptionDirectory, Collection result) { - final List templateFiles = new SortedList(new Comparator() { - @Override - public int compare(PsiFile o1, PsiFile o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + final List templateFiles = new SortedList((o1, o2) -> o1.getName().compareTo(o2.getName())); for (PsiFile file : descriptionDirectory.getFiles()) { final String fileName = file.getName(); if (fileName.endsWith(".template")) { diff --git a/plugins/devkit/src/navigation/ExtensionPointDeclarationRelatedItemLineMarkerProvider.java b/plugins/devkit/src/navigation/ExtensionPointDeclarationRelatedItemLineMarkerProvider.java index d71b54a540f6..810cc606599f 100644 --- a/plugins/devkit/src/navigation/ExtensionPointDeclarationRelatedItemLineMarkerProvider.java +++ b/plugins/devkit/src/navigation/ExtensionPointDeclarationRelatedItemLineMarkerProvider.java @@ -39,22 +39,10 @@ import java.util.List; public class ExtensionPointDeclarationRelatedItemLineMarkerProvider extends DevkitRelatedLineMarkerProviderBase { private static final NotNullFunction> CONVERTER = - new NotNullFunction>() { - @NotNull - @Override - public Collection fun(ExtensionPointCandidate candidate) { - return Collections.singleton(candidate.pointer.getElement()); - } - }; + candidate -> Collections.singleton(candidate.pointer.getElement()); private static final NotNullFunction> RELATED_ITEM_PROVIDER = - new NotNullFunction>() { - @NotNull - @Override - public Collection fun(ExtensionPointCandidate candidate) { - return GotoRelatedItem.createItems(Collections.singleton(candidate.pointer.getElement()), "DevKit"); - } - }; + candidate -> GotoRelatedItem.createItems(Collections.singleton(candidate.pointer.getElement()), "DevKit"); @Override protected void collectNavigationMarkers(@NotNull PsiElement element, Collection result) { diff --git a/plugins/devkit/src/projectRoots/IdeaJdk.java b/plugins/devkit/src/projectRoots/IdeaJdk.java index d10dadbdfcef..106cf424c3a5 100644 --- a/plugins/devkit/src/projectRoots/IdeaJdk.java +++ b/plugins/devkit/src/projectRoots/IdeaJdk.java @@ -127,12 +127,10 @@ public class IdeaJdk extends JavaDependentSdkType implements JavaSdkType { public static boolean isFromIDEAProject(String path) { File home = new File(path); - File[] openapiDir = home.listFiles(new FileFilter() { - public boolean accept(File pathname) { - @NonNls final String name = pathname.getName(); - if (name.equals("openapi") && pathname.isDirectory()) return true; //todo - return false; - } + File[] openapiDir = home.listFiles(pathname -> { + @NonNls final String name = pathname.getName(); + if (name.equals("openapi") && pathname.isDirectory()) return true; //todo + return false; }); return openapiDir != null && openapiDir.length != 0; } @@ -343,13 +341,11 @@ public class IdeaJdk extends JavaDependentSdkType implements JavaSdkType { private static void addSources(File file, SdkModificator sdkModificator) { final File src = new File(new File(file, LIB_DIR_NAME), SRC_DIR_NAME); if (!src.exists()) return; - File[] srcs = src.listFiles(new FileFilter() { - public boolean accept(File pathname) { - @NonNls final String path = pathname.getPath(); - //noinspection SimplifiableIfStatement - if (path.contains("generics")) return false; - return path.endsWith(".jar") || path.endsWith(".zip"); - } + File[] srcs = src.listFiles(pathname -> { + @NonNls final String path = pathname.getPath(); + //noinspection SimplifiableIfStatement + if (path.contains("generics")) return false; + return path.endsWith(".jar") || path.endsWith(".zip"); }); for (int i = 0; srcs != null && i < srcs.length; i++) { File jarFile = srcs[i]; diff --git a/plugins/devkit/src/projectRoots/IdeaJdkConfigurable.java b/plugins/devkit/src/projectRoots/IdeaJdkConfigurable.java index 4dc93bb25eda..e9bb4688ade5 100644 --- a/plugins/devkit/src/projectRoots/IdeaJdkConfigurable.java +++ b/plugins/devkit/src/projectRoots/IdeaJdkConfigurable.java @@ -204,10 +204,8 @@ public class IdeaJdkConfigurable implements AdditionalDataConfigurable { Sandbox sandbox = new Sandbox(mySandboxHome.getText(), (Sdk)myInternalJres.getSelectedItem(), myIdeaJdk); final SdkModificator modificator = myIdeaJdk.getSdkModificator(); modificator.setSdkAdditionalData(sandbox); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - modificator.commitChanges(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + modificator.commitChanges(); }); ((ProjectJdkImpl) myIdeaJdk).resetVersionString(); myModified = false; diff --git a/plugins/devkit/src/references/IconsReferencesContributor.java b/plugins/devkit/src/references/IconsReferencesContributor.java index 404baad97bef..f294345822b8 100644 --- a/plugins/devkit/src/references/IconsReferencesContributor.java +++ b/plugins/devkit/src/references/IconsReferencesContributor.java @@ -310,34 +310,29 @@ public class IconsReferencesContributor extends PsiReferenceContributor model.setCaseSensitive(true); model.setFindAll(true); model.setWholeWordsOnly(true); - FindInProjectUtil.findUsages(model, project, new Processor() { - @Override - public boolean process(final UsageInfo usage) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final PsiElement element = usage.getElement(); + FindInProjectUtil.findUsages(model, project, usage -> { + ApplicationManager.getApplication().runReadAction(() -> { + final PsiElement element = usage.getElement(); - final ProperTextRange textRange = usage.getRangeInElement(); - if (element != null && textRange != null) { - final PsiElement start = element.findElementAt(textRange.getStartOffset()); - final PsiElement end = element.findElementAt(textRange.getEndOffset()); - if (start != null && end != null) { - PsiElement value = PsiTreeUtil.findCommonParent(start, end); - if (value instanceof PsiJavaToken) { - value = value.getParent(); - } - if (value != null) { - final PsiFileReference reference = FileReferenceUtil.findFileReference(value); - if (reference != null) { - consumer.process(reference); - } - } + final ProperTextRange textRange = usage.getRangeInElement(); + if (element != null && textRange != null) { + final PsiElement start = element.findElementAt(textRange.getStartOffset()); + final PsiElement end = element.findElementAt(textRange.getEndOffset()); + if (start != null && end != null) { + PsiElement value = PsiTreeUtil.findCommonParent(start, end); + if (value instanceof PsiJavaToken) { + value = value.getParent(); + } + if (value != null) { + final PsiFileReference reference = FileReferenceUtil.findFileReference(value); + if (reference != null) { + consumer.process(reference); } } } - }); - return true; - } + } + }); + return true; }, new FindUsagesProcessPresentation(new UsageViewPresentation())); } } diff --git a/plugins/devkit/src/testAssistant/TestCaseAsRelatedFileProvider.java b/plugins/devkit/src/testAssistant/TestCaseAsRelatedFileProvider.java index bbe3e54899f7..3a942822c9eb 100644 --- a/plugins/devkit/src/testAssistant/TestCaseAsRelatedFileProvider.java +++ b/plugins/devkit/src/testAssistant/TestCaseAsRelatedFileProvider.java @@ -46,11 +46,8 @@ public class TestCaseAsRelatedFileProvider extends GotoRelatedProvider { return Collections.emptyList(); } - return ContainerUtil.map(locations, new Function() { - @Override - public GotoRelatedItem fun(Location location) { - return new GotoRelatedItem(location.getPsiElement()); - } + return ContainerUtil.map(locations, location -> { + return new GotoRelatedItem(location.getPsiElement()); }); } } diff --git a/plugins/devkit/src/testAssistant/TestDataNavigationHandler.java b/plugins/devkit/src/testAssistant/TestDataNavigationHandler.java index 63f2ae20e208..e18ae870ae65 100644 --- a/plugins/devkit/src/testAssistant/TestDataNavigationHandler.java +++ b/plugins/devkit/src/testAssistant/TestDataNavigationHandler.java @@ -132,16 +132,14 @@ public class TestDataNavigationHandler implements GutterIconNavigationHandler= 0) { - createMissingFiles(project, fileNames); - } - else { - for (int index : indices) { - openFileByIndex(project, fileNames, index); - } + builder.setItemChoosenCallback(() -> { + final int[] indices = list.getSelectedIndices(); + if (ArrayUtil.indexOf(indices, fileNames.size()) >= 0) { + createMissingFiles(project, fileNames); + } + else { + for (int index : indices) { + openFileByIndex(project, fileNames, index); } } }).createPopup().show(point); diff --git a/plugins/devkit/src/testAssistant/TestLocationDataRule.java b/plugins/devkit/src/testAssistant/TestLocationDataRule.java index 74c9d34c5a96..fe626ae3cb79 100644 --- a/plugins/devkit/src/testAssistant/TestLocationDataRule.java +++ b/plugins/devkit/src/testAssistant/TestLocationDataRule.java @@ -72,12 +72,7 @@ public class TestLocationDataRule implements GetDataRule { final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(project); final List words = StringUtil.getWordsIn(relativePath); // put longer strings first - Collections.sort(words, new Comparator() { - @Override - public int compare(final String o1, final String o2) { - return o2.length() - o1.length(); - } - }); + Collections.sort(words, (o1, o2) -> o2.length() - o1.length()); final GlobalSearchScope testScope = GlobalSearchScopesCore.projectTestScope(project); Set resultFiles = null; diff --git a/plugins/devkit/testSources/codeInsight/CreateClassFixTest.java b/plugins/devkit/testSources/codeInsight/CreateClassFixTest.java index d74b28814d7b..f2c608cbb85b 100644 --- a/plugins/devkit/testSources/codeInsight/CreateClassFixTest.java +++ b/plugins/devkit/testSources/codeInsight/CreateClassFixTest.java @@ -84,16 +84,14 @@ public class CreateClassFixTest extends UsefulTestCase{ @After public void tearDown() throws Exception { final Ref ex = new Ref(); - Runnable runnable = new Runnable() { - public void run() { - try { - myFixture.tearDown(); - myFixture = null; - CreateClassFixTest.super.tearDown(); - } - catch (Exception e) { - ex.set(e); - } + Runnable runnable = () -> { + try { + myFixture.tearDown(); + myFixture = null; + CreateClassFixTest.super.tearDown(); + } + catch (Exception e) { + ex.set(e); } }; invokeTestRunnable(runnable); @@ -118,22 +116,20 @@ public class CreateClassFixTest extends UsefulTestCase{ @Test public void runSingle() throws Throwable { - Runnable runnable = new Runnable() { - public void run() { - IntentionAction resultAction = null; - final String createAction = QuickFixBundle.message(myCreateClass ? "create.class.text" : "create.interface.text", myTestName); - final List actions = myFixture.getAvailableIntentions(getSourceRoot() + "/plugin" + myTestName + ".xml"); - for (IntentionAction action : actions) { - if (Comparing.strEqual(action.getText(), createAction)) { - resultAction = action; - break; - } + Runnable runnable = () -> { + IntentionAction resultAction = null; + final String createAction = QuickFixBundle.message(myCreateClass ? "create.class.text" : "create.interface.text", myTestName); + final List actions = myFixture.getAvailableIntentions(getSourceRoot() + "/plugin" + myTestName + ".xml"); + for (IntentionAction action : actions) { + if (Comparing.strEqual(action.getText(), createAction)) { + resultAction = action; + break; } - Assert.assertNotNull(resultAction); - myFixture.launchAction(resultAction); - final Project project = myFixture.getProject(); - Assert.assertNotNull(JavaPsiFacade.getInstance(project).findClass(myTestName, GlobalSearchScope.allScope(project))); } + Assert.assertNotNull(resultAction); + myFixture.launchAction(resultAction); + final Project project = myFixture.getProject(); + Assert.assertNotNull(JavaPsiFacade.getInstance(project).findClass(myTestName, GlobalSearchScope.allScope(project))); }; invokeTestRunnable(runnable); } diff --git a/plugins/devkit/testSources/navigation/DevKitGutterTargetsChecker.java b/plugins/devkit/testSources/navigation/DevKitGutterTargetsChecker.java index 4d60ad4a36be..dbb173be14c5 100644 --- a/plugins/devkit/testSources/navigation/DevKitGutterTargetsChecker.java +++ b/plugins/devkit/testSources/navigation/DevKitGutterTargetsChecker.java @@ -59,11 +59,8 @@ public class DevKitGutterTargetsChecker { throw new IllegalArgumentException(gutterMark.getClass() + ": gutter not supported"); } - UsefulTestCase.assertSameElements(ContainerUtil.map(targetElements, new Function() { - @Override - public String fun(PsiElement element) { - return SymbolPresentationUtil.getSymbolPresentableText(element); - } + UsefulTestCase.assertSameElements(ContainerUtil.map(targetElements, element -> { + return SymbolPresentationUtil.getSymbolPresentableText(element); }), expectedTargets); } } diff --git a/plugins/eclipse/src/org/jdom/output/EclipseXMLOutputter.java b/plugins/eclipse/src/org/jdom/output/EclipseXMLOutputter.java index be141be27cc3..aaeaf5f7b788 100644 --- a/plugins/eclipse/src/org/jdom/output/EclipseXMLOutputter.java +++ b/plugins/eclipse/src/org/jdom/output/EclipseXMLOutputter.java @@ -1117,11 +1117,7 @@ public class EclipseXMLOutputter implements Cloneable { for (Object attribute : attributes) { atts.add((Attribute)((Attribute)attribute).clone()); } - Collections.sort(atts, new Comparator() { - public int compare(Attribute o1, Attribute o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(atts, (o1, o2) -> o1.getName().compareTo(o2.getName())); for (int i = 0; i < atts.size(); i++) { Attribute attribute = (Attribute) atts.get(i); Namespace ns = attribute.getNamespace(); diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/DotProjectFileHelper.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/DotProjectFileHelper.java index 8546e59d09da..1b95eb5ae8e6 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/DotProjectFileHelper.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/DotProjectFileHelper.java @@ -61,10 +61,8 @@ public class DotProjectFileHelper { } EclipseJDOMUtil.output(doc.getRootElement(), projectFile, module.getProject()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(projectFile.getPath())); - } + ApplicationManager.getApplication().runWriteAction(() -> { + LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(projectFile.getPath())); }); } catch (JDOMException e) { diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EJavadocUtil.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EJavadocUtil.java index e48f8943bdd9..e73ef90d8491 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EJavadocUtil.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EJavadocUtil.java @@ -203,12 +203,7 @@ public class EJavadocUtil { } static void setupJavadocAttributes(Element orderEntry, LibraryOrderEntry libraryOrderEntry, final ModuleRootModel model) { - setupAttributes(orderEntry, new Function() { - @Override - public String fun(String s) { - return toEclipseJavadocPath(model, s); - } - }, JAVADOC_LOCATION, libraryOrderEntry.getRootUrls(JavadocOrderRootType.getInstance())); + setupAttributes(orderEntry, s -> toEclipseJavadocPath(model, s), JAVADOC_LOCATION, libraryOrderEntry.getRootUrls(JavadocOrderRootType.getInstance())); } static void setupAttributes(Element orderEntry, diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseClasspathWriter.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseClasspathWriter.java index 5111b7a6c6b7..7f16e44a80a6 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseClasspathWriter.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseClasspathWriter.java @@ -193,12 +193,7 @@ public class EclipseClasspathWriter { final String[] nativeRoots = libraryOrderEntry.getUrls(NativeLibraryOrderRootType.getInstance()); if (nativeRoots.length > 0) { - EJavadocUtil.setupAttributes(orderEntry, new Function() { - @Override - public String fun(String nativeRoot) { - return EPathUtil.collapse2EclipsePath(nativeRoot, model); - } - }, EclipseXml.DLL_LINK, nativeRoots); + EJavadocUtil.setupAttributes(orderEntry, nativeRoot -> EPathUtil.collapse2EclipsePath(nativeRoot, model), EclipseXml.DLL_LINK, nativeRoots); } setExported(orderEntry, libraryOrderEntry); } diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/export/ExportEclipseProjectsAction.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/export/ExportEclipseProjectsAction.java index d0369ed89cae..b8f60d291679 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/export/ExportEclipseProjectsAction.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/export/ExportEclipseProjectsAction.java @@ -96,11 +96,8 @@ public class ExportEclipseProjectsAction extends AnAction implements DumbAware { } } else if (Messages.showOkCancelDialog(project, "Eclipse incompatible modules found:

      • " + - StringUtil.join(incompatibleModules, new Function() { - @Override - public String fun(Module module) { - return module.getName(); - } + StringUtil.join(incompatibleModules, module -> { + return module.getName(); }, "
      • ") + "

      Would you like to proceed and possibly lose your configurations?", EclipseBundle.message("eclipse.export.dialog.title"), Messages.getWarningIcon()) != Messages.OK) { diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java index 86a9237efd37..32bc2562c34e 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java @@ -111,24 +111,18 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement ProgressManager.getInstance().run(new Task.Modal(getCurrentProject(), EclipseBundle.message("eclipse.import.scanning"), true) { public void run(@NotNull ProgressIndicator indicator) { final ArrayList roots = new ArrayList(); - EclipseProjectFinder.findModuleRoots(roots, path, new Processor() { - @Override - public boolean process(String path) { - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - if (progressIndicator != null) { - if (progressIndicator.isCanceled()) return false; - progressIndicator.setText2(path); - } - return true; + EclipseProjectFinder.findModuleRoots(roots, path, path12 -> { + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + if (progressIndicator != null) { + if (progressIndicator.isCanceled()) return false; + progressIndicator.setText2(path12); } + return true; }); - Collections.sort(roots, new Comparator() { - @Override - public int compare(String path1, String path2) { - final String projectName1 = EclipseProjectFinder.findProjectName(path1); - final String projectName2 = EclipseProjectFinder.findProjectName(path2); - return projectName1 != null && projectName2 != null ? projectName1.compareToIgnoreCase(projectName2) : 0; - } + Collections.sort(roots, (path1, path2) -> { + final String projectName1 = EclipseProjectFinder.findProjectName(path1); + final String projectName2 = EclipseProjectFinder.findProjectName(path2); + return projectName1 != null && projectName2 != null ? projectName1.compareToIgnoreCase(projectName2) : 0; }); getParameters().workspace = roots; getParameters().root = path; @@ -179,23 +173,21 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement final List projectsToConvert = getParameters().projectsToConvert; final boolean oneProjectToConvert = projectsToConvert.size() == 1; final String separator = oneProjectToConvert ? "
      " : ", "; - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - try { - for (String path : projectsToConvert) { - File classPathFile = new File(path, EclipseXml.DOT_CLASSPATH_EXT); - if (classPathFile.exists()) { - EclipseClasspathReader.collectVariables(variables, JDOMUtil.load(classPathFile), path); - } - collectUnknownNatures(path, naturesNames, separator); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + try { + for (String path : projectsToConvert) { + File classPathFile = new File(path, EclipseXml.DOT_CLASSPATH_EXT); + if (classPathFile.exists()) { + EclipseClasspathReader.collectVariables(variables, JDOMUtil.load(classPathFile), path); } + collectUnknownNatures(path, naturesNames, separator); } - catch (IOException e) { - refEx.set(e); - } - catch (JDOMException e) { - refEx.set(e); - } + } + catch (IOException e) { + refEx.set(e); + } + catch (JDOMException e) { + refEx.set(e); } }, EclipseBundle.message("eclipse.import.converting"), false, currentProject); @@ -215,12 +207,7 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement naturesByProject = naturesNames.values().iterator().next(); } else { - naturesByProject = StringUtil.join(naturesNames.keySet(), new Function() { - @Override - public String fun(String projectPath) { - return projectPath + "(" + naturesNames.get(projectPath) + ")"; - } - }, "
      "); + naturesByProject = StringUtil.join(naturesNames.keySet(), projectPath -> projectPath + "(" + naturesNames.get(projectPath) + ")", "
      "); } Notifications.Bus.notify(new Notification(title, title, "Imported projects contain unknown natures:
      " + naturesByProject + "
      " + "Some settings may be lost after import.", NotificationType.WARNING)); @@ -262,13 +249,11 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement } if (!files.isEmpty()) { final int resultCode = Messages.showYesNoCancelDialog(ApplicationNamesInfo.getInstance().getFullProductName() + - " module files found:\n" + - StringUtil.join(files,new Function() { - public String fun(File file) { - return file.getPath(); - } + " module files found:\n" + + StringUtil.join(files, file -> { + return file.getPath(); }, "\n") + - ".\n Would you like to reuse them?", "Module Files Found", + ".\n Would you like to reuse them?", "Module Files Found", Messages.getQuestionIcon()); if (resultCode != Messages.YES) { if (resultCode == Messages.NO) { @@ -324,18 +309,14 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement ClasspathStorage.setStorageType(rootModel, getParameters().linkConverted ? JpsEclipseClasspathSerializer.CLASSPATH_STORAGE_ID : ClassPathStorageUtil.DEFAULT_STORAGE); if (model != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - rootModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + rootModel.commit(); }); } } if (model == null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ModifiableModelCommitter.multiCommit(rootModels, moduleModel); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ModifiableModelCommitter.multiCommit(rootModels, moduleModel); }); } } @@ -413,33 +394,25 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement if (module2NatureNames.size() == 0) { return; } - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - @Override - public void run() { - DumbService.getInstance(project).smartInvokeLater(new Runnable() { - @Override - public void run() { - for (EclipseNatureImporter importer : EclipseNatureImporter.EP_NAME.getExtensions()) { - final String importerNatureName = importer.getNatureName(); - final List modulesToImport = new ArrayList(); + StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> DumbService.getInstance(project).smartInvokeLater(() -> { + for (EclipseNatureImporter importer : EclipseNatureImporter.EP_NAME.getExtensions()) { + final String importerNatureName = importer.getNatureName(); + final List modulesToImport = new ArrayList(); - for (Map.Entry> entry : module2NatureNames.entrySet()) { - final Module module = entry.getKey(); - final Set natureNames = entry.getValue(); + for (Map.Entry> entry : module2NatureNames.entrySet()) { + final Module module = entry.getKey(); + final Set natureNames = entry.getValue(); - if (natureNames.contains(importerNatureName)) { - modulesToImport.add(module); - } - } - - if (modulesToImport.size() > 0) { - importer.doImport(project, modulesToImport); - } - } + if (natureNames.contains(importerNatureName)) { + modulesToImport.add(module); } - }); + } + + if (modulesToImport.size() > 0) { + importer.doImport(project, modulesToImport); + } } - }); + })); } private static void createEclipseLibrary(final Project project, final Collection libraries, final String libraryName) { @@ -460,18 +433,16 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement if (file != null) { final VirtualFile pluginsDir = file.findChild("plugins"); if (pluginsDir != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final LibraryTable table = - LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(LibraryTablesRegistrar.APPLICATION_LEVEL, project); - assert table != null; - final LibraryTable.ModifiableModel tableModel = table.getModifiableModel(); - final Library library = tableModel.createLibrary(libraryName); - final Library.ModifiableModel libraryModel = library.getModifiableModel(); - libraryModel.addJarDirectory(pluginsDir, true); - libraryModel.commit(); - tableModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final LibraryTable table = + LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(LibraryTablesRegistrar.APPLICATION_LEVEL, project); + assert table != null; + final LibraryTable.ModifiableModel tableModel = table.getModifiableModel(); + final Library library = tableModel.createLibrary(libraryName); + final Library.ModifiableModel libraryModel = library.getModifiableModel(); + libraryModel.addJarDirectory(pluginsDir, true); + libraryModel.commit(); + tableModel.commit(); }); libraries.remove(libraryName); } diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/importer/EclipseCodeStyleSchemeImporter.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/importer/EclipseCodeStyleSchemeImporter.java index 380c80e7c3eb..201c0b97fddf 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/importer/EclipseCodeStyleSchemeImporter.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/importer/EclipseCodeStyleSchemeImporter.java @@ -53,12 +53,7 @@ public class EclipseCodeStyleSchemeImporter implements SchemeImporter importPair = ImportSchemeChooserDialog.selectOrCreateTargetScheme(project, currentScheme, schemeFactory, readSchemeNames(selectedFile)); if (importPair != null) { - readFromStream(selectedFile, new ThrowableConsumer() { - @Override - public void consume(InputStream stream) throws SchemeImportException { - new EclipseCodeStyleImportWorker().importScheme(stream, importPair.first, importPair.second); - } - }); + readFromStream(selectedFile, stream -> new EclipseCodeStyleImportWorker().importScheme(stream, importPair.first, importPair.second)); return importPair.second; } return null; @@ -90,12 +85,7 @@ public class EclipseCodeStyleSchemeImporter implements SchemeImporter() { - @Override - public void consume(InputStream stream) throws SchemeImportException { - reader.readSettings(stream); - } - }); + readFromStream(selectedFile, stream -> reader.readSettings(stream)); return ArrayUtil.toStringArray(names); } diff --git a/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseClasspathTest.java b/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseClasspathTest.java index 05f211ca32fa..b5735e6c6852 100644 --- a/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseClasspathTest.java +++ b/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseClasspathTest.java @@ -90,18 +90,15 @@ public class EclipseClasspathTest extends IdeaTestCase { } }); - ModuleRootModificationUtil.updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - try { - EclipseClasspathReader classpathReader = new EclipseClasspathReader(path, project, null); - classpathReader.init(model); - classpathReader.readClasspath(model, classpathElement); - new EclipseClasspathStorageProvider().assertCompatible(model); - } - catch (Exception e) { - throw new RuntimeException(e); - } + ModuleRootModificationUtil.updateModel(module, model -> { + try { + EclipseClasspathReader classpathReader = new EclipseClasspathReader(path, project, null); + classpathReader.init(model); + classpathReader.readClasspath(model, classpathElement); + new EclipseClasspathStorageProvider().assertCompatible(model); + } + catch (Exception e) { + throw new RuntimeException(e); } }); return module; diff --git a/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseLibrariesModificationsTest.java b/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseLibrariesModificationsTest.java index d7972ddbb3fc..950625849677 100644 --- a/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseLibrariesModificationsTest.java +++ b/plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseLibrariesModificationsTest.java @@ -150,38 +150,36 @@ public class EclipseLibrariesModificationsTest extends EclipseVarsTest { final Project project = getProject(); final String path = project.getBaseDir().getPath() + "/test"; final Module module = EclipseClasspathTest.setUpModule(path, project); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); - final String parentUrl = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, model.getContentRoots()[0].getParent().getPath()); - final Library library = model.getModuleLibraryTable().getLibraryByName("test.jar"); - final Library.ModifiableModel libModifiableModel = library.getModifiableModel(); - final String[] oldClsRoots = libModifiableModel.getUrls(OrderRootType.CLASSES); - for (String oldClsRoot : oldClsRoots) { - libModifiableModel.removeRoot(oldClsRoot, OrderRootType.CLASSES); - } - - final String[] oldSrcRoots = libModifiableModel.getUrls(OrderRootType.SOURCES); - for (String oldSrcRoot : oldSrcRoots) { - libModifiableModel.removeRoot(oldSrcRoot, OrderRootType.SOURCES); - } - - final String[] oldJdcRoots = libModifiableModel.getUrls(JavadocOrderRootType.getInstance()); - for (String oldJavadocRoot : oldJdcRoots) { - libModifiableModel.removeRoot(oldJavadocRoot, JavadocOrderRootType.getInstance()); - } - for (String classRoot : classRoots) { - libModifiableModel.addRoot(parentUrl + classRoot, OrderRootType.CLASSES); - } - for (String sourceRoot : sourceRoots) { - libModifiableModel.addRoot(parentUrl + sourceRoot, OrderRootType.SOURCES); - } - for (String javadocRoot : javadocs) { - libModifiableModel.addRoot(parentUrl + javadocRoot, JavadocOrderRootType.getInstance()); - } - libModifiableModel.commit(); - model.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); + final String parentUrl = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, model.getContentRoots()[0].getParent().getPath()); + final Library library = model.getModuleLibraryTable().getLibraryByName("test.jar"); + final Library.ModifiableModel libModifiableModel = library.getModifiableModel(); + final String[] oldClsRoots = libModifiableModel.getUrls(OrderRootType.CLASSES); + for (String oldClsRoot : oldClsRoots) { + libModifiableModel.removeRoot(oldClsRoot, OrderRootType.CLASSES); } + + final String[] oldSrcRoots = libModifiableModel.getUrls(OrderRootType.SOURCES); + for (String oldSrcRoot : oldSrcRoots) { + libModifiableModel.removeRoot(oldSrcRoot, OrderRootType.SOURCES); + } + + final String[] oldJdcRoots = libModifiableModel.getUrls(JavadocOrderRootType.getInstance()); + for (String oldJavadocRoot : oldJdcRoots) { + libModifiableModel.removeRoot(oldJavadocRoot, JavadocOrderRootType.getInstance()); + } + for (String classRoot : classRoots) { + libModifiableModel.addRoot(parentUrl + classRoot, OrderRootType.CLASSES); + } + for (String sourceRoot : sourceRoots) { + libModifiableModel.addRoot(parentUrl + sourceRoot, OrderRootType.SOURCES); + } + for (String javadocRoot : javadocs) { + libModifiableModel.addRoot(parentUrl + javadocRoot, JavadocOrderRootType.getInstance()); + } + libModifiableModel.commit(); + model.commit(); }); EclipseClasspathTest.checkModule(project.getBaseDir().getPath() + "/expected", module); diff --git a/plugins/editorconfig/src/org/editorconfig/configmanagement/LineEndingsManager.java b/plugins/editorconfig/src/org/editorconfig/configmanagement/LineEndingsManager.java index 0cfd3d6e9b36..eb2cfea56b6a 100644 --- a/plugins/editorconfig/src/org/editorconfig/configmanagement/LineEndingsManager.java +++ b/plugins/editorconfig/src/org/editorconfig/configmanagement/LineEndingsManager.java @@ -44,18 +44,15 @@ public class LineEndingsManager extends FileDocumentManagerAdapter { } private void updateStatusBar() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - IdeFrame frame = WindowManager.getInstance().getIdeFrame(myProject); - StatusBar statusBar = frame != null ? frame.getStatusBar() : null; - StatusBarWidget widget = statusBar != null ? statusBar.getWidget("LineSeparator") : null; + ApplicationManager.getApplication().invokeLater(() -> { + IdeFrame frame = WindowManager.getInstance().getIdeFrame(myProject); + StatusBar statusBar = frame != null ? frame.getStatusBar() : null; + StatusBarWidget widget = statusBar != null ? statusBar.getWidget("LineSeparator") : null; - if (widget instanceof LineSeparatorPanel) { - FileEditorManagerEvent event = new FileEditorManagerEvent(FileEditorManager.getInstance(myProject), - null, null, null, null); - ((LineSeparatorPanel)widget).selectionChanged(event); - } + if (widget instanceof LineSeparatorPanel) { + FileEditorManagerEvent event = new FileEditorManagerEvent(FileEditorManager.getInstance(myProject), + null, null, null, null); + ((LineSeparatorPanel)widget).selectionChanged(event); } }); } diff --git a/plugins/editorconfig/src/org/editorconfig/plugincomponents/EditorConfigNotifierProvider.java b/plugins/editorconfig/src/org/editorconfig/plugincomponents/EditorConfigNotifierProvider.java index 3ee8c64e6728..ea0e05d9f7f0 100644 --- a/plugins/editorconfig/src/org/editorconfig/plugincomponents/EditorConfigNotifierProvider.java +++ b/plugins/editorconfig/src/org/editorconfig/plugincomponents/EditorConfigNotifierProvider.java @@ -50,19 +50,13 @@ public class EditorConfigNotifierProvider extends EditorNotifications.Provider { + PropertiesComponent.getInstance(project).setValue(EDITOR_CONFIG_ACCEPTED, true); + EditorNotifications.getInstance(project).updateAllNotifications(); }); - panel.createActionLabel("Disable EditorConfig support", new Runnable() { - @Override - public void run() { - settings.getCustomSettings(EditorConfigSettings.class).ENABLED = false; - EditorNotifications.getInstance(project).updateAllNotifications(); - } + panel.createActionLabel("Disable EditorConfig support", () -> { + settings.getCustomSettings(EditorConfigSettings.class).ENABLED = false; + EditorNotifications.getInstance(project).updateAllNotifications(); }); return panel; } diff --git a/plugins/generate-tostring/src/org/jetbrains/java/generate/GenerateToStringActionHandlerImpl.java b/plugins/generate-tostring/src/org/jetbrains/java/generate/GenerateToStringActionHandlerImpl.java index e412314e21df..111ae7b8ce6d 100644 --- a/plugins/generate-tostring/src/org/jetbrains/java/generate/GenerateToStringActionHandlerImpl.java +++ b/plugins/generate-tostring/src/org/jetbrains/java/generate/GenerateToStringActionHandlerImpl.java @@ -237,10 +237,8 @@ public class GenerateToStringActionHandlerImpl implements GenerateToStringAction } }; - ShowSettingsUtil.getInstance().editConfigurable(MemberChooserHeaderPanel.this, composite, new Runnable() { - public void run() { - ui.selectItem(ToStringTemplatesManager.getInstance().getDefaultTemplate()); - } + ShowSettingsUtil.getInstance().editConfigurable(MemberChooserHeaderPanel.this, composite, () -> { + ui.selectItem(ToStringTemplatesManager.getInstance().getDefaultTemplate()); }); Disposer.dispose(disposable); } diff --git a/plugins/generate-tostring/src/org/jetbrains/java/generate/template/TemplatesManager.java b/plugins/generate-tostring/src/org/jetbrains/java/generate/template/TemplatesManager.java index bea9456020a1..745d06281681 100644 --- a/plugins/generate-tostring/src/org/jetbrains/java/generate/template/TemplatesManager.java +++ b/plugins/generate-tostring/src/org/jetbrains/java/generate/template/TemplatesManager.java @@ -127,16 +127,13 @@ public abstract class TemplatesManager implements PersistentStateComponent elementClass) { final List methodNames = ContainerUtil.mapNotNull(elementClass.getMethods(), - new Function() { - @Override - public String fun(Method method) { - final String methodName = method.getName(); - if (methodName.startsWith("set")) { - //hide setters from completion list - return null; - } - return method.getGenericReturnType().toString() + " " + methodName + "();"; + method -> { + final String methodName = method.getName(); + if (methodName.startsWith("set")) { + //hide setters from completion list + return null; } + return method.getGenericReturnType().toString() + " " + methodName + "();"; }); final String text = "interface " + elementClass.getSimpleName() + " {\n" + StringUtil.join(methodNames, "\n") + "}"; final PsiClass aClass = JavaPsiFacade.getElementFactory(project).createClassFromText(text, null).getInnerClasses()[0]; diff --git a/plugins/generate-tostring/testSrc/org/jetbrains/java/generate/test/DummyModelTestBean.java b/plugins/generate-tostring/testSrc/org/jetbrains/java/generate/test/DummyModelTestBean.java index 89833fe34ceb..564d25612dea 100644 --- a/plugins/generate-tostring/testSrc/org/jetbrains/java/generate/test/DummyModelTestBean.java +++ b/plugins/generate-tostring/testSrc/org/jetbrains/java/generate/test/DummyModelTestBean.java @@ -60,11 +60,7 @@ public abstract class DummyModelTestBean { public void nonGetterMethod() { List list = new ArrayList(); - Collections.sort(list, new Comparator() { - public int compare(Object o, Object o1) { - return 0; - } - }); + Collections.sort(list, (o, o1) -> 0); } public boolean isMyMethod() { diff --git a/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitChooseAccountStepImpl.java b/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitChooseAccountStepImpl.java index 897e29967c33..303f9f97f37f 100644 --- a/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitChooseAccountStepImpl.java +++ b/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitChooseAccountStepImpl.java @@ -116,13 +116,7 @@ public class CloudGitChooseAccountStepImpl extends CloudGitChooseAccountStepBase @Override public void moduleAdded(@NotNull Project project, @NotNull Module addedModule) { if (addedModule == module) { - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - - @Override - public void run() { - onModuleAdded(module); - } - }); + StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> onModuleAdded(module)); connection.disconnect(); } } diff --git a/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitRemoteDetector.java b/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitRemoteDetector.java index f5bc8f14b510..87ba118a562f 100644 --- a/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitRemoteDetector.java +++ b/plugins/git4idea/remote-servers-git-java/src/com/intellij/remoteServer/util/importProject/CloudGitRemoteDetector.java @@ -247,12 +247,7 @@ public class CloudGitRemoteDetector extends AbstractProjectComponent implements if (targetModule == null) { AddModuleWizard wizard = new AddModuleWizard(myProject, myRepositoryRoot.getPath(), new ImportFromSourcesProvider()); - wizard.navigateToStep(new Function() { - @Override - public Boolean fun(Step step) { - return step instanceof RootsDetectionStep; - } - }); + wizard.navigateToStep(step -> step instanceof RootsDetectionStep); if (wizard.getStepCount() > 0 && !wizard.showAndGet()) { return; } diff --git a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentChecker.java b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentChecker.java index ed0bf6809113..3ad65d327554 100644 --- a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentChecker.java +++ b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentChecker.java @@ -88,28 +88,24 @@ public class CloudGitDeploymentChecker< RuntimeConfigurationWarning warning = new RuntimeConfigurationWarning("Cloud Git URL found in repository, but it doesn't match the run configuration"); - warning.setQuickFix(new Runnable() { + warning.setQuickFix(() -> { + CloudGitApplication application + = new CloudConnectionTask(project, "Searching for application", server) { - @Override - public void run() { - CloudGitApplication application - = new CloudConnectionTask(project, "Searching for application", server) { - - @Override - protected CloudGitApplication run(SR serverRuntime) throws ServerRuntimeException { - CloudGitDeploymentRuntime deploymentRuntime - = (CloudGitDeploymentRuntime)serverRuntime.createDeploymentRuntime(deploymentSource, settings, project); - return deploymentRuntime.findApplication4Repository(); - } - }.performSync(); - - if (application == null) { - Messages.showErrorDialog(project, "No application matching repository URL(s) found in account", server.getName()); - } - else { - settings.setDefaultDeploymentName(false); - settings.setDeploymentName(application.getName()); + @Override + protected CloudGitApplication run(SR serverRuntime) throws ServerRuntimeException { + CloudGitDeploymentRuntime deploymentRuntime + = (CloudGitDeploymentRuntime)serverRuntime.createDeploymentRuntime(deploymentSource, settings, project); + return deploymentRuntime.findApplication4Repository(); } + }.performSync(); + + if (application == null) { + Messages.showErrorDialog(project, "No application matching repository URL(s) found in account", server.getName()); + } + else { + settings.setDefaultDeploymentName(false); + settings.setDeploymentName(application.getName()); } }); diff --git a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java index eabb0aeaa2ea..0011bde99d96 100644 --- a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java +++ b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java @@ -253,13 +253,7 @@ public class CloudGitDeploymentRuntime extends CloudDeploymentRuntime { private static T runOnEdt(final Computable computable) { final Ref result = new Ref(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - - @Override - public void run() { - result.set(computable.compute()); - } - }, ModalityState.any()); + ApplicationManager.getApplication().invokeAndWait(() -> result.set(computable.compute()), ModalityState.any()); return result.get(); } @@ -474,13 +468,7 @@ public class CloudGitDeploymentRuntime extends CloudDeploymentRuntime { } protected void refreshContentRoot() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - - @Override - public void run() { - getRepositoryRoot().refresh(false, true); - } - }); + ApplicationManager.getApplication().invokeLater(() -> getRepositoryRoot().refresh(false, true)); } public void fetchAndRefresh() throws ServerRuntimeException { diff --git a/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java b/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java index 0d1dbd276ba2..556a77b17680 100644 --- a/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java +++ b/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java @@ -157,30 +157,18 @@ public class AppEngineUploader { } private void compileAndUpload() { - final Runnable startUploading = new Runnable() { - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - startUploadingProcess(); - } - }); - } - }; + final Runnable startUploading = () -> ApplicationManager.getApplication().invokeLater(() -> startUploadingProcess()); final CompilerManager compilerManager = CompilerManager.getInstance(myProject); final CompileScope moduleScope = compilerManager.createModuleCompileScope(myAppEngineFacet.getModule(), true); final CompileScope compileScope = ArtifactCompileScope.createScopeWithArtifacts(moduleScope, Collections.singletonList(myArtifact)); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - compilerManager.make(compileScope, new CompileStatusNotification() { - public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) { - if (!aborted && errors == 0) { - startUploading.run(); - } - } - }); + ApplicationManager.getApplication().invokeLater(() -> compilerManager.make(compileScope, new CompileStatusNotification() { + public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) { + if (!aborted && errors == 0) { + startUploading.run(); + } } - }); + })); } private void startUploadingProcess() { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrModifierFix.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrModifierFix.java index c3ec46d00329..d3849d142f50 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrModifierFix.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrModifierFix.java @@ -29,22 +29,16 @@ import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; * @author Max Medvedev */ public class GrModifierFix extends GroovyFix { - public static final Function MODIFIER_LIST = new Function() { - @Override - public PsiModifierList fun(ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - assert element instanceof PsiModifierList : element; - return (PsiModifierList)element; - } + public static final Function MODIFIER_LIST = descriptor -> { + final PsiElement element = descriptor.getPsiElement(); + assert element instanceof PsiModifierList : element; + return (PsiModifierList)element; }; - public static final Function MODIFIER_LIST_OWNER = new Function() { - @Override - public PsiModifierList fun(ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - assert element instanceof PsiModifierListOwner : element; - return ((PsiModifierListOwner)element).getModifierList(); - } + public static final Function MODIFIER_LIST_OWNER = descriptor -> { + final PsiElement element = descriptor.getPsiElement(); + assert element instanceof PsiModifierListOwner : element; + return ((PsiModifierListOwner)element).getModifierList(); }; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/confusing/ClashingTraitMethodsInspectionBase.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/confusing/ClashingTraitMethodsInspectionBase.java index 4195dd9a11ae..4c5c46781dcf 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/confusing/ClashingTraitMethodsInspectionBase.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/confusing/ClashingTraitMethodsInspectionBase.java @@ -116,11 +116,8 @@ public abstract class ClashingTraitMethodsInspectionBase extends BaseInspection @NotNull private String buildTraitString(@NotNull ClashingMethod entry) { - return StringUtil.join(entry.getSuperTraits(), new Function() { - @Override - public String fun(GrTypeDefinition tr) { - return tr.getName(); - } + return StringUtil.join(entry.getSuperTraits(), tr -> { + return tr.getName(); }, ", "); } }; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/dataflow/GroovyVariableCanBeFinalInspection.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/dataflow/GroovyVariableCanBeFinalInspection.java index 32219454b54c..31da91f630ae 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/dataflow/GroovyVariableCanBeFinalInspection.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/dataflow/GroovyVariableCanBeFinalInspection.java @@ -44,13 +44,10 @@ import java.util.List; public class GroovyVariableCanBeFinalInspection extends GroovyLocalInspectionBase { private static final Function ID_MODIFIER_LIST_PROVIDER = - new Function() { - @Override - public PsiModifierList fun(ProblemDescriptor descriptor) { - final PsiElement identifier = descriptor.getPsiElement(); - final PsiVariable variable = PsiTreeUtil.getParentOfType(identifier, PsiVariable.class); - return variable == null ? null : variable.getModifierList(); - } + descriptor -> { + final PsiElement identifier = descriptor.getPsiElement(); + final PsiVariable variable = PsiTreeUtil.getParentOfType(identifier, PsiVariable.class); + return variable == null ? null : variable.getModifierList(); }; private static void process(@NotNull GrControlFlowOwner owner, @NotNull GrVariable variable, @NotNull ProblemsHolder problemsHolder) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java index 53f0cc87f7d5..0f2fea1ff77a 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java @@ -67,14 +67,11 @@ public class GrMethodMayBeStaticInspection extends BaseInspection { @Override public void visitMethod(GrMethod method) { if (checkMethod(method)) { - final GrModifierFix modifierFix = new GrModifierFix(method, PsiModifier.STATIC, false, true, new Function() { - @Override - public PsiModifierList fun(ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElement parent = element.getParent(); - assert parent instanceof GrMethod : "element: " + element + ", parent:" + parent; - return ((GrMethod)parent).getModifierList(); - } + final GrModifierFix modifierFix = new GrModifierFix(method, PsiModifier.STATIC, false, true, descriptor -> { + final PsiElement element = descriptor.getPsiElement(); + final PsiElement parent = element.getParent(); + assert parent instanceof GrMethod : "element: " + element + ", parent:" + parent; + return ((GrMethod)parent).getModifierList(); }); registerError(method.getNameIdentifierGroovy(), message("method.may.be.static"), new LocalQuickFix[]{modifierFix}, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/GroovyTypeCheckVisitor.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/GroovyTypeCheckVisitor.java index 22b2d1b10f29..733395ddcaca 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/GroovyTypeCheckVisitor.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/GroovyTypeCheckVisitor.java @@ -919,11 +919,8 @@ public class GroovyTypeCheckVisitor extends BaseInspectionVisitor { GrParameter[] parameters = parameterList.getParameters(); if (parameters.length > 0) { List signatures = ClosureParamsEnhancer.findFittingSignatures((GrClosableBlock)parent); - final List paramTypes = ContainerUtil.map(parameters, new Function() { - @Override - public PsiType fun(GrParameter parameter) { - return parameter.getType(); - } + final List paramTypes = ContainerUtil.map(parameters, parameter -> { + return parameter.getType(); }); if (signatures.size() > 1) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java index 023d2681dceb..77ee5d7eb3ee 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java @@ -213,12 +213,8 @@ public class UnusedDefInspection extends GroovyLocalInspectionBase { } } - return ReferencesSearch.search(var, var.getUseScope()).forEach(new Processor() { - @Override - public boolean process(PsiReference ref) { - return ControlFlowUtils.findControlFlowOwner(ref.getElement()) == scope; - } - }); + return ReferencesSearch.search(var, var.getUseScope()).forEach( + ref -> ControlFlowUtils.findControlFlowOwner(ref.getElement()) == scope); } return true; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/utils/ControlFlowUtils.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/utils/ControlFlowUtils.java index 1f36c19d3da4..dec3a969f5c3 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/utils/ControlFlowUtils.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/utils/ControlFlowUtils.java @@ -517,23 +517,20 @@ public class ControlFlowUtils { } if (applicable.isEmpty()) return null; - Collections.sort(applicable, new Comparator() { - @Override - public int compare(Instruction o1, Instruction o2) { - PsiElement e1 = o1.getElement(); - PsiElement e2 = o2.getElement(); - LOG.assertTrue(e1 != null); - LOG.assertTrue(e2 != null); - final TextRange t1 = e1.getTextRange(); - final TextRange t2 = e2.getTextRange(); - final int s1 = t1.getStartOffset(); - final int s2 = t2.getStartOffset(); + Collections.sort(applicable, (o1, o2) -> { + PsiElement e1 = o1.getElement(); + PsiElement e2 = o2.getElement(); + LOG.assertTrue(e1 != null); + LOG.assertTrue(e2 != null); + final TextRange t1 = e1.getTextRange(); + final TextRange t2 = e2.getTextRange(); + final int s1 = t1.getStartOffset(); + final int s2 = t2.getStartOffset(); - if (s1 == s2) { - return t1.getEndOffset() - t2.getEndOffset(); - } - return s2 - s1; + if (s1 == s2) { + return t1.getEndOffset() - t2.getEndOffset(); } + return s2 - s1; }); return applicable.get(0); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/GroovyConfigUtils.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/GroovyConfigUtils.java index 1eb0df7aa948..d0f00cfe65a2 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/GroovyConfigUtils.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/config/GroovyConfigUtils.java @@ -154,11 +154,8 @@ public abstract class GroovyConfigUtils extends AbstractConfigUtils { } public Collection getSDKVersions(Library[] libraries) { - return ContainerUtil.map2List(libraries, new Function() { - @Override - public String fun(Library library) { - return getSDKLibVersion(library); - } + return ContainerUtil.map2List(libraries, library -> { + return getSDKLibVersion(library); }); } } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/configSlurper/ConfigSlurperMapContentProvider.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/configSlurper/ConfigSlurperMapContentProvider.java index 20b4ad2311f6..08d49c98b0a9 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/configSlurper/ConfigSlurperMapContentProvider.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/configSlurper/ConfigSlurperMapContentProvider.java @@ -87,12 +87,7 @@ public class ConfigSlurperMapContentProvider extends GroovyMapContentProvider { final Set res = new HashSet(); - info.first.collectVariants(info.second, new PairConsumer() { - @Override - public void consume(String variant, Boolean isFinal) { - res.add(variant); - } - }); + info.first.collectVariants(info.second, (variant, isFinal) -> res.add(variant)); return res; } @@ -104,15 +99,12 @@ public class ConfigSlurperMapContentProvider extends GroovyMapContentProvider { final Ref res = new Ref(); - info.first.collectVariants(info.second, new PairConsumer() { - @Override - public void consume(String variant, Boolean isFinal) { - if (variant.equals(key)) { - res.set(isFinal); - } - else if (variant.startsWith(key) && variant.length() > key.length() && variant.charAt(key.length()) == '.') { - res.set(false); - } + info.first.collectVariants(info.second, (variant, isFinal) -> { + if (variant.equals(key)) { + res.set(isFinal); + } + else if (variant.startsWith(key) && variant.length() > key.length() && variant.charAt(key.length()) == '.') { + res.set(false); } }); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/CustomMembersGenerator.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/CustomMembersGenerator.java index 226dcc24380d..9668f1a559ce 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/CustomMembersGenerator.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/CustomMembersGenerator.java @@ -196,12 +196,7 @@ public class CustomMembersGenerator extends GroovyObjectSupport implements GdslM if (argTypes == null) return; String[] types = new String[argTypes.length]; - ContainerUtil.map(argTypes, new Function() { - @Override - public Object fun(PsiType type) { - return type.getCanonicalText(); - } - }, types); + ContainerUtil.map(argTypes, (Function)type -> type.getCanonicalText(), types); generator.setDelegate(this); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java index 0b59d2ec9f22..946eced68a42 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java @@ -156,13 +156,10 @@ public class GroovyDslFileIndex extends ScalarIndexExtension { private static void clearScriptCache() { Application app = ApplicationManager.getApplication(); - app.invokeLater(new Runnable() { - @Override - public void run() { - for (Project project : ProjectManager.getInstance().getOpenProjects()) { - project.putUserData(SCRIPTS_CACHE, null); - ((PsiModificationTrackerImpl)PsiManager.getInstance(project).getModificationTracker()).incCounter(); - } + app.invokeLater(() -> { + for (Project project : ProjectManager.getInstance().getOpenProjects()) { + project.putUserData(SCRIPTS_CACHE, null); + ((PsiModificationTrackerImpl)PsiManager.getInstance(project).getModificationTracker()).incCounter(); } }, app.getDisposed()); } @@ -457,29 +454,26 @@ public class GroovyDslFileIndex extends ScalarIndexExtension { final String text) { final String fileUrl = vfile.getUrl(); - final Runnable parseScript = new Runnable() { - @Override - public void run() { - GroovyDslExecutor executor = getCachedExecutor(vfile, stamp); - try { - if (executor == null && isActivated(vfile)) { - executor = createExecutor(text, vfile, project); - // executor is not only time-consuming to create, but also takes some PermGenSpace - // => we can't afford garbage-collecting it together with PsiFile - // => cache globally by file instance - vfile.putUserData(CACHED_EXECUTOR, Pair.create(executor, stamp)); - if (executor != null) { - setStatusAndError(vfile, Status.ACTIVE, null); - } + final Runnable parseScript = () -> { + GroovyDslExecutor executor = getCachedExecutor(vfile, stamp); + try { + if (executor == null && isActivated(vfile)) { + executor = createExecutor(text, vfile, project); + // executor is not only time-consuming to create, but also takes some PermGenSpace + // => we can't afford garbage-collecting it together with PsiFile + // => cache globally by file instance + vfile.putUserData(CACHED_EXECUTOR, Pair.create(executor, stamp)); + if (executor != null) { + setStatusAndError(vfile, Status.ACTIVE, null); } } - finally { - // access to our MultiMap should be synchronized - synchronized (filesInProcessing) { - // put evaluated executor to all queues - for (LinkedBlockingQueue> queue : filesInProcessing.remove(fileUrl)) { - queue.offer(Pair.create(vfile, executor)); - } + } + finally { + // access to our MultiMap should be synchronized + synchronized (filesInProcessing) { + // put evaluated executor to all queues + for (LinkedBlockingQueue> queue1 : filesInProcessing.remove(fileUrl)) { + queue1.offer(Pair.create(vfile, executor)); } } } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/AnnotatedMembersSearcher.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/AnnotatedMembersSearcher.java index eb702e373b59..6e176dbd8296 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/AnnotatedMembersSearcher.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/AnnotatedMembersSearcher.java @@ -65,16 +65,13 @@ public class AnnotatedMembersSearcher implements QueryExecutor result = new ArrayList(); for (final PsiElement element : members) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiElement e = - element instanceof GroovyFile ? - ((GroovyFile)element).getPackageDefinition() : element; + ApplicationManager.getApplication().runReadAction(() -> { + PsiElement e = + element instanceof GroovyFile ? + ((GroovyFile)element).getPackageDefinition() : element; - if (e instanceof PsiModifierListOwner) { - result.add((PsiModifierListOwner)e); - } + if (e instanceof PsiModifierListOwner) { + result.add((PsiModifierListOwner)e); } }); } @@ -103,22 +100,19 @@ public class AnnotatedMembersSearcher implements QueryExecutor(); for (final PsiElement element : ((LocalSearchScope)scope).getScope()) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (element instanceof GroovyPsiElement) { - ((GroovyPsiElement)element).accept(new GroovyRecursiveElementVisitor() { - @Override - public void visitMethod(GrMethod method) { - candidates.add(method); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (element instanceof GroovyPsiElement) { + ((GroovyPsiElement)element).accept(new GroovyRecursiveElementVisitor() { + @Override + public void visitMethod(GrMethod method) { + candidates.add(method); + } - @Override - public void visitField(GrField field) { - candidates.add(field); - } - }); - } + @Override + public void visitField(GrField field) { + candidates.add(field); + } + }); } }); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GDKSuperMethodSearcher.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GDKSuperMethodSearcher.java index aaa782d2561d..c33a25abee7b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GDKSuperMethodSearcher.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GDKSuperMethodSearcher.java @@ -86,19 +86,16 @@ public class GDKSuperMethodSearcher implements QueryExecutor result = new ArrayList(goodSupers.size()); result.add(goodSupers.get(0)); - final Comparator comparator = new Comparator() { - @Override - public int compare(PsiMethod o1, PsiMethod o2) { //compare by first parameter type - final PsiType type1 = getRealType(o1); - final PsiType type2 = getRealType(o2); - if (TypesUtil.isAssignableByMethodCallConversion(type1, type2, o1)) { - return -1; - } - else if (TypesUtil.isAssignableByMethodCallConversion(type2, type1, o1)) { - return 1; - } - return 0; + final Comparator comparator = (o1, o2) -> { //compare by first parameter type + final PsiType type1 = getRealType(o1); + final PsiType type2 = getRealType(o2); + if (TypesUtil.isAssignableByMethodCallConversion(type1, type2, o1)) { + return -1; } + else if (TypesUtil.isAssignableByMethodCallConversion(type2, type1, o1)) { + return 1; + } + return 0; }; Outer: diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GroovyConstructorUsagesSearcher.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GroovyConstructorUsagesSearcher.java index e989158a4f21..2eba2e7cb4ed 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GroovyConstructorUsagesSearcher.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/GroovyConstructorUsagesSearcher.java @@ -99,15 +99,12 @@ public class GroovyConstructorUsagesSearcher extends QueryExecutorBase newExpressionProcessor = new Processor() { - @Override - public boolean process(GrNewExpression grNewExpression) { - final PsiMethod resolvedConstructor = grNewExpression.resolveMethod(); - if (includeOverloads || constructor.getManager().areElementsEquivalent(resolvedConstructor, constructor)) { - return consumer.process(grNewExpression.getReferenceElement()); - } - return true; + final Processor newExpressionProcessor = grNewExpression -> { + final PsiMethod resolvedConstructor = grNewExpression.resolveMethod(); + if (includeOverloads || constructor.getManager().areElementsEquivalent(resolvedConstructor, constructor)) { + return consumer.process(grNewExpression.getReferenceElement()); } + return true; }; processGroovyClassUsages(clazz, searchScope, collector, newExpressionProcessor, literalProcessor); @@ -135,19 +132,16 @@ public class GroovyConstructorUsagesSearcher extends QueryExecutorBase newExpressionProcessor, final LiteralConstructorSearcher literalProcessor) { - ReferencesSearch.searchOptimized(clazz, scope, false, collector, true, new PairProcessor() { - @Override - public boolean process(PsiReference ref, SearchRequestCollector collector) { - final PsiElement element = ref.getElement(); + ReferencesSearch.searchOptimized(clazz, scope, false, collector, true, (ref, collector1) -> { + final PsiElement element = ref.getElement(); - if (element instanceof GrCodeReferenceElement) { - if (!processGroovyConstructorUsages((GrCodeReferenceElement)element, newExpressionProcessor, literalProcessor)) { - return false; - } + if (element instanceof GrCodeReferenceElement) { + if (!processGroovyConstructorUsages((GrCodeReferenceElement)element, newExpressionProcessor, literalProcessor)) { + return false; } - - return true; } + + return true; }); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/LiteralConstructorReference.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/LiteralConstructorReference.java index e88b5e3fe191..366af3b3d0b4 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/LiteralConstructorReference.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/findUsages/LiteralConstructorReference.java @@ -180,11 +180,8 @@ public class LiteralConstructorReference extends PsiReferenceBase.Poly() { - @Override - public PsiType fun(GrExpression grExpression) { - return grExpression.getType(); - } + return ContainerUtil.map2Array(arguments, PsiType.class, (NullableFunction)grExpression -> { + return grExpression.getType(); }); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppClosureParameterTypeProvider.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppClosureParameterTypeProvider.java index 18cd4fc1db56..de0711caf8b3 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppClosureParameterTypeProvider.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppClosureParameterTypeProvider.java @@ -152,11 +152,8 @@ public class GppClosureParameterTypeProvider extends AbstractClosureParameterEnh } public static PsiType[] getParameterTypes(final Pair pair) { - return ContainerUtil.map2Array(pair.first.getParameterList().getParameters(), PsiType.class, new Function() { - @Override - public PsiType fun(PsiParameter psiParameter) { - return pair.second.substitute(psiParameter.getType()); - } + return ContainerUtil.map2Array(pair.first.getParameterList().getParameters(), PsiType.class, psiParameter -> { + return pair.second.substitute(psiParameter.getType()); }); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppExpectedTypesContributor.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppExpectedTypesContributor.java index a7228a2a3201..516d7ae1c7da 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppExpectedTypesContributor.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/gpp/GppExpectedTypesContributor.java @@ -62,11 +62,8 @@ public class GppExpectedTypesContributor extends GroovyExpectedTypesContributor private static List addExpectedConstructorParameters(GrListOrMap list, GrExpression[] args, GrExpression arg) { - PsiType[] argTypes = ContainerUtil.map2Array(args, PsiType.class, new NullableFunction() { - @Override - public PsiType fun(GrExpression grExpression) { - return grExpression.getType(); - } + PsiType[] argTypes = ContainerUtil.map2Array(args, PsiType.class, (NullableFunction)grExpression -> { + return grExpression.getType(); }); final ArrayList result = new ArrayList(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java index 21ca27b1cffd..8f0e7af8f387 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java @@ -93,12 +93,7 @@ public class ClosureDescriptor extends LightElement implements PsiElement { if (method instanceof ClsMethodImpl) method = ((ClsMethodImpl)method).getSourceMirrorMethod(); final PsiParameter[] parameters = method.getParameterList().getParameters(); final PsiType[] typeArray = PsiType.createArray(parameters.length); - ContainerUtil.map(parameters, new Function() { - @Override - public PsiType fun(PsiParameter parameter) { - return parameter.getType(); - } - }, typeArray); + ContainerUtil.map(parameters, parameter -> parameter.getType(), typeArray); return GrClosureSignatureUtil.isSignatureApplicable(closureSignature, typeArray, place); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/documentation/GroovyPresentationUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/documentation/GroovyPresentationUtil.java index ddff2ad209e8..d3042a3ec97e 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/documentation/GroovyPresentationUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/documentation/GroovyPresentationUtil.java @@ -64,39 +64,36 @@ public class GroovyPresentationUtil { else { builder.append(parameter.getName()); final Set structural = Collections.synchronizedSet(new LinkedHashSet()); - ReferencesSearch.search(parameter, parameter.getUseScope()).forEach(new Processor() { - @Override - public boolean process(PsiReference ref) { - PsiElement parent = ref.getElement().getParent(); - if (parent instanceof GrReferenceExpression) { + ReferencesSearch.search(parameter, parameter.getUseScope()).forEach(ref -> { + PsiElement parent = ref.getElement().getParent(); + if (parent instanceof GrReferenceExpression) { - if (structural.size() >= CONSTRAINTS_NUMBER) { //handle too many constraints - structural.add("..."); - return false; - } - - StringBuilder builder1 = new StringBuilder(); - builder1.append(((GrReferenceElement)parent).getReferenceName()); - PsiType[] argTypes = PsiUtil.getArgumentTypes(parent, true); - if (argTypes != null) { - builder1.append("("); - if (argTypes.length > 0) { - builder1.append(argTypes.length); - if (argTypes.length == 1) { - builder1.append(" arg"); - } - else { - builder1.append(" args"); - } - } - builder1.append(')'); - } - - structural.add(builder1.toString()); + if (structural.size() >= CONSTRAINTS_NUMBER) { //handle too many constraints + structural.add("..."); + return false; } - return true; + StringBuilder builder1 = new StringBuilder(); + builder1.append(((GrReferenceElement)parent).getReferenceName()); + PsiType[] argTypes = PsiUtil.getArgumentTypes(parent, true); + if (argTypes != null) { + builder1.append("("); + if (argTypes.length > 0) { + builder1.append(argTypes.length); + if (argTypes.length == 1) { + builder1.append(" arg"); + } + else { + builder1.append(" args"); + } + } + builder1.append(')'); + } + + structural.add(builder1.toString()); } + + return true; }); if (!structural.isEmpty()) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariable.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariable.java index 569c93ce1976..1a177016d23f 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariable.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariable.java @@ -35,13 +35,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; */ public interface GrVariable extends PsiVariable, GrNamedElement { GrVariable[] EMPTY_ARRAY = new GrVariable[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrVariable[] create(int count) { - return new GrVariable[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrVariable[count]; @Override @NotNull diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariableDeclaration.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariableDeclaration.java index ce918bbb05e2..b47d60a4b967 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariableDeclaration.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/GrVariableDeclaration.java @@ -30,13 +30,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; * @date: 27.03.2007 */ public interface GrVariableDeclaration extends GrStatement, GrMembersDeclaration { - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrVariableDeclaration[] create(int count) { - return new GrVariableDeclaration[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrVariableDeclaration[count]; @Nullable GrTypeElement getTypeElementGroovy(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/params/GrParameter.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/params/GrParameter.java index c379a81d9bf4..923f98b0afc4 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/params/GrParameter.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/params/GrParameter.java @@ -33,13 +33,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement; */ public interface GrParameter extends PsiParameter, GrVariable, GrCondition { GrParameter[] EMPTY_ARRAY = new GrParameter[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrParameter[] create(int count) { - return new GrParameter[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrParameter[count]; @Override @Nullable diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/GrReferenceList.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/GrReferenceList.java index 7b74b4459117..60d55b3d0dd1 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/GrReferenceList.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/GrReferenceList.java @@ -27,13 +27,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; * @author ilyas */ public interface GrReferenceList extends GroovyPsiElement, PsiReferenceList { - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrReferenceList[] create(int count) { - return new GrReferenceList[0]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrReferenceList[0]; @Nullable PsiElement getKeyword(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrEnumConstant.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrEnumConstant.java index 61dcc5abedf8..9f3050ae1b23 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrEnumConstant.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrEnumConstant.java @@ -32,13 +32,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrEnumConsta */ public interface GrEnumConstant extends GrField, GrConstructorCall, PsiEnumConstant { GrEnumConstant[] EMPTY_ARRAY = new GrEnumConstant[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrEnumConstant[] create(int count) { - return new GrEnumConstant[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrEnumConstant[count]; @Override @Nullable diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrMethod.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrMethod.java index f0df7e74a21e..bb3dfa168cce 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrMethod.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/members/GrMethod.java @@ -43,13 +43,7 @@ import java.util.Map; public interface GrMethod extends GrMembersDeclaration, GrNamedElement, PsiMethod, GrMember, GrParametersOwner, GrTopLevelDefinition, GrTypeParameterListOwner, GrDocCommentOwner { GrMethod[] EMPTY_ARRAY = new GrMethod[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrMethod[] create(int count) { - return new GrMethod[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrMethod[count]; @Nullable GrOpenBlock getBlock(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java index a2263e0a3648..b8ff769eb20b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java @@ -31,13 +31,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; public interface GrImportStatement extends GrTopStatement { GrImportStatement[] EMPTY_ARRAY = new GrImportStatement[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrImportStatement[] create(int count) { - return new GrImportStatement[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new GrImportStatement[count]; @Nullable GrCodeReferenceElement getImportReference(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java index 30c7a20b5eb8..cd629802525b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java @@ -100,11 +100,8 @@ public class GroovyExpectedTypesProvider { public static List getDefaultExpectedTypes(@NotNull GrExpression element) { TypeConstraint[] constraints = calculateTypeConstraints(element); - return ContainerUtil.map(constraints, new Function() { - @Override - public PsiType fun(TypeConstraint constraint) { - return constraint.getDefaultType(); - } + return ContainerUtil.map(constraints, constraint -> { + return constraint.getDefaultType(); }); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java index e975ec703ff5..9163ecc39355 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java @@ -125,11 +125,8 @@ public abstract class GrLiteralClassType extends PsiClassType { final PsiType[] params = getParameters(); if (params.length == 0 || params[0] == null) return name; - return name + "<" + StringUtil.join(params, new Function() { - @Override - public String fun(PsiType psiType) { - return psiType.getPresentableText(); - } + return name + "<" + StringUtil.join(params, psiType -> { + return psiType.getPresentableText(); }, ", ") + ">"; } @@ -140,12 +137,7 @@ public abstract class GrLiteralClassType extends PsiClassType { final PsiType[] params = getParameters(); if (params.length == 0 || params[0] == null) return name; - final Function f = new Function() { - @Override - public String fun(PsiType psiType) { - return psiType.getCanonicalText(); - } - }; + final Function f = psiType -> psiType.getCanonicalText(); return name + "<" + StringUtil.join(params, f, ", ") + ">"; } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapTypeFromNamedArgs.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapTypeFromNamedArgs.java index dab7a56d866c..49d2da5f3d2d 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapTypeFromNamedArgs.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapTypeFromNamedArgs.java @@ -50,11 +50,8 @@ public class GrMapTypeFromNamedArgs extends GrMapType { @NotNull @Override protected List> compute() { - return ContainerUtil.map(myOtherEntries, new Function, Couple>() { - @Override - public Couple fun(Couple pair) { - return Couple.of(inferTypePreventingRecursion(pair.first), inferTypePreventingRecursion(pair.second)); - } + return ContainerUtil.map(myOtherEntries, pair -> { + return Couple.of(inferTypePreventingRecursion(pair.first), inferTypePreventingRecursion(pair.second)); }); } }; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrReassignedLocalVarsChecker.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrReassignedLocalVarsChecker.java index 28d33b732c34..7654c7bdd692 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrReassignedLocalVarsChecker.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrReassignedLocalVarsChecker.java @@ -122,12 +122,7 @@ public class GrReassignedLocalVarsChecker { assert resolved instanceof GrVariable; - return TypeInferenceHelper.getCurrentContext().getExpressionType(((GrVariable)resolved), new Function() { - @Override - public PsiType fun(GrVariable variable) { - return getLeastUpperBoundByVar(variable); - } - }); + return TypeInferenceHelper.getCurrentContext().getExpressionType(((GrVariable)resolved), variable -> getLeastUpperBoundByVar(variable)); } @Nullable diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTraitType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTraitType.java index eda206e007cd..963aad33b1d8 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTraitType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTraitType.java @@ -64,11 +64,8 @@ public class GrTraitType extends PsiType { @NotNull @Override public String getPresentableText() { - return myExprType.getPresentableText() + " as " + StringUtil.join(ContainerUtil.map(myTraitTypes, new Function() { - @Override - public String fun(PsiType type) { - return type.getPresentableText(); - } + return myExprType.getPresentableText() + " as " + StringUtil.join(ContainerUtil.map(myTraitTypes, type -> { + return type.getPresentableText(); }), ", "); } @@ -81,11 +78,8 @@ public class GrTraitType extends PsiType { @NotNull @Override public String getInternalCanonicalText() { - return myExprType.getCanonicalText() + " as " + StringUtil.join(ContainerUtil.map(myTraitTypes, new Function() { - @Override - public String fun(PsiType type) { - return type.getInternalCanonicalText(); - } + return myExprType.getCanonicalText() + " as " + StringUtil.join(ContainerUtil.map(myTraitTypes, type -> { + return type.getInternalCanonicalText(); }), ", "); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyNamesUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyNamesUtil.java index 8ad1b75749f7..c8c1e5967eb2 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyNamesUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyNamesUtil.java @@ -100,11 +100,8 @@ public class GroovyNamesUtil { } public static String camelToSnake(final String string) { - return StringUtil.join(camelizeString(string), new Function() { - @Override - public String fun(final String s) { - return StringUtil.decapitalize(s); - } + return StringUtil.join(camelizeString(string), s -> { + return StringUtil.decapitalize(s); }, "-"); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java index 2cca3e3422fd..bb1c80766ded 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java @@ -68,12 +68,7 @@ public class GroovyPsiManager { public GroovyPsiManager(Project project) { myProject = project; - PsiManagerEx.getInstanceEx(myProject).registerRunnableToRunOnAnyChange(new Runnable() { - @Override - public void run() { - dropTypesCache(); - } - }); + PsiManagerEx.getInstanceEx(myProject).registerRunnableToRunOnAnyChange(() -> dropTypesCache()); } public void dropTypesCache() { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java index 49cec6ec1e66..8b44a4debd32 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java @@ -228,17 +228,12 @@ public class GrListOrMapImpl extends GrExpressionImpl implements GrListOrMap { @NotNull @Override protected PsiType[] inferComponents() { - return ContainerUtil.map(initializers, new Function() { + return ContainerUtil.map(initializers, expression -> RecursionManager.doPreventingRecursion(expression, false, new Computable() { @Override - public PsiType fun(final GrExpression expression) { - return RecursionManager.doPreventingRecursion(expression, false, new Computable() { - @Override - public PsiType compute() { - return TypesUtil.boxPrimitiveType(expression.getType(), expression.getManager(), myScope); - } - }); + public PsiType compute() { + return TypesUtil.boxPrimitiveType(expression.getType(), expression.getManager(), myScope); } - }, new PsiType[initializers.length]); + }), new PsiType[initializers.length]); } @Override diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/annotation/GrAnnotationImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/annotation/GrAnnotationImpl.java index b0ba156e1a25..671fde310866 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/annotation/GrAnnotationImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/annotation/GrAnnotationImpl.java @@ -55,12 +55,8 @@ import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; public class GrAnnotationImpl extends GrStubElementBase implements GrAnnotation, StubBasedPsiElement { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.annotation.GrAnnotationImpl"); - private static final PairFunction ANNOTATION_CREATOR = new PairFunction() { - @Override - public PsiAnnotation fun(Project project, String text) { - return GroovyPsiElementFactory.getInstance(project).createAnnotationFromText(text); - } - }; + private static final PairFunction ANNOTATION_CREATOR = + (project, text) -> GroovyPsiElementFactory.getInstance(project).createAnnotationFromText(text); public GrAnnotationImpl(@NotNull ASTNode node) { super(node); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java index 41d6f98ef711..0e8c318be880 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/modifiers/GrModifierListImpl.java @@ -64,13 +64,7 @@ import java.util.Map; public class GrModifierListImpl extends GrStubElementBase implements GrModifierList, StubBasedPsiElement { public static final TObjectIntHashMap NAME_TO_MODIFIER_FLAG_MAP = new TObjectIntHashMap(); public static final Map NAME_TO_MODIFIER_ELEMENT_TYPE = ContainerUtil.newHashMap(); - private static final ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrAnnotation[] create(int count) { - return new GrAnnotation[count]; - } - }; + private static final ArrayFactory ARRAY_FACTORY = count -> new GrAnnotation[count]; private static final TObjectIntHashMap PRIORITY = new TObjectIntHashMap(16); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosableSignatureImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosableSignatureImpl.java index 9c319c1dbc81..cd376397af8b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosableSignatureImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosableSignatureImpl.java @@ -52,12 +52,7 @@ class GrClosableSignatureImpl implements GrClosureSignature { public GrClosureParameter[] getParameters() { GrParameter[] parameters = myBlock.getAllParameters(); - return ContainerUtil.map(parameters, new Function() { - @Override - public GrClosureParameter fun(final GrParameter parameter) { - return createClosureParameter(parameter); - } - }, new GrClosureParameter[parameters.length]); + return ContainerUtil.map(parameters, parameter -> createClosureParameter(parameter), new GrClosureParameter[parameters.length]); } @NotNull diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java index f0da1740b7d3..cd6b3ce29a44 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrClosureSignatureUtil.java @@ -98,12 +98,7 @@ public class GrClosureSignatureUtil { public static GrClosureSignature createSignature(MethodSignature signature) { final PsiType[] types = signature.getParameterTypes(); GrClosureParameter[] parameters = new GrClosureParameter[types.length]; - ContainerUtil.map(types, new Function() { - @Override - public GrClosureParameter fun(PsiType type) { - return new GrImmediateClosureParameterImpl(type, null, false, null); - } - }, parameters); + ContainerUtil.map(types, type -> new GrImmediateClosureParameterImpl(type, null, false, null), parameters); return new GrImmediateClosureSignatureImpl(parameters, null, false, false); } @@ -135,12 +130,9 @@ public class GrClosureSignatureUtil { public static GrClosureSignature rawSignature(@NotNull final GrClosureSignature signature) { final GrClosureParameter[] params = signature.getParameters(); - final GrClosureParameter[] closureParams = ContainerUtil.map(params, new Function() { - @Override - public GrClosureParameter fun(GrClosureParameter parameter) { - PsiType type = TypeConversionUtil.erasure(parameter.getType()); - return new GrImmediateClosureParameterImpl(type, parameter.getName(), parameter.isOptional(), parameter.getDefaultInitializer()); - } + final GrClosureParameter[] closureParams = ContainerUtil.map(params, parameter -> { + PsiType type = TypeConversionUtil.erasure(parameter.getType()); + return new GrImmediateClosureParameterImpl(type, parameter.getName(), parameter.isOptional(), parameter.getDefaultInitializer()); }, new GrClosureParameter[params.length]); return new GrClosureSignatureWithNewParameters(signature, closureParams); @@ -366,12 +358,7 @@ public class GrClosureSignatureUtil { } private static Function, PsiType> ARG_WRAPPER_COMPUTER() { - return new Function, PsiType>() { - @Override - public PsiType fun(ArgWrapper argWrapper) { - return argWrapper.type; - } - }; + return argWrapper -> argWrapper.type; } @Nullable @@ -736,12 +723,7 @@ public class GrClosureSignatureUtil { boolean hasNamedArgs, boolean partial, @NotNull PsiElement context) { - final ArgInfo[] innerMap = mapParametersToArguments(signature, innerArgs.toArray(new InnerArg[innerArgs.size()]), new Function() { - @Override - public PsiType fun(InnerArg o) { - return o.type; - } - }, context, partial); + final ArgInfo[] innerMap = mapParametersToArguments(signature, innerArgs.toArray(new InnerArg[innerArgs.size()]), o -> o.type, context, partial); if (innerMap == null) return null; ArgInfo[] map = new ArgInfo[innerMap.length]; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrMethodSignatureImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrMethodSignatureImpl.java index 5ab7024983eb..2f356bb0d34d 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrMethodSignatureImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/signatures/GrMethodSignatureImpl.java @@ -52,12 +52,7 @@ class GrMethodSignatureImpl implements GrClosureSignature { @Override public GrClosureParameter[] getParameters() { PsiParameter[] parameters = myMethod.getParameterList().getParameters(); - return ContainerUtil.map(parameters, new Function() { - @Override - public GrClosureParameter fun(PsiParameter parameter) { - return createClosureParameter(parameter); - } - }, new GrClosureParameter[parameters.length]); + return ContainerUtil.map(parameters, parameter -> createClosureParameter(parameter), new GrClosureParameter[parameters.length]); } @NotNull diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrFieldImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrFieldImpl.java index 133b1845f499..33635cf3042d 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrFieldImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrFieldImpl.java @@ -143,17 +143,14 @@ public class GrFieldImpl extends GrVariableBaseImpl implements GrFi @Override public PsiType getTypeGroovy() { - PsiType type = TypeInferenceHelper.getCurrentContext().getExpressionType(this, new Function() { - @Override - public PsiType fun(GrFieldImpl field) { - if (getDeclaredType() == null && getInitializerGroovy() == null) { - final PsiType type = GrVariableEnhancer.getEnhancedType(field); - if (type != null) { - return type; - } + PsiType type = TypeInferenceHelper.getCurrentContext().getExpressionType(this, field -> { + if (getDeclaredType() == null && getInitializerGroovy() == null) { + final PsiType type1 = GrVariableEnhancer.getEnhancedType(field); + if (type1 != null) { + return type1; } - return null; } + return null; }); if (type != null) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/blocks/GrClosableBlockImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/blocks/GrClosableBlockImpl.java index da6046506ba5..b27782f64a88 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/blocks/GrClosableBlockImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/blocks/GrClosableBlockImpl.java @@ -329,12 +329,8 @@ public class GrClosableBlockImpl extends GrBlockImpl implements GrClosableBlock return PsiImplUtil.replaceExpression(this, newExpr, removeUnnecessaryParentheses); } - private static final Function ourTypesCalculator = new NullableFunction() { - @Override - public PsiType fun(GrClosableBlock block) { - return GroovyPsiManager.inferType(block, new MethodTypeInferencer(block)); - } - }; + private static final Function ourTypesCalculator = + (NullableFunction)block -> GroovyPsiManager.inferType(block, new MethodTypeInferencer(block)); @Override @Nullable diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrAssignmentExpressionImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrAssignmentExpressionImpl.java index fe01c2742c85..b4282cc7c5f0 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrAssignmentExpressionImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrAssignmentExpressionImpl.java @@ -286,11 +286,8 @@ public class GrAssignmentExpressionImpl extends GrExpressionImpl implements GrAs } }; - private static final Function TYPE_CALCULATOR = new Function() { - @Override - public PsiType fun(GrAssignmentExpressionImpl expression) { - final Function calculator = GrBinaryExpressionTypeCalculators.getTypeCalculator(expression.getFacade()); - return calculator.fun(expression.getFacade()); - } + private static final Function TYPE_CALCULATOR = expression -> { + final Function calculator = GrBinaryExpressionTypeCalculators.getTypeCalculator(expression.getFacade()); + return calculator.fun(expression.getFacade()); }; } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrBinaryExpressionImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrBinaryExpressionImpl.java index e48cf5c7d50d..783a008194fa 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrBinaryExpressionImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrBinaryExpressionImpl.java @@ -86,12 +86,8 @@ public abstract class GrBinaryExpressionImpl extends GrExpressionImpl implements } }; - private static final Function TYPE_CALCULATOR = new Function() { - @Override - public PsiType fun(GrBinaryExpressionImpl expression) { - return GrBinaryExpressionTypeCalculators.getTypeCalculator(expression.getFacade()).fun(expression.getFacade()); - } - }; + private static final Function TYPE_CALCULATOR = + expression -> GrBinaryExpressionTypeCalculators.getTypeCalculator(expression.getFacade()).fun(expression.getFacade()); private final GrBinaryFacade myFacade = new GrBinaryFacade() { @NotNull diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrConditionalExprImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrConditionalExprImpl.java index 3f7dff19fc4c..4e015f0bd4cb 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrConditionalExprImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrConditionalExprImpl.java @@ -33,10 +33,8 @@ import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper; * @author ilyas */ public class GrConditionalExprImpl extends GrExpressionImpl implements GrConditionalExpression { - private static final Function TYPE_CALCULATOR = new NullableFunction() { - @Override - @Nullable - public PsiType fun(GrConditionalExpression conditional) { + private static final Function TYPE_CALCULATOR = + (NullableFunction)conditional -> { GrExpression thenBranch = conditional.getThenBranch(); GrExpression elseBranch = conditional.getElseBranch(); if (thenBranch == null) { @@ -49,8 +47,7 @@ public class GrConditionalExprImpl extends GrExpressionImpl implements GrConditi return TypesUtil.getLeastUpperBoundNullable(thenType, elseType, conditional.getManager()); } return null; - } - }; + }; public GrConditionalExprImpl(@NotNull ASTNode node) { super(node); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrMethodCallImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrMethodCallImpl.java index dd7265ead727..d09af91f6b9b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrMethodCallImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrMethodCallImpl.java @@ -37,29 +37,25 @@ import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrCallExpressionTypeC * @author Maxim.Medvedev */ public abstract class GrMethodCallImpl extends GrCallExpressionImpl implements GrMethodCall { - private static final Function METHOD_CALL_TYPES_CALCULATOR = new Function() { - @Override - @Nullable - public PsiType fun(GrMethodCall callExpression) { - GroovyResolveResult[] resolveResults; + private static final Function METHOD_CALL_TYPES_CALCULATOR = callExpression -> { + GroovyResolveResult[] resolveResults; - GrExpression invokedExpression = callExpression.getInvokedExpression(); - if (invokedExpression instanceof GrReferenceExpression) { - resolveResults = ((GrReferenceExpression)invokedExpression).multiResolve(false); - } - else { - resolveResults = GroovyResolveResult.EMPTY_ARRAY; - } - - for (GrCallExpressionTypeCalculator typeCalculator : GrCallExpressionTypeCalculator.EP_NAME.getExtensions()) { - PsiType res = typeCalculator.calculateReturnType(callExpression, resolveResults); - if (res != null) { - return res; - } - } - - return null; + GrExpression invokedExpression = callExpression.getInvokedExpression(); + if (invokedExpression instanceof GrReferenceExpression) { + resolveResults = ((GrReferenceExpression)invokedExpression).multiResolve(false); } + else { + resolveResults = GroovyResolveResult.EMPTY_ARRAY; + } + + for (GrCallExpressionTypeCalculator typeCalculator : GrCallExpressionTypeCalculator.EP_NAME.getExtensions()) { + PsiType res = typeCalculator.calculateReturnType(callExpression, resolveResults); + if (res != null) { + return res; + } + } + + return null; }; public GrMethodCallImpl(@NotNull ASTNode node) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java index 230d8328187f..74f1863aa2be 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java @@ -59,9 +59,8 @@ import java.util.List; */ public class GrNewExpressionImpl extends GrCallExpressionImpl implements GrNewExpression { - private static final Function MY_TYPE_CALCULATOR = new NullableFunction() { - @Override - public PsiType fun(GrNewExpressionImpl newExpression) { + private static final Function MY_TYPE_CALCULATOR = + (NullableFunction)newExpression -> { final GrAnonymousClassDefinition anonymous = newExpression.getAnonymousClassDefinition(); if (anonymous != null) { return new GrAnonymousClassType(LanguageLevel.JDK_1_5, anonymous.getResolveScope(), @@ -85,8 +84,7 @@ public class GrNewExpressionImpl extends GrCallExpressionImpl implements GrNewEx } return null; - } - }; + }; private static final ResolveCache.PolyVariantResolver RESOLVER = new ResolveCache.PolyVariantResolver() { @NotNull diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java index ab461b835324..0ea7f132ff3e 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java @@ -786,12 +786,7 @@ public class TypesUtil { @Override protected PsiType[] inferComponents() { final GrAnnotationMemberValue[] initializers = value.getInitializers(); - return ContainerUtil.map(initializers, new Function() { - @Override - public PsiType fun(GrAnnotationMemberValue value) { - return inferAnnotationMemberValueType(value); - } - }, PsiType.createArray(initializers.length)); + return ContainerUtil.map(initializers, value1 -> inferAnnotationMemberValueType(value1), PsiType.createArray(initializers.length)); } @Override diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java index aa277cd2f786..942eba074ddb 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java @@ -50,12 +50,8 @@ import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; */ public class GrIndexPropertyImpl extends GrExpressionImpl implements GrIndexProperty { - private static final Function TYPE_CALCULATOR = new NullableFunction() { - @Override - public PsiType fun(GrIndexPropertyImpl index) { - return index.inferType(null); - } - }; + private static final Function TYPE_CALCULATOR = + (NullableFunction)index -> index.inferType(null); private static final ResolveCache.PolyVariantResolver RESOLVER = new ResolveCache.PolyVariantResolver() { @NotNull @Override @@ -219,13 +215,7 @@ public class GrIndexPropertyImpl extends GrExpressionImpl implements GrIndexProp final GrTupleType tupleType = new GrImmediateTupleType(argTypes, JavaPsiFacade.getInstance(getProject()), resolveScope); final GroovyResolveResult[] tupleCandidates = ResolveUtil.getMethodCandidates(thisType, name, invoked, tupleType); if (incompleteCode) { - candidates = ArrayUtil.mergeArrays(candidates, tupleCandidates, new ArrayFactory() { - @NotNull - @Override - public GroovyResolveResult[] create(int count) { - return new GroovyResolveResult[count]; - } - }); + candidates = ArrayUtil.mergeArrays(candidates, tupleCandidates, count -> new GroovyResolveResult[count]); } else { candidates = tupleCandidates; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/types/GrSafeCastExpressionImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/types/GrSafeCastExpressionImpl.java index 1360d5daa490..5ce4d2f72e6d 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/types/GrSafeCastExpressionImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/types/GrSafeCastExpressionImpl.java @@ -48,32 +48,29 @@ import java.util.HashMap; public class GrSafeCastExpressionImpl extends GrExpressionImpl implements GrSafeCastExpression, PsiPolyVariantReference { private static final Function TYPE_CALCULATOR = - new NullableFunction() { - @Override - public PsiType fun(GrSafeCastExpressionImpl cast) { - GrTypeElement typeElement = cast.getCastTypeElement(); - if (typeElement == null) return null; + (NullableFunction)cast -> { + GrTypeElement typeElement = cast.getCastTypeElement(); + if (typeElement == null) return null; - final PsiType opType = cast.getOperand().getType(); - final PsiType castType = typeElement.getType(); + final PsiType opType = cast.getOperand().getType(); + final PsiType castType = typeElement.getType(); - if (isCastToRawCollectionFromArray(opType, castType)) { - final PsiClass resolved = ((PsiClassType)castType).resolve(); - assert resolved != null; - final PsiTypeParameter typeParameter = resolved.getTypeParameters()[0]; - final HashMap substitutionMap = new HashMap(); - substitutionMap.put(typeParameter, TypesUtil.getItemType(opType)); - final PsiSubstitutor substitutor = JavaPsiFacade.getElementFactory(cast.getProject()).createSubstitutor(substitutionMap); - return JavaPsiFacade.getElementFactory(cast.getProject()).createType(resolved, substitutor); - } - - PsiType traitClassType = GrTraitType.createTraitType(cast); - if (traitClassType != null) { - return traitClassType; - } - - return castType;//TypesUtil.boxPrimitiveType(castType, cast.getManager(), cast.getResolveScope()); + if (isCastToRawCollectionFromArray(opType, castType)) { + final PsiClass resolved = ((PsiClassType)castType).resolve(); + assert resolved != null; + final PsiTypeParameter typeParameter = resolved.getTypeParameters()[0]; + final HashMap substitutionMap = new HashMap(); + substitutionMap.put(typeParameter, TypesUtil.getItemType(opType)); + final PsiSubstitutor substitutor = JavaPsiFacade.getElementFactory(cast.getProject()).createSubstitutor(substitutionMap); + return JavaPsiFacade.getElementFactory(cast.getProject()).createType(resolved, substitutor); } + + PsiType traitClassType = GrTraitType.createTraitType(cast); + if (traitClassType != null) { + return traitClassType; + } + + return castType;//TypesUtil.boxPrimitiveType(castType, cast.getManager(), cast.getResolveScope()); }; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/ClosureSyntheticParameter.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/ClosureSyntheticParameter.java index 08e542c00b1c..dc6b1a7a497a 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/ClosureSyntheticParameter.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/ClosureSyntheticParameter.java @@ -37,15 +37,12 @@ import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrVariableEnhancer; * @author ven */ public class ClosureSyntheticParameter extends GrLightParameter implements NavigationItem, GrRenameableLightElement { - private static final Function TYPES_CALCULATOR = new Function() { - @Override - public PsiType fun(ClosureSyntheticParameter parameter) { - PsiType typeGroovy = GrVariableEnhancer.getEnhancedType(parameter); - if (typeGroovy instanceof PsiIntersectionType) { - return ((PsiIntersectionType)typeGroovy).getRepresentative(); - } - return typeGroovy; + private static final Function TYPES_CALCULATOR = parameter -> { + PsiType typeGroovy = GrVariableEnhancer.getEnhancedType(parameter); + if (typeGroovy instanceof PsiIntersectionType) { + return ((PsiIntersectionType)typeGroovy).getRepresentative(); } + return typeGroovy; }; private final GrClosableBlock myClosure; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrTypeParameterListImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrTypeParameterListImpl.java index 499d38fae03c..9cacb8b319a4 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrTypeParameterListImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrTypeParameterListImpl.java @@ -37,13 +37,7 @@ import org.jetbrains.plugins.groovy.lang.psi.impl.GrStubElementBase; * @author ilyas */ public class GrTypeParameterListImpl extends GrStubElementBase implements GrTypeParameterList, StubBasedPsiElement { - private static final ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public GrTypeParameter[] create(int count) { - return new GrTypeParameter[count]; - } - }; + private static final ArrayFactory ARRAY_FACTORY = count -> new GrTypeParameter[count]; public GrTypeParameterListImpl(EmptyStub stub) { super(stub, GroovyElementTypes.TYPE_PARAMETER_LIST); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromAbstractTypeMethodsHintProcessor.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromAbstractTypeMethodsHintProcessor.java index d1c666fda47b..11e543c1ffef 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromAbstractTypeMethodsHintProcessor.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromAbstractTypeMethodsHintProcessor.java @@ -47,11 +47,8 @@ public class FromAbstractTypeMethodsHintProcessor extends SignatureHintProcessor if (aClass == null) return Collections.emptyList(); Collection abstractSignatures = OverrideImplementExploreUtil.getMethodSignaturesToImplement(aClass); - return ContainerUtil.map(abstractSignatures, new Function() { - @Override - public PsiType[] fun(MethodSignature signature) { - return signature.getParameterTypes(); - } + return ContainerUtil.map(abstractSignatures, signature -> { + return signature.getParameterTypes(); }); } } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromStringHintProcessor.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromStringHintProcessor.java index 858246a01d36..e59f50d0e1c3 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromStringHintProcessor.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/FromStringHintProcessor.java @@ -47,24 +47,18 @@ public class FromStringHintProcessor extends SignatureHintProcessor { @NotNull final PsiSubstitutor substitutor, @NotNull String[] options) { LightElement context = new FromStringLightElement(method); - return ContainerUtil.map(options, new Function() { - @Override - public PsiType[] fun(String value) { - String[] params = value.split(","); - return ContainerUtil.map(params, new Function() { - @Override - public PsiType fun(String param) { - try { - PsiType original = JavaPsiFacade.getElementFactory(method.getProject()).createTypeFromText(param, context); - return substitutor.substitute(original); - } - catch (IncorrectOperationException e) { - //do nothing. Just don't throw an exception - } - return PsiType.NULL; - } - }, new PsiType[params.length]); - } + return ContainerUtil.map(options, value -> { + String[] params = value.split(","); + return ContainerUtil.map(params, param -> { + try { + PsiType original = JavaPsiFacade.getElementFactory(method.getProject()).createTypeFromText(param, context); + return substitutor.substitute(original); + } + catch (IncorrectOperationException e) { + //do nothing. Just don't throw an exception + } + return PsiType.NULL; + }, new PsiType[params.length]); }); } } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/SimpleTypeHintProcessor.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/SimpleTypeHintProcessor.java index dc5fafe40715..8c49b9a881f2 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/SimpleTypeHintProcessor.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/SimpleTypeHintProcessor.java @@ -42,16 +42,13 @@ public class SimpleTypeHintProcessor extends SignatureHintProcessor { public List inferExpectedSignatures(@NotNull final PsiMethod method, @NotNull PsiSubstitutor substitutor, @NotNull String[] options) { - return Collections.singletonList(ContainerUtil.map(options, new Function() { - @Override - public PsiType fun(String value) { - try { - PsiType type = JavaPsiFacade.getElementFactory(method.getProject()).createTypeFromText(value, method); - return DefaultGroovyMethods.asBoolean(type) ? type : PsiType.NULL; - } - catch (IncorrectOperationException e) { - return PsiType.NULL; - } + return Collections.singletonList(ContainerUtil.map(options, value -> { + try { + PsiType type = JavaPsiFacade.getElementFactory(method.getProject()).createTypeFromText(value, method); + return DefaultGroovyMethods.asBoolean(type) ? type : PsiType.NULL; + } + catch (IncorrectOperationException e) { + return PsiType.NULL; } }, new PsiType[options.length])); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java index 1d06f9cb2866..45e786def7d5 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java @@ -605,12 +605,7 @@ public class GrClassImplUtil { public static PsiField[] getAllFields(GrTypeDefinition grType) { Map fieldsMap = CollectClassMembersUtil.getAllFields(grType); - return ContainerUtil.map2Array(fieldsMap.values(), PsiField.class, new Function() { - @Override - public PsiField fun(CandidateInfo entry) { - return (PsiField)entry.getElement(); - } - }); + return ContainerUtil.map2Array(fieldsMap.values(), PsiField.class, entry -> (PsiField)entry.getElement()); } public static boolean isClassEquivalentTo(GrTypeDefinitionImpl definition, PsiElement another) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java index fed0c61a1493..73dcaa7f3142 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.java @@ -133,16 +133,13 @@ public class ResolveUtil { @NotNull final ResolveState state) { final GrClosableBlock maxScope = nonCodeProcessor != null ? PsiTreeUtil.getParentOfType(place, GrClosableBlock.class, true, PsiFile.class) : null; - return PsiTreeUtil.treeWalkUp(place, maxScope, new PairProcessor() { - @Override - public boolean process(PsiElement scope, PsiElement lastParent) { - ProgressManager.checkCanceled(); - if (!doProcessDeclarations(originalPlace, lastParent, scope, substituteProcessor(processor, scope), nonCodeProcessor, state)) { - return false; - } - issueLevelChangeEvents(processor, scope); - return true; + return PsiTreeUtil.treeWalkUp(place, maxScope, (scope, lastParent) -> { + ProgressManager.checkCanceled(); + if (!doProcessDeclarations(originalPlace, lastParent, scope, substituteProcessor(processor, scope), nonCodeProcessor, state)) { + return false; } + issueLevelChangeEvents(processor, scope); + return true; }); } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/LibrariesUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/LibrariesUtil.java index 32ede785af15..8abd83afc4f4 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/LibrariesUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/LibrariesUtil.java @@ -238,11 +238,8 @@ public class LibrariesUtil { public static File[] getFilesInDirectoryByPattern(String dirPath, final Pattern pattern) { File distDir = new File(dirPath); - File[] files = distDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return pattern.matcher(name).matches(); - } + File[] files = distDir.listFiles((dir, name) -> { + return pattern.matcher(name).matches(); }); return files != null ? files : new File[0]; } diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java index 03d72fcc1248..fa60a640345d 100644 --- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java +++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java @@ -197,19 +197,16 @@ public class GrConcatenationAwareInjector implements ConcatenationAwareInjector @Override public boolean visitVariable(PsiVariable variable) { if (myConfiguration.getAdvancedConfiguration().getDfaOption() != Configuration.DfaOption.OFF && visitedVars.add(variable)) { - ReferencesSearch.search(variable, searchScope).forEach(new Processor() { - @Override - public boolean process(PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - if (element instanceof GrExpression) { - final GrExpression refExpression = (GrExpression)element; - places.add(refExpression); - if (!myUnparsable) { - myUnparsable = checkUnparsableReference(refExpression); - } + ReferencesSearch.search(variable, searchScope).forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + if (element instanceof GrExpression) { + final GrExpression refExpression = (GrExpression)element; + places.add(refExpression); + if (!myUnparsable) { + myUnparsable = checkUnparsableReference(refExpression); } - return true; } + return true; }); } if (!processCommentInjections(variable)) { diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java index 0d66d21002f0..c646af070aa1 100644 --- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java +++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java @@ -112,16 +112,14 @@ public class GroovyLanguageInjectionSupport extends AbstractLanguageInjectionSup if (injectionsMap.isEmpty() && annotations.isEmpty()) return false; final ArrayList originalInjections = new ArrayList(injectionsMap.keySet()); - final List newInjections = ContainerUtil.mapNotNull(originalInjections, new NullableFunction() { - @Override - public BaseInjection fun(final BaseInjection injection) { - final Pair pair = injectionsMap.get(injection); - final String placeText = JavaLanguageInjectionSupport.getPatternStringForJavaPlace(pair.first, pair.second); - final BaseInjection newInjection = injection.copy(); - newInjection.setPlaceEnabled(placeText, false); - return InjectorUtils.canBeRemoved(newInjection) ? null : newInjection; - } - }); + final List newInjections = ContainerUtil.mapNotNull(originalInjections, + (NullableFunction)injection -> { + final Pair pair = injectionsMap.get(injection); + final String placeText = JavaLanguageInjectionSupport.getPatternStringForJavaPlace(pair.first, pair.second); + final BaseInjection newInjection = injection.copy(); + newInjection.setPlaceEnabled(placeText, false); + return InjectorUtils.canBeRemoved(newInjection) ? null : newInjection; + }); configuration.replaceInjectionsWithUndo(project, newInjections, originalInjections, annotations); return true; } @@ -211,20 +209,17 @@ public class GroovyLanguageInjectionSupport extends AbstractLanguageInjectionSup private static Processor getAnnotationFixer(@NotNull final Project project, @NotNull final String languageId) { - return new Processor() { - @Override - public boolean process(@Nullable PsiLanguageInjectionHost host) { - if (host == null) return false; + return host -> { + if (host == null) return false; - final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration(); - boolean allowed = configuration.isSourceModificationAllowed(); - configuration.setSourceModificationAllowed(true); - try { - return doInject(languageId, host, host); - } - finally { - configuration.setSourceModificationAllowed(allowed); - } + final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration(); + boolean allowed = configuration.isSourceModificationAllowed(); + configuration.setSourceModificationAllowed(true); + try { + return doInject(languageId, host, host); + } + finally { + configuration.setSourceModificationAllowed(allowed); } }; } diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java index 3fcf1c337b86..f972e134088f 100644 --- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java +++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/PatternEditorContextMembersProvider.java @@ -63,12 +63,7 @@ public class PatternEditorContextMembersProvider extends NonCodeMembersContribut @NotNull final ResolveState state) { final PsiFile file = place.getContainingFile().getOriginalFile(); final BaseInjection injection = file.getUserData(BaseInjection.INJECTION_KEY); - Processor processor = new Processor() { - @Override - public boolean process(PsiElement element) { - return element.processDeclarations(scopeProcessor, state, null, place); - } - }; + Processor processor = element -> element.processDeclarations(scopeProcessor, state, null, place); if (injection == null) { processDevContext(file, processor); } @@ -169,13 +164,10 @@ public class PatternEditorContextMembersProvider extends NonCodeMembersContribut } }; final StringSearcher searcher = new StringSearcher("patternClass", true, true); - CacheManager.SERVICE.getInstance(beanClass.getProject()).processFilesWithWord(new Processor() { - @Override - public boolean process(PsiFile psiFile) { - LowLevelSearchUtil.processElementsContainingWordInElement(occurenceProcessor, psiFile, searcher, true, - new EmptyProgressIndicator()); - return true; - } + CacheManager.SERVICE.getInstance(beanClass.getProject()).processFilesWithWord(psiFile -> { + LowLevelSearchUtil.processElementsContainingWordInElement(occurenceProcessor, psiFile, searcher, true, + new EmptyProgressIndicator()); + return true; }, searcher.getPattern(), UsageSearchContext.IN_FOREIGN_LANGUAGES, scope, searcher.isCaseSensitive()); } return ContainerUtil.newHashSet(roots); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovySourceRootDetector.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovySourceRootDetector.java index 1d7dad3e9e1a..0cc2c52675d9 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovySourceRootDetector.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovySourceRootDetector.java @@ -46,12 +46,7 @@ public class GroovySourceRootDetector extends JavaSourceRootDetector { @Override @NotNull protected NullableFunction getPackageNameFetcher() { - return new NullableFunction() { - @Override - public String fun(CharSequence charSequence) { - return getPackageName(charSequence); - } - }; + return charSequence -> getPackageName(charSequence); } @Nullable diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/DumpGroovyControlFlowAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/DumpGroovyControlFlowAction.java index d6948e14b4ab..ef2996ef524c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/DumpGroovyControlFlowAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/DumpGroovyControlFlowAction.java @@ -58,12 +58,7 @@ public class DumpGroovyControlFlowAction extends AnAction implements DumbAware { public void pass(GrControlFlowOwner grExpression) { passInner(grExpression); } - }, new Function() { - @Override - public String fun(GrControlFlowOwner flowOwner) { - return flowOwner.getText(); - } - } + }, flowOwner -> flowOwner.getText() ); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/accessors/GroovyGenerateGetterSetterAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/accessors/GroovyGenerateGetterSetterAction.java index 6fc6167967ec..6c989a3e5e5b 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/accessors/GroovyGenerateGetterSetterAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/accessors/GroovyGenerateGetterSetterAction.java @@ -41,19 +41,15 @@ public class GroovyGenerateGetterSetterAction extends GrBaseGenerateAction { } static { - GenerateAccessorProviderRegistrar.registerProvider(new NotNullFunction>() { - @Override - @NotNull - public Collection fun(PsiClass s) { - if (!(s instanceof GrTypeDefinition)) return Collections.emptyList(); - final List result = new ArrayList(); - for (PsiField field : s.getFields()) { - if (!(field instanceof PsiEnumConstant) && field instanceof GrField) { - result.add(new GrFieldMember((GrField)field)); - } + GenerateAccessorProviderRegistrar.registerProvider(s -> { + if (!(s instanceof GrTypeDefinition)) return Collections.emptyList(); + final List result = new ArrayList(); + for (PsiField field : s.getFields()) { + if (!(field instanceof PsiEnumConstant) && field instanceof GrField) { + result.add(new GrFieldMember((GrField)field)); } - return result; } + return result; }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/equals/GroovyGenerateEqualsHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/equals/GroovyGenerateEqualsHandler.java index ec097853d1d5..799388710f23 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/equals/GroovyGenerateEqualsHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/generate/equals/GroovyGenerateEqualsHandler.java @@ -121,11 +121,8 @@ public class GroovyGenerateEqualsHandler extends GenerateMembersHandlerBase { GroovyGenerateEqualsHelper helper = new GroovyGenerateEqualsHelper(project, aClass, myEqualsFields, myHashCodeFields, myNonNullFields, useInstanceofToCheckParameterType); Collection methods = helper.generateMembers(); - return ContainerUtil.map2List(methods, new Function>() { - @Override - public PsiGenerationInfo fun(final PsiMethod s) { - return new GroovyGenerationInfo(s); - } + return ContainerUtil.map2List(methods, (Function>)s -> { + return new GroovyGenerationInfo(s); }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassActionBase.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassActionBase.java index 451182bf88c6..149253491f35 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassActionBase.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassActionBase.java @@ -118,14 +118,9 @@ public abstract class CreateClassActionBase extends Intention { } } catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog( - GroovyBundle.message("cannot.create.class.error.text", name, e.getLocalizedMessage()), - GroovyBundle.message("cannot.create.class.error.title")); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog( + GroovyBundle.message("cannot.create.class.error.text", name, e.getLocalizedMessage()), + GroovyBundle.message("cannot.create.class.error.title"))); return null; } PsiModifierList modifiers = targetClass.getModifierList(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassFix.java index dc0481d2a0ec..776b7777a240 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateClassFix.java @@ -174,12 +174,9 @@ public abstract class CreateClassFix { PsiClass template = createTemplate(factory, name); if (template == null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (editor != null && editor.getComponent().isDisplayable()) { - HintManager.getInstance().showErrorHint(editor, GroovyIntentionsBundle.message("cannot.create.class")); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (editor != null && editor.getComponent().isDisplayable()) { + HintManager.getInstance().showErrorHint(editor, GroovyIntentionsBundle.message("cannot.create.class")); } }); return; @@ -290,12 +287,9 @@ public abstract class CreateClassFix { } private static void bindRef(@NotNull final PsiClass targetClass, @NotNull final GrReferenceElement ref) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final PsiElement newRef = ref.bindToElement(targetClass); - JavaCodeStyleManager.getInstance(targetClass.getProject()).shortenClassReferences(newRef); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final PsiElement newRef = ref.bindToElement(targetClass); + JavaCodeStyleManager.getInstance(targetClass.getProject()).shortenClassReferences(newRef); }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateParameterFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateParameterFromUsageFix.java index fee314a3664d..1f4aa3c15c80 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateParameterFromUsageFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateParameterFromUsageFix.java @@ -118,12 +118,9 @@ public class CreateParameterFromUsageFix extends Intention implements MethodOrCl showDialog(toSearchFor, ref, project); } else if (scopes.size() > 1) { - myEnclosingMethodsPopup = MethodOrClosureScopeChooser.create(scopes, editor, this, new PairFunction() { - @Override - public Object fun(GrParametersOwner owner, PsiElement element) { - showDialog((PsiMethod)owner, ref, project); - return null; - } + myEnclosingMethodsPopup = MethodOrClosureScopeChooser.create(scopes, editor, this, (owner, element) -> { + showDialog((PsiMethod)owner, ref, project); + return null; }); myEnclosingMethodsPopup.showInBestPositionFor(editor); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrCreateFromUsageBaseFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrCreateFromUsageBaseFix.java index 16100550885d..a85e20e61491 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrCreateFromUsageBaseFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GrCreateFromUsageBaseFix.java @@ -108,24 +108,13 @@ public abstract class GrCreateFromUsageBaseFix extends Intention { final PopupChooserBuilder builder = new PopupChooserBuilder(list); renderer.installSpeedSearch(builder); - Runnable runnable = new Runnable() { - @Override - public void run() { - int index = list.getSelectedIndex(); - if (index < 0) return; - final PsiClass aClass = (PsiClass)list.getSelectedValue(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - invokeImpl(project, aClass); - } - }); - } - }, getText(), null); - } + Runnable runnable = () -> { + int index = list.getSelectedIndex(); + if (index < 0) return; + final PsiClass aClass = (PsiClass)list.getSelectedValue(); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + invokeImpl(project, aClass); + }), getText(), null); }; builder. diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyCreateClassDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyCreateClassDialog.java index 5ed50b62efef..9715b2be9470 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyCreateClassDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyCreateClassDialog.java @@ -145,22 +145,19 @@ public class GroovyCreateClassDialog extends DialogWrapper { final String packageName = getPackageName(); final Ref errorStringRef = new Ref(); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - try { - final PsiDirectory baseDir = myModule == null ? null : PackageUtil.findPossiblePackageDirectoryInModule(myModule, packageName); - myTargetDirectory = myModule == null ? null - : PackageUtil.findOrCreateDirectoryForPackage(myModule, packageName, baseDir, true); - if (myTargetDirectory == null) { - errorStringRef.set(""); - return; - } - errorStringRef.set(RefactoringMessageUtil.checkCanCreateClass(myTargetDirectory, getClassName())); - } - catch (IncorrectOperationException e) { - errorStringRef.set(e.getMessage()); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + try { + final PsiDirectory baseDir = myModule == null ? null : PackageUtil.findPossiblePackageDirectoryInModule(myModule, packageName); + myTargetDirectory = myModule == null ? null + : PackageUtil.findOrCreateDirectoryForPackage(myModule, packageName, baseDir, true); + if (myTargetDirectory == null) { + errorStringRef.set(""); + return; } + errorStringRef.set(RefactoringMessageUtil.checkCanCreateClass(myTargetDirectory, getClassName())); + } + catch (IncorrectOperationException e) { + errorStringRef.set(e.getMessage()); } }, GroovyInspectionBundle.message("create.directory.command"), null); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyStaticImportMethodFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyStaticImportMethodFix.java index 9d6716ed3c72..9c2a4df03601 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyStaticImportMethodFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/GroovyStaticImportMethodFix.java @@ -159,26 +159,23 @@ public class GroovyStaticImportMethodFix extends Intention { } private void doImport(final PsiMethod toImport) { - CommandProcessor.getInstance().executeCommand(toImport.getProject(), new Runnable() { - @Override - public void run() { - AccessToken accessToken = WriteAction.start(); + CommandProcessor.getInstance().executeCommand(toImport.getProject(), () -> { + AccessToken accessToken = WriteAction.start(); + try { try { - try { - GrMethodCall element = myMethodCall.getElement(); - if (element != null) { - getMethodExpression(element).bindToElementViaStaticImport(toImport); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); + GrMethodCall element = myMethodCall.getElement(); + if (element != null) { + getMethodExpression(element).bindToElementViaStaticImport(toImport); } } - finally { - accessToken.finish(); + catch (IncorrectOperationException e) { + LOG.error(e); } } + finally { + accessToken.finish(); + } }, getText(), this); } @@ -189,14 +186,11 @@ public class GroovyStaticImportMethodFix extends Intention { new PopupChooserBuilder(list). setTitle(QuickFixBundle.message("static.import.method.choose.method.to.import")). setMovable(true). - setItemChoosenCallback(new Runnable() { - @Override - public void run() { - PsiMethod selectedValue = (PsiMethod)list.getSelectedValue(); - if (selectedValue == null) return; - LOG.assertTrue(selectedValue.isValid()); - doImport(selectedValue); - } + setItemChoosenCallback(() -> { + PsiMethod selectedValue = (PsiMethod)list.getSelectedValue(); + if (selectedValue == null) return; + LOG.assertTrue(selectedValue.isValid()); + doImport(selectedValue); }).createPopup(). showInBestPositionFor(editor); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicManagerImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicManagerImpl.java index 045f3e3486a0..87e9f2163229 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicManagerImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicManagerImpl.java @@ -53,12 +53,9 @@ public class DynamicManagerImpl extends DynamicManager { public DynamicManagerImpl(final Project project) { myProject = project; - StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { - @Override - public void run() { - if (!myRootElement.getContainingClasses().isEmpty()) { - DynamicToolWindowWrapper.getInstance(project).getToolWindow(); //initialize myToolWindow - } + StartupManager.getInstance(project).registerPostStartupActivity(() -> { + if (!myRootElement.getContainingClasses().isEmpty()) { + DynamicToolWindowWrapper.getInstance(project).getToolWindow(); //initialize myToolWindow } }); } @@ -121,44 +118,41 @@ public class DynamicManagerImpl extends DynamicManager { private void addItemInTree(final DClassElement classElement, final DItemElement itemElement, final ToolWindow window) { final ListTreeTableModelOnColumns myTreeTableModel = DynamicToolWindowWrapper.getInstance(myProject).getTreeTableModel(); - window.activate(new Runnable() { - @Override - public void run() { - final Object rootObject = myTreeTableModel.getRoot(); - if (!(rootObject instanceof DefaultMutableTreeNode)) return; - final DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) rootObject; + window.activate(() -> { + final Object rootObject = myTreeTableModel.getRoot(); + if (!(rootObject instanceof DefaultMutableTreeNode)) return; + final DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) rootObject; - DefaultMutableTreeNode node = new DefaultMutableTreeNode(itemElement); - if (rootNode.getChildCount() > 0) { - for (DefaultMutableTreeNode classNode = (DefaultMutableTreeNode) rootNode.getFirstChild(); - classNode != null; - classNode = (DefaultMutableTreeNode) rootNode.getChildAfter(classNode)) { + DefaultMutableTreeNode node = new DefaultMutableTreeNode(itemElement); + if (rootNode.getChildCount() > 0) { + for (DefaultMutableTreeNode classNode = (DefaultMutableTreeNode) rootNode.getFirstChild(); + classNode != null; + classNode = (DefaultMutableTreeNode) rootNode.getChildAfter(classNode)) { - final Object classRow = classNode.getUserObject(); - if (!(classRow instanceof DClassElement)) return; + final Object classRow = classNode.getUserObject(); + if (!(classRow instanceof DClassElement)) return; - DClassElement otherClassName = (DClassElement) classRow; - if (otherClassName.equals(classElement)) { - int index = getIndexToInsert(classNode, itemElement); - classNode.insert(node, index); - myTreeTableModel.nodesWereInserted(classNode, new int[]{index}); - DynamicToolWindowWrapper.getInstance(myProject).setSelectedNode(node); - return; - } + DClassElement otherClassName = (DClassElement) classRow; + if (otherClassName.equals(classElement)) { + int index = getIndexToInsert(classNode, itemElement); + classNode.insert(node, index); + myTreeTableModel.nodesWereInserted(classNode, new int[]{index}); + DynamicToolWindowWrapper.getInstance(myProject).setSelectedNode(node); + return; } } - - // if there is no such class in tree - int index = getIndexToInsert(rootNode, classElement); - DefaultMutableTreeNode classNode = new DefaultMutableTreeNode(classElement); - rootNode.insert(classNode, index); - myTreeTableModel.nodesWereInserted(rootNode, new int[]{index}); - - classNode.add(node); - myTreeTableModel.nodesWereInserted(classNode, new int[]{0}); - - DynamicToolWindowWrapper.getInstance(myProject).setSelectedNode(node); } + + // if there is no such class in tree + int index = getIndexToInsert(rootNode, classElement); + DefaultMutableTreeNode classNode = new DefaultMutableTreeNode(classElement); + rootNode.insert(classNode, index); + myTreeTableModel.nodesWereInserted(rootNode, new int[]{index}); + + classNode.add(node); + myTreeTableModel.nodesWereInserted(classNode, new int[]{0}); + + DynamicToolWindowWrapper.getInstance(myProject).setSelectedNode(node); }, true); } @@ -358,11 +352,8 @@ public class DynamicManagerImpl extends DynamicManager { public Iterable getMethods(final String classQname) { DClassElement classElement = getRootElement().getClassElement(classQname); if (classElement == null) return Collections.emptyList(); - return ContainerUtil.map(classElement.getMethods(), new Function() { - @Override - public PsiMethod fun(DMethodElement methodElement) { - return methodElement.getPsi(PsiManager.getInstance(myProject), classQname); - } + return ContainerUtil.map(classElement.getMethods(), methodElement -> { + return methodElement.getPsi(PsiManager.getInstance(myProject), classQname); }); } @@ -370,11 +361,8 @@ public class DynamicManagerImpl extends DynamicManager { public Iterable getProperties(final String classQname) { DClassElement classElement = getRootElement().getClassElement(classQname); if (classElement == null) return Collections.emptyList(); - return ContainerUtil.map(classElement.getProperties(), new Function() { - @Override - public PsiVariable fun(DPropertyElement propertyElement) { - return propertyElement.getPsi(PsiManager.getInstance(myProject), classQname); - } + return ContainerUtil.map(classElement.getProperties(), propertyElement -> { + return propertyElement.getPsi(PsiManager.getInstance(myProject), classQname); }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicToolWindowWrapper.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicToolWindowWrapper.java index 182eb1bed731..97b01cf8c178 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicToolWindowWrapper.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/DynamicToolWindowWrapper.java @@ -628,15 +628,11 @@ public class DynamicToolWindowWrapper { } private static String[] mapToUnqualified(final String[] argumentsNames) { - return ContainerUtil.map2Array(argumentsNames, String.class, new NullableFunction() { - @Override - @Nullable - public String fun(final String s) { - if (s == null) return null; - int index = s.lastIndexOf("."); - if (index > 0 && index < s.length() - 1) return s.substring(index + 1); - return s; - } + return ContainerUtil.map2Array(argumentsNames, String.class, (NullableFunction)s -> { + if (s == null) return null; + int index = s.lastIndexOf("."); + if (index > 0 && index < s.length() - 1) return s.substring(index + 1); + return s; }); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitMethod.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitMethod.java index 9636e1f4d5d8..6ce5821c6212 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitMethod.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitMethod.java @@ -154,62 +154,59 @@ public class GrDynamicImplicitMethod extends GrLightMethodBuilder implements GrD @Override public void navigate(boolean requestFocus) { - DynamicToolWindowWrapper.getInstance(getProject()).getToolWindow().activate(new Runnable() { - @Override - public void run() { - DynamicToolWindowWrapper toolWindowWrapper = DynamicToolWindowWrapper.getInstance(getProject()); - final TreeTable treeTable = toolWindowWrapper.getTreeTable(); - final ListTreeTableModelOnColumns model = toolWindowWrapper.getTreeTableModel(); + DynamicToolWindowWrapper.getInstance(getProject()).getToolWindow().activate(() -> { + DynamicToolWindowWrapper toolWindowWrapper = DynamicToolWindowWrapper.getInstance(getProject()); + final TreeTable treeTable = toolWindowWrapper.getTreeTable(); + final ListTreeTableModelOnColumns model = toolWindowWrapper.getTreeTableModel(); - Object root = model.getRoot(); + Object root = model.getRoot(); - if (root == null || !(root instanceof DefaultMutableTreeNode)) return; + if (root == null || !(root instanceof DefaultMutableTreeNode)) return; - DefaultMutableTreeNode treeRoot = ((DefaultMutableTreeNode) root); - DefaultMutableTreeNode desiredNode; + DefaultMutableTreeNode treeRoot = ((DefaultMutableTreeNode) root); + DefaultMutableTreeNode desiredNode; - JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject()); - final PsiClassType fqClassName = facade.getElementFactory().createTypeByFQClassName(myContainingClassName, ProjectScope.getAllScope(getProject())); - final PsiClass psiClass = fqClassName.resolve(); - if (psiClass == null) return; + JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject()); + final PsiClassType fqClassName = facade.getElementFactory().createTypeByFQClassName(myContainingClassName, ProjectScope.getAllScope(getProject())); + final PsiClass psiClass = fqClassName.resolve(); + if (psiClass == null) return; - PsiClass trueClass = null; - DMethodElement methodElement = null; + PsiClass trueClass = null; + DMethodElement methodElement = null; - final GrParameter[] parameters = getParameters(); + final GrParameter[] parameters = getParameters(); - List parameterTypes = new ArrayList(); - for (GrParameter parameter : parameters) { - final String type = parameter.getType().getCanonicalText(); - parameterTypes.add(type); + List parameterTypes = new ArrayList(); + for (GrParameter parameter : parameters) { + final String type = parameter.getType().getCanonicalText(); + parameterTypes.add(type); + } + + for (PsiClass aSuper : PsiUtil.iterateSupers(psiClass, true)) { + methodElement = DynamicManager.getInstance(getProject()).findConcreteDynamicMethod(aSuper.getQualifiedName(), getName(), ArrayUtil.toStringArray(parameterTypes)); + + if (methodElement != null) { + trueClass = aSuper; + break; } + } - for (PsiClass aSuper : PsiUtil.iterateSupers(psiClass, true)) { - methodElement = DynamicManager.getInstance(getProject()).findConcreteDynamicMethod(aSuper.getQualifiedName(), getName(), ArrayUtil.toStringArray(parameterTypes)); + if (trueClass == null) return; + final DefaultMutableTreeNode classNode = TreeUtil.findNodeWithObject(treeRoot, new DClassElement(getProject(), trueClass.getQualifiedName())); - if (methodElement != null) { - trueClass = aSuper; - break; - } - } + if (classNode == null) return; + desiredNode = TreeUtil.findNodeWithObject(classNode, methodElement); - if (trueClass == null) return; - final DefaultMutableTreeNode classNode = TreeUtil.findNodeWithObject(treeRoot, new DClassElement(getProject(), trueClass.getQualifiedName())); + if (desiredNode == null) return; + final TreePath path = TreeUtil.getPathFromRoot(desiredNode); - if (classNode == null) return; - desiredNode = TreeUtil.findNodeWithObject(classNode, methodElement); - - if (desiredNode == null) return; - final TreePath path = TreeUtil.getPathFromRoot(desiredNode); - - treeTable.getTree().expandPath(path); - treeTable.getTree().setSelectionPath(path); - treeTable.getTree().fireTreeExpanded(path); + treeTable.getTree().expandPath(path); + treeTable.getTree().setSelectionPath(path); + treeTable.getTree().fireTreeExpanded(path); // ToolWindowManager.getInstance(myProject).getFocusManager().requestFocus(treeTable, true); - treeTable.revalidate(); - treeTable.repaint(); - } + treeTable.revalidate(); + treeTable.repaint(); }, true); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitProperty.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitProperty.java index 530c908a608b..5532f8352622 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitProperty.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/GrDynamicImplicitProperty.java @@ -107,52 +107,49 @@ public class GrDynamicImplicitProperty extends GrImplicitVariableImpl implements super.navigate(requestFocus); return; } - DynamicToolWindowWrapper.getInstance(myProject).getToolWindow().activate(new Runnable() { - @Override - public void run() { - DynamicToolWindowWrapper toolWindowWrapper = DynamicToolWindowWrapper.getInstance(myProject); - final TreeTable treeTable = toolWindowWrapper.getTreeTable(); - final ListTreeTableModelOnColumns model = toolWindowWrapper.getTreeTableModel(); + DynamicToolWindowWrapper.getInstance(myProject).getToolWindow().activate(() -> { + DynamicToolWindowWrapper toolWindowWrapper = DynamicToolWindowWrapper.getInstance(myProject); + final TreeTable treeTable = toolWindowWrapper.getTreeTable(); + final ListTreeTableModelOnColumns model = toolWindowWrapper.getTreeTableModel(); - Object root = model.getRoot(); + Object root = model.getRoot(); - if (root == null || !(root instanceof DefaultMutableTreeNode)) return; + if (root == null || !(root instanceof DefaultMutableTreeNode)) return; - DefaultMutableTreeNode treeRoot = ((DefaultMutableTreeNode) root); - final PsiClass psiClass = getContainingClassElement(); - if (psiClass == null) return; + DefaultMutableTreeNode treeRoot = ((DefaultMutableTreeNode) root); + final PsiClass psiClass = getContainingClassElement(); + if (psiClass == null) return; - final DefaultMutableTreeNode desiredNode; - DPropertyElement dynamicProperty = null; - PsiClass trueSuper = null; - for (PsiClass aSuper : PsiUtil.iterateSupers(psiClass, true)) { - dynamicProperty = DynamicManager.getInstance(myProject).findConcreteDynamicProperty(aSuper.getQualifiedName(), getName()); + final DefaultMutableTreeNode desiredNode; + DPropertyElement dynamicProperty = null; + PsiClass trueSuper = null; + for (PsiClass aSuper : PsiUtil.iterateSupers(psiClass, true)) { + dynamicProperty = DynamicManager.getInstance(myProject).findConcreteDynamicProperty(aSuper.getQualifiedName(), getName()); - if (dynamicProperty != null) { - trueSuper = aSuper; - break; - } + if (dynamicProperty != null) { + trueSuper = aSuper; + break; } - - if (trueSuper == null) return; - - final DefaultMutableTreeNode classNode = TreeUtil.findNodeWithObject(treeRoot, new DClassElement(myProject, trueSuper.getQualifiedName())); - if (classNode == null) return; - - desiredNode = TreeUtil.findNodeWithObject(classNode, dynamicProperty); - - if (desiredNode == null) return; - final TreePath path = TreeUtil.getPathFromRoot(desiredNode); - - treeTable.getTree().expandPath(path); - treeTable.getTree().setSelectionPath(path); - treeTable.getTree().fireTreeExpanded(path); - - ToolWindowManager.getInstance(myProject).getFocusManager().requestFocus(treeTable, true); - treeTable.revalidate(); - treeTable.repaint(); - } + + if (trueSuper == null) return; + + final DefaultMutableTreeNode classNode = TreeUtil.findNodeWithObject(treeRoot, new DClassElement(myProject, trueSuper.getQualifiedName())); + if (classNode == null) return; + + desiredNode = TreeUtil.findNodeWithObject(classNode, dynamicProperty); + + if (desiredNode == null) return; + final TreePath path = TreeUtil.getPathFromRoot(desiredNode); + + treeTable.getTree().expandPath(path); + treeTable.getTree().setSelectionPath(path); + treeTable.getTree().fireTreeExpanded(path); + + ToolWindowManager.getInstance(myProject).getFocusManager().requestFocus(treeTable, true); + treeTable.revalidate(); + treeTable.repaint(); + }, true); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicDialog.java index feb4963f7f87..3c8c9c7b7fbf 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/dynamic/ui/DynamicDialog.java @@ -214,52 +214,49 @@ public abstract class DynamicDialog extends DialogWrapper { final Document document = PsiDocumentManager.getInstance(myProject).getDocument(myContext.getContainingFile()); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - UndoManager.getInstance(myProject).undoableActionPerformed(new GlobalUndoableAction(document) { - @Override - public void undo() throws UnexpectedUndoException { + CommandProcessor.getInstance().executeCommand(myProject, () -> { + UndoManager.getInstance(myProject).undoableActionPerformed(new GlobalUndoableAction(document) { + @Override + public void undo() throws UnexpectedUndoException { - final DItemElement itemElement; - if (mySettings.isMethod()) { - final List myPairList = mySettings.getParams(); - final String[] argumentsTypes = QuickfixUtil.getArgumentsTypes(myPairList); - itemElement = - myDynamicManager.findConcreteDynamicMethod(mySettings.getContainingClassName(), mySettings.getName(), argumentsTypes); - } - else { - itemElement = myDynamicManager.findConcreteDynamicProperty(mySettings.getContainingClassName(), mySettings.getName()); - } - - if (itemElement == null) { - Messages.showWarningDialog(myProject, GroovyInspectionBundle.message("Cannot.perform.undo.operation"), - GroovyInspectionBundle.message("Undo.disable")); - return; - } - final DClassElement classElement = myDynamicManager.getClassElementByItem(itemElement); - - if (classElement == null) { - Messages.showWarningDialog(myProject, GroovyInspectionBundle.message("Cannot.perform.undo.operation"), - GroovyInspectionBundle.message("Undo.disable")); - return; - } - - removeElement(itemElement); - - if (classElement.getMethods().isEmpty() && classElement.getProperties().isEmpty()) { - myDynamicManager.removeClassElement(classElement); - } + final DItemElement itemElement; + if (mySettings.isMethod()) { + final List myPairList = mySettings.getParams(); + final String[] argumentsTypes = QuickfixUtil.getArgumentsTypes(myPairList); + itemElement = + myDynamicManager.findConcreteDynamicMethod(mySettings.getContainingClassName(), mySettings.getName(), argumentsTypes); + } + else { + itemElement = myDynamicManager.findConcreteDynamicProperty(mySettings.getContainingClassName(), mySettings.getName()); } - @Override - public void redo() throws UnexpectedUndoException { - addElement(mySettings); + if (itemElement == null) { + Messages.showWarningDialog(myProject, GroovyInspectionBundle.message("Cannot.perform.undo.operation"), + GroovyInspectionBundle.message("Undo.disable")); + return; } - }); + final DClassElement classElement = myDynamicManager.getClassElementByItem(itemElement); - addElement(mySettings); - } + if (classElement == null) { + Messages.showWarningDialog(myProject, GroovyInspectionBundle.message("Cannot.perform.undo.operation"), + GroovyInspectionBundle.message("Undo.disable")); + return; + } + + removeElement(itemElement); + + if (classElement.getMethods().isEmpty() && classElement.getProperties().isEmpty()) { + myDynamicManager.removeClassElement(classElement); + } + } + + @Override + public void redo() throws UnexpectedUndoException { + addElement(mySettings); + } + }); + + addElement(mySettings); }, "Add dynamic element", null); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyMarkerTypes.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyMarkerTypes.java index 2ca7f7eba3c6..b9710650df99 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyMarkerTypes.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GroovyMarkerTypes.java @@ -58,42 +58,38 @@ import java.util.*; * @author Max Medvedev */ public class GroovyMarkerTypes { - static final MarkerType OVERRIDING_PROPERTY_TYPE = new MarkerType("OVERRIDING_PROPERTY_TYPE",new Function() { - @Nullable - @Override - public String fun(PsiElement psiElement) { - final PsiElement parent = psiElement.getParent(); - if (!(parent instanceof GrField)) return null; - final GrField field = (GrField)parent; + static final MarkerType OVERRIDING_PROPERTY_TYPE = new MarkerType("OVERRIDING_PROPERTY_TYPE", psiElement -> { + final PsiElement parent = psiElement.getParent(); + if (!(parent instanceof GrField)) return null; + final GrField field = (GrField)parent; - final List accessors = GroovyPropertyUtils.getFieldAccessors(field); - StringBuilder builder = new StringBuilder(); - builder.append(""); - int count = 0; - String sep = ""; - for (GrAccessorMethod method : accessors) { - PsiMethod[] superMethods = method.findSuperMethods(false); - count += superMethods.length; - if (superMethods.length == 0) continue; - PsiMethod superMethod = superMethods[0]; - boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); - boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); + final List accessors = GroovyPropertyUtils.getFieldAccessors(field); + StringBuilder builder = new StringBuilder(); + builder.append(""); + int count = 0; + String sep = ""; + for (GrAccessorMethod method : accessors) { + PsiMethod[] superMethods = method.findSuperMethods(false); + count += superMethods.length; + if (superMethods.length == 0) continue; + PsiMethod superMethod = superMethods[0]; + boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); + boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); - @NonNls final String key; - if (isSuperAbstract && !isAbstract) { - key = "method.implements.in"; - } - else { - key = "method.overrides.in"; - } - builder.append(sep); - sep = "
      "; - composeText(superMethods, DaemonBundle.message(key), builder); + @NonNls final String key; + if (isSuperAbstract && !isAbstract) { + key = "method.implements.in"; } - if (count == 0) return null; - builder.append(""); - return builder.toString(); + else { + key = "method.overrides.in"; + } + builder.append(sep); + sep = "
      "; + composeText(superMethods, DaemonBundle.message(key), builder); } + if (count == 0) return null; + builder.append(""); + return builder.toString(); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { @@ -114,33 +110,29 @@ public class GroovyMarkerTypes { new MethodCellRenderer(showMethodNames)); } }); - static final MarkerType OVERRIDEN_PROPERTY_TYPE = new MarkerType("OVERRIDEN_PROPERTY_TYPE",new Function() { - @Nullable - @Override - public String fun(PsiElement element) { - PsiElement parent = element.getParent(); - if (!(parent instanceof GrField)) return null; - final List accessors = GroovyPropertyUtils.getFieldAccessors((GrField)parent); + static final MarkerType OVERRIDEN_PROPERTY_TYPE = new MarkerType("OVERRIDEN_PROPERTY_TYPE", element -> { + PsiElement parent = element.getParent(); + if (!(parent instanceof GrField)) return null; + final List accessors = GroovyPropertyUtils.getFieldAccessors((GrField)parent); - PsiElementProcessor.CollectElementsWithLimit processor = new PsiElementProcessor.CollectElementsWithLimit(5); + PsiElementProcessor.CollectElementsWithLimit processor = new PsiElementProcessor.CollectElementsWithLimit(5); - for (GrAccessorMethod method : accessors) { - OverridingMethodsSearch.search(method).forEach(new PsiElementProcessorAdapter(processor)); - } - if (processor.isOverflow()) { - return DaemonBundle.message("method.is.overridden.too.many"); - } - - PsiMethod[] overridings = processor.toArray(new PsiMethod[processor.getCollection().size()]); - if (overridings.length == 0) return null; - - Comparator comparator = new MethodCellRenderer(false).getComparator(); - Arrays.sort(overridings, comparator); - - String start = DaemonBundle.message("method.is.overriden.header"); - @NonNls String pattern = "    {1}"; - return GutterIconTooltipHelper.composeText(overridings, start, pattern); + for (GrAccessorMethod method : accessors) { + OverridingMethodsSearch.search(method).forEach(new PsiElementProcessorAdapter(processor)); } + if (processor.isOverflow()) { + return DaemonBundle.message("method.is.overridden.too.many"); + } + + PsiMethod[] overridings = processor.toArray(new PsiMethod[processor.getCollection().size()]); + if (overridings.length == 0) return null; + + Comparator comparator = new MethodCellRenderer(false).getComparator(); + Arrays.sort(overridings, comparator); + + String start = DaemonBundle.message("method.is.overriden.header"); + @NonNls String pattern = "    {1}"; + return GutterIconTooltipHelper.composeText(overridings, start, pattern); }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { @@ -156,19 +148,11 @@ public class GroovyMarkerTypes { Set result = new THashSet<>(); Processor collectProcessor = Processors.cancelableCollectProcessor(result); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (GrAccessorMethod method : GroovyPropertyUtils.getFieldAccessors(field)) { - OverridingMethodsSearch.search(method).forEach(collectProcessor); - } - } - }); + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + for (GrAccessorMethod method : GroovyPropertyUtils.getFieldAccessors(field)) { + OverridingMethodsSearch.search(method).forEach(collectProcessor); } - }, "Searching for overriding methods", true, field.getProject(), (JComponent)e.getComponent())) { + }), "Searching for overriding methods", true, field.getProject(), (JComponent)e.getComponent())) { return; } @@ -182,31 +166,29 @@ public class GroovyMarkerTypes { } } ); - public static final MarkerType GR_OVERRIDING_METHOD = new MarkerType("GR_OVERRIDING_METHOD", new NullableFunction() { - @Override - public String fun(PsiElement element) { - PsiElement parent = element.getParent(); - if (!(parent instanceof GrMethod)) return null; - GrMethod method = (GrMethod)parent; + public static final MarkerType GR_OVERRIDING_METHOD = new MarkerType("GR_OVERRIDING_METHOD", + (NullableFunction)element -> { + PsiElement parent = element.getParent(); + if (!(parent instanceof GrMethod)) return null; + GrMethod method = (GrMethod)parent; - Set superMethods = collectSuperMethods(method); - if (superMethods.isEmpty()) return null; + Set superMethods = collectSuperMethods(method); + if (superMethods.isEmpty()) return null; - PsiMethod superMethod = superMethods.iterator().next(); - boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); - boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); + PsiMethod superMethod = superMethods.iterator().next(); + boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); + boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); - final boolean sameSignature = superMethod.getSignature(PsiSubstitutor.EMPTY).equals(method.getSignature(PsiSubstitutor.EMPTY)); - @NonNls final String key; - if (isSuperAbstract && !isAbstract){ - key = sameSignature ? "method.implements" : "method.implements.in"; - } - else{ - key = sameSignature ? "method.overrides" : "method.overrides.in"; - } - return GutterIconTooltipHelper.composeText(superMethods, "", DaemonBundle.message(key)); - } - }, new LineMarkerNavigator(){ + final boolean sameSignature = superMethod.getSignature(PsiSubstitutor.EMPTY).equals(method.getSignature(PsiSubstitutor.EMPTY)); + @NonNls final String key; + if (isSuperAbstract && !isAbstract){ + key = sameSignature ? "method.implements" : "method.implements.in"; + } + else{ + key = sameSignature ? "method.overrides" : "method.overrides.in"; + } + return GutterIconTooltipHelper.composeText(superMethods, "", DaemonBundle.message(key)); + }, new LineMarkerNavigator(){ @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); @@ -222,44 +204,42 @@ public class GroovyMarkerTypes { } }); - public static final MarkerType GR_OVERRIDEN_METHOD = new MarkerType("GR_OVERRIDEN_METHOD",new NullableFunction() { - @Override - public String fun(PsiElement element) { - PsiElement parent = element.getParent(); - if (!(parent instanceof GrMethod)) return null; - GrMethod method = (GrMethod)parent; + public static final MarkerType GR_OVERRIDEN_METHOD = new MarkerType("GR_OVERRIDEN_METHOD", + (NullableFunction)element -> { + PsiElement parent = element.getParent(); + if (!(parent instanceof GrMethod)) return null; + GrMethod method = (GrMethod)parent; - final PsiElementProcessor.CollectElementsWithLimit processor = new PsiElementProcessor.CollectElementsWithLimit(5); + final PsiElementProcessor.CollectElementsWithLimit processor = new PsiElementProcessor.CollectElementsWithLimit(5); - for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { - OverridingMethodsSearch.search(m).forEach(new ReadActionProcessor() { - @Override - public boolean processInReadAction(PsiMethod method) { - if (method instanceof GrTraitMethod) { - return true; - } - return processor.execute(method); - } - }); - } + for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { + OverridingMethodsSearch.search(m).forEach(new ReadActionProcessor() { + @Override + public boolean processInReadAction(PsiMethod method) { + if (method instanceof GrTraitMethod) { + return true; + } + return processor.execute(method); + } + }); + } - boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); + boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); - if (processor.isOverflow()){ - return isAbstract ? DaemonBundle.message("method.is.implemented.too.many") : DaemonBundle.message("method.is.overridden.too.many"); - } + if (processor.isOverflow()){ + return isAbstract ? DaemonBundle.message("method.is.implemented.too.many") : DaemonBundle.message("method.is.overridden.too.many"); + } - PsiMethod[] overridings = processor.toArray(new PsiMethod[processor.getCollection().size()]); - if (overridings.length == 0) return null; + PsiMethod[] overridings = processor.toArray(new PsiMethod[processor.getCollection().size()]); + if (overridings.length == 0) return null; - Comparator comparator = new MethodCellRenderer(false).getComparator(); - Arrays.sort(overridings, comparator); + Comparator comparator = new MethodCellRenderer(false).getComparator(); + Arrays.sort(overridings, comparator); - String start = isAbstract ? DaemonBundle.message("method.is.implemented.header") : DaemonBundle.message("method.is.overriden.header"); - @NonNls String pattern = "    {1}"; - return GutterIconTooltipHelper.composeText(overridings, start, pattern); - } - }, new LineMarkerNavigator(){ + String start = isAbstract ? DaemonBundle.message("method.is.implemented.header") : DaemonBundle.message("method.is.overriden.header"); + @NonNls String pattern = "    {1}"; + return GutterIconTooltipHelper.composeText(overridings, start, pattern); + }, new LineMarkerNavigator(){ @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); @@ -274,27 +254,19 @@ public class GroovyMarkerTypes { final GrMethod method = (GrMethod)parent; final PsiElementProcessor.CollectElementsWithLimit collectProcessor = new PsiElementProcessor.CollectElementsWithLimit(2, new THashSet()); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { + OverridingMethodsSearch.search(m).forEach(new ReadActionProcessor() { @Override - public void run() { - for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { - OverridingMethodsSearch.search(m).forEach(new ReadActionProcessor() { - @Override - public boolean processInReadAction(PsiMethod psiMethod) { - if (psiMethod instanceof GrReflectedMethod) { - psiMethod = ((GrReflectedMethod)psiMethod).getBaseMethod(); - } - return collectProcessor.execute(psiMethod); - } - }); + public boolean processInReadAction(PsiMethod psiMethod) { + if (psiMethod instanceof GrReflectedMethod) { + psiMethod = ((GrReflectedMethod)psiMethod).getBaseMethod(); } + return collectProcessor.execute(psiMethod); } }); } - }, MarkerType.SEARCHING_FOR_OVERRIDING_METHODS, true, method.getProject(), (JComponent)e.getComponent())) { + }), MarkerType.SEARCHING_FOR_OVERRIDING_METHODS, true, method.getProject(), (JComponent)e.getComponent())) { return; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/GroovyOptimizeImportsFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/GroovyOptimizeImportsFix.java index 8dc7c4b9a3d3..868c3f4055ab 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/GroovyOptimizeImportsFix.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/GroovyOptimizeImportsFix.java @@ -116,14 +116,11 @@ public class GroovyOptimizeImportsFix implements IntentionAction { } return !DaemonCodeAnalyzerEx - .processHighlights(myDocument, myFile.getProject(), HighlightSeverity.ERROR, 0, myDocument.getTextLength(), new Processor() { - @Override - public boolean process(HighlightInfo error) { - int infoStart = error.getActualStartOffset(); - int infoEnd = error.getActualEndOffset(); + .processHighlights(myDocument, myFile.getProject(), HighlightSeverity.ERROR, 0, myDocument.getTextLength(), error -> { + int infoStart = error.getActualStartOffset(); + int infoEnd = error.getActualEndOffset(); - return ignoreRange.containsRange(infoStart, infoEnd) && error.type.equals(HighlightInfoType.WRONG_REF); - } + return ignoreRange.containsRange(infoStart, infoEnd) && error.type.equals(HighlightInfoType.WRONG_REF); }); } @@ -132,23 +129,20 @@ public class GroovyOptimizeImportsFix implements IntentionAction { @NotNull final Editor editor) { final long stamp = editor.getDocument().getModificationStamp(); Project project = file.getProject(); - TransactionGuard.submitTransaction(project, new Runnable() { - @Override - public void run() { - if (editor.isDisposed() || editor.getDocument().getModificationStamp() != stamp) return; - //no need to optimize imports on the fly during undo/redo - final UndoManager undoManager = UndoManager.getInstance(project); - if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return; - PsiDocumentManager.getInstance(project).commitAllDocuments(); - String beforeText = file.getText(); - final long oldStamp = editor.getDocument().getModificationStamp(); - DocumentUtil.writeInRunUndoTransparentAction(runnable); - if (oldStamp != editor.getDocument().getModificationStamp()) { - String afterText = file.getText(); - if (Comparing.strEqual(beforeText, afterText)) { - String path = file.getViewProvider().getVirtualFile().getPath(); - LOG.error("Import optimizer hasn't optimized any imports", new Attachment(path, afterText)); - } + TransactionGuard.submitTransaction(project, () -> { + if (editor.isDisposed() || editor.getDocument().getModificationStamp() != stamp) return; + //no need to optimize imports on the fly during undo/redo + final UndoManager undoManager = UndoManager.getInstance(project); + if (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) return; + PsiDocumentManager.getInstance(project).commitAllDocuments(); + String beforeText = file.getText(); + final long oldStamp = editor.getDocument().getModificationStamp(); + DocumentUtil.writeInRunUndoTransparentAction(runnable); + if (oldStamp != editor.getDocument().getModificationStamp()) { + String afterText = file.getText(); + if (Comparing.strEqual(beforeText, afterText)) { + String path = file.getViewProvider().getVirtualFile().getPath(); + LOG.error("Import optimizer hasn't optimized any imports", new Attachment(path, afterText)); } } }); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/ExcludeFromStubGenerationAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/ExcludeFromStubGenerationAction.java index 4cafc7ec5920..b274a67221e6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/ExcludeFromStubGenerationAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/ExcludeFromStubGenerationAction.java @@ -47,11 +47,8 @@ public class ExcludeFromStubGenerationAction extends AnAction implements DumbAwa final Project project = file.getProject(); final GroovyCompilerConfigurable configurable = new GroovyCompilerConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { - @Override - public void run() { - configurable.getExcludes().addEntry(new ExcludeEntryDescription(virtualFile, false, true, project)); - } + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { + configurable.getExcludes().addEntry(new ExcludeEntryDescription(virtualFile, false, true, project)); }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyStubNotificationProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyStubNotificationProvider.java index ae75e2830b08..49ebe7eab5c6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyStubNotificationProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyStubNotificationProvider.java @@ -68,33 +68,21 @@ public class GroovyStubNotificationProvider extends EditorNotifications.Provider private static EditorNotificationPanel decorateStubFile(final VirtualFile file, final Project project) { final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText("This stub is generated for Groovy class to make Groovy-Java cross-compilation possible"); - panel.createActionLabel("Go to the Groovy class", new Runnable() { - @Override - public void run() { - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - final PsiClass original = findClassByStub(project, file); - if (original != null) { - original.navigate(true); - } - } - }); - } + panel.createActionLabel("Go to the Groovy class", () -> { + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { + final PsiClass original = findClassByStub(project, file); + if (original != null) { + original.navigate(true); + } + }); }); - panel.createActionLabel("Exclude from stub generation", new Runnable() { - @Override - public void run() { - DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() { - @Override - public void run() { - final PsiClass psiClass = findClassByStub(project, file); - if (psiClass != null) { - ExcludeFromStubGenerationAction.doExcludeFromStubGeneration(psiClass.getContainingFile()); - } - } - }); - } + panel.createActionLabel("Exclude from stub generation", () -> { + DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { + final PsiClass psiClass = findClassByStub(project, file); + if (psiClass != null) { + ExcludeFromStubGenerationAction.doExcludeFromStubGeneration(psiClass.getContainingFile()); + } + }); }); return panel; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/DefaultGroovyFrameworkConfigNotification.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/DefaultGroovyFrameworkConfigNotification.java index 2cca1543777d..1038b6ce5519 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/config/DefaultGroovyFrameworkConfigNotification.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/config/DefaultGroovyFrameworkConfigNotification.java @@ -43,11 +43,8 @@ public class DefaultGroovyFrameworkConfigNotification extends GroovyFrameworkCon public EditorNotificationPanel createConfigureNotificationPanel(@NotNull final Module module) { final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(GroovyBundle.message("groovy.library.is.not.configured.for.module", module.getName())); - panel.createActionLabel(GroovyBundle.message("configure.groovy.library"), new Runnable() { - @Override - public void run() { - AddCustomLibraryDialog.createDialog(new GroovyLibraryDescription(), module, null).show(); - } + panel.createActionLabel(GroovyBundle.message("configure.groovy.library"), () -> { + AddCustomLibraryDialog.createDialog(new GroovyLibraryDescription(), module, null).show(); }); return panel; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java index ac03ca70ad3d..7c13733ea1bc 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java @@ -126,13 +126,10 @@ public class GroovyConsole { final GroovyConsole existingConsole = contentFile.getUserData(GROOVY_CONSOLE); if (existingConsole != null) return; - final Consumer initializer = new Consumer() { - @Override - public void consume(Module module) { - final GroovyConsole console = createConsole(project, contentFile, module); - if (console != null) { - callback.consume(console); - } + final Consumer initializer = module -> { + final GroovyConsole console = createConsole(project, contentFile, module); + if (console != null) { + callback.consume(console); } }; @@ -247,11 +244,6 @@ public class GroovyConsole { } private static Consumer restarter(final Project project, final VirtualFile file) { - return new Consumer() { - @Override - public void consume(Module module) { - createConsole(project, file, module); - } - }; + return module -> createConsole(project, file, module); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleUtil.java index 6b3b42cd0fb0..44ad803501fa 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsoleUtil.java @@ -44,19 +44,16 @@ public class GroovyConsoleUtil { } }; - private static final Function MODULE_VERSION = new Function() { - @Override - public String fun(@NotNull Module module) { - final String moduleGroovyHomePath = LibrariesUtil.getGroovyHomePath(module); - boolean bundled = moduleGroovyHomePath == null || !hasGroovyAll(module); - final String homePathToUse = bundled - ? GroovyFacetUtil.getBundledGroovyJar().getParentFile().getParent() - : moduleGroovyHomePath; - final String version = GroovyConfigUtils.getInstance().getSDKVersion(homePathToUse); - return version == AbstractConfigUtils.UNDEFINED_VERSION - ? "" - : (bundled ? "Bundled " : "") + "Groovy " + version; - } + private static final Function MODULE_VERSION = module -> { + final String moduleGroovyHomePath = LibrariesUtil.getGroovyHomePath(module); + boolean bundled = moduleGroovyHomePath == null || !hasGroovyAll(module); + final String homePathToUse = bundled + ? GroovyFacetUtil.getBundledGroovyJar().getParentFile().getParent() + : moduleGroovyHomePath; + final String version = GroovyConfigUtils.getInstance().getSDKVersion(homePathToUse); + return version == AbstractConfigUtils.UNDEFINED_VERSION + ? "" + : (bundled ? "Bundled " : "") + "Groovy " + version; }; static boolean hasGroovyAll(Module module) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrExecuteCommandAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrExecuteCommandAction.java index b1f30abaf616..bc8b5abdf6cb 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrExecuteCommandAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrExecuteCommandAction.java @@ -47,12 +47,7 @@ public class GrExecuteCommandAction extends AnAction { final GroovyConsole existingConsole = virtualFile.getUserData(GroovyConsole.GROOVY_CONSOLE); if (existingConsole == null) { - GroovyConsole.getOrCreateConsole(project, virtualFile, new Consumer() { - @Override - public void consume(GroovyConsole console) { - console.execute(command); - } - }); + GroovyConsole.getOrCreateConsole(project, virtualFile, console -> console.execute(command)); } else { existingConsole.execute(command); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrSelectModuleAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrSelectModuleAction.java index dda0ec39a546..29082dd80ff5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrSelectModuleAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/actions/GrSelectModuleAction.java @@ -65,17 +65,14 @@ public class GrSelectModuleAction extends AnAction { public void actionPerformed(AnActionEvent e) { final Project project = e.getProject(); if (project == null) return; - GroovyConsoleUtil.selectModuleAndRun(project, new Consumer() { - @Override - public void consume(Module module) { - final Module existingModule = myProjectConsole.getSelectedModule(myFile); - if (module.equals(existingModule)) return; - final GroovyConsole existingConsole = myFile.getUserData(GroovyConsole.GROOVY_CONSOLE); - if (existingConsole != null) existingConsole.stop(); - myProjectConsole.setFileModule(myFile, module); - myFile.putUserData(GroovyConsole.GROOVY_CONSOLE, null); - ProjectView.getInstance(project).refresh(); - } + GroovyConsoleUtil.selectModuleAndRun(project, module -> { + final Module existingModule = myProjectConsole.getSelectedModule(myFile); + if (module.equals(existingModule)) return; + final GroovyConsole existingConsole = myFile.getUserData(GroovyConsole.GROOVY_CONSOLE); + if (existingConsole != null) existingConsole.stop(); + myProjectConsole.setFileModule(myFile, module); + myFile.putUserData(GroovyConsole.GROOVY_CONSOLE, null); + ProjectView.getInstance(project).refresh(); }, e.getDataContext()); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java index 9f732635fc46..ca820da03bc0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyCodeFragmentFactory.java @@ -80,11 +80,8 @@ public class GroovyCodeFragmentFactory extends CodeFragmentFactory { final Map parameters = pair.first; List names = new ArrayList(parameters.keySet()); - List values = ContainerUtil.map(names, new Function() { - @Override - public String fun(String name) { - return parameters.get(name); - } + List values = ContainerUtil.map(names, name -> { + return parameters.get(name); }); String text = toEval.getText(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMCompletionContributor.java index 16f71c77b922..663e8788a982 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMCompletionContributor.java @@ -61,12 +61,8 @@ public class DGMCompletionContributor extends CompletionContributor { PsiElement position = parameters.getPosition(); if (!DGMUtil.isInDGMFile(position)) return; - AllClassesGetter.processJavaClasses(parameters, result.getPrefixMatcher(), true, new Consumer() { - @Override - public void consume(PsiClass aClass) { - result.addElement(GroovyCompletionUtil.createClassLookupItem(aClass)); - } - }); + AllClassesGetter.processJavaClasses(parameters, result.getPrefixMatcher(), true, + aClass -> result.addElement(GroovyCompletionUtil.createClassLookupItem(aClass))); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/doc/actions/GenerateGroovyDocAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/doc/actions/GenerateGroovyDocAction.java index 17265e48a43b..1eba141d9040 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/doc/actions/GenerateGroovyDocAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/doc/actions/GenerateGroovyDocAction.java @@ -77,38 +77,35 @@ public final class GenerateGroovyDocAction extends AnAction implements DumbAware } private static void generateGroovydoc(final GroovyDocConfiguration configuration, final Project project) { - Runnable groovyDocRun = new Runnable() { - @Override - public void run() { - Groovydoc groovydoc = new Groovydoc(); - groovydoc.setProject(new org.apache.tools.ant.Project()); - groovydoc.setDestdir(new File(configuration.OUTPUT_DIRECTORY)); - groovydoc.setPrivate(configuration.OPTION_IS_PRIVATE); - groovydoc.setUse(configuration.OPTION_IS_USE); - groovydoc.setWindowtitle(configuration.WINDOW_TITLE); + Runnable groovyDocRun = () -> { + Groovydoc groovydoc = new Groovydoc(); + groovydoc.setProject(new org.apache.tools.ant.Project()); + groovydoc.setDestdir(new File(configuration.OUTPUT_DIRECTORY)); + groovydoc.setPrivate(configuration.OPTION_IS_PRIVATE); + groovydoc.setUse(configuration.OPTION_IS_USE); + groovydoc.setWindowtitle(configuration.WINDOW_TITLE); - final Path path = new Path(new org.apache.tools.ant.Project()); - path.setPath(configuration.INPUT_DIRECTORY); - groovydoc.setSourcepath(path); + final Path path = new Path(new org.apache.tools.ant.Project()); + path.setPath(configuration.INPUT_DIRECTORY); + groovydoc.setSourcepath(path); - String packages = ""; - for (int i = 0; i < configuration.PACKAGES.length; i++) { - final String s = configuration.PACKAGES[i]; - if (s != null && s.isEmpty()) continue; + String packages = ""; + for (int i = 0; i < configuration.PACKAGES.length; i++) { + final String s = configuration.PACKAGES[i]; + if (s != null && s.isEmpty()) continue; - if (i > 0) { - packages += ","; - } - - packages += s; + if (i > 0) { + packages += ","; } - groovydoc.setPackagenames(packages); - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - progressIndicator.setIndeterminate(true); - progressIndicator.setText(GroovyDocBundle.message("groovy.doc.progress.indication.text")); - groovydoc.execute(); + packages += s; } + groovydoc.setPackagenames(packages); + + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + progressIndicator.setIndeterminate(true); + progressIndicator.setText(GroovyDocBundle.message("groovy.doc.progress.indication.text")); + groovydoc.execute(); }; ProgressManager.getInstance() diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/GroovyImportOptimizer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/GroovyImportOptimizer.java index 3a9d5e109ada..8f2de561a4d0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/GroovyImportOptimizer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/GroovyImportOptimizer.java @@ -44,22 +44,19 @@ import java.util.*; public class GroovyImportOptimizer implements ImportOptimizer { public static Comparator getComparator(final GroovyCodeStyleSettings settings) { - return new Comparator() { - @Override - public int compare(GrImportStatement statement1, GrImportStatement statement2) { - if (settings.LAYOUT_STATIC_IMPORTS_SEPARATELY) { - if (statement1.isStatic() && !statement2.isStatic()) return 1; - if (statement2.isStatic() && !statement1.isStatic()) return -1; - } - - final GrCodeReferenceElement ref1 = statement1.getImportReference(); - final GrCodeReferenceElement ref2 = statement2.getImportReference(); - String name1 = ref1 != null ? PsiUtil.getQualifiedReferenceText(ref1) : null; - String name2 = ref2 != null ? PsiUtil.getQualifiedReferenceText(ref2) : null; - if (name1 == null) return name2 == null ? 0 : -1; - if (name2 == null) return 1; - return name1.compareTo(name2); + return (statement1, statement2) -> { + if (settings.LAYOUT_STATIC_IMPORTS_SEPARATELY) { + if (statement1.isStatic() && !statement2.isStatic()) return 1; + if (statement2.isStatic() && !statement1.isStatic()) return -1; } + + final GrCodeReferenceElement ref1 = statement1.getImportReference(); + final GrCodeReferenceElement ref2 = statement2.getImportReference(); + String name1 = ref1 != null ? PsiUtil.getQualifiedReferenceText(ref1) : null; + String name2 = ref2 != null ? PsiUtil.getQualifiedReferenceText(ref2) : null; + if (name1 == null) return name2 == null ? 0 : -1; + if (name2 == null) return 1; + return name1.compareTo(name2); }; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/blocks/GroovyBlockGenerator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/blocks/GroovyBlockGenerator.java index 4caff8fa37a3..a121d63c57a2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/blocks/GroovyBlockGenerator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/blocks/GroovyBlockGenerator.java @@ -498,11 +498,8 @@ public class GroovyBlockGenerator { GrStatement first = embedded ? inner : group.get(1); List alignments = ContainerUtil - .map2List(getSpockTable(first), new Function() { - @Override - public AlignmentProvider.Aligner fun(LeafPsiElement leaf) { - return myAlignmentProvider.createAligner(leaf, true, Alignment.Anchor.RIGHT); - } + .map2List(getSpockTable(first), leaf -> { + return myAlignmentProvider.createAligner(leaf, true, Alignment.Anchor.RIGHT); }); int second = embedded ? 1 : 2; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/gant/AntTasksProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/gant/AntTasksProvider.java index 84e50e7775b3..6181e03c352d 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/gant/AntTasksProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/gant/AntTasksProvider.java @@ -148,28 +148,25 @@ public class AntTasksProvider { public AntClassLoader(ArrayList urls) { super(build().urls(urls).allowUnescaped().noPreload()); - myFuture = ApplicationManager.getApplication().executeOnPooledThread(new Callable>() { - @Override - public Map call() throws Exception { - try { - final ReflectedProject antProject = ReflectedProject.getProject(AntClassLoader.this); - final Map result = new HashMap(); - if (antProject != null) { - final Map taskDefinitions = antProject.getTaskDefinitions(); - if (taskDefinitions != null) { - result.putAll(taskDefinitions); - } - final Map dataTypeDefinitions = antProject.getDataTypeDefinitions(); - if (dataTypeDefinitions != null) { - result.putAll(dataTypeDefinitions); - } + myFuture = ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + final ReflectedProject antProject = ReflectedProject.getProject(AntClassLoader.this); + final Map result = new HashMap(); + if (antProject != null) { + final Map taskDefinitions = antProject.getTaskDefinitions(); + if (taskDefinitions != null) { + result.putAll(taskDefinitions); + } + final Map dataTypeDefinitions = antProject.getDataTypeDefinitions(); + if (dataTypeDefinitions != null) { + result.putAll(dataTypeDefinitions); } - return result; - } - catch (Exception e) { - LOG.error(e); - return null; } + return result; + } + catch (Exception e) { + LOG.error(e); + return null; } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/grape/GrabDependencies.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/grape/GrabDependencies.java index ecbc76436191..fccc9101710c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/grape/GrabDependencies.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/grape/GrabDependencies.java @@ -124,18 +124,15 @@ public class GrabDependencies implements IntentionAction { PsiClass grab = JavaPsiFacade.getInstance(file.getProject()).findClass(GrabAnnos.GRAB_ANNO, file.getResolveScope()); final Ref result = Ref.create(); if (grab != null) { - ReferencesSearch.search(grab, new LocalSearchScope(file)).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - if (reference instanceof GrCodeReferenceElement) { - PsiElement parent = ((GrCodeReferenceElement)reference).getParent(); - if (parent instanceof PsiAnnotation) { - result.set((PsiAnnotation)parent); - return false; - } + ReferencesSearch.search(grab, new LocalSearchScope(file)).forEach(reference -> { + if (reference instanceof GrCodeReferenceElement) { + PsiElement parent = ((GrCodeReferenceElement)reference).getParent(); + if (parent instanceof PsiAnnotation) { + result.set((PsiAnnotation)parent); + return false; } - return true; } + return true; }); } return Result.create(result.get(), file); @@ -255,12 +252,7 @@ public class GrabDependencies implements IntentionAction { } }); - Function mapper = new Function() { - @Override - public String fun(GrAnnotation grAnnotation) { - return grAnnotation.getText(); - } - }; + Function mapper = grAnnotation -> grAnnotation.getText(); String common = StringUtil.join(excludes, mapper, " ") + " " + StringUtil.join(resolvers, mapper, " "); LinkedHashMap result = new LinkedHashMap(); for (GrAnnotation grab : grabs) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/IntentionUtils.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/IntentionUtils.java index 78c398d76465..b0691f4ceec4 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/IntentionUtils.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/IntentionUtils.java @@ -101,52 +101,49 @@ public class IntentionUtils { TemplateEditingListener templateListener = new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument()); - final int offset = newEditor.getCaretModel().getOffset(); - PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false); - if (context instanceof PsiMethod) { - final PsiTypeParameter[] typeParameters = ((PsiMethod)context).getTypeParameters(); - if (typeParameters.length > 0) { - for (PsiTypeParameter typeParameter : typeParameters) { - if (CreateMethodFromUsageFix.checkTypeParam(method, typeParameter)) { - final JVMElementFactory factory = JVMElementFactories.getFactory(method.getLanguage(), method.getProject()); - PsiTypeParameterList list = method.getTypeParameterList(); - if (list == null) { - PsiTypeParameterList newList = factory.createTypeParameterList(); - list = (PsiTypeParameterList)method.addAfter(newList, method.getModifierList()); - } - list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes())); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument()); + final int offset = newEditor.getCaretModel().getOffset(); + PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false); + if (context instanceof PsiMethod) { + final PsiTypeParameter[] typeParameters = ((PsiMethod)context).getTypeParameters(); + if (typeParameters.length > 0) { + for (PsiTypeParameter typeParameter : typeParameters) { + if (CreateMethodFromUsageFix.checkTypeParam(method1, typeParameter)) { + final JVMElementFactory factory = JVMElementFactories.getFactory(method1.getLanguage(), method1.getProject()); + PsiTypeParameterList list = method1.getTypeParameterList(); + if (list == null) { + PsiTypeParameterList newList = factory.createTypeParameterList(); + list = (PsiTypeParameterList)method1.addAfter(newList, method1.getModifierList()); } + list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes())); } } } - if (method != null) { - try { - final boolean hasNoReturnType = method.getReturnTypeElement() == null && method instanceof GrMethod; - if (hasNoReturnType) { - ((GrMethod)method).setReturnType(PsiType.VOID); - } - if (method.getBody() != null) { - FileTemplateManager templateManager = FileTemplateManager.getInstance(project); - FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY); - - PsiClass containingClass = method.getContainingClass(); - LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up"); - CreateFromUsageUtils.setupMethodBody(method, containingClass, fileTemplate); - } - if (hasNoReturnType) { - ((GrMethod)method).setReturnType(null); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); + } + if (method1 != null) { + try { + final boolean hasNoReturnType = method1.getReturnTypeElement() == null && method1 instanceof GrMethod; + if (hasNoReturnType) { + ((GrMethod)method1).setReturnType(PsiType.VOID); } + if (method1.getBody() != null) { + FileTemplateManager templateManager = FileTemplateManager.getInstance(project); + FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY); - CreateFromUsageUtils.setupEditor(method, newEditor); + PsiClass containingClass = method1.getContainingClass(); + LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up"); + CreateFromUsageUtils.setupMethodBody(method1, containingClass, fileTemplate); + } + if (hasNoReturnType) { + ((GrMethod)method1).setReturnType(null); + } } + catch (IncorrectOperationException e) { + LOG.error(e); + } + + CreateFromUsageUtils.setupEditor(method1, newEditor); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/CreateParameterForFieldIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/CreateParameterForFieldIntention.java index da4dbf8a7542..1d756905fa5d 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/CreateParameterForFieldIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/CreateParameterForFieldIntention.java @@ -103,26 +103,15 @@ public class CreateParameterForFieldIntention extends Intention { new PopupChooserBuilder(list).setTitle(GroovyIntentionsBundle.message("create.parameter.for.field.intention.name")). setMovable(true). - setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object[] selectedValues = list.getSelectedValues(); - Arrays.sort(selectedValues, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return ((GrMethod)o2).getParameterList().getParametersCount() - ((GrMethod)o1).getParameterList().getParametersCount(); - } - }); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - for (Object selectedValue : selectedValues) { - LOG.assertTrue(((GrMethod)selectedValue).isValid()); - addParameter(field, ((GrMethod)selectedValue), project); - } - } - }, GroovyIntentionsBundle.message("create.parameter.for.field.intention.name"), null); - } + setItemChoosenCallback(() -> { + final Object[] selectedValues = list.getSelectedValues(); + Arrays.sort(selectedValues, (o1, o2) -> ((GrMethod)o2).getParameterList().getParametersCount() - ((GrMethod)o1).getParameterList().getParametersCount()); + CommandProcessor.getInstance().executeCommand(project, () -> { + for (Object selectedValue : selectedValues) { + LOG.assertTrue(((GrMethod)selectedValue).isValid()); + addParameter(field, ((GrMethod)selectedValue), project); + } + }, GroovyIntentionsBundle.message("create.parameter.for.field.intention.name"), null); }).createPopup().showInBestPositionFor(editor); } @@ -140,20 +129,14 @@ public class CreateParameterForFieldIntention extends Intention { new PopupChooserBuilder(list).setTitle(GroovyIntentionsBundle.message("create.parameter.for.field.intention.name")). setMovable(true). - setItemChoosenCallback(new Runnable() { - @Override - public void run() { - final Object[] selectedValues = list.getSelectedValues(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - for (Object selectedValue : selectedValues) { - LOG.assertTrue(((GrField)selectedValue).isValid()); - addParameter(((GrField)selectedValue), constructor, project); - } - } - }, GroovyIntentionsBundle.message("create.parameter.for.field.intention.name"), null); - } + setItemChoosenCallback(() -> { + final Object[] selectedValues = list.getSelectedValues(); + CommandProcessor.getInstance().executeCommand(project, () -> { + for (Object selectedValue : selectedValues) { + LOG.assertTrue(((GrField)selectedValue).isValid()); + addParameter(((GrField)selectedValue), constructor, project); + } + }, GroovyIntentionsBundle.message("create.parameter.for.field.intention.name"), null); }).createPopup().showInBestPositionFor(editor); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertClosureToMethodIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertClosureToMethodIntention.java index 9e5c37a62772..683a0bbff81e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertClosureToMethodIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertClosureToMethodIntention.java @@ -133,12 +133,7 @@ public class ConvertClosureToMethodIntention extends Intention { } } if (!conflicts.isEmpty()) { - final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, new Runnable() { - @Override - public void run() { - execute(field, fieldUsages); - } - }); + final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, () -> execute(field, fieldUsages)); conflictsDialog.show(); if (conflictsDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return; } @@ -170,50 +165,47 @@ public class ConvertClosureToMethodIntention extends Intention { builder.append(") {"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - block.getParameterList().delete(); - block.getLBrace().delete(); - final PsiElement psiElement = PsiUtil.skipWhitespacesAndComments(block.getFirstChild(), true); - if (psiElement != null && "->".equals(psiElement.getText())) { - psiElement.delete(); - } - builder.append(block.getText()); - final GrMethod method = GroovyPsiElementFactory.getInstance(field.getProject()).createMethodFromText(builder.toString()); - field.getParent().replace(method); - for (PsiElement usage : fieldUsages) { - if (usage instanceof GrReferenceExpression) { - final PsiElement parent = usage.getParent(); - StringBuilder newRefText = new StringBuilder(); - if (parent instanceof GrReferenceExpression && - usage == ((GrReferenceExpression)parent).getQualifier() && - "call".equals(((GrReferenceExpression)parent).getReferenceName())) { - newRefText.append(usage.getText()); - usage = parent; + ApplicationManager.getApplication().runWriteAction(() -> { + block.getParameterList().delete(); + block.getLBrace().delete(); + final PsiElement psiElement = PsiUtil.skipWhitespacesAndComments(block.getFirstChild(), true); + if (psiElement != null && "->".equals(psiElement.getText())) { + psiElement.delete(); + } + builder.append(block.getText()); + final GrMethod method = GroovyPsiElementFactory.getInstance(field.getProject()).createMethodFromText(builder.toString()); + field.getParent().replace(method); + for (PsiElement usage : fieldUsages) { + if (usage instanceof GrReferenceExpression) { + final PsiElement parent = usage.getParent(); + StringBuilder newRefText = new StringBuilder(); + if (parent instanceof GrReferenceExpression && + usage == ((GrReferenceExpression)parent).getQualifier() && + "call".equals(((GrReferenceExpression)parent).getReferenceName())) { + newRefText.append(usage.getText()); + usage = parent; + } + else { + PsiElement qualifier = ((GrReferenceExpression)usage).getQualifier(); + if (qualifier == null) { + if (parent instanceof GrReferenceExpression && + ((GrReferenceExpression)parent).getQualifier() != null && + usage != ((GrReferenceExpression)parent).getQualifier()) { + qualifier = ((GrReferenceExpression)parent).getQualifier(); + usage = parent; + } + } + + if (qualifier != null) { + newRefText.append(qualifier.getText()).append('.'); + ((GrReferenceExpression)usage).setQualifier(null); } else { - PsiElement qualifier = ((GrReferenceExpression)usage).getQualifier(); - if (qualifier == null) { - if (parent instanceof GrReferenceExpression && - ((GrReferenceExpression)parent).getQualifier() != null && - usage != ((GrReferenceExpression)parent).getQualifier()) { - qualifier = ((GrReferenceExpression)parent).getQualifier(); - usage = parent; - } - } - - if (qualifier != null) { - newRefText.append(qualifier.getText()).append('.'); - ((GrReferenceExpression)usage).setQualifier(null); - } - else { - newRefText.append("this."); - } - newRefText.append('&').append(usage.getText()); + newRefText.append("this."); } - usage.replace(factory.createReferenceExpressionFromText(newRefText.toString())); + newRefText.append('&').append(usage.getText()); } + usage.replace(factory.createReferenceExpressionFromText(newRefText.toString())); } } }); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertMethodToClosureIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertMethodToClosureIntention.java index 2f3087ec33b8..f6a8d3b056a3 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertMethodToClosureIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/ConvertMethodToClosureIntention.java @@ -98,12 +98,7 @@ public class ConvertMethodToClosureIntention extends Intention { } } if (!conflicts.isEmpty()) { - ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, new Runnable() { - @Override - public void run() { - execute(method, usagesToConvert); - } - }); + ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, () -> execute(method, usagesToConvert)); conflictsDialog.show(); if (conflictsDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return; } @@ -111,32 +106,29 @@ public class ConvertMethodToClosureIntention extends Intention { } private static void execute(final GrMethod method, final Collection usagesToConvert) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(method.getProject()); + ApplicationManager.getApplication().runWriteAction(() -> { + GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(method.getProject()); - StringBuilder builder = new StringBuilder(method.getTextLength()); - String modifiers = method.getModifierList().getText(); - if (modifiers.trim().isEmpty()) { - modifiers = GrModifier.DEF; - } - builder.append(modifiers).append(' '); - builder.append(method.getName()).append("={"); - builder.append(method.getParameterList().getText()).append(" ->"); - final GrOpenBlock block = method.getBlock(); - builder.append(block.getText().substring(1)); - final GrVariableDeclaration variableDeclaration = - GroovyPsiElementFactory.getInstance(method.getProject()).createFieldDeclarationFromText(builder.toString()); - method.replace(variableDeclaration); + StringBuilder builder = new StringBuilder(method.getTextLength()); + String modifiers = method.getModifierList().getText(); + if (modifiers.trim().isEmpty()) { + modifiers = GrModifier.DEF; + } + builder.append(modifiers).append(' '); + builder.append(method.getName()).append("={"); + builder.append(method.getParameterList().getText()).append(" ->"); + final GrOpenBlock block = method.getBlock(); + builder.append(block.getText().substring(1)); + final GrVariableDeclaration variableDeclaration = + GroovyPsiElementFactory.getInstance(method.getProject()).createFieldDeclarationFromText(builder.toString()); + method.replace(variableDeclaration); - for (GrReferenceExpression element : usagesToConvert) { - final PsiElement qualifier = element.getQualifier(); - final StringBuilder text = new StringBuilder(qualifier.getText()); - element.setQualifier(null); - text.append('.').append(element.getText()); - element.replace(factory.createExpressionFromText(text.toString())); - } + for (GrReferenceExpression element : usagesToConvert) { + final PsiElement qualifier = element.getQualifier(); + final StringBuilder text = new StringBuilder(qualifier.getText()); + element.setQualifier(null); + text.append('.').append(element.getText()); + element.replace(factory.createExpressionFromText(text.toString())); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertConcatenationToGstringIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertConcatenationToGstringIntention.java index 1ed3954cb516..8aef181964e5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertConcatenationToGstringIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertConcatenationToGstringIntention.java @@ -123,12 +123,7 @@ public class ConvertConcatenationToGstringIntention extends Intention { invokeImpl(selectedValue, document); } }, - new Function() { - @Override - public String fun(GrExpression grExpression) { - return grExpression.getText(); - } - } + grExpression -> grExpression.getText() ); } } @@ -151,20 +146,17 @@ public class ConvertConcatenationToGstringIntention extends Intention { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject()); final GrExpression newExpr = factory.createExpressionFromText(GrStringUtil.addQuotes(text, true)); - CommandProcessor.getInstance().executeCommand(element.getProject(), new Runnable() { - @Override - public void run() { - final AccessToken accessToken = WriteAction.start(); - try { - final GrExpression expression = ((GrExpression)element).replaceWithExpression(newExpr, true); - if (expression instanceof GrString) { - GrStringUtil.removeUnnecessaryBracesInGString((GrString)expression); - } - } - finally { - accessToken.finish(); + CommandProcessor.getInstance().executeCommand(element.getProject(), () -> { + final AccessToken accessToken = WriteAction.start(); + try { + final GrExpression expression = ((GrExpression)element).replaceWithExpression(newExpr, true); + if (expression instanceof GrString) { + GrStringUtil.removeUnnecessaryBracesInGString((GrString)expression); } } + finally { + accessToken.finish(); + } }, null, null, document); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertStringToMultilineIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertStringToMultilineIntention.java index ab256f8a31a3..3c1766ccb2e2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertStringToMultilineIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertStringToMultilineIntention.java @@ -87,12 +87,7 @@ public class ConvertStringToMultilineIntention extends Intention { invokeImpl(selectedValue, project, editor); } }; - final Function renderer = new Function() { - @Override - public String fun(@NotNull GrExpression grExpression) { - return grExpression.getText(); - } - }; + final Function renderer = grExpression -> grExpression.getText(); IntroduceTargetChooser.showChooser(editor, expressions, callback, renderer); } } @@ -162,44 +157,36 @@ public class ConvertStringToMultilineIntention extends Intention { final StringBuilder buffer = prepareNewLiteralText(literals); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - final int offset = editor.getCaretModel().getOffset(); - final TextRange range = element.getTextRange(); - int shift; - if (editor.getSelectionModel().hasSelection()) { - shift = 0; - } - else if (range.getStartOffset() == offset) { - shift = 0; - } - else if (range.getEndOffset() == offset + 1) { - shift = -2; - } - else { - shift = 2; - } + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + final int offset = editor.getCaretModel().getOffset(); + final TextRange range = element.getTextRange(); + int shift; + if (editor.getSelectionModel().hasSelection()) { + shift = 0; + } + else if (range.getStartOffset() == offset) { + shift = 0; + } + else if (range.getEndOffset() == offset + 1) { + shift = -2; + } + else { + shift = 2; + } - final GrExpression newLiteral = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(buffer.toString()); + final GrExpression newLiteral = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(buffer.toString()); - element.replaceWithExpression(newLiteral, true); + element.replaceWithExpression(newLiteral, true); - if (shift != 0) { - editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + shift); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + if (shift != 0) { + editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + shift); + } } - }, getText(), null); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), getText(), null); } private static StringBuilder prepareNewLiteralText(List literals) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrCreateSubclassAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrCreateSubclassAction.java index c0e43ab9a353..b850a73187ca 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrCreateSubclassAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrCreateSubclassAction.java @@ -86,14 +86,10 @@ public class GrCreateSubclassAction extends CreateSubclassAction { targetClass.set(CreateClassActionBase.createClassByType(targetDirectory, className, PsiManager.getInstance(project), psiClass, GroovyTemplates.GROOVY_CLASS, true)); } catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(project, CodeInsightBundle.message("intention.error.cannot.create.class.message", className) + - "\n" + e.getLocalizedMessage(), - CodeInsightBundle.message("intention.error.cannot.create.class.title")); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(project, CodeInsightBundle.message("intention.error.cannot.create.class.message", className) + + "\n" + e.getLocalizedMessage(), + CodeInsightBundle.message("intention.error.cannot.create.class.title"))); return; } startTemplate(oldTypeParameterList, project, psiClass, targetClass.get(), false); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrSetStrongTypeIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrSetStrongTypeIntention.java index c768d2a2ddf2..bb1e9771b5da 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrSetStrongTypeIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/declaration/GrSetStrongTypeIntention.java @@ -143,13 +143,10 @@ public class GrSetStrongTypeIntention extends Intention { @Override public void templateFinished(Template template, boolean brokenOff) { if (brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (rangeMarker.isValid()) { - document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText); - editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (rangeMarker.isValid()) { + document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText); + editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java index 20e8986e628f..67b564ac3623 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrAliasImportIntention.java @@ -166,11 +166,8 @@ public class GrAliasImportIntention extends Intention { if (brokenOff) { if (importStatement != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - importStatement.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + importStatement.delete(); }); } return; @@ -178,15 +175,12 @@ public class GrAliasImportIntention extends Intention { updateRefs(usages, name, importStatement); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final GrImportStatement context = PsiTreeUtil.findElementOfClassAtRange(file, contextImportPointer.getStartOffset(), - contextImportPointer.getEndOffset(), - GrImportStatement.class); - if (context != null) { - context.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final GrImportStatement context1 = PsiTreeUtil.findElementOfClassAtRange(file, contextImportPointer.getStartOffset(), + contextImportPointer.getEndOffset(), + GrImportStatement.class); + if (context1 != null) { + context1.delete(); } }); } @@ -206,46 +200,43 @@ public class GrAliasImportIntention extends Intention { }); for (final UsageInfo usage : usages) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final PsiElement usageElement = usage.getElement(); - if (usageElement == null) return; + ApplicationManager.getApplication().runWriteAction(() -> { + final PsiElement usageElement = usage.getElement(); + if (usageElement == null) return; - if (usageElement.getParent() instanceof GrImportStatement) return; + if (usageElement.getParent() instanceof GrImportStatement) return; - if (usageElement instanceof GrReferenceElement) { - final GrReferenceElement ref = (GrReferenceElement)usageElement; - final PsiElement qualifier = ref.getQualifier(); + if (usageElement instanceof GrReferenceElement) { + final GrReferenceElement ref = (GrReferenceElement)usageElement; + final PsiElement qualifier = ref.getQualifier(); - if (qualifier == null) { - final String refName = ref.getReferenceName(); - if (refName == null) return; + if (qualifier == null) { + final String refName = ref.getReferenceName(); + if (refName == null) return; - if (memberName.equals(refName)) { + if (memberName.equals(refName)) { + ref.handleElementRenameSimple(name); + } + else if (refName.equals(GroovyPropertyUtils.getPropertyNameByAccessorName(memberName))) { + final String newPropName = GroovyPropertyUtils.getPropertyNameByAccessorName(name); + if (newPropName != null) { + ref.handleElementRenameSimple(newPropName); + } + else { ref.handleElementRenameSimple(name); } - else if (refName.equals(GroovyPropertyUtils.getPropertyNameByAccessorName(memberName))) { - final String newPropName = GroovyPropertyUtils.getPropertyNameByAccessorName(name); - if (newPropName != null) { - ref.handleElementRenameSimple(newPropName); - } - else { - ref.handleElementRenameSimple(name); - } - } - else if (refName.equals(GroovyPropertyUtils.getGetterNameBoolean(memberName))) { - final String getterName = GroovyPropertyUtils.getGetterNameBoolean(name); - ref.handleElementRenameSimple(getterName); - } - else if (refName.equals(GroovyPropertyUtils.getGetterNameNonBoolean(memberName))) { - final String getterName = GroovyPropertyUtils.getGetterNameNonBoolean(name); - ref.handleElementRenameSimple(getterName); - } - else if (refName.equals(GroovyPropertyUtils.getSetterName(memberName))) { - final String getterName = GroovyPropertyUtils.getSetterName(name); - ref.handleElementRenameSimple(getterName); - } + } + else if (refName.equals(GroovyPropertyUtils.getGetterNameBoolean(memberName))) { + final String getterName = GroovyPropertyUtils.getGetterNameBoolean(name); + ref.handleElementRenameSimple(getterName); + } + else if (refName.equals(GroovyPropertyUtils.getGetterNameNonBoolean(memberName))) { + final String getterName = GroovyPropertyUtils.getGetterNameNonBoolean(name); + ref.handleElementRenameSimple(getterName); + } + else if (refName.equals(GroovyPropertyUtils.getSetterName(memberName))) { + final String getterName = GroovyPropertyUtils.getSetterName(name); + ref.handleElementRenameSimple(getterName); } } } @@ -259,15 +250,12 @@ public class GrAliasImportIntention extends Intention { final ArrayList infos = new ArrayList(); final HashSet usedRefs = ContainerUtil.newHashSet(); - final Processor consumer = new Processor() { - @Override - public boolean process(PsiReference reference) { - if (usedRefs.add(reference)) { - infos.add(new UsageInfo(reference)); - } - - return true; + final Processor consumer = reference -> { + if (usedRefs.add(reference)) { + infos.add(new UsageInfo(reference)); } + + return true; }; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrSortMapKeysIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrSortMapKeysIntention.java index af795cc1a9fb..55ff0739cde2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrSortMapKeysIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/other/GrSortMapKeysIntention.java @@ -63,15 +63,12 @@ public class GrSortMapKeysIntention extends Intention { builder.append("["); - Arrays.sort(args, new Comparator() { - @Override - public int compare(GrNamedArgument o1, GrNamedArgument o2) { - final String l1 = o1.getLabelName(); - final String l2 = o2.getLabelName(); - assert l1 != null && l2 != null; + Arrays.sort(args, (o1, o2) -> { + final String l1 = o1.getLabelName(); + final String l2 = o2.getLabelName(); + assert l1 != null && l2 != null; - return l1.compareTo(l2); - } + return l1.compareTo(l2); }); for (GrNamedArgument arg : args) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java index af885a164d96..31dc674931dd 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/parameterToEntry/ConvertParameterToMapEntryIntention.java @@ -173,11 +173,8 @@ public class ConvertParameterToMapEntryIntention extends Intention { } private static String[] generateValidNames(final String[] names, final GrParameter param) { - return ContainerUtil.map2Array(names, String.class, new Function() { - @Override - public String fun(final String s) { - return (new GroovyValidationUtil.ParameterNameSuggester(s, param)).generateName(); - } + return ContainerUtil.map2Array(names, String.class, s -> { + return (new GroovyValidationUtil.ParameterNameSuggester(s, param)).generateName(); }); } @@ -194,149 +191,138 @@ public class ConvertParameterToMapEntryIntention extends Intention { final Project project = element.getProject(); - final Runnable runnable = new Runnable() { - @Override - public void run() { - final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); + final Runnable runnable = () -> { + final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); - final GrParameterList list = owner.getParameterList(); - assert list != null; - final int index = list.getParameterNumber(param); - if (!createNewFirstParam && index <= 0) { // bad undo - return; - } + final GrParameterList list = owner.getParameterList(); + assert list != null; + final int index = list.getParameterNumber(param); + if (!createNewFirstParam && index <= 0) { // bad undo + return; + } - //Remove old arguments from occurrences - //final List calls = getCallOccurrences(occurrences); - try { - for (PsiElement occurrence : occurrences) { - GrReferenceExpression refExpr = null; - GroovyResolveResult resolveResult = null; - boolean isExplicitGetterCall = false; - if (occurrence instanceof GrReferenceExpression) { - final PsiElement parent = occurrence.getParent(); - if (parent instanceof GrCall) { - refExpr = (GrReferenceExpression)occurrence; - resolveResult = refExpr.advancedResolve(); - final PsiElement resolved = resolveResult.getElement(); - if (resolved instanceof PsiMethod && - GroovyPropertyUtils.isSimplePropertyGetter(((PsiMethod)resolved)) && - //check for explicit getter call - ((PsiMethod)resolved).getName().equals(refExpr.getReferenceName())) { - isExplicitGetterCall = true; - } - } - else if (parent instanceof GrReferenceExpression) { - resolveResult = ((GrReferenceExpression)parent).advancedResolve(); - final PsiElement resolved = resolveResult.getElement(); - if (resolved instanceof PsiMethod && "call".equals(((PsiMethod)resolved).getName())) { - refExpr = (GrReferenceExpression)parent; - } + //Remove old arguments from occurrences + //final List calls = getCallOccurrences(occurrences); + try { + for (PsiElement occurrence : occurrences) { + GrReferenceExpression refExpr = null; + GroovyResolveResult resolveResult = null; + boolean isExplicitGetterCall = false; + if (occurrence instanceof GrReferenceExpression) { + final PsiElement parent = occurrence.getParent(); + if (parent instanceof GrCall) { + refExpr = (GrReferenceExpression)occurrence; + resolveResult = refExpr.advancedResolve(); + final PsiElement resolved = resolveResult.getElement(); + if (resolved instanceof PsiMethod && + GroovyPropertyUtils.isSimplePropertyGetter(((PsiMethod)resolved)) && + //check for explicit getter call + ((PsiMethod)resolved).getName().equals(refExpr.getReferenceName())) { + isExplicitGetterCall = true; } } - if (refExpr == null) continue; - final GrClosureSignature signature = generateSignature(owner, refExpr); - if (signature == null) continue; - GrCall call; - if (isExplicitGetterCall) { - PsiElement parent = refExpr.getParent(); - LOG.assertTrue(parent instanceof GrCall); - parent = parent.getParent(); - if (parent instanceof GrReferenceExpression && "call".equals(((GrReferenceExpression)parent).getReferenceName())) { - parent = parent.getParent(); + else if (parent instanceof GrReferenceExpression) { + resolveResult = ((GrReferenceExpression)parent).advancedResolve(); + final PsiElement resolved = resolveResult.getElement(); + if (resolved instanceof PsiMethod && "call".equals(((PsiMethod)resolved).getName())) { + refExpr = (GrReferenceExpression)parent; } - if (parent instanceof GrCall) { - call = (GrCall)parent; + } + } + if (refExpr == null) continue; + final GrClosureSignature signature = generateSignature(owner, refExpr); + if (signature == null) continue; + GrCall call; + if (isExplicitGetterCall) { + PsiElement parent = refExpr.getParent(); + LOG.assertTrue(parent instanceof GrCall); + parent = parent.getParent(); + if (parent instanceof GrReferenceExpression && "call".equals(((GrReferenceExpression)parent).getReferenceName())) { + parent = parent.getParent(); + } + if (parent instanceof GrCall) { + call = (GrCall)parent; + } + else { + continue; + } + } + else { + call = (GrCall)refExpr.getParent(); + } + + if (resolveResult.isInvokedOnProperty()) { + final PsiElement parent = call.getParent(); + if (parent instanceof GrCall) { + call = (GrCall)parent; + } + else if (parent instanceof GrReferenceExpression && parent.getParent() instanceof GrCall) { + final PsiElement resolved = ((GrReferenceExpression)parent).resolve(); + if (resolved instanceof PsiMethod && "call".equals(((PsiMethod)resolved).getName())) { + call = (GrCall)parent.getParent(); } else { continue; } } - else { - call = (GrCall)refExpr.getParent(); - } - - if (resolveResult.isInvokedOnProperty()) { - final PsiElement parent = call.getParent(); - if (parent instanceof GrCall) { - call = (GrCall)parent; - } - else if (parent instanceof GrReferenceExpression && parent.getParent() instanceof GrCall) { - final PsiElement resolved = ((GrReferenceExpression)parent).resolve(); - if (resolved instanceof PsiMethod && "call".equals(((PsiMethod)resolved).getName())) { - call = (GrCall)parent.getParent(); - } - else { - continue; - } - } - } - - final GrClosureSignatureUtil.ArgInfo[] argInfos = GrClosureSignatureUtil.mapParametersToArguments(signature, call); - if (argInfos == null) continue; - final GrClosureSignatureUtil.ArgInfo argInfo = argInfos[index]; - - final GrNamedArgument namedArg; - if (argInfo.isMultiArg) { - if (argInfo.args.isEmpty()) continue; - String arg = "[" + StringUtil.join(ContainerUtil.map(argInfo.args, new Function() { - @Override - public String fun(PsiElement element) { - return element.getText(); - } - }), ", ") + "]"; - for (PsiElement psiElement : argInfo.args) { - psiElement.delete(); - } - namedArg = factory.createNamedArgument(paramName, factory.createExpressionFromText(arg)); - } - else { - if (argInfo.args.isEmpty()) continue; - final PsiElement argument = argInfo.args.iterator().next(); - assert argument instanceof GrExpression; - namedArg = factory.createNamedArgument(paramName, (GrExpression)argument); - argument.delete(); - } - call.addNamedArgument(namedArg); } + + final GrClosureSignatureUtil.ArgInfo[] argInfos = GrClosureSignatureUtil.mapParametersToArguments(signature, call); + if (argInfos == null) continue; + final GrClosureSignatureUtil.ArgInfo argInfo = argInfos[index]; + + final GrNamedArgument namedArg; + if (argInfo.isMultiArg) { + if (argInfo.args.isEmpty()) continue; + String arg = "[" + StringUtil.join(ContainerUtil.map(argInfo.args, element1 -> { + return element1.getText(); + }), ", ") + "]"; + for (PsiElement psiElement : argInfo.args) { + psiElement.delete(); + } + namedArg = factory.createNamedArgument(paramName, factory.createExpressionFromText(arg)); + } + else { + if (argInfo.args.isEmpty()) continue; + final PsiElement argument = argInfo.args.iterator().next(); + assert argument instanceof GrExpression; + namedArg = factory.createNamedArgument(paramName, (GrExpression)argument); + argument.delete(); + } + call.addNamedArgument(namedArg); + } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + + //Replace of occurrences of old parameter in closure/method + final Collection references = ReferencesSearch.search(param).findAll(); + for (PsiReference ref : references) { + final PsiElement elt = ref.getElement(); + if (elt instanceof GrReferenceExpression) { + GrReferenceExpression expr = (GrReferenceExpression)elt; + final GrExpression newExpr = factory.createExpressionFromText(mapName + "." + paramName); + expr.replaceWithExpression(newExpr, true); + } + } + + //Add new map parameter to closure/method if it's necessary + if (createNewFirstParam) { + try { + final GrParameter newParam = factory.createParameter(mapName, specifyMapType ? MAP_TYPE_TEXT : "", null); + list.addAfter(newParam, null); } catch (IncorrectOperationException e) { LOG.error(e); } - - //Replace of occurrences of old parameter in closure/method - final Collection references = ReferencesSearch.search(param).findAll(); - for (PsiReference ref : references) { - final PsiElement elt = ref.getElement(); - if (elt instanceof GrReferenceExpression) { - GrReferenceExpression expr = (GrReferenceExpression)elt; - final GrExpression newExpr = factory.createExpressionFromText(mapName + "." + paramName); - expr.replaceWithExpression(newExpr, true); - } - } - - //Add new map parameter to closure/method if it's necessary - if (createNewFirstParam) { - try { - final GrParameter newParam = factory.createParameter(mapName, specifyMapType ? MAP_TYPE_TEXT : "", null); - list.addAfter(newParam, null); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - - //Eliminate obsolete parameter from parameter list - param.delete(); } + + //Eliminate obsolete parameter from parameter list + param.delete(); }; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(runnable); - } - }, REFACTORING_NAME, null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(runnable), REFACTORING_NAME, null); } @@ -452,12 +438,9 @@ public class ConvertParameterToMapEntryIntention extends Intention { @Override public void run(@NotNull final ProgressIndicator indicator) { final Collection references = Collections.synchronizedSet(new HashSet()); - final Processor consumer = new Processor() { - @Override - public boolean process(PsiReference psiReference) { - references.add(psiReference); - return true; - } + final Processor consumer = psiReference -> { + references.add(psiReference); + return true; }; ReferencesSearch.search(namedElem).forEach(consumer); boolean isProperty = ApplicationManager.getApplication().runReadAction(new Computable() { @@ -478,13 +461,10 @@ public class ConvertParameterToMapEntryIntention extends Intention { } } for (final PsiReference reference : references) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiElement element = reference.getElement(); - if (element != null) { - occurrences.add(element); - } + ApplicationManager.getApplication().runReadAction(() -> { + final PsiElement element = reference.getElement(); + if (element != null) { + occurrences.add(element); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/ClosureCompleter.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/ClosureCompleter.java index 64e2c6675990..72649a235e16 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/ClosureCompleter.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/ClosureCompleter.java @@ -155,23 +155,20 @@ public abstract class ClosureCompleter { TemplateEditingListener templateListener = new TemplateEditingAdapter() { @Override public void templateFinished(Template template, boolean brokenOff) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiDocumentManager.getInstance(project).commitDocument(document); - final CaretModel caretModel = editor.getCaretModel(); - final int offset = caretModel.getOffset(); - GrClosableBlock block = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, GrClosableBlock.class, false); - if (block != null) { - final PsiElement arrow = block.getArrow(); - if (arrow != null) { - caretModel.moveToOffset(arrow.getTextRange().getEndOffset()); - } - - // fix space before closure lbrace - final TextRange range = block.getTextRange(); - CodeStyleManager.getInstance(project).reformatRange(block.getParent(), range.getStartOffset() - 1, range.getEndOffset(), true); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(project).commitDocument(document); + final CaretModel caretModel = editor.getCaretModel(); + final int offset = caretModel.getOffset(); + GrClosableBlock block1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, GrClosableBlock.class, false); + if (block1 != null) { + final PsiElement arrow = block1.getArrow(); + if (arrow != null) { + caretModel.moveToOffset(arrow.getTextRange().getEndOffset()); } + + // fix space before closure lbrace + final TextRange range1 = block1.getTextRange(); + CodeStyleManager.getInstance(project).reformatRange(block1.getParent(), range1.getStartOffset() - 1, range1.getEndOffset(), true); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/CompleteReferenceExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/CompleteReferenceExpression.java index d1175f8d1ac8..86834222a417 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/CompleteReferenceExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/CompleteReferenceExpression.java @@ -409,12 +409,9 @@ public class CompleteReferenceExpression { protected CompleteReferenceProcessor() { super(null, EnumSet.allOf(DeclarationKind.class), myRefExpr, PsiType.EMPTY_ARRAY); - myConsumer = new Consumer() { - @Override - public void consume(LookupElement element) { - myIsEmpty = false; - CompleteReferenceExpression.this.myConsumer.consume(element); - } + myConsumer = element -> { + myIsEmpty = false; + CompleteReferenceExpression.this.myConsumer.consume(element); }; myPreferredFieldNames = addAllRestrictedProperties(); mySkipPackages = shouldSkipPackages(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GrMainCompletionProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GrMainCompletionProvider.java index 6dc725bb2617..1bf77892bd82 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GrMainCompletionProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GrMainCompletionProvider.java @@ -173,18 +173,15 @@ public class GrMainCompletionProvider extends CompletionProvider() { - @Override - public void consume(PsiClass psiClass) { - for (JavaPsiClassReferenceElement element : JavaClassNameCompletionContributor - .createClassLookupItems(psiClass, afterNew, new GroovyClassNameInsertHandler(), new Condition() { - @Override - public boolean value(PsiClass psiClass) { - return !inheritors.alreadyProcessed(psiClass); - } - })) { - consumer.consume(element); - } + AllClassesGetter.processJavaClasses(parameters, matcher, parameters.getInvocationCount() <= 1, psiClass -> { + for (JavaPsiClassReferenceElement element : JavaClassNameCompletionContributor + .createClassLookupItems(psiClass, afterNew, new GroovyClassNameInsertHandler(), new Condition() { + @Override + public boolean value(PsiClass psiClass) { + return !inheritors.alreadyProcessed(psiClass); + } + })) { + consumer.consume(element); } }); } @@ -227,45 +224,42 @@ public class GrMainCompletionProvider extends CompletionProvider() { - @Override - public void consume(LookupElement lookupElement) { - Object object = lookupElement.getObject(); - if (object instanceof GroovyResolveResult) { - object = ((GroovyResolveResult)object).getElement(); - } + GroovyCompletionUtil.processVariants(reference, matcher, parameters, lookupElement -> { + Object object = lookupElement.getObject(); + if (object instanceof GroovyResolveResult) { + object = ((GroovyResolveResult)object).getElement(); + } - if (isLightElementDeclaredDuringCompletion(object)) { - return; - } + if (isLightElementDeclaredDuringCompletion(object)) { + return; + } - if (!(lookupElement instanceof LookupElementBuilder) && inheritorsHolder.alreadyProcessed(lookupElement)) { - return; - } + if (!(lookupElement instanceof LookupElementBuilder) && inheritorsHolder.alreadyProcessed(lookupElement)) { + return; + } - if (honorExcludes && object instanceof PsiMember && JavaCompletionUtil.isInExcludedPackage((PsiMember)object, true)) { - return; - } + if (honorExcludes && object instanceof PsiMember && JavaCompletionUtil.isInExcludedPackage((PsiMember)object, true)) { + return; + } - if (!(object instanceof PsiClass)) { - int priority = assignPriority(lookupElement, qualifierType); - lookupElement = JavaCompletionUtil.highlightIfNeeded(qualifierType, - PrioritizedLookupElement.withPriority(lookupElement, priority), object, reference); - } + if (!(object instanceof PsiClass)) { + int priority = assignPriority(lookupElement, qualifierType); + lookupElement = JavaCompletionUtil.highlightIfNeeded(qualifierType, + PrioritizedLookupElement.withPriority(lookupElement, priority), object, reference); + } - if ((object instanceof PsiMethod || object instanceof PsiField) && - ((PsiModifierListOwner)object).hasModifierProperty(PsiModifier.STATIC)) { - if (lookupElement.getLookupString().equals(((PsiMember)object).getName())) { - staticMembers.put(CompletionUtil.getOriginalOrSelf((PsiModifierListOwner)object), lookupElement); - } + if ((object instanceof PsiMethod || object instanceof PsiField) && + ((PsiModifierListOwner)object).hasModifierProperty(PsiModifier.STATIC)) { + if (lookupElement.getLookupString().equals(((PsiMember)object).getName())) { + staticMembers.put(CompletionUtil.getOriginalOrSelf((PsiModifierListOwner)object), lookupElement); } + } - PrioritizedLookupElement prio = lookupElement.as(PrioritizedLookupElement.CLASS_CONDITION_KEY); - if (prio == null || prio.getPriority() == 0) { - zeroPriority.add(lookupElement); - } else { - consumer.consume(lookupElement); - } + PrioritizedLookupElement prio = lookupElement.as(PrioritizedLookupElement.CLASS_CONDITION_KEY); + if (prio == null || prio.getPriority() == 0) { + zeroPriority.add(lookupElement); + } else { + consumer.consume(lookupElement); } }); @@ -292,9 +286,26 @@ public class GrMainCompletionProvider extends CompletionProvider staticMembers, final Consumer consumer) { final StaticMemberProcessor processor = completeStaticMembers(parameters); - processor.processMembersOfRegisteredClasses(matcher, new PairConsumer() { - @Override - public void consume(PsiMember member, PsiClass psiClass) { + processor.processMembersOfRegisteredClasses(matcher, (member, psiClass) -> { + if (member instanceof GrAccessorMethod) { + member = ((GrAccessorMethod)member).getProperty(); + } + member = CompletionUtil.getOriginalOrSelf(member); + if (staticMembers.containsKey(member)) { + return; + } + final String name = member.getName(); + if (name == null || !matcher.prefixMatches(name)) { + staticMembers.remove(member); + return; + } + JavaGlobalMemberLookupElement element = createGlobalMemberElement(member, psiClass, true); + staticMembers.put(member, element); + consumer.consume(element); + }); + if (parameters.getInvocationCount() >= 2 && StringUtil.isNotEmpty(matcher.getPrefix())) { + return () -> processor.processStaticMethodsGlobally(matcher, element -> { + PsiMember member = (PsiMember)element.getObject(); if (member instanceof GrAccessorMethod) { member = ((GrAccessorMethod)member).getProperty(); } @@ -302,37 +313,9 @@ public class GrMainCompletionProvider extends CompletionProvider= 2 && StringUtil.isNotEmpty(matcher.getPrefix())) { - return new Runnable() { - @Override - public void run() { - processor.processStaticMethodsGlobally(matcher, new Consumer() { - @Override - public void consume(LookupElement element) { - PsiMember member = (PsiMember)element.getObject(); - if (member instanceof GrAccessorMethod) { - member = ((GrAccessorMethod)member).getProperty(); - } - member = CompletionUtil.getOriginalOrSelf(member); - if (staticMembers.containsKey(member)) { - return; - } - staticMembers.put(member, element); - consumer.consume(element); - } - }); - } - }; + }); } return EmptyRunnable.INSTANCE; } @@ -483,12 +466,7 @@ public class GrMainCompletionProvider extends CompletionProvider() { - @Override - public void consume(LookupElement lookupElement) { - result.addElement(lookupElement); - } - }); + completeReference(parameters, reference, inheritors, result.getPrefixMatcher(), lookupElement -> result.addElement(lookupElement)); if (reference.getQualifier() == null) { if (!GroovySmartCompletionContributor.AFTER_NEW.accepts(position)) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionUtil.java index c16aaca58b04..b5a249def4de 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionUtil.java @@ -369,11 +369,8 @@ public class GroovyCompletionUtil { String tailText = getPackageText((PsiClass)element); final PsiClass psiClass = (PsiClass)element; if ((substitutor == null || substitutor.getSubstitutionMap().isEmpty()) && psiClass.getTypeParameters().length > 0) { - tailText = "<" + StringUtil.join(psiClass.getTypeParameters(), new Function() { - @Override - public String fun(PsiTypeParameter psiTypeParameter) { - return psiTypeParameter.getName(); - } + tailText = "<" + StringUtil.join(psiClass.getTypeParameters(), psiTypeParameter -> { + return psiTypeParameter.getName(); }, "," + (showSpaceAfterComma(psiClass) ? " " : "")) + ">" + tailText; } builder = builder.withTailText(tailText, true); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyConfigSlurperCompletionProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyConfigSlurperCompletionProvider.java index 6a47575ee91f..277a312e1d95 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyConfigSlurperCompletionProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyConfigSlurperCompletionProvider.java @@ -75,12 +75,7 @@ class GroovyConfigSlurperCompletionProvider extends CompletionProvider variants = new HashMap(); - collectVariants(new PairConsumer() { - @Override - public void consume(String s, Boolean isFinal) { - variants.put(s, isFinal); - } - }, ref, groovyFile); + collectVariants((s, isFinal) -> variants.put(s, isFinal), ref, groovyFile); if (variants.isEmpty()) return; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyNoVariantsDelegator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyNoVariantsDelegator.java index 875a5a936924..4833120c8c16 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyNoVariantsDelegator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyNoVariantsDelegator.java @@ -83,16 +83,13 @@ public class GroovyNoVariantsDelegator extends CompletionContributor { } private static void suggestNonImportedClasses(CompletionParameters parameters, final CompletionResultSet result) { - GrMainCompletionProvider.addAllClasses(parameters, new Consumer() { - @Override - public void consume(LookupElement element) { - JavaPsiClassReferenceElement classElement = - element.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); - if (classElement != null) { - classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); - } - result.addElement(element); + GrMainCompletionProvider.addAllClasses(parameters, element -> { + JavaPsiClassReferenceElement classElement = + element.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); + if (classElement != null) { + classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); } + result.addElement(element); }, new JavaCompletionSession(result), result.getPrefixMatcher()); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java index 68f4d515c4ea..c9b58da10e7a 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovySmartCompletionContributor.java @@ -108,31 +108,28 @@ public class GroovySmartCompletionContributor extends CompletionContributor { if (reference == null) return; if (reference instanceof GrReferenceElement) { GroovyCompletionUtil.processVariants((GrReferenceElement)reference, result.getPrefixMatcher(), params, - new Consumer() { - @Override - public void consume(LookupElement variant) { - PsiType type = null; + variant -> { + PsiType type = null; - Object o = variant.getObject(); - if (o instanceof GroovyResolveResult) { - if (!((GroovyResolveResult)o).isAccessible()) return; - o = ((GroovyResolveResult)o).getElement(); - } + Object o = variant.getObject(); + if (o instanceof GroovyResolveResult) { + if (!((GroovyResolveResult)o).isAccessible()) return; + o = ((GroovyResolveResult)o).getElement(); + } - if (o instanceof PsiElement) { - type = getTypeByElement((PsiElement)o, position); + if (o instanceof PsiElement) { + type = getTypeByElement((PsiElement)o, position); + } + else if (o instanceof String) { + if ("true".equals(o) || "false".equals(o)) { + type = PsiType.BOOLEAN; } - else if (o instanceof String) { - if ("true".equals(o) || "false".equals(o)) { - type = PsiType.BOOLEAN; - } - } - if (type == null) return; - for (TypeConstraint info : infos) { - if (info.satisfied(type, position)) { - result.addElement(variant); - break; - } + } + if (type == null) return; + for (TypeConstraint info : infos) { + if (info.satisfied(type, position)) { + result.addElement(variant); + break; } } }); @@ -197,12 +194,7 @@ public class GroovySmartCompletionContributor extends CompletionContributor { protected void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext matchingContext, @NotNull final CompletionResultSet result) { - generateInheritorVariants(parameters, result.getPrefixMatcher(), new Consumer() { - @Override - public void consume(LookupElement lookupElement) { - result.addElement(lookupElement); - } - }); + generateInheritorVariants(parameters, result.getPrefixMatcher(), lookupElement -> result.addElement(lookupElement)); } }); @@ -218,12 +210,9 @@ public class GroovySmartCompletionContributor extends CompletionContributor { final GrReferenceExpression reference = (GrReferenceExpression)position.getParent(); if (reference == null) return; - CompleteReferenceExpression.processRefInAnnotation(reference, result.getPrefixMatcher(), new Consumer() { - @Override - public void consume(@Nullable LookupElement element) { - if (element != null) { - result.addElement(element); - } + CompleteReferenceExpression.processRefInAnnotation(reference, result.getPrefixMatcher(), element -> { + if (element != null) { + result.addElement(element); } }, params); } @@ -259,12 +248,7 @@ public class GroovySmartCompletionContributor extends CompletionContributor { static void addExpectedClassMembers(CompletionParameters params, final CompletionResultSet result) { for (final TypeConstraint info : getExpectedTypeInfos(params)) { - Consumer consumer = new Consumer() { - @Override - public void consume(LookupElement element) { - result.addElement(element); - } - }; + Consumer consumer = element -> result.addElement(element); PsiType type = info.getType(); PsiType defType = info.getDefaultType(); boolean searchInheritors = params.getInvocationCount() > 1; @@ -318,13 +302,10 @@ public class GroovySmartCompletionContributor extends CompletionContributor { final PsiType diamond = inferDiamond(place); - JavaInheritorsGetter.processInheritors(parameters, expectedClassTypes, matcher, new Consumer() { - @Override - public void consume(final PsiType type) { - final LookupElement element = addExpectedType(type, place, parameters, diamond); - if (element != null) { - consumer.consume(element); - } + JavaInheritorsGetter.processInheritors(parameters, expectedClassTypes, matcher, type -> { + final LookupElement element = addExpectedType(type, place, parameters, diamond); + if (element != null) { + consumer.consume(element); } }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyTypeParameterInfoHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyTypeParameterInfoHandler.java index 2e54bef62d8e..4228f4a274d2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyTypeParameterInfoHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parameterInfo/GroovyTypeParameterInfoHandler.java @@ -155,11 +155,8 @@ public class GroovyTypeParameterInfoHandler implements ParameterInfoHandlerWithT buffer.append(p.getName()); int highlightEndOffset = buffer.length(); buffer.append(" extends "); - buffer.append(StringUtil.join(p.getSuperTypes(), new Function() { - @Override - public String fun(final PsiClassType t) { - return t.getPresentableText(); - } + buffer.append(StringUtil.join(p.getSuperTypes(), t -> { + return t.getPresentableText(); }, ", ")); context.setupUIComponentPresentation(buffer.toString(), 0, highlightEndOffset, false, false, false, context.getDefaultParameterColor()); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcConsole.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcConsole.java index e36a96e417d0..a4056e7ee44b 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcConsole.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcConsole.java @@ -276,29 +276,23 @@ public class MvcConsole implements Disposable { public void processTerminated(ProcessEvent event) { final int exitCode = event.getExitCode(); if (exitCode == 0 && !gotError.get().booleanValue()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed() || !closeOnDone) return; - myToolWindow.hide(null); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed() || !closeOnDone) return; + myToolWindow.hide(null); }, modalityState); } } }); } catch (final Exception e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(e.getMessage(), "Cannot Start Process"); + ApplicationManager.getApplication().invokeLater(() -> { + Messages.showErrorDialog(e.getMessage(), "Cannot Start Process"); - try { - if (onDone != null && !module.isDisposed()) onDone.run(); - } - catch (Exception e) { - LOG.error(e); - } + try { + if (onDone != null && !module.isDisposed()) onDone.run(); + } + catch (Exception e1) { + LOG.error(e1); } }, modalityState); return; @@ -313,40 +307,34 @@ public class MvcConsole implements Disposable { myContent.setDisplayName((framework == null ? "" : framework.getDisplayName() + ":") + "Executing..."); myConsole.scrollToEnd(); myConsole.attachToProcess(handler); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - handler.startNotify(); - handler.waitFor(); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + handler.startNotify(); + handler.waitFor(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; - module.putUserData(UPDATING_BY_CONSOLE_PROCESS, true); - LocalFileSystem.getInstance().refresh(false); - module.putUserData(UPDATING_BY_CONSOLE_PROCESS, null); + module.putUserData(UPDATING_BY_CONSOLE_PROCESS, true); + LocalFileSystem.getInstance().refresh(false); + module.putUserData(UPDATING_BY_CONSOLE_PROCESS, null); - try { - if (onDone != null && !module.isDisposed()) onDone.run(); - } - catch (Exception e) { - LOG.error(e); - } - myConsole.print("\n", ConsoleViewContentType.NORMAL_OUTPUT); - myKillAction.setHandler(null); - myContent.setDisplayName(""); + try { + if (onDone != null && !module.isDisposed()) onDone.run(); + } + catch (Exception e) { + LOG.error(e); + } + myConsole.print("\n", ConsoleViewContentType.NORMAL_OUTPUT); + myKillAction.setHandler(null); + myContent.setDisplayName(""); - myExecuting = false; + myExecuting = false; - final MyProcessInConsole pic = myProcessQueue.poll(); - if (pic != null) { - executeProcessImpl(pic, false); - } - } - }, modalityState); - } + final MyProcessInConsole pic1 = myProcessQueue.poll(); + if (pic1 != null) { + executeProcessImpl(pic1, false); + } + }, modalityState); }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java index 0c36f66173f6..5092cbca238a 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java @@ -105,12 +105,8 @@ public abstract class MvcFramework { @NotNull public Map createConfigureActions(final @NotNull Module module) { - return Collections.singletonMap("Configure " + getFrameworkName() + " SDK", new Runnable() { - @Override - public void run() { - configureAsLibraryDependency(module); - } - }); + return Collections.singletonMap("Configure " + getFrameworkName() + " SDK", + () -> configureAsLibraryDependency(module)); } protected void configureAsLibraryDependency(@NotNull Module module) { @@ -164,18 +160,15 @@ public abstract class MvcFramework { final GeneralCommandLine commandLine = getCreationCommandLine(module); if (commandLine == null) return; - MvcConsole.executeProcess(module, commandLine, new Runnable() { - @Override - public void run() { - VirtualFile root = findAppRoot(module); - if (root == null) return; + MvcConsole.executeProcess(module, commandLine, () -> { + VirtualFile root = findAppRoot(module); + if (root == null) return; - PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(root); - IdeView ide = LangDataKeys.IDE_VIEW.getData(DataManager.getInstance().getDataContext()); - if (ide != null) ide.selectElement(psiDir); + PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(root); + IdeView ide = LangDataKeys.IDE_VIEW.getData(DataManager.getInstance().getDataContext()); + if (ide != null) ide.selectElement(psiDir); - //also here comes fileCreated(application.properties) which manages roots and run configuration - } + //also here comes fileCreated(application.properties) which manages roots and run configuration }, true); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java index 178ecb64be68..bf6b050ad8e6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java @@ -144,36 +144,33 @@ public class MvcModuleStructureSynchronizer extends AbstractProjectComponent { if (framework == null) return; if (framework.isToReformatOnCreation(file) || file.isDirectory()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!file.isValid()) return; - if (!framework.hasSupport(module)) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (!file.isValid()) return; + if (!framework.hasSupport(module)) return; - final List files = new ArrayList(); + final List files = new ArrayList(); - if (file.isDirectory()) { - ModuleRootManager.getInstance(module).getFileIndex().iterateContentUnderDirectory(file, new ContentIterator() { - @Override - public boolean processFile(VirtualFile fileOrDir) { - if (!fileOrDir.isDirectory() && framework.isToReformatOnCreation(fileOrDir)) { - files.add(file); - } - return true; + if (file.isDirectory()) { + ModuleRootManager.getInstance(module).getFileIndex().iterateContentUnderDirectory(file, new ContentIterator() { + @Override + public boolean processFile(VirtualFile fileOrDir) { + if (!fileOrDir.isDirectory() && framework.isToReformatOnCreation(fileOrDir)) { + files.add(file); } - }); - } - else { - files.add(file); - } - - PsiManager manager = PsiManager.getInstance(myProject); - - for (VirtualFile virtualFile : files) { - PsiFile psiFile = manager.findFile(virtualFile); - if (psiFile != null) { - new ReformatCodeProcessor(myProject, psiFile, null, false).run(); + return true; } + }); + } + else { + files.add(file); + } + + PsiManager manager = PsiManager.getInstance(myProject); + + for (VirtualFile virtualFile : files) { + PsiFile psiFile = manager.findFile(virtualFile); + if (psiFile != null) { + new ReformatCodeProcessor(myProject, psiFile, null, false).run(); } } }, module.getDisposed()); @@ -435,12 +432,7 @@ public class MvcModuleStructureSynchronizer extends AbstractProjectComponent { if (!roots.equals(mvcModuleStructureSynchronizer.myPluginRoots)) { mvcModuleStructureSynchronizer.myPluginRoots = roots; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - mvcModuleStructureSynchronizer.queue(UpdateProjectStructure, project); - } - }); + ApplicationManager.getApplication().invokeLater(() -> mvcModuleStructureSynchronizer.queue(UpdateProjectStructure, project)); } } } @@ -454,30 +446,27 @@ public class MvcModuleStructureSynchronizer extends AbstractProjectComponent { StartupManager.getInstance(myProject).runWhenProjectIsInitialized(new DumbAwareRunnable() { @Override public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; - for (ToolWindowEP ep : ToolWindowEP.EP_NAME.getExtensions()) { - if (MvcToolWindowDescriptor.class.isAssignableFrom(ep.getFactoryClass())) { - MvcToolWindowDescriptor descriptor = (MvcToolWindowDescriptor)ep.getToolWindowFactory(); - String id = descriptor.getToolWindowId(); - boolean shouldShow = descriptor.value(myProject); + for (ToolWindowEP ep : ToolWindowEP.EP_NAME.getExtensions()) { + if (MvcToolWindowDescriptor.class.isAssignableFrom(ep.getFactoryClass())) { + MvcToolWindowDescriptor descriptor = (MvcToolWindowDescriptor)ep.getToolWindowFactory(); + String id = descriptor.getToolWindowId(); + boolean shouldShow = descriptor.value(myProject); - ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); + ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); - ToolWindow toolWindow = toolWindowManager.getToolWindow(id); + ToolWindow toolWindow = toolWindowManager.getToolWindow(id); - if (shouldShow && toolWindow == null) { - toolWindow = toolWindowManager.registerToolWindow(id, true, ToolWindowAnchor.LEFT, myProject, true); - toolWindow.setIcon(descriptor.getFramework().getToolWindowIcon()); - descriptor.createToolWindowContent(myProject, toolWindow); - } - else if (!shouldShow && toolWindow != null) { - toolWindowManager.unregisterToolWindow(id); - Disposer.dispose(toolWindow.getContentManager()); - } + if (shouldShow && toolWindow == null) { + toolWindow = toolWindowManager.registerToolWindow(id, true, ToolWindowAnchor.LEFT, myProject, true); + toolWindow.setIcon(descriptor.getFramework().getToolWindowIcon()); + descriptor.createToolWindowContent(myProject, toolWindow); + } + else if (!shouldShow && toolWindow != null) { + toolWindowManager.unregisterToolWindow(id); + Disposer.dispose(toolWindow.getContentManager()); } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureUtil.java index 7f03158e0564..c2823526040e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureUtil.java @@ -112,12 +112,7 @@ public class MvcModuleStructureUtil { for (final VirtualFile excluded : structure.getExcludedFolders(root)) { if (moduleRootManager.getFileIndex().isInContent(excluded)) { - actions.add(new Consumer() { - @Override - public void consume(ContentEntry contentEntry) { - contentEntry.addExcludeFolder(excluded); - } - }); + actions.add(contentEntry -> contentEntry.addExcludeFolder(excluded)); } } @@ -127,20 +122,17 @@ public class MvcModuleStructureUtil { return null; } - return new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - ContentEntry contentEntry = findContentEntry(model, root); - if (contentEntry == null) { - contentEntry = model.addContentEntry(root); - } + return model -> { + ContentEntry contentEntry = findContentEntry(model, root); + if (contentEntry == null) { + contentEntry = model.addContentEntry(root); + } - for (final Consumer action : actions) { - action.consume(contentEntry); - } - if (modifyLib != null) { - modifyLib.consume(model); - } + for (final Consumer action : actions) { + action.consume(contentEntry); + } + if (modifyLib != null) { + modifyLib.consume(model); } }; } @@ -155,14 +147,11 @@ public class MvcModuleStructureUtil { @NotNull List> actions, @NotNull Collection sourceRoots) { if (sourceRoots.contains(file)) { - actions.add(new Consumer() { - @Override - public void consume(ContentEntry contentEntry) { - SourceFolder[] folders = contentEntry.getSourceFolders(); - for (SourceFolder folder : folders) { - if (Comparing.equal(folder.getFile(), file)) { - contentEntry.removeSourceFolder(folder); - } + actions.add(contentEntry -> { + SourceFolder[] folders = contentEntry.getSourceFolders(); + for (SourceFolder folder : folders) { + if (Comparing.equal(folder.getFile(), file)) { + contentEntry.removeSourceFolder(folder); } } }); @@ -181,13 +170,10 @@ public class MvcModuleStructureUtil { return null; } - return new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - Library.ModifiableModel libModel = modifyDefaultLibrary(model, libName); - libModel.addJarDirectory(libDir, false); - libModel.commit(); - } + return model -> { + Library.ModifiableModel libModel = modifyDefaultLibrary(model, libName); + libModel.addJarDirectory(libDir, false); + libModel.commit(); }; } @@ -227,27 +213,19 @@ public class MvcModuleStructureUtil { JpsModuleSourceRootType existingRootType = sourceRoots.get(src); if (rootType == JavaSourceRootType.TEST_SOURCE && (existingRootType != null && existingRootType != JavaSourceRootType.TEST_SOURCE)) { // see http://youtrack.jetbrains.net/issue/IDEA-70642 - actions.add(new Consumer() { - @Override - public void consume(ContentEntry entry) { - for (SourceFolder folder : entry.getSourceFolders()) { - if (Comparing.equal(folder.getFile(), src)) { - entry.removeSourceFolder(folder); - entry.addSourceFolder(src, rootType); - break; - } + actions.add(entry -> { + for (SourceFolder folder : entry.getSourceFolders()) { + if (Comparing.equal(folder.getFile(), src)) { + entry.removeSourceFolder(folder); + entry.addSourceFolder(src, rootType); + break; } } }); return; } - actions.add(new Consumer() { - @Override - public void consume(ContentEntry contentEntry) { - contentEntry.addSourceFolder(src, rootType); - } - }); + actions.add(contentEntry -> contentEntry.addSourceFolder(src, rootType)); } public static void updateModuleStructure(final Module module, MvcProjectStructure structure, @NotNull VirtualFile root) { @@ -256,12 +234,9 @@ public class MvcModuleStructureUtil { // update module if (!actions.first.isEmpty()) { - ModuleRootModificationUtil.updateModel(module, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - for (final Consumer action : actions.first) { - action.consume(model); - } + ModuleRootModificationUtil.updateModel(module, model -> { + for (final Consumer action : actions.first) { + action.consume(model); } }); } @@ -278,17 +253,9 @@ public class MvcModuleStructureUtil { for (Consumer action : actions.second) { action.consume(model); } - application.invokeAndWait(new Runnable() { - @Override - public void run() { - application.runWriteAction(new Runnable() { - @Override - public void run() { - model.commit(); - } - }); - } - }, application.getDefaultModalityState()); + application.invokeAndWait(() -> application.runWriteAction(() -> { + model.commit(); + }), application.getDefaultModalityState()); } } @@ -359,13 +326,10 @@ public class MvcModuleStructureUtil { private static void moveupLibrariesFromMavenPlugin(final Module module, Collection> actions) { if (moveupLibrariesFromMavenPlugin(ModuleRootManager.getInstance(module)) != null) { - actions.add(new Consumer() { - @Override - public void consume(ModifiableRootModel modifiableRootModel) { - OrderEntry[] orderEntries = moveupLibrariesFromMavenPlugin(modifiableRootModel); - if (orderEntries != null) { - modifiableRootModel.rearrangeOrderEntries(orderEntries); - } + actions.add(modifiableRootModel -> { + OrderEntry[] orderEntries = moveupLibrariesFromMavenPlugin(modifiableRootModel); + if (orderEntries != null) { + modifiableRootModel.rearrangeOrderEntries(orderEntries); } }); } @@ -389,18 +353,15 @@ public class MvcModuleStructureUtil { } if (!toRemove.isEmpty() || !toRemoveContent.isEmpty()) { - actions.add(new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - for (ContentEntry entry : model.getContentEntries()) { - if (toRemoveContent.remove(entry.getUrl())) { - model.removeContentEntry(entry); - } - else { - for (SourceFolder folder : entry.getSourceFolders()) { - if (toRemove.remove(folder)) { - entry.removeSourceFolder(folder); - } + actions.add(model -> { + for (ContentEntry entry : model.getContentEntries()) { + if (toRemoveContent.remove(entry.getUrl())) { + model.removeContentEntry(entry); + } + else { + for (SourceFolder folder : entry.getSourceFolders()) { + if (toRemove.remove(folder)) { + entry.removeSourceFolder(folder); } } } @@ -438,15 +399,12 @@ public class MvcModuleStructureUtil { } if (!toRemoveUrls.isEmpty()) { - actions.add(new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - final Library.ModifiableModel modifiableModel = modifyDefaultLibrary(model, libName); - for (String url : toRemoveUrls) { - modifiableModel.removeRoot(url, OrderRootType.CLASSES); - } - modifiableModel.commit(); + actions.add(model -> { + final Library.ModifiableModel modifiableModel = modifyDefaultLibrary(model, libName); + for (String url : toRemoveUrls) { + modifiableModel.removeRoot(url, OrderRootType.CLASSES); } + modifiableModel.commit(); }); } } @@ -529,16 +487,13 @@ public class MvcModuleStructureUtil { final boolean isLibrariesEquals = appLibraries.equals(auxLibraries) && getJarUrls(auxUserLibrary).equals(getJarUrls(appUserLibrary)); if (!isSdkEquals || !isLibrariesEquals) { - ModuleRootModificationUtil.updateModel(pluginsModule, new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - if (!isSdkEquals) { - copySdk(appRootManager, model); - } + ModuleRootModificationUtil.updateModel(pluginsModule, model -> { + if (!isSdkEquals) { + copySdk(appRootManager, model); + } - if (!isLibrariesEquals) { - copyUserLibraries(appRootManager, model, framework); - } + if (!isLibrariesEquals) { + copyUserLibraries(appRootManager, model, framework); } }); } @@ -751,13 +706,10 @@ public class MvcModuleStructureUtil { } public static Consumer removeStaleContentEntries(final Collection pluginDirs) { - return new Consumer() { - @Override - public void consume(ModifiableRootModel modifiableRootModel) { - for (final ContentEntry entry : modifiableRootModel.getContentEntries()) { - if (!pluginDirs.contains(entry.getFile())) { - modifiableRootModel.removeContentEntry(entry); - } + return modifiableRootModel -> { + for (final ContentEntry entry : modifiableRootModel.getContentEntries()) { + if (!pluginDirs.contains(entry.getFile())) { + modifiableRootModel.removeContentEntry(entry); } } }; @@ -796,16 +748,13 @@ public class MvcModuleStructureUtil { } public static Consumer exportDefaultLibrary(final String libraryName) { - return new Consumer() { - @Override - public void consume(ModifiableRootModel modifiableRootModel) { - for (final OrderEntry entry : modifiableRootModel.getOrderEntries()) { - if (entry instanceof LibraryOrderEntry) { - final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry; - String lName = libraryOrderEntry.getLibraryName(); - if (lName != null && lName.startsWith(libraryName)) { - libraryOrderEntry.setExported(true); - } + return modifiableRootModel -> { + for (final OrderEntry entry : modifiableRootModel.getOrderEntries()) { + if (entry instanceof LibraryOrderEntry) { + final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry; + String lName = libraryOrderEntry.getLibraryName(); + if (lName != null && lName.startsWith(libraryName)) { + libraryOrderEntry.setExported(true); } } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcProjectWithoutLibraryNotificator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcProjectWithoutLibraryNotificator.java index 11b5e5e4c245..936aac196bf5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcProjectWithoutLibraryNotificator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcProjectWithoutLibraryNotificator.java @@ -59,11 +59,8 @@ public class MvcProjectWithoutLibraryNotificator implements StartupActivity, Dum .append("Module ").append('\'').append(module.getName()).append('\'') .append(" has no ").append(name).append(" SDK."); if (!actions.isEmpty()) content.append("
      "); - content.append(StringUtil.join(actions.keySet(), new Function() { - @Override - public String fun(String actionName) { - return String.format("%s", actionName, actionName); - } + content.append(StringUtil.join(actions.keySet(), actionName -> { + return String.format("%s", actionName, actionName); }, " ")); content.append(""); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcUpgradeAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcUpgradeAction.java index 91ae7ab35a41..1e56f543e254 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcUpgradeAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcUpgradeAction.java @@ -41,12 +41,7 @@ public class MvcUpgradeAction extends MvcActionBase { protected void actionPerformed(@NotNull AnActionEvent e, @NotNull final Module module, @NotNull final MvcFramework framework) { final GroovyLibraryDescription description = framework.createLibraryDescription(); final AddCustomLibraryDialog dialog = - AddCustomLibraryDialog.createDialog(description, module, new ParameterizedRunnable() { - @Override - public void run(ModifiableRootModel modifiableRootModel) { - removeOldMvcSdk(framework, modifiableRootModel); - } - }); + AddCustomLibraryDialog.createDialog(description, module, modifiableRootModel -> removeOldMvcSdk(framework, modifiableRootModel)); dialog.setTitle("Change " + framework.getDisplayName() + " SDK version"); if (dialog.showAndGet()) { module.putUserData(MvcFramework.UPGRADE, Boolean.TRUE); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/projectView/MvcProjectViewSelectInTarget.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/projectView/MvcProjectViewSelectInTarget.java index f26471af75fb..b725673ae05f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/projectView/MvcProjectViewSelectInTarget.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/projectView/MvcProjectViewSelectInTarget.java @@ -51,13 +51,10 @@ public class MvcProjectViewSelectInTarget extends SelectInTargetBase implements return; } - final Runnable select = new Runnable() { - @Override - public void run() { - final MvcProjectViewPane view = MvcProjectViewPane.getView(project, framework); - if (view != null) { - view.selectFile(file, requestFocus); - } + final Runnable select = () -> { + final MvcProjectViewPane view = MvcProjectViewPane.getView(project, framework); + if (view != null) { + view.selectFile(file, requestFocus); } }; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyImportOptimizerRefactoringHelper.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyImportOptimizerRefactoringHelper.java index c3de84d60431..407635f32407 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyImportOptimizerRefactoringHelper.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyImportOptimizerRefactoringHelper.java @@ -60,31 +60,25 @@ public class GroovyImportOptimizerRefactoringHelper implements RefactoringHelper public void performOperation(final Project project, final Set files) { final ProgressManager progressManager = ProgressManager.getInstance(); final Map, Set>> redundants = new HashMap, Set>>(); - final Runnable findUnusedImports = new Runnable() { - @Override - public void run() { - final ProgressIndicator progressIndicator = progressManager.getProgressIndicator(); - final int total = files.size(); - int i = 0; - for (final GroovyFile file : files) { - if (!file.isValid()) continue; - final VirtualFile virtualFile = file.getVirtualFile(); - if (!ProjectRootManager.getInstance(project).getFileIndex().isInSource(virtualFile)) { - continue; - } - if (progressIndicator != null) { - progressIndicator.setText2(virtualFile.getPresentableUrl()); - progressIndicator.setFraction((double)i++/total); - } - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final Set usedImports = GroovyImportUtil.findUsedImports(file); - final List validImports = PsiUtil.getValidImportStatements(file); - redundants.put(file, Pair.create(validImports, usedImports)); - } - }); + final Runnable findUnusedImports = () -> { + final ProgressIndicator progressIndicator = progressManager.getProgressIndicator(); + final int total = files.size(); + int i = 0; + for (final GroovyFile file : files) { + if (!file.isValid()) continue; + final VirtualFile virtualFile = file.getVirtualFile(); + if (!ProjectRootManager.getInstance(project).getFileIndex().isInSource(virtualFile)) { + continue; } + if (progressIndicator != null) { + progressIndicator.setText2(virtualFile.getPresentableUrl()); + progressIndicator.setFraction((double)i++/total); + } + ApplicationManager.getApplication().runReadAction(() -> { + final Set usedImports = GroovyImportUtil.findUsedImports(file); + final List validImports = PsiUtil.getValidImportStatements(file); + redundants.put(file, Pair.create(validImports, usedImports)); + }); } }; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringUtil.java index a8ed927f3e70..1b601f480dd2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyRefactoringUtil.java @@ -80,19 +80,16 @@ public abstract class GroovyRefactoringUtil { public static PsiElement[] getExpressionOccurrences(@NotNull PsiElement expr, @NotNull PsiElement scope) { ArrayList occurrences = new ArrayList(); - Comparator comparator = new Comparator() { - @Override - public int compare(PsiElement element1, PsiElement element2) { - if (element1 != null && element1.equals(element2)) return 0; + Comparator comparator = (element1, element2) -> { + if (element1 != null && element1.equals(element2)) return 0; - if (element1 instanceof GrParameter && - element2 instanceof GrParameter) { - final String name1 = ((GrParameter) element1).getName(); - final String name2 = ((GrParameter) element2).getName(); - return name1.compareTo(name2); - } - return 1; + if (element1 instanceof GrParameter && + element2 instanceof GrParameter) { + final String name1 = ((GrParameter) element1).getName(); + final String name2 = ((GrParameter) element2).getName(); + return name1.compareTo(name2); } + return 1; }; if (scope instanceof GrLoopStatement) { @@ -136,13 +133,10 @@ public abstract class GroovyRefactoringUtil { } public static void sortOccurrences(PsiElement[] occurrences) { - Arrays.sort(occurrences, new Comparator() { - @Override - public int compare(PsiElement elem1, PsiElement elem2) { - final int offset1 = elem1.getTextRange().getStartOffset(); - final int offset2 = elem2.getTextRange().getStartOffset(); - return offset1 - offset2; - } + Arrays.sort(occurrences, (elem1, elem2) -> { + final int offset1 = elem1.getTextRange().getStartOffset(); + final int offset2 = elem2.getTextRange().getStartOffset(); + return offset1 - offset2; }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureDialog.java index f4286ee1706b..1ef5deb1fdc2 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureDialog.java @@ -305,11 +305,8 @@ public class GrChangeSignatureDialog extends ChangeSignatureDialogBase infos = getParameters(); if (!infos.isEmpty()) { - final List paramsText = ContainerUtil.map(infos, new Function() { - @Override - public String fun(GrParameterInfo info) { - return generateParameterText(info); - } + final List paramsText = ContainerUtil.map(infos, info -> { + return generateParameterText(info); }); builder.append("\n").append(INDENT); builder.append(StringUtil.join(paramsText, ",\n" + INDENT)); @@ -320,11 +317,8 @@ public class GrChangeSignatureDialog extends ChangeSignatureDialogBase 0) { builder.append("\nthrows\n"); - final List exceptionNames = ContainerUtil.map(exceptions, new Function() { - @Override - public String fun(PsiTypeCodeFragment fragment) { - return fragment.getText(); - } + final List exceptionNames = ContainerUtil.map(exceptions, fragment -> { + return fragment.getText(); }); builder.append(INDENT).append(StringUtil.join(exceptionNames, ",\n" + INDENT)); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java index b4de21c48d1f..0b1e02d29fa8 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java @@ -719,18 +719,14 @@ public class GrChangeSignatureUsageProcessor implements ChangeSignatureUsageProc } else if (context instanceof GrTryCatchStatement) { final GrCatchClause[] catchClauses = ((GrTryCatchStatement)context).getCatchClauses(); - List referencedTypes = ContainerUtil.map(catchClauses, new Function() { - @Override - @Nullable - public PsiClassType fun(GrCatchClause grCatchClause) { - final GrParameter grParameter = grCatchClause.getParameter(); - final PsiType type = grParameter != null ? grParameter.getType() : null; - if (type instanceof PsiClassType) { - return (PsiClassType)type; - } - else { - return null; - } + List referencedTypes = ContainerUtil.map(catchClauses, grCatchClause -> { + final GrParameter grParameter = grCatchClause.getParameter(); + final PsiType type = grParameter != null ? grParameter.getType() : null; + if (type instanceof PsiClassType) { + return (PsiClassType)type; + } + else { + return null; } }); @@ -762,13 +758,9 @@ public class GrChangeSignatureUsageProcessor implements ChangeSignatureUsageProc final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(tryCatch.getProject()); final GrCatchClause[] clauses = tryCatch.getCatchClauses(); - List restricted = ContainerUtil.map(clauses, new Function() { - @Override - @Nullable - public String fun(GrCatchClause grCatchClause) { - final GrParameter grParameter = grCatchClause.getParameter(); - return grParameter != null ? grParameter.getName() : null; - } + List restricted = ContainerUtil.map(clauses, grCatchClause -> { + final GrParameter grParameter = grCatchClause.getParameter(); + return grParameter != null ? grParameter.getName() : null; }); restricted = ContainerUtil.skipNulls(restricted); @@ -802,13 +794,7 @@ public class GrChangeSignatureUsageProcessor implements ChangeSignatureUsageProc } private static PsiClassType[] getExceptions(ThrownExceptionInfo[] infos, final PsiElement context, final PsiManager manager) { - return ContainerUtil.map(infos, new Function() { - @Override - @Nullable - public PsiClassType fun(ThrownExceptionInfo thrownExceptionInfo) { - return (PsiClassType)thrownExceptionInfo.createType(context, manager); - } - }, new PsiClassType[infos.length]); + return ContainerUtil.map(infos, thrownExceptionInfo -> (PsiClassType)thrownExceptionInfo.createType(context, manager), new PsiClassType[infos.length]); } private static boolean isParameterOptional(JavaParameterInfo parameterInfo) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClassItemGeneratorImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClassItemGeneratorImpl.java index 3a7c6508c3d7..7bad9e9d261a 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClassItemGeneratorImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ClassItemGeneratorImpl.java @@ -368,11 +368,8 @@ public class ClassItemGeneratorImpl implements ClassItemGenerator { Map setters = context.getSetters(); Set> entries = setters.entrySet(); if (ApplicationManager.getApplication().isUnitTestMode()) { - entries = ImmutableSortedSet.copyOf(new Comparator>() { - @Override - public int compare(Map.Entry o1, Map.Entry o2) { - return o1.getValue().compareTo(o2.getValue()); - } + entries = ImmutableSortedSet.copyOf((o1, o2) -> { + return o1.getValue().compareTo(o2.getValue()); }, entries); } for (Map.Entry entry : entries) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ConvertToJavaProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ConvertToJavaProcessor.java index e88833fdeaba..a4f6ecd58749 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ConvertToJavaProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ConvertToJavaProcessor.java @@ -102,12 +102,8 @@ public class ConvertToJavaProcessor extends BaseRefactoringProcessor { newFile = file.setName(fileName); } catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(myProject, e.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon()); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showMessageDialog(myProject, e.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon())); return; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeProvider.java index e00b361ab356..3824f8f0769e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeProvider.java @@ -127,29 +127,26 @@ public class TypeProvider { if (!paramInds.isEmpty()) { final GrClosureSignature signature = GrClosureSignatureUtil.createSignature(method, PsiSubstitutor.EMPTY); - MethodReferencesSearch.search(method, true).forEach(new Processor() { - @Override - public boolean process(PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - final PsiManager manager = element.getManager(); - final GlobalSearchScope resolveScope = element.getResolveScope(); + MethodReferencesSearch.search(method, true).forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + final PsiManager manager = element.getManager(); + final GlobalSearchScope resolveScope = element.getResolveScope(); - if (element instanceof GrReferenceExpression) { - final GrCall call = (GrCall)element.getParent(); - final GrClosureSignatureUtil.ArgInfo[] argInfos = GrClosureSignatureUtil.mapParametersToArguments(signature, call); + if (element instanceof GrReferenceExpression) { + final GrCall call = (GrCall)element.getParent(); + final GrClosureSignatureUtil.ArgInfo[] argInfos = GrClosureSignatureUtil.mapParametersToArguments(signature, call); - if (argInfos == null) return true; - paramInds.forEach(new TIntProcedure() { - @Override - public boolean execute(int i) { - PsiType type = GrClosureSignatureUtil.getTypeByArg(argInfos[i], manager, resolveScope); - types[i] = TypesUtil.getLeastUpperBoundNullable(type, types[i], manager); - return true; - } - }); - } - return true; + if (argInfos == null) return true; + paramInds.forEach(new TIntProcedure() { + @Override + public boolean execute(int i) { + PsiType type = GrClosureSignatureUtil.getTypeByArg(argInfos[i], manager, resolveScope); + types[i] = TypesUtil.getLeastUpperBoundNullable(type, types[i], manager); + return true; + } + }); } + return true; }); } paramInds.forEach(new TIntProcedure() { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/method/GroovyExtractMethodHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/method/GroovyExtractMethodHandler.java index c44580432699..0e88036bbfac 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/method/GroovyExtractMethodHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/method/GroovyExtractMethodHandler.java @@ -193,27 +193,24 @@ public class GroovyExtractMethodHandler implements RefactoringActionHandler { final ExtractMethodInfoHelper helper = getSettings(initialInfo, owner); if (helper == null) return; - CommandProcessor.getInstance().executeCommand(helper.getProject(), new Runnable() { - @Override - public void run() { - final AccessToken lock = ApplicationManager.getApplication().acquireWriteActionLock(GroovyExtractMethodHandler.class); - try { - createMethod(helper, owner); - GrStatementOwner declarationOwner = - helper.getStringPartInfo() == null ? GroovyRefactoringUtil.getDeclarationOwner(helper.getStatements()[0]) : null; - GrStatement realStatement = ExtractUtil.replaceStatement(declarationOwner, helper); + CommandProcessor.getInstance().executeCommand(helper.getProject(), () -> { + final AccessToken lock = ApplicationManager.getApplication().acquireWriteActionLock(GroovyExtractMethodHandler.class); + try { + createMethod(helper, owner); + GrStatementOwner declarationOwner = + helper.getStringPartInfo() == null ? GroovyRefactoringUtil.getDeclarationOwner(helper.getStatements()[0]) : null; + GrStatement realStatement = ExtractUtil.replaceStatement(declarationOwner, helper); - // move to offset - if (editor != null) { - PsiDocumentManager.getInstance(helper.getProject()).commitDocument(editor.getDocument()); - editor.getSelectionModel().removeSelection(); - editor.getCaretModel().moveToOffset(ExtractUtil.getCaretOffset(realStatement)); - } - } - finally { - lock.finish(); + // move to offset + if (editor != null) { + PsiDocumentManager.getInstance(helper.getProject()).commitDocument(editor.getDocument()); + editor.getSelectionModel().removeSelection(); + editor.getCaretModel().moveToOffset(ExtractUtil.getCaretOffset(realStatement)); } } + finally { + lock.finish(); + } }, REFACTORING_NAME, null); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractInterface/GrExtractInterfaceHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractInterface/GrExtractInterfaceHandler.java index a9eb16af5159..ac9c9bbf7240 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractInterface/GrExtractInterfaceHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extractInterface/GrExtractInterfaceHandler.java @@ -122,12 +122,7 @@ public class GrExtractInterfaceHandler implements RefactoringActionHandler, Elem SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(myClass); final SmartPsiElementPointer interfacePointer = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(anInterface); - final Runnable turnRefsToSuperRunnable = new Runnable() { - @Override - public void run() { - ExtractClassUtil.askAndTurnRefsToSuper(myProject, classPointer, interfacePointer); - } - }; + final Runnable turnRefsToSuperRunnable = () -> ExtractClassUtil.askAndTurnRefsToSuper(myProject, classPointer, interfacePointer); SwingUtilities.invokeLater(turnRefsToSuperRunnable); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalHandler.java index d51343cc8816..c2eafe3b02bd 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalHandler.java @@ -78,11 +78,8 @@ public class GroovyInlineLocalHandler extends InlineActionHandler { if (!CommonRefactoringUtil.checkReadOnlyStatus(project, local)) return; final GroovyInlineLocalProcessor processor = new GroovyInlineLocalProcessor(project, localVarSettings, local); - processor.setPrepareSuccessfulSwingThreadCallback(new Runnable() { - @Override - public void run() { - //do nothing - } + processor.setPrepareSuccessfulSwingThreadCallback(() -> { + //do nothing }); processor.run(); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineMethodUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineMethodUtil.java index 1f475c669ee4..95d483a9d276 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineMethodUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineMethodUtil.java @@ -604,12 +604,8 @@ public class GroovyInlineMethodUtil { final boolean isFinal = ((GrVariable)resolved).hasModifierProperty(PsiModifier.FINAL); if (!isFinal) { final PsiReference lastRef = - Collections.max(ReferencesSearch.search(resolved).findAll(), new Comparator() { - @Override - public int compare(PsiReference o1, PsiReference o2) { - return o1.getElement().getTextRange().getStartOffset() - o2.getElement().getTextRange().getStartOffset(); - } - }); + Collections.max(ReferencesSearch.search(resolved).findAll(), + (o1, o2) -> o1.getElement().getTextRange().getStartOffset() - o2.getElement().getTextRange().getStartOffset()); return lastRef.getElement() == expression; } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrAbstractInplaceIntroducer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrAbstractInplaceIntroducer.java index 7a02d06f0d4b..877752195175 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrAbstractInplaceIntroducer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrAbstractInplaceIntroducer.java @@ -175,11 +175,8 @@ public abstract class GrAbstractInplaceIntroducer result = ContainerUtil.map(getOccurrenceMarkers(), new Function() { - @Override - public PsiElement fun(RangeMarker marker) { - return PsiImplUtil.findElementInRange(myFile, marker.getStartOffset(), marker.getEndOffset(), GrExpression.class); - } + List result = ContainerUtil.map(getOccurrenceMarkers(), marker -> { + return PsiImplUtil.findElementInRange(myFile, marker.getStartOffset(), marker.getEndOffset(), GrExpression.class); }); return PsiUtilCore.toPsiElementArray(result); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrFinalListener.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrFinalListener.java index 2cd42b42bb4a..1c0dca06d2e7 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrFinalListener.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrFinalListener.java @@ -48,18 +48,15 @@ public class GrFinalListener { LOG.assertTrue(modifierList != null); final int textOffset = modifierList.getTextOffset(); - final Runnable runnable = new Runnable() { - @Override - public void run() { - if (generateFinal) { - final GrTypeElement typeElement = variable.getTypeElementGroovy(); - final int typeOffset = typeElement != null ? typeElement.getTextOffset() : textOffset; - document.insertString(typeOffset, modifier + " "); - } - else { - final int idx = modifierList.getText().indexOf(modifier); - document.deleteString(textOffset + idx, textOffset + idx + modifier.length() + 1); - } + final Runnable runnable = () -> { + if (generateFinal) { + final GrTypeElement typeElement = variable.getTypeElementGroovy(); + final int typeOffset = typeElement != null ? typeElement.getTextOffset() : textOffset; + document.insertString(typeOffset, modifier + " "); + } + else { + final int idx = modifierList.getText().indexOf(modifier); + document.deleteString(textOffset + idx, textOffset + idx + modifier.length() + 1); } }; final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java index fd84b3c10ca9..b5dec69df74c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java @@ -82,12 +82,7 @@ import java.util.*; public abstract class GrIntroduceHandlerBase implements RefactoringActionHandler { private static final Logger LOG = Logger.getInstance(GrIntroduceHandlerBase.class); - public static final Function GR_EXPRESSION_RENDERER = new Function() { - @Override - public String fun(@NotNull GrExpression expr) { - return expr.getText(); - } - }; + public static final Function GR_EXPRESSION_RENDERER = expr -> expr.getText(); public static GrExpression insertExplicitCastIfNeeded(GrVariable variable, GrExpression initializer) { PsiType ltype = findLValueType(initializer); @@ -350,83 +345,67 @@ public abstract class GrIntroduceHandlerBase ref) { - CommandProcessor.getInstance().executeCommand(ref.get().getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - GrIntroduceContext context = ref.get(); + CommandProcessor.getInstance().executeCommand(ref.get().getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + GrIntroduceContext context = ref.get(); - StringPartInfo stringPart = context.getStringPart(); - assert stringPart != null; + StringPartInfo stringPart = context.getStringPart(); + assert stringPart != null; - GrExpression expression = stringPart.replaceLiteralWithConcatenation(null); + GrExpression expression = stringPart.replaceLiteralWithConcatenation(null); - ref.set(new GrIntroduceContextImpl(context.getProject(), context.getEditor(), expression, null, null, new PsiElement[]{expression}, context.getScope())); - } - }); - } - }, getRefactoringName(), getRefactoringName()); + ref.set(new GrIntroduceContextImpl(context.getProject(), context.getEditor(), expression, null, null, new PsiElement[]{expression}, context.getScope())); + }), getRefactoringName(), getRefactoringName()); } protected void addBraces(@NotNull final GrStatement anchor, @NotNull final Ref contextRef) { - CommandProcessor.getInstance().executeCommand(contextRef.get().getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - GrIntroduceContext context = contextRef.get(); - SmartPointerManager pointManager = SmartPointerManager.getInstance(context.getProject()); - SmartPsiElementPointer expressionRef = context.getExpression() != null ? pointManager.createSmartPsiElementPointer(context.getExpression()) : null; - SmartPsiElementPointer varRef = context.getVar() != null ? pointManager.createSmartPsiElementPointer(context.getVar()) : null; + CommandProcessor.getInstance().executeCommand(contextRef.get().getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + GrIntroduceContext context = contextRef.get(); + SmartPointerManager pointManager = SmartPointerManager.getInstance(context.getProject()); + SmartPsiElementPointer expressionRef = context.getExpression() != null ? pointManager.createSmartPsiElementPointer(context.getExpression()) : null; + SmartPsiElementPointer varRef = context.getVar() != null ? pointManager.createSmartPsiElementPointer(context.getVar()) : null; - SmartPsiElementPointer[] occurrencesRefs = new SmartPsiElementPointer[context.getOccurrences().length]; - PsiElement[] occurrences = context.getOccurrences(); - for (int i = 0; i < occurrences.length; i++) { - occurrencesRefs[i] = pointManager.createSmartPsiElementPointer(occurrences[i]); - } - - - PsiFile file = anchor.getContainingFile(); - SmartPsiFileRange anchorPointer = pointManager.createSmartPsiFileRangePointer(file, anchor.getTextRange()); - - Document document = context.getEditor().getDocument(); - CharSequence sequence = document.getCharsSequence(); - - TextRange range = anchor.getTextRange(); - - int end = range.getEndOffset(); - document.insertString(end, "\n}"); - - int start = range.getStartOffset(); - while (start > 0 && Character.isWhitespace(sequence.charAt(start - 1))) { - start--; - } - document.insertString(start, "{"); - - PsiDocumentManager.getInstance(context.getProject()).commitDocument(document); - - Segment anchorSegment = anchorPointer.getRange(); - PsiElement restoredAnchor = PsiImplUtil - .findElementInRange(file, anchorSegment.getStartOffset(), anchorSegment.getEndOffset(), PsiElement.class); - GrCodeBlock block = (GrCodeBlock)restoredAnchor.getParent(); - CodeStyleManager.getInstance(context.getProject()).reformat(block.getRBrace()); - CodeStyleManager.getInstance(context.getProject()).reformat(block.getLBrace()); - - for (int i = 0; i < occurrencesRefs.length; i++) { - occurrences[i] = occurrencesRefs[i].getElement(); - } - - contextRef.set(new GrIntroduceContextImpl(context.getProject(), context.getEditor(), - expressionRef != null ? expressionRef.getElement() : null, - varRef != null ? varRef.getElement() : null, - null, occurrences, context.getScope())); - } - }); + SmartPsiElementPointer[] occurrencesRefs = new SmartPsiElementPointer[context.getOccurrences().length]; + PsiElement[] occurrences = context.getOccurrences(); + for (int i = 0; i < occurrences.length; i++) { + occurrencesRefs[i] = pointManager.createSmartPsiElementPointer(occurrences[i]); } - }, getRefactoringName(), getRefactoringName()); + + + PsiFile file = anchor.getContainingFile(); + SmartPsiFileRange anchorPointer = pointManager.createSmartPsiFileRangePointer(file, anchor.getTextRange()); + + Document document = context.getEditor().getDocument(); + CharSequence sequence = document.getCharsSequence(); + + TextRange range = anchor.getTextRange(); + + int end = range.getEndOffset(); + document.insertString(end, "\n}"); + + int start = range.getStartOffset(); + while (start > 0 && Character.isWhitespace(sequence.charAt(start - 1))) { + start--; + } + document.insertString(start, "{"); + + PsiDocumentManager.getInstance(context.getProject()).commitDocument(document); + + Segment anchorSegment = anchorPointer.getRange(); + PsiElement restoredAnchor = PsiImplUtil + .findElementInRange(file, anchorSegment.getStartOffset(), anchorSegment.getEndOffset(), PsiElement.class); + GrCodeBlock block = (GrCodeBlock)restoredAnchor.getParent(); + CodeStyleManager.getInstance(context.getProject()).reformat(block.getRBrace()); + CodeStyleManager.getInstance(context.getProject()).reformat(block.getLBrace()); + + for (int i = 0; i < occurrencesRefs.length; i++) { + occurrences[i] = occurrencesRefs[i].getElement(); + } + + contextRef.set(new GrIntroduceContextImpl(context.getProject(), context.getEditor(), + expressionRef != null ? expressionRef.getElement() : null, + varRef != null ? varRef.getElement() : null, + null, occurrences, context.getScope())); + }), getRefactoringName(), getRefactoringName()); } @NotNull @@ -467,15 +446,12 @@ public abstract class GrIntroduceHandlerBase() { - @Override - public boolean process(PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - if (element != null) { - list.add(element); - } - return true; + ReferencesSearch.search(variable, new LocalSearchScope(scope)).forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + if (element != null) { + list.add(element); } + return true; }); return list.toArray(new PsiElement[list.size()]); } @@ -501,17 +477,9 @@ public abstract class GrIntroduceHandlerBase ApplicationManager.getApplication().runWriteAction(() -> { + runRefactoring(context, settings); + }), getRefactoringName(), null); } return true; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceValidatorEngine.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceValidatorEngine.java index f19684826de8..2e2a3af68856 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceValidatorEngine.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceValidatorEngine.java @@ -106,12 +106,7 @@ public class GrIntroduceValidatorEngine implements GrIntroduceHandlerBase.Valida MultiMap list = isOKImpl(varName, allOccurences); String result = ""; final String[] strings = ArrayUtil.toStringArray((Collection)list.values()); - Arrays.sort(strings, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.compareTo(o2); - } - }); + Arrays.sort(strings, (o1, o2) -> o1.compareTo(o2)); for (String s : strings) { result = result + s.replaceAll("", "").replaceAll("", "") + "\n"; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterDialog.java index 33a199dcc135..933504465860 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterDialog.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterDialog.java @@ -514,12 +514,7 @@ public class GrIntroduceParameterDialog extends DialogWrapper { } protected void invokeRefactoring(BaseRefactoringProcessor processor) { - final Runnable prepareSuccessfulCallback = new Runnable() { - @Override - public void run() { - close(DialogWrapper.OK_EXIT_CODE); - } - }; + final Runnable prepareSuccessfulCallback = () -> close(DialogWrapper.OK_EXIT_CODE); processor.setPrepareSuccessfulSwingThreadCallback(prepareSuccessfulCallback); processor.setPreviewUsages(false); processor.run(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java index 65ae25a2872e..f02ae10baa07 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java @@ -85,12 +85,7 @@ public class GrIntroduceParameterHandler implements RefactoringActionHandler, Me public void pass(final GrExpression selectedValue) { invoke(project, editor, file, selectedValue.getTextRange().getStartOffset(), selectedValue.getTextRange().getEndOffset()); } - }, new Function() { - @Override - public String fun(GrExpression grExpression) { - return grExpression.getText(); - } - } + }, grExpression -> grExpression.getText() ); return; } @@ -129,12 +124,9 @@ public class GrIntroduceParameterHandler implements RefactoringActionHandler, Me showDialogOrStartInplace(new IntroduceParameterInfoImpl(initialInfo, owner, toSearchFor), editor); } else { - myEnclosingMethodsPopup = MethodOrClosureScopeChooser.create(scopes, editor, this, new PairFunction() { - @Override - public Object fun(GrParametersOwner owner, PsiElement element) { - showDialogOrStartInplace(new IntroduceParameterInfoImpl(initialInfo, owner, element), editor); - return null; - } + myEnclosingMethodsPopup = MethodOrClosureScopeChooser.create(scopes, editor, this, (owner, element) -> { + showDialogOrStartInplace(new IntroduceParameterInfoImpl(initialInfo, owner, element), editor); + return null; }); myEnclosingMethodsPopup.showInBestPositionFor(editor); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GroovyIntroduceParameterUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GroovyIntroduceParameterUtil.java index 19ff63a9c61d..d4c5b655be98 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GroovyIntroduceParameterUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GroovyIntroduceParameterUtil.java @@ -346,15 +346,12 @@ public class GroovyIntroduceParameterUtil { final GrVariable var = settings.getVar(); LOG.assertTrue(var != null); final List list = Collections.synchronizedList(new ArrayList()); - ReferencesSearch.search(var, new LocalSearchScope(scope)).forEach(new Processor() { - @Override - public boolean process(PsiReference psiReference) { - final PsiElement element = psiReference.getElement(); - if (element != null) { - list.add(element); - } - return true; + ReferencesSearch.search(var, new LocalSearchScope(scope)).forEach(psiReference -> { + final PsiElement element = psiReference.getElement(); + if (element != null) { + list.add(element); } + return true; }); return list.toArray(new PsiElement[list.size()]); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/memberPullUp/GrPullUpHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/memberPullUp/GrPullUpHandler.java index 19480e0d80e8..e49530e5b214 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/memberPullUp/GrPullUpHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/memberPullUp/GrPullUpHandler.java @@ -168,21 +168,13 @@ public class GrPullUpHandler implements RefactoringActionHandler, GrPullUpDialog final PsiClass superClass = dialog.getSuperClass(); if (!checkWritable(superClass, infos)) return false; final MultiMap conflicts = new MultiMap(); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final PsiDirectory targetDirectory = superClass.getContainingFile().getContainingDirectory(); - final PsiPackage targetPackage = - targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; - conflicts.putAllValues(GrPullUpConflictsUtil.checkConflicts(infos, mySubclass, superClass, targetPackage, targetDirectory, - dialog.getContainmentVerifier())); - } - }); - } - }, RefactoringBundle.message("detecting.possible.conflicts"), true, myProject)) { + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + final PsiDirectory targetDirectory = superClass.getContainingFile().getContainingDirectory(); + final PsiPackage targetPackage = + targetDirectory != null ? JavaDirectoryService.getInstance().getPackage(targetDirectory) : null; + conflicts.putAllValues(GrPullUpConflictsUtil.checkConflicts(infos, mySubclass, superClass, targetPackage, targetDirectory, + dialog.getContainmentVerifier())); + }), RefactoringBundle.message("detecting.possible.conflicts"), true, myProject)) { return false; } if (!conflicts.isEmpty()) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/GroovyMoveClassToInnerHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/GroovyMoveClassToInnerHandler.java index 4de152b33591..c331b8f58cb0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/GroovyMoveClassToInnerHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/GroovyMoveClassToInnerHandler.java @@ -94,12 +94,7 @@ public class GroovyMoveClassToInnerHandler implements MoveClassToInnerHandler { } else { //rebind imports first - Collections.sort(usageInfos, new Comparator() { - @Override - public int compare(UsageInfo o1, UsageInfo o2) { - return PsiUtil.BY_POSITION.compare(o1.getElement(), o2.getElement()); - } - }); + Collections.sort(usageInfos, (o1, o2) -> PsiUtil.BY_POSITION.compare(o1.getElement(), o2.getElement())); } return importStatements; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyMemberHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyMemberHandler.java index f6e86df1ed19..9990722d1b6c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyMemberHandler.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyMemberHandler.java @@ -246,12 +246,7 @@ public class MoveGroovyMemberHandler implements MoveMemberHandler { }); } if (!referencedFields.isEmpty()) { - Collections.sort(referencedFields, new Comparator() { - @Override - public int compare(final PsiField o1, final PsiField o2) { - return -PsiUtilCore.compareElementsByPosition(o1, o2); - } - }); + Collections.sort(referencedFields, (o1, o2) -> -PsiUtilCore.compareElementsByPosition(o1, o2)); return referencedFields.get(0); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameAliasImportedMethodProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameAliasImportedMethodProcessor.java index 1f947c2f6c49..0d582d7a1f49 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameAliasImportedMethodProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/rename/RenameAliasImportedMethodProcessor.java @@ -144,21 +144,18 @@ public class RenameAliasImportedMethodProcessor extends RenameJavaMethodProcesso final List result) { if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod)element; - OverridingMethodsSearch.search(method).forEach(new Processor() { - @Override - public boolean process(PsiMethod overrider) { - PsiElement original = overrider; - if (overrider instanceof PsiMirrorElement) { - original = ((PsiMirrorElement)overrider).getPrototype(); - } - - if (original instanceof SyntheticElement) return true; - - if (original instanceof GrField) { - result.add(new FieldNameCollisionInfo((GrField)original, method)); - } - return true; + OverridingMethodsSearch.search(method).forEach(overrider -> { + PsiElement original = overrider; + if (overrider instanceof PsiMirrorElement) { + original = ((PsiMirrorElement)overrider).getPrototype(); } + + if (original instanceof SyntheticElement) return true; + + if (original instanceof GrField) { + result.add(new FieldNameCollisionInfo((GrField)original, method)); + } + return true; }); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/safeDelete/JavaSafeDeleteDelegateForGroovy.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/safeDelete/JavaSafeDeleteDelegateForGroovy.java index 10056c32469f..57c07d76a8b8 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/safeDelete/JavaSafeDeleteDelegateForGroovy.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/safeDelete/JavaSafeDeleteDelegateForGroovy.java @@ -73,11 +73,8 @@ public class JavaSafeDeleteDelegateForGroovy implements JavaSafeDeleteDelegate { newText.append('('); final List parameters = new ArrayList(Arrays.asList(method.getParameterList().getParameters())); parameters.remove(parameter); - newText.append(StringUtil.join(parameters, new Function() { - @Override - public String fun(PsiParameter psiParameter) { - return parameter.getType().getCanonicalText(); - } + newText.append(StringUtil.join(parameters, psiParameter -> { + return parameter.getType().getCanonicalText(); }, ",")); newText.append(")*/"); usages.add(new SafeDeleteReferenceJavaDeleteUsageInfo(element, parameter, true) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/ui/MethodOrClosureScopeChooser.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/ui/MethodOrClosureScopeChooser.java index 43317bd5ede2..c9b982296e13 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/ui/MethodOrClosureScopeChooser.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/ui/MethodOrClosureScopeChooser.java @@ -151,12 +151,7 @@ public class MethodOrClosureScopeChooser { else { toSearchFor = superMethod.isEnabled() && superMethod.isSelected() ? ToSearchIn.getParent() : null; } - IdeFocusManager.findInstance().doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - callback.fun(ToSearchIn, toSearchFor); - } - }); + IdeFocusManager.findInstance().doWhenFocusSettlesDown(() -> callback.fun(ToSearchIn, toSearchFor)); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0))); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/testIntegration/GroovyTestGenerator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/testIntegration/GroovyTestGenerator.java index 17827730cbcc..312abda47f49 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/testIntegration/GroovyTestGenerator.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/testIntegration/GroovyTestGenerator.java @@ -154,14 +154,9 @@ public class GroovyTestGenerator implements TestGenerator { } private static void showErrorLater(final Project project, final String targetClassName) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(project, - CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName), - CodeInsightBundle.message("intention.error.cannot.create.class.title")); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project, + CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName), + CodeInsightBundle.message("intention.error.cannot.create.class.title"))); } private static void generateMethod(@NotNull TestIntegrationUtils.MethodKind methodKind, diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyRangeTypeCheckTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyRangeTypeCheckTest.java index 406a4b0c4a78..5f24afa8fd3e 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyRangeTypeCheckTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyRangeTypeCheckTest.java @@ -49,12 +49,9 @@ public class GroovyRangeTypeCheckTest extends LightCodeInsightFixtureTestCase { LocalQuickFix[] fixes = {fix}; final ProblemDescriptor descriptor = InspectionManager.getInstance(getProject()).createProblemDescriptor(range, "bla-bla", false, fixes, ProblemHighlightType.WEAK_WARNING); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - fix.applyFix(myFixture.getProject(), descriptor); - PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + fix.applyFix(myFixture.getProject(), descriptor); + PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); }); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/CompletionTestBase.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/CompletionTestBase.java index 8b1285e1e872..8b2eff9f99bf 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/CompletionTestBase.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/CompletionTestBase.java @@ -57,12 +57,7 @@ public abstract class CompletionTestBase extends JavaCodeInsightFixtureTestCase } }); } - Collections.sort(items, new Comparator() { - @Override - public int compare(LookupElement o1, LookupElement o2) { - return o1.getLookupString().compareTo(o2.getLookupString()); - } - }); + Collections.sort(items, (o1, o2) -> o1.getLookupString().compareTo(o2.getLookupString())); result = ""; for (LookupElement item : items) { result = result + "\n" + item.getLookupString(); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ConvertMapToClassTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ConvertMapToClassTest.java index 14d064ebae74..fee2a0cd91b7 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ConvertMapToClassTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ConvertMapToClassTest.java @@ -79,13 +79,11 @@ public class ConvertMapToClassTest extends GrIntentionTestCase { final GrTypeDefinition foo = ConvertMapToClassIntention.createClass(getProject(), map.getNamedArguments(), "", "Foo"); myFixture.addFileToProject(getTestName(true) + "/Foo.groovy", foo.getContainingFile().getText()); final PsiClass psiClass = myFixture.findClass("Foo"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - ConvertMapToClassIntention - .replaceMapWithClass(getProject(), map, psiClass, ConvertMapToClassIntention.checkForReturnFromMethod(map), - ConvertMapToClassIntention.checkForVariableDeclaration(map), - ConvertMapToClassIntention.checkForMethodParameter(map)); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + ConvertMapToClassIntention + .replaceMapWithClass(getProject(), map, psiClass, ConvertMapToClassIntention.checkForReturnFromMethod(map), + ConvertMapToClassIntention.checkForVariableDeclaration(map), + ConvertMapToClassIntention.checkForMethodParameter(map)); }); myFixture.checkResultByFile(getTestName(true) + "/Foo.groovy", getTestName(true) + "/Expected.groovy", true); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java index e1965b0fddd6..7c5e82459aae 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java @@ -28,18 +28,10 @@ public class PsiEventsTest extends PsiTestCase { final Document doc = docManager.getDocument(file); assertNotNull(doc); CommandProcessor.getInstance().executeCommand(myProject, - new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - doc.insertString(3, " "); - docManager.commitDocument(doc); - } - }); - } - }, + () -> ApplicationManager.getApplication().runWriteAction(() -> { + doc.insertString(3, " "); + docManager.commitDocument(doc); + }), "file text set", this ); diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java index bce3b603a7b6..cde9284217fe 100644 --- a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java @@ -186,35 +186,32 @@ public int getOffset(int index) { public void sortHandlers(final StructContext context) { - Collections.sort(exceptionTable.getHandlers(), new Comparator() { + Collections.sort(exceptionTable.getHandlers(), (handler0, handler1) -> { - public int compare(ExceptionHandler handler0, ExceptionHandler handler1) { - - if (handler0.to == handler1.to) { - if (handler0.exceptionClass == null) { - return 1; - } - else { - if (handler1.exceptionClass == null) { - return -1; - } - else if (handler0.exceptionClass.equals(handler1.exceptionClass)) { - return (handler0.from > handler1.from) ? -1 : 1; // invalid code - } - else { - if (Util.instanceOf(context, handler0.exceptionClass, handler1.exceptionClass)) { - return -1; - } - else { - return 1; - } - } - } + if (handler0.to == handler1.to) { + if (handler0.exceptionClass == null) { + return 1; } else { - return (handler0.to > handler1.to) ? 1 : -1; + if (handler1.exceptionClass == null) { + return -1; + } + else if (handler0.exceptionClass.equals(handler1.exceptionClass)) { + return (handler0.from > handler1.from) ? -1 : 1; // invalid code + } + else { + if (Util.instanceOf(context, handler0.exceptionClass, handler1.exceptionClass)) { + return -1; + } + else { + return 1; + } + } } } + else { + return (handler0.to > handler1.to) ? 1 : -1; + } }); } diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java index ada6abcea429..48f8db846234 100644 --- a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java @@ -133,14 +133,12 @@ public class ImportCollector { private List packImports() { List> lst = new ArrayList>(mapSimpleNames.entrySet()); - Collections.sort(lst, new Comparator>() { - public int compare(Entry par0, Entry par1) { - int res = par0.getValue().compareTo(par1.getValue()); - if (res == 0) { - res = par0.getKey().compareTo(par1.getKey()); - } - return res; + Collections.sort(lst, (par0, par1) -> { + int res = par0.getValue().compareTo(par1.getValue()); + if (res == 0) { + res = par0.getKey().compareTo(par1.getKey()); } + return res; }); List res = new ArrayList(); diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java index c93be38f6aba..00eea784c567 100644 --- a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java @@ -191,11 +191,7 @@ public class DomHelper { lstPosts.add(stt.id); } - Collections.sort(lstPosts, new Comparator() { - public int compare(Integer o1, Integer o2) { - return mapSortOrder.get(o1).compareTo(mapSortOrder.get(o2)); - } - }); + Collections.sort(lstPosts, (o1, o2) -> mapSortOrder.get(o1).compareTo(mapSortOrder.get(o2))); if (lstPosts.size() > 1 && lstPosts.get(0).intValue() == st.id) { lstPosts.add(lstPosts.remove(0)); diff --git a/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java index 3d142166edee..f20ae5559a45 100644 --- a/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java +++ b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java @@ -124,11 +124,8 @@ public class SingleClassesTest { File parent = classFile.getParentFile(); if (parent != null) { final String pattern = classFile.getName().replace(".class", "") + "\\$.+\\.class"; - File[] inner = parent.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.matches(pattern); - } + File[] inner = parent.listFiles((dir, name) -> { + return name.matches(pattern); }); if (inner != null) Collections.addAll(files, inner); } diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/SuspiciousLocalesLanguagesInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/SuspiciousLocalesLanguagesInspection.java index 505cf5b96bda..13761410a05d 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/SuspiciousLocalesLanguagesInspection.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/SuspiciousLocalesLanguagesInspection.java @@ -116,12 +116,9 @@ public class SuspiciousLocalesLanguagesInspection extends BaseLocalInspectionToo if (!(resourceBundle instanceof ResourceBundleImpl) || files.size() < 2) { return null; } - List bundleLocales = ContainerUtil.mapNotNull(files, new Function() { - @Override - public Locale fun(PropertiesFile propertiesFile) { - final Locale locale = propertiesFile.getLocale(); - return locale == PropertiesUtil.DEFAULT_LOCALE ? null : locale; - } + List bundleLocales = ContainerUtil.mapNotNull(files, propertiesFile1 -> { + final Locale locale = propertiesFile1.getLocale(); + return locale == PropertiesUtil.DEFAULT_LOCALE ? null : locale; }); bundleLocales = ContainerUtil.filter(bundleLocales, new Condition() { @Override diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java index 81360dd665dc..5d600bcdf1fb 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/duplicateStringLiteral/DuplicateStringLiteralInspection.java @@ -104,12 +104,7 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { final List words = StringUtil.getWordsIn(stringToFind); if (words.isEmpty()) return; // put longer strings first - Collections.sort(words, new Comparator() { - @Override - public int compare(final String o1, final String o2) { - return o2.length() - o1.length(); - } - }); + Collections.sort(words, (o1, o2) -> o2.length() - o1.length()); final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); Set resultFiles = null; @@ -175,23 +170,15 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { String classList; if (isOnTheFly) { - classList = StringUtil.join(tenClassesMost, new Function() { - @Override - public String fun(final PsiClass aClass) { - final boolean thisFile = aClass.getContainingFile() == originalExpression.getContainingFile(); - //noinspection HardCodedStringLiteral - return "   '" + aClass.getQualifiedName() + "'" + - (thisFile ? " " + InspectionsBundle.message("inspection.duplicates.message.in.this.file") : ""); - } + classList = StringUtil.join(tenClassesMost, aClass -> { + final boolean thisFile = aClass.getContainingFile() == originalExpression.getContainingFile(); + //noinspection HardCodedStringLiteral + return "   '" + aClass.getQualifiedName() + "'" + + (thisFile ? " " + InspectionsBundle.message("inspection.duplicates.message.in.this.file") : ""); }, ", " + BR); } else { - classList = StringUtil.join(tenClassesMost, new Function() { - @Override - public String fun(final PsiClass aClass) { - return "'" + aClass.getQualifiedName() + "'"; - } - }, ", "); + classList = StringUtil.join(tenClassesMost, aClass -> "'" + aClass.getQualifiedName() + "'", ", "); } if (classes.size() > tenClassesMost.size()) { @@ -318,42 +305,39 @@ public class DuplicateStringLiteralInspection extends BaseLocalInspectionTool { @Override public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; - final List expressions = new ArrayList(); - for(SmartPsiElementPointer ptr: myExpressions) { - final PsiElement element = ptr.getElement(); - if (element != null) { - expressions.add((PsiExpression) element); - } + SwingUtilities.invokeLater(() -> { + if (project.isDisposed()) return; + final List expressions = new ArrayList(); + for(SmartPsiElementPointer ptr: myExpressions) { + final PsiElement element = ptr.getElement(); + if (element != null) { + expressions.add((PsiExpression) element); } - final PsiExpression[] expressionArray = expressions.toArray(new PsiExpression[expressions.size()]); - final IntroduceConstantHandler handler = new IntroduceConstantHandler() { - @Override - protected OccurrenceManager createOccurrenceManager(PsiExpression selectedExpr, PsiClass parentClass) { - final OccurrenceFilter filter = new OccurrenceFilter() { - @Override - public boolean isOK(PsiExpression occurrence) { - return true; - } - }; - return new BaseOccurrenceManager(filter) { - @Override - protected PsiExpression[] defaultOccurrences() { - return expressionArray; - } - - @Override - protected PsiExpression[] findOccurrences() { - return expressionArray; - } - }; - } - }; - handler.invoke(project, expressionArray); } + final PsiExpression[] expressionArray = expressions.toArray(new PsiExpression[expressions.size()]); + final IntroduceConstantHandler handler = new IntroduceConstantHandler() { + @Override + protected OccurrenceManager createOccurrenceManager(PsiExpression selectedExpr, PsiClass parentClass) { + final OccurrenceFilter filter = new OccurrenceFilter() { + @Override + public boolean isOK(PsiExpression occurrence) { + return true; + } + }; + return new BaseOccurrenceManager(filter) { + @Override + protected PsiExpression[] defaultOccurrences() { + return expressionArray; + } + + @Override + protected PsiExpression[] findOccurrences() { + return expressionArray; + } + }; + } + }; + handler.invoke(project, expressionArray); }); } diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nInspection.java index dc10aa76fa0e..c48902e7ec89 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nInspection.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nInspection.java @@ -287,13 +287,10 @@ public class I18nInspection extends BaseLocalInspectionTool { final JTextField text = new JTextField(nonNlsCommentPattern); final FieldPanel nonNlsCommentPatternComponent = new FieldPanel(text, CodeInsightBundle.message("inspection.i18n.option.ignore.comment.pattern"), - CodeInsightBundle.message("inspection.i18n.option.ignore.comment.title"), null, new Runnable() { - @Override - public void run() { - nonNlsCommentPattern = text.getText(); - cacheNonNlsCommentPattern(); - } - }); + CodeInsightBundle.message("inspection.i18n.option.ignore.comment.title"), null, () -> { + nonNlsCommentPattern = text.getText(); + cacheNonNlsCommentPattern(); + }); panel.add(nonNlsCommentPatternComponent, gc); final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(panel); @@ -443,15 +440,12 @@ public class I18nInspection extends BaseLocalInspectionTool { @Override public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) { //do it later because it is invoked from write action - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - PsiElement element = descriptor.getPsiElement(); - if (!(element instanceof PsiExpression)) return; + ApplicationManager.getApplication().invokeLater(() -> { + PsiElement element = descriptor.getPsiElement(); + if (!(element instanceof PsiExpression)) return; - PsiExpression[] expressions = {(PsiExpression)element}; - new IntroduceConstantHandler().invoke(project, expressions); - } + PsiExpression[] expressions = {(PsiExpression)element}; + new IntroduceConstantHandler().invoke(project, expressions); }, project.getDisposed()); } diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeAction.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeAction.java index c7e4bb94b155..c0243bb55c0e 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeAction.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeAction.java @@ -135,24 +135,18 @@ public class I18nizeAction extends AnAction { if (!FileModificationService.getInstance().prepareFileForWrite(file.getContainingFile())) return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - try { - handler.performI18nization(psiFile, editor, dialog.getLiteralExpression(), propertiesFiles, dialog.getKey(), - StringUtil.unescapeStringCharacters(dialog.getValue()), - dialog.getI18nizedText(), dialog.getParameters(), - dialog.getPropertyCreationHandler()); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }, CodeInsightBundle.message("quickfix.i18n.command.name"), project); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> { + try { + handler.performI18nization(psiFile, editor, dialog.getLiteralExpression(), propertiesFiles, dialog.getKey(), + StringUtil.unescapeStringCharacters(dialog.getValue()), + dialog.getI18nizedText(), dialog.getParameters(), + dialog.getPropertyCreationHandler()); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }, CodeInsightBundle.message("quickfix.i18n.command.name"), project); }); } diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeQuickFix.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeQuickFix.java index 11d235c86c8b..ecff94af69c5 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeQuickFix.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/I18nizeQuickFix.java @@ -132,24 +132,16 @@ public class I18nizeQuickFix implements LocalQuickFix, I18nQuickFixHandler { !FileModificationService.getInstance().prepareFileForWrite(file.getContainingFile())) return; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - performI18nization(psiFile, PsiUtilBase.findEditor(psiFile), dialog.getLiteralExpression(), propertiesFiles, dialog.getKey(), - dialog.getValue(), dialog.getI18nizedText(), dialog.getParameters(), - dialog.getPropertyCreationHandler()); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + performI18nization(psiFile, PsiUtilBase.findEditor(psiFile), dialog.getLiteralExpression(), propertiesFiles, dialog.getKey(), + dialog.getValue(), dialog.getI18nizedText(), dialog.getParameters(), + dialog.getPropertyCreationHandler()); } - }, CodeInsightBundle.message("quickfix.i18n.command.name"), project); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), CodeInsightBundle.message("quickfix.i18n.command.name"), project); } protected PsiElement doReplacementInJava(@NotNull final PsiFile psiFile, diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nizeQuickFixDialog.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nizeQuickFixDialog.java index d6ce383d427f..3d599d31551a 100644 --- a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nizeQuickFixDialog.java +++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nizeQuickFixDialog.java @@ -141,12 +141,7 @@ public class JavaI18nizeQuickFixDialog extends I18nizeQuickFixDialog { public void hyperlinkUpdate(HyperlinkEvent e) { final FileTemplateConfigurable configurable = new FileTemplateConfigurable(myProject); final FileTemplate template = FileTemplateManager.getInstance(myProject).getCodeTemplate(templateName); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - configurable.setTemplate(template, null); - } - }); + SwingUtilities.invokeLater(() -> configurable.setTemplate(template, null)); boolean ok = ShowSettingsUtil.getInstance().editConfigurable(myPanel, configurable); if (ok) { FileTemplateManager.getInstance(myProject).saveAllTemplates(); @@ -214,12 +209,7 @@ public class JavaI18nizeQuickFixDialog extends I18nizeQuickFixDialog { } myRBEditorTextField.setHistory(ArrayUtil.toStringArray(result)); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myRBEditorTextField.setSelectedIndex(0); - } - }); + SwingUtilities.invokeLater(() -> myRBEditorTextField.setSelectedIndex(0)); } @Override diff --git a/plugins/java-i18n/src/com/intellij/refactoring/inline/InlinePropertyHandler.java b/plugins/java-i18n/src/com/intellij/refactoring/inline/InlinePropertyHandler.java index 73e165d45dca..1c6876097cca 100644 --- a/plugins/java-i18n/src/com/intellij/refactoring/inline/InlinePropertyHandler.java +++ b/plugins/java-i18n/src/com/intellij/refactoring/inline/InlinePropertyHandler.java @@ -66,19 +66,17 @@ public class InlinePropertyHandler extends JavaInlineActionHandler { final Collection containingFiles = Collections.synchronizedSet(new HashSet()); containingFiles.add(psiElement.getContainingFile()); boolean result = ReferencesSearch.search(psiElement).forEach( - new Processor() { - public boolean process(final PsiReference psiReference) { - PsiElement element = psiReference.getElement(); - PsiElement parent = element.getParent(); - if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiMethodCallExpression) { - if (((PsiExpressionList)parent).getExpressions().length == 1) { - occurrences.add(parent.getParent()); - containingFiles.add(element.getContainingFile()); - return true; - } + psiReference -> { + PsiElement element = psiReference.getElement(); + PsiElement parent = element.getParent(); + if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiMethodCallExpression) { + if (((PsiExpressionList)parent).getExpressions().length == 1) { + occurrences.add(parent.getParent()); + containingFiles.add(element.getContainingFile()); + return true; } - return false; } + return false; } ); diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxNamespaceDescriptor.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxNamespaceDescriptor.java index 6263fa5aeb31..f6cdd51a0807 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxNamespaceDescriptor.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxNamespaceDescriptor.java @@ -52,12 +52,9 @@ public class JavaFxNamespaceDescriptor implements XmlNSDescriptor, Validator result = new ArrayList(); - ClassInheritorsSearch.search(paneClass, paneClass.getUseScope(), true, true, false).forEach(new Processor() { - @Override - public boolean process(PsiClass psiClass) { - result.add(new JavaFxClassTagDescriptor(psiClass.getName(), psiClass)); - return true; - } + ClassInheritorsSearch.search(paneClass, paneClass.getUseScope(), true, true, false).forEach(psiClass -> { + result.add(new JavaFxClassTagDescriptor(psiClass.getName(), psiClass)); + return true; }); return result.toArray(new XmlElementDescriptor[result.size()]); } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java index 0817e30ab30c..3441c200191b 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java @@ -523,16 +523,13 @@ public class JavaFxPsiUtil { if (builderClass != null) { final PsiMethod[] buildMethods = builderClass.findMethodsByName("build", false); if (buildMethods.length == 1 && buildMethods[0].getParameterList().getParametersCount() == 0) { - if (ClassInheritorsSearch.search(builderClass).forEach(new Processor() { - @Override - public boolean process(PsiClass aClass) { - PsiType returnType = null; - final PsiMethod method = MethodSignatureUtil.findMethodBySuperMethod(aClass, buildMethods[0], false); - if (method != null) { - returnType = method.getReturnType(); - } - return !Comparing.equal(psiClass, PsiUtil.resolveClassInClassTypeOnly(returnType)); + if (ClassInheritorsSearch.search(builderClass).forEach(aClass -> { + PsiType returnType = null; + final PsiMethod method = MethodSignatureUtil.findMethodBySuperMethod(aClass, buildMethods[0], false); + if (method != null) { + returnType = method.getReturnType(); } + return !Comparing.equal(psiClass, PsiUtil.resolveClassInClassTypeOnly(returnType)); })) { return Result.create(false, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); } @@ -1142,30 +1139,27 @@ public class JavaFxPsiUtil { }; final GlobalSearchScope globalSearchScope = GlobalSearchScope .notScope(GlobalSearchScope.getScopeRestrictedByFileTypes(myContainingFile.getResolveScope(), StdFileTypes.XML)); - ReferencesSearch.search(myContainingFile, globalSearchScope).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element instanceof PsiLiteralExpression) { - final PsiNewExpression expression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class); - if (expression != null) { - final PsiType type = expression.getType(); - if (type != null && type.equalsToText(JavaFxCommonNames.JAVAFX_FXML_FXMLLOADER)) { - final PsiElement parent = expression.getParent(); - if (parent instanceof PsiLocalVariable) { - ReferencesSearch.search(parent).forEach(processor); - final PsiClass controller = processor.getInjectedController(); - if (controller != null) { - injectedController.set(controller); - dep.set(processor.getContainingFile()); - return false; - } + ReferencesSearch.search(myContainingFile, globalSearchScope).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element instanceof PsiLiteralExpression) { + final PsiNewExpression expression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class); + if (expression != null) { + final PsiType type = expression.getType(); + if (type != null && type.equalsToText(JavaFxCommonNames.JAVAFX_FXML_FXMLLOADER)) { + final PsiElement parent = expression.getParent(); + if (parent instanceof PsiLocalVariable) { + ReferencesSearch.search(parent).forEach(processor); + final PsiClass controller = processor.getInjectedController(); + if (controller != null) { + injectedController.set(controller); + dep.set(processor.getContainingFile()); + return false; } } } } - return true; } + return true; }); } } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxImportsOptimizer.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxImportsOptimizer.java index 36d3938bc3ac..6ed9b376d8e3 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxImportsOptimizer.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxImportsOptimizer.java @@ -67,12 +67,7 @@ public class JavaFxImportsOptimizer implements ImportOptimizer { final List> names = new ArrayList>(); final Set demandedForNested = new HashSet<>(); collectNamesToImport(names, demandedForNested, (XmlFile)file); - Collections.sort(names, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return StringUtil.compare(o1.first, o2.first, true); - } - }); + Collections.sort(names, (o1, o2) -> StringUtil.compare(o1.first, o2.first, true)); final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project); final List> sortedNames = ImportHelper.sortItemsAccordingToSettings(names, settings); final HashSet onDemand = new HashSet(); @@ -100,24 +95,21 @@ public class JavaFxImportsOptimizer implements ImportOptimizer { final XmlDocument document = dummyFile.getDocument(); final XmlProlog newImportList = document != null ? document.getProlog() : null; if (newImportList == null) return EmptyRunnable.getInstance(); - return new Runnable() { - @Override - public void run() { - final XmlDocument xmlDocument = ((XmlFile)file).getDocument(); - final XmlProlog prolog = xmlDocument != null ? xmlDocument.getProlog() : null; - if (prolog != null) { - final Collection instructions = PsiTreeUtil.findChildrenOfType(prolog, XmlProcessingInstruction.class); - for (final XmlProcessingInstruction instruction : instructions) { - final ASTNode node = instruction.getNode(); - final ASTNode nameNode = node.findChildByType(XmlTokenType.XML_NAME); - if (nameNode != null && nameNode.getText().equals("import")) { - instruction.delete(); - } + return () -> { + final XmlDocument xmlDocument = ((XmlFile)file).getDocument(); + final XmlProlog prolog = xmlDocument != null ? xmlDocument.getProlog() : null; + if (prolog != null) { + final Collection instructions = PsiTreeUtil.findChildrenOfType(prolog, XmlProcessingInstruction.class); + for (final XmlProcessingInstruction instruction : instructions) { + final ASTNode node = instruction.getNode(); + final ASTNode nameNode = node.findChildByType(XmlTokenType.XML_NAME); + if (nameNode != null && nameNode.getText().equals("import")) { + instruction.delete(); } - prolog.add(newImportList); - } else { - document.addBefore(newImportList, document.getRootTag()); } + prolog.add(newImportList); + } else { + document.addBefore(newImportList, document.getRootTag()); } }; } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxRelatedItemLineMarkerProvider.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxRelatedItemLineMarkerProvider.java index eb9bee7bc955..6bb93d470c51 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxRelatedItemLineMarkerProvider.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/JavaFxRelatedItemLineMarkerProvider.java @@ -68,12 +68,7 @@ public class JavaFxRelatedItemLineMarkerProvider extends RelatedItemLineMarkerPr } if (!defaultConstructor) return; final ArrayList targets = new ArrayList(); - collectTargets(field, targets, new Function() { - @Override - public GotoRelatedItem fun(PsiElement element) { - return new GotoRelatedItem(element); - } - }, true); + collectTargets(field, targets, element1 -> new GotoRelatedItem(element1), true); if (targets.isEmpty()) return; result.add(new RelatedItemLineMarkerInfo(field, field.getNameIdentifier().getTextRange(), @@ -93,23 +88,20 @@ public class JavaFxRelatedItemLineMarkerProvider extends RelatedItemLineMarkerPr final List fxmls = JavaFxControllerClassIndex.findFxmlsWithController(field.getProject(), qualifiedName); if (fxmls.isEmpty()) return; ReferencesSearch.search(field, GlobalSearchScope.filesScope(field.getProject(), fxmls)).forEach( - new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement referenceElement = reference.getElement(); - if (referenceElement == null) return true; - final PsiFile containingFile = referenceElement.getContainingFile(); - if (containingFile == null) return true; - if (!JavaFxFileTypeFactory.isFxml(containingFile)) return true; - if (!(referenceElement instanceof XmlAttributeValue)) return true; - final XmlAttributeValue attributeValue = (XmlAttributeValue)referenceElement; - final PsiElement parent = attributeValue.getParent(); - if (!(parent instanceof XmlAttribute)) return true; - if (!FxmlConstants.FX_ID.equals(((XmlAttribute)parent).getName())) return true; - targets.add(fun.fun(parent)); - return !stopAtFirst; - } - }); + reference -> { + final PsiElement referenceElement = reference.getElement(); + if (referenceElement == null) return true; + final PsiFile containingFile = referenceElement.getContainingFile(); + if (containingFile == null) return true; + if (!JavaFxFileTypeFactory.isFxml(containingFile)) return true; + if (!(referenceElement instanceof XmlAttributeValue)) return true; + final XmlAttributeValue attributeValue = (XmlAttributeValue)referenceElement; + final PsiElement parent = attributeValue.getParent(); + if (!(parent instanceof XmlAttribute)) return true; + if (!FxmlConstants.FX_ID.equals(((XmlAttribute)parent).getName())) return true; + targets.add(fun.fun(parent)); + return !stopAtFirst; + }); } private static class JavaFXIdIconNavigationHandler implements GutterIconNavigationHandler { diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxCollapseSubTagToAttributeIntention.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxCollapseSubTagToAttributeIntention.java index 4e1aad6efecd..5f26f273e3a7 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxCollapseSubTagToAttributeIntention.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxCollapseSubTagToAttributeIntention.java @@ -47,15 +47,12 @@ public class JavaFxCollapseSubTagToAttributeIntention extends PsiElementBaseInte value = tag.getValue().getText().trim(); } else { - value = StringUtil.join(tag.getSubTags(), new Function() { - @Override - public String fun(XmlTag childTag) { - final XmlAttribute valueAttr = childTag.getAttribute(FxmlConstants.FX_VALUE); - if (valueAttr != null) { - return valueAttr.getValue(); - } - return ""; + value = StringUtil.join(tag.getSubTags(), childTag -> { + final XmlAttribute valueAttr = childTag.getAttribute(FxmlConstants.FX_VALUE); + if (valueAttr != null) { + return valueAttr.getValue(); } + return ""; }, ", "); } final XmlAttribute attribute = XmlElementFactory.getInstance(project).createXmlAttribute(tag.getName(), value); diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxExpandAttributeIntention.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxExpandAttributeIntention.java index a0d9b01d9978..17a343532746 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxExpandAttributeIntention.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxExpandAttributeIntention.java @@ -60,12 +60,7 @@ public class JavaFxExpandAttributeIntention extends PsiElementBaseIntentionActio final String typeNode = itemType.getPresentableText(); JavaFxPsiUtil.insertImportWhenNeeded((XmlFile)attr.getContainingFile(), typeNode, itemType.getCanonicalText()); final String[] vals = value != null ? value.split(",") : ArrayUtil.EMPTY_STRING_ARRAY; - value = StringUtil.join(vals, new Function() { - @Override - public String fun(String s) { - return "<" + typeNode + " " + FxmlConstants.FX_VALUE + "=\"" + s.trim() + "\"/>"; - } - }, "\n"); + value = StringUtil.join(vals, s -> "<" + typeNode + " " + FxmlConstants.FX_VALUE + "=\"" + s.trim() + "\"/>", "\n"); } } final XmlTag childTag = XmlElementFactory.getInstance(project).createTagFromText("<" + name + ">" + value + ""); diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxInjectPageLanguageIntention.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxInjectPageLanguageIntention.java index 15a64ce5e680..7f6c1b7c587e 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxInjectPageLanguageIntention.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/intentions/JavaFxInjectPageLanguageIntention.java @@ -97,12 +97,8 @@ public class JavaFxInjectPageLanguageIntention extends PsiElementBaseIntentionAc } else { final JBList list = new JBList(availableLanguages); JBPopupFactory.getInstance().createListPopupBuilder(list) - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - registerPageLanguage(project, containingFile, (String)list.getSelectedValue()); - } - }).createPopup().showInBestPositionFor(editor); + .setItemChoosenCallback( + () -> registerPageLanguage(project, containingFile, (String)list.getSelectedValue())).createPopup().showInBestPositionFor(editor); } } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/descriptors/JavaFxClassTagDescriptorBase.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/descriptors/JavaFxClassTagDescriptorBase.java index 0d71984fd0cb..8a3909922f3f 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/descriptors/JavaFxClassTagDescriptorBase.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/descriptors/JavaFxClassTagDescriptorBase.java @@ -99,21 +99,14 @@ public abstract class JavaFxClassTagDescriptorBase implements XmlElementDescript static void collectStaticAttributesDescriptors(@Nullable XmlTag context, List simpleAttrs) { if (context == null) return; - collectParentStaticProperties(context.getParentTag(), simpleAttrs, new Function() { - @Override - public XmlAttributeDescriptor fun(PsiMethod method) { - return new JavaFxSetterAttributeDescriptor(method, method.getContainingClass()); - } - }); + collectParentStaticProperties(context.getParentTag(), simpleAttrs, + method -> new JavaFxSetterAttributeDescriptor(method, method.getContainingClass())); } protected static void collectStaticElementDescriptors(XmlTag context, List children) { - collectParentStaticProperties(context, children, new Function() { - @Override - public XmlElementDescriptor fun(PsiMethod method) { - final PsiClass aClass = method.getContainingClass(); - return new JavaFxPropertyTagDescriptor(aClass, PropertyUtil.getPropertyName(method.getName()), true); - } + collectParentStaticProperties(context, children, method -> { + final PsiClass aClass = method.getContainingClass(); + return new JavaFxPropertyTagDescriptor(aClass, PropertyUtil.getPropertyName(method.getName()), true); }); } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java index e13985227b4a..2f06486cff35 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxControllerFieldSearcher.java @@ -63,35 +63,32 @@ public class JavaFxControllerFieldSearcher implements QueryExecutor fxmlWithController = JavaFxControllerClassIndex.findFxmlWithController(project, qualifiedName); for (final PsiFile file : fxmlWithController) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final String fieldName = field.getName(); - if (fieldName == null) return; - final VirtualFile virtualFile = file.getViewProvider().getVirtualFile(); - final SearchScope searchScope = queryParameters.getEffectiveSearchScope(); - boolean contains = searchScope instanceof LocalSearchScope ? ((LocalSearchScope)searchScope).isInScope(virtualFile) : - ((GlobalSearchScope)searchScope).contains(virtualFile); - if (contains) { - file.accept(new XmlRecursiveElementVisitor() { - @Override - public void visitXmlAttributeValue(final XmlAttributeValue value) { - final PsiReference reference = value.getReference(); - if (reference != null) { - final PsiElement resolve = reference.resolve(); - if (resolve instanceof XmlAttributeValue) { - final PsiElement parent = resolve.getParent(); - if (parent instanceof XmlAttribute) { - final XmlAttribute attribute = (XmlAttribute)parent; - if (FxmlConstants.FX_ID.equals(attribute.getName()) && fieldName.equals(attribute.getValue())) { - consumer.process(reference); - } + ApplicationManager.getApplication().runReadAction(() -> { + final String fieldName = field.getName(); + if (fieldName == null) return; + final VirtualFile virtualFile = file.getViewProvider().getVirtualFile(); + final SearchScope searchScope = queryParameters.getEffectiveSearchScope(); + boolean contains = searchScope instanceof LocalSearchScope ? ((LocalSearchScope)searchScope).isInScope(virtualFile) : + ((GlobalSearchScope)searchScope).contains(virtualFile); + if (contains) { + file.accept(new XmlRecursiveElementVisitor() { + @Override + public void visitXmlAttributeValue(final XmlAttributeValue value) { + final PsiReference reference = value.getReference(); + if (reference != null) { + final PsiElement resolve = reference.resolve(); + if (resolve instanceof XmlAttributeValue) { + final PsiElement parent = resolve.getParent(); + if (parent instanceof XmlAttribute) { + final XmlAttribute attribute = (XmlAttribute)parent; + if (FxmlConstants.FX_ID.equals(attribute.getName()) && fieldName.equals(attribute.getValue())) { + consumer.process(reference); } } } } - }); - } + } + }); } }); } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderEditor.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderEditor.java index 88e18667a61a..5c068cfee651 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderEditor.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderEditor.java @@ -137,34 +137,24 @@ public class SceneBuilderEditor extends UserDataHolderBase implements FileEditor @Override public void saveChanges(final String content) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (mySceneBuilder != null) { + ApplicationManager.getApplication().invokeLater(() -> { + if (mySceneBuilder != null) { - if (!myDocument.isWritable() && ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(myFile).hasReadonlyFiles()) { - return; - } + if (!myDocument.isWritable() && ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(myFile).hasReadonlyFiles()) { + return; + } - try { - myChangeListener.setRunState(false); + try { + myChangeListener.setRunState(false); - // XXX: strange behavior with undo/redo + // XXX: strange behavior with undo/redo - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - myDocument.setText(content); - } - }, "JavaFX Scene Builder edit operation", null); - } - }); - } - finally { - myChangeListener.setRunState(true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(myProject, () -> myDocument.setText(content), "JavaFX Scene Builder edit operation", null); + }); + } + finally { + myChangeListener.setRunState(true); } } }); @@ -172,11 +162,7 @@ public class SceneBuilderEditor extends UserDataHolderBase implements FileEditor @Override public void handleError(final Throwable e) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - public void run() { - showErrorPage(e); - } - }); + UIUtil.invokeLaterIfNeeded(() -> showErrorPage(e)); } private void updateState() { diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderImpl.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderImpl.java index 38e701adc0f9..63f420bf8d01 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderImpl.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/sceneBuilder/SceneBuilderImpl.java @@ -283,23 +283,17 @@ public class SceneBuilderImpl implements SceneBuilder { } private void startChangeListener() { - myListener = new ChangeListener() { - @Override - public void changed(ObservableValue observable, Number oldValue, Number newValue) { - if (!mySkipChanges) { - myEditorCallback.saveChanges(myEditorController.getFxmlText()); - UsageTrigger.trigger("scene-builder.edit"); - } + myListener = (observable, oldValue, newValue) -> { + if (!mySkipChanges) { + myEditorCallback.saveChanges(myEditorController.getFxmlText()); + UsageTrigger.trigger("scene-builder.edit"); } }; - mySelectionListener = new ChangeListener() { - @Override - public void changed(ObservableValue observable, Number oldValue, Number newValue) { - if (!mySkipChanges) { - int[][] state = getSelectionState(); - if (state != null) { - mySelectionState.put(myEditorController.getFxmlText(), state); - } + mySelectionListener = (observable, oldValue, newValue) -> { + if (!mySkipChanges) { + int[][] state = getSelectionState(); + if (state != null) { + mySelectionState.put(myEditorController.getFxmlText(), state); } } }; diff --git a/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java b/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java index 040f4cb52bb3..ce947572d2c2 100644 --- a/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java +++ b/plugins/junit/src/com/intellij/execution/ConfigurationUtil.java @@ -88,16 +88,14 @@ public class ConfigurationUtil { } ); for (final PsiMethod method : suiteMethods) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final PsiClass containingClass = method.getContainingClass(); - if (containingClass == null) return; - if (containingClass instanceof PsiAnonymousClass) return; - if (containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) return; - if (containingClass.getContainingClass() != null && !containingClass.hasModifierProperty(PsiModifier.STATIC)) return; - if (JUnitUtil.isSuiteMethod(method) && testClassFilter.isAccepted(containingClass)) { - found.add(containingClass); - } + ApplicationManager.getApplication().runReadAction(() -> { + final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) return; + if (containingClass instanceof PsiAnonymousClass) return; + if (containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) return; + if (containingClass.getContainingClass() != null && !containingClass.hasModifierProperty(PsiModifier.STATIC)) return; + if (JUnitUtil.isSuiteMethod(method) && testClassFilter.isAccepted(containingClass)) { + found.add(containingClass); } }); } @@ -127,59 +125,54 @@ public class ConfigurationUtil { ); if (testAnnotation != null) { //allScope is used to find all abstract test cases which probably have inheritors in the current 'scope' - ClassesWithAnnotatedMembersSearch.search(testAnnotation, GlobalSearchScope.allScope(manager.getProject())).forEach(new Processor() { - public boolean process(final PsiClass annotated) { - AccessToken token = ReadAction.start(); - try { - if (!processed.add(annotated)) { // don't process the same class twice regardless of it being in the scope + ClassesWithAnnotatedMembersSearch.search(testAnnotation, GlobalSearchScope.allScope(manager.getProject())).forEach(annotated -> { + AccessToken token = ReadAction.start(); + try { + if (!processed.add(annotated)) { // don't process the same class twice regardless of it being in the scope + return true; + } + final VirtualFile file = PsiUtilCore.getVirtualFile(annotated); + if (file != null && scope.contains(file) && testClassFilter.isAccepted(annotated)) { + if (!found.add(annotated)) { return true; } - final VirtualFile file = PsiUtilCore.getVirtualFile(annotated); - if (file != null && scope.contains(file) && testClassFilter.isAccepted(annotated)) { - if (!found.add(annotated)) { - return true; - } - isJUnit4.set(Boolean.TRUE); - } + isJUnit4.set(Boolean.TRUE); } - finally { - token.finish(); - } - if (table != null) { - SmartClassAnchor[] candidates = table.getAllSubtypes(annotated); - for (final SmartClassAnchor candidate : candidates) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - int fileId = candidate.myFileId; - VirtualFile file = PersistentFS.getInstance().findFileById(fileId); - if (file != null && scope.contains(file)) { - PsiClass aClass = ClassAnchorUtil.retrieve(manager.getProject(), candidate); - if (testClassFilter.isAccepted(aClass)) { - found.add(aClass); - processed.add(aClass); - isJUnit4.set(Boolean.TRUE); - } - } - } - }); - } - } - else { - ClassInheritorsSearch.search(annotated, scope, true, true, false).forEach(new ReadActionProcessor() { - @Override - public boolean processInReadAction(PsiClass aClass) { + } + finally { + token.finish(); + } + if (table != null) { + SmartClassAnchor[] candidates = table.getAllSubtypes(annotated); + for (final SmartClassAnchor candidate : candidates) { + ApplicationManager.getApplication().runReadAction(() -> { + int fileId = candidate.myFileId; + VirtualFile file = PersistentFS.getInstance().findFileById(fileId); + if (file != null && scope.contains(file)) { + PsiClass aClass = ClassAnchorUtil.retrieve(manager.getProject(), candidate); if (testClassFilter.isAccepted(aClass)) { found.add(aClass); processed.add(aClass); isJUnit4.set(Boolean.TRUE); } - return true; } }); } - return true; } + else { + ClassInheritorsSearch.search(annotated, scope, true, true, false).forEach(new ReadActionProcessor() { + @Override + public boolean processInReadAction(PsiClass aClass) { + if (testClassFilter.isAccepted(aClass)) { + found.add(aClass); + processed.add(aClass); + isJUnit4.set(Boolean.TRUE); + } + return true; + } + }); + } + return true; }); } diff --git a/plugins/junit/src/com/intellij/execution/junit/TestMethods.java b/plugins/junit/src/com/intellij/execution/junit/TestMethods.java index bbfb2ebf8913..7cb761ccaf02 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestMethods.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestMethods.java @@ -62,12 +62,7 @@ public class TestMethods extends TestMethod { final Project project = module.getProject(); final SourceScope scope = getSourceScope(); final GlobalSearchScope searchScope = scope != null ? scope.getGlobalSearchScope() : GlobalSearchScope.allScope(project); - addClassesListToJavaParameters(myFailedTests, new Function() { - @Override - public String fun(AbstractTestProxy testInfo) { - return testInfo != null ? getTestPresentation(testInfo, project, searchScope) : null; - } - }, data.getPackageName(), true, javaParameters); + addClassesListToJavaParameters(myFailedTests, testInfo -> testInfo != null ? getTestPresentation(testInfo, project, searchScope) : null, data.getPackageName(), true, javaParameters); return javaParameters; } diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java index d13a10e17203..67f8a594fa87 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java @@ -241,14 +241,11 @@ public abstract class TestObject extends JavaTestFrameworkRunnableState { + unboundOutputRoot.flush(); + packetsReceiver.checkTerminated(); + final JUnitRunningModel model = packetsReceiver.getModel(); + notifyByBalloon(model, myStarted, consoleProperties); }; handler.getOut().addRequest(runnable, queue); } @@ -348,11 +345,8 @@ public abstract class TestObject extends JavaTestFrameworkRunnableState> perModule = forkPerModule() ? new TreeMap>(new Comparator() { - @Override - public int compare(Module o1, Module o2) { - return StringUtil.compare(o1.getName(), o2.getName(), true); - } + final Map> perModule = forkPerModule() ? new TreeMap>((o1, o2) -> { + return StringUtil.compare(o1.getName(), o2.getName(), true); }) : null; final List testNames = new ArrayList(); diff --git a/plugins/junit/src/com/intellij/execution/junit/TestPackage.java b/plugins/junit/src/com/intellij/execution/junit/TestPackage.java index ddf2d17acca7..7de78f87a2a4 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestPackage.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestPackage.java @@ -88,13 +88,8 @@ public class TestPackage extends TestObject { myFoundTests = !myClasses.isEmpty(); try { - addClassesListToJavaParameters(myClasses, new Function() { - @Override - @Nullable - public String fun(final PsiClass psiClass) { - return psiClass != null ? JavaExecutionUtil.getRuntimeQualifiedName(psiClass) : null; - } - }, getPackageName(data), createTempFiles(), getJavaParameters()); + addClassesListToJavaParameters(myClasses, + psiClass -> psiClass != null ? JavaExecutionUtil.getRuntimeQualifiedName(psiClass) : null, getPackageName(data), createTempFiles(), getJavaParameters()); } catch (ExecutionException ignored) {} } diff --git a/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java b/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java index 62d35845bd5b..c7a67c110b78 100644 --- a/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java +++ b/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java @@ -74,12 +74,7 @@ public class TestsPattern extends TestPackage { protected void search() throws ExecutionException { final Function nameFunction = StringUtil.isEmpty(data.METHOD_NAME) ? FunctionUtil.id() - : new Function() { - @Override - public String fun(String className) { - return className; - } - }; + : (Function)className -> className; addClassesListToJavaParameters(classNames, nameFunction, "", false, getJavaParameters()); } diff --git a/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurationModel.java b/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurationModel.java index 9f04e6ac30bf..2e8b767654a7 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurationModel.java +++ b/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurationModel.java @@ -195,10 +195,8 @@ public class JUnitConfigurationModel { } } else { - WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { - public void run() { - ((Document)document).replaceString(0, ((Document)document).getTextLength(), text); - } + WriteCommandAction.runWriteCommandAction(myProject, () -> { + ((Document)document).replaceString(0, ((Document)document).getTextLength(), text); }); } } diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/ConsolePanel.java b/plugins/junit/src/com/intellij/execution/junit2/ui/ConsolePanel.java index 56b603429f5a..716ceb5aa15b 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/ConsolePanel.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/ConsolePanel.java @@ -152,12 +152,7 @@ public class ConsolePanel extends TestResultsPanel { private final ProcessAdapter myProcessListener = new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - doStop(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> doStop()); } }; diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/JUnitStatusLine.java b/plugins/junit/src/com/intellij/execution/junit2/ui/JUnitStatusLine.java index 60ecbef27875..a0604a5c219d 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/JUnitStatusLine.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/JUnitStatusLine.java @@ -54,15 +54,12 @@ class JUnitStatusLine extends TestStatusLine { @Override public void processTerminated(ProcessEvent event) { process.removeProcessListener(this); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myStateInfo.setTerminated(myState); - if (!myTestsBuilt && myProgressBar.getValue() == 0) { - setStatusColor(ColorProgressBar.RED); - setFraction(1.0); - myState.append(ExecutionBundle.message("junit.running.info.failed.to.start.error.message")); - } + ApplicationManager.getApplication().invokeLater(() -> { + myStateInfo.setTerminated(myState); + if (!myTestsBuilt && myProgressBar.getValue() == 0) { + setStatusColor(ColorProgressBar.RED); + setFraction(1.0); + myState.append(ExecutionBundle.message("junit.running.info.failed.to.start.error.message")); } }); } diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/model/JUnitRunningModel.java b/plugins/junit/src/com/intellij/execution/junit2/ui/model/JUnitRunningModel.java index beb0d013540c..34b25837b26b 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/ui/model/JUnitRunningModel.java +++ b/plugins/junit/src/com/intellij/execution/junit2/ui/model/JUnitRunningModel.java @@ -210,13 +210,11 @@ public class JUnitRunningModel implements TestFrameworkRunningModel { } public void focusGained(final FocusEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (!myTreeBuilder.isDisposed()) { - myNotifier.fireTestSelected((TestProxy)getTreeView().getSelectedTest()); - } - } - }); + ApplicationManager.getApplication().invokeLater(() -> { + if (!myTreeBuilder.isDisposed()) { + myNotifier.fireTestSelected((TestProxy)getTreeView().getSelectedTest()); + } + }); } public void install() { diff --git a/plugins/junit/test/com/intellij/execution/junit/JUnitRerunFailedTestsTest.java b/plugins/junit/test/com/intellij/execution/junit/JUnitRerunFailedTestsTest.java index 2b2584dbd96a..79d1ac4f4dd8 100644 --- a/plugins/junit/test/com/intellij/execution/junit/JUnitRerunFailedTestsTest.java +++ b/plugins/junit/test/com/intellij/execution/junit/JUnitRerunFailedTestsTest.java @@ -125,10 +125,8 @@ public class JUnitRerunFailedTestsTest extends LightCodeInsightFixtureTestCase testProxy.setLocator(JavaTestLocator.INSTANCE); final String presentation = TestMethods.getTestPresentation(testProxy, project, searchScope); assertEquals("ChildTest,testMe", presentation); - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - public void run() { - baseClass.getMethods()[0].setName("testName2"); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + baseClass.getMethods()[0].setName("testName2"); }); assertNull(TestMethods.getTestPresentation(testProxy, project, searchScope)); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java index ba3d265b7d10..5d4280da4458 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomProjectProcessorUtils.java @@ -73,11 +73,9 @@ public class MavenDomProjectProcessorUtils { public static Set collectParentProjects(@NotNull final MavenDomProjectModel projectDom) { final Set parents = new HashSet(); - Processor collectProcessor = new Processor() { - public boolean process(MavenDomProjectModel model) { - parents.add(model); - return false; - } + Processor collectProcessor = model -> { + parents.add(model); + return false; }; processParentProjects(projectDom, collectProcessor); @@ -146,14 +144,12 @@ public class MavenDomProjectProcessorUtils { public static Set collectProperties(@NotNull MavenDomProjectModel projectDom, @NotNull final Project project) { final Set properties = new HashSet(); - Processor collectProcessor = new Processor() { - public boolean process(MavenDomProperties mavenDomProperties) { - XmlTag propertiesTag = mavenDomProperties.getXmlTag(); - if (propertiesTag != null) { - ContainerUtil.addAll(properties, propertiesTag.getSubTags()); - } - return false; + Processor collectProcessor = mavenDomProperties -> { + XmlTag propertiesTag = mavenDomProperties.getXmlTag(); + if (propertiesTag != null) { + ContainerUtil.addAll(properties, propertiesTag.getSubTags()); } + return false; }; processProperties(projectDom, collectProcessor, project); @@ -180,17 +176,15 @@ public class MavenDomProjectProcessorUtils { @NotNull final Set excludes) { Project project = model.getManager().getProject(); final Set usages = new HashSet(); - Processor collectProcessor = new Processor() { - public boolean process(MavenDomProjectModel mavenDomProjectModel) { - for (MavenDomDependency domDependency : mavenDomProjectModel.getDependencies().getDependencies()) { - if (excludes.contains(domDependency)) continue; + Processor collectProcessor = mavenDomProjectModel -> { + for (MavenDomDependency domDependency : mavenDomProjectModel.getDependencies().getDependencies()) { + if (excludes.contains(domDependency)) continue; - if (dependencyId.equals(DependencyConflictId.create(domDependency))) { - usages.add(domDependency); - } + if (dependencyId.equals(DependencyConflictId.create(domDependency))) { + usages.add(domDependency); } - return false; } + return false; }; processChildrenRecursively(model, collectProcessor, project, new HashSet(), true); @@ -219,15 +213,13 @@ public class MavenDomProjectProcessorUtils { final Set usages = new HashSet(); - Processor collectProcessor = new Processor() { - public boolean process(MavenDomProjectModel mavenDomProjectModel) { - for (MavenDomPlugin domPlugin : mavenDomProjectModel.getBuild().getPlugins().getPlugins()) { - if (MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) { - usages.add(domPlugin); - } + Processor collectProcessor = mavenDomProjectModel -> { + for (MavenDomPlugin domPlugin : mavenDomProjectModel.getBuild().getPlugins().getPlugins()) { + if (MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) { + usages.add(domPlugin); } - return false; } + return false; }; processChildrenRecursively(model, collectProcessor, project, new HashSet(), true); @@ -285,16 +277,13 @@ public class MavenDomProjectProcessorUtils { final Ref res = new Ref(); - Processor processor = new Processor() { - @Override - public boolean process(MavenDomDependency dependency) { - if (depId.equals(DependencyConflictId.create(dependency))) { - res.set(dependency); - return true; - } - - return false; + Processor processor = dependency1 -> { + if (depId.equals(DependencyConflictId.create(dependency1))) { + res.set(dependency1); + return true; } + + return false; }; processDependenciesInDependencyManagement(model, processor, project); @@ -326,11 +315,8 @@ public class MavenDomProjectProcessorUtils { } }; - Function domProfileFunction = new Function() { - public MavenDomPlugins fun(MavenDomProjectModelBase mavenDomProfile) { - return mavenDomProfile.getBuild().getPluginManagement().getPlugins(); - } - }; + Function domProfileFunction = + mavenDomProfile -> mavenDomProfile.getBuild().getPluginManagement().getPlugins(); process(model, processor, model.getManager().getProject(), domProfileFunction, domProfileFunction); @@ -342,52 +328,46 @@ public class MavenDomProjectProcessorUtils { @NotNull final Processor processor, @NotNull final Project project) { - Processor managedDependenciesListProcessor = new Processor() { - @Override - public boolean process(MavenDomDependencies dependencies) { - SmartList importDependencies = null; + Processor managedDependenciesListProcessor = dependencies -> { + SmartList importDependencies = null; - for (MavenDomDependency domDependency : dependencies.getDependencies()) { - if ("import".equals(domDependency.getScope().getRawText())) { - if (importDependencies == null) { - importDependencies = new SmartList(); - } + for (MavenDomDependency domDependency : dependencies.getDependencies()) { + if ("import".equals(domDependency.getScope().getRawText())) { + if (importDependencies == null) { + importDependencies = new SmartList(); + } - importDependencies.add(domDependency); - } - else { - if (processor.process(domDependency)) return true; - } + importDependencies.add(domDependency); } + else { + if (processor.process(domDependency)) return true; + } + } - if (importDependencies != null) { - for (MavenDomDependency domDependency : importDependencies) { - GenericDomValue version = domDependency.getVersion(); - if (version.getXmlElement() != null) { - GenericDomValueReference reference = new GenericDomValueReference(version); - PsiElement resolve = reference.resolve(); + if (importDependencies != null) { + for (MavenDomDependency domDependency : importDependencies) { + GenericDomValue version = domDependency.getVersion(); + if (version.getXmlElement() != null) { + GenericDomValueReference reference = new GenericDomValueReference(version); + PsiElement resolve = reference.resolve(); - if (resolve instanceof XmlFile) { - MavenDomProjectModel dependModel = MavenDomUtil.getMavenDomModel((PsiFile)resolve, MavenDomProjectModel.class); - if (dependModel != null) { - for (MavenDomDependency dep : dependModel.getDependencyManagement().getDependencies().getDependencies()) { - if (processor.process(dep)) return true; - } + if (resolve instanceof XmlFile) { + MavenDomProjectModel dependModel = MavenDomUtil.getMavenDomModel((PsiFile)resolve, MavenDomProjectModel.class); + if (dependModel != null) { + for (MavenDomDependency dep : dependModel.getDependencyManagement().getDependencies().getDependencies()) { + if (processor.process(dep)) return true; } } } } } - - return false; } + + return false; }; - Function domFunction = new Function() { - public MavenDomDependencies fun(MavenDomProjectModelBase mavenDomProfile) { - return mavenDomProfile.getDependencyManagement().getDependencies(); - } - }; + Function domFunction = + mavenDomProfile -> mavenDomProfile.getDependencyManagement().getDependencies(); return process(projectDom, managedDependenciesListProcessor, project, domFunction, domFunction); } @@ -395,11 +375,7 @@ public class MavenDomProjectProcessorUtils { public static boolean processDependencies(@NotNull MavenDomProjectModel projectDom, @NotNull final Processor processor) { - Function domFunction = new Function() { - public MavenDomDependencies fun(MavenDomProjectModelBase mavenDomProfile) { - return mavenDomProfile.getDependencies(); - } - }; + Function domFunction = mavenDomProfile -> mavenDomProfile.getDependencies(); return process(projectDom, processor, projectDom.getManager().getProject(), domFunction, domFunction); } @@ -408,11 +384,7 @@ public class MavenDomProjectProcessorUtils { @NotNull final Processor processor, @NotNull final Project project) { - Function domFunction = new Function() { - public MavenDomProperties fun(MavenDomProjectModelBase mavenDomProfile) { - return mavenDomProfile.getProperties(); - } - }; + Function domFunction = mavenDomProfile -> mavenDomProfile.getProperties(); return process(projectDom, processor, project, domFunction, domFunction); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyCompletionUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyCompletionUtil.java index cf272277a10c..c0c951500ad4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyCompletionUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/converters/MavenDependencyCompletionUtil.java @@ -43,18 +43,15 @@ public class MavenDependencyCompletionUtil { final Ref ref = new Ref(); MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement(domModel, - new Processor() { - @Override - public boolean process(MavenDomDependency dependency) { - if (groupId.equals(dependency.getGroupId().getStringValue()) - && - artifactId.equals( - dependency.getArtifactId().getStringValue())) { - ref.set(dependency); - return true; - } - return false; + dependency -> { + if (groupId.equals(dependency.getGroupId().getStringValue()) + && + artifactId.equals( + dependency.getArtifactId().getStringValue())) { + ref.set(dependency); + return true; } + return false; }, project); return ref.get(); @@ -112,12 +109,8 @@ public class MavenDependencyCompletionUtil { } public static void invokeCompletion(@NotNull final InsertionContext context, final CompletionType completionType) { - context.setLaterRunnable(new Runnable() { - @Override - public void run() { - new CodeCompletionHandlerBase(completionType).invokeCompletion(context.getProject(), context.getEditor()); - } - }); + context.setLaterRunnable( + () -> new CodeCompletionHandlerBase(completionType).invokeCompletion(context.getProject(), context.getEditor())); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java index d1a033813e0a..01e339cdd1aa 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateDependencyUtil.java @@ -49,10 +49,8 @@ public class GenerateDependencyUtil { List dependencies = new ArrayList(); MavenDomProjectModelMember[] memberCandidates = - ContainerUtil.map2Array(candidates, MavenDomProjectModelMember.class, new Function() { - public MavenDomProjectModelMember fun(MavenDomDependency dependency) { - return new MavenDomProjectModelMember(dependency); - } + ContainerUtil.map2Array(candidates, MavenDomProjectModelMember.class, dependency -> { + return new MavenDomProjectModelMember(dependency); }); MemberChooser chooser = new MemberChooser(memberCandidates, true, true, project) { @@ -78,10 +76,8 @@ public class GenerateDependencyUtil { if (chooser.getExitCode() == MemberChooser.OK_EXIT_CODE) { final MavenDomProjectModelMember[] members = chooser.getSelectedElements(new MavenDomProjectModelMember[0]); if (members != null) { - dependencies.addAll(ContainerUtil.mapNotNull(members, new Function() { - public MavenDomDependency fun(MavenDomProjectModelMember mavenDomProjectModelMember) { - return mavenDomProjectModelMember.getDependency(); - } + dependencies.addAll(ContainerUtil.mapNotNull(members, mavenDomProjectModelMember -> { + return mavenDomProjectModelMember.getDependency(); })); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java index c7d3c6f37fec..a7b771fb155b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/GenerateManagedDependencyAction.java @@ -115,15 +115,13 @@ public class GenerateManagedDependencyAction extends GenerateDomElementAction { public static Map collectManagingDependencies(@NotNull final MavenDomProjectModel model) { final Map dependencies = new HashMap(); - Processor collectProcessor = new Processor() { - public boolean process(MavenDomDependency dependency) { - DependencyConflictId id = DependencyConflictId.create(dependency); - if (id != null && !dependencies.containsKey(id)) { - dependencies.put(id, dependency); - } - - return false; + Processor collectProcessor = dependency -> { + DependencyConflictId id = DependencyConflictId.create(dependency); + if (id != null && !dependencies.containsKey(id)) { + dependencies.put(id, dependency); } + + return false; }; MavenDomProjectProcessorUtils.processDependenciesInDependencyManagement(model, collectProcessor, model.getManager().getProject()); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java index 0710a04daa98..10376ef71382 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/generate/MavenGenerateDomActionGroup.java @@ -34,24 +34,12 @@ public class MavenGenerateDomActionGroup extends DefaultActionGroup { addSeparator(); add(createAction(MavenDomBundle.message("generate.dependency.template"), MavenDomDependency.class, "maven-dependency", - new Function() { - public DomElement fun(MavenDomProjectModel mavenDomProjectModel) { - return mavenDomProjectModel.getDependencies(); - } - })); + mavenDomProjectModel -> mavenDomProjectModel.getDependencies())); add(createAction(MavenDomBundle.message("generate.plugin.template"), MavenDomPlugin.class, "maven-plugin", - new Function() { - public DomElement fun(MavenDomProjectModel mavenDomProjectModel) { - return mavenDomProjectModel.getBuild().getPlugins(); - } - })); + mavenDomProjectModel -> mavenDomProjectModel.getBuild().getPlugins())); add(createAction(MavenDomBundle.message("generate.repository.template"), MavenDomRepository.class, "maven-repository", - new Function() { - public DomElement fun(MavenDomProjectModel mavenDomProjectModel) { - return mavenDomProjectModel.getRepositories(); - } - })); + mavenDomProjectModel -> mavenDomProjectModel.getRepositories())); addSeparator(); add(new GenerateParentAction()); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java index 63d3106cd737..6816e10c6536 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java @@ -143,11 +143,9 @@ public class MavenDuplicateDependenciesInspection extends DomElementsInspection< private static MultiMap getDuplicateDependenciesMap(MavenDomProjectModel projectModel) { final MultiMap allDependencies = MultiMap.createSet(); - Processor collectProcessor = new Processor() { - public boolean process(MavenDomProjectModel model) { - collect(allDependencies, model.getDependencies()); - return false; - } + Processor collectProcessor = model -> { + collect(allDependencies, model.getDependencies()); + return false; }; MavenDomProjectProcessorUtils.processChildrenRecursively(projectModel, collectProcessor, true); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenPomXmlCompletionTagListenerContributor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenPomXmlCompletionTagListenerContributor.java index 9e28f2e60598..9dc5f2825d6c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenPomXmlCompletionTagListenerContributor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenPomXmlCompletionTagListenerContributor.java @@ -46,50 +46,47 @@ public class MavenPomXmlCompletionTagListenerContributor extends CompletionContr if (!(description instanceof MavenDomProjectModelDescription)) return; - result.runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(CompletionResult r) { - final LookupElement lookupElement = r.getLookupElement(); + result.runRemainingContributors(parameters, r -> { + final LookupElement lookupElement = r.getLookupElement(); - if (myHandledTags.contains(lookupElement.getLookupString())) { - LookupElement decorator = - LookupElementDecorator.withInsertHandler(lookupElement, new InsertHandler>() { - @Override - public void handleInsert(final InsertionContext context, LookupElementDecorator item) { - lookupElement.handleInsert(context); + if (myHandledTags.contains(lookupElement.getLookupString())) { + LookupElement decorator = + LookupElementDecorator.withInsertHandler(lookupElement, new InsertHandler>() { + @Override + public void handleInsert(final InsertionContext context, LookupElementDecorator item) { + lookupElement.handleInsert(context); - Object object = lookupElement.getObject(); - if ("dependency".equals(lookupElement.getLookupString()) && object instanceof XmlTag - && "maven-4.0.0.xsd".equals(((XmlTag)object).getContainingFile().getName())) { - context.commitDocument(); + Object object = lookupElement.getObject(); + if ("dependency".equals(lookupElement.getLookupString()) && object instanceof XmlTag + && "maven-4.0.0.xsd".equals(((XmlTag)object).getContainingFile().getName())) { + context.commitDocument(); - CaretModel caretModel = context.getEditor().getCaretModel(); + CaretModel caretModel = context.getEditor().getCaretModel(); - PsiElement psiElement = context.getFile().findElementAt(caretModel.getOffset()); - XmlTag xmlTag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class); - if (xmlTag != null) { - DomElement domElement = DomManager.getDomManager(context.getProject()).getDomElement(xmlTag); - if (domElement instanceof MavenDomDependency) { - String s = "\n\n\n"; - context.getDocument().insertString(caretModel.getOffset(), s); - caretModel.moveToOffset(caretModel.getOffset() + s.length() - "\n".length()); + PsiElement psiElement = context.getFile().findElementAt(caretModel.getOffset()); + XmlTag xmlTag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class); + if (xmlTag != null) { + DomElement domElement = DomManager.getDomManager(context.getProject()).getDomElement(xmlTag); + if (domElement instanceof MavenDomDependency) { + String s = "\n\n\n"; + context.getDocument().insertString(caretModel.getOffset(), s); + caretModel.moveToOffset(caretModel.getOffset() + s.length() - "\n".length()); - context.commitDocument(); + context.commitDocument(); - new ReformatCodeProcessor(context.getProject(), context.getFile(), xmlTag.getTextRange(), false).run(); + new ReformatCodeProcessor(context.getProject(), context.getFile(), xmlTag.getTextRange(), false).run(); - MavenDependencyCompletionUtil.invokeCompletion(context, CompletionType.BASIC); - } + MavenDependencyCompletionUtil.invokeCompletion(context, CompletionType.BASIC); } } } - }); + } + }); - r = r.withLookupElement(decorator); - } - - result.passResult(r); + r = r.withLookupElement(decorator); } + + result.passResult(r); }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java index 6afb813c91a8..935a9efab408 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/ExtractManagedDependenciesAction.java @@ -216,13 +216,11 @@ public class ExtractManagedDependenciesAction extends BaseRefactoringAction { private static Function> getOccurencesFunction(final MavenDomDependency dependency) { - return new Function>() { - public Set fun(MavenDomProjectModel model) { - DependencyConflictId dependencyId = DependencyConflictId.create(dependency); - if (dependencyId == null) return Collections.emptySet(); + return model -> { + DependencyConflictId dependencyId = DependencyConflictId.create(dependency); + if (dependencyId == null) return Collections.emptySet(); - return MavenDomProjectProcessorUtils.searchDependencyUsages(model, dependencyId, Collections.singleton(dependency)); - } + return MavenDomProjectProcessorUtils.searchDependencyUsages(model, dependencyId, Collections.singleton(dependency)); }; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java index 5e7e107babef..1d36120cbf5b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java @@ -103,18 +103,16 @@ public class SelectMavenProjectDialog extends DialogWrapper { protected JComponent createCenterPanel() { ComboBoxUtil.setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), myMavenDomProjectModels, - new Function>() { - public Pair fun(MavenDomProjectModel model) { - String projectName = model.getName().getStringValue(); - MavenProject mavenProject = MavenDomUtil.findProject(model); - if (mavenProject != null) { - projectName = mavenProject.getDisplayName(); - } - if (StringUtil.isEmptyOrSpaces(projectName)) { - projectName = "pom.xml"; - } - return Pair.create(projectName, model); + model -> { + String projectName = model.getName().getStringValue(); + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + projectName = mavenProject.getDisplayName(); } + if (StringUtil.isEmptyOrSpaces(projectName)) { + projectName = "pom.xml"; + } + return Pair.create(projectName, model); }); myReplaceAllListener = new ItemListener() { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java index 7245313c6767..4a5afef254b2 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/refactorings/introduce/IntroducePropertyDialog.java @@ -201,18 +201,16 @@ public class IntroducePropertyDialog extends DialogWrapper { List projects = getProjects(); ComboBoxUtil - .setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), projects, new Function>() { - public Pair fun(MavenDomProjectModel model) { - String projectName = model.getName().getStringValue(); - MavenProject mavenProject = MavenDomUtil.findProject(model); - if (mavenProject != null) { - projectName = mavenProject.getDisplayName(); - } - if (StringUtil.isEmptyOrSpaces(projectName)) { - projectName = "pom.xml"; - } - return Pair.create(projectName, model); + .setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), projects, model -> { + String projectName = model.getName().getStringValue(); + MavenProject mavenProject = MavenDomUtil.findProject(model); + if (mavenProject != null) { + projectName = mavenProject.getDisplayName(); } + if (StringUtil.isEmptyOrSpaces(projectName)) { + projectName = "pom.xml"; + } + return Pair.create(projectName, model); }); myMavenProjectsComboBox.setSelectedItem(myMavenDomProjectModel); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java index 3939461fb802..b2ff58547f87 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPathReferenceConverter.java @@ -140,24 +140,21 @@ public class MavenPathReferenceConverter extends PathReferenceConverter { }; if (isAbsolutePath) { - set.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, new Function>() { - @Override - public Collection fun(PsiFile file) { - VirtualFile virtualFile = file.getVirtualFile(); + set.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, file -> { + VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile == null) { - return FileReferenceSet.ABSOLUTE_TOP_LEVEL.fun(file); - } - - virtualFile = VfsUtil.getRootFile(virtualFile); - PsiDirectory root = file.getManager().findDirectory(virtualFile); - - if (root == null) { - return FileReferenceSet.ABSOLUTE_TOP_LEVEL.fun(file); - } - - return Collections.singletonList(root); + if (virtualFile == null) { + return FileReferenceSet.ABSOLUTE_TOP_LEVEL.fun(file); } + + virtualFile = VfsUtil.getRootFile(virtualFile); + PsiDirectory root = file.getManager().findDirectory(virtualFile); + + if (root == null) { + return FileReferenceSet.ABSOLUTE_TOP_LEVEL.fun(file); + } + + return Collections.singletonList(root); }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java index bebd44da248c..d09139e29c1e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReference.java @@ -187,18 +187,15 @@ public class MavenPropertyPsiReference extends MavenPsiReference { MavenDomConfiguration pluginCfg = DomUtil.findDomElement(myElement, MavenDomConfiguration.class); if (pluginCfg != null) { - boolean notFound = MavenPluginDescriptor.processDescriptors(new Processor() { - @Override - public boolean process(MavenPluginDescriptor descriptor) { - if (descriptor.properties != null) { - for (MavenPluginDescriptor.ModelProperty property : descriptor.properties) { - if (property.insideConfigurationOnly && property.name.equals(myText)) { - return false; - } + boolean notFound = MavenPluginDescriptor.processDescriptors(descriptor -> { + if (descriptor.properties != null) { + for (MavenPluginDescriptor.ModelProperty property : descriptor.properties) { + if (property.insideConfigurationOnly && property.name.equals(myText)) { + return false; } } - return true; } + return true; }, pluginCfg); if (!notFound) { @@ -420,18 +417,15 @@ public class MavenPropertyPsiReference extends MavenPsiReference { MavenDomConfiguration pluginCfg = DomUtil.findDomElement(myElement, MavenDomConfiguration.class); if (pluginCfg != null) { - MavenPluginDescriptor.processDescriptors(new Processor() { - @Override - public boolean process(MavenPluginDescriptor descriptor) { - if (descriptor.properties != null) { - for (MavenPluginDescriptor.ModelProperty property : descriptor.properties) { - if (property.insideConfigurationOnly) { - result.add(LookupElementBuilder.create(property.name).withIcon(PlatformIcons.PROPERTY_ICON)); - } + MavenPluginDescriptor.processDescriptors(descriptor -> { + if (descriptor.properties != null) { + for (MavenPluginDescriptor.ModelProperty property : descriptor.properties) { + if (property.insideConfigurationOnly) { + result.add(LookupElementBuilder.create(property.name).withIcon(PlatformIcons.PROPERTY_ICON)); } } - return true; } + return true; }, pluginCfg); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java index f837f3205854..3a9163902cad 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalExecutor.java @@ -110,11 +110,7 @@ public class MavenExternalExecutor extends MavenExecutor { if (indicator != null) { if (indicator.isCanceled()) { if (!isCancelled()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - cancel(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> cancel()); } } if (text.matches(PHASE_INFO_REGEXP)) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java index 124fe9f7e031..2db92cdf63e1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenSelectProjectPopup.java @@ -53,21 +53,15 @@ public class MavenSelectProjectPopup { final JTextField workingDirectoryField, final JButton showModulesButton, @Nullable final JComponent focusAfterSelection) { - attachToButton(projectsManager, showModulesButton, new Consumer() { - @Override - public void consume(MavenProject project) { - workingDirectoryField.setText(project.getDirectory()); + attachToButton(projectsManager, showModulesButton, project -> { + workingDirectoryField.setText(project.getDirectory()); - if (focusAfterSelection != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (workingDirectoryField.hasFocus()) { - focusAfterSelection.requestFocus(); - } - } - }); - } + if (focusAfterSelection != null) { + ApplicationManager.getApplication().invokeLater(() -> { + if (workingDirectoryField.hasFocus()) { + focusAfterSelection.requestFocus(); + } + }); } }); @@ -136,22 +130,19 @@ public class MavenSelectProjectPopup { final Ref popupRef = new Ref(); - final Runnable clickCallBack = new Runnable() { - @Override - public void run() { - TreePath path = projectTree.getSelectionPath(); - if (path == null) return; + final Runnable clickCallBack = () -> { + TreePath path = projectTree.getSelectionPath(); + if (path == null) return; - Object lastPathComponent = path.getLastPathComponent(); - if (!(lastPathComponent instanceof DefaultMutableTreeNode)) return; + Object lastPathComponent = path.getLastPathComponent(); + if (!(lastPathComponent instanceof DefaultMutableTreeNode)) return; - Object object = ((DefaultMutableTreeNode)lastPathComponent).getUserObject(); - if (object == null) return; // may be it's the root + Object object = ((DefaultMutableTreeNode)lastPathComponent).getUserObject(); + if (object == null) return; // may be it's the root - callback.consume((MavenProject)object); + callback.consume((MavenProject)object); - popupRef.get().closeOk(null); - } + popupRef.get().closeOk(null); }; projectTree.addKeyListener(new KeyAdapter() { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java index 21cb8690c1a6..5ce48ec8e82a 100755 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenFoldersImporter.java @@ -117,12 +117,7 @@ public class MavenFoldersImporter { roots.putValues(JavaSourceRootType.TEST_SOURCE, myMavenProject.getTestSources()); for (MavenImporter each : MavenImporter.getSuitableImporters(myMavenProject)) { - each.collectSourceRoots(myMavenProject, new PairConsumer>() { - @Override - public void consume(String s, JpsModuleSourceRootType type) { - roots.putValue(type, s); - } - }); + each.collectSourceRoots(myMavenProject, (s, type) -> roots.putValue(type, s)); } for (MavenResource each : myMavenProject.getResources()) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java index 34cf8b44530c..0bd8d4631628 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java @@ -99,74 +99,35 @@ public class MavenModuleImporter { } public void preConfigFacets() { - MavenUtil.invokeAndWaitWriteAction(myModule.getProject(), new Runnable() { - public void run() { - if (myModule.isDisposed()) return; + MavenUtil.invokeAndWaitWriteAction(myModule.getProject(), () -> { + if (myModule.isDisposed()) return; - final ModuleType moduleType = ModuleType.get(myModule); + final ModuleType moduleType = ModuleType.get(myModule); - for (final MavenImporter importer : getSuitableImporters()) { - final MavenProjectChanges changes; - if (myMavenProjectChanges == null) { - if (importer.processChangedModulesOnly()) continue; - changes = MavenProjectChanges.NONE; - } - else { - changes = myMavenProjectChanges; - } + for (final MavenImporter importer : getSuitableImporters()) { + final MavenProjectChanges changes; + if (myMavenProjectChanges == null) { + if (importer.processChangedModulesOnly()) continue; + changes = MavenProjectChanges.NONE; + } + else { + changes = myMavenProjectChanges; + } - if (importer.getModuleType() == moduleType) { - importer.preProcess(myModule, myMavenProject, changes, myModifiableModelsProvider); - } + if (importer.getModuleType() == moduleType) { + importer.preProcess(myModule, myMavenProject, changes, myModifiableModelsProvider); } } }); } public void configFacets(final List postTasks) { - MavenUtil.smartInvokeAndWait(myModule.getProject(), ModalityState.defaultModalityState(), new Runnable() { - public void run() { - if (myModule.isDisposed()) return; + MavenUtil.smartInvokeAndWait(myModule.getProject(), ModalityState.defaultModalityState(), () -> { + if (myModule.isDisposed()) return; - final ModuleType moduleType = ModuleType.get(myModule); - - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (final MavenImporter importer : getSuitableImporters()) { - final MavenProjectChanges changes; - if (myMavenProjectChanges == null) { - if (importer.processChangedModulesOnly()) continue; - changes = MavenProjectChanges.NONE; - } - else { - changes = myMavenProjectChanges; - } - - if (importer.getModuleType() == moduleType) { - importer.process(myModifiableModelsProvider, - myModule, - myRootModelAdapter, - myMavenTree, - myMavenProject, - changes, - myMavenProjectToModuleName, - postTasks); - } - } - } - }); - } - }); - } - - public void postConfigFacets() { - MavenUtil.invokeAndWaitWriteAction(myModule.getProject(), new Runnable() { - public void run() { - if (myModule.isDisposed()) return; - - final ModuleType moduleType = ModuleType.get(myModule); + final ModuleType moduleType = ModuleType.get(myModule); + ApplicationManager.getApplication().runWriteAction(() -> { for (final MavenImporter importer : getSuitableImporters()) { final MavenProjectChanges changes; if (myMavenProjectChanges == null) { @@ -178,9 +139,39 @@ public class MavenModuleImporter { } if (importer.getModuleType() == moduleType) { - importer.postProcess(myModule, myMavenProject, changes, myModifiableModelsProvider); + importer.process(myModifiableModelsProvider, + myModule, + myRootModelAdapter, + myMavenTree, + myMavenProject, + changes, + myMavenProjectToModuleName, + postTasks); } } + }); + }); + } + + public void postConfigFacets() { + MavenUtil.invokeAndWaitWriteAction(myModule.getProject(), () -> { + if (myModule.isDisposed()) return; + + final ModuleType moduleType = ModuleType.get(myModule); + + for (final MavenImporter importer : getSuitableImporters()) { + final MavenProjectChanges changes; + if (myMavenProjectChanges == null) { + if (importer.processChangedModulesOnly()) continue; + changes = MavenProjectChanges.NONE; + } + else { + changes = myMavenProjectChanges; + } + + if (importer.getModuleType() == moduleType) { + importer.postProcess(myModule, myMavenProject, changes, myModifiableModelsProvider); + } } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java index 0e86ade4d880..45eb6b16ef3c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java @@ -139,22 +139,20 @@ public class MavenProjectImporter { } if (hasChanges) { - MavenUtil.invokeAndWaitWriteAction(myProject, new Runnable() { - public void run() { - myModelsProvider.commit(); + MavenUtil.invokeAndWaitWriteAction(myProject, () -> { + myModelsProvider.commit(); - if (projectsHaveChanges) { - removeOutdatedCompilerConfigSettings(); + if (projectsHaveChanges) { + removeOutdatedCompilerConfigSettings(); - for (MavenProject mavenProject : myAllProjects) { - Module module = myMavenProjectToModule.get(mavenProject); - if (module != null && module.isDisposed()) { - module = null; - } + for (MavenProject mavenProject : myAllProjects) { + Module module = myMavenProjectToModule.get(mavenProject); + if (module != null && module.isDisposed()) { + module = null; + } - for (MavenModuleConfigurer configurer : MavenModuleConfigurer.getConfigurers()) { - configurer.configure(mavenProject, myProject, module); - } + for (MavenModuleConfigurer configurer : MavenModuleConfigurer.getConfigurers()) { + configurer.configure(mavenProject, myProject, module); } } } @@ -168,11 +166,7 @@ public class MavenProjectImporter { } private void disposeModifiableModels() { - MavenUtil.invokeAndWaitWriteAction(myProject, new Runnable() { - public void run() { - myModelsProvider.dispose(); - } - }); + MavenUtil.invokeAndWaitWriteAction(myProject, () -> myModelsProvider.dispose()); } private boolean projectsToImportHaveChanges() { @@ -244,20 +238,18 @@ public class MavenProjectImporter { if (incompatibleNotMavenized.isEmpty()) return changed; final int[] result = new int[1]; - MavenUtil.invokeAndWait(myProject, myModelsProvider.getModalityStateForQuestionDialogs(), new Runnable() { - public void run() { - String message = ProjectBundle.message("maven.import.incompatible.modules", - incompatibleNotMavenized.size(), - formatProjectsWithModules(incompatibleNotMavenized)); - String[] options = { - ProjectBundle.message("maven.import.incompatible.modules.recreate"), - ProjectBundle.message("maven.import.incompatible.modules.ignore") - }; + MavenUtil.invokeAndWait(myProject, myModelsProvider.getModalityStateForQuestionDialogs(), () -> { + String message = ProjectBundle.message("maven.import.incompatible.modules", + incompatibleNotMavenized.size(), + formatProjectsWithModules(incompatibleNotMavenized)); + String[] options = { + ProjectBundle.message("maven.import.incompatible.modules.recreate"), + ProjectBundle.message("maven.import.incompatible.modules.ignore") + }; - result[0] = Messages.showOkCancelDialog(myProject, message, - ProjectBundle.message("maven.project.import.title"), - options[0], options[1], Messages.getQuestionIcon()); - } + result[0] = Messages.showOkCancelDialog(myProject, message, + ProjectBundle.message("maven.project.import.title"), + options[0], options[1], Messages.getQuestionIcon()); }); if (result[0] == Messages.OK) { @@ -296,17 +288,15 @@ public class MavenProjectImporter { } private static String formatProjectsWithModules(List> projectsWithModules) { - return StringUtil.join(projectsWithModules, new Function, String>() { - public String fun(Pair each) { - MavenProject project = each.first; - Module module = each.second; - return ModuleType.get(module).getName() + - " '" + - module.getName() + - "' for Maven project " + - project.getMavenId().getDisplayString(); - } - }, "
      "); + return StringUtil.join(projectsWithModules, each -> { + MavenProject project = each.first; + Module module = each.second; + return ModuleType.get(module).getName() + + " '" + + module.getName() + + "' for Maven project " + + project.getMavenId().getDisplayString(); + }, "
      "); } private boolean deleteObsoleteModules() { @@ -316,14 +306,11 @@ public class MavenProjectImporter { setMavenizedModules(obsoleteModules, false); final int[] result = new int[1]; - MavenUtil.invokeAndWait(myProject, myModelsProvider.getModalityStateForQuestionDialogs(), new Runnable() { - public void run() { - result[0] = Messages.showYesNoDialog(myProject, - ProjectBundle.message("maven.import.message.delete.obsolete", formatModules(obsoleteModules)), - ProjectBundle.message("maven.project.import.title"), - Messages.getQuestionIcon()); - } - }); + MavenUtil.invokeAndWait(myProject, myModelsProvider.getModalityStateForQuestionDialogs(), + () -> result[0] = Messages.showYesNoDialog(myProject, + ProjectBundle.message("maven.import.message.delete.obsolete", formatModules(obsoleteModules)), + ProjectBundle.message("maven.project.import.title"), + Messages.getQuestionIcon())); if (result[0] == Messages.NO) return false;// NO @@ -483,11 +470,7 @@ public class MavenProjectImporter { } private void setMavenizedModules(final Collection modules, final boolean mavenized) { - MavenUtil.invokeAndWaitWriteAction(myProject, new Runnable() { - public void run() { - MavenProjectsManager.getInstance(myProject).setMavenizedModules(modules, mavenized); - } - }); + MavenUtil.invokeAndWaitWriteAction(myProject, () -> MavenProjectsManager.getInstance(myProject).setMavenizedModules(modules, mavenized)); } private boolean ensureModuleCreated(MavenProject project) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java index ed4f931af2db..b370bfca22ed 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java @@ -439,14 +439,11 @@ public class MavenRootModelAdapter { public Library findLibrary(@NotNull final MavenArtifact artifact) { final String name = artifact.getLibraryName(); final Ref result = Ref.create(null); - myRootModel.orderEntries().forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - if (name.equals(library.getName())) { - result.set(library); - } - return true; + myRootModel.orderEntries().forEachLibrary(library -> { + if (name.equals(library.getName())) { + result.set(library); } + return true; }); return result.get(); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java index 9265edab4eb9..0524d157660c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenArtifactSearchPanel.java @@ -180,17 +180,14 @@ public class MavenArtifactSearchPanel extends JPanel { final String text = mySearchField.getText(); myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - try { - doSearch(text); - } - catch (Throwable e) { - MavenLog.LOG.warn(e); - } - } - }, 500); + myAlarm.addRequest(() -> { + try { + doSearch(text); + } + catch (Throwable e) { + MavenLog.LOG.warn(e); + } + }, 500); } private void resortUsingDependencyVersionMap(List result) { @@ -200,16 +197,13 @@ public class MavenArtifactSearchPanel extends JPanel { MavenArtifactInfo artifactInfo = searchResult.versions.get(0); final String managedVersion = myManagedDependenciesMap.get(Pair.create(artifactInfo.getGroupId(), artifactInfo.getArtifactId())); if (managedVersion != null) { - Collections.sort(searchResult.versions, new Comparator() { - @Override - public int compare(MavenArtifactInfo o1, MavenArtifactInfo o2) { - String v1 = o1.getVersion(); - String v2 = o2.getVersion(); - if (Comparing.equal(v1, v2)) return 0; - if (managedVersion.equals(v1)) return -1; - if (managedVersion.equals(v2)) return 1; - return 0; - } + Collections.sort(searchResult.versions, (o1, o2) -> { + String v1 = o1.getVersion(); + String v2 = o2.getVersion(); + if (Comparing.equal(v1, v2)) return 0; + if (managedVersion.equals(v1)) return -1; + if (managedVersion.equals(v2)) return 1; + return 0; }); } } @@ -223,16 +217,13 @@ public class MavenArtifactSearchPanel extends JPanel { final TreeModel model = new MyTreeModel(result); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!myDialog.isVisible()) return; + SwingUtilities.invokeLater(() -> { + if (!myDialog.isVisible()) return; - myResultList.getEmptyText().setText("No results"); - myResultList.setModel(model); - myResultList.setSelectionRow(0); - myResultList.setPaintBusy(false); - } + myResultList.getEmptyText().setText("No results"); + myResultList.setModel(model); + myResultList.setSelectionRow(0); + myResultList.setPaintBusy(false); }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenRepositoriesConfigurable.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenRepositoriesConfigurable.java index b9cbfb1a2415..437cae48b55f 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenRepositoriesConfigurable.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenRepositoriesConfigurable.java @@ -160,24 +160,21 @@ public class MavenRepositoriesConfigurable extends BaseConfigurable implements S private void testServiceConnection(String url) { myTestButton.setEnabled(false); - RepositoryAttachHandler.searchRepositories(myProject, Collections.singletonList(url), new Processor>() { - @Override - public boolean process(Collection infos) { - myTestButton.setEnabled(true); - if (infos.isEmpty()) { - Messages.showMessageDialog("No repositories found", "Service Connection Failed", Messages.getWarningIcon()); - } - else { - final StringBuilder sb = new StringBuilder(); - sb.append(infos.size()).append(infos.size() == 1 ? "repository" : " repositories").append(" found"); - //for (MavenRepositoryInfo info : infos) { - // sb.append("\n "); - // sb.append(info.getId()).append(" (").append(info.getName()).append(")").append(": ").append(info.getUrl()); - //} - Messages.showMessageDialog(sb.toString(), "Service Connection Successful", Messages.getInformationIcon()); - } - return true; + RepositoryAttachHandler.searchRepositories(myProject, Collections.singletonList(url), infos -> { + myTestButton.setEnabled(true); + if (infos.isEmpty()) { + Messages.showMessageDialog("No repositories found", "Service Connection Failed", Messages.getWarningIcon()); } + else { + final StringBuilder sb = new StringBuilder(); + sb.append(infos.size()).append(infos.size() == 1 ? "repository" : " repositories").append(" found"); + //for (MavenRepositoryInfo info : infos) { + // sb.append("\n "); + // sb.append(info.getId()).append(" (").append(info.getName()).append(")").append(": ").append(info.getUrl()); + //} + Messages.showMessageDialog(sb.toString(), "Service Connection Successful", Messages.getInformationIcon()); + } + return true; }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java index 54d6c5ed0974..cb23358c6c92 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenSearcher.java @@ -54,11 +54,7 @@ public abstract class MavenSearcher() { - public int compare(RESULT_TYPE o1, RESULT_TYPE o2) { - return makeSortKey(o1).compareTo(makeSortKey(o2)); - } - }); + Collections.sort(result, (o1, o2) -> makeSortKey(o1).compareTo(makeSortKey(o2))); } protected String makeSortKey(RESULT_TYPE result) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/javadoc/MojoClassAnnotationTagProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/javadoc/MojoClassAnnotationTagProvider.java index f846d7af7ed3..3f3acc93ca4e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/javadoc/MojoClassAnnotationTagProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/javadoc/MojoClassAnnotationTagProvider.java @@ -44,11 +44,8 @@ public class MojoClassAnnotationTagProvider implements CustomJavadocTagProvider @Override public List getSupportedTags() { - return ContainerUtil.map(ANNOTATION_NAMES, new Function() { - @Override - public JavadocTagInfo fun(String name) { - return new MojoAnnotationInfo(name); - } + return ContainerUtil.map(ANNOTATION_NAMES, name -> { + return new MojoAnnotationInfo(name); }); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java index d44a7533eada..39d8ebd6903d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsNavigator.java @@ -202,59 +202,34 @@ public class MavenProjectsNavigator extends MavenSimpleProjectComponent implemen myShortcutsManager.addListener(new MavenShortcutsManager.Listener() { @Override public void shortcutsUpdated() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateGoals(); - } - }); + scheduleStructureRequest(() -> myStructure.updateGoals()); } }); myTasksManager.addListener(new MavenTasksManager.Listener() { @Override public void compileTasksChanged() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateGoals(); - } - }); + scheduleStructureRequest(() -> myStructure.updateGoals()); } }); RunManagerEx.getInstanceEx(myProject).addRunManagerListener(new RunManagerAdapter() { @Override public void beforeRunTasksChanged() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateGoals(); - } - }); + scheduleStructureRequest(() -> myStructure.updateGoals()); } }); MavenRunner.getInstance(myProject).getSettings().addListener(new MavenRunnerSettings.Listener() { @Override public void skipTestsChanged() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateGoals(); - } - }); + scheduleStructureRequest(() -> myStructure.updateGoals()); } }); ((RunManagerEx)RunManager.getInstance(myProject)).addRunManagerListener(new RunManagerAdapter() { private void changed() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateRunConfigurations(); - } - }); + scheduleStructureRequest(() -> myStructure.updateRunConfigurations()); } @Override @@ -359,12 +334,7 @@ public class MavenProjectsNavigator extends MavenSimpleProjectComponent implemen } public void selectInTree(final MavenProject project) { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.select(project); - } - }); + scheduleStructureRequest(() -> myStructure.select(project)); } private void scheduleStructureRequest(final Runnable r) { @@ -376,28 +346,25 @@ public class MavenProjectsNavigator extends MavenSimpleProjectComponent implemen } if (myToolWindow == null) return; - MavenUtil.invokeLater(myProject, new Runnable() { - @Override - public void run() { - if (!myToolWindow.isVisible()) return; + MavenUtil.invokeLater(myProject, () -> { + if (!myToolWindow.isVisible()) return; - boolean shouldCreate = myStructure == null; - if (shouldCreate) { - initStructure(); - } + boolean shouldCreate = myStructure == null; + if (shouldCreate) { + initStructure(); + } - r.run(); + r.run(); - if (shouldCreate) { - if (myState.treeState != null) { - TreeState treeState = new TreeState(); - try { - treeState.readExternal(myState.treeState); - treeState.applyTo(myTree); - } - catch (InvalidDataException e) { - MavenLog.LOG.info(e); - } + if (shouldCreate) { + if (myState.treeState != null) { + TreeState treeState = new TreeState(); + try { + treeState.readExternal(myState.treeState); + treeState.applyTo(myTree); + } + catch (InvalidDataException e) { + MavenLog.LOG.info(e); } } } @@ -409,12 +376,7 @@ public class MavenProjectsNavigator extends MavenSimpleProjectComponent implemen } private void scheduleStructureUpdate() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.update(); - } - }); + scheduleStructureRequest(() -> myStructure.update()); } private class MyProjectsListener extends MavenProjectsTree.ListenerAdapter implements MavenProjectsManager.Listener { @@ -433,22 +395,12 @@ public class MavenProjectsNavigator extends MavenSimpleProjectComponent implemen @Override public void projectsIgnoredStateChanged(final List ignored, final List unignored, boolean fromImport) { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateIgnored(ContainerUtil.concat(ignored, unignored)); - } - }); + scheduleStructureRequest(() -> myStructure.updateIgnored(ContainerUtil.concat(ignored, unignored))); } @Override public void profilesChanged() { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateProfiles(); - } - }); + scheduleStructureRequest(() -> myStructure.updateProfiles()); } @Override @@ -468,12 +420,7 @@ public class MavenProjectsNavigator extends MavenSimpleProjectComponent implemen } private void scheduleUpdateProjects(final List projects, final List deleted) { - scheduleStructureRequest(new Runnable() { - @Override - public void run() { - myStructure.updateProjects(projects, deleted); - } - }); + scheduleStructureRequest(() -> myStructure.updateProjects(projects, deleted)); } } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java index add37a073d5b..5926fe921288 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java @@ -78,12 +78,7 @@ public class MavenProjectsStructure extends SimpleTreeStructure { private static final Collection BASIC_PHASES = MavenConstants.BASIC_PHASES; private static final Collection PHASES = MavenConstants.PHASES; - private static final Comparator NODE_COMPARATOR = new Comparator() { - @Override - public int compare(MavenSimpleNode o1, MavenSimpleNode o2) { - return StringUtil.compare(o1.getName(), o2.getName(), true); - } - }; + private static final Comparator NODE_COMPARATOR = (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true); private final Project myProject; private final MavenProjectsManager myProjectsManager; @@ -731,13 +726,11 @@ public class MavenProjectsStructure extends SimpleTreeStructure { }); JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle("Choose file to open ") - .setItemChoosenCallback(new Runnable() { - public void run() { - final Object value = list.getSelectedValue(); - if (value instanceof MavenDomProfile) { - final Navigatable navigatable = getNavigatable((MavenDomProfile)value); - if (navigatable != null) navigatable.navigate(requestFocus); - } + .setItemChoosenCallback(() -> { + final Object value = list.getSelectedValue(); + if (value instanceof MavenDomProfile) { + final Navigatable navigatable = getNavigatable((MavenDomProfile)value); + if (navigatable != null) navigatable.navigate(requestFocus); } }).createPopup().showInFocusCenter(); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/SelectInMavenNavigatorTarget.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/SelectInMavenNavigatorTarget.java index ee46c12cb8f7..2d1f44475cf9 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/SelectInMavenNavigatorTarget.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/SelectInMavenNavigatorTarget.java @@ -30,11 +30,7 @@ public class SelectInMavenNavigatorTarget implements SelectInTarget { } public void selectIn(final SelectInContext context, boolean requestFocus) { - Runnable r = new Runnable() { - public void run() { - MavenProjectsNavigator.getInstance(context.getProject()).selectInTree(getMavenProject(context)); - } - }; + Runnable r = () -> MavenProjectsNavigator.getInstance(context.getProject()).selectInTree(getMavenProject(context)); if (requestFocus) { ToolWindowManager.getInstance(context.getProject()).getToolWindow(getToolWindowId()).activate(r); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java index 5a562c31e59d..36d623c734bc 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenArtifactDownloader.java @@ -184,36 +184,34 @@ public class MavenArtifactDownloader { for (final DownloadElement eachElement : data.classifiersWithExtensions) { final int finalTotal = total; - futures.add(EXECUTOR.submit(new Runnable() { - public void run() { - try { - if (myProject.isDisposed()) return; + futures.add(EXECUTOR.submit(() -> { + try { + if (myProject.isDisposed()) return; - myProgress.checkCanceled(); - myProgress.setFraction(((double)downloaded.getAndIncrement()) / finalTotal); + myProgress.checkCanceled(); + myProgress.setFraction(((double)downloaded.getAndIncrement()) / finalTotal); - MavenArtifact a = myEmbedder.resolve(new MavenArtifactInfo(id, eachElement.extension, eachElement.classifier), - new ArrayList(data.repositories)); - File file = a.getFile(); - if (file.exists()) { - synchronized (downloadedFiles) { - downloadedFiles.add(file); + MavenArtifact a = myEmbedder.resolve(new MavenArtifactInfo(id, eachElement.extension, eachElement.classifier), + new ArrayList(data.repositories)); + File file = a.getFile(); + if (file.exists()) { + synchronized (downloadedFiles) { + downloadedFiles.add(file); - switch (eachElement.type) { - case SOURCES: - result.resolvedSources.add(id); - result.unresolvedSources.remove(id); - break; - case DOCS: - result.resolvedDocs.add(id); - result.unresolvedDocs.remove(id); - break; - } + switch (eachElement.type) { + case SOURCES: + result.resolvedSources.add(id); + result.unresolvedSources.remove(id); + break; + case DOCS: + result.resolvedDocs.add(id); + result.unresolvedDocs.remove(id); + break; } } } - catch (MavenProcessCanceledException ignore) { - } + } + catch (MavenProcessCanceledException ignore) { } })); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java index 535f4e2e1333..76eb84d8397a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java @@ -153,35 +153,33 @@ public class MavenConsoleImpl extends MavenConsole { private void ensureAttachedToToolWindow() { if (!isOpen.compareAndSet(false, true)) return; - MavenUtil.invokeLater(myProject, new Runnable() { - public void run() { - MessageView messageView = MessageView.SERVICE.getInstance(myProject); + MavenUtil.invokeLater(myProject, () -> { + MessageView messageView = MessageView.SERVICE.getInstance(myProject); - Content content = ContentFactory.SERVICE.getInstance().createContent( - myConsoleView.getComponent(), myTitle, true); - content.putUserData(CONSOLE_KEY, MavenConsoleImpl.this); - messageView.getContentManager().addContent(content); - messageView.getContentManager().setSelectedContent(content); + Content content = ContentFactory.SERVICE.getInstance().createContent( + myConsoleView.getComponent(), myTitle, true); + content.putUserData(CONSOLE_KEY, MavenConsoleImpl.this); + messageView.getContentManager().addContent(content); + messageView.getContentManager().setSelectedContent(content); - // remove unused tabs - for (Content each : messageView.getContentManager().getContents()) { - if (each.isPinned()) continue; - if (each == content) continue; + // remove unused tabs + for (Content each : messageView.getContentManager().getContents()) { + if (each.isPinned()) continue; + if (each == content) continue; - MavenConsoleImpl console = each.getUserData(CONSOLE_KEY); - if (console == null) continue; + MavenConsoleImpl console = each.getUserData(CONSOLE_KEY); + if (console == null) continue; - if (!myTitle.equals(console.myTitle)) continue; + if (!myTitle.equals(console.myTitle)) continue; - if (console.isFinished()) { - messageView.getContentManager().removeContent(each, true); - } + if (console.isFinished()) { + messageView.getContentManager().removeContent(each, true); } + } - ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW); - if (!toolWindow.isActive()) { - toolWindow.activate(null, false); - } + ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW); + if (!toolWindow.isActive()) { + toolWindow.activate(null, false); } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java index 4e5a992e0b76..a7c7ecb6b748 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEmbeddersManager.java @@ -54,11 +54,9 @@ public class MavenEmbeddersManager { } public synchronized void clearCaches() { - forEachPooled(false, new Function() { - public Object fun(MavenEmbedderWrapper each) { - each.clearCaches(); - return null; - } + forEachPooled(false, each -> { + each.clearCaches(); + return null; }); myEmbeddersToClear.addAll(myEmbeddersInUse); } @@ -111,11 +109,9 @@ public class MavenEmbeddersManager { } private synchronized void releasePooledEmbedders(boolean force) { - forEachPooled(force, new Function() { - public Object fun(MavenEmbedderWrapper each) { - each.release(); - return null; - } + forEachPooled(force, each -> { + each.release(); + return null; }); myPool.clear(); myEmbeddersInUse.clear(); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java index 229fb723d633..a5db6021d94c 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenEnvironmentForm.java @@ -66,23 +66,17 @@ public class MavenEnvironmentForm implements PanelWithAnchor { DocumentAdapter listener = new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (isUpdating) return; - if (!panel.isShowing()) return; + UIUtil.invokeLaterIfNeeded(() -> { + if (isUpdating) return; + if (!panel.isShowing()) return; - myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(new Runnable() { - @Override - public void run() { - isUpdating = true; - userSettingsFileOverrider.updateDefault(); - localRepositoryOverrider.updateDefault(); - isUpdating = false; - } - }, 100); - } + myUpdateAlarm.cancelAllRequests(); + myUpdateAlarm.addRequest(() -> { + isUpdating = true; + userSettingsFileOverrider.updateDefault(); + localRepositoryOverrider.updateDefault(); + isUpdating = false; + }, 100); }); } }; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenIgnoredFilesConfigurable.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenIgnoredFilesConfigurable.java index 043118d7d219..5063b2fc983b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenIgnoredFilesConfigurable.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenIgnoredFilesConfigurable.java @@ -78,11 +78,7 @@ public class MavenIgnoredFilesConfigurable implements SearchableConfigurable, Co MavenUIUtil.setElements(myIgnoredFilesPathsChooser, MavenUtil.collectPaths(myManager.getProjectsFiles()), myOriginallyIgnoredFilesPaths, - new Comparator() { - public int compare(String o1, String o2) { - return FileUtil.comparePaths(o1, o2); - } - }); + (o1, o2) -> FileUtil.comparePaths(o1, o2)); myIgnoredFilesPattersEditor.setText(myOriginallyIgnoredFilesPatterns); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java index 40c106a4adec..dbe7e7982064 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java @@ -496,19 +496,16 @@ public class MavenProjectReader { MavenLog.LOG.info(e); MavenLog.printInTests(e); // print exception since we need to know if something wrong with our logic - return ContainerUtil.mapNotNull(files, new Function() { - @Override - public MavenProjectReaderResult fun(VirtualFile file) { - MavenProjectReaderResult result = readProject(generalSettings, file, explicitProfiles, locator); - String message = e.getMessage(); - if (message != null) { - result.readingProblems.add(MavenProjectProblem.createStructureProblem(file.getPath(), message)); - } - else { - result.readingProblems.add(MavenProjectProblem.createSyntaxProblem(file.getPath(), MavenProjectProblem.ProblemType.SYNTAX)); - } - return result; + return ContainerUtil.mapNotNull(files, file -> { + MavenProjectReaderResult result = readProject(generalSettings, file, explicitProfiles, locator); + String message = e.getMessage(); + if (message != null) { + result.readingProblems.add(MavenProjectProblem.createStructureProblem(file.getPath(), message)); } + else { + result.readingProblems.add(MavenProjectProblem.createSyntaxProblem(file.getPath(), MavenProjectProblem.ProblemType.SYNTAX)); + } + return result; }); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java index 912264364299..91ece50eaf45 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java @@ -168,35 +168,30 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent StartupManagerEx startupManager = StartupManagerEx.getInstanceEx(myProject); - startupManager.registerStartupActivity(new Runnable() { - public void run() { - boolean wasMavenized = !myState.originalFiles.isEmpty(); - if (!wasMavenized) return; - initMavenized(); - } + startupManager.registerStartupActivity(() -> { + boolean wasMavenized = !myState.originalFiles.isEmpty(); + if (!wasMavenized) return; + initMavenized(); }); - startupManager.registerPostStartupActivity(new Runnable() { - @Override - public void run() { - if (!isMavenizedProject()) { - showNotificationOrphanMavenProject(myProject); - } - CompilerManager.getInstance(myProject).addBeforeTask(new CompileTask() { - @Override - public boolean execute(CompileContext context) { - AccessToken token = ReadAction.start(); - - try { - new MavenResourceCompilerConfigurationGenerator(myProject, myProjectsTree).generateBuildConfiguration(context.isRebuild()); - } - finally { - token.finish(); - } - return true; - } - }); + startupManager.registerPostStartupActivity(() -> { + if (!isMavenizedProject()) { + showNotificationOrphanMavenProject(myProject); } + CompilerManager.getInstance(myProject).addBeforeTask(new CompileTask() { + @Override + public boolean execute(CompileContext context) { + AccessToken token = ReadAction.start(); + + try { + new MavenResourceCompilerConfigurationGenerator(myProject, myProjectsTree).generateBuildConfiguration(context.isRebuild()); + } + finally { + token.finish(); + } + return true; + } + }); }); } @@ -575,16 +570,13 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent myWatcher.addManagedFilesWithProfiles(files, profiles); } - MavenUtil.invokeLater(myProject, new Runnable() { - @Override - public void run() { - if (myProject == null || !myProject.isDefault() && !myProject.isDisposed()) { - for (Notification notification : EventLog.getLogModel(myProject).getNotifications()) { - if (NON_MANAGED_POM_NOTIFICATION_GROUP_ID.equals(notification.getGroupId())) { - for (VirtualFile file : files) { - if (StringUtil.startsWith(notification.getContent(), file.getPresentableUrl())) { - notification.expire(); - } + MavenUtil.invokeLater(myProject, () -> { + if (myProject == null || !myProject.isDefault() && !myProject.isDisposed()) { + for (Notification notification : EventLog.getLogModel(myProject).getNotifications()) { + if (NON_MANAGED_POM_NOTIFICATION_GROUP_ID.equals(notification.getGroupId())) { + for (VirtualFile file : files) { + if (StringUtil.startsWith(notification.getContent(), file.getPresentableUrl())) { + notification.expire(); } } } @@ -846,84 +838,74 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent private AsyncPromise> scheduleResolve() { final AsyncPromise> result = new AsyncPromise>(); - runWhenFullyOpen(new Runnable() { - public void run() { - LinkedHashSet toResolve; - synchronized (myImportingDataLock) { - toResolve = new LinkedHashSet(myProjectsToResolve); - myProjectsToResolve.clear(); - } - if(toResolve.isEmpty()) return; + runWhenFullyOpen(() -> { + LinkedHashSet toResolve; + synchronized (myImportingDataLock) { + toResolve = new LinkedHashSet(myProjectsToResolve); + myProjectsToResolve.clear(); + } + if(toResolve.isEmpty()) return; - final ResolveContext context = new ResolveContext(); - Runnable onCompletion = new Runnable() { - @Override - public void run() { - if (hasScheduledProjects()) { - scheduleImport().processed(result); - } - else { - result.setResult(Collections.emptyList()); - } - } - }; - - final boolean useSinglePomResolver = Boolean.getBoolean("idea.maven.use.single.pom.resolver"); - if (useSinglePomResolver) { - Iterator it = toResolve.iterator(); - while (it.hasNext()) { - MavenProject each = it.next(); - myResolvingProcessor.scheduleTask(new MavenProjectsProcessorResolvingTask( - Collections.singleton(each), myProjectsTree, getGeneralSettings(), it.hasNext() ? null : onCompletion, context)); - } + final ResolveContext context = new ResolveContext(); + Runnable onCompletion = () -> { + if (hasScheduledProjects()) { + scheduleImport().processed(result); } else { - myResolvingProcessor.scheduleTask( - new MavenProjectsProcessorResolvingTask(toResolve, myProjectsTree, getGeneralSettings(), onCompletion, context)); + result.setResult(Collections.emptyList()); } + }; + + final boolean useSinglePomResolver = Boolean.getBoolean("idea.maven.use.single.pom.resolver"); + if (useSinglePomResolver) { + Iterator it = toResolve.iterator(); + while (it.hasNext()) { + MavenProject each = it.next(); + myResolvingProcessor.scheduleTask(new MavenProjectsProcessorResolvingTask( + Collections.singleton(each), myProjectsTree, getGeneralSettings(), it.hasNext() ? null : onCompletion, context)); + } + } + else { + myResolvingProcessor.scheduleTask( + new MavenProjectsProcessorResolvingTask(toResolve, myProjectsTree, getGeneralSettings(), onCompletion, context)); } }); return result; } public void evaluateEffectivePom(@NotNull final MavenProject mavenProject, @NotNull final NullableConsumer consumer) { - runWhenFullyOpen(new Runnable() { + runWhenFullyOpen(() -> myResolvingProcessor.scheduleTask(new MavenProjectsProcessorTask() { @Override - public void run() { - myResolvingProcessor.scheduleTask(new MavenProjectsProcessorTask() { - @Override - public void perform(Project project, - MavenEmbeddersManager embeddersManager, - MavenConsole console, - MavenProgressIndicator indicator) - throws MavenProcessCanceledException { + public void perform(Project project, + MavenEmbeddersManager embeddersManager, + MavenConsole console, + MavenProgressIndicator indicator) + throws MavenProcessCanceledException { - indicator.setText("Evaluating effective POM"); + indicator.setText("Evaluating effective POM"); - myProjectsTree.executeWithEmbedder(mavenProject, - getEmbeddersManager(), - MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE, - console, - indicator, - new MavenProjectsTree.EmbedderTask() { - @Override - public void run(MavenEmbedderWrapper embedder) throws MavenProcessCanceledException { - try { - MavenExplicitProfiles profiles = mavenProject.getActivatedProfilesIds(); - String res = - embedder.evaluateEffectivePom(mavenProject.getFile(), profiles.getEnabledProfiles(), - profiles.getDisabledProfiles()); - consumer.consume(res); - } - catch (UnsupportedOperationException e) { - consumer.consume(null); // null means UnsupportedOperationException - } - } - }); - } - }); + myProjectsTree.executeWithEmbedder(mavenProject, + getEmbeddersManager(), + MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE, + console, + indicator, + new MavenProjectsTree.EmbedderTask() { + @Override + public void run(MavenEmbedderWrapper embedder) throws MavenProcessCanceledException { + try { + MavenExplicitProfiles profiles = mavenProject.getActivatedProfilesIds(); + String res = + embedder.evaluateEffectivePom(mavenProject.getFile(), profiles.getEnabledProfiles(), + profiles.getDisabledProfiles()); + consumer.consume(res); + } + catch (UnsupportedOperationException e) { + consumer.consume(null); // null means UnsupportedOperationException + } + } + }); } - }); + })); } @TestOnly @@ -938,20 +920,15 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent } public void scheduleFoldersResolve(final Collection projects) { - runWhenFullyOpen(new Runnable() { - public void run() { - Iterator it = projects.iterator(); - while (it.hasNext()) { - MavenProject each = it.next(); - Runnable onCompletion = it.hasNext() ? null : new Runnable() { - @Override - public void run() { - if (hasScheduledProjects()) scheduleImport(); - } - }; - myFoldersResolvingProcessor.scheduleTask( - new MavenProjectsProcessorFoldersResolvingTask(each, getImportingSettings(), myProjectsTree, onCompletion)); - } + runWhenFullyOpen(() -> { + Iterator it = projects.iterator(); + while (it.hasNext()) { + MavenProject each = it.next(); + Runnable onCompletion = it.hasNext() ? null : (Runnable)() -> { + if (hasScheduledProjects()) scheduleImport(); + }; + myFoldersResolvingProcessor.scheduleTask( + new MavenProjectsProcessorFoldersResolvingTask(each, getImportingSettings(), myProjectsTree, onCompletion)); } }); } @@ -961,12 +938,8 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent } private void schedulePluginsResolve(final MavenProject project, final NativeMavenProjectHolder nativeMavenProject) { - runWhenFullyOpen(new Runnable() { - public void run() { - myPluginsResolvingProcessor - .scheduleTask(new MavenProjectsProcessorPluginsResolvingTask(project, nativeMavenProject, myProjectsTree)); - } - }); + runWhenFullyOpen(() -> myPluginsResolvingProcessor + .scheduleTask(new MavenProjectsProcessorPluginsResolvingTask(project, nativeMavenProject, myProjectsTree))); } public void scheduleArtifactsDownloading(final Collection projects, @@ -975,12 +948,8 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent @Nullable final AsyncResult result) { if (!sources && !docs) return; - runWhenFullyOpen(new Runnable() { - public void run() { - myArtifactsDownloadingProcessor - .scheduleTask(new MavenProjectsProcessorArtifactsDownloadingTask(projects, artifacts, myProjectsTree, sources, docs, result)); - } - }); + runWhenFullyOpen(() -> myArtifactsDownloadingProcessor + .scheduleTask(new MavenProjectsProcessorArtifactsDownloadingTask(projects, artifacts, myProjectsTree, sources, docs, result))); } private void scheduleImportSettings() { @@ -996,15 +965,11 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent private Promise> scheduleImport() { final AsyncPromise> result = new AsyncPromise>(); - runWhenFullyOpen(new Runnable() { + runWhenFullyOpen(() -> myImportingQueue.queue(new Update(MavenProjectsManager.this) { public void run() { - myImportingQueue.queue(new Update(MavenProjectsManager.this) { - public void run() { - result.setResult(importProjects()); - } - }); + result.setResult(importProjects()); } - }); + })); return result; } @@ -1056,11 +1021,7 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent @TestOnly public void performScheduledImportInTests() { if (!isInitialized()) return; - runWhenFullyOpen(new Runnable() { - public void run() { - myImportingQueue.flush(); - } - }); + runWhenFullyOpen(() -> myImportingQueue.flush()); } private void runWhenFullyOpen(final Runnable runnable) { @@ -1072,19 +1033,12 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent } final Ref wrapper = new Ref(); - wrapper.set(new Runnable() { - public void run() { - if (!StartupManagerEx.getInstanceEx(myProject).postStartupActivityPassed()) { - myInitializationAlarm.addRequest(new Runnable() { // should not remove previously schedules tasks - - public void run() { - wrapper.get().run(); - } - }, 1000); - return; - } - runnable.run(); + wrapper.set(() -> { + if (!StartupManagerEx.getInstanceEx(myProject).postStartupActivityPassed()) { + myInitializationAlarm.addRequest(() -> wrapper.get().run(), 1000); + return; } + runnable.run(); }); MavenUtil.runWhenInitialized(myProject, wrapper.get()); } @@ -1148,13 +1102,11 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent } public void updateProjectTargetFolders() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (myProject.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (myProject.isDisposed()) return; - MavenFoldersImporter.updateProjectFolders(myProject, true); - VirtualFileManager.getInstance().asyncRefresh(null); - } + MavenFoldersImporter.updateProjectFolders(myProject, true); + VirtualFileManager.getInstance().asyncRefresh(null); }); } @@ -1175,28 +1127,26 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent final Ref importer = new Ref(); final Ref> postTasks = new Ref>(); - final Runnable r = new Runnable() { - public void run() { - MavenProjectImporter projectImporter = new MavenProjectImporter(myProject, - myProjectsTree, - getFileToModuleMapping(new MavenModelsProvider() { - @Override - public Module[] getModules() { - return modelsProvider.getModules(); - } + final Runnable r = () -> { + MavenProjectImporter projectImporter = new MavenProjectImporter(myProject, + myProjectsTree, + getFileToModuleMapping(new MavenModelsProvider() { + @Override + public Module[] getModules() { + return modelsProvider.getModules(); + } - @Override - public VirtualFile[] getContentRoots(Module module) { - return modelsProvider.getContentRoots(module); - } - }), - projectsToImportWithChanges, - importModuleGroupsRequired, - modelsProvider, - getImportingSettings()); - importer.set(projectImporter); - postTasks.set(projectImporter.importProject()); - } + @Override + public VirtualFile[] getContentRoots(Module module) { + return modelsProvider.getContentRoots(module); + } + }), + projectsToImportWithChanges, + importModuleGroupsRequired, + modelsProvider, + getImportingSettings()); + importer.set(projectImporter); + postTasks.set(projectImporter.importProject()); }; // called from wizard or ui diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java index 423075f293cb..51c574f83b97 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java @@ -164,20 +164,15 @@ public class MavenProjectsManagerWatcher { myChangedDocuments.clear(); } - MavenUtil.invokeLater(myProject, new Runnable() { + MavenUtil.invokeLater(myProject, () -> new WriteAction() { @Override - public void run() { - new WriteAction() { - @Override - protected void run(@NotNull Result result) throws Throwable { - for (Document each : copy) { - PsiDocumentManager.getInstance(myProject).commitDocument(each); - ((FileDocumentManagerImpl)FileDocumentManager.getInstance()).saveDocument(each, false); - } - } - }.execute(); + protected void run(@NotNull Result result) throws Throwable { + for (Document each : copy) { + PsiDocumentManager.getInstance(myProject).commitDocument(each); + ((FileDocumentManagerImpl)FileDocumentManager.getInstance()).saveDocument(each, false); + } } - }); + }.execute()); } }); } @@ -301,27 +296,19 @@ public class MavenProjectsManagerWatcher { @NotNull private Runnable createScheduleImportAction(final boolean forceImportAndResolve, final AsyncPromise promise) { - return new Runnable() { - @Override - public void run() { - if (myProject.isDisposed()) { - promise.setError("Project disposed"); - return; - } + return () -> { + if (myProject.isDisposed()) { + promise.setError("Project disposed"); + return; + } - if (forceImportAndResolve || myManager.getImportingSettings().isImportAutomatically()) { - myManager.scheduleImportAndResolve().done(new Consumer>() { - @Override - public void consume(List modules) { - promise.setResult(null); - } - }); - } - else { - promise.setResult(null); - } - } - }; + if (forceImportAndResolve || myManager.getImportingSettings().isImportAutomatically()) { + myManager.scheduleImportAndResolve().done(modules -> promise.setResult(null)); + } + else { + promise.setResult(null); + } + }; } private void onSettingsChange() { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java index 0e3c07936f2d..e2fe324f583d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsProcessorArtifactsDownloadingTask.java @@ -57,15 +57,13 @@ public class MavenProjectsProcessorArtifactsDownloadingTask implements MavenProj if (myCallbackResult != null) myCallbackResult.setDone(result); // todo: hack to update all file pointers. - MavenUtil.invokeLater(project, new Runnable() { - public void run() { - AccessToken accessToken = WriteAction.start(); - try { - ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true); - } - finally { - accessToken.finish(); - } + MavenUtil.invokeLater(project, () -> { + AccessToken accessToken = WriteAction.start(); + try { + ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true); + } + finally { + accessToken.finish(); } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java index e36edb88194f..fe143ed49bd4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsTree.java @@ -249,19 +249,11 @@ public class MavenProjectsTree { } public void setIgnoredFilesPaths(final List paths) { - doChangeIgnoreStatus(new Runnable() { - public void run() { - myIgnoredFilesPaths = new ArrayList(paths); - } - }); + doChangeIgnoreStatus(() -> myIgnoredFilesPaths = new ArrayList(paths)); } public void removeIgnoredFilesPaths(final Collection paths) { - doChangeIgnoreStatus(new Runnable() { - public void run() { - myIgnoredFilesPaths.removeAll(paths); - } - }); + doChangeIgnoreStatus(() -> myIgnoredFilesPaths.removeAll(paths)); } public boolean getIgnoredState(MavenProject project) { @@ -280,14 +272,12 @@ public class MavenProjectsTree { private void doSetIgnoredState(List projects, final boolean ignored, boolean fromImport) { final List paths = MavenUtil.collectPaths(MavenUtil.collectFiles(projects)); - doChangeIgnoreStatus(new Runnable() { - public void run() { - if (ignored) { - myIgnoredFilesPaths.addAll(paths); - } - else { - myIgnoredFilesPaths.removeAll(paths); - } + doChangeIgnoreStatus(() -> { + if (ignored) { + myIgnoredFilesPaths.addAll(paths); + } + else { + myIgnoredFilesPaths.removeAll(paths); } }, fromImport); } @@ -299,11 +289,9 @@ public class MavenProjectsTree { } public void setIgnoredFilesPatterns(final List patterns) { - doChangeIgnoreStatus(new Runnable() { - public void run() { - myIgnoredFilesPatternsCache = null; - myIgnoredFilesPatterns = new ArrayList(patterns); - } + doChangeIgnoreStatus(() -> { + myIgnoredFilesPatternsCache = null; + myIgnoredFilesPatterns = new ArrayList(patterns); }); } @@ -1258,24 +1246,18 @@ public class MavenProjectsTree { try { process.checkCanceled(); - final List names = ContainerUtil.mapNotNull(mavenProjects, new Function() { - @Override - public String fun(MavenProject project) { - return project.getDisplayName(); - } + final List names = ContainerUtil.mapNotNull(mavenProjects, project12 -> { + return project12.getDisplayName(); }); final String text = StringUtil.shortenPathWithEllipsis(StringUtil.join(names, ", "), 200); process.setText(ProjectBundle.message("maven.resolving.pom", text)); process.setText2(""); final MavenExplicitProfiles explicitProfiles = new MavenExplicitProfiles(new LinkedHashSet(), new LinkedHashSet()); - Collection files = ContainerUtil.map(mavenProjects, new Function() { - @Override - public VirtualFile fun(MavenProject project) { - explicitProfiles.getEnabledProfiles().addAll(project.getActivatedProfilesIds().getEnabledProfiles()); - explicitProfiles.getDisabledProfiles().addAll(project.getActivatedProfilesIds().getDisabledProfiles()); - return project.getFile(); - } + Collection files = ContainerUtil.map(mavenProjects, project1 -> { + explicitProfiles.getEnabledProfiles().addAll(project1.getActivatedProfilesIds().getEnabledProfiles()); + explicitProfiles.getDisabledProfiles().addAll(project1.getActivatedProfilesIds().getDisabledProfiles()); + return project1.getFile(); }); Collection results = new MavenProjectReader().resolveProject( generalSettings, embedder, files, explicitProfiles, myProjectLocator); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResourceCompilerConfigurationGenerator.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResourceCompilerConfigurationGenerator.java index f8745ac71f4d..c3c4369c88a8 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResourceCompilerConfigurationGenerator.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenResourceCompilerConfigurationGenerator.java @@ -176,27 +176,24 @@ public class MavenResourceCompilerConfigurationGenerator { final Document document = new Document(new Element("maven-project-configuration")); XmlSerializer.serializeInto(projectConfig, document.getRootElement()); - buildManager.runCommand(new Runnable() { - @Override - public void run() { - buildManager.clearState(myProject); - FileUtil.createIfDoesntExist(mavenConfigFile); - try { - JDOMUtil.writeDocument(document, mavenConfigFile, "\n"); + buildManager.runCommand(() -> { + buildManager.clearState(myProject); + FileUtil.createIfDoesntExist(mavenConfigFile); + try { + JDOMUtil.writeDocument(document, mavenConfigFile, "\n"); - DataOutputStream crcOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(crcFile))); - try { - crcOutput.writeInt(crc); - } - finally { - crcOutput.close(); - } + DataOutputStream crcOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(crcFile))); + try { + crcOutput.writeInt(crc); } - catch (IOException e) { - LOG.debug("Unable to write config file", e); - throw new RuntimeException(e); + finally { + crcOutput.close(); } } + catch (IOException e) { + LOG.debug("Unable to write config file", e); + throw new RuntimeException(e); + } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/MavenShowEffectivePom.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/MavenShowEffectivePom.java index d92b7cb4ebcc..46d6b76b9fa6 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/MavenShowEffectivePom.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/MavenShowEffectivePom.java @@ -54,37 +54,29 @@ public class MavenShowEffectivePom extends AnAction implements DumbAware { final MavenProject mavenProject = manager.findProject(file); assert mavenProject != null; - manager.evaluateEffectivePom(mavenProject, new NullableConsumer() { - @Override - public void consume(final String s) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; + manager.evaluateEffectivePom(mavenProject, s -> ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; - if (s == null) { // null means UnsupportedOperationException - new Notification(MavenUtil.MAVEN_NOTIFICATION_GROUP, - "Error", - "Failed to evaluate effective pom.", - NotificationType.ERROR).notify(project); - return; - } - - String fileName = mavenProject.getMavenId().getArtifactId() + "-effective-pom.xml"; - PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, XMLLanguage.INSTANCE, s); - try { - //noinspection ConstantConditions - file.getVirtualFile().setWritable(false); - } - catch (IOException e) { - LOG.error(e); - } - - file.navigate(true); - } - }); + if (s == null) { // null means UnsupportedOperationException + new Notification(MavenUtil.MAVEN_NOTIFICATION_GROUP, + "Error", + "Failed to evaluate effective pom.", + NotificationType.ERROR).notify(project); + return; } - }); + + String fileName = mavenProject.getMavenId().getArtifactId() + "-effective-pom.xml"; + PsiFile file1 = PsiFileFactory.getInstance(project).createFileFromText(fileName, XMLLanguage.INSTANCE, s); + try { + //noinspection ConstantConditions + file1.getVirtualFile().setWritable(false); + } + catch (IOException e) { + LOG.error(e); + } + + file1.navigate(true); + })); } @Nullable diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java index 1c5c727dd09e..7bdb019be924 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java @@ -122,11 +122,8 @@ public abstract class MavenEmbedderWrapper extends RemoteObjectWrapper>() { @Override public Collection execute() throws RemoteException, MavenServerProcessCanceledException { - final List ioFiles = ContainerUtil.map(files, new Function() { - @Override - public File fun(VirtualFile file) { - return new File(file.getPath()); - } + final List ioFiles = ContainerUtil.map(files, file -> { + return new File(file.getPath()); }); return getOrCreateWrappee().resolveProject(ioFiles, activeProfiles, inactiveProfiles); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java index 7216c4e360a4..c401e0573010 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java @@ -444,11 +444,8 @@ public class MavenServerManager extends RemoteObjectWrapper impleme private static void addMavenLibs(List classpath, File mavenHome) { addDir(classpath, new File(mavenHome, "lib")); File bootFolder = new File(mavenHome, "boot"); - File[] classworldsJars = bootFolder.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return StringUtil.contains(name, "classworlds"); - } + File[] classworldsJars = bootFolder.listFiles((dir, name) -> { + return StringUtil.contains(name, "classworlds"); }); if (classworldsJars != null) { Collections.addAll(classpath, classworldsJars); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java index 501d7066c8f5..2003547371d6 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java @@ -153,52 +153,50 @@ public class MavenBeforeRunTasksProvider extends BeforeRunTaskProvider { + final Project project = CommonDataKeys.PROJECT.getData(context); + final MavenProject mavenProject = getMavenProject(task); - if (project == null || project.isDisposed() || mavenProject == null) return; + if (project == null || project.isDisposed() || mavenProject == null) return; - FileDocumentManager.getInstance().saveAllDocuments(); + FileDocumentManager.getInstance().saveAllDocuments(); - final MavenExplicitProfiles explicitProfiles = MavenProjectsManager.getInstance(project).getExplicitProfiles(); - final MavenRunner mavenRunner = MavenRunner.getInstance(project); + final MavenExplicitProfiles explicitProfiles = MavenProjectsManager.getInstance(project).getExplicitProfiles(); + final MavenRunner mavenRunner = MavenRunner.getInstance(project); - targetDone.down(); - new Task.Backgroundable(project, TasksBundle.message("maven.tasks.executing"), true) { - public void run(@NotNull ProgressIndicator indicator) { - try { - MavenRunnerParameters params = new MavenRunnerParameters( - true, - mavenProject.getDirectory(), - ParametersListUtil.parse(task.getGoal()), - explicitProfiles.getEnabledProfiles(), - explicitProfiles.getDisabledProfiles()); + targetDone.down(); + new Task.Backgroundable(project, TasksBundle.message("maven.tasks.executing"), true) { + public void run(@NotNull ProgressIndicator indicator) { + try { + MavenRunnerParameters params = new MavenRunnerParameters( + true, + mavenProject.getDirectory(), + ParametersListUtil.parse(task.getGoal()), + explicitProfiles.getEnabledProfiles(), + explicitProfiles.getDisabledProfiles()); - result[0] = mavenRunner.runBatch(Collections.singletonList(params), - null, - null, - TasksBundle.message("maven.tasks.executing"), - indicator); - } - finally { - targetDone.up(); - } - } - - @Override - public boolean shouldStartInBackground() { - return MavenRunner.getInstance(project).getSettings().isRunMavenInBackground(); - } - - @Override - public void processSentToBackground() { - MavenRunner.getInstance(project).getSettings().setRunMavenInBackground(true); - } - }.queue(); + result[0] = mavenRunner.runBatch(Collections.singletonList(params), + null, + null, + TasksBundle.message("maven.tasks.executing"), + indicator); + } + finally { + targetDone.up(); + } } - }, ModalityState.NON_MODAL); + + @Override + public boolean shouldStartInBackground() { + return MavenRunner.getInstance(project).getSettings().isRunMavenInBackground(); + } + + @Override + public void processSentToBackground() { + MavenRunner.getInstance(project).getSettings().setRunMavenInBackground(true); + } + }.queue(); + }, ModalityState.NON_MODAL); } catch (Exception e) { MavenLog.LOG.error(e); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java index 8aab5102533e..782b23c0ce77 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenKeymapExtension.java @@ -61,11 +61,7 @@ public class MavenKeymapExtension implements ExternalSystemKeymapExtension.Actio ); if (project == null) return result; - Comparator projectComparator = new Comparator() { - public int compare(MavenProject o1, MavenProject o2) { - return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); - } - }; + Comparator projectComparator = (o1, o2) -> o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); Map>> projectToActionsMapping = new TreeMap>>(projectComparator); @@ -82,15 +78,13 @@ public class MavenKeymapExtension implements ExternalSystemKeymapExtension.Actio Set> actions = projectToActionsMapping.get(mavenProject); if (actions == null) { final List projectGoals = collectGoals(mavenProject); - actions = new TreeSet>(new Comparator>() { - public int compare(Pair o1, Pair o2) { - String goal1 = o1.getFirst(); - String goal2 = o2.getFirst(); - int index1 = projectGoals.indexOf(goal1); - int index2 = projectGoals.indexOf(goal2); - if (index1 == index2) return goal1.compareToIgnoreCase(goal2); - return (index1 < index2 ? -1 : 1); - } + actions = new TreeSet>((o1, o2) -> { + String goal1 = o1.getFirst(); + String goal2 = o2.getFirst(); + int index1 = projectGoals.indexOf(goal1); + int index2 = projectGoals.indexOf(goal2); + if (index1 == index2) return goal1.compareToIgnoreCase(goal2); + return (index1 < index2 ? -1 : 1); }); projectToActionsMapping.put(mavenProject, actions); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java index 7e505f04431d..8c41ef17dde9 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenShortcutsManager.java @@ -255,12 +255,8 @@ public class MavenShortcutsManager extends MavenSimpleProjectComponent implement } private List selectScheduledProjects(final boolean forUpdate) { - return ContainerUtil.mapNotNull(mySheduledProjects.entrySet(), new Function, MavenProject>() { - @Override - public MavenProject fun(Map.Entry eachEntry) { - return forUpdate == eachEntry.getValue() ? eachEntry.getKey() : null; - } - }); + return ContainerUtil.mapNotNull(mySheduledProjects.entrySet(), + eachEntry -> forUpdate == eachEntry.getValue() ? eachEntry.getKey() : null); } } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEditorTabTitleUpdater.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEditorTabTitleUpdater.java index 910719ff570b..9fc34de11a22 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEditorTabTitleUpdater.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenEditorTabTitleUpdater.java @@ -44,11 +44,9 @@ public class MavenEditorTabTitleUpdater extends MavenSimpleProjectComponent { } private void updateTabName(final List projects) { - MavenUtil.invokeLater(myProject, new Runnable() { - public void run() { - for (MavenProject each : projects) { - FileEditorManagerEx.getInstanceEx(myProject).updateFilePresentation(each.getFile()); - } + MavenUtil.invokeLater(myProject, () -> { + for (MavenProject each : projects) { + FileEditorManagerEx.getInstanceEx(myProject).updateFilePresentation(each.getFile()); } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java index 4ea05ca1764f..3eb93eb5526a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java @@ -149,23 +149,21 @@ public class MavenMergingUpdateQueue extends MergingUpdateQueue { } public void makeModalAware(Project project) { - MavenUtil.invokeLater(project, new Runnable() { - public void run() { - final ModalityStateListener listener = new ModalityStateListener() { - @Override - public void beforeModalityStateChanged(boolean entering) { - if (entering) { - suspend(); - } - else { - resume(); - } + MavenUtil.invokeLater(project, () -> { + final ModalityStateListener listener = new ModalityStateListener() { + @Override + public void beforeModalityStateChanged(boolean entering) { + if (entering) { + suspend(); + } + else { + resume(); } - }; - LaterInvocator.addModalityStateListener(listener, MavenMergingUpdateQueue.this); - if (MavenUtil.isInModalContext()) { - suspend(); } + }; + LaterInvocator.addModalityStateListener(listener, MavenMergingUpdateQueue.this); + if (MavenUtil.isInModalContext()) { + suspend(); } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java index 238a7895884d..019dafc946c1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenUtil.java @@ -166,15 +166,12 @@ public class MavenUtil { else { final Semaphore semaphore = new Semaphore(); semaphore.down(); - DumbService.getInstance(p).smartInvokeLater(new Runnable() { - @Override - public void run() { - try { - r.run(); - } - finally { - semaphore.up(); - } + DumbService.getInstance(p).smartInvokeLater(() -> { + try { + r.run(); + } + finally { + semaphore.up(); } }, state); semaphore.waitFor(); @@ -182,11 +179,7 @@ public class MavenUtil { } public static void invokeAndWaitWriteAction(Project p, final Runnable r) { - invokeAndWait(p, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(r); - } - }); + invokeAndWait(p, () -> ApplicationManager.getApplication().runWriteAction(r)); } public static void runDumbAware(final Project project, final Runnable r) { @@ -259,18 +252,14 @@ public class MavenUtil { } public static List collectPaths(List files) { - return ContainerUtil.map(files, new Function() { - public String fun(VirtualFile file) { - return file.getPath(); - } + return ContainerUtil.map(files, file -> { + return file.getPath(); }); } public static List collectFiles(Collection projects) { - return ContainerUtil.map(projects, new Function() { - public VirtualFile fun(MavenProject project) { - return project.getFile(); - } + return ContainerUtil.map(projects, project -> { + return project.getFile(); }); } @@ -283,10 +272,8 @@ public class MavenUtil { } public static List> mapToList(Map map) { - return ContainerUtil.map2List(map.entrySet(), new Function, Pair>() { - public Pair fun(Map.Entry tuEntry) { - return Pair.create(tuEntry.getKey(), tuEntry.getValue()); - } + return ContainerUtil.map2List(map.entrySet(), tuEntry -> { + return Pair.create(tuEntry.getKey(), tuEntry.getValue()); }); } @@ -451,19 +438,17 @@ public class MavenUtil { final MavenTask task) { final MavenProgressIndicator indicator = new MavenProgressIndicator(); - Runnable runnable = new Runnable() { - public void run() { - if (project.isDisposed()) return; + Runnable runnable = () -> { + if (project.isDisposed()) return; - try { - task.run(indicator); - } - catch (MavenProcessCanceledException ignore) { - indicator.cancel(); - } - catch (ProcessCanceledException ignore) { - indicator.cancel(); - } + try { + task.run(indicator); + } + catch (MavenProcessCanceledException ignore) { + indicator.cancel(); + } + catch (ProcessCanceledException ignore) { + indicator.cancel(); } }; @@ -489,16 +474,14 @@ public class MavenUtil { } } }; - invokeLater(project, new Runnable() { - public void run() { - if (future.isDone()) return; - new Task.Backgroundable(project, title, cancellable) { - public void run(@NotNull ProgressIndicator i) { - indicator.setIndicator(i); - handler.waitFor(); - } - }.queue(); - } + invokeLater(project, () -> { + if (future.isDone()) return; + new Task.Backgroundable(project, title, cancellable) { + public void run(@NotNull ProgressIndicator i) { + indicator.setIndicator(i); + handler.waitFor(); + } + }.queue(); }); return handler; } @@ -602,12 +585,7 @@ public class MavenUtil { } if (list.length > 1) { - Arrays.sort(list, new Comparator() { - @Override - public int compare(String o1, String o2) { - return StringUtil.compareVersionNumbers(o2, o1); - } - }); + Arrays.sort(list, (o1, o2) -> StringUtil.compareVersionNumbers(o2, o1)); } final File file = new File(brewDir, list[0] + "/libexec"); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java index 499b6dd99d2d..149cb1e1d1a1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/RepositoryAttachDialog.java @@ -117,11 +117,9 @@ public class RepositoryAttachDialog extends DialogWrapper { textField.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - if (myProgressIcon.isDisposed()) return; - updateComboboxSelection(false); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myProgressIcon.isDisposed()) return; + updateComboboxSelection(false); }); } }); @@ -250,36 +248,34 @@ public class RepositoryAttachDialog extends DialogWrapper { if (myCoordinates.containsKey(text)) return false; if (myProgressIcon.isRunning()) return false; myProgressIcon.resume(); - RepositoryAttachHandler.searchArtifacts(myProject, text, new PairProcessor>, Boolean>() { - public boolean process(Collection> artifacts, Boolean tooMany) { - if (myProgressIcon.isDisposed()) return false; - if (tooMany != null) myProgressIcon.suspend(); // finished - final int prevSize = myCoordinates.size(); - for (Pair each : artifacts) { - myCoordinates.put(each.first.getGroupId() + ":" + each.first.getArtifactId() + ":" + each.first.getVersion(), each); - String url = each.second != null? each.second.getUrl() : null; - if (StringUtil.isNotEmpty(url) && !myRepositories.containsKey(url)) { - myRepositories.put(url, each.second); - } - } - String title = getTitle(); - String tooManyMessage = ": too many results found"; - if (tooMany != null) { - boolean alreadyThere = title.endsWith(tooManyMessage); - if (tooMany.booleanValue() && !alreadyThere) { - setTitle(title + tooManyMessage); - } - else if (!tooMany.booleanValue() && alreadyThere) { - setTitle(title.substring(0, title.length() - tooManyMessage.length())); - } - } - updateComboboxSelection(prevSize != myCoordinates.size()); - // tooMany != null on last call, so enable OK action to let - // local maven repo a chance even if all remote services failed - setOKActionEnabled(!myRepositories.isEmpty() || tooMany != null); - return true; + RepositoryAttachHandler.searchArtifacts(myProject, text, (artifacts, tooMany) -> { + if (myProgressIcon.isDisposed()) return false; + if (tooMany != null) myProgressIcon.suspend(); // finished + final int prevSize = myCoordinates.size(); + for (Pair each : artifacts) { + myCoordinates.put(each.first.getGroupId() + ":" + each.first.getArtifactId() + ":" + each.first.getVersion(), each); + String url = each.second != null? each.second.getUrl() : null; + if (StringUtil.isNotEmpty(url) && !myRepositories.containsKey(url)) { + myRepositories.put(url, each.second); } - }); + } + String title = getTitle(); + String tooManyMessage = ": too many results found"; + if (tooMany != null) { + boolean alreadyThere = title.endsWith(tooManyMessage); + if (tooMany.booleanValue() && !alreadyThere) { + setTitle(title + tooManyMessage); + } + else if (!tooMany.booleanValue() && alreadyThere) { + setTitle(title.substring(0, title.length() - tooManyMessage.length())); + } + } + updateComboboxSelection(prevSize != myCoordinates.size()); + // tooMany != null on last call, so enable OK action to let + // local maven repo a chance even if all remote services failed + setOKActionEnabled(!myRepositories.isEmpty() || tooMany != null); + return true; + }); return true; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAddLibraryAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAddLibraryAction.java index 1da01a531c6f..456d976ca87d 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAddLibraryAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAddLibraryAction.java @@ -57,11 +57,8 @@ public class RepositoryAddLibraryAction extends IntentionAndQuickFixAction { module, modifiableModel, modifiableModelsProvider); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifiableModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + modifiableModel.commit(); }); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java index b12502c6d3b8..ea2c9a0c3737 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java @@ -141,20 +141,18 @@ public class RepositoryAttachHandler { if (attachSources) extraTypes.add(MavenExtraArtifactType.SOURCES); if (attachJavaDoc) extraTypes.add(MavenExtraArtifactType.DOCS); final Ref> result = Ref.create(null); - doResolveInner(project, getMavenId(coord), extraTypes, repositories, new Processor>() { - public boolean process(final List artifacts) { - if (!artifacts.isEmpty()) { - AccessToken accessToken = WriteAction.start(); - try { - final List roots = createRoots(artifacts, copyTo); - result.set(roots); - } - finally { - accessToken.finish(); - } + doResolveInner(project, getMavenId(coord), extraTypes, repositories, artifacts -> { + if (!artifacts.isEmpty()) { + AccessToken accessToken = WriteAction.start(); + try { + final List roots = createRoots(artifacts, copyTo); + result.set(roots); + } + finally { + accessToken.finish(); } - return true; } + return true; }, indicator); List roots = result.get(); @@ -270,10 +268,8 @@ public class RepositoryAttachHandler { if (!proceedFlag.get()) break; final Boolean aBoolean = i == length - 1 ? tooManyResults : null; ApplicationManager.getApplication().invokeLater( - new Runnable() { - public void run() { - proceedFlag.set(resultProcessor.process(resultList, aBoolean)); - } + () -> { + proceedFlag.set(resultProcessor.process(resultList, aBoolean)); }, new Condition() { @Override public boolean value(Object o) { @@ -312,11 +308,7 @@ public class RepositoryAttachHandler { MavenLog.LOG.error(e); } finally { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - resultProcessor.process(result.get()); - } - }); + ApplicationManager.getApplication().invokeLater(() -> resultProcessor.process(result.get())); } } }); @@ -348,18 +340,9 @@ public class RepositoryAttachHandler { } // download docs & sources if (!extraTypes.isEmpty()) { - Set allowedClassifiers = JBIterable.from(extraTypes).transform(new Function() { - @Override - public String fun(MavenExtraArtifactType extraType) { - return extraType.getDefaultClassifier(); - } - }).toSet(); - List resolve = JBIterable.from(extraTypes).transform(new Function() { - @Override - public MavenArtifactInfo fun(MavenExtraArtifactType extraType) { - return new MavenArtifactInfo(mavenId, extraType.getDefaultExtension(), extraType.getDefaultClassifier()); - } - }).toList(); + Set allowedClassifiers = JBIterable.from(extraTypes).transform(extraType -> extraType.getDefaultClassifier()).toSet(); + List resolve = JBIterable.from(extraTypes).transform( + extraType -> new MavenArtifactInfo(mavenId, extraType.getDefaultExtension(), extraType.getDefaultClassifier())).toList(); // skip sources/javadoc for dependencies for (MavenArtifact artifact : embedder.resolveTransitively(new ArrayList(resolve), remoteRepositories)) { if (!artifact.isResolved() || MavenConstants.SCOPE_TEST.equals(artifact.getScope()) || !allowedClassifiers.contains(artifact.getClassifier())) { @@ -375,16 +358,8 @@ public class RepositoryAttachHandler { finally { manager.release(embedder); if (!cancelled && resultProcessor != null) { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - public void run() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - resultProcessor.process(new ArrayList(result)); - } - }); - } - }, indicator.getModalityState()); + ApplicationManager.getApplication().invokeAndWait(() -> DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> resultProcessor.process(new ArrayList(result))), indicator.getModalityState()); } } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySupport.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySupport.java index 9d1268b61dc7..5f219006b590 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySupport.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySupport.java @@ -91,11 +91,8 @@ public class RepositoryLibrarySupport { RepositoryLibraryProperties realLibraryProperties = (RepositoryLibraryProperties)library.getProperties(); realLibraryProperties.setMavenId(libraryProperties.getMavenId()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - modifiableModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + modifiableModel.commit(); }); RepositoryUtils.loadDependencies( module.getProject(), diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySynchronizer.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySynchronizer.java index 5f331bae62f8..31e68977e3ce 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySynchronizer.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryLibrarySynchronizer.java @@ -59,24 +59,18 @@ public class RepositoryLibrarySynchronizer implements StartupActivity, DumbAware private static Collection collectLibraries(final @NotNull Project project, final @NotNull Predicate predicate) { final HashSet result = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (final Module module : ModuleManager.getInstance(project).getModules()) { - OrderEnumerator.orderEntries(module).withoutSdk().forEachLibrary(new Processor() { - @Override - public boolean process(Library library) { - if (predicate.apply(library)) { - result.add(library); - } - return true; - } - }); - } - for (Library library : ProjectLibraryTable.getInstance(project).getLibraries()) { + ApplicationManager.getApplication().runReadAction(() -> { + for (final Module module : ModuleManager.getInstance(project).getModules()) { + OrderEnumerator.orderEntries(module).withoutSdk().forEachLibrary(library -> { if (predicate.apply(library)) { result.add(library); } + return true; + }); + } + for (Library library : ProjectLibraryTable.getInstance(project).getLibraries()) { + if (predicate.apply(library)) { + result.add(library); } } }); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryUtils.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryUtils.java index bacb1f6dcde9..b9811c3a0c9b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryUtils.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryUtils.java @@ -81,24 +81,16 @@ public class RepositoryUtils { } final String localRepositoryPath = FileUtil.toSystemIndependentName(MavenProjectsManager.getInstance(project).getLocalRepository().getPath()); - List roots = JBIterable.of(urls).transform(new Function() { - @Override - public String fun(String urlWithPrefix) { - String url = StringUtil.trimStart(urlWithPrefix, JarFileSystem.PROTOCOL_PREFIX); - return url.startsWith(localRepositoryPath) ? null : FileUtil.toSystemDependentName(PathUtil.getParentPath(url)); - } + List roots = JBIterable.of(urls).transform(urlWithPrefix -> { + String url = StringUtil.trimStart(urlWithPrefix, JarFileSystem.PROTOCOL_PREFIX); + return url.startsWith(localRepositoryPath) ? null : FileUtil.toSystemDependentName(PathUtil.getParentPath(url)); }).toList(); Map counts = new HashMap(); for (String root : roots) { int count = counts.get(root) != null ? counts.get(root) : 0; counts.put(root, count + 1); } - return Collections.max(counts.entrySet(), new Comparator>() { - @Override - public int compare(Map.Entry o1, Map.Entry o2) { - return o1.getValue().compareTo(o2.getValue()); - } - }).getKey(); + return Collections.max(counts.entrySet(), (o1, o2) -> o1.getValue().compareTo(o2.getValue())).getKey(); } public static String resolveEffectiveVersion(@NotNull Project project, @NotNull RepositoryLibraryProperties properties) { @@ -145,33 +137,26 @@ public class RepositoryUtils { @Override public void process(final @Nullable List roots) { if (roots == null || roots.isEmpty()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(project, ProjectBundle.message("maven.downloading.failed", properties.getMavenId()), - CommonBundle.getErrorTitle()); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(project, ProjectBundle.message("maven.downloading.failed", properties.getMavenId()), + CommonBundle.getErrorTitle())); return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (library.isDisposed()) { - return; - } - AccessToken token = WriteAction.start(); - try { - final NewLibraryEditor editor = new NewLibraryEditor(null, properties); - editor.removeAllRoots(); - editor.addRoots(roots); - final Library.ModifiableModel model = library.getModifiableModel(); - editor.applyTo((LibraryEx.ModifiableModelEx)model); - model.commit(); - } - finally { - token.finish(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (library.isDisposed()) { + return; + } + AccessToken token = WriteAction.start(); + try { + final NewLibraryEditor editor = new NewLibraryEditor(null, properties); + editor.removeAllRoots(); + editor.addRoots(roots); + final Library.ModifiableModel model = library.getModifiableModel(); + editor.applyTo((LibraryEx.ModifiableModelEx)model); + model.commit(); + } + finally { + token.finish(); } }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/propertiesEditor/RepositoryLibraryPropertiesEditor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/propertiesEditor/RepositoryLibraryPropertiesEditor.java index 7c53dbbb8dc3..dc0d901704f1 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/propertiesEditor/RepositoryLibraryPropertiesEditor.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/propertiesEditor/RepositoryLibraryPropertiesEditor.java @@ -253,20 +253,14 @@ public class RepositoryLibraryPropertiesEditor { return; } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - initVersionsPanel(); - } + ApplicationManager.getApplication().invokeLater(() -> { + initVersionsPanel(); }, ModalityState.any()); } private void versionsFailedToLoad() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - setState(State.FailedToLoad); - } + ApplicationManager.getApplication().invokeLater(() -> { + setState(State.FailedToLoad); }, ModalityState.any()); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenRemoteManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenRemoteManager.java index 29e7db350bcf..34ddd775d232 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenRemoteManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenRemoteManager.java @@ -109,11 +109,8 @@ public abstract class MavenRemoteManager { + startTask(); }, ModalityState.any()); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenVersionsRemoteManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenVersionsRemoteManager.java index d845b18b337c..0de65f7a03ed 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenVersionsRemoteManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/remote/MavenVersionsRemoteManager.java @@ -67,13 +67,10 @@ public class MavenVersionsRemoteManager repositoryLibraryDescription.getGroupId(), repositoryLibraryDescription.getArtifactId(), remoteRepositories); - Collections.sort(versions, new Comparator() { - @Override - public int compare(String o1, String o2) { - MavenVersionComparable v1 = new MavenVersionComparable(o1); - MavenVersionComparable v2 = new MavenVersionComparable(o2); - return v2.compareTo(v1); - } + Collections.sort(versions, (o1, o2) -> { + MavenVersionComparable v1 = new MavenVersionComparable(o1); + MavenVersionComparable v2 = new MavenVersionComparable(o2); + return v2.compareTo(v1); }); return versions; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenArchetypesStep.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenArchetypesStep.java index 30e54d1c5d28..032fba1cb184 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenArchetypesStep.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenArchetypesStep.java @@ -175,16 +175,14 @@ public class MavenArchetypesStep extends ModuleWizardStep implements Disposable private static TreeNode groupAndSortArchetypes(Set archetypes) { List list = new ArrayList(archetypes); - Collections.sort(list, new Comparator() { - public int compare(MavenArchetype o1, MavenArchetype o2) { - String key1 = o1.groupId + ":" + o1.artifactId; - String key2 = o2.groupId + ":" + o2.artifactId; + Collections.sort(list, (o1, o2) -> { + String key1 = o1.groupId + ":" + o1.artifactId; + String key2 = o2.groupId + ":" + o2.artifactId; - int result = key1.compareToIgnoreCase(key2); - if (result != 0) return result; + int result = key1.compareToIgnoreCase(key2); + if (result != 0) return result; - return o2.version.compareToIgnoreCase(o1.version); - } + return o2.version.compareToIgnoreCase(o1.version); }); Map> map = new TreeMap>(); @@ -234,33 +232,29 @@ public class MavenArchetypesStep extends ModuleWizardStep implements Disposable final Object currentUpdaterMarker = new Object(); myCurrentUpdaterMarker = currentUpdaterMarker; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - final Set archetypes = MavenIndicesManager.getInstance().getArchetypes(); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final Set archetypes = MavenIndicesManager.getInstance().getArchetypes(); - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (currentUpdaterMarker != myCurrentUpdaterMarker) return; // Other updater has been run. + //noinspection SSBasedInspection + SwingUtilities.invokeLater(() -> { + if (currentUpdaterMarker != myCurrentUpdaterMarker) return; // Other updater has been run. - ((CardLayout)myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes"); + ((CardLayout)myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes"); - TreeNode root = groupAndSortArchetypes(archetypes); - TreeModel model = new DefaultTreeModel(root); - myArchetypesTree.setModel(model); + TreeNode root = groupAndSortArchetypes(archetypes); + TreeModel model = new DefaultTreeModel(root); + myArchetypesTree.setModel(model); - if (selected != null) { - TreePath path = findNodePath(selected, model, model.getRoot()); - if (path != null) { - myArchetypesTree.expandPath(path.getParentPath()); - TreeUtil.selectPath(myArchetypesTree, path, true); - } - } - - updateArchetypeDescription(); + if (selected != null) { + TreePath path = findNodePath(selected, model, model.getRoot()); + if (path != null) { + myArchetypesTree.expandPath(path.getParentPath()); + TreeUtil.selectPath(myArchetypesTree, path, true); } - }); - } + } + + updateArchetypeDescription(); + }); }); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java index 283cbe235127..aecba9e017a4 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenModuleBuilderHelper.java @@ -132,13 +132,11 @@ public class MavenModuleBuilderHelper { } // execute when current dialog is closed (e.g. Project Structure) - MavenUtil.invokeLater(project, ModalityState.NON_MODAL, new Runnable() { - public void run() { - if (!pom.isValid()) return; + MavenUtil.invokeLater(project, ModalityState.NON_MODAL, () -> { + if (!pom.isValid()) return; - EditorHelper.openInEditor(getPsiFile(project, pom)); - if (myArchetype != null) generateFromArchetype(project, pom); - } + EditorHelper.openInEditor(getPsiFile(project, pom)); + if (myArchetype != null) generateFromArchetype(project, pom); }); } @@ -214,11 +212,7 @@ public class MavenModuleBuilderHelper { props.putAll(myPropertiesToCreateByArtifact); - runner.run(params, settings, new Runnable() { - public void run() { - copyGeneratedFiles(workingDir, pom, project); - } - }); + runner.run(params, settings, () -> copyGeneratedFiles(workingDir, pom, project)); } private void copyGeneratedFiles(File workingDir, VirtualFile pom, Project project) { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java index 68a44fcca6d9..a891c10c36de 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java @@ -99,21 +99,18 @@ public abstract class MavenTestCase extends UsefulTestCase { throw new RuntimeException(e); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { + try { + setUpInWriteAction(); + } + catch (Throwable e) { try { - setUpInWriteAction(); + tearDown(); } - catch (Throwable e) { - try { - tearDown(); - } - catch (Exception e1) { - e1.printStackTrace(); - } - throw new RuntimeException(e); + catch (Exception e1) { + e1.printStackTrace(); } + throw new RuntimeException(e); } }); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDependencyCompletionAndResolutionTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDependencyCompletionAndResolutionTest.java index 11b848aa2912..45f62fb4893b 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDependencyCompletionAndResolutionTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDependencyCompletionAndResolutionTest.java @@ -714,12 +714,7 @@ public class MavenDependencyCompletionAndResolutionTest extends MavenDomWithIndi String libPath = myIndicesFixture.getRepositoryHelper().getTestDataPath("local1/junit/junit/4.0/junit-4.0.jar"); final VirtualFile libFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(libPath); - ((ChooseFileIntentionAction)((IntentionActionWrapper)action).getDelegate()).setFileChooser(new Producer() { - @Override - public VirtualFile[] produce() { - return new VirtualFile[]{libFile}; - } - }); + ((ChooseFileIntentionAction)((IntentionActionWrapper)action).getDelegate()).setFileChooser(() -> new VirtualFile[]{libFile}); XmlCodeStyleSettings xmlSettings = CodeStyleSettingsManager.getInstance(myProject).getCurrentSettings().getCustomSettings(XmlCodeStyleSettings.class); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDomTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDomTestCase.java index a5b5bd168b2a..f2f125e9f8f7 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDomTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDomTestCase.java @@ -383,11 +383,8 @@ public abstract class MavenDomTestCase extends MavenImportingTestCase { }); PsiElement target = ((PsiElement2UsageTargetAdapter)targets[0]).getElement(); List result = new ArrayList(ReferencesSearch.search(target).findAll()); - return ContainerUtil.map(result, new Function() { - @Override - public PsiElement fun(PsiReference psiReference) { - return psiReference.getElement(); - } + return ContainerUtil.map(result, psiReference -> { + return psiReference.getElement(); }); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenModelReadingAndWritingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenModelReadingAndWritingTest.java index ce70bbe3b442..73ac857e5c6a 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenModelReadingAndWritingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenModelReadingAndWritingTest.java @@ -47,22 +47,15 @@ public class MavenModelReadingAndWritingTest extends MavenImportingTestCase { } public void testWriting() throws Exception { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - MavenDomProjectModel model = getDomModel(); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + MavenDomProjectModel model = getDomModel(); - model.getGroupId().setStringValue("foo"); - model.getArtifactId().setStringValue("bar"); - model.getVersion().setStringValue("baz"); + model.getGroupId().setStringValue("foo"); + model.getArtifactId().setStringValue("bar"); + model.getVersion().setStringValue("baz"); - formatAndSaveProjectPomDocument(); - } - }); - } - }, null, null); + formatAndSaveProjectPomDocument(); + }), null, null); assertSameLines("\r\n" + " ApplicationManager.getApplication().runWriteAction(() -> { + MavenDomProjectModel model = getDomModel(); - MavenDomDependency d = model.getDependencies().addDependency(); - d.getGroupId().setStringValue("group"); - d.getArtifactId().setStringValue("artifact"); - d.getVersion().setStringValue("version"); + MavenDomDependency d = model.getDependencies().addDependency(); + d.getGroupId().setStringValue("group"); + d.getArtifactId().setStringValue("artifact"); + d.getVersion().setStringValue("version"); - formatAndSaveProjectPomDocument(); - } - }); - } - }, null, null); + formatAndSaveProjectPomDocument(); + }), null, null); assertSameLines("\r\n" + "1"); final Document doc = FileDocumentManager.getInstance().getDocument(myProjectPom); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - doc.setText(createPomXml("test" + - "project" + - "2" + + WriteCommandAction.runWriteCommandAction(null, () -> { + doc.setText(createPomXml("test" + + "project" + + "2" + - "" + - " value" + - "")); - } + "" + + " value" + + "")); }); PsiDocumentManager.getInstance(myProject).commitDocument(doc); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenClasspathsAndSearchScopesTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenClasspathsAndSearchScopesTest.java index 8e7caf98107b..443efbb3e2b1 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenClasspathsAndSearchScopesTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenClasspathsAndSearchScopesTest.java @@ -1314,19 +1314,12 @@ public class MavenClasspathsAndSearchScopesTest extends MavenImportingTestCase { } private static List orderEntriesToOwnerModules(List orderEntries) { - return ContainerUtil.map(orderEntries, new Function() { - @Override - public Module fun(OrderEntry orderEntry) { return orderEntry.getOwnerModule(); } - }); + return ContainerUtil.map(orderEntries, orderEntry -> { return orderEntry.getOwnerModule(); }); } private static List orderEntriesToDepModules(List orderEntries) { - return ContainerUtil.map(orderEntries, new Function() { - @Override - public Module fun(OrderEntry orderEntry) { - return (orderEntry instanceof ModuleOrderEntry) ? ((ModuleOrderEntry)orderEntry).getModule() : null; - } - }); + return ContainerUtil.map(orderEntries, + orderEntry -> (orderEntry instanceof ModuleOrderEntry) ? ((ModuleOrderEntry)orderEntry).getModule() : null); } private void assertAllProductionClasspath(String moduleName, String... paths) throws Exception { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenExecutionTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenExecutionTest.java index 70f3ce23e1f0..b9ddc4c88d3f 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenExecutionTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenExecutionTest.java @@ -87,10 +87,7 @@ public class MavenExecutionTest extends MavenImportingTestCase { MavenRunnerParameters params = new MavenRunnerParameters(true, getProjectPath(), Arrays.asList("compile"), Collections.emptyList()); execute(params); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - } + SwingUtilities.invokeAndWait(() -> { }); assertSources("project", @@ -108,31 +105,21 @@ public class MavenExecutionTest extends MavenImportingTestCase { private void execute(final MavenRunnerParameters params) { final Semaphore sema = new Semaphore(); sema.down(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - MavenRunConfigurationType.runConfiguration( - myProject, params, getMavenGeneralSettings(), - new MavenRunnerSettings(), - new ProgramRunner.Callback() { + UIUtil.invokeLaterIfNeeded(() -> MavenRunConfigurationType.runConfiguration( + myProject, params, getMavenGeneralSettings(), + new MavenRunnerSettings(), + new ProgramRunner.Callback() { + @Override + public void processStarted(final RunContentDescriptor descriptor) { + descriptor.getProcessHandler().addProcessListener(new ProcessAdapter() { @Override - public void processStarted(final RunContentDescriptor descriptor) { - descriptor.getProcessHandler().addProcessListener(new ProcessAdapter() { - @Override - public void processTerminated(ProcessEvent event) { - sema.up(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - Disposer.dispose(descriptor); - } - }); - } - }); + public void processTerminated(ProcessEvent event) { + sema.up(); + UIUtil.invokeLaterIfNeeded(() -> Disposer.dispose(descriptor)); } }); - } - }); + } + })); sema.waitFor(); } } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java index c1d4a901c0e5..4eca62f78c4c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/DependenciesImportingTest.java @@ -2090,37 +2090,31 @@ public class DependenciesImportingTest extends MavenImportingTestCase { } private void createAndAddProjectLibrary(final String moduleName, final String libraryName) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - Library lib = createProjectLibrary(libraryName); - ModuleRootModificationUtil.addDependency(getModule(moduleName), lib); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Library lib = createProjectLibrary(libraryName); + ModuleRootModificationUtil.addDependency(getModule(moduleName), lib); }); } private void clearLibraryRoots(final String libraryName, final OrderRootType... types) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - Library lib = ProjectLibraryTable.getInstance(myProject).getLibraryByName(libraryName); - Library.ModifiableModel model = lib.getModifiableModel(); - for (OrderRootType eachType : types) { - for (String each : model.getUrls(eachType)) { - model.removeRoot(each, eachType); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Library lib = ProjectLibraryTable.getInstance(myProject).getLibraryByName(libraryName); + Library.ModifiableModel model = lib.getModifiableModel(); + for (OrderRootType eachType : types) { + for (String each : model.getUrls(eachType)) { + model.removeRoot(each, eachType); } - model.commit(); } + model.commit(); }); } private void addLibraryRoot(final String libraryName, final OrderRootType type, final String path) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - Library lib = ProjectLibraryTable.getInstance(myProject).getLibraryByName(libraryName); - Library.ModifiableModel model = lib.getModifiableModel(); - model.addRoot(path, type); - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + Library lib = ProjectLibraryTable.getInstance(myProject).getLibraryByName(libraryName); + Library.ModifiableModel model = lib.getModifiableModel(); + model.addRoot(path, type); + model.commit(); }); } @@ -2153,13 +2147,11 @@ public class DependenciesImportingTest extends MavenImportingTestCase { "project" + "1"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - LibraryTable appTable = LibraryTablesRegistrar.getInstance().getLibraryTable(); - Library lib = appTable.createLibrary("foo"); - ModuleRootModificationUtil.addDependency(getModule("project"), lib); - appTable.removeLibrary(lib); - } + ApplicationManager.getApplication().runWriteAction(() -> { + LibraryTable appTable = LibraryTablesRegistrar.getInstance().getLibraryTable(); + Library lib = appTable.createLibrary("foo"); + ModuleRootModificationUtil.addDependency(getModule("project"), lib); + appTable.removeLibrary(lib); }); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java index 2666bd9a0b51..46f5bf6584a3 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/FoldersImportingTest.java @@ -96,15 +96,13 @@ public class FoldersImportingTest extends MavenImportingTestCase { "project" + "1"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - MavenRootModelAdapter adapter = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), - getModule("project"), - new IdeModifiableModelsProviderImpl(myProject)); - adapter.addSourceFolder(dir1.getPath(), JavaSourceRootType.SOURCE); - adapter.addExcludedFolder(dir2.getPath()); - adapter.getRootModel().commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + MavenRootModelAdapter adapter = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), + getModule("project"), + new IdeModifiableModelsProviderImpl(myProject)); + adapter.addSourceFolder(dir1.getPath(), JavaSourceRootType.SOURCE); + adapter.addExcludedFolder(dir2.getPath()); + adapter.getRootModel().commit(); }); @@ -1049,22 +1047,19 @@ public class FoldersImportingTest extends MavenImportingTestCase { " " + ""); - final Runnable testAssertions = new Runnable() { - @Override - public void run() { - assertSources("project", - "anno", - "src/main/java", - "target/generated-sources/annotations", - "target/generated-sources/foo", - "target/generated-sources/test-annotations"); + final Runnable testAssertions = () -> { + assertSources("project", + "anno", + "src/main/java", + "target/generated-sources/annotations", + "target/generated-sources/foo", + "target/generated-sources/test-annotations"); - assertResources("project", "src/main/resources"); - assertTestSources("project", - "src/test/java", - "target/generated-test-sources/foo"); - assertTestResources("project", "src/test/resources"); - } + assertResources("project", "src/main/resources"); + assertTestSources("project", + "src/test/java", + "target/generated-test-sources/foo"); + assertTestResources("project", "src/test/resources"); }; testAssertions.run(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java index 6aae8144fb2d..d352a5fb5a1b 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/GroovyImporterTest.java @@ -484,14 +484,12 @@ public class GroovyImporterTest extends MavenImportingTestCase { " " + ""); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - MavenRootModelAdapter a = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), - getModule("project"), - new IdeModifiableModelsProviderImpl(myProject)); - a.unregisterAll(getProjectPath() + "/target", true, true); - a.getRootModel().commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + MavenRootModelAdapter a = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), + getModule("project"), + new IdeModifiableModelsProviderImpl(myProject)); + a.unregisterAll(getProjectPath() + "/target", true, true); + a.getRootModel().commit(); }); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenPerformanceTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenPerformanceTest.java index 9253ddd2f00d..4b986f335a42 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenPerformanceTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/MavenPerformanceTest.java @@ -39,54 +39,29 @@ public abstract class MavenPerformanceTest extends MavenImportingTestCase { } public void testReading() throws Exception { - measure(4000, new Runnable() { - @Override - public void run() { - waitForReadingCompletion(); - } - }); + measure(4000, () -> waitForReadingCompletion()); } public void testImporting() throws Exception { waitForReadingCompletion(); - measure(8, new Runnable() { - @Override - public void run() { - myProjectsManager.importProjects(); - } - }); + measure(8, () -> myProjectsManager.importProjects()); } public void testReImporting() throws Exception { waitForReadingCompletion(); myProjectsManager.importProjects(); - measure(2, new Runnable() { - @Override - public void run() { - myProjectsManager.importProjects(); - } - }); + measure(2, () -> myProjectsManager.importProjects()); } public void testResolving() throws Exception { waitForReadingCompletion(); List mavenProjects = myProjectsManager.getProjects(); - Collections.sort(mavenProjects, new Comparator() { - @Override - public int compare(MavenProject o1, MavenProject o2) { - return o1.getPath().compareToIgnoreCase(o2.getPath()); - } - }); + Collections.sort(mavenProjects, (o1, o2) -> o1.getPath().compareToIgnoreCase(o2.getPath())); myProjectsManager.unscheduleAllTasksInTests(); myProjectsManager.scheduleResolveInTests(mavenProjects.subList(0, 100)); - measure(50000, new Runnable() { - @Override - public void run() { - myProjectsManager.waitForResolvingCompletion(); - } - }); + measure(50000, () -> myProjectsManager.waitForResolvingCompletion()); } private static void measure(long expected, Runnable r) { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/WorkingWithOpenProjectTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/WorkingWithOpenProjectTest.java index 77f7746e4808..df9570a70858 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/WorkingWithOpenProjectTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/WorkingWithOpenProjectTest.java @@ -56,20 +56,18 @@ public class WorkingWithOpenProjectTest extends MavenImportingTestCase { myProjectsManager.listenForExternalChanges(); final Document d = FileDocumentManager.getInstance().getDocument(myProjectPom); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - d.setText(createPomXml("test" + - "project" + - "1" + + WriteCommandAction.runWriteCommandAction(null, () -> { + d.setText(createPomXml("test" + + "project" + + "1" + - "" + - " " + - " junit" + - " junit" + - " 4.0" + - " " + - "")); - } + "" + + " " + + " junit" + + " junit" + + " 4.0" + + " " + + "")); }); resolveDependenciesAndImport(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java index 6003adc09cac..1853cb08b840 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/indices/MavenIndicesStressTest.java @@ -42,34 +42,28 @@ public abstract class MavenIndicesStressTest extends MavenIndicesTestCase implem final AtomicBoolean isFinished = new AtomicBoolean(false); - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - try { - for (int i = 0; i < 3; i++) { - System.out.println("INDEXING #" + i); - indices.updateOrRepair(index, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); - } - } - catch (MavenProcessCanceledException e) { - throw new RuntimeException(e); - } - finally { - isFinished.set(true); + Thread t1 = new Thread(() -> { + try { + for (int i = 0; i < 3; i++) { + System.out.println("INDEXING #" + i); + indices.updateOrRepair(index, true, getMavenGeneralSettings(), EMPTY_MAVEN_PROCESS); } } - },"maven index 1"); + catch (MavenProcessCanceledException e) { + throw new RuntimeException(e); + } + finally { + isFinished.set(true); + } + }, "maven index 1"); - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - Random random = new Random(); - while (!isFinished.get()) { - int i = random.nextInt(100); - System.out.println("Adding artifact #" + i); - //index.addArtifact(new MavenId("group" + i, "artifact" + i, "" + i)); - fail(); - } + Thread t2 = new Thread(() -> { + Random random = new Random(); + while (!isFinished.get()) { + int i = random.nextInt(100); + System.out.println("Adding artifact #" + i); + //index.addArtifact(new MavenId("group" + i, "artifact" + i, "" + i)); + fail(); } }, "maven index 2"); @@ -137,21 +131,18 @@ public abstract class MavenIndicesStressTest extends MavenIndicesTestCase implem } private static Thread createThread(final MavenIndex index, final AtomicInteger finishedCount) { - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - try { - for (int i = 0; i < 1000; i++) { - System.out.println("Adding artifact #" + i); - //index.addArtifact(new MavenId("group" + i, "artifact" + i, "" + i)); - fail(); - } - } - finally { - finishedCount.incrementAndGet(); + Thread t2 = new Thread(() -> { + try { + for (int i = 0; i < 1000; i++) { + System.out.println("Adding artifact #" + i); + //index.addArtifact(new MavenId("group" + i, "artifact" + i, "" + i)); + fail(); } } - },"maven test"); + finally { + finishedCount.incrementAndGet(); + } + }, "maven test"); return t2; } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java index 7261327dc9ca..50670bff0da6 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java @@ -1037,11 +1037,8 @@ public class MavenProjectReaderTest extends MavenTestCase { ""); MavenModel p = readProject(module); - assertOrderedElementsAreEqual(ContainerUtil.map(p.getProfiles(), new Function() { - @Override - public Object fun(MavenProfile profile) { - return profile.getId(); - } + assertOrderedElementsAreEqual(ContainerUtil.map(p.getProfiles(), (Function)profile -> { + return profile.getId(); }), "profileFromChild", "profileFromParent"); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenFoldersImporterTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenFoldersImporterTest.java index e541d227818e..81eeacfc0594 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenFoldersImporterTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenFoldersImporterTest.java @@ -136,14 +136,12 @@ public class MavenFoldersImporterTest extends MavenImportingTestCase { final File sourceDir = new File(myProjectRoot.getPath(), "target/src"); sourceDir.mkdirs(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - MavenRootModelAdapter adapter = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), - getModule("project"), - new IdeModifiableModelsProviderImpl(myProject)); - adapter.addSourceFolder(sourceDir.getPath(), JavaSourceRootType.SOURCE); - adapter.getRootModel().commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + MavenRootModelAdapter adapter = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), + getModule("project"), + new IdeModifiableModelsProviderImpl(myProject)); + adapter.addSourceFolder(sourceDir.getPath(), JavaSourceRootType.SOURCE); + adapter.getRootModel().commit(); }); @@ -167,15 +165,13 @@ public class MavenFoldersImporterTest extends MavenImportingTestCase { "project" + "1"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - MavenRootModelAdapter adapter = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), - getModule("project"), - new IdeModifiableModelsProviderImpl(myProject)); - adapter.useModuleOutput(new File(myProjectRoot.getPath(), "target/my-classes").getPath(), - new File(myProjectRoot.getPath(), "target/my-test-classes").getPath()); - adapter.getRootModel().commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + MavenRootModelAdapter adapter = new MavenRootModelAdapter(myProjectsTree.findProject(myProjectPom), + getModule("project"), + new IdeModifiableModelsProviderImpl(myProject)); + adapter.useModuleOutput(new File(myProjectRoot.getPath(), "target/my-classes").getPath(), + new File(myProjectRoot.getPath(), "target/my-test-classes").getPath()); + adapter.getRootModel().commit(); }); @@ -254,14 +250,11 @@ public class MavenFoldersImporterTest extends MavenImportingTestCase { assertGeneratedSources("project", "target/generated-sources/xxx"); - ModuleRootModificationUtil.updateModel(getModule("project"), new Consumer() { - @Override - public void consume(ModifiableRootModel model) { - for (SourceFolder folder : model.getContentEntries()[0].getSourceFolders()) { - JavaSourceRootProperties properties = folder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); - assertNotNull(properties); - properties.setForGeneratedSources(false); - } + ModuleRootModificationUtil.updateModel(getModule("project"), model -> { + for (SourceFolder folder : model.getContentEntries()[0].getSourceFolders()) { + JavaSourceRootProperties properties = folder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); + assertNotNull(properties); + properties.setForGeneratedSources(false); } }); assertGeneratedSources("project"); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsManagerTest.java index 1e62108ccbc2..850f6114689e 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsManagerTest.java @@ -943,16 +943,14 @@ public class MavenProjectsManagerTest extends MavenImportingTestCase { createProjectSubDir("src/main/java"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ModifiableRootModel model = ModuleRootManager.getInstance(getModule("project")).getModifiableModel(); - for (OrderEntry each : model.getOrderEntries()) { - if (each instanceof LibraryOrderEntry && MavenRootModelAdapter.isMavenLibrary(((LibraryOrderEntry)each).getLibrary())) { - model.removeOrderEntry(each); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ModifiableRootModel model = ModuleRootManager.getInstance(getModule("project")).getModifiableModel(); + for (OrderEntry each : model.getOrderEntries()) { + if (each instanceof LibraryOrderEntry && MavenRootModelAdapter.isMavenLibrary(((LibraryOrderEntry)each).getLibrary())) { + model.removeOrderEntry(each); } - model.commit(); } + model.commit(); }); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeIgnoresTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeIgnoresTest.java index 3fcebb675e8d..c17c28a2e6f4 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeIgnoresTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeIgnoresTest.java @@ -87,11 +87,8 @@ public class MavenProjectsTreeIgnoresTest extends MavenProjectsTreeTestCase { } private String format(List projects) { - return StringUtil.join(projects, new Function() { - @Override - public String fun(MavenProject project) { - return project.getMavenId().getArtifactId(); - } + return StringUtil.join(projects, project -> { + return project.getMavenId().getArtifactId(); }, ", "); } } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeReadingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeReadingTest.java index 85662f0be765..900635679268 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeReadingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/importing/MavenProjectsTreeReadingTest.java @@ -2254,11 +2254,8 @@ public class MavenProjectsTreeReadingTest extends MavenProjectsTreeTestCase { log += " "; return; } - log += StringUtil.join(updated, new Function() { - @Override - public String fun(MavenProject each) { - return each.getMavenId().getArtifactId(); - } + log += StringUtil.join(updated, each -> { + return each.getMavenId().getArtifactId(); }, " ") + " "; } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/server/MavenServerManagerTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/server/MavenServerManagerTest.java index a7d62213e4c6..e63ea9604ed0 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/server/MavenServerManagerTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/server/MavenServerManagerTest.java @@ -28,37 +28,31 @@ public class MavenServerManagerTest extends MavenTestCase { //make sure all components are initialized to prevent deadlocks MavenServerManager.getInstance().getOrCreateWrappee(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Future result = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - MavenServerManager.getInstance().shutdown(true); - try { - MavenServerManager.getInstance().getOrCreateWrappee(); - } - catch (RemoteException e) { - throw new RuntimeException(e); - } - } - }); - + ApplicationManager.getApplication().runWriteAction(() -> { + Future result = ApplicationManager.getApplication().executeOnPooledThread(() -> { + MavenServerManager.getInstance().shutdown(true); try { - result.get(10, TimeUnit.SECONDS); + MavenServerManager.getInstance().getOrCreateWrappee(); } - catch (InterruptedException e) { + catch (RemoteException e) { throw new RuntimeException(e); } - catch (java.util.concurrent.ExecutionException e) { - throw new RuntimeException(e); - } - catch (TimeoutException e) { - printThreadDump(); - throw new RuntimeException(e); - } - result.cancel(true); + }); + + try { + result.get(10, TimeUnit.SECONDS); } + catch (InterruptedException e) { + throw new RuntimeException(e); + } + catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException(e); + } + catch (TimeoutException e) { + printThreadDump(); + throw new RuntimeException(e); + } + result.cancel(true); }); } } diff --git a/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java b/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java index 13011c5cd28d..aa48a1aadc9b 100644 --- a/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java +++ b/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java @@ -51,19 +51,17 @@ public class PropertiesUtil { @Override protected Set compute() { final HashSet locales = - new HashSet(ContainerUtil.flatten(ContainerUtil.map(Locale.getAvailableLocales(), new Function>() { - @Override - public List fun(Locale locale) { - final ArrayList languages = ContainerUtil.newArrayList(locale.getLanguage()); - try { - languages.add(locale.getISO3Language()); - } - catch (MissingResourceException ignored) { - // if ISO3 language is not found for existed locale then exception is thrown anyway - } - return languages; - } - }))); + new HashSet(ContainerUtil.flatten(ContainerUtil.map(Locale.getAvailableLocales(), + (Function>)locale -> { + final ArrayList languages = ContainerUtil.newArrayList(locale.getLanguage()); + try { + languages.add(locale.getISO3Language()); + } + catch (MissingResourceException ignored) { + // if ISO3 language is not found for existed locale then exception is thrown anyway + } + return languages; + }))); locales.addAll(ContainerUtil.newArrayList(Locale.getISOLanguages())); return locales; } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/duplicatePropertyInspection/DuplicatePropertyInspection.java b/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/duplicatePropertyInspection/DuplicatePropertyInspection.java index 56d86b635e0d..cb31c779439c 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/duplicatePropertyInspection/DuplicatePropertyInspection.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/duplicatePropertyInspection/DuplicatePropertyInspection.java @@ -155,35 +155,29 @@ public class DuplicatePropertyInspection extends GlobalSimpleInspectionTool { final Map> processedKeyToFiles = Collections.synchronizedMap(new HashMap>()); final ProgressIndicator original = ProgressManager.getInstance().getProgressIndicator(); final ProgressIndicator progress = ProgressWrapper.wrap(original); - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(properties, progress, false, new Processor() { - @Override - public boolean process(final IProperty property) { - if (original != null) { - if (original.isCanceled()) return false; - original.setText2(PropertiesBundle.message("searching.for.property.key.progress.text", property.getUnescapedKey())); - } - processTextUsages(processedValueToFiles, property.getValue(), processedKeyToFiles, searchHelper, scope); - processTextUsages(processedKeyToFiles, property.getUnescapedKey(), processedValueToFiles, searchHelper, scope); - return true; - } - })) throw new ProcessCanceledException(); + ProgressManager.getInstance().runProcess(() -> { + if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(properties, progress, false, property -> { + if (original != null) { + if (original.isCanceled()) return false; + original.setText2(PropertiesBundle.message("searching.for.property.key.progress.text", property.getUnescapedKey())); + } + processTextUsages(processedValueToFiles, property.getValue(), processedKeyToFiles, searchHelper, scope); + processTextUsages(processedKeyToFiles, property.getUnescapedKey(), processedValueToFiles, searchHelper, scope); + return true; + })) throw new ProcessCanceledException(); - List problemDescriptors = new ArrayList(); - Map> keyToDifferentValues = new HashMap>(); - if (CHECK_DUPLICATE_KEYS || CHECK_DUPLICATE_KEYS_WITH_DIFFERENT_VALUES) { - prepareDuplicateKeysByFile(processedKeyToFiles, manager, keyToDifferentValues, problemDescriptors, file, original); - } - if (CHECK_DUPLICATE_VALUES) prepareDuplicateValuesByFile(processedValueToFiles, manager, problemDescriptors, file, original); - if (CHECK_DUPLICATE_KEYS_WITH_DIFFERENT_VALUES) { - processDuplicateKeysWithDifferentValues(keyToDifferentValues, processedKeyToFiles, problemDescriptors, manager, file, original); - } - if (!problemDescriptors.isEmpty()) { - processor.addProblemElement(refManager.getReference(file), - problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()])); - } + List problemDescriptors = new ArrayList(); + Map> keyToDifferentValues = new HashMap>(); + if (CHECK_DUPLICATE_KEYS || CHECK_DUPLICATE_KEYS_WITH_DIFFERENT_VALUES) { + prepareDuplicateKeysByFile(processedKeyToFiles, manager, keyToDifferentValues, problemDescriptors, file, original); + } + if (CHECK_DUPLICATE_VALUES) prepareDuplicateValuesByFile(processedValueToFiles, manager, problemDescriptors, file, original); + if (CHECK_DUPLICATE_KEYS_WITH_DIFFERENT_VALUES) { + processDuplicateKeysWithDifferentValues(keyToDifferentValues, processedKeyToFiles, problemDescriptors, manager, file, original); + } + if (!problemDescriptors.isEmpty()) { + processor.addProblemElement(refManager.getReference(file), + problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()])); } }, progress); } @@ -333,12 +327,7 @@ public class DuplicatePropertyInspection extends GlobalSimpleInspectionTool { final Set resultFiles) { final List words = StringUtil.getWordsIn(stringToFind); if (words.isEmpty()) return; - Collections.sort(words, new Comparator() { - @Override - public int compare(final String o1, final String o2) { - return o2.length() - o1.length(); - } - }); + Collections.sort(words, (o1, o2) -> o2.length() - o1.length()); for (String word : words) { final Set files = new THashSet(); searchHelper.processAllFilesWithWord(word, scope, Processors.cancelableCollectProcessor(files), true); diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/unsorted/AlphaUnsortedPropertiesFileInspection.java b/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/unsorted/AlphaUnsortedPropertiesFileInspection.java index 7fe5a6d8ffab..7cce96af8598 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/unsorted/AlphaUnsortedPropertiesFileInspection.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/codeInspection/unsorted/AlphaUnsortedPropertiesFileInspection.java @@ -123,12 +123,7 @@ public class AlphaUnsortedPropertiesFileInspection extends LocalInspectionTool { private static void sortPropertiesFile(final PropertiesFile file) { final List properties = new ArrayList(file.getProperties()); - Collections.sort(properties, new Comparator() { - @Override - public int compare(@NotNull IProperty p1, @NotNull IProperty p2) { - return Comparing.compare(p1.getKey(), p2.getKey(), String.CASE_INSENSITIVE_ORDER); - } - }); + Collections.sort(properties, (p1, p2) -> Comparing.compare(p1.getKey(), p2.getKey(), String.CASE_INSENSITIVE_ORDER)); final char delimiter = PropertiesCodeStyleSettings.getInstance(file.getProject()).getDelimiter(); final StringBuilder rawText = new StringBuilder(); for (int i = 0; i < properties.size(); i++) { diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundle.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundle.java index a735fd7e92ee..8a4a46a17747 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundle.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundle.java @@ -43,23 +43,15 @@ public class CustomResourceBundle extends ResourceBundle { private CustomResourceBundle(final List files, final @NotNull String baseName) { LOG.assertTrue(!files.isEmpty()); myFiles = new ArrayList(files); - Collections.sort(myFiles, new Comparator() { - @Override - public int compare(PropertiesFile f1, PropertiesFile f2) { - return f1.getName().compareTo(f2.getName()); - } - }); + Collections.sort(myFiles, (f1, f2) -> f1.getName().compareTo(f2.getName())); myBaseName = baseName; } public static CustomResourceBundle fromState(final CustomResourceBundleState state, final Project project) { final PsiManager psiManager = PsiManager.getInstance(project); final List files = - ContainerUtil.map(state.getFiles(VirtualFileManager.getInstance()), new Function() { - @Override - public PropertiesFile fun(VirtualFile virtualFile) { - return PropertiesImplUtil.getPropertiesFile(psiManager.findFile(virtualFile)); - } + ContainerUtil.map(state.getFiles(VirtualFileManager.getInstance()), virtualFile -> { + return PropertiesImplUtil.getPropertiesFile(psiManager.findFile(virtualFile)); }); return files.size() < 2 ? null : new CustomResourceBundle(files, state.getBaseName()); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundleState.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundleState.java index 9be149d6a4db..4fc58b311c50 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundleState.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/CustomResourceBundleState.java @@ -56,12 +56,9 @@ public class CustomResourceBundleState { } public List getFiles(@NotNull final VirtualFileManager manager) { - return ContainerUtil.mapNotNull(getFileUrls(), new Function() { - @Override - public VirtualFile fun(String url) { - return manager.findFileByUrl(url); - } - }); + return ContainerUtil.mapNotNull(getFileUrls(), url -> { + return manager.findFileByUrl(url); + }); } @Nullable diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleManager.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleManager.java index f15f5ca9ac9b..f6e488bb4749 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleManager.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleManager.java @@ -234,11 +234,8 @@ public class ResourceBundleManager implements PersistentStateComponent propertiesFiles, final String baseName) { myState.getCustomResourceBundles() - .add(new CustomResourceBundleState().addAll(ContainerUtil.map(propertiesFiles, new Function() { - @Override - public String fun(PropertiesFile file) { - return file.getVirtualFile().getUrl(); - } + .add(new CustomResourceBundleState().addAll(ContainerUtil.map(propertiesFiles, file -> { + return file.getVirtualFile().getUrl(); })).setBaseName(baseName)); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/ResourceBundleFileStructureViewElement.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/ResourceBundleFileStructureViewElement.java index e1eae1c64cff..f71e330febfb 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/ResourceBundleFileStructureViewElement.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/ResourceBundleFileStructureViewElement.java @@ -153,11 +153,8 @@ public class ResourceBundleFileStructureViewElement implements StructureViewTree @Override public PsiFile[] getFiles() { final List files = getValue().getPropertiesFiles(); - return ContainerUtil.map2Array(files, new PsiFile[files.size()], new Function() { - @Override - public PsiFile fun(PropertiesFile propertiesFile) { - return propertiesFile.getContainingFile(); - } + return ContainerUtil.map2Array(files, new PsiFile[files.size()], propertiesFile -> { + return propertiesFile.getContainingFile(); }); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/inspections/ResourceBundleEditorInspectionPass.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/inspections/ResourceBundleEditorInspectionPass.java index 27bfe9e0e75f..f7e09db245b9 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/inspections/ResourceBundleEditorInspectionPass.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/inspections/ResourceBundleEditorInspectionPass.java @@ -49,11 +49,8 @@ public class ResourceBundleEditorInspectionPass { @Nullable public static InspectionPassInfo inspect(@NotNull final String key, ResourceBundle resourceBundle) { final List properties = - ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), new Function() { - @Override - public IProperty fun(PropertiesFile propertiesFile) { - return propertiesFile.findPropertyByKey(key); - } + ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), propertiesFile -> { + return propertiesFile.findPropertyByKey(key); }); if (properties.isEmpty()) { @@ -71,13 +68,10 @@ public class ResourceBundleEditorInspectionPass { List> allDescriptors = new SmartList>(); - SortedSet highlightTypes = new TreeSet(new Comparator() { - @Override - public int compare(HighlightInfoType o1, HighlightInfoType o2) { - final HighlightSeverity s1 = o1.getSeverity(null); - final HighlightSeverity s2 = o2.getSeverity(null); - return Comparing.compare(s1, s2); - } + SortedSet highlightTypes = new TreeSet((o1, o2) -> { + final HighlightSeverity s1 = o1.getSeverity(null); + final HighlightSeverity s2 = o2.getSeverity(null); + return Comparing.compare(s1, s2); }); for (InspectionToolWrapper tool : propertiesTools) { diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertiesParser.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertiesParser.java index 1661b0c7998c..c434600de06c 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertiesParser.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertiesParser.java @@ -30,26 +30,21 @@ import org.jetbrains.annotations.NotNull; */ public class PropertiesParser implements PsiParser { private static final TripleFunction,ThreeState> - MATCH_BY_KEY = new TripleFunction, ThreeState>() { - @Override - public ThreeState fun(ASTNode oldNode, - LighterASTNode newNode, - FlyweightCapableTreeStructure structure) { - if (oldNode.getElementType() == PropertiesElementTypes.PROPERTY) { - ASTNode oldName = oldNode.findChildByType(PropertiesTokenTypes.KEY_CHARACTERS); - if (oldName != null) { - CharSequence oldNameStr = oldName.getChars(); - CharSequence newNameStr = findKeyCharacters(newNode, structure); + MATCH_BY_KEY = (oldNode, newNode, structure) -> { + if (oldNode.getElementType() == PropertiesElementTypes.PROPERTY) { + ASTNode oldName = oldNode.findChildByType(PropertiesTokenTypes.KEY_CHARACTERS); + if (oldName != null) { + CharSequence oldNameStr = oldName.getChars(); + CharSequence newNameStr = findKeyCharacters(newNode, structure); - if (oldNameStr != null && !Comparing.equal(oldNameStr, newNameStr)) { - return ThreeState.NO; - } - } - } + if (oldNameStr != null && !Comparing.equal(oldNameStr, newNameStr)) { + return ThreeState.NO; + } + } + } - return ThreeState.UNSURE; - } - }; + return ThreeState.UNSURE; + }; private static CharSequence findKeyCharacters(LighterASTNode newNode, FlyweightCapableTreeStructure structure) { Ref childrenRef = Ref.create(null); diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertiesFileImpl.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertiesFileImpl.java index 6705eb635972..f82ee002303f 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertiesFileImpl.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertiesFileImpl.java @@ -150,14 +150,11 @@ public class PropertiesFileImpl extends PsiFileBase implements PropertiesFile { return null; } if (myAlphaSorted) { - final int insertIndex = Collections.binarySearch(myProperties, property, new Comparator() { - @Override - public int compare(IProperty p1, IProperty p2) { - final String k1 = p1.getKey(); - final String k2 = p2.getKey(); - LOG.assertTrue(k1 != null && k2 != null); - return String.CASE_INSENSITIVE_ORDER.compare(k1, k2); - } + final int insertIndex = Collections.binarySearch(myProperties, property, (p1, p2) -> { + final String k1 = p1.getKey(); + final String k2 = p2.getKey(); + LOG.assertTrue(k1 != null && k2 != null); + return String.CASE_INSENSITIVE_ORDER.compare(k1, k2); }); return insertIndex == -1 ? null :myProperties.get(insertIndex < 0 ? - insertIndex - 2 : insertIndex); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/references/PropertyReferenceBase.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/references/PropertyReferenceBase.java index 2cc4851b012f..e8ea30f5dc76 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/references/PropertyReferenceBase.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/references/PropertyReferenceBase.java @@ -154,12 +154,10 @@ public abstract class PropertyReferenceBase implements PsiPolyVariantReference, } } // put default properties file first - ContainerUtil.quickSort(properties, new Comparator() { - public int compare(final IProperty o1, final IProperty o2) { - String name1 = o1.getPropertiesFile().getName(); - String name2 = o2.getPropertiesFile().getName(); - return Comparing.compare(name1, name2); - } + ContainerUtil.quickSort(properties, (o1, o2) -> { + String name1 = o1.getPropertiesFile().getName(); + String name2 = o2.getPropertiesFile().getName(); + return Comparing.compare(name1, name2); }); return getResolveResults(properties); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/GroupByWordPrefixes.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/GroupByWordPrefixes.java index 79472a5d1691..f4e0ea5aa4b1 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/GroupByWordPrefixes.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/GroupByWordPrefixes.java @@ -83,21 +83,18 @@ public class GroupByWordPrefixes implements Grouper, Sorter { List words = StringUtil.split(text, mySeparator); keys.add(new Key(words, element)); } - Collections.sort(keys, new Comparator() { - @Override - public int compare(final Key k1, final Key k2) { - List o1 = k1.words; - List o2 = k2.words; - for (int i = 0; i < Math.max(o1.size(), o2.size()); i++) { - if (i == o1.size()) return 1; - if (i == o2.size()) return -1; - String s1 = o1.get(i); - String s2 = o2.get(i); - int res = s1.compareTo(s2); - if (res != 0) return res; - } - return 0; + Collections.sort(keys, (k1, k2) -> { + List o1 = k1.words; + List o2 = k2.words; + for (int i = 0; i < Math.max(o1.size(), o2.size()); i++) { + if (i == o1.size()) return 1; + if (i == o2.size()) return -1; + String s1 = o1.get(i); + String s2 = o2.get(i); + int res = s1.compareTo(s2); + if (res != 0) return res; } + return 0; }); List groups = new ArrayList(); int groupStart = 0; diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesFileStructureViewModel.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesFileStructureViewModel.java index f013839553c6..615c0e69f2b1 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesFileStructureViewModel.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesFileStructureViewModel.java @@ -42,12 +42,10 @@ public class PropertiesFileStructureViewModel extends TextEditorBasedStructureVi private static final Sorter KIND_SORTER = new Sorter() { @NotNull public Comparator getComparator() { - return new Comparator() { - public int compare(final Object o1, final Object o2) { - int weight1 = o1 instanceof PropertiesPrefixGroup ? 1 : 0; - int weight2 = o2 instanceof PropertiesPrefixGroup ? 1 : 0; - return weight1 - weight2; - } + return (o1, o2) -> { + int weight1 = o1 instanceof PropertiesPrefixGroup ? 1 : 0; + int weight2 = o2 instanceof PropertiesPrefixGroup ? 1 : 0; + return weight1 - weight2; }; } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesPrefixGroup.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesPrefixGroup.java index f37c6166d9a0..b1ae52c27ed7 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesPrefixGroup.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/structureView/PropertiesPrefixGroup.java @@ -141,19 +141,15 @@ public class PropertiesPrefixGroup implements Group, ResourceBundleEditorViewEle @NotNull @Override public IProperty[] getProperties() { - final List elements = ContainerUtil.mapNotNull(getChildren(), new NullableFunction() { - @Nullable - @Override - public IProperty fun(final TreeElement treeElement) { - if (treeElement instanceof PropertiesStructureViewElement) { - PropertiesStructureViewElement propertiesElement = (PropertiesStructureViewElement)treeElement; - return propertiesElement.getValue(); - } - else if (treeElement instanceof ResourceBundlePropertyStructureViewElement) { - return ((ResourceBundlePropertyStructureViewElement)treeElement).getProperties()[0]; - } - return null; + final List elements = ContainerUtil.mapNotNull(getChildren(), (NullableFunction)treeElement -> { + if (treeElement instanceof PropertiesStructureViewElement) { + PropertiesStructureViewElement propertiesElement = (PropertiesStructureViewElement)treeElement; + return propertiesElement.getValue(); } + else if (treeElement instanceof ResourceBundlePropertyStructureViewElement) { + return ((ResourceBundlePropertyStructureViewElement)treeElement).getProperties()[0]; + } + return null; }); return elements.toArray(new IProperty[elements.size()]); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlPropertiesFileImpl.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlPropertiesFileImpl.java index 3306a21e86ef..b6d1a566e527 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlPropertiesFileImpl.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/xml/XmlPropertiesFileImpl.java @@ -164,13 +164,10 @@ public class XmlPropertiesFileImpl extends XmlPropertiesFile { if (myAlphaSorted) { final XmlProperty dummyProperty = new XmlProperty(entry, this); final int insertIndex = - Collections.binarySearch(myProperties, dummyProperty, new Comparator() { - @Override - public int compare(IProperty p1, IProperty p2) { - final String k1 = p1.getKey(); - final String k2 = p2.getKey(); - return k1.compareTo(k2); - } + Collections.binarySearch(myProperties, dummyProperty, (p1, p2) -> { + final String k1 = p1.getKey(); + final String k2 = p2.getKey(); + return k1.compareTo(k2); }); final IProperty insertPosition; final IProperty inserted; diff --git a/plugins/properties/src/com/intellij/lang/properties/PropertiesDocumentationProvider.java b/plugins/properties/src/com/intellij/lang/properties/PropertiesDocumentationProvider.java index 524bde6509ea..2954ba9eb25e 100644 --- a/plugins/properties/src/com/intellij/lang/properties/PropertiesDocumentationProvider.java +++ b/plugins/properties/src/com/intellij/lang/properties/PropertiesDocumentationProvider.java @@ -69,11 +69,8 @@ public class PropertiesDocumentationProvider extends AbstractDocumentationProvid if (background != null) { info +="
      "; } - String doc = StringUtil.join(ContainerUtil.map(StringUtil.split(text, "\n"), new Function() { - @Override - public String fun(String s) { - return StringUtil.trimStart(StringUtil.trimStart(s, "#"), "!").trim(); - } + String doc = StringUtil.join(ContainerUtil.map(StringUtil.split(text, "\n"), s -> { + return StringUtil.trimStart(StringUtil.trimStart(s, "#"), "!").trim(); }), "
      "); info += "" + doc + "\n
      "; if (background != null) { diff --git a/plugins/properties/src/com/intellij/lang/properties/PropertiesFilesManager.java b/plugins/properties/src/com/intellij/lang/properties/PropertiesFilesManager.java index 5477c137021e..ef269a9d60de 100644 --- a/plugins/properties/src/com/intellij/lang/properties/PropertiesFilesManager.java +++ b/plugins/properties/src/com/intellij/lang/properties/PropertiesFilesManager.java @@ -53,26 +53,18 @@ public class PropertiesFilesManager extends AbstractProjectComponent { if (EncodingManager.PROP_NATIVE2ASCII_SWITCH.equals(propertyName) || EncodingManager.PROP_PROPERTIES_FILES_ENCODING.equals(propertyName) ) { - DumbService.getInstance(myProject).smartInvokeLater(new Runnable(){ - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable(){ - @Override - public void run() { - Collection filesToRefresh = FileBasedIndex.getInstance() - .getContainingFiles(FileTypeIndex.NAME, PropertiesFileType.INSTANCE, GlobalSearchScope.allScope(myProject)); - VirtualFile[] virtualFiles = VfsUtilCore.toVirtualFileArray(filesToRefresh); - FileDocumentManager.getInstance().saveAllDocuments(); + DumbService.getInstance(myProject).smartInvokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> { + Collection filesToRefresh = FileBasedIndex.getInstance() + .getContainingFiles(FileTypeIndex.NAME, PropertiesFileType.INSTANCE, GlobalSearchScope.allScope(myProject)); + VirtualFile[] virtualFiles = VfsUtilCore.toVirtualFileArray(filesToRefresh); + FileDocumentManager.getInstance().saveAllDocuments(); - //force to re-detect encoding - for (VirtualFile virtualFile : virtualFiles) { - virtualFile.setCharset(null); - } - FileDocumentManager.getInstance().reloadFiles(virtualFiles); - } - }); + //force to re-detect encoding + for (VirtualFile virtualFile : virtualFiles) { + virtualFile.setCharset(null); } - }); + FileDocumentManager.getInstance().reloadFiles(virtualFiles); + })); } } }; diff --git a/plugins/properties/src/com/intellij/lang/properties/ResourceBundleReference.java b/plugins/properties/src/com/intellij/lang/properties/ResourceBundleReference.java index c09657c572e6..9cca0dc637f9 100644 --- a/plugins/properties/src/com/intellij/lang/properties/ResourceBundleReference.java +++ b/plugins/properties/src/com/intellij/lang/properties/ResourceBundleReference.java @@ -41,12 +41,7 @@ import java.util.Set; public class ResourceBundleReference extends PsiReferenceBase implements PsiPolyVariantReference, BundleNameEvaluator, ResolvingHint { private static final Function PROPERTIES_FILE_PSI_ELEMENT_FUNCTION = - new Function() { - @Override - public PsiElement fun(PropertiesFile propertiesFile) { - return propertiesFile.getContainingFile(); - } - }; + propertiesFile -> propertiesFile.getContainingFile(); private final String myBundleName; public ResourceBundleReference(final PsiElement element) { diff --git a/plugins/properties/src/com/intellij/lang/properties/create/CreateResourceBundleDialogComponent.java b/plugins/properties/src/com/intellij/lang/properties/create/CreateResourceBundleDialogComponent.java index 5d3882f13676..b9759f782a66 100644 --- a/plugins/properties/src/com/intellij/lang/properties/create/CreateResourceBundleDialogComponent.java +++ b/plugins/properties/src/com/intellij/lang/properties/create/CreateResourceBundleDialogComponent.java @@ -59,17 +59,14 @@ import java.util.*; public class CreateResourceBundleDialogComponent { private final static Logger LOG = Logger.getInstance(CreateResourceBundleDialogComponent.class); - private static final Comparator LOCALE_COMPARATOR = new Comparator() { - @Override - public int compare(Locale l1, Locale l2) { - if (l1 == PropertiesUtil.DEFAULT_LOCALE) { - return -1; - } - if (l2 == PropertiesUtil.DEFAULT_LOCALE) { - return 1; - } - return l1.toString().compareTo(l2.toString()); + private static final Comparator LOCALE_COMPARATOR = (l1, l2) -> { + if (l1 == PropertiesUtil.DEFAULT_LOCALE) { + return -1; } + if (l2 == PropertiesUtil.DEFAULT_LOCALE) { + return 1; + } + return l1.toString().compareTo(l2.toString()); }; private final Project myProject; private final PsiDirectory myDirectory; @@ -175,24 +172,21 @@ public class CreateResourceBundleDialogComponent { return ApplicationManager.getApplication().runWriteAction(new Computable>() { @Override public List compute() { - return ContainerUtil.map(fileNames, new Function() { - @Override - public PsiFile fun(String n) { - final boolean isXml = myResourceBundle == null - ? myUseXMLBasedPropertiesCheckBox.isSelected() - : myResourceBundle.getDefaultPropertiesFile() instanceof XmlPropertiesFile; - if (isXml) { - FileTemplate template = FileTemplateManager.getInstance(myProject).getInternalTemplate("XML Properties File.xml"); - LOG.assertTrue(template != null); - try { - return (PsiFile)FileTemplateUtil.createFromTemplate(template, n, null, myDirectory); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } else { - return myDirectory.createFile(n); + return ContainerUtil.map(fileNames, n -> { + final boolean isXml = myResourceBundle == null + ? myUseXMLBasedPropertiesCheckBox.isSelected() + : myResourceBundle.getDefaultPropertiesFile() instanceof XmlPropertiesFile; + if (isXml) { + FileTemplate template = FileTemplateManager.getInstance(myProject).getInternalTemplate("XML Properties File.xml"); + LOG.assertTrue(template != null); + try { + return (PsiFile)FileTemplateUtil.createFromTemplate(template, n, null, myDirectory); } + catch (Exception e) { + throw new RuntimeException(e); + } + } else { + return myDirectory.createFile(n); } }); } @@ -207,23 +201,15 @@ public class CreateResourceBundleDialogComponent { private Set getFileNamesToCreate() { final String name = getBaseName(); final String suffix = getPropertiesFileSuffix(); - return ContainerUtil.map2Set(myLocalesModel.getItems(), new Function() { - @Override - public String fun(Locale locale) { - return name + (locale == PropertiesUtil.DEFAULT_LOCALE ? "" : ("_" + locale.toString())) + suffix; - } - }); + return ContainerUtil.map2Set(myLocalesModel.getItems(), + locale -> name + (locale == PropertiesUtil.DEFAULT_LOCALE ? "" : ("_" + locale.toString())) + suffix); } private void combineToResourceBundleIfNeed(Collection files) { - Collection createdFiles = ContainerUtil.map(files, new NotNullFunction() { - @NotNull - @Override - public PropertiesFile fun(PsiFile dom) { - final PropertiesFile file = PropertiesImplUtil.getPropertiesFile(dom); - LOG.assertTrue(file != null, dom.getName()); - return file; - } + Collection createdFiles = ContainerUtil.map(files, (NotNullFunction)dom -> { + final PropertiesFile file = PropertiesImplUtil.getPropertiesFile(dom); + LOG.assertTrue(file != null, dom.getName()); + return file; }); ResourceBundle mainBundle = myResourceBundle; @@ -336,11 +322,8 @@ public class CreateResourceBundleDialogComponent { restrictedLocales = Collections.emptyList(); } else { locales = Collections.emptyList(); - restrictedLocales = ContainerUtil.map(myResourceBundle.getPropertiesFiles(), new Function() { - @Override - public Locale fun(PropertiesFile propertiesFile) { - return propertiesFile.getLocale(); - } + restrictedLocales = ContainerUtil.map(myResourceBundle.getPropertiesFiles(), propertiesFile -> { + return propertiesFile.getLocale(); }); } myLocalesModel = new CollectionListModel(locales) { @@ -409,12 +392,7 @@ public class CreateResourceBundleDialogComponent { @Override public boolean onClick(@NotNull MouseEvent event, int clickCount) { if (clickCount == 1) { - myLocalesModel.add(ContainerUtil.map(projectExistLocalesList.getSelectedValues(), new Function() { - @Override - public Locale fun(Object o) { - return (Locale)o; - } - })); + myLocalesModel.add(ContainerUtil.map(projectExistLocalesList.getSelectedValues(), o -> (Locale)o)); return true; } return false; diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/GotoPropertyDeclarationsProvider.java b/plugins/properties/src/com/intellij/lang/properties/editor/GotoPropertyDeclarationsProvider.java index 5b4818f4e75b..1966cab76420 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/GotoPropertyDeclarationsProvider.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/GotoPropertyDeclarationsProvider.java @@ -61,15 +61,11 @@ public class GotoPropertyDeclarationsProvider extends GotoRelatedProvider { final PropertiesFile file = PropertiesImplUtil.getPropertiesFile(property.getPsiElement().getContainingFile()); assert file != null; final ResourceBundle resourceBundle = file.getResourceBundle(); - return ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), new NullableFunction() { - @Nullable - @Override - public GotoRelatedItem fun(PropertiesFile f) { - final IProperty foundProperty = f.findPropertyByKey(propertyKey); - return foundProperty == null ? - null : - new GotoRelatedItem(foundProperty.getPsiElement(), "Property Declarations"); - } + return ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), (NullableFunction)f -> { + final IProperty foundProperty = f.findPropertyByKey(propertyKey); + return foundProperty == null ? + null : + new GotoRelatedItem(foundProperty.getPsiElement(), "Property Declarations"); }); } } diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/GotoResourceBundleLocalizationsProvider.java b/plugins/properties/src/com/intellij/lang/properties/editor/GotoResourceBundleLocalizationsProvider.java index ac4c5faf9c43..242cf551718c 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/GotoResourceBundleLocalizationsProvider.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/GotoResourceBundleLocalizationsProvider.java @@ -53,11 +53,8 @@ public class GotoResourceBundleLocalizationsProvider extends GotoRelatedProvider if (bundlePropertiesFiles.size() != 1) { final ArrayList propertiesFilesWithoutCurrent = ContainerUtil.newArrayList(bundlePropertiesFiles); propertiesFilesWithoutCurrent.remove(psiFile); - return ContainerUtil.map(propertiesFilesWithoutCurrent, new Function() { - @Override - public GotoRelatedItem fun(final PropertiesFile propertiesFile) { - return new GotoRelatedItem((PsiElement) propertiesFile, "Other Localizations"); - } + return ContainerUtil.map(propertiesFilesWithoutCurrent, propertiesFile -> { + return new GotoRelatedItem((PsiElement) propertiesFile, "Other Localizations"); }); } else { return Collections.emptyList(); diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java b/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java index 639e22b67205..ec5d3633dbdd 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/NewPropertyAction.java @@ -160,16 +160,10 @@ class NewPropertyAction extends AnAction { } } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(resourceBundle.getProject(), new Runnable() { - @Override - public void run() { - myResourceBundleEditor.getPropertiesInsertDeleteManager().insertNewProperty(newPropertyName, ""); - } - }); - } + ApplicationManager.getApplication().runWriteAction(() -> { + WriteCommandAction.runWriteCommandAction(resourceBundle.getProject(), () -> { + myResourceBundleEditor.getPropertiesInsertDeleteManager().insertNewProperty(newPropertyName, ""); + }); }); myResourceBundleEditor.updateTreeRoot(); diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/PropertiesCopyHandler.java b/plugins/properties/src/com/intellij/lang/properties/editor/PropertiesCopyHandler.java index 9821a90b6086..78733581f969 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/PropertiesCopyHandler.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/PropertiesCopyHandler.java @@ -102,12 +102,8 @@ public class PropertiesCopyHandler extends CopyHandlerDelegateBase { } final ResourceBundle resourceBundle = representative.getPropertiesFile().getResourceBundle(); final List properties = ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), - new NullableFunction() { - @Nullable - @Override - public IProperty fun(PropertiesFile propertiesFile) { - return propertiesFile.findPropertyByKey(key); - } + (NullableFunction)propertiesFile -> { + return propertiesFile.findPropertyByKey(key); }); final PropertiesCopyDialog dlg = new PropertiesCopyDialog(properties, resourceBundle); if (!properties.isEmpty() && dlg.showAndGet()) { @@ -142,21 +138,15 @@ public class PropertiesCopyHandler extends CopyHandlerDelegateBase { } if (!propertiesFileMapping.isEmpty()) { - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - @Override - public void run() { - if (!FileModificationService.getInstance().preparePsiElementsForWrite(ContainerUtil.map(propertiesFileMapping.values(), - new Function() { - @Override - public PsiElement fun(PropertiesFile file) { - return file.getContainingFile(); - } - }))) return; - for (Map.Entry entry : propertiesFileMapping.entrySet()) { - final String value = entry.getKey().getValue(); - final PropertiesFile target = entry.getValue(); - target.addProperty(newName, value); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + if (!FileModificationService.getInstance().preparePsiElementsForWrite(ContainerUtil.map(propertiesFileMapping.values(), + (Function)file -> { + return file.getContainingFile(); + }))) return; + for (Map.Entry entry : propertiesFileMapping.entrySet()) { + final String value = entry.getKey().getValue(); + final PropertiesFile target = entry.getValue(); + target.addProperty(newName, value); } }); diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleAsVirtualFile.java b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleAsVirtualFile.java index cbb620ca018c..d1130ebfb029 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleAsVirtualFile.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleAsVirtualFile.java @@ -177,11 +177,8 @@ public class ResourceBundleAsVirtualFile extends VirtualFile { @Override public void refresh(boolean asynchronous, boolean recursive, Runnable postRunnable) { - List files = ContainerUtil.mapNotNull(myResourceBundle.getPropertiesFiles(), new Function() { - @Override - public VirtualFile fun(PropertiesFile file) { - return file.getVirtualFile(); - } + List files = ContainerUtil.mapNotNull(myResourceBundle.getPropertiesFiles(), file -> { + return file.getVirtualFile(); }); if (!files.isEmpty()) { RefreshQueue.getInstance().refresh(false, false, postRunnable, files); diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java index 78c7e5b394dc..32878943fa50 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java @@ -292,12 +292,9 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document return; } mySelectionChangeAlarm.cancelAllRequests(); - mySelectionChangeAlarm.addRequest(new Runnable() { - @Override - public void run() { - mySelectionChangeAlarm.cancelAllRequests(); - setStructureViewSelection(propertyName); - } + mySelectionChangeAlarm.addRequest(() -> { + mySelectionChangeAlarm.cancelAllRequests(); + setStructureViewSelection(propertyName); }, 500); return; } @@ -371,28 +368,22 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { - @Override - public void run() { - try { + ApplicationManager.getApplication().runWriteAction(() -> { + WriteCommandAction.runWriteCommandAction(myProject, () -> { + try { - if (currentValue.isEmpty() && - ResourceBundleEditorKeepEmptyValueToggleAction.keepEmptyProperties() && - propertiesFile.equals(myResourceBundle.getDefaultPropertiesFile().getVirtualFile())) { - myPropertiesInsertDeleteManager.deletePropertyIfExist(currentSelectedProperty, PropertiesImplUtil.getPropertiesFile(propertiesFile, myProject)); - } else { - myPropertiesInsertDeleteManager.insertOrUpdateTranslation(currentSelectedProperty, currentValue, PropertiesImplUtil.getPropertiesFile(propertiesFile, myProject)); - } - } - catch (final IncorrectOperationException e) { - LOG.error(e); - } + if (currentValue.isEmpty() && + ResourceBundleEditorKeepEmptyValueToggleAction.keepEmptyProperties() && + propertiesFile.equals(myResourceBundle.getDefaultPropertiesFile().getVirtualFile())) { + myPropertiesInsertDeleteManager.deletePropertyIfExist(currentSelectedProperty, PropertiesImplUtil.getPropertiesFile(propertiesFile, myProject)); + } else { + myPropertiesInsertDeleteManager.insertOrUpdateTranslation(currentSelectedProperty, currentValue, PropertiesImplUtil.getPropertiesFile(propertiesFile, myProject)); } - }); - } + } + catch (final IncorrectOperationException e) { + LOG.error(e); + } + }); }); } @@ -526,21 +517,13 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document if (editor == null) continue; final IProperty property = propertiesFile.findPropertyByKey(propertyName); final Document document = editor.getDocument(); - CommandProcessor.getInstance().executeCommand(null, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (!checkIsUnderUndoRedoAction || - !undoManager.isActive() || - !(undoManager.isRedoInProgress() || undoManager.isUndoInProgress())) { - updateDocumentFromPropertyValue(getPropertyEditorValue(property), document, propertiesFile.getVirtualFile()); - } - } - }); + CommandProcessor.getInstance().executeCommand(null, () -> ApplicationManager.getApplication().runWriteAction(() -> { + if (!checkIsUnderUndoRedoAction || + !undoManager.isActive() || + !(undoManager.isRedoInProgress() || undoManager.isUndoInProgress())) { + updateDocumentFromPropertyValue(getPropertyEditorValue(property), document, propertiesFile.getVirtualFile()); } - }, "", this); + }), "", this); JPanel titledPanel = myTitledPanels.get(propertiesFile.getVirtualFile()); ((TitledBorder)titledPanel.getBorder()).setTitleColor(property == null ? JBColor.RED : UIUtil.getLabelTextForeground()); titledPanel.repaint(); @@ -590,14 +573,11 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document } private void selectionChanged() { myBackSlashPressed.clear(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - updateEditorsFromProperties(true); - final StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject); - if (statusBar != null) { - statusBar.setInfo("Selected property: " + getSelectedPropertyName()); - } + UIUtil.invokeLaterIfNeeded(() -> { + updateEditorsFromProperties(true); + final StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject); + if (statusBar != null) { + statusBar.setInfo("Selected property: " + getSelectedPropertyName()); } }); } @@ -623,12 +603,7 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document if (tree == null) return Collections.emptyList(); TreePath[] selected = tree.getSelectionModel().getSelectionPaths(); if (selected == null || selected.length == 0) return Collections.emptyList(); - return ContainerUtil.map(selected, new Function() { - @Override - public DefaultMutableTreeNode fun(TreePath treePath) { - return (DefaultMutableTreeNode)treePath.getLastPathComponent(); - } - }); + return ContainerUtil.map(selected, treePath -> (DefaultMutableTreeNode)treePath.getLastPathComponent()); } @Nullable @@ -651,16 +626,13 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document @NotNull public Collection getSelectedElements() { final Collection selectedNodes = getSelectedNodes(); - return ContainerUtil.mapNotNull(selectedNodes, new NullableFunction() { - @Nullable - @Override - public ResourceBundleEditorViewElement fun(DefaultMutableTreeNode selectedNode) { - Object userObject = selectedNode.getUserObject(); - if (!(userObject instanceof AbstractTreeNode)) return null; - Object value = ((AbstractTreeNode)userObject).getValue(); - return value instanceof ResourceBundleEditorViewElement ? (ResourceBundleEditorViewElement) value : null; - } - }); + return ContainerUtil.mapNotNull(selectedNodes, + (NullableFunction)selectedNode -> { + Object userObject = selectedNode.getUserObject(); + if (!(userObject instanceof AbstractTreeNode)) return null; + Object value = ((AbstractTreeNode)userObject).getValue(); + return value instanceof ResourceBundleEditorViewElement ? (ResourceBundleEditorViewElement) value : null; + }); } @Nullable @@ -884,11 +856,8 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document @Override public Document[] getDocuments() { - return ContainerUtil.map2Array(myEditors.keySet(), new Document[myEditors.size()], new Function() { - @Override - public Document fun(VirtualFile propertiesFile) { - return FileDocumentManager.getInstance().getDocument(propertiesFile); - } + return ContainerUtil.map2Array(myEditors.keySet(), new Document[myEditors.size()], propertiesFile -> { + return FileDocumentManager.getInstance().getDocument(propertiesFile); }); } @@ -956,28 +925,22 @@ public class ResourceBundleEditor extends UserDataHolderBase implements Document if (currentSelectedProperty == null) { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { - @Override - public void run() { - try { - for (Map.Entry entry : myEditors.entrySet()) { - final Editor translationEditor = entry.getValue(); - if (translationEditor != editor) { - final VirtualFile propertiesFile = entry.getKey(); - myPropertiesInsertDeleteManager.insertOrUpdateTranslation(currentSelectedProperty, valueToPropagate, PropertiesImplUtil.getPropertiesFile(propertiesFile, myProject)); - translationEditor.getDocument().setText(valueToPropagate); - } - } - } - catch (final IncorrectOperationException e) { - LOG.error(e); + ApplicationManager.getApplication().runWriteAction(() -> { + WriteCommandAction.runWriteCommandAction(myProject, () -> { + try { + for (Map.Entry entry : myEditors.entrySet()) { + final Editor translationEditor = entry.getValue(); + if (translationEditor != editor) { + final VirtualFile propertiesFile = entry.getKey(); + myPropertiesInsertDeleteManager.insertOrUpdateTranslation(currentSelectedProperty, valueToPropagate, PropertiesImplUtil.getPropertiesFile(propertiesFile, myProject)); + translationEditor.getDocument().setText(valueToPropagate); } } - }); - } + } + catch (final IncorrectOperationException e1) { + LOG.error(e1); + } + }); }); } }); diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleStructureViewComponent.java b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleStructureViewComponent.java index 695fc03c9a55..af4676ee7f58 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleStructureViewComponent.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleStructureViewComponent.java @@ -117,20 +117,12 @@ public class ResourceBundleStructureViewComponent extends PropertiesGroupingStru } else { return ContainerUtil.toArray(ContainerUtil.flatten( - ContainerUtil.mapNotNull(selectedElements, new NullableFunction>() { - @Nullable - @Override - public List fun(ResourceBundleEditorViewElement element) { - final IProperty[] properties = element.getProperties(); - return properties == null ? null : ContainerUtil.newArrayList(properties); - } - })), new ArrayFactory() { - @NotNull - @Override - public IProperty[] create(int count) { + ContainerUtil.mapNotNull(selectedElements, (NullableFunction>)element -> { + final IProperty[] properties = element.getProperties(); + return properties == null ? null : ContainerUtil.newArrayList(properties); + })), count -> { return new IProperty[count]; - } - }); + }); } } else if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) { diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/inspections/incomplete/IncompletePropertyInspection.java b/plugins/properties/src/com/intellij/lang/properties/editor/inspections/incomplete/IncompletePropertyInspection.java index a86f40cd4d7f..ac161aeb970b 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/inspections/incomplete/IncompletePropertyInspection.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/inspections/incomplete/IncompletePropertyInspection.java @@ -135,39 +135,25 @@ public class IncompletePropertyInspection extends LocalInspectionTool implements final TreeSet suffixesToIgnore = new TreeSet(ContainerUtil.map(allFilesWithoutTranslation, - new Function() { - @Override - public String fun(PropertiesFile file) { - return PropertiesUtil.getSuffix(file); - } - })); + file -> { + return PropertiesUtil.getSuffix(file); + })); if (new IncompletePropertyInspectionOptionsPanel(suffixesToIgnore).showDialogAndGet(project)) { - DisableInspectionToolAction.modifyAndCommitProjectProfile(new Consumer() { - @Override - public void consume(ModifiableModel modifiableModel) { - ((IncompletePropertyInspection)modifiableModel.getInspectionTool(TOOL_KEY, element).getTool()).addSuffixes(suffixesToIgnore); - } - }, project); + DisableInspectionToolAction.modifyAndCommitProjectProfile( + modifiableModel -> ((IncompletePropertyInspection)modifiableModel.getInspectionTool(TOOL_KEY, element).getTool()).addSuffixes(suffixesToIgnore), project); } } } public boolean isPropertyComplete(final String key, final ResourceBundle resourceBundle) { - return isPropertyComplete(ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), new Function() { - @Override - public IProperty fun(PropertiesFile file) { - return file.findPropertyByKey(key); - } + return isPropertyComplete(ContainerUtil.mapNotNull(resourceBundle.getPropertiesFiles(), file -> { + return file.findPropertyByKey(key); }), resourceBundle); } private boolean isPropertyComplete(final List properties, final ResourceBundle resourceBundle) { - final Set existed = ContainerUtil.map2Set(properties, new Function() { - - @Override - public PropertiesFile fun(IProperty property) { - return property.getPropertiesFile(); - } + final Set existed = ContainerUtil.map2Set(properties, property -> { + return property.getPropertiesFile(); }); for (PropertiesFile file : resourceBundle.getPropertiesFiles()) { if (!existed.contains(file) && !getIgnoredSuffixes().contains(PropertiesUtil.getSuffix(file))) { diff --git a/plugins/properties/src/com/intellij/lang/properties/projectView/ResourceBundleDeleteProvider.java b/plugins/properties/src/com/intellij/lang/properties/projectView/ResourceBundleDeleteProvider.java index d99db439e744..44396a6b424c 100644 --- a/plugins/properties/src/com/intellij/lang/properties/projectView/ResourceBundleDeleteProvider.java +++ b/plugins/properties/src/com/intellij/lang/properties/projectView/ResourceBundleDeleteProvider.java @@ -40,19 +40,11 @@ import static com.intellij.util.containers.ContainerUtil.*; public class ResourceBundleDeleteProvider implements DeleteProvider { private static final Logger LOG = Logger.getInstance(ResourceBundleDeleteProvider.class); - private static final Function> MAPPER_RES_BUNDLE_TO_FILES = new Function>() { - @Override - public List fun(ResourceBundle resourceBundle) { - return resourceBundle.getPropertiesFiles(); - } - }; + private static final Function> MAPPER_RES_BUNDLE_TO_FILES = + resourceBundle -> resourceBundle.getPropertiesFiles(); - private static final Function MAPPER_FILE_AS_PSI_ELEMENT = new Function() { - @Override - public PsiElement fun(PropertiesFile propertiesFile) { - return propertiesFile.getContainingFile(); - } - }; + private static final Function MAPPER_FILE_AS_PSI_ELEMENT = + propertiesFile -> propertiesFile.getContainingFile(); public void deleteElement(@NotNull DataContext dataContext) { final ResourceBundle[] resourceBundles = ResourceBundle.ARRAY_DATA_KEY.getData(dataContext); diff --git a/plugins/properties/src/com/intellij/lang/properties/refactoring/rename/ResourceBundleFromEditorRenameHandler.java b/plugins/properties/src/com/intellij/lang/properties/refactoring/rename/ResourceBundleFromEditorRenameHandler.java index b51517c80ec3..74531fd099bf 100644 --- a/plugins/properties/src/com/intellij/lang/properties/refactoring/rename/ResourceBundleFromEditorRenameHandler.java +++ b/plugins/properties/src/com/intellij/lang/properties/refactoring/rename/ResourceBundleFromEditorRenameHandler.java @@ -79,22 +79,19 @@ public class ResourceBundleFromEditorRenameHandler implements RenameHandler { assert resourceBundleEditor != null; final ResourceBundleEditorViewElement selectedElement = resourceBundleEditor.getSelectedElementIfOnlyOne(); if (selectedElement != null) { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - if (selectedElement instanceof PropertiesPrefixGroup) { - final PropertiesPrefixGroup group = (PropertiesPrefixGroup)selectedElement; - ResourceBundleRenameUtil.renameResourceBundleKeySection(getPsiElementsFromGroup(group), - group.getPresentableName(), - group.getPrefix().length() - group.getPresentableName().length()); - } else if (selectedElement instanceof ResourceBundlePropertyStructureViewElement) { - final PsiElement psiElement = ((ResourceBundlePropertyStructureViewElement)selectedElement).getProperty().getPsiElement(); - ResourceBundleRenameUtil.renameResourceBundleKey(psiElement, project); - } else if (selectedElement instanceof ResourceBundleFileStructureViewElement) { - ResourceBundleRenameUtil.renameResourceBundleBaseName(((ResourceBundleFileStructureViewElement)selectedElement).getValue(), project); - } else { - throw new IllegalStateException("unsupported type: " + selectedElement.getClass()); - } + CommandProcessor.getInstance().runUndoTransparentAction(() -> { + if (selectedElement instanceof PropertiesPrefixGroup) { + final PropertiesPrefixGroup group = (PropertiesPrefixGroup)selectedElement; + ResourceBundleRenameUtil.renameResourceBundleKeySection(getPsiElementsFromGroup(group), + group.getPresentableName(), + group.getPrefix().length() - group.getPresentableName().length()); + } else if (selectedElement instanceof ResourceBundlePropertyStructureViewElement) { + final PsiElement psiElement = ((ResourceBundlePropertyStructureViewElement)selectedElement).getProperty().getPsiElement(); + ResourceBundleRenameUtil.renameResourceBundleKey(psiElement, project); + } else if (selectedElement instanceof ResourceBundleFileStructureViewElement) { + ResourceBundleRenameUtil.renameResourceBundleBaseName(((ResourceBundleFileStructureViewElement)selectedElement).getValue(), project); + } else { + throw new IllegalStateException("unsupported type: " + selectedElement.getClass()); } }); } @@ -106,18 +103,14 @@ public class ResourceBundleFromEditorRenameHandler implements RenameHandler { } private static List getPsiElementsFromGroup(final PropertiesPrefixGroup propertiesPrefixGroup) { - return ContainerUtil.mapNotNull(propertiesPrefixGroup.getChildren(), new NullableFunction() { - @Nullable - @Override - public PsiElement fun(TreeElement treeElement) { - if (treeElement instanceof PropertiesStructureViewElement) { - return ((PropertiesStructureViewElement)treeElement).getValue().getPsiElement(); - } - if (treeElement instanceof ResourceBundlePropertyStructureViewElement) { - return ((ResourceBundlePropertyStructureViewElement)treeElement).getProperty().getPsiElement(); - } - return null; + return ContainerUtil.mapNotNull(propertiesPrefixGroup.getChildren(), (NullableFunction)treeElement -> { + if (treeElement instanceof PropertiesStructureViewElement) { + return ((PropertiesStructureViewElement)treeElement).getValue().getPsiElement(); } + if (treeElement instanceof ResourceBundlePropertyStructureViewElement) { + return ((ResourceBundlePropertyStructureViewElement)treeElement).getProperty().getPsiElement(); + } + return null; }); } } diff --git a/plugins/properties/src/com/intellij/lang/properties/references/CreatePropertyFix.java b/plugins/properties/src/com/intellij/lang/properties/references/CreatePropertyFix.java index 335cacbfea1f..6cf6946fd1ae 100644 --- a/plugins/properties/src/com/intellij/lang/properties/references/CreatePropertyFix.java +++ b/plugins/properties/src/com/intellij/lang/properties/references/CreatePropertyFix.java @@ -151,19 +151,15 @@ public class CreatePropertyFix implements IntentionAction, LocalQuickFix { } UndoUtil.markPsiFileForUndo(psiElement.getContainingFile()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - try { - I18nUtil.createProperty(project, selectedPropertiesFiles, key, value); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }, CodeInsightBundle.message("quickfix.i18n.command.name"), project); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> { + try { + I18nUtil.createProperty(project, selectedPropertiesFiles, key, value); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }, CodeInsightBundle.message("quickfix.i18n.command.name"), project); }); } diff --git a/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java b/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java index 2bfe67a15980..4c74fe894a77 100644 --- a/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java +++ b/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java @@ -308,14 +308,11 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick List paths = suggestPropertiesFiles(); final String lastUrl = suggestSelectedFileUrl(paths); final String lastPath = lastUrl == null ? null : FileUtil.toSystemDependentName(VfsUtil.urlToPath(lastUrl)); - Collections.sort(paths, new Comparator() { - @Override - public int compare(final String path1, final String path2) { - if (lastPath != null && lastPath.equals(path1)) return -1; - if (lastPath != null && lastPath.equals(path2)) return 1; - int r = LastSelectedPropertiesFileStore.getUseCount(path2) - LastSelectedPropertiesFileStore.getUseCount(path1); - return r == 0 ? path1.compareTo(path2) : r; - } + Collections.sort(paths, (path1, path2) -> { + if (lastPath != null && lastPath.equals(path1)) return -1; + if (lastPath != null && lastPath.equals(path2)) return 1; + int r = LastSelectedPropertiesFileStore.getUseCount(path2) - LastSelectedPropertiesFileStore.getUseCount(path1); + return r == 0 ? path1.compareTo(path2) : r; }); myPropertiesFile.setHistory(paths); if (lastPath != null) { diff --git a/plugins/properties/src/com/intellij/lang/properties/references/PropertiesCompletionContributor.java b/plugins/properties/src/com/intellij/lang/properties/references/PropertiesCompletionContributor.java index f94d9abb6eff..4889b3a705c3 100644 --- a/plugins/properties/src/com/intellij/lang/properties/references/PropertiesCompletionContributor.java +++ b/plugins/properties/src/com/intellij/lang/properties/references/PropertiesCompletionContributor.java @@ -136,12 +136,9 @@ public class PropertiesCompletionContributor extends CompletionContributor { } public static LookupElement[] getVariants(Set variants) { - List elements = ContainerUtil.mapNotNull(variants, new NullableFunction() { - @Override - public LookupElement fun(Object o) { - if (o instanceof String) return LookupElementBuilder.create((String)o).withIcon(PlatformIcons.PROPERTY_ICON); - return createVariant((IProperty)o); - } + List elements = ContainerUtil.mapNotNull(variants, (NullableFunction)o -> { + if (o instanceof String) return LookupElementBuilder.create((String)o).withIcon(PlatformIcons.PROPERTY_ICON); + return createVariant((IProperty)o); }); return elements.toArray(new LookupElement[elements.size()]); } diff --git a/plugins/properties/testSrc/com/intellij/lang/properties/CustomResourceBundleTest.java b/plugins/properties/testSrc/com/intellij/lang/properties/CustomResourceBundleTest.java index 5e463f3c252d..4e5f04233af3 100644 --- a/plugins/properties/testSrc/com/intellij/lang/properties/CustomResourceBundleTest.java +++ b/plugins/properties/testSrc/com/intellij/lang/properties/CustomResourceBundleTest.java @@ -142,11 +142,8 @@ public class CustomResourceBundleTest extends LightPlatformCodeInsightFixtureTes final PsiDirectory newDir = PsiManager.getInstance(getProject()).findDirectory( myFixture.getTempDirFixture().findOrCreateDir("new-resources-dir")); new MoveFilesOrDirectoriesProcessor(getProject(), new PsiElement[] {file2.getContainingFile()}, newDir, false, false, null, null).run(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - file3.getContainingFile().delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + file3.getContainingFile().delete(); }); @@ -162,11 +159,8 @@ public class CustomResourceBundleTest extends LightPlatformCodeInsightFixtureTes final PsiFile file = myFixture.addFileToProject("Base_Page.properties", ""); final PsiFile file2 = myFixture.addFileToProject("Base_Page_en.properties", ""); final String baseName = - PropertiesUtil.getDefaultBaseName(map(list(file, file2), new Function() { - @Override - public PropertiesFile fun(PsiFile psiFile) { - return PropertiesImplUtil.getPropertiesFile(file); - } + PropertiesUtil.getDefaultBaseName(map(list(file, file2), psiFile -> { + return PropertiesImplUtil.getPropertiesFile(file); })); assertEquals("Base_Page", baseName); } @@ -188,11 +182,8 @@ public class CustomResourceBundleTest extends LightPlatformCodeInsightFixtureTes final PsiFile someFile = myFixture.addFileToProject("to_remove/asd.txt", ""); final PsiDirectory toRemove = someFile.getParent(); assertNotNull(toRemove); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - toRemove.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + toRemove.delete(); }); final ResourceBundleManagerState state = resourceBundleManager.getState(); @@ -202,11 +193,8 @@ public class CustomResourceBundleTest extends LightPlatformCodeInsightFixtureTes final PsiDirectory directory = propertiesFile.getParent().getParent(); assertNotNull(directory); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - directory.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + directory.delete(); }); assertSize(1, state.getCustomResourceBundles()); @@ -214,11 +202,8 @@ public class CustomResourceBundleTest extends LightPlatformCodeInsightFixtureTes final PsiDirectory directory1 = propFile1.getParent().getParent(); assertNotNull(directory1); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - directory1.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + directory1.delete(); }); assertSize(0, state.getCustomResourceBundles()); @@ -243,11 +228,8 @@ public class CustomResourceBundleTest extends LightPlatformCodeInsightFixtureTes final PsiDirectory toMove = myFixture.addFileToProject("asd/temp.txt", "").getParent(); assertNotNull(toMove); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - MoveFilesOrDirectoriesUtil.doMoveDirectory(propFile1.getParent(), toMove); - } + ApplicationManager.getApplication().runWriteAction(() -> { + MoveFilesOrDirectoriesUtil.doMoveDirectory(propFile1.getParent(), toMove); }); final PsiDirectory movedDir = toMove.findSubdirectory("qwe"); diff --git a/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesEnterTest.java b/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesEnterTest.java index c6f1b6a35909..9ed2e3564157 100644 --- a/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesEnterTest.java +++ b/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesEnterTest.java @@ -47,12 +47,9 @@ public class PropertiesEnterTest extends LightPlatformCodeInsightTestCase { public void testBeforeComment() throws Exception { doTest(); } public void testPerformance() throws Exception { configureByFile(BASE_PATH + getTestName(false)+".properties"); - PlatformTestUtil.startPerformanceTest("Property files editing", 1000, new ThrowableRunnable() { - @Override - public void run() throws Throwable { - type("aaaa=bbb"); - PsiDocumentManager.getInstance(ourProject).commitAllDocuments(); - } + PlatformTestUtil.startPerformanceTest("Property files editing", 1000, () -> { + type("aaaa=bbb"); + PsiDocumentManager.getInstance(ourProject).commitAllDocuments(); }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesFileTest.java b/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesFileTest.java index f9bd07023419..306c7da3ac45 100644 --- a/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesFileTest.java +++ b/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesFileTest.java @@ -44,10 +44,8 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase public void testAddPropertyAfterComment() throws Exception { final PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "#xxxxx"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - propertiesFile.addProperty(myPropertyToAdd); - } + ApplicationManager.getApplication().runWriteAction(() -> { + propertiesFile.addProperty(myPropertyToAdd); }); @@ -63,10 +61,8 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase public void testAddPropertyAfterProperty() throws Exception { final PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "xxx=yyy"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - propertiesFile.addProperty(myPropertyToAdd); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + propertiesFile.addProperty(myPropertyToAdd); }); @@ -83,10 +79,8 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase assertPropertyEquals(properties.get(0), "xxx", "yyy"); assertPropertyEquals(properties.get(1), "zzz", "ttt"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - properties.get(1).getPsiElement().delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + properties.get(1).getPsiElement().delete(); }); List propertiesAfter = propertiesFile.getProperties(); @@ -98,10 +92,8 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "xxx=yyy\nxxx2=tyrt\nxxx3=ttt\n\n"); final Property property = (Property)propertiesFile.findPropertyByKey("xxx2"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - public void run() { - property.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + property.delete(); }); @@ -111,10 +103,9 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "xxx=yyy\nxxx2=tyrt\nxxx3=ttt\n\n"); final Property property = (Property)propertiesFile.findPropertyByKey("xxx"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){public void run() { + WriteCommandAction.runWriteCommandAction(null, () -> { property.delete(); - } - }); + }); assertEquals("xxx2=tyrt\nxxx3=ttt\n\n", propertiesFile.getText()); @@ -123,10 +114,9 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase public void testAddToEnd() throws IncorrectOperationException { final PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "a=b\\nccc"); assertEquals(1,propertiesFile.getProperties().size()); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){public void run() { + WriteCommandAction.runWriteCommandAction(null, () -> { propertiesFile.addProperty(myPropertyToAdd); - } - }); + }); assertEquals("a=b\\nccc\nkkk=vvv", propertiesFile.getText()); } @@ -144,29 +134,25 @@ public class PropertiesFileTest extends LightPlatformCodeInsightFixtureTestCase public void testAddPropertyAfter() throws IncorrectOperationException { final PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "a=b\nc=d\ne=f"); final Property c = (Property)propertiesFile.findPropertyByKey("c"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){public void run() { + WriteCommandAction.runWriteCommandAction(null, () -> { propertiesFile.addPropertyAfter(myPropertyToAdd, c); - } - }); + }); assertEquals("a=b\nc=d\nkkk=vvv\ne=f", propertiesFile.getText()); } public void testAddPropertyAfterLast() throws IncorrectOperationException { final PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "a=b\nc=d\ne=f"); final Property p = (Property)propertiesFile.findPropertyByKey("e"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){public void run() { + WriteCommandAction.runWriteCommandAction(null, () -> { propertiesFile.addPropertyAfter(myPropertyToAdd, p); - } - }); + }); assertEquals("a=b\nc=d\ne=f\nkkk=vvv", propertiesFile.getText()); } public void testAddPropertyAfterInBeginning() throws IncorrectOperationException { final PropertiesFile propertiesFile = PropertiesElementFactory.createPropertiesFile(getProject(), "a=b\nc=d\ne=f"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - propertiesFile.addPropertyAfter(myPropertyToAdd, null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + propertiesFile.addPropertyAfter(myPropertyToAdd, null); }); assertEquals("kkk=vvv\na=b\nc=d\ne=f", propertiesFile.getText()); diff --git a/plugins/properties/testSrc/com/intellij/lang/properties/xml/XmlPropertiesTest.java b/plugins/properties/testSrc/com/intellij/lang/properties/xml/XmlPropertiesTest.java index 50950c98ccc3..fc762b739122 100644 --- a/plugins/properties/testSrc/com/intellij/lang/properties/xml/XmlPropertiesTest.java +++ b/plugins/properties/testSrc/com/intellij/lang/properties/xml/XmlPropertiesTest.java @@ -59,10 +59,8 @@ public class XmlPropertiesTest extends LightPlatformCodeInsightFixtureTestCase { final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(psiFile); assertNotNull(propertiesFile); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - public void run() { - propertiesFile.addProperty("kkk", "vvv"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + propertiesFile.addProperty("kkk", "vvv"); }); final IProperty property = propertiesFile.findPropertyByKey("kkk"); @@ -75,20 +73,16 @@ public class XmlPropertiesTest extends LightPlatformCodeInsightFixtureTestCase { final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(psiFile); assertNotNull(propertiesFile); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - public void run() { - propertiesFile.addProperty("kkk", "vvv"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + propertiesFile.addProperty("kkk", "vvv"); }); final IProperty property = propertiesFile.findPropertyByKey("kkk"); assertNotNull(property); assertEquals("vvv", property.getValue()); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - public void run() { - propertiesFile.addProperty("kkk2", "vvv"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + propertiesFile.addProperty("kkk2", "vvv"); }); final IProperty property2 = propertiesFile.findPropertyByKey("kkk2"); @@ -101,13 +95,11 @@ public class XmlPropertiesTest extends LightPlatformCodeInsightFixtureTestCase { final PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(psiFile); assertNotNull(propertiesFile); - WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { - public void run() { - propertiesFile.addProperty("d", "vvv"); - propertiesFile.addProperty("a", "vvv"); - propertiesFile.addProperty("l", "vvv"); - propertiesFile.addProperty("v", "vvv"); - } + WriteCommandAction.runWriteCommandAction(getProject(), () -> { + propertiesFile.addProperty("d", "vvv"); + propertiesFile.addProperty("a", "vvv"); + propertiesFile.addProperty("l", "vvv"); + propertiesFile.addProperty("v", "vvv"); }); assertTrue(propertiesFile.isAlphaSorted()); assertTrue(PropertiesImplUtil.getPropertiesFile(psiFile).isAlphaSorted()); diff --git a/plugins/tasks/tasks-api/src/com/intellij/tasks/BranchInfo.java b/plugins/tasks/tasks-api/src/com/intellij/tasks/BranchInfo.java index 1abcbb802c23..e963a7f901f5 100644 --- a/plugins/tasks/tasks-api/src/com/intellij/tasks/BranchInfo.java +++ b/plugins/tasks/tasks-api/src/com/intellij/tasks/BranchInfo.java @@ -40,15 +40,12 @@ public class BranchInfo { public boolean original; public static List fromTaskInfo(final VcsTaskHandler.TaskInfo taskInfo, final boolean original) { - return ContainerUtil.map(taskInfo.getRepositories(), new Function() { - @Override - public BranchInfo fun(String s) { - BranchInfo info = new BranchInfo(); - info.name = taskInfo.getName(); - info.repository = s; - info.original = original; - return info; - } + return ContainerUtil.map(taskInfo.getRepositories(), s -> { + BranchInfo info = new BranchInfo(); + info.name = taskInfo.getName(); + info.repository = s; + info.original = original; + return info; }); } diff --git a/plugins/tasks/tasks-api/src/com/intellij/tasks/config/BaseRepositoryEditor.java b/plugins/tasks/tasks-api/src/com/intellij/tasks/config/BaseRepositoryEditor.java index 98729c94254e..7a133d6c7850 100644 --- a/plugins/tasks/tasks-api/src/com/intellij/tasks/config/BaseRepositoryEditor.java +++ b/plugins/tasks/tasks-api/src/com/intellij/tasks/config/BaseRepositoryEditor.java @@ -200,11 +200,7 @@ public class BaseRepositoryEditor extends TaskReposito textField.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - doApply(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> doApply()); } }); } diff --git a/plugins/tasks/tasks-api/src/com/intellij/tasks/ui/TaskDialogPanelProvider.java b/plugins/tasks/tasks-api/src/com/intellij/tasks/ui/TaskDialogPanelProvider.java index 453abc81ed12..9eacf4339e15 100644 --- a/plugins/tasks/tasks-api/src/com/intellij/tasks/ui/TaskDialogPanelProvider.java +++ b/plugins/tasks/tasks-api/src/com/intellij/tasks/ui/TaskDialogPanelProvider.java @@ -35,23 +35,17 @@ public abstract class TaskDialogPanelProvider { private final static ExtensionPointName EP_NAME = ExtensionPointName.create("com.intellij.tasks.dialogPanelProvider"); public static List getOpenTaskPanels(@NotNull Project project, @NotNull Task task) { - return ContainerUtil.mapNotNull(Extensions.getExtensions(EP_NAME), new NullableFunction() { - @Nullable - @Override - public TaskDialogPanel fun(TaskDialogPanelProvider provider) { - return provider.getOpenTaskPanel(project, task); - } - }); + return ContainerUtil.mapNotNull(Extensions.getExtensions(EP_NAME), + (NullableFunction)provider -> { + return provider.getOpenTaskPanel(project, task); + }); } public static List getCloseTaskPanels(@NotNull Project project, @NotNull LocalTask task) { - return ContainerUtil.mapNotNull(Extensions.getExtensions(EP_NAME), new NullableFunction() { - @Nullable - @Override - public TaskDialogPanel fun(TaskDialogPanelProvider provider) { - return provider.getCloseTaskPanel(project, task); - } - }); + return ContainerUtil.mapNotNull(Extensions.getExtensions(EP_NAME), + (NullableFunction)provider -> { + return provider.getCloseTaskPanel(project, task); + }); } @Nullable diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardField.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardField.java index 366d56bad1ca..17dbdc3bdab4 100644 --- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardField.java +++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardField.java @@ -104,12 +104,7 @@ public enum JqlStandardField { return type == JqlFieldType.UNKNOWN? ALL_FIELD_NAMES : new ArrayList(TYPE_LOOKUP.get(type)); } - public static final List ALL_FIELD_NAMES = ContainerUtil.map2List(VALUES, new Function() { - @Override - public String fun(JqlStandardField field) { - return field.myName; - } - }); + public static final List ALL_FIELD_NAMES = ContainerUtil.map2List(VALUES, field -> field.myName); public static JqlFieldType typeOf(String name) { for (Map.Entry> entry : TYPE_LOOKUP.entrySet()) { diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardFunction.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardFunction.java index 49d3a3f493fd..6cba099fa53a 100644 --- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardFunction.java +++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/jql/codeinsight/JqlStandardFunction.java @@ -90,10 +90,5 @@ public enum JqlStandardFunction { return new ArrayList(TYPE_LOOKUP.get(Pair.create(type, multipleResults))); } - public static final List ALL_FUNCTION_NAMES = ContainerUtil.map2List(VALUES, new Function() { - @Override - public String fun(JqlStandardFunction field) { - return field.myName; - } - }); + public static final List ALL_FUNCTION_NAMES = ContainerUtil.map2List(VALUES, field -> field.myName); } diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestApi.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestApi.java index 78919e390d5f..57a47a2eca21 100644 --- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestApi.java +++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestApi.java @@ -56,11 +56,8 @@ public abstract class JiraRestApi extends JiraRemoteApi { GetMethod method = getMultipleIssuesSearchMethod(jql, max); String response = myRepository.executeMethod(method); List issues = parseIssues(response); - return ContainerUtil.map(issues, new Function() { - @Override - public JiraRestTask fun(JiraIssue issue) { - return new JiraRestTask(issue, myRepository); - } + return ContainerUtil.map(issues, issue -> { + return new JiraRestTask(issue, myRepository); }); } diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestTask.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestTask.java index 5eab2efece44..6a9a2bece617 100644 --- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestTask.java +++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/rest/JiraRestTask.java @@ -63,29 +63,26 @@ public class JiraRestTask extends JiraTask { @Override @NotNull public Comment[] getComments() { - return ContainerUtil.map2Array(myJiraIssue.getComments(), Comment.class, new Function() { - @Override - public Comment fun(final JiraComment comment) { - return new Comment() { + return ContainerUtil.map2Array(myJiraIssue.getComments(), Comment.class, (Function)comment -> { + return new Comment() { - public String getText() { - return comment.getBody(); - } + public String getText() { + return comment.getBody(); + } - public String getAuthor() { - return comment.getAuthor().getDisplayName(); - } + public String getAuthor() { + return comment.getAuthor().getDisplayName(); + } - public Date getDate() { - return comment.getCreated(); - } + public Date getDate() { + return comment.getCreated(); + } - @Override - public String toString() { - return comment.getAuthor().getDisplayName(); - } - }; - } + @Override + public String toString() { + return comment.getAuthor().getDisplayName(); + } + }; }); } diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraLegacyApi.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraLegacyApi.java index 7f5ab27cc9a1..559938a6fa04 100644 --- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraLegacyApi.java +++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraLegacyApi.java @@ -73,10 +73,8 @@ public class JiraLegacyApi extends JiraRemoteApi { if (channel != null) { List children = channel.getChildren("item"); LOG.debug("Total issues in JIRA RSS feed: " + children.size()); - return ContainerUtil.map(children, new Function() { - public Task fun(Element element) { - return new JiraSoapTask(element, myRepository); - } + return ContainerUtil.map(children, element -> { + return new JiraSoapTask(element, myRepository); }); } else { diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraSoapTask.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraSoapTask.java index 9da515a31af3..db88ef94cd69 100644 --- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraSoapTask.java +++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/soap/JiraSoapTask.java @@ -73,28 +73,25 @@ class JiraSoapTask extends JiraTask { Element comments = element.getChild("comments"); if (comments != null) { - myComments = ContainerUtil.map(comments.getChildren("comment"), new Function() { - @Override - public Comment fun(final Element element) { - return new Comment() { - @Override - public String getText() { - return element.getText(); - } + myComments = ContainerUtil.map(comments.getChildren("comment"), element1 -> { + return new Comment() { + @Override + public String getText() { + return element1.getText(); + } - @Nullable - @Override - public String getAuthor() { - return element.getAttributeValue("author"); - } + @Nullable + @Override + public String getAuthor() { + return element1.getAttributeValue("author"); + } - @Nullable - @Override - public Date getDate() { - return parseDate(element.getAttributeValue("created")); - } - }; - } + @Nullable + @Override + public Date getDate() { + return parseDate(element1.getAttributeValue("created")); + } + }; }); } else { myComments = ContainerUtil.emptyList(); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/DeadlockWithCertificateDialogAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/DeadlockWithCertificateDialogAction.java index 87f2ca7b3107..bf471828b7d8 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/DeadlockWithCertificateDialogAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/DeadlockWithCertificateDialogAction.java @@ -16,22 +16,19 @@ public class DeadlockWithCertificateDialogAction extends AnAction { public static final String SELF_SIGNED_SERVER_URL = "https://self-signed.certificates-tests.labs.intellij.net"; @Override public void actionPerformed(final AnActionEvent e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - URL location = null; - try { - location = new URL(SELF_SIGNED_SERVER_URL); - } - catch (MalformedURLException ignored) { - } - // EDT will not be released for dialog until message dialog is shown. Meanwhile downloading of image by - // ImageFetcher thread, started by MediaTracker, won't stop until certificate is accepted by user. - Messages.showMessageDialog(e.getProject(), - "This dialog may not be shown due to deadlock caused by MediaTracker and CertificateManager. " + - "Fortunately it didn't happen." , - "Deadlocking Dialog", new ImageIcon(location)); + ApplicationManager.getApplication().invokeLater(() -> { + URL location = null; + try { + location = new URL(SELF_SIGNED_SERVER_URL); } + catch (MalformedURLException ignored) { + } + // EDT will not be released for dialog until message dialog is shown. Meanwhile downloading of image by + // ImageFetcher thread, started by MediaTracker, won't stop until certificate is accepted by user. + Messages.showMessageDialog(e.getProject(), + "This dialog may not be shown due to deadlock caused by MediaTracker and CertificateManager. " + + "Fortunately it didn't happen." , + "Deadlocking Dialog", new ImageIcon(location)); }); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java index 4710e7a0a3e3..11995a64b43f 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java @@ -110,12 +110,7 @@ public class GotoTaskAction extends GotoActionBase implements DumbAware { private static void showOpenTaskDialog(final Project project, final Task task) { JBPopup hint = DocumentationManager.getInstance(project).getDocInfoHint(); if (hint != null) hint.cancel(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - new OpenTaskDialog(project, task).show(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> new OpenTaskDialog(project, task).show()); } private static class GotoTaskPopupModel extends SimpleChooseByNameModel implements DumbAware { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SearchSupport.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SearchSupport.java index 8b99213f41f8..da1715fb3764 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SearchSupport.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SearchSupport.java @@ -75,16 +75,11 @@ public abstract class SearchSupport { }); //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myTextField.addKeyListener(new KeyAdapter() { - public void keyPressed(final KeyEvent e) { - processListSelection(e); - } - }); + SwingUtilities.invokeLater(() -> myTextField.addKeyListener(new KeyAdapter() { + public void keyPressed(final KeyEvent e) { + processListSelection(e); } - }); + })); myList.setVisibleRowCount(10); myListModel = new SortedListModel(null); @@ -243,18 +238,10 @@ public abstract class SearchSupport { final int caret = myTextField.getCaretModel().getOffset(); getEditor().getSelectionModel().setSelection(caret, caret); myTextField.setFocusTraversalKeysEnabled(true); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myTextField.requestFocus(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> myTextField.requestFocus()); return Boolean.TRUE; } - }).setItemChoosenCallback(new Runnable() { - public void run() { - processChosenFromCompletion(); - } - }).setCancelKeyEnabled(false).setAlpha(0.1f).setFocusOwners(new Component[]{myTextField}). + }).setItemChoosenCallback(() -> processChosenFromCompletion()).setCancelKeyEnabled(false).setAlpha(0.1f).setFocusOwners(new Component[]{myTextField}). createPopup(); adjustPopupSize(); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/ShowTaskDescription.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/ShowTaskDescription.java index bd8e2f83b94a..6a0790c45d58 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/ShowTaskDescription.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/ShowTaskDescription.java @@ -50,11 +50,8 @@ public class ShowTaskDescription extends BaseTaskAction { assert project != null; final LocalTask task = getActiveTask(e); FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.quickjavadoc.ctrln"); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - DocumentationManager.getInstance(project).showJavaDocInfo(new TaskPsiElement(PsiManager.getInstance(project), task), null); - } - }, getCommandName(), null); + CommandProcessor.getInstance().executeCommand(project, + () -> DocumentationManager.getInstance(project).showJavaDocInfo(new TaskPsiElement(PsiManager.getInstance(project), task), null), getCommandName(), null); } protected String getCommandName() { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java index 537fa3dc6caf..ce7583d9ee47 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java @@ -236,11 +236,9 @@ public class SwitchTaskAction extends BaseTaskAction { else { List infos = task.getChangeLists(); - List lists = ContainerUtil.mapNotNull(infos, new NullableFunction() { - public LocalChangeList fun(ChangeListInfo changeListInfo) { - LocalChangeList changeList = ChangeListManager.getInstance(project).getChangeList(changeListInfo.id); - return changeList != null && !changeList.isDefault() ? changeList : null; - } + List lists = ContainerUtil.mapNotNull(infos, (NullableFunction)changeListInfo -> { + LocalChangeList changeList = ChangeListManager.getInstance(project).getChangeList(changeListInfo.id); + return changeList != null && !changeList.isDefault() ? changeList : null; }); boolean removeIt = true; diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskItemProvider.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskItemProvider.java index 0bd5835cd1a6..8b528c940d85 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskItemProvider.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskItemProvider.java @@ -68,12 +68,7 @@ class TaskItemProvider implements ChooseByNameItemProvider, Disposable { return true; } - FutureTask> future = new FutureTask>(new Callable>() { - @Override - public List call() throws Exception { - return fetchFromServer(pattern, everywhere, cancelled); - } - }); + FutureTask> future = new FutureTask>(() -> fetchFromServer(pattern, everywhere, cancelled)); // Newer request always wins Future> oldFuture = myFutureReference.getAndSet(future); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskSearchSupport.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskSearchSupport.java index ab3f60a045d2..e63bdcd37ecc 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskSearchSupport.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskSearchSupport.java @@ -54,11 +54,8 @@ public class TaskSearchSupport { public static List filterTasks(final String pattern, final List tasks) { final Matcher matcher = getMatcher(pattern); - return ContainerUtil.mapNotNull(tasks, new NullableFunction() { - public Task fun(Task task) { - return matcher.matches(task.getPresentableId()) || matcher.matches(task.getSummary()) ? task : null; - } - }); + return ContainerUtil.mapNotNull(tasks, + (NullableFunction)task -> matcher.matches(task.getPresentableId()) || matcher.matches(task.getSummary()) ? task : null); } public static List getRepositoriesTasks(final TaskManager myManager, diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/LoadContextAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/LoadContextAction.java index 7c661f575022..0d4add5eaf89 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/LoadContextAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/LoadContextAction.java @@ -58,79 +58,71 @@ public class LoadContextAction extends BaseTaskAction { DefaultActionGroup group = new DefaultActionGroup(); final WorkingContextManager manager = WorkingContextManager.getInstance(project); List history = manager.getContextHistory(); - List infos = new ArrayList(ContainerUtil.map2List(history, new Function() { - public ContextHolder fun(final ContextInfo info) { - return new ContextHolder() { - @Override - void load(final boolean clear) { - LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager, clear, info.name); - UndoableCommand.execute(project, undoableAction, "Load context " + info.comment, "Context"); - } + List infos = new ArrayList(ContainerUtil.map2List(history, (Function)info -> { + return new ContextHolder() { + @Override + void load(final boolean clear) { + LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager, clear, info.name); + UndoableCommand.execute(project, undoableAction, "Load context " + info.comment, "Context"); + } - @Override - void remove() { - manager.removeContext(info.name); - } + @Override + void remove() { + manager.removeContext(info.name); + } - @Override - Date getDate() { - return new Date(info.date); - } + @Override + Date getDate() { + return new Date(info.date); + } - @Override - String getComment() { - return info.comment; - } + @Override + String getComment() { + return info.comment; + } - @Override - Icon getIcon() { - return TasksIcons.SavedContext; - } - }; - } + @Override + Icon getIcon() { + return TasksIcons.SavedContext; + } + }; })); final TaskManager taskManager = TaskManager.getManager(project); List tasks = taskManager.getLocalTasks(); - infos.addAll(ContainerUtil.mapNotNull(tasks, new NullableFunction() { - public ContextHolder fun(final LocalTask task) { - if (task.isActive()) { - return null; - } - return new ContextHolder() { - @Override - void load(boolean clear) { - LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager, clear, task); - UndoableCommand.execute(project, undoableAction, "Load context " + TaskUtil.getTrimmedSummary(task), "Context"); - } - - @Override - void remove() { - SwitchTaskAction.removeTask(project, task, taskManager); - } - - @Override - Date getDate() { - return task.getUpdated(); - } - - @Override - String getComment() { - return TaskUtil.getTrimmedSummary(task); - } - - @Override - Icon getIcon() { - return task.getIcon(); - } - }; + infos.addAll(ContainerUtil.mapNotNull(tasks, (NullableFunction)task -> { + if (task.isActive()) { + return null; } + return new ContextHolder() { + @Override + void load(boolean clear) { + LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager, clear, task); + UndoableCommand.execute(project, undoableAction, "Load context " + TaskUtil.getTrimmedSummary(task), "Context"); + } + + @Override + void remove() { + SwitchTaskAction.removeTask(project, task, taskManager); + } + + @Override + Date getDate() { + return task.getUpdated(); + } + + @Override + String getComment() { + return TaskUtil.getTrimmedSummary(task); + } + + @Override + Icon getIcon() { + return task.getIcon(); + } + }; })); - Collections.sort(infos, new Comparator() { - public int compare(ContextHolder o1, ContextHolder o2) { - return o2.getDate().compareTo(o1.getDate()); - } - }); + Collections.sort(infos, (o1, o2) -> o2.getDate().compareTo(o1.getDate())); final Ref shiftPressed = Ref.create(false); boolean today = true; diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/UndoableCommand.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/UndoableCommand.java index 4498d79bd795..8157126b862e 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/UndoableCommand.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/context/UndoableCommand.java @@ -28,18 +28,16 @@ import com.intellij.openapi.project.Project; public class UndoableCommand { public static void execute(final Project project, final UndoableAction action, String name, String groupId) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - - try { - action.redo(); - } - catch (UnexpectedUndoException e) { - throw new RuntimeException(e); - } - UndoManager.getInstance(project).undoableActionPerformed(action); + CommandProcessor.getInstance().executeCommand(project, () -> { + try { + action.redo(); } + catch (UnexpectedUndoException e) { + throw new RuntimeException(e); + } + UndoManager.getInstance(project).undoableActionPerformed(action); + }, name, groupId); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/vcs/VcsOpenTaskPanel.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/vcs/VcsOpenTaskPanel.java index 0d42adc35c71..e9ea3dfe1a74 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/vcs/VcsOpenTaskPanel.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/vcs/VcsOpenTaskPanel.java @@ -160,12 +160,7 @@ public class VcsOpenTaskPanel extends TaskDialogPanel { } if (myCreateBranch.isSelected()) { VcsTaskHandler.TaskInfo branchFrom = (VcsTaskHandler.TaskInfo)myBranchFrom.getSelectedItem(); - Runnable createBranch = new Runnable() { - @Override - public void run() { - myTaskManager.createBranch(localTask, myPreviousTask, myBranchName.getText(), branchFrom); - } - }; + Runnable createBranch = () -> myTaskManager.createBranch(localTask, myPreviousTask, myBranchName.getText(), branchFrom); if (branchFrom != null) { myVcsTaskHandler.switchToTask(branchFrom, createBranch); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepository.java index 10dee6228773..b77757a8e1a7 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepository.java @@ -84,11 +84,8 @@ public class BugzillaRepository extends BaseRepositoryImpl { Hashtable response = createIssueSearchRequest(query, offset, limit, withClosed).execute(); Vector> bugs = (Vector>)response.get("bugs"); - return ContainerUtil.map2Array(bugs, BugzillaTask.class, new Function, BugzillaTask>() { - @Override - public BugzillaTask fun(Hashtable hashTable) { - return new BugzillaTask(hashTable, BugzillaRepository.this); - } + return ContainerUtil.map2Array(bugs, BugzillaTask.class, hashTable -> { + return new BugzillaTask(hashTable, BugzillaRepository.this); }); } @@ -246,11 +243,8 @@ public class BugzillaRepository extends BaseRepositoryImpl { @NotNull private static List extractNotEmptyNames(@NotNull Vector> vector) { - return ContainerUtil.mapNotNull(vector, new Function, String>() { - @Override - public String fun(Hashtable table) { - return StringUtil.nullize((String)table.get("name")); - } + return ContainerUtil.mapNotNull(vector, table -> { + return StringUtil.nullize((String)table.get("name")); }); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepositoryEditor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepositoryEditor.java index 2ae56e9bbac3..2c09fa529652 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepositoryEditor.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/bugzilla/BugzillaRepositoryEditor.java @@ -40,12 +40,7 @@ public class BugzillaRepositoryEditor extends BaseRepositoryEditor installProductAndComponentCompletion()); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/config/TaskRepositoriesConfigurable.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/config/TaskRepositoriesConfigurable.java index 54978e3ba32a..36b1c6900c4f 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/config/TaskRepositoriesConfigurable.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/config/TaskRepositoriesConfigurable.java @@ -172,11 +172,7 @@ public class TaskRepositoriesConfigurable extends BaseConfigurable implements Co } }); - myChangeListener = new Consumer() { - public void consume(TaskRepository repository) { - ((CollectionListModel)myRepositoriesList.getModel()).contentsChanged(repository); - } - }; + myChangeListener = repository -> ((CollectionListModel)myRepositoriesList.getModel()).contentsChanged(repository); } private void addRepository(TaskRepository repository) { @@ -223,10 +219,8 @@ public class TaskRepositoriesConfigurable extends BaseConfigurable implements Co } public void apply() throws ConfigurationException { - List newRepositories = ContainerUtil.map(myRepositories, new Function() { - public TaskRepository fun(TaskRepository taskRepository) { - return taskRepository.clone(); - } + List newRepositories = ContainerUtil.map(myRepositories, taskRepository -> { + return taskRepository.clone(); }); myManager.setRepositories(newRepositories); myManager.updateIssues(null); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java index 66054c8f0429..03697fa4cced 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/context/WorkingContextManager.java @@ -62,11 +62,7 @@ public class WorkingContextManager { @NonNls private static final String TASKS_ZIP_POSTFIX = ".tasks.zip"; @NonNls private static final String TASK_XML_POSTFIX = ".task.xml"; private static final String CONTEXT_ZIP_POSTFIX = ".contexts.zip"; - private static final Comparator ENTRY_COMPARATOR = new Comparator() { - public int compare(JBZipEntry o1, JBZipEntry o2) { - return Long.signum(o2.getTime() - o1.getTime()); - } - }; + private static final Comparator ENTRY_COMPARATOR = (o1, o2) -> Long.signum(o2.getTime() - o1.getTime()); public static WorkingContextManager getInstance(Project project) { return ServiceManager.getService(project, WorkingContextManager.class); @@ -222,11 +218,7 @@ public class WorkingContextManager { try { archive = getTasksArchive(zipPostfix); List entries = archive.getEntries(); - return ContainerUtil.mapNotNull(entries, new NullableFunction() { - public ContextInfo fun(JBZipEntry entry) { - return entry.getName().startsWith("/context") ? new ContextInfo(entry.getName(), entry.getTime(), entry.getComment()) : null; - } - }); + return ContainerUtil.mapNotNull(entries, (NullableFunction)entry -> entry.getName().startsWith("/context") ? new ContextInfo(entry.getName(), entry.getTime(), entry.getComment()) : null); } catch (IOException e) { LOG.error(e); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/context/XDebuggerBreakpointsContextProvider.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/context/XDebuggerBreakpointsContextProvider.java index 5dabf0b91e3b..cfc96486bb60 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/context/XDebuggerBreakpointsContextProvider.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/context/XDebuggerBreakpointsContextProvider.java @@ -74,10 +74,8 @@ public class XDebuggerBreakpointsContextProvider extends WorkingContextProvider public void clearContext() { XBreakpointBase[] breakpoints = myBreakpointManager.getAllBreakpoints(); for (final XBreakpointBase breakpoint : breakpoints) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myBreakpointManager.removeBreakpoint(breakpoint); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myBreakpointManager.removeBreakpoint(breakpoint); }); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/fogbugz/FogBugzRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/fogbugz/FogBugzRepository.java index 0d71999728f8..429ce4eff448 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/fogbugz/FogBugzRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/fogbugz/FogBugzRepository.java @@ -92,12 +92,8 @@ public class FogBugzRepository extends BaseRepositoryImpl { } final XPath commentPath = XPath.newInstance("events/event"); final List nodes = (List)XPath.newInstance("/response/cases/case").selectNodes(document); - final List tasks = ContainerUtil.mapNotNull(nodes, new NotNullFunction() { - @NotNull - @Override - public Task fun(Element element) { - return createCase(element, commentPath); - } + final List tasks = ContainerUtil.mapNotNull(nodes, (NotNullFunction)element -> { + return createCase(element, commentPath); }); return tasks.toArray(new Task[tasks.size()]); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepositoryUtil.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepositoryUtil.java index 110e28101914..28ce5db26202 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepositoryUtil.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/GenericRepositoryUtil.java @@ -43,15 +43,12 @@ public class GenericRepositoryUtil { } PostMethod postMethod = new PostMethod(requestUrl.substring(0, n)); String[] queryParams = requestUrl.substring(n + 1).split("&"); - postMethod.addParameters(ContainerUtil.map2Array(queryParams, NameValuePair.class, new Function() { - @Override - public NameValuePair fun(String s) { - String[] nv = s.split("="); - if (nv.length == 1) { - return new NameValuePair(nv[0], ""); - } - return new NameValuePair(nv[0], nv[1]); + postMethod.addParameters(ContainerUtil.map2Array(queryParams, NameValuePair.class, s -> { + String[] nv = s.split("="); + if (nv.length == 1) { + return new NameValuePair(nv[0], ""); } + return new NameValuePair(nv[0], nv[1]); })); return postMethod; } @@ -89,11 +86,8 @@ public class GenericRepositoryUtil { } public static List createPlaceholdersList(List variables) { - return ContainerUtil.map2List(variables, new Function() { - @Override - public String fun(TemplateVariable variable) { - return String.format("{%s}", variable.getName()); - } + return ContainerUtil.map2List(variables, variable -> { + return String.format("{%s}", variable.getName()); }); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/JsonPathResponseHandler.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/JsonPathResponseHandler.java index c79cb81899f7..6ce726aeb728 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/JsonPathResponseHandler.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/generic/JsonPathResponseHandler.java @@ -85,11 +85,8 @@ public final class JsonPathResponseHandler extends SelectorBasedResponseHandler if (list == null) { return ContainerUtil.emptyList(); } - return ContainerUtil.map2List(list, new Function() { - @Override - public Object fun(Object o) { - return o.toString(); - } + return ContainerUtil.map2List(list, (Function)o -> { + return o.toString(); }).subList(0, Math.min(list.size(), max)); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java index 8b850c2f76a6..da3093e12a28 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java @@ -105,11 +105,8 @@ public class GitlabRepository extends NewBaseRepositoryImpl { @Override public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception { final List issues = fetchIssues((offset / limit) + 1, limit, !withClosed); - return ContainerUtil.map2Array(issues, GitlabTask.class, new Function() { - @Override - public GitlabTask fun(GitlabIssue issue) { - return new GitlabTask(GitlabRepository.this, issue); - } + return ContainerUtil.map2Array(issues, GitlabTask.class, issue -> { + return new GitlabTask(GitlabRepository.this, issue); }); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepositoryEditor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepositoryEditor.java index b87c5430d0d0..5cea7774d088 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepositoryEditor.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepositoryEditor.java @@ -39,12 +39,7 @@ public class GitlabRepositoryEditor extends BaseRepositoryEditor initialize()); } private void initialize() { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskChangelistSupport.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskChangelistSupport.java index 7b857e5bb085..c8b713a553e5 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskChangelistSupport.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskChangelistSupport.java @@ -58,28 +58,26 @@ public class TaskChangelistSupport implements EditChangelistSupport { myTaskManager.getState().trackContextForNewChangelist : myTaskManager.getAssociatedTask(initial) != null); bottomPanel.add(checkBox); - return new Consumer() { - public void consume(LocalChangeList changeList) { - if (initial == null) { - myTaskManager.getState().trackContextForNewChangelist = checkBox.isSelected(); - if (checkBox.isSelected()) { + return changeList -> { + if (initial == null) { + myTaskManager.getState().trackContextForNewChangelist = checkBox.isSelected(); + if (checkBox.isSelected()) { + myTaskManager.trackContext(changeList); + } + else { + myTaskManager.getActiveTask().addChangelist(new ChangeListInfo(changeList)); + } + } + else { + final LocalTask associatedTask = myTaskManager.getAssociatedTask(changeList); + if (checkBox.isSelected()) { + if (associatedTask == null) { myTaskManager.trackContext(changeList); } - else { - myTaskManager.getActiveTask().addChangelist(new ChangeListInfo(changeList)); - } } else { - final LocalTask associatedTask = myTaskManager.getAssociatedTask(changeList); - if (checkBox.isSelected()) { - if (associatedTask == null) { - myTaskManager.trackContext(changeList); - } - } - else { - if (associatedTask != null) { - myTaskManager.removeTask(associatedTask); - } + if (associatedTask != null) { + myTaskManager.removeTask(associatedTask); } } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java index 8119d5871fd0..13e7ed5c39b5 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java @@ -87,11 +87,9 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.impl.TaskManagerImpl"); private static final DecimalFormat LOCAL_TASK_ID_FORMAT = new DecimalFormat("LOCAL-00000"); - public static final Comparator TASK_UPDATE_COMPARATOR = new Comparator() { - public int compare(@NotNull Task o1, @NotNull Task o2) { - int i = Comparing.compare(o2.getUpdated(), o1.getUpdated()); - return i == 0 ? Comparing.compare(o2.getCreated(), o1.getCreated()) : i; - } + public static final Comparator TASK_UPDATE_COMPARATOR = (o1, o2) -> { + int i = Comparing.compare(o2.getUpdated(), o1.getUpdated()); + return i == 0 ? Comparing.compare(o2.getCreated(), o1.getCreated()) : i; }; private static final Convertor KEY_CONVERTOR = new Convertor() { @Override @@ -113,12 +111,7 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe LocalTask result = super.put(key, task); if (size() > myConfig.taskHistoryLength) { ArrayList> list = new ArrayList>(entrySet()); - Collections.sort(list, new Comparator>() { - @Override - public int compare(@NotNull Map.Entry o1, @NotNull Map.Entry o2) { - return TASK_UPDATE_COMPARATOR.compare(o2.getValue(), o1.getValue()); - } - }); + Collections.sort(list, (o1, o2) -> TASK_UPDATE_COMPARATOR.compare(o2.getValue(), o1.getValue())); for (Map.Entry oldest : list) { if (!oldest.getValue().isDefault()) { remove(oldest.getKey()); @@ -166,10 +159,8 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe public void defaultListChanged(ChangeList oldDefaultList, ChangeList newDefaultList) { final LocalTask associatedTask = getAssociatedTask((LocalChangeList)newDefaultList); if (associatedTask != null && !getActiveTask().equals(associatedTask)) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - activateTask(associatedTask, true); - } + ApplicationManager.getApplication().invokeLater(() -> { + activateTask(associatedTask, true); }, myProject.getDisposed()); } } @@ -502,16 +493,13 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe task.setActive(true); addTask(task); if (task.isIssue()) { - StartupManager.getInstance(myProject).runWhenProjectIsInitialized(new Runnable() { - public void run() { - ProgressManager.getInstance().run(new com.intellij.openapi.progress.Task.Backgroundable(myProject, "Updating " + task.getPresentableId()) { + StartupManager.getInstance(myProject).runWhenProjectIsInitialized( + () -> ProgressManager.getInstance().run(new com.intellij.openapi.progress.Task.Backgroundable(myProject, "Updating " + task.getPresentableId()) { - public void run(@NotNull ProgressIndicator indicator) { - updateIssue(task.getId()); - } - }); - } - }); + public void run(@NotNull ProgressIndicator indicator) { + updateIssue(task.getId()); + } + })); } LocalTask oldActiveTask = myActiveTask; boolean isChanged = !task.equals(oldActiveTask); @@ -717,11 +705,7 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe } }); myCacheRefreshTimer.setInitialDelay(0); - StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() { - public void run() { - myCacheRefreshTimer.start(); - } - }); + StartupManager.getInstance(myProject).registerPostStartupActivity(() -> myCacheRefreshTimer.start()); } // make sure that the default task is exist @@ -787,11 +771,7 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe doUpdate(onComplete); } else { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - doUpdate(onComplete); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> doUpdate(onComplete)); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskStateCombo.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskStateCombo.java index 379ab3561f8d..e484ba87251c 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskStateCombo.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskStateCombo.java @@ -140,22 +140,14 @@ public abstract class TaskStateCombo extends JPanel { @NotNull static List wrapList(@NotNull Collection states) { - return ContainerUtil.map(states, new Function() { - @Override - public CustomStateTrinityAdapter fun(CustomTaskState state) { - return new CustomStateTrinityAdapter(state); - } + return ContainerUtil.map(states, state -> { + return new CustomStateTrinityAdapter(state); }); } @NotNull static List unwrapList(@NotNull Collection wrapped) { - return ContainerUtil.map(wrapped, new Function() { - @Override - public CustomTaskState fun(CustomStateTrinityAdapter adapter) { - return adapter.myState; - } - }); + return ContainerUtil.map(wrapped, adapter -> adapter.myState); } } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskUiUtil.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskUiUtil.java index 0f8e571a9e87..5f863dea6250 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskUiUtil.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskUiUtil.java @@ -65,11 +65,8 @@ public class TaskUiUtil { @Nullable @Override public final NotificationInfo notifyFinished() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - updateUI(); - } + ApplicationManager.getApplication().invokeLater(() -> { + updateUI(); }, myModalityState); return null; } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/lighthouse/LighthouseRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/lighthouse/LighthouseRepository.java index bb60b57b429c..f41c089a0b4a 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/lighthouse/LighthouseRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/lighthouse/LighthouseRepository.java @@ -100,10 +100,8 @@ public class LighthouseRepository extends BaseRepositoryImpl { List children = element.getChildren("ticket"); - List taskList = ContainerUtil.mapNotNull(children, new NullableFunction() { - public Task fun(Element o) { - return createIssue(o); - } + List taskList = ContainerUtil.mapNotNull(children, (NullableFunction)o -> { + return createIssue(o); }); tasks.addAll(taskList); page++; diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepository.java index 4404bc5e2385..7372d1091f16 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepository.java @@ -124,13 +124,11 @@ public class MantisRepository extends BaseRepositoryImpl { IssueHeaderData[] headers = fetchProjectIssues(soap, project, myCurrentFilter, pageNumber, pageSize); ContainerUtil.addAll(collectedHeaders, headers); } - return ContainerUtil.mapNotNull(collectedHeaders, new NullableFunction() { - public Task fun(IssueHeaderData issueData) { - if (issueData.getId() == null || issueData.getSummary() == null) { - return null; - } - return new MantisTask(issueData, MantisRepository.this); + return ContainerUtil.mapNotNull(collectedHeaders, (NullableFunction)issueData -> { + if (issueData.getId() == null || issueData.getSummary() == null) { + return null; } + return new MantisTask(issueData, MantisRepository.this); }); } @@ -183,11 +181,8 @@ public class MantisRepository extends BaseRepositoryImpl { myAllProjectsAvailable = checkAllProjectsAvailable(soap); List projects = - new ArrayList(ContainerUtil.map(fetchUserProjects(soap), new Function() { - @Override - public MantisProject fun(final ProjectData data) { - return new MantisProject(data); - } + new ArrayList(ContainerUtil.map(fetchUserProjects(soap), data -> { + return new MantisProject(data); })); List commonFilters = new LinkedList(); for (MantisProject project : projects) { @@ -205,12 +200,7 @@ public class MantisRepository extends BaseRepositoryImpl { project.setFilters(projectFilters); } - Collections.sort(commonFilters, new Comparator() { - @Override - public int compare(MantisFilter f1, MantisFilter f2) { - return f1.getName().compareTo(f2.getName()); - } - }); + Collections.sort(commonFilters, (f1, f2) -> f1.getName().compareTo(f2.getName())); commonFilters.add(0, MantisFilter.newUndefined()); MantisProject undefined = MantisProject.newUndefined(); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java index c34006e949a6..b5e58287f9db 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java @@ -81,12 +81,7 @@ public class MantisRepositoryEditor extends BaseRepositoryEditor new FetchMantisProjects().queue()); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisTask.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisTask.java index da775aab3fa8..517a4248d454 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisTask.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisTask.java @@ -41,28 +41,25 @@ public class MantisTask extends Task { myComments = Comment.EMPTY_ARRAY; } else { - myComments = ContainerUtil.map2Array(data.getNotes(), Comment.class, new Function() { - @Override - public Comment fun(final IssueNoteData data) { - return new Comment() { - @Override - public String getText() { - return data.getText(); - } + myComments = ContainerUtil.map2Array(data.getNotes(), Comment.class, (Function)data1 -> { + return new Comment() { + @Override + public String getText() { + return data1.getText(); + } - @Nullable - @Override - public String getAuthor() { - return data.getReporter().getName(); - } + @Nullable + @Override + public String getAuthor() { + return data1.getReporter().getName(); + } - @Nullable - @Override - public Date getDate() { - return data.getDate_submitted().getTime(); - } - }; - } + @Nullable + @Override + public Date getDate() { + return data1.getDate_submitted().getTime(); + } + }; }); } } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/pivotal/PivotalTrackerRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/pivotal/PivotalTrackerRepository.java index f327e0ad968a..2e14aa65c4b5 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/pivotal/PivotalTrackerRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/pivotal/PivotalTrackerRepository.java @@ -87,10 +87,8 @@ public class PivotalTrackerRepository extends BaseRepositoryImpl { public Task[] getIssues(@Nullable final String query, final int max, final long since) throws Exception { List children = getStories(query, max); - final List tasks = ContainerUtil.mapNotNull(children, new NullableFunction() { - public Task fun(Element o) { - return createIssue(o); - } + final List tasks = ContainerUtil.mapNotNull(children, (NullableFunction)o -> { + return createIssue(o); }); return tasks.toArray(new Task[tasks.size()]); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java index 0a4d5273f37d..0e566674985c 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java @@ -150,11 +150,8 @@ public class RedmineRepository extends NewBaseRepositoryImpl { @Override public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception { List issues = fetchIssues(query, offset, limit, withClosed); - List result = ContainerUtil.map(issues, new Function() { - @Override - public RedmineTask fun(RedmineIssue issue) { - return new RedmineTask(RedmineRepository.this, issue); - } + List result = ContainerUtil.map(issues, issue -> { + return new RedmineTask(RedmineRepository.this, issue); }); if (query != null && ID_PATTERN.matcher(query).matches()) { LOG.debug("Query '" + query + "' looks like an issue ID. Requesting it explicitly from the server " + this); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepositoryEditor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepositoryEditor.java index c95d0f98a32e..72b6e14289d6 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepositoryEditor.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepositoryEditor.java @@ -45,12 +45,7 @@ public class RedmineRepositoryEditor extends BaseRepositoryEditor initialize()); } @Override diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepository.java index 38d859fee8c9..067e44570b67 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepository.java @@ -137,11 +137,8 @@ public final class TrelloRepository extends NewBaseRepositoryImpl { @Override public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception { final List cards = fetchCards(offset + limit, withClosed); - return ContainerUtil.map2Array(cards, Task.class, new Function() { - @Override - public Task fun(TrelloCard card) { - return new TrelloTask(card, TrelloRepository.this); - } + return ContainerUtil.map2Array(cards, Task.class, (Function)card -> { + return new TrelloTask(card, TrelloRepository.this); }); } @@ -325,11 +322,8 @@ public final class TrelloRepository extends NewBaseRepositoryImpl { .addParameter("fields", "none"); final List visibleCards = makeRequestAndDeserializeJsonResponse(visibleCardsUrl.build(), TrelloUtil.LIST_OF_CARDS_TYPE); LOG.debug("Total " + visibleCards.size() + " visible cards"); - final Set visibleCardsIDs = ContainerUtil.map2Set(visibleCards, new Function() { - @Override - public String fun(TrelloCard card) { - return card.getId(); - } + final Set visibleCardsIDs = ContainerUtil.map2Set(visibleCards, card -> { + return card.getId(); }); for (TrelloCard card : cards) { card.setVisible(visibleCardsIDs.contains(card.getId())); diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepositoryEditor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepositoryEditor.java index f7dcd54d3baa..1f5a5b31a15f 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepositoryEditor.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/trello/TrelloRepositoryEditor.java @@ -148,11 +148,7 @@ public class TrelloRepositoryEditor extends BaseRepositoryEditor initialize()); } private void initialize() { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackIntellisense.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackIntellisense.java index fce2326e3be7..90000aada769 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackIntellisense.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackIntellisense.java @@ -139,20 +139,14 @@ public class YouTrackIntellisense { TaskUtil.prettyFormatXmlToLog(LOG, root); @NotNull final Element highlight = root.getChild("highlight"); //assert highlight != null : "no '/IntelliSense/highlight' element in YouTrack response"; - myHighlightRanges = ContainerUtil.map(highlight.getChildren("range"), new Function() { - @Override - public HighlightRange fun(Element range) { - return new HighlightRange(range); - } + myHighlightRanges = ContainerUtil.map(highlight.getChildren("range"), range -> { + return new HighlightRange(range); }); @NotNull final Element suggest = root.getChild("suggest"); //assert suggest != null : "no '/IntelliSense/suggest' element in YouTrack response"; - myCompletionItems = ContainerUtil.map(suggest.getChildren("item"), new Function() { - @Override - public CompletionItem fun(Element item) { - return new CompletionItem(item); - } + myCompletionItems = ContainerUtil.map(suggest.getChildren("item"), item -> { + return new CompletionItem(item); }); } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java index de31128eb2a4..709dd05511af 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/YouTrackRepository.java @@ -117,10 +117,8 @@ public class YouTrackRepository extends BaseRepositoryImpl { List children = element.getChildren("issue"); - final List tasks = ContainerUtil.mapNotNull(children, new NullableFunction() { - public Task fun(Element o) { - return createIssue(o); - } + final List tasks = ContainerUtil.mapNotNull(children, (NullableFunction)o -> { + return createIssue(o); }); return tasks.toArray(new Task[tasks.size()]); } @@ -222,12 +220,9 @@ public class YouTrackRepository extends BaseRepositoryImpl { try { final InputStream stream = method.getResponseBodyAsStream(); final Element element = new SAXBuilder(false).build(stream).getRootElement(); - return ContainerUtil.map2Set(element.getChild("suggest").getChildren("item"), new Function() { - @Override - public CustomTaskState fun(Element element) { - final String stateName = element.getChildText("option"); - return new CustomTaskState(stateName, stateName); - } + return ContainerUtil.map2Set(element.getChild("suggest").getChildren("item"), element1 -> { + final String stateName = element1.getChildText("option"); + return new CustomTaskState(stateName, stateName); }); } finally { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/lang/codeinsight/YouTrackCompletionContributor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/lang/codeinsight/YouTrackCompletionContributor.java index 81326b9a1fe3..b7a811f7cde1 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/lang/codeinsight/YouTrackCompletionContributor.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/youtrack/lang/codeinsight/YouTrackCompletionContributor.java @@ -48,24 +48,17 @@ public class YouTrackCompletionContributor extends CompletionContributor { } final Application application = ApplicationManager.getApplication(); - Future> future = application.executeOnPooledThread(new Callable>() { - @Override - public List call() throws Exception { - return intellisense.fetchCompletion(parameters.getOriginalFile().getText(), parameters.getOffset()); - } - }); + Future> future = application.executeOnPooledThread( + () -> intellisense.fetchCompletion(parameters.getOriginalFile().getText(), parameters.getOffset())); try { final List suggestions = future.get(TIMEOUT, TimeUnit.MILLISECONDS); // actually backed by original CompletionResultSet result = result.withPrefixMatcher(extractPrefix(parameters)).caseInsensitive(); - result.addAllElements(ContainerUtil.map(suggestions, new Function() { - @Override - public LookupElement fun(CompletionItem item) { - return LookupElementBuilder.create(item, item.getOption()) - .withTypeText(item.getDescription(), true) - .withInsertHandler(INSERT_HANDLER) - .withBoldness(item.getStyleClass().equals("keyword")); - } + result.addAllElements(ContainerUtil.map(suggestions, (Function)item -> { + return LookupElementBuilder.create(item, item.getOption()) + .withTypeText(item.getDescription(), true) + .withInsertHandler(INSERT_HANDLER) + .withBoldness(item.getStyleClass().equals("keyword")); })); } catch (Exception ignored) { diff --git a/plugins/tasks/tasks-java/src/com/intellij/tasks/context/java/BreakpointsContextProvider.java b/plugins/tasks/tasks-java/src/com/intellij/tasks/context/java/BreakpointsContextProvider.java index 057aa1b748a6..d0e0dcd2130b 100644 --- a/plugins/tasks/tasks-java/src/com/intellij/tasks/context/java/BreakpointsContextProvider.java +++ b/plugins/tasks/tasks-java/src/com/intellij/tasks/context/java/BreakpointsContextProvider.java @@ -66,10 +66,8 @@ public class BreakpointsContextProvider extends WorkingContextProvider { final BreakpointManager breakpointManager = ((DebuggerManagerEx)myDebuggerManager).getBreakpointManager(); List breakpoints = breakpointManager.getBreakpoints(); for (final Breakpoint breakpoint : breakpoints) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - breakpointManager.removeBreakpoint(breakpoint); - } + ApplicationManager.getApplication().runWriteAction(() -> { + breakpointManager.removeBreakpoint(breakpoint); }); } } diff --git a/plugins/tasks/tasks-tests/test/com/intellij/tasks/TestRepositoryType.java b/plugins/tasks/tasks-tests/test/com/intellij/tasks/TestRepositoryType.java index 93d9c5b25bc1..eff08e5b2b3e 100644 --- a/plugins/tasks/tasks-tests/test/com/intellij/tasks/TestRepositoryType.java +++ b/plugins/tasks/tasks-tests/test/com/intellij/tasks/TestRepositoryType.java @@ -44,11 +44,8 @@ public class TestRepositoryType extends TaskRepositoryType { @NotNull @Override public TaskRepositoryEditor createEditor(TestRepository repository, Project project, Consumer changeListener) { - return new BaseRepositoryEditor(project, repository, new Consumer() { - @Override - public void consume(TestRepository repository) { + return new BaseRepositoryEditor(project, repository, repository1 -> { - } }); } diff --git a/plugins/tasks/tasks-tests/test/com/intellij/tasks/context/ContextTest.java b/plugins/tasks/tasks-tests/test/com/intellij/tasks/context/ContextTest.java index db609abb2b85..474c66218bf3 100644 --- a/plugins/tasks/tasks-tests/test/com/intellij/tasks/context/ContextTest.java +++ b/plugins/tasks/tasks-tests/test/com/intellij/tasks/context/ContextTest.java @@ -82,15 +82,13 @@ public class ContextTest extends TaskManagerTestCase { final XsltBreakpointType type = XBreakpointType.EXTENSION_POINT_NAME.findExtension(XsltBreakpointType.class); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - XLineBreakpointImpl breakpoint = - (XLineBreakpointImpl)breakpointManager.addLineBreakpoint(type, "foo", 0, null); + ApplicationManager.getApplication().runWriteAction(() -> { + XLineBreakpointImpl breakpoint = + (XLineBreakpointImpl)breakpointManager.addLineBreakpoint(type, "foo", 0, null); - final String name = "foo"; - manager.saveContext(name, null); - breakpointManager.removeBreakpoint(breakpoint); - } + final String name = "foo"; + manager.saveContext(name, null); + breakpointManager.removeBreakpoint(breakpoint); }); manager.loadContext("foo"); Collection> breakpoints = breakpointManager.getBreakpoints(type); diff --git a/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/BugzillaIntegrationTest.java b/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/BugzillaIntegrationTest.java index 7053adc77dbc..94e927e631c0 100644 --- a/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/BugzillaIntegrationTest.java +++ b/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/BugzillaIntegrationTest.java @@ -32,11 +32,8 @@ public class BugzillaIntegrationTest extends TaskManagerTestCase { assertEquals(TaskState.OPEN, task.getState()); Set states = myRepository.getAvailableTaskStates(task); - List stateNames = ContainerUtil.map(states, new Function() { - @Override - public String fun(CustomTaskState state) { - return state.getPresentableName(); - } + List stateNames = ContainerUtil.map(states, state -> { + return state.getPresentableName(); }); assertContainsElements(stateNames, "IN_PROGRESS"); assertDoesntContain(stateNames, "CONFIRMED"); @@ -45,11 +42,8 @@ public class BugzillaIntegrationTest extends TaskManagerTestCase { setStateAndCheckResult(task, IN_PROGRESS_STATE, TaskState.IN_PROGRESS); states = myRepository.getAvailableTaskStates(task); - stateNames = ContainerUtil.map(states, new Function() { - @Override - public String fun(CustomTaskState state) { - return state.getPresentableName(); - } + stateNames = ContainerUtil.map(states, state -> { + return state.getPresentableName(); }); assertContainsElements(stateNames, "CONFIRMED"); assertDoesntContain(stateNames, "IN_PROGRESS"); diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java index 8bf81bccfc56..37013d695ffb 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java @@ -52,13 +52,7 @@ public abstract class AbstractTerminalRunner { catch (final Exception e) { LOG.warn("Error running terminal", e); - UIUtil.invokeLaterIfNeeded(new Runnable() { - - @Override - public void run() { - Messages.showErrorDialog(AbstractTerminalRunner.this.getProject(), e.getMessage(), getTitle()); - } - }); + UIUtil.invokeLaterIfNeeded(() -> Messages.showErrorDialog(AbstractTerminalRunner.this.getProject(), e.getMessage(), getTitle())); } } }); @@ -69,12 +63,7 @@ public abstract class AbstractTerminalRunner { try { final T process = createProcess(null); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - initConsoleUI(process); - } - }); + UIUtil.invokeLaterIfNeeded(() -> initConsoleUI(process)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); @@ -164,11 +153,7 @@ public abstract class AbstractTerminalRunner { // Request focus final ToolWindow window = ToolWindowManager.getInstance(myProject).getToolWindow(defaultExecutor.getId()); - window.activate(new Runnable() { - public void run() { - IdeFocusManager.getInstance(myProject).requestFocus(toFocus, true); - } - }); + window.activate(() -> IdeFocusManager.getInstance(myProject).requestFocus(toFocus, true)); } @NotNull diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java index 4430119b5c3e..d7cb0abad2fa 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java @@ -175,12 +175,7 @@ public class LocalTerminalDirectRunner extends AbstractTerminalRunner() { - @Override - public void consume(Integer integer) { - notifyProcessTerminated(integer); - } - }); + myWaitFor.setTerminationCallback(integer -> notifyProcessTerminated(integer)); } finally { removeProcessListener(this); diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java index e6716825cf9c..473471fae3ff 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java @@ -110,12 +110,9 @@ public class TerminalView { myTerminalWidget.addTabListener(new TabbedTerminalWidget.TabListener() { @Override public void tabClosed(JediTermWidget terminal) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myTerminalWidget != null) { - hideIfNoActiveSessions(toolWindow, myTerminalWidget); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myTerminalWidget != null) { + hideIfNoActiveSessions(toolWindow, myTerminalWidget); } }); } @@ -171,11 +168,8 @@ public class TerminalView { terminalRunner.openSession(myTerminalWidget); } - toolWindow.activate(new Runnable() { - @Override - public void run() { + toolWindow.activate(() -> { - } }, true); } @@ -200,12 +194,7 @@ public class TerminalView { public void createNewSession(Project project, final AbstractTerminalRunner terminalRunner) { final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal"); - toolWindow.activate(new Runnable() { - @Override - public void run() { - openSession(toolWindow, terminalRunner); - } - }, true); + toolWindow.activate(() -> openSession(toolWindow, terminalRunner), true); } private static void hideIfNoActiveSessions(@NotNull final ToolWindow toolWindow, @NotNull JBTabbedTerminalWidget terminal) { diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/vfs/TerminalSessionEditor.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/vfs/TerminalSessionEditor.java index bed2622175c7..d844118264d6 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/vfs/TerminalSessionEditor.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/vfs/TerminalSessionEditor.java @@ -76,12 +76,7 @@ public class TerminalSessionEditor extends UserDataHolderBase implements FileEdi .setTerminationCallback(new Predicate() { @Override public boolean apply(Integer integer) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - FileEditorManagerEx.getInstanceEx(myProject).closeFile(myFile); - } - }); + ApplicationManager.getApplication().invokeLater(() -> FileEditorManagerEx.getInstanceEx(myProject).closeFile(myFile)); return true; } diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java index 7d5d35004879..029fd650d813 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java @@ -151,11 +151,8 @@ public class SearchingForTestsTask extends SearchForTestsTask { if (TestType.GROUP.getType().equals(myData.TEST_OBJECT)) { String groupName = myData.getGroupName(); if (!StringUtil.isEmptyOrSpaces(groupName)) { - final List names = ContainerUtil.map(StringUtil.split(groupName, ","), new Function() { - @Override - public String fun(String groupName) { - return groupName.trim(); - } + final List names = ContainerUtil.map(StringUtil.split(groupName, ","), groupName1 -> { + return groupName1.trim(); }); groupNames = new HashSet(names); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java index 41c65b55dc91..e99ea51beb26 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java @@ -250,11 +250,8 @@ public class TestNGRunnableState extends JavaTestFrameworkRunnableState>> classes) { if (forkPerModule()) { - final Map> perModule = new TreeMap>(new Comparator() { - @Override - public int compare(Module o1, Module o2) { - return StringUtil.compare(o1.getName(), o2.getName(), true); - } + final Map> perModule = new TreeMap>((o1, o2) -> { + return StringUtil.compare(o1.getName(), o2.getName(), true); }); for (final PsiClass psiClass : classes.keySet()) { diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/browser/GroupList.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/browser/GroupList.java index c0be62ab92a6..109a7e1b18ef 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/browser/GroupList.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/browser/GroupList.java @@ -37,12 +37,7 @@ public class GroupList extends JPanel public GroupList(PsiClass[] classes) { super(new BorderLayout()); - SortedListModel model = new SortedListModel(new Comparator() - { - public int compare(String s1, String s2) { - return s1.compareTo(s2); - } - }); + SortedListModel model = new SortedListModel((s1, s2) -> s1.compareTo(s2)); list = new JBList(model); Set groups = TestNGUtil.getAnnotationValues("groups", classes); String[] array = ArrayUtil.toStringArray(groups); diff --git a/plugins/testng/src/com/theoryinpractice/testng/inspection/JUnitConvertTool.java b/plugins/testng/src/com/theoryinpractice/testng/inspection/JUnitConvertTool.java index 5ace6bb7c33d..2e62f9cd40e0 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/inspection/JUnitConvertTool.java +++ b/plugins/testng/src/com/theoryinpractice/testng/inspection/JUnitConvertTool.java @@ -213,16 +213,13 @@ public class JUnitConvertTool extends BaseJavaLocalInspectionTool { private static List convertJunitAnnotations(final PsiElementFactory factory, final PsiMethod method) throws IncorrectOperationException { PsiAnnotation[] annotations = method.getModifierList().getAnnotations(); - return ContainerUtil.mapNotNull(annotations, new Function() { - @Override - public PsiElement fun(PsiAnnotation annotation) { - final String testNgAnnotation = ANNOTATIONS_MAP.get(annotation.getQualifiedName()); - if (testNgAnnotation != null) { - final PsiAnnotation newAnnotation = factory.createAnnotationFromText("@org.testng.annotations.Test", method); - return annotation.replace(newAnnotation); - } - return null; + return ContainerUtil.mapNotNull(annotations, annotation -> { + final String testNgAnnotation = ANNOTATIONS_MAP.get(annotation.getQualifiedName()); + if (testNgAnnotation != null) { + final PsiAnnotation newAnnotation = factory.createAnnotationFromText("@org.testng.annotations.Test", method); + return annotation.replace(newAnnotation); } + return null; }); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/inspection/UndeclaredTestInspection.java b/plugins/testng/src/com/theoryinpractice/testng/inspection/UndeclaredTestInspection.java index fa875b15d717..e1528ea26e06 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/inspection/UndeclaredTestInspection.java +++ b/plugins/testng/src/com/theoryinpractice/testng/inspection/UndeclaredTestInspection.java @@ -146,22 +146,19 @@ public class UndeclaredTestInspection extends BaseJavaLocalInspectionTool { public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { final PsiClass psiClass = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiClass.class); LOG.assertTrue(psiClass != null); - SwingUtilities.invokeLater(new Runnable() { //need to show dialog - - public void run() { - final String testngXmlPath = new SuiteBrowser(project).showDialog(); - if (testngXmlPath == null) return; - final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(testngXmlPath); - LOG.assertTrue(virtualFile != null); - final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); - LOG.assertTrue(psiFile instanceof XmlFile); - final XmlFile testngXML = (XmlFile)psiFile; - new WriteCommandAction(project, getName(), testngXML) { - protected void run(@NotNull final Result result) throws Throwable { - patchTestngXml(testngXML, psiClass); - } - }.execute(); - } + SwingUtilities.invokeLater(() -> { + final String testngXmlPath = new SuiteBrowser(project).showDialog(); + if (testngXmlPath == null) return; + final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(testngXmlPath); + LOG.assertTrue(virtualFile != null); + final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); + LOG.assertTrue(psiFile instanceof XmlFile); + final XmlFile testngXML = (XmlFile)psiFile; + new WriteCommandAction(project, getName(), testngXML) { + protected void run(@NotNull final Result result) throws Throwable { + patchTestngXml(testngXML, psiClass); + } + }.execute(); }); } } @@ -204,28 +201,26 @@ public class UndeclaredTestInspection extends BaseJavaLocalInspectionTool { public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) { final PsiClass psiClass = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiClass.class); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final VirtualFile file = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, null); - if (file != null) { - final PsiManager psiManager = PsiManager.getInstance(project); - final PsiDirectory directory = psiManager.findDirectory(file); - LOG.assertTrue(directory != null); - new WriteCommandAction(project, getName(), null) { - protected void run(@NotNull final Result result) throws Throwable { - XmlFile testngXml = (XmlFile)PsiFileFactory.getInstance(psiManager.getProject()) - .createFileFromText("testng.xml", "\n"); - try { - testngXml = (XmlFile)directory.add(testngXml); - } - catch (IncorrectOperationException e) { - //todo suggest new name - return; - } - patchTestngXml(testngXml, psiClass); + SwingUtilities.invokeLater(() -> { + final VirtualFile file = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, null); + if (file != null) { + final PsiManager psiManager = PsiManager.getInstance(project); + final PsiDirectory directory = psiManager.findDirectory(file); + LOG.assertTrue(directory != null); + new WriteCommandAction(project, getName(), null) { + protected void run(@NotNull final Result result) throws Throwable { + XmlFile testngXml = (XmlFile)PsiFileFactory.getInstance(psiManager.getProject()) + .createFileFromText("testng.xml", "\n"); + try { + testngXml = (XmlFile)directory.add(testngXml); } - }.execute(); - } + catch (IncorrectOperationException e) { + //todo suggest new name + return; + } + patchTestngXml(testngXml, psiClass); + } + }.execute(); } }); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/model/IDEARemoteTestRunnerClient.java b/plugins/testng/src/com/theoryinpractice/testng/model/IDEARemoteTestRunnerClient.java index 0570be8a831f..da83b8dd384c 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/model/IDEARemoteTestRunnerClient.java +++ b/plugins/testng/src/com/theoryinpractice/testng/model/IDEARemoteTestRunnerClient.java @@ -64,26 +64,22 @@ public class IDEARemoteTestRunnerClient extends AbstractRemoteTestRunnerClient @Override protected void notifyStart(final GenericMessage genericMessage) { - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - public void run() { - for (final IRemoteSuiteListener listener : m_suiteListeners) { - listener.onInitialization(genericMessage); - } + DumbService.getInstance(myProject).smartInvokeLater(() -> { + for (final IRemoteSuiteListener listener : m_suiteListeners) { + listener.onInitialization(genericMessage); } }, ModalityState.NON_MODAL); } @Override protected void notifySuiteEvents(final SuiteMessage suiteMessage) { - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - public void run() { - for (final IRemoteSuiteListener listener : m_suiteListeners) { - if (suiteMessage.isMessageOnStart()) { - listener.onStart(suiteMessage); - } - else { - listener.onFinish(suiteMessage); - } + DumbService.getInstance(myProject).smartInvokeLater(() -> { + for (final IRemoteSuiteListener listener : m_suiteListeners) { + if (suiteMessage.isMessageOnStart()) { + listener.onStart(suiteMessage); + } + else { + listener.onFinish(suiteMessage); } } }, ModalityState.NON_MODAL); @@ -91,15 +87,13 @@ public class IDEARemoteTestRunnerClient extends AbstractRemoteTestRunnerClient @Override protected void notifyTestEvents(final TestMessage testMessage) { - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - public void run() { - for (final IRemoteTestListener listener : m_testListeners) { - if (testMessage.isMessageOnStart()) { - listener.onStart(testMessage); - } - else { - listener.onFinish(testMessage); - } + DumbService.getInstance(myProject).smartInvokeLater(() -> { + for (final IRemoteTestListener listener : m_testListeners) { + if (testMessage.isMessageOnStart()) { + listener.onStart(testMessage); + } + else { + listener.onFinish(testMessage); } } }, ModalityState.NON_MODAL); @@ -107,26 +101,24 @@ public class IDEARemoteTestRunnerClient extends AbstractRemoteTestRunnerClient @Override protected void notifyResultEvents(final TestResultMessage testResultMessage) { - DumbService.getInstance(myProject).smartInvokeLater(new Runnable() { - public void run() { - for (final IRemoteTestListener listener : m_testListeners) { - switch (testResultMessage.getResult()) { - case MessageHelper.TEST_STARTED: - listener.onTestStart(testResultMessage); - break; - case MessageHelper.PASSED_TEST: - listener.onTestSuccess(testResultMessage); - break; - case MessageHelper.FAILED_TEST: - listener.onTestFailure(testResultMessage); - break; - case MessageHelper.SKIPPED_TEST: - listener.onTestSkipped(testResultMessage); - break; - case MessageHelper.FAILED_ON_PERCENTAGE_TEST: - listener.onTestFailedButWithinSuccessPercentage(testResultMessage); - break; - } + DumbService.getInstance(myProject).smartInvokeLater(() -> { + for (final IRemoteTestListener listener : m_testListeners) { + switch (testResultMessage.getResult()) { + case MessageHelper.TEST_STARTED: + listener.onTestStart(testResultMessage); + break; + case MessageHelper.PASSED_TEST: + listener.onTestSuccess(testResultMessage); + break; + case MessageHelper.FAILED_TEST: + listener.onTestFailure(testResultMessage); + break; + case MessageHelper.SKIPPED_TEST: + listener.onTestSkipped(testResultMessage); + break; + case MessageHelper.FAILED_ON_PERCENTAGE_TEST: + listener.onTestFailedButWithinSuccessPercentage(testResultMessage); + break; } } }, ModalityState.NON_MODAL); diff --git a/plugins/testng/src/com/theoryinpractice/testng/model/TestNGConfigurationModel.java b/plugins/testng/src/com/theoryinpractice/testng/model/TestNGConfigurationModel.java index 53f403acf68c..efeecee0602a 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/model/TestNGConfigurationModel.java +++ b/plugins/testng/src/com/theoryinpractice/testng/model/TestNGConfigurationModel.java @@ -205,11 +205,9 @@ public class TestNGConfigurationModel throw new RuntimeException(e); } } else { - WriteCommandAction.runWriteCommandAction(project, new Runnable() { - public void run() { - ((com.intellij.openapi.editor.Document)document) - .replaceString(0, ((com.intellij.openapi.editor.Document)document).getTextLength(), value); - } + WriteCommandAction.runWriteCommandAction(project, () -> { + ((com.intellij.openapi.editor.Document)document) + .replaceString(0, ((com.intellij.openapi.editor.Document)document).getTextLength(), value); }); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/model/TestNGResultsTableModel.java b/plugins/testng/src/com/theoryinpractice/testng/model/TestNGResultsTableModel.java index 269b8cc04aca..7b2f794545f9 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/model/TestNGResultsTableModel.java +++ b/plugins/testng/src/com/theoryinpractice/testng/model/TestNGResultsTableModel.java @@ -72,11 +72,7 @@ public class TestNGResultsTableModel extends ListTableModel { } public Comparator getComparator() { - return new Comparator() { - public int compare(final TestResultMessage o1, final TestResultMessage o2) { - return o1.getResult() - o2.getResult(); - } - }; + return (o1, o2) -> o1.getResult() - o2.getResult(); } } @@ -96,11 +92,7 @@ public class TestNGResultsTableModel extends ListTableModel { } public Comparator getComparator() { - return new Comparator() { - public int compare(final TestResultMessage o1, final TestResultMessage o2) { - return o1.getMethod().compareToIgnoreCase(o2.getMethod()); - } - }; + return (o1, o2) -> o1.getMethod().compareToIgnoreCase(o2.getMethod()); } } @@ -119,11 +111,7 @@ public class TestNGResultsTableModel extends ListTableModel { } public Comparator getComparator() { - return new Comparator() { - public int compare(final TestResultMessage o1, final TestResultMessage o2) { - return o1.getTestClass().compareToIgnoreCase(o2.getTestClass()); - } - }; + return (o1, o2) -> o1.getTestClass().compareToIgnoreCase(o2.getTestClass()); } } @@ -141,11 +129,7 @@ public class TestNGResultsTableModel extends ListTableModel { } public Comparator getComparator() { - return new Comparator() { - public int compare(final TestResultMessage o1, final TestResultMessage o2) { - return (int)(getDuration(o1) - getDuration(o2)); - } - }; + return (o1, o2) -> (int)(getDuration(o1) - getDuration(o2)); } } } diff --git a/plugins/testng/src/com/theoryinpractice/testng/model/TestNGTestObject.java b/plugins/testng/src/com/theoryinpractice/testng/model/TestNGTestObject.java index 21eef64eca03..64e7f1c14a1e 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/model/TestNGTestObject.java +++ b/plugins/testng/src/com/theoryinpractice/testng/model/TestNGTestObject.java @@ -147,22 +147,20 @@ public abstract class TestNGTestObject { final GlobalSearchScope searchScope, final Set membersToCheckNow, final PsiClass... classes) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final Project project = classes[0].getProject(); - final PsiClass testAnnotation = JavaPsiFacade.getInstance(project).findClass(annotationFqn, GlobalSearchScope.allScope(project)); - if (testAnnotation == null) { - return; - } - for (PsiMember psiMember : AnnotatedMembersSearch.search(testAnnotation, searchScope)) { - final PsiClass containingClass = psiMember.getContainingClass(); - if (containingClass == null) continue; - if (skipUnrelated && ArrayUtil.find(classes, containingClass) < 0) continue; - final PsiAnnotation annotation = AnnotationUtil.findAnnotation(psiMember, annotationFqn); - if (TestNGUtil.isAnnotatedWithParameter(annotation, "groups", groups)) { - if (appendMember(psiMember, alreadyMarkedToBeChecked, results)) { - membersToCheckNow.add(psiMember); - } + ApplicationManager.getApplication().runReadAction(() -> { + final Project project = classes[0].getProject(); + final PsiClass testAnnotation = JavaPsiFacade.getInstance(project).findClass(annotationFqn, GlobalSearchScope.allScope(project)); + if (testAnnotation == null) { + return; + } + for (PsiMember psiMember : AnnotatedMembersSearch.search(testAnnotation, searchScope)) { + final PsiClass containingClass = psiMember.getContainingClass(); + if (containingClass == null) continue; + if (skipUnrelated && ArrayUtil.find(classes, containingClass) < 0) continue; + final PsiAnnotation annotation = AnnotationUtil.findAnnotation(psiMember, annotationFqn); + if (TestNGUtil.isAnnotatedWithParameter(annotation, "groups", groups)) { + if (appendMember(psiMember, alreadyMarkedToBeChecked, results)) { + membersToCheckNow.add(psiMember); } } } @@ -195,21 +193,19 @@ public abstract class TestNGTestObject { valuesMap.put("dependsOnMethods", testMethodDependencies); TestNGUtil.collectAnnotationValues(valuesMap, methods, containingClass); if (!testMethodDependencies.isEmpty()) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final Project project = containingClass.getProject(); - final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); - for (String dependency : testMethodDependencies) { - final String className = StringUtil.getPackageName(dependency); - final String methodName = StringUtil.getShortName(dependency); - if (StringUtil.isEmpty(className)) { - checkClassMethods(methodName, containingClass, alreadyMarkedToBeChecked, membersToCheckNow, results); - } - else { - final PsiClass aClass = psiFacade.findClass(className, containingClass.getResolveScope()); - if (aClass != null) { - checkClassMethods(methodName, aClass, alreadyMarkedToBeChecked, membersToCheckNow, results); - } + ApplicationManager.getApplication().runReadAction(() -> { + final Project project = containingClass.getProject(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + for (String dependency : testMethodDependencies) { + final String className = StringUtil.getPackageName(dependency); + final String methodName = StringUtil.getShortName(dependency); + if (StringUtil.isEmpty(className)) { + checkClassMethods(methodName, containingClass, alreadyMarkedToBeChecked, membersToCheckNow, results); + } + else { + final PsiClass aClass = psiFacade.findClass(className, containingClass.getResolveScope()); + if (aClass != null) { + checkClassMethods(methodName, aClass, alreadyMarkedToBeChecked, membersToCheckNow, results); } } } diff --git a/plugins/testng/src/com/theoryinpractice/testng/model/TestProxy.java b/plugins/testng/src/com/theoryinpractice/testng/model/TestProxy.java index f921ee00a092..d341a1b6cb0e 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/model/TestProxy.java +++ b/plugins/testng/src/com/theoryinpractice/testng/model/TestProxy.java @@ -113,16 +113,14 @@ public class TestProxy extends AbstractTestProxy { public void setResultMessage(final TestResultMessage resultMessage) { //if we have a result, then our parent is a class, so we can look up our method //this is a bit fragile as it assumes parent is set first and correctly - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - PsiClass psiClass = (PsiClass)getParent().getPsiElement(); - if (psiClass != null) { - PsiMethod[] methods = psiClass.getAllMethods(); - for (PsiMethod method : methods) { - if (method.getName().equals(resultMessage.getMethod())) { - setPsiElement(method); - break; - } + ApplicationManager.getApplication().runReadAction(() -> { + PsiClass psiClass = (PsiClass)getParent().getPsiElement(); + if (psiClass != null) { + PsiMethod[] methods = psiClass.getAllMethods(); + for (PsiMethod method : methods) { + if (method.getName().equals(resultMessage.getMethod())) { + setPsiElement(method); + break; } } } diff --git a/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java b/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java index 2735721db6b4..03cff26e9bef 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java +++ b/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java @@ -324,10 +324,8 @@ public class TestNGResults extends TestResultsPanel implements TestFrameworkRunn //look up the psiclass now if (owner.getPsiElement() == null) { final TestProxy finalOwner = owner; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - finalOwner.setPsiElement(ClassUtil.findPsiClass(PsiManager.getInstance(project), result.getTestClass())); - } + ApplicationManager.getApplication().runReadAction(() -> { + finalOwner.setPsiElement(ClassUtil.findPsiClass(PsiManager.getInstance(project), result.getTestClass())); }); } return owner; @@ -369,35 +367,33 @@ public class TestNGResults extends TestResultsPanel implements TestFrameworkRunn } LvcsHelper.addLabel(this); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - animator.stopMovie(); - updateStatusLine(); - if (total > count || myStatus == MessageHelper.SKIPPED_TEST) { - myStatusLine.setStatusColor(ColorProgressBar.YELLOW); - } - else if (myStatus == MessageHelper.FAILED_TEST) { - myStatusLine.setStatusColor(ColorProgressBar.RED); - } - else { - myStatusLine.setStatusColor(ColorProgressBar.GREEN); - } - rootNode.setInProgress(false); - if (TestNGConsoleProperties.SELECT_FIRST_DEFECT.value(myProperties)) { - selectTest(rootNode.getFirstDefect()); - } - else { - final DefaultMutableTreeNode node = treeBuilder.getNodeForElement(rootNode); - if (node != null && myLastSelected == null) { - tree.getSelectionModel().setSelectionPath(new TreePath(node)); - } - } - tree.repaint(); - if (total > 0 || - !ResetConfigurationModuleAdapter.tryWithAnotherModule(configuration, getProperties().isDebug())) { - TestsUIUtil.notifyByBalloon(project, started, rootNode, getProperties(), "in " + getTime()); + SwingUtilities.invokeLater(() -> { + animator.stopMovie(); + updateStatusLine(); + if (total > count || myStatus == MessageHelper.SKIPPED_TEST) { + myStatusLine.setStatusColor(ColorProgressBar.YELLOW); + } + else if (myStatus == MessageHelper.FAILED_TEST) { + myStatusLine.setStatusColor(ColorProgressBar.RED); + } + else { + myStatusLine.setStatusColor(ColorProgressBar.GREEN); + } + rootNode.setInProgress(false); + if (TestNGConsoleProperties.SELECT_FIRST_DEFECT.value(myProperties)) { + selectTest(rootNode.getFirstDefect()); + } + else { + final DefaultMutableTreeNode node = treeBuilder.getNodeForElement(rootNode); + if (node != null && myLastSelected == null) { + tree.getSelectionModel().setSelectionPath(new TreePath(node)); } } + tree.repaint(); + if (total > 0 || + !ResetConfigurationModuleAdapter.tryWithAnotherModule(configuration, getProperties().isDebug())) { + TestsUIUtil.notifyByBalloon(project, started, rootNode, getProperties(), "in " + getTime()); + } }); } diff --git a/plugins/testng/src/com/theoryinpractice/testng/ui/actions/RerunFailedTestsAction.java b/plugins/testng/src/com/theoryinpractice/testng/ui/actions/RerunFailedTestsAction.java index 4cbee48eddd9..b293d3879a93 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/ui/actions/RerunFailedTestsAction.java +++ b/plugins/testng/src/com/theoryinpractice/testng/ui/actions/RerunFailedTestsAction.java @@ -70,10 +70,8 @@ public class RerunFailedTestsAction extends JavaRerunFailedTestsAction { final GlobalSearchScope scope = getConfiguration().getConfigurationModule().getSearchScope(); final Project project = getConfiguration().getProject(); for (final AbstractTestProxy proxy : failedTests) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - includeFailedTestWithDependencies(classes, scope, project, proxy); - } + ApplicationManager.getApplication().runReadAction(() -> { + includeFailedTestWithDependencies(classes, scope, project, proxy); }); } } diff --git a/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java b/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java index dfd5807fdbdb..edf4605ee83c 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java +++ b/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java @@ -359,25 +359,21 @@ public class TestNGUtil { if (psiMethods != null) { for (final PsiMethod psiMethod : psiMethods) { ApplicationManager.getApplication().runReadAction( - new Runnable() { - public void run() { - appendAnnotationAttributeValues(results, AnnotationUtil.findAnnotation(psiMethod, test), psiMethod); - } + () -> { + appendAnnotationAttributeValues(results, AnnotationUtil.findAnnotation(psiMethod, test), psiMethod); } ); } } else { for (final PsiClass psiClass : classes) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - if (psiClass != null && hasTest(psiClass)) { - appendAnnotationAttributeValues(results, AnnotationUtil.findAnnotation(psiClass, test), psiClass); - PsiMethod[] methods = psiClass.getMethods(); - for (PsiMethod method : methods) { - if (method != null) { - appendAnnotationAttributeValues(results, AnnotationUtil.findAnnotation(method, test), method); - } + ApplicationManager.getApplication().runReadAction(() -> { + if (psiClass != null && hasTest(psiClass)) { + appendAnnotationAttributeValues(results, AnnotationUtil.findAnnotation(psiClass, test), psiClass); + PsiMethod[] methods = psiClass.getMethods(); + for (PsiMethod method : methods) { + if (method != null) { + appendAnnotationAttributeValues(results, AnnotationUtil.findAnnotation(method, test), method); } } } @@ -437,24 +433,22 @@ public class TestNGUtil { @Nullable public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) { final PsiClass[][] holder = new PsiClass[1][]; - final Runnable process = new Runnable() { - public void run() { - final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + final Runnable process = () -> { + final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - final Collection set = new LinkedHashSet(); - final PsiManager manager = PsiManager.getInstance(filter.getProject()); - final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); - final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope()); - for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) { - if (filter.isAccepted(psiClass)) { - if (indicator != null) { - indicator.setText2("Found test class " + ReadAction.compute(psiClass::getQualifiedName)); - } - set.add(psiClass); + final Collection set = new LinkedHashSet(); + final PsiManager manager = PsiManager.getInstance(filter.getProject()); + final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); + final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope()); + for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) { + if (filter.isAccepted(psiClass)) { + if (indicator != null) { + indicator.setText2("Found test class " + ReadAction.compute(psiClass::getQualifiedName)); } + set.add(psiClass); } - holder[0] = set.toArray(new PsiClass[set.size()]); } + holder[0] = set.toArray(new PsiClass[set.size()]); }; if (sync) { ProgressManager.getInstance().runProcessWithProgressSynchronously(process, "Searching For Tests...", true, filter.getProject()); diff --git a/plugins/testng/testSources/com/theoryinpractice/testng/inspection/TestNGDependsOnInspectionTest.java b/plugins/testng/testSources/com/theoryinpractice/testng/inspection/TestNGDependsOnInspectionTest.java index 3e317c0d6ca4..637c4d42cda1 100644 --- a/plugins/testng/testSources/com/theoryinpractice/testng/inspection/TestNGDependsOnInspectionTest.java +++ b/plugins/testng/testSources/com/theoryinpractice/testng/inspection/TestNGDependsOnInspectionTest.java @@ -26,16 +26,14 @@ import org.testng.annotations.Test; public class TestNGDependsOnInspectionTest extends LightCodeInsightFixtureTestCase { @Test public void testDependencies() throws Exception { - Runnable runnable = new Runnable() { - public void run() { - myFixture.addClass("package org.testng.annotations;\n" + - "public @interface AfterSuite { java.lang.String[] dependsOnMethods() default {};}"); - myFixture.addClass("package org.testng.annotations;\n" + - "public @interface BeforeMethod { java.lang.String[] dependsOnMethods() default {};}"); - myFixture.addClass("package org.testng.annotations;\n" + - "public @interface Test { java.lang.String[] dependsOnMethods() default {};}"); - myFixture.testHighlighting(true, false, false, "Dependencies.java"); - } + Runnable runnable = () -> { + myFixture.addClass("package org.testng.annotations;\n" + + "public @interface AfterSuite { java.lang.String[] dependsOnMethods() default {};}"); + myFixture.addClass("package org.testng.annotations;\n" + + "public @interface BeforeMethod { java.lang.String[] dependsOnMethods() default {};}"); + myFixture.addClass("package org.testng.annotations;\n" + + "public @interface Test { java.lang.String[] dependsOnMethods() default {};}"); + myFixture.testHighlighting(true, false, false, "Dependencies.java"); }; UIUtil.invokeAndWaitIfNeeded(runnable); } diff --git a/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java b/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java index 2d0f3a913726..2a2dac46d0ae 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java @@ -87,21 +87,18 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, @Override public void deleteElement(final @NotNull DataContext dataContext) { - myDesigner.getToolProvider().execute(new ThrowableRunnable() { - @Override - public void run() throws Exception { - EditableArea area = getArea(dataContext); - List selection = area.getSelection(); + myDesigner.getToolProvider().execute(() -> { + EditableArea area = getArea(dataContext); + List selection = area.getSelection(); - if (selection.isEmpty()) { - return; - } - - myDesigner.getToolProvider().loadDefaultTool(); - List components = RadComponent.getPureSelection(selection); - updateSelectionBeforeDelete(area, components.get(0), selection); - handleDeletion(components); + if (selection.isEmpty()) { + return; } + + myDesigner.getToolProvider().loadDefaultTool(); + List components = RadComponent.getPureSelection(selection); + updateSelectionBeforeDelete(area, components.get(0), selection); + handleDeletion(components); }, DesignerBundle.message("command.delete.selection"), true); } diff --git a/plugins/ui-designer-core/src/com/intellij/designer/actions/MorphingAction.java b/plugins/ui-designer-core/src/com/intellij/designer/actions/MorphingAction.java index ff9cf510dde2..32da700ac0d9 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/actions/MorphingAction.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/actions/MorphingAction.java @@ -53,20 +53,17 @@ public class MorphingAction extends AnAction { @Override public void actionPerformed(AnActionEvent e) { - myDesigner.getToolProvider().execute(new ThrowableRunnable() { - @Override - public void run() throws Exception { - List newComponents = new ArrayList(); + myDesigner.getToolProvider().execute(() -> { + List newComponents = new ArrayList(); - for (RadComponent component : myComponents) { - RadComponent newComponent = component.morphingTo(myTarget); - if (newComponent != null) { - newComponents.add(newComponent); - } + for (RadComponent component : myComponents) { + RadComponent newComponent = component.morphingTo(myTarget); + if (newComponent != null) { + newComponents.add(newComponent); } - - myArea.setSelection(newComponents); } + + myArea.setSelection(newComponents); }, "Run Morphing action", true); } diff --git a/plugins/ui-designer-core/src/com/intellij/designer/actions/WrapInAction.java b/plugins/ui-designer-core/src/com/intellij/designer/actions/WrapInAction.java index e6b32d9a92c0..4ed1bb315606 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/actions/WrapInAction.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/actions/WrapInAction.java @@ -57,12 +57,7 @@ public class WrapInAction extends AnAction { @Override public void actionPerformed(AnActionEvent e) { - myDesigner.getToolProvider().execute(new ThrowableRunnable() { - @Override - public void run() throws Exception { - myArea.select(myProvider.wrapIn(myParent, myComponents, myTarget)); - } - }, "Run Wrap In action", true); + myDesigner.getToolProvider().execute(() -> myArea.select(myProvider.wrapIn(myParent, myComponents, myTarget)), "Run Wrap In action", true); } public static void fill(DesignerEditorPanel designer, DefaultActionGroup group, EditableArea area) { diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java index 1d004c9bd00e..98da6b9c797d 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java @@ -170,13 +170,10 @@ public abstract class DesignerEditorPanel extends JPanel createErrorCard(); createProgressPanel(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - DesignerEditorPanel designer = DesignerEditorPanel.this; - getDesignerWindowManager().bind(designer); - getPaletteWindowManager().bind(designer); - } + UIUtil.invokeLaterIfNeeded(() -> { + DesignerEditorPanel designer = DesignerEditorPanel.this; + getDesignerWindowManager().bind(designer); + getPaletteWindowManager().bind(designer); }); } @@ -981,32 +978,21 @@ public abstract class DesignerEditorPanel extends JPanel public boolean execute(final ThrowableRunnable operation, String command, final boolean updateProperties) { myLastExecuteCommand = command; final Ref result = Ref.create(Boolean.TRUE); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - public void run() { - result.set(DesignerEditorPanel.this.execute(operation, updateProperties)); - } - }, command, null); + CommandProcessor.getInstance().executeCommand(getProject(), + () -> result.set(DesignerEditorPanel.this.execute(operation, updateProperties)), command, null); return result.get(); } @Override public void executeWithReparse(final ThrowableRunnable operation, String command) { myLastExecuteCommand = command; - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - public void run() { - DesignerEditorPanel.this.executeWithReparse(operation); - } - }, command, null); + CommandProcessor.getInstance().executeCommand(getProject(), () -> DesignerEditorPanel.this.executeWithReparse(operation), command, null); } @Override public void execute(final List operations, String command) { myLastExecuteCommand = command; - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - public void run() { - DesignerEditorPanel.this.execute(operations); - } - }, command, null); + CommandProcessor.getInstance().executeCommand(getProject(), () -> DesignerEditorPanel.this.execute(operations), command, null); } @Override diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/ExternalPSIChangeListener.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/ExternalPSIChangeListener.java index f3302fcdb16b..62a72e431955 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/ExternalPSIChangeListener.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/ExternalPSIChangeListener.java @@ -111,12 +111,9 @@ public class ExternalPSIChangeListener extends PsiTreeChangeAdapter { public void addRequest(final Runnable runnable) { clear(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myRunState && myInitialize && !myDesigner.isProjectClosed()) { - runnable.run(); - } + myAlarm.addRequest(() -> { + if (myRunState && myInitialize && !myDesigner.isProjectClosed()) { + runnable.run(); } }, myDelayMillis, ModalityState.stateForComponent(myDesigner)); } diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/InplaceEditingLayer.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/InplaceEditingLayer.java index 2fd7aad346bc..b08cdbc45101 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/InplaceEditingLayer.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/InplaceEditingLayer.java @@ -60,10 +60,8 @@ public class InplaceEditingLayer extends JComponent { return; } // [vova] we need LaterInvocator here to prevent write-access assertions - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - finishEditing(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + finishEditing(true); }, ModalityState.NON_MODAL); } }; @@ -185,11 +183,9 @@ public class InplaceEditingLayer extends JComponent { else { grabFocus(); final JComponent finalComponentToFocus = componentToFocus; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - finalComponentToFocus.requestFocusInWindow(); - myFocusWatcher.install(myInplaceComponent); - } + ApplicationManager.getApplication().invokeLater(() -> { + finalComponentToFocus.requestFocusInWindow(); + myFocusWatcher.install(myInplaceComponent); }); } @@ -206,19 +202,16 @@ public class InplaceEditingLayer extends JComponent { if (myInplaceComponent != null) { if (commit) { - myDesigner.getToolProvider().execute(new ThrowableRunnable() { - @Override - public void run() throws Exception { - int size = myProperties.size(); + myDesigner.getToolProvider().execute(() -> { + int size = myProperties.size(); - for (int i = 0; i < size; i++) { - Property property = myProperties.get(i); - Object oldValue = property.getValue(myRadComponent); - Object newValue = myEditors.get(i).getValue(); + for (int i = 0; i < size; i++) { + Property property = myProperties.get(i); + Object oldValue = property.getValue(myRadComponent); + Object newValue = myEditors.get(i).getValue(); - if (!Comparing.equal(oldValue, newValue)) { - property.setValue(myRadComponent, newValue); - } + if (!Comparing.equal(oldValue, newValue)) { + property.setValue(myRadComponent, newValue); } } }, DesignerBundle.message("command.set.property.value"), true); diff --git a/plugins/ui-designer-core/src/com/intellij/designer/inspection/AbstractQuickFixManager.java b/plugins/ui-designer-core/src/com/intellij/designer/inspection/AbstractQuickFixManager.java index 7692d5418388..57fe413cf300 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/inspection/AbstractQuickFixManager.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/inspection/AbstractQuickFixManager.java @@ -70,12 +70,7 @@ public abstract class AbstractQuickFixManager { myComponent = component; myViewPort = viewPort; - myShowHintRequest = new Runnable() { - @Override - public void run() { - showHint(); - } - }; + myShowHintRequest = () -> showHint(); new VisibilityWatcher() { @Override @@ -316,17 +311,7 @@ public abstract class AbstractQuickFixManager { } private Runnable getQuickFixRunnable(final QuickFix value) { - return new Runnable() { - @Override - public void run() { - myDesigner.getToolProvider().executeWithReparse(new ThrowableRunnable() { - @Override - public void run() throws Exception { - ApplicationManager.getApplication().runWriteAction(value); - } - }, "Run '" + value.getName() + "' QuickFix"); - } - }; + return () -> myDesigner.getToolProvider().executeWithReparse(() -> ApplicationManager.getApplication().runWriteAction(value), "Run '" + value.getName() + "' QuickFix"); } private static final Border INACTIVE_BORDER = BorderFactory.createEmptyBorder(4, 4, 4, 4); diff --git a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java index 6f42108cab9a..47220b0f2567 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java @@ -96,28 +96,26 @@ public class ShowJavadoc extends AnAction implements IPropertyTableAction { callback = documentationManager.queueFetchDocInfo(javadocElement, component); } - callback.doWhenProcessed(new Runnable() { - public void run() { - JBPopup hint = - JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) - .setProject(project) - .setDimensionServiceKey(project, DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false) - .setResizable(true) - .setMovable(true) - .setRequestFocus(true) - .setTitle(DesignerBundle.message("designer.properties.javadoc.title", property.getName())) - .setCancelCallback(new Computable() { - @Override - public Boolean compute() { - Disposer.dispose(component); - return Boolean.TRUE; - } - }) - .createPopup(); - component.setHint(hint); - Disposer.register(hint, component); - hint.show(new RelativePoint(myTable.getParent(), new Point(0, 0))); - } + callback.doWhenProcessed(() -> { + JBPopup hint = + JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) + .setProject(project) + .setDimensionServiceKey(project, DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false) + .setResizable(true) + .setMovable(true) + .setRequestFocus(true) + .setTitle(DesignerBundle.message("designer.properties.javadoc.title", property.getName())) + .setCancelCallback(new Computable() { + @Override + public Boolean compute() { + Disposer.dispose(component); + return Boolean.TRUE; + } + }) + .createPopup(); + component.setHint(hint); + Disposer.register(hint, component); + hint.show(new RelativePoint(myTable.getParent(), new Point(0, 0))); }); if (javadocElement == null) { diff --git a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/TableTabAction.java b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/TableTabAction.java index 775d68fc3b78..0f1531695b8b 100644 --- a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/TableTabAction.java +++ b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/TableTabAction.java @@ -56,12 +56,7 @@ public class TableTabAction extends ToggleAction implements DumbAware { myPanel.setCurrentTab(myTab); } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - updateState(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> updateState()); } } diff --git a/plugins/ui-designer/src/com/intellij/ide/palette/impl/PaletteComponentList.java b/plugins/ui-designer/src/com/intellij/ide/palette/impl/PaletteComponentList.java index 92f24e11330e..7e5501be663f 100644 --- a/plugins/ui-designer/src/com/intellij/ide/palette/impl/PaletteComponentList.java +++ b/plugins/ui-designer/src/com/intellij/ide/palette/impl/PaletteComponentList.java @@ -93,20 +93,18 @@ public class PaletteComponentList extends JBList { addMouseListener(new PopupHandler() { public void invokePopup(final Component comp, final int x, final int y) { requestFocusInWindow(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - int index = locationToIndex(new Point(x, y)); - PaletteItem[] items = myGroup.getItems(); - if (index >= 0 && index < items.length) { - if (getSelectedIndex() != index) { - addSelectionInterval(index, index); - } - PaletteItem item = items [index]; - ActionGroup group = item.getPopupActionGroup(); - if (group != null) { - ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group); - popupMenu.getComponent().show(comp, x, y); - } + SwingUtilities.invokeLater(() -> { + int index = locationToIndex(new Point(x, y)); + PaletteItem[] items = myGroup.getItems(); + if (index >= 0 && index < items.length) { + if (getSelectedIndex() != index) { + addSelectionInterval(index, index); + } + PaletteItem item = items [index]; + ActionGroup group1 = item.getPopupActionGroup(); + if (group1 != null) { + ActionPopupMenu popupMenu1 = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group1); + popupMenu1.getComponent().show(comp, x, y); } } }); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/CutCopyPasteSupport.java b/plugins/ui-designer/src/com/intellij/uiDesigner/CutCopyPasteSupport.java index a4ecbfbec91f..5529e9947bef 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/CutCopyPasteSupport.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/CutCopyPasteSupport.java @@ -97,11 +97,7 @@ public final class CutCopyPasteSupport implements CopyProvider, CutProvider, Pas public void performCut(@NotNull final DataContext dataContext) { if (doCopy() && myEditor.ensureEditable()) { - CommandProcessor.getInstance().executeCommand(myEditor.getProject(), new Runnable() { - public void run() { - FormEditingUtil.deleteSelection(myEditor); - } - }, UIDesignerBundle.message("command.cut"), null); + CommandProcessor.getInstance().executeCommand(myEditor.getProject(), () -> FormEditingUtil.deleteSelection(myEditor), UIDesignerBundle.message("command.cut"), null); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java b/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java index f2443b264b78..7eaf54950049 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/FormEditingUtil.java @@ -528,41 +528,39 @@ public final class FormEditingUtil { return; } - Runnable runnable = new Runnable() { - public void run() { - if (!GridChangeUtil.canDeleteCells(container, cells, isRow)) { - Set componentsInColumn = new HashSet(); - for (RadComponent component : container.getComponents()) { - GridConstraints c = component.getConstraints(); - for (int cell : cells) { - if (c.contains(isRow, cell)) { - componentsInColumn.add(component); - break; - } + Runnable runnable = () -> { + if (!GridChangeUtil.canDeleteCells(container, cells, isRow)) { + Set componentsInColumn = new HashSet(); + for (RadComponent component : container.getComponents()) { + GridConstraints c = component.getConstraints(); + for (int cell : cells) { + if (c.contains(isRow, cell)) { + componentsInColumn.add(component); + break; } } - - if (componentsInColumn.size() > 0) { - String message = isRow - ? UIDesignerBundle.message("delete.row.nonempty", componentsInColumn.size(), cells.length) - : UIDesignerBundle.message("delete.column.nonempty", componentsInColumn.size(), cells.length); - - final int rc = Messages.showYesNoDialog(editor, message, - isRow ? UIDesignerBundle.message("delete.row.title") - : UIDesignerBundle.message("delete.column.title"), Messages.getQuestionIcon()); - if (rc != Messages.YES) { - return; - } - - deleteComponents(componentsInColumn, false); - } } - for (int cell : cells) { - container.getGridLayoutManager().deleteGridCells(container, cell, isRow); + if (componentsInColumn.size() > 0) { + String message = isRow + ? UIDesignerBundle.message("delete.row.nonempty", componentsInColumn.size(), cells.length) + : UIDesignerBundle.message("delete.column.nonempty", componentsInColumn.size(), cells.length); + + final int rc = Messages.showYesNoDialog(editor, message, + isRow ? UIDesignerBundle.message("delete.row.title") + : UIDesignerBundle.message("delete.column.title"), Messages.getQuestionIcon()); + if (rc != Messages.YES) { + return; + } + + deleteComponents(componentsInColumn, false); } - editor.refreshAndSave(true); } + + for (int cell : cells) { + container.getGridLayoutManager().deleteGridCells(container, cell, isRow); + } + editor.refreshAndSave(true); }; CommandProcessor.getInstance().executeCommand(editor.getProject(), runnable, isRow ? UIDesignerBundle.message("command.delete.row") diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/GridBuildUtil.java b/plugins/ui-designer/src/com/intellij/uiDesigner/GridBuildUtil.java index a6530568733a..1f8f78fe958d 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/GridBuildUtil.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/GridBuildUtil.java @@ -242,17 +242,15 @@ public class GridBuildUtil { private static GridLayoutManager createOneDimensionGrid(final RadComponent[] selection, final boolean isVertical){ Arrays.sort( selection, - new Comparator() { - public int compare(final RadComponent o1, final RadComponent o2){ - final Rectangle bounds1 = o1.getBounds(); - final Rectangle bounds2 = o2.getBounds(); + (o1, o2) -> { + final Rectangle bounds1 = o1.getBounds(); + final Rectangle bounds2 = o2.getBounds(); - if (isVertical) { - return (bounds1.y + bounds1.height / 2) - (bounds2.y + bounds2.height / 2); - } - else { - return (bounds1.x + bounds1.width / 2) - (bounds2.x + bounds2.width / 2); - } + if (isVertical) { + return (bounds1.y + bounds1.height / 2) - (bounds2.y + bounds2.height / 2); + } + else { + return (bounds1.x + bounds1.width / 2) - (bounds2.x + bounds2.width / 2); } } ); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/GuiDesignerConfigurable.java b/plugins/ui-designer/src/com/intellij/uiDesigner/GuiDesignerConfigurable.java index 41aba46fdfb2..6cabb09f684c 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/GuiDesignerConfigurable.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/GuiDesignerConfigurable.java @@ -203,24 +203,14 @@ public final class GuiDesignerConfigurable implements SearchableConfigurable, Co * Launches vanish/generate sources processes */ private void applyImpl() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - vanishGeneratedSources(); - } - }); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + vanishGeneratedSources(); + }), "", null); } public void run() { - ProgressManager.getInstance().runProcess(new Runnable() { - public void run() { - applyImpl(); - } - }, myProgressWindow); + ProgressManager.getInstance().runProcess(() -> applyImpl(), myProgressWindow); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/AbstractGuiEditorAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/AbstractGuiEditorAction.java index b4f74c76a87a..fac5e33aa381 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/AbstractGuiEditorAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/AbstractGuiEditorAction.java @@ -50,12 +50,10 @@ public abstract class AbstractGuiEditorAction extends AnAction implements DumbAw if (myModifying) { if (!editor.ensureEditable()) return; } - Runnable runnable = new Runnable() { - public void run() { - actionPerformed(editor, selection, e); - if (myModifying) { - editor.refreshAndSave(true); - } + Runnable runnable = () -> { + actionPerformed(editor, selection, e); + if (myModifying) { + editor.refreshAndSave(true); } }; if (getCommandName() != null) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ChooseLocaleAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ChooseLocaleAction.java index 3f7d68d76e78..475bac30a788 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ChooseLocaleAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ChooseLocaleAction.java @@ -57,11 +57,7 @@ public class ChooseLocaleAction extends ComboBoxAction { if (editor != null) { Locale[] locales = FormEditingUtil.collectUsedLocales(editor.getModule(), editor.getRootContainer()); if (locales.length > 1 || (locales.length == 1 && locales [0].getDisplayName().length() > 0)) { - Arrays.sort(locales, new Comparator() { - public int compare(final Locale o1, final Locale o2) { - return o1.getDisplayName().compareTo(o2.getDisplayName()); - } - }); + Arrays.sort(locales, (o1, o2) -> o1.getDisplayName().compareTo(o2.getDisplayName())); for(Locale locale: locales) { group.add(new SetLocaleAction(editor, locale, true)); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateComponentAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateComponentAction.java index f0d3c8b2199a..db9cc9ae96da 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateComponentAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateComponentAction.java @@ -39,14 +39,12 @@ public class CreateComponentAction extends AbstractGuiEditorAction { private ComponentItem myLastCreatedComponent = null; protected void actionPerformed(final GuiEditor editor, final List selection, final AnActionEvent e) { - Processor processor = new Processor() { - public boolean process(final ComponentItem selectedValue) { - if (selectedValue != null) { - myLastCreatedComponent = selectedValue; - editor.getMainProcessor().startInsertProcessor(selectedValue, getCreateLocation(editor, selection)); - } - return true; + Processor processor = selectedValue -> { + if (selectedValue != null) { + myLastCreatedComponent = selectedValue; + editor.getMainProcessor().startInsertProcessor(selectedValue, getCreateLocation(editor, selection)); } + return true; }; PaletteListPopupStep step = new PaletteListPopupStep(editor, myLastCreatedComponent, processor, diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateListenerAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateListenerAction.java index 6e112efeaea3..34a26871528d 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateListenerAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/CreateListenerAction.java @@ -94,11 +94,7 @@ public class CreateListenerAction extends AbstractGuiEditorAction { } EventSetDescriptor[] sortedDescriptors = new EventSetDescriptor[eventSetDescriptors.length]; System.arraycopy(eventSetDescriptors, 0, sortedDescriptors, 0, eventSetDescriptors.length); - Arrays.sort(sortedDescriptors, new Comparator() { - public int compare(final EventSetDescriptor o1, final EventSetDescriptor o2) { - return o1.getListenerType().getName().compareTo(o2.getListenerType().getName()); - } - }); + Arrays.sort(sortedDescriptors, (o1, o2) -> o1.getListenerType().getName().compareTo(o2.getListenerType().getName())); for(EventSetDescriptor descriptor: sortedDescriptors) { actionGroup.add(new MyCreateListenerAction(selection, descriptor)); } @@ -137,15 +133,9 @@ public class CreateListenerAction extends AbstractGuiEditorAction { public void actionPerformed(AnActionEvent e) { CommandProcessor.getInstance().executeCommand( mySelection.get(0).getProject(), - new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - createListener(); - } - }); - } - }, UIDesignerBundle.message("create.listener.command"), null + () -> ApplicationManager.getApplication().runWriteAction(() -> { + createListener(); + }), UIDesignerBundle.message("create.listener.command"), null ); } @@ -252,14 +242,12 @@ public class CreateListenerAction extends AbstractGuiEditorAction { if (brace != null) { editor.getCaretModel().moveToOffset(brace.getTextOffset()); } - CommandProcessor.getInstance().executeCommand(myClass.getProject(), new Runnable() { - public void run() { - if (!OverrideImplementExploreUtil.getMethodSignaturesToImplement(newClass).isEmpty()) { - OverrideImplementUtil.chooseAndImplementMethods(newClass.getProject(), editor, newClass); - } - else { - OverrideImplementUtil.chooseAndOverrideMethods(newClass.getProject(), editor, newClass); - } + CommandProcessor.getInstance().executeCommand(myClass.getProject(), () -> { + if (!OverrideImplementExploreUtil.getMethodSignaturesToImplement(newClass).isEmpty()) { + OverrideImplementUtil.chooseAndImplementMethods(newClass.getProject(), editor, newClass); + } + else { + OverrideImplementUtil.chooseAndOverrideMethods(newClass.getProject(), editor, newClass); } }, "", null); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/GenerateMainAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/GenerateMainAction.java index d1c3cd936d28..f24496ea48cf 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/GenerateMainAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/GenerateMainAction.java @@ -108,24 +108,18 @@ public class GenerateMainAction extends AnAction { mainBuilder.append("}\n"); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - PsiMethod method = - JavaPsiFacade.getInstance(file.getProject()).getElementFactory().createMethodFromText(mainBuilder.toString(), file); - List> infos = Collections.singletonList(new PsiGenerationInfo(method)); - List> resultMembers = GenerateMembersUtil.insertMembersAtOffset(file, offset, infos); - resultMembers.get(0).positionCaret(editor, false); - } - catch (IncorrectOperationException e1) { - LOG.error(e1); - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + PsiMethod method = + JavaPsiFacade.getInstance(file.getProject()).getElementFactory().createMethodFromText(mainBuilder.toString(), file); + List> infos = Collections.singletonList(new PsiGenerationInfo(method)); + List> resultMembers = GenerateMembersUtil.insertMembersAtOffset(file, offset, infos); + resultMembers.get(0).positionCaret(editor, false); } - }, null, null); + catch (IncorrectOperationException e1) { + LOG.error(e1); + } + }), null, null); } @Override diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MorphAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MorphAction.java index 80579d3a0e01..a04c22128dcd 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MorphAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MorphAction.java @@ -61,18 +61,16 @@ public class MorphAction extends AbstractGuiEditorAction { } protected void actionPerformed(final GuiEditor editor, final List selection, final AnActionEvent e) { - Processor processor = new Processor() { - public boolean process(final ComponentItem selectedValue) { - Runnable runnable = () -> { - for(RadComponent c: selection) { - if (!morphComponent(editor, c, selectedValue)) break; - } - editor.refreshAndSave(true); - }; - CommandProcessor.getInstance().executeCommand(editor.getProject(), runnable, UIDesignerBundle.message("morph.component.command"), null); - editor.getGlassLayer().requestFocus(); - return true; - } + Processor processor = selectedValue -> { + Runnable runnable = () -> { + for(RadComponent c: selection) { + if (!morphComponent(editor, c, selectedValue)) break; + } + editor.refreshAndSave(true); + }; + CommandProcessor.getInstance().executeCommand(editor.getProject(), runnable, UIDesignerBundle.message("morph.component.command"), null); + editor.getGlassLayer().requestFocus(); + return true; }; PaletteListPopupStep step = new PaletteListPopupStep(editor, myLastMorphComponent, processor, diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MoveComponentAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MoveComponentAction.java index 6728456338bf..74c74f8263a0 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MoveComponentAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/MoveComponentAction.java @@ -46,12 +46,10 @@ public class MoveComponentAction extends AbstractGuiEditorAction { protected void actionPerformed(final GuiEditor editor, final List selection, final AnActionEvent e) { if (myColumnDelta != 0) { // sort the selection so that move in indexed layout will handle components in correct order - Collections.sort(selection, new Comparator() { - public int compare(final RadComponent o1, final RadComponent o2) { - int index1 = o1.getParent().indexOfComponent(o1); - int index2 = o2.getParent().indexOfComponent(o2); - return (index2 - index1) * myColumnDelta; - } + Collections.sort(selection, (o1, o2) -> { + int index1 = o1.getParent().indexOfComponent(o1); + int index2 = o2.getParent().indexOfComponent(o2); + return (index2 - index1) * myColumnDelta; }); } for(RadComponent c: selection) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java index 49766b110bfa..15d43896772c 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java @@ -363,11 +363,7 @@ public final class PreviewFormAction extends AnAction{ } finally { final Project project = myModule.getProject(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - WindowManager.getInstance().getStatusBar(project).setInfo(myStatusbarMessage); - } - }); + SwingUtilities.invokeLater(() -> WindowManager.getInstance().getStatusBar(project).setInfo(myStatusbarMessage)); } } }; diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ShowJavadocAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ShowJavadocAction.java index 5f7717e6efe6..50be2a7f1a00 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ShowJavadocAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/ShowJavadocAction.java @@ -65,24 +65,22 @@ public final class ShowJavadocAction extends AnAction { tabbedPane.addTab(UIDesignerBundle.message("tab.setter"), component2); documentationManager.fetchDocInfo(getter, component1); - documentationManager.queueFetchDocInfo(setter, component2).doWhenProcessed(new Runnable() { - public void run() { - final JBPopup hint = - JBPopupFactory.getInstance().createComponentPopupBuilder(tabbedPane.getComponent(), component1) - .setDimensionServiceKey(aClass.getProject(), DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false) - .setResizable(true) - .setMovable(true) - .setRequestFocus(true) - .setTitle(UIDesignerBundle.message("property.javadoc.title", introspectedProperty.getName())) - .createPopup(); - component1.setHint(hint); - component2.setHint(hint); - Disposer.register(hint, component1); - Disposer.register(hint, component2); - Disposer.register(hint, disposable); - hint.show(new RelativePoint(inspector, new Point(0,0))); - //component1.requestFocus(); - } + documentationManager.queueFetchDocInfo(setter, component2).doWhenProcessed(() -> { + final JBPopup hint = + JBPopupFactory.getInstance().createComponentPopupBuilder(tabbedPane.getComponent(), component1) + .setDimensionServiceKey(aClass.getProject(), DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false) + .setResizable(true) + .setMovable(true) + .setRequestFocus(true) + .setTitle(UIDesignerBundle.message("property.javadoc.title", introspectedProperty.getName())) + .createPopup(); + component1.setHint(hint); + component2.setHint(hint); + Disposer.register(hint, component1); + Disposer.register(hint, component2); + Disposer.register(hint, disposable); + hint.show(new RelativePoint(inspector, new Point(0,0))); + //component1.requestFocus(); }); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/SurroundAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/SurroundAction.java index c8f5a2177b61..5d3d17a46c85 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/SurroundAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/SurroundAction.java @@ -64,114 +64,112 @@ public class SurroundAction extends AbstractGuiEditorAction { assert cItem != null; CommandProcessor.getInstance().executeCommand( editor.getProject(), - new Runnable() { - public void run() { - RadContainer newContainer = (RadContainer) InsertComponentProcessor.createInsertedComponent(editor, cItem); - if (newContainer == null) { - return; - } + () -> { + RadContainer newContainer = (RadContainer) InsertComponentProcessor.createInsertedComponent(editor, cItem); + if (newContainer == null) { + return; + } - if (cItem == palette.getPanelItem()) { - if (selectionParent.getLayoutManager().isGrid()) { - try { - newContainer.setLayoutManager(LayoutManagerRegistry.createLayoutManager(selectionParent.getLayoutManager().getName())); - } - catch (Exception e1) { - LOG.error(e1); - return; - } - } - else { - newContainer.setLayoutManager(LayoutManagerRegistry.createDefaultGridLayoutManager(editor.getProject())); - } - } - - Rectangle rc = new Rectangle(0, 0, 1, 1); - int minIndex = Integer.MAX_VALUE; + if (cItem == palette.getPanelItem()) { if (selectionParent.getLayoutManager().isGrid()) { - rc = FormEditingUtil.getSelectionBounds(selection); - } - else if (selectionParent.getLayoutManager().isIndexed()) { - for(RadComponent c: selection) { - minIndex = Math.min(minIndex, selectionParent.indexOfComponent(c)); + try { + newContainer.setLayoutManager(LayoutManagerRegistry.createLayoutManager(selectionParent.getLayoutManager().getName())); + } + catch (Exception e1) { + LOG.error(e1); + return; } - } - for(RadComponent c: selection) { - selectionParent.removeComponent(c); - } - - if (selectionParent.getLayoutManager().isGrid()) { - final GridConstraints newConstraints = newContainer.getConstraints(); - newConstraints.setRow(rc.y); - newConstraints.setColumn(rc.x); - newConstraints.setRowSpan(rc.height); - newConstraints.setColSpan(rc.width); - } - else if (selectionParent.getLayout() instanceof XYLayoutManager && selection.size() == 1) { - newContainer.setBounds(selection.get(0).getBounds()); - } - - if (selection.size() == 1) { - newContainer.setCustomLayoutConstraints(selection.get(0).getCustomLayoutConstraints()); - } - if (minIndex != Integer.MAX_VALUE) { - selectionParent.addComponent(newContainer, minIndex); } else { - selectionParent.addComponent(newContainer); + newContainer.setLayoutManager(LayoutManagerRegistry.createDefaultGridLayoutManager(editor.getProject())); } - - if (newContainer instanceof RadTabbedPane) { - // the first tab is created by RadTabbedPane itself - assert newContainer.getComponentCount() == 1; - newContainer = (RadContainer) newContainer.getComponent(0); - } - else if (newContainer instanceof RadSplitPane) { - if (selection.size() > 2) { - RadContainer panel = InsertComponentProcessor.createPanelComponent(editor); - panel.setCustomLayoutConstraints(LwSplitPane.POSITION_LEFT); - newContainer.addComponent(panel); - newContainer = panel; - } - else { - if (selection.size() > 0) { - selection.get(0).setCustomLayoutConstraints(LwSplitPane.POSITION_LEFT); - } - if (selection.size() > 1) { - selection.get(1).setCustomLayoutConstraints(LwSplitPane.POSITION_RIGHT); - } - } - } - - // if surrounding a single control with JPanel, 1x1 grid in resulting container is sufficient - // otherwise, copy column properties and row/col spans - if (newContainer.getComponentClass().equals(JPanel.class) && selection.size() > 1) { - if (selectionParent.getLayoutManager().isGrid()) { - newContainer.getGridLayoutManager().copyGridSection(selectionParent, newContainer, rc); - } - else { - // TODO[yole]: correctly handle surround from indexed - newContainer.setLayout(new GridLayoutManager(rc.height, rc.width)); - } - } - - for(RadComponent c: selection) { - if (selectionParent.getLayoutManager().isGrid()) { - if (selection.size() > 1) { - c.getConstraints().setRow(c.getConstraints().getRow() - rc.y); - c.getConstraints().setColumn(c.getConstraints().getColumn() - rc.x); - } - else { - c.getConstraints().setRow(0); - c.getConstraints().setColumn(0); - c.getConstraints().setRowSpan(1); - c.getConstraints().setColSpan(1); - } - } - newContainer.addComponent(c); - } - editor.refreshAndSave(true); } + + Rectangle rc = new Rectangle(0, 0, 1, 1); + int minIndex = Integer.MAX_VALUE; + if (selectionParent.getLayoutManager().isGrid()) { + rc = FormEditingUtil.getSelectionBounds(selection); + } + else if (selectionParent.getLayoutManager().isIndexed()) { + for(RadComponent c: selection) { + minIndex = Math.min(minIndex, selectionParent.indexOfComponent(c)); + } + } + for(RadComponent c: selection) { + selectionParent.removeComponent(c); + } + + if (selectionParent.getLayoutManager().isGrid()) { + final GridConstraints newConstraints = newContainer.getConstraints(); + newConstraints.setRow(rc.y); + newConstraints.setColumn(rc.x); + newConstraints.setRowSpan(rc.height); + newConstraints.setColSpan(rc.width); + } + else if (selectionParent.getLayout() instanceof XYLayoutManager && selection.size() == 1) { + newContainer.setBounds(selection.get(0).getBounds()); + } + + if (selection.size() == 1) { + newContainer.setCustomLayoutConstraints(selection.get(0).getCustomLayoutConstraints()); + } + if (minIndex != Integer.MAX_VALUE) { + selectionParent.addComponent(newContainer, minIndex); + } + else { + selectionParent.addComponent(newContainer); + } + + if (newContainer instanceof RadTabbedPane) { + // the first tab is created by RadTabbedPane itself + assert newContainer.getComponentCount() == 1; + newContainer = (RadContainer) newContainer.getComponent(0); + } + else if (newContainer instanceof RadSplitPane) { + if (selection.size() > 2) { + RadContainer panel = InsertComponentProcessor.createPanelComponent(editor); + panel.setCustomLayoutConstraints(LwSplitPane.POSITION_LEFT); + newContainer.addComponent(panel); + newContainer = panel; + } + else { + if (selection.size() > 0) { + selection.get(0).setCustomLayoutConstraints(LwSplitPane.POSITION_LEFT); + } + if (selection.size() > 1) { + selection.get(1).setCustomLayoutConstraints(LwSplitPane.POSITION_RIGHT); + } + } + } + + // if surrounding a single control with JPanel, 1x1 grid in resulting container is sufficient + // otherwise, copy column properties and row/col spans + if (newContainer.getComponentClass().equals(JPanel.class) && selection.size() > 1) { + if (selectionParent.getLayoutManager().isGrid()) { + newContainer.getGridLayoutManager().copyGridSection(selectionParent, newContainer, rc); + } + else { + // TODO[yole]: correctly handle surround from indexed + newContainer.setLayout(new GridLayoutManager(rc.height, rc.width)); + } + } + + for(RadComponent c: selection) { + if (selectionParent.getLayoutManager().isGrid()) { + if (selection.size() > 1) { + c.getConstraints().setRow(c.getConstraints().getRow() - rc.y); + c.getConstraints().setColumn(c.getConstraints().getColumn() - rc.x); + } + else { + c.getConstraints().setRow(0); + c.getConstraints().setColumn(0); + c.getConstraints().setRowSpan(1); + c.getConstraints().setColSpan(1); + } + } + newContainer.addComponent(c); + } + editor.refreshAndSave(true); }, null, null); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeBoundFieldTypeFix.java b/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeBoundFieldTypeFix.java index 6462cf499d5c..8dae149c2551 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeBoundFieldTypeFix.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeBoundFieldTypeFix.java @@ -55,21 +55,15 @@ public class ChangeBoundFieldTypeFix implements IntentionAction { } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { - CommandProcessor.getInstance().executeCommand(myField.getProject(), new Runnable() { - public void run() { - try { - final PsiManager manager = myField.getManager(); - myField.getTypeElement().replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createTypeElement(myTypeToSet)); - } - catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable(){ - public void run() { - Messages.showErrorDialog(myField.getProject(), - QuickFixBundle.message("cannot.change.field.exception", myField.getName(), e.getLocalizedMessage()), - CommonBundle.getErrorTitle()); - } - }); - } + CommandProcessor.getInstance().executeCommand(myField.getProject(), () -> { + try { + final PsiManager manager = myField.getManager(); + myField.getTypeElement().replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createTypeElement(myTypeToSet)); + } + catch (final IncorrectOperationException e) { + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(myField.getProject(), + QuickFixBundle.message("cannot.change.field.exception", myField.getName(), e.getLocalizedMessage()), + CommonBundle.getErrorTitle())); } }, getText(), null); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeFormComponentTypeFix.java b/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeFormComponentTypeFix.java index 3ddec299894f..f823e9b3dee7 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeFormComponentTypeFix.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/binding/ChangeFormComponentTypeFix.java @@ -67,13 +67,11 @@ public class ChangeFormComponentTypeFix implements IntentionAction { } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { - CommandProcessor.getInstance().executeCommand(file.getProject(), new Runnable() { - public void run() { - final ReadonlyStatusHandler readOnlyHandler = ReadonlyStatusHandler.getInstance(myFormFile.getProject()); - final ReadonlyStatusHandler.OperationStatus status = readOnlyHandler.ensureFilesWritable(myFormFile.getVirtualFile()); - if (!status.hasReadonlyFiles()) { - FormReferenceProvider.setGUIComponentType(myFormFile, myFieldName, myComponentTypeToSet); - } + CommandProcessor.getInstance().executeCommand(file.getProject(), () -> { + final ReadonlyStatusHandler readOnlyHandler = ReadonlyStatusHandler.getInstance(myFormFile.getProject()); + final ReadonlyStatusHandler.OperationStatus status = readOnlyHandler.ensureFilesWritable(myFormFile.getVirtualFile()); + if (!status.hasReadonlyFiles()) { + FormReferenceProvider.setGUIComponentType(myFormFile, myFieldName, myComponentTypeToSet); } }, getText(), null); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/binding/FormReferenceProvider.java b/plugins/ui-designer/src/com/intellij/uiDesigner/binding/FormReferenceProvider.java index 50e7121a6237..5722283b5364 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/binding/FormReferenceProvider.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/binding/FormReferenceProvider.java @@ -157,10 +157,8 @@ public class FormReferenceProvider extends PsiReferenceProvider { } final PsiReference finalClassReference = classReference; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - processReferences(rootTag, finalClassReference, file, processor); - } + ApplicationManager.getApplication().runReadAction(() -> { + processReferences(rootTag, finalClassReference, file, processor); }); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTreeBuilder.java b/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTreeBuilder.java index aa5161ea0b96..a140362df15c 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTreeBuilder.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTreeBuilder.java @@ -193,13 +193,10 @@ public final class ComponentTreeBuilder extends AbstractTreeBuilder { myInsideChange++; try{ - queueUpdate().doWhenDone(new Runnable() { - @Override - public void run() { - // After updating the tree we have to synchronize the selection in the tree - // with selected element in the hierarchy - syncSelection(); - } + queueUpdate().doWhenDone(() -> { + // After updating the tree we have to synchronize the selection in the tree + // with selected element in the hierarchy + syncSelection(); }); }finally{ myInsideChange--; diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DesignDropTargetListener.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DesignDropTargetListener.java index bf571888661d..e9fdee839f09 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DesignDropTargetListener.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DesignDropTargetListener.java @@ -208,11 +208,9 @@ class DesignDropTargetListener implements DropTargetListener { final DraggedComponentList dcl = DraggedComponentList.fromTransferable(dtde.getTransferable()); if (dcl != null) { CommandProcessor.getInstance().executeCommand(myEditor.getProject(), - new Runnable() { - public void run() { - if (processDrop(dcl, dtde.getLocation(), dtde.getDropAction())) { - myEditor.refreshAndSave(true); - } + () -> { + if (processDrop(dcl, dtde.getLocation(), dtde.getDropAction())) { + myEditor.refreshAndSave(true); } }, UIDesignerBundle.message("command.drop.components"), null); } @@ -221,14 +219,12 @@ class DesignDropTargetListener implements DropTargetListener { if (componentItem != null) { myEditor.getMainProcessor().setInsertFeedbackEnabled(false); new InsertComponentProcessor(myEditor).processComponentInsert(dtde.getLocation(), componentItem); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - PaletteToolWindowManager.getInstance(myEditor).clearActiveItem(); - myEditor.getActiveDecorationLayer().removeFeedback(); - myEditor.getLayeredPane().setCursor(null); - myEditor.getGlassLayer().requestFocus(); - myEditor.getMainProcessor().setInsertFeedbackEnabled(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + PaletteToolWindowManager.getInstance(myEditor).clearActiveItem(); + myEditor.getActiveDecorationLayer().removeFeedback(); + myEditor.getLayeredPane().setCursor(null); + myEditor.getGlassLayer().requestFocus(); + myEditor.getMainProcessor().setInsertFeedbackEnabled(true); }); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DraggedComponentList.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DraggedComponentList.java index 28774bacbf27..21491b723496 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DraggedComponentList.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/DraggedComponentList.java @@ -71,17 +71,15 @@ public class DraggedComponentList implements Transferable, ComponentDragObject { mySelection = FormEditingUtil.getSelectedComponents(editor); // sort selection in correct grid order - Collections.sort(mySelection, new Comparator() { - public int compare(final RadComponent o1, final RadComponent o2) { - if (o1.getParent() == o2.getParent()) { - int result = o1.getConstraints().getRow() - o2.getConstraints().getRow(); - if (result == 0) { - result = o1.getConstraints().getColumn() - o2.getConstraints().getColumn(); - } - return result; + Collections.sort(mySelection, (o1, o2) -> { + if (o1.getParent() == o2.getParent()) { + int result = o1.getConstraints().getRow() - o2.getConstraints().getRow(); + if (result == 0) { + result = o1.getConstraints().getColumn() - o2.getConstraints().getColumn(); } - return 0; + return result; } + return 0; }); RadComponent componentUnderMouse = null; diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridCaptionPanel.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridCaptionPanel.java index 99a982f5acd3..7a4e6f05344f 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridCaptionPanel.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GridCaptionPanel.java @@ -93,11 +93,7 @@ public class GridCaptionPanel extends JPanel implements ComponentSelectionListen @Override public void focusGained(FocusEvent e) { repaint(); // ensure we don't have two repaints of properties panel - one from focus gain and another from click - myAlarm.addRequest(new Runnable() { - public void run() { - editor.fireSelectedComponentChanged(); - } - }, 1000); + myAlarm.addRequest(() -> editor.fireSelectedComponentChanged(), 1000); } @Override public void focusLost(FocusEvent e) { @@ -107,13 +103,9 @@ public class GridCaptionPanel extends JPanel implements ComponentSelectionListen } public static JBColor getGutterColor() { - return new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - Color color = EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.GUTTER_BACKGROUND); - return color == null ? UIUtil.getPanelBackground() : color; - } + return new JBColor(() -> { + Color color = EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.GUTTER_BACKGROUND); + return color == null ? UIUtil.getPanelBackground() : color; }); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java index cb38c5b580c5..f7c67b7a2947 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java @@ -341,13 +341,7 @@ public final class GuiEditor extends JPanel implements DesignerEditorPanelFacade gbc.weighty = 1.0; myScrollPane = ScrollPaneFactory.createScrollPane(myLayeredPane); - myScrollPane.setBackground(new JBColor(new NotNullProducer() { - @NotNull - @Override - public Color produce() { - return EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground(); - } - })); + myScrollPane.setBackground(new JBColor(() -> EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground())); panel.add(myScrollPane, gbc); myHorzCaptionPanel.attachToScrollPane(myScrollPane); myVertCaptionPanel.attachToScrollPane(myScrollPane); @@ -379,12 +373,9 @@ public final class GuiEditor extends JPanel implements DesignerEditorPanelFacade UsageTrigger.trigger("swing-designer.open"); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - DesignerToolWindowManager.getInstance(myProject).bind(GuiEditor.this); - PaletteToolWindowManager.getInstance(myProject).bind(GuiEditor.this); - } + UIUtil.invokeLaterIfNeeded(() -> { + DesignerToolWindowManager.getInstance(myProject).bind(GuiEditor.this); + PaletteToolWindowManager.getInstance(myProject).bind(GuiEditor.this); }); } @@ -659,38 +650,32 @@ public final class GuiEditor extends JPanel implements DesignerEditorPanelFacade private void saveToFile() { LOG.debug("GuiEditor.saveToFile(): group ID=" + myNextSaveGroupId); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - myInsideChange = true; - try { - final XmlWriter writer = new XmlWriter(); - getRootContainer().write(writer); - final String newText = writer.getText(); - final String oldText = myDocument.getText(); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + myInsideChange = true; + try { + final XmlWriter writer = new XmlWriter(); + getRootContainer().write(writer); + final String newText = writer.getText(); + final String oldText = myDocument.getText(); - try { - final ReplaceInfo replaceInfo = findFragmentToChange(oldText, newText); - if (replaceInfo.getStartOffset() == -1) { - // do nothing - texts are equal - } - else { - myDocument.replaceString(replaceInfo.getStartOffset(), replaceInfo.getEndOffset(), replaceInfo.getReplacement()); - } - } - catch (Exception e) { - LOG.error(e); - myDocument.replaceString(0, oldText.length(), newText); - } - } - finally { - myInsideChange = false; - } + try { + final ReplaceInfo replaceInfo = findFragmentToChange(oldText, newText); + if (replaceInfo.getStartOffset() == -1) { + // do nothing - texts are equal } - }); + else { + myDocument.replaceString(replaceInfo.getStartOffset(), replaceInfo.getEndOffset(), replaceInfo.getReplacement()); + } + } + catch (Exception e) { + LOG.error(e); + myDocument.replaceString(0, oldText.length(), newText); + } } - }, "UI Designer Save", myNextSaveGroupId); + finally { + myInsideChange = false; + } + }), "UI Designer Save", myNextSaveGroupId); myNextSaveGroupId = new Object(); fireHierarchyChanged(); @@ -1140,11 +1125,7 @@ public final class GuiEditor extends JPanel implements DesignerEditorPanelFacade if (!GuiEditor.this.ensureEditable()) { return; } - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - public void run() { - FormEditingUtil.deleteSelection(GuiEditor.this); - } - }, UIDesignerBundle.message("command.delete.selection"), null); + CommandProcessor.getInstance().executeCommand(getProject(), () -> FormEditingUtil.deleteSelection(GuiEditor.this), UIDesignerBundle.message("command.delete.selection"), null); } public boolean canDeleteElement(@NotNull final DataContext dataContext) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InplaceEditingLayer.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InplaceEditingLayer.java index 06dbad60f37a..599c7a45679e 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InplaceEditingLayer.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InplaceEditingLayer.java @@ -213,11 +213,9 @@ public final class InplaceEditingLayer extends JComponent{ else { grabFocus(); final JComponent finalComponentToFocus = componentToFocus; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - finalComponentToFocus.requestFocusInWindow(); - myFocusWatcher.install(myInplaceEditorComponent); - } + ApplicationManager.getApplication().invokeLater(() -> { + finalComponentToFocus.requestFocusInWindow(); + myFocusWatcher.install(myInplaceEditorComponent); }); } @@ -251,16 +249,14 @@ public final class InplaceEditingLayer extends JComponent{ if (!myEditor.isUndoRedoInProgress()) { CommandProcessor.getInstance().executeCommand( myInplaceComponent.getProject(), - new Runnable() { - public void run() { - try { - final Object value = myInplaceEditor.getValue(); - myInplaceProperty.setValue(myInplaceComponent, value); - } - catch (Exception ignored) { - } - myEditor.refreshAndSave(true); + () -> { + try { + final Object value = myInplaceEditor.getValue(); + myInplaceProperty.setValue(myInplaceComponent, value); } + catch (Exception ignored) { + } + myEditor.refreshAndSave(true); }, UIDesignerBundle.message("command.set.property.value"), null); } // 2. Remove editor from the layer @@ -353,10 +349,8 @@ public final class InplaceEditingLayer extends JComponent{ return; } // [vova] we need LaterInvocator here to prevent write-access assertions - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - finishInplaceEditing(); - } + ApplicationManager.getApplication().invokeLater(() -> { + finishInplaceEditing(); }, ModalityState.NON_MODAL); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InsertComponentProcessor.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InsertComponentProcessor.java index 2c91b10049b4..f409f02469bb 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InsertComponentProcessor.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/InsertComponentProcessor.java @@ -218,16 +218,14 @@ public final class InsertComponentProcessor extends EventProcessor { return; } ApplicationManager.getApplication().runWriteAction( - new Runnable() { - public void run() { - CreateFieldFix.runImpl(editor.getProject(), - editor.getRootContainer(), - aClass, - insertedComponent.getComponentClassName(), - insertedComponent.getBinding(), - false, // silently skip all errors (if any) - null); - } + () -> { + CreateFieldFix.runImpl(editor.getProject(), + editor.getRootContainer(), + aClass, + insertedComponent.getComponentClassName(), + insertedComponent.getBinding(), + false, // silently skip all errors (if any) + null); } ); } @@ -303,35 +301,33 @@ public final class InsertComponentProcessor extends EventProcessor { if (location.canDrop(dragObject)) { CommandProcessor.getInstance().executeCommand( myEditor.getProject(), - new Runnable() { - public void run() { - createBindingWhenDrop(myEditor, myInsertedComponent, forceBinding); + () -> { + createBindingWhenDrop(myEditor, myInsertedComponent, forceBinding); - final RadComponent[] components = new RadComponent[]{myInsertedComponent}; - location.processDrop(myEditor, components, null, dragObject); + final RadComponent[] components = new RadComponent[]{myInsertedComponent}; + location.processDrop(myEditor, components, null, dragObject); - FormEditingUtil.selectSingleComponent(myEditor, myInsertedComponent); + FormEditingUtil.selectSingleComponent(myEditor, myInsertedComponent); - if (location.getContainer() != null && location.getContainer().isXY()) { - Dimension newSize = myInsertedComponent.getPreferredSize(); - Util.adjustSize(myInsertedComponent.getDelegee(), myInsertedComponent.getConstraints(), newSize); - myInsertedComponent.setSize(newSize); - } - - if (myInsertedComponent.getParent() instanceof RadRootContainer && - myInsertedComponent instanceof RadAtomicComponent) { - GridBuildUtil.convertToGrid(myEditor); - FormEditingUtil.selectSingleComponent(myEditor, myInsertedComponent); - } - - checkBindTopLevelPanel(); - - if (!mySticky) { - PaletteToolWindowManager.getInstance(myEditor).clearActiveItem(); - } - - myEditor.refreshAndSave(false); + if (location.getContainer() != null && location.getContainer().isXY()) { + Dimension newSize = myInsertedComponent.getPreferredSize(); + Util.adjustSize(myInsertedComponent.getDelegee(), myInsertedComponent.getConstraints(), newSize); + myInsertedComponent.setSize(newSize); } + + if (myInsertedComponent.getParent() instanceof RadRootContainer && + myInsertedComponent instanceof RadAtomicComponent) { + GridBuildUtil.convertToGrid(myEditor); + FormEditingUtil.selectSingleComponent(myEditor, myInsertedComponent); + } + + checkBindTopLevelPanel(); + + if (!mySticky) { + PaletteToolWindowManager.getInstance(myEditor).clearActiveItem(); + } + + myEditor.refreshAndSave(false); }, UIDesignerBundle.message("command.insert.component"), null); } myComponentToInsert = null; @@ -384,17 +380,15 @@ public final class InsertComponentProcessor extends EventProcessor { Messages.getQuestionIcon()); if (rc == Messages.CANCEL) return false; if (rc == Messages.YES) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final ModifiableRootModel model = ModuleRootManager.getInstance(myEditor.getModule()).getModifiableModel(); - if (libraryOrderEntry.isModuleLevel()) { - copyModuleLevelLibrary(libraryOrderEntry.getLibrary(), model); - } - else { - model.addLibraryEntry(libraryOrderEntry.getLibrary()); - } - model.commit(); + ApplicationManager.getApplication().runWriteAction(() -> { + final ModifiableRootModel model = ModuleRootManager.getInstance(myEditor.getModule()).getModifiableModel(); + if (libraryOrderEntry.isModuleLevel()) { + copyModuleLevelLibrary(libraryOrderEntry.getLibrary(), model); } + else { + model.addLibraryEntry(libraryOrderEntry.getLibrary()); + } + model.commit(); }); } return true; diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/ListenerNavigateButton.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/ListenerNavigateButton.java index 794dd956b280..79e18a60ca0b 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/ListenerNavigateButton.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/ListenerNavigateButton.java @@ -117,30 +117,28 @@ public class ListenerNavigateButton extends JButton implements ActionListener { return null; } final LocalSearchScope scope = new LocalSearchScope(boundClassFile); - ReferencesSearch.search(boundField, scope).forEach(new Processor() { - public boolean process(final PsiReference ref) { - final PsiElement element = ref.getElement(); - if (element.getParent() instanceof PsiReferenceExpression) { - PsiReferenceExpression refExpr = (PsiReferenceExpression) element.getParent(); - if (refExpr.getParent() instanceof PsiMethodCallExpression) { - PsiMethodCallExpression methodCall = (PsiMethodCallExpression) refExpr.getParent(); - final PsiElement psiElement = refExpr.resolve(); - if (psiElement instanceof PsiMethod) { - PsiMethod method = (PsiMethod) psiElement; - for(EventSetDescriptor eventSetDescriptor: eventSetDescriptors) { - if (Comparing.equal(eventSetDescriptor.getAddListenerMethod().getName(), method.getName())) { - final String eventName = eventSetDescriptor.getName(); - final PsiExpression[] args = methodCall.getArgumentList().getExpressions(); - if (args.length > 0) { - addListenerRef(actionGroup, eventName, args[0]); - } + ReferencesSearch.search(boundField, scope).forEach(ref -> { + final PsiElement element = ref.getElement(); + if (element.getParent() instanceof PsiReferenceExpression) { + PsiReferenceExpression refExpr = (PsiReferenceExpression) element.getParent(); + if (refExpr.getParent() instanceof PsiMethodCallExpression) { + PsiMethodCallExpression methodCall = (PsiMethodCallExpression) refExpr.getParent(); + final PsiElement psiElement = refExpr.resolve(); + if (psiElement instanceof PsiMethod) { + PsiMethod method = (PsiMethod) psiElement; + for(EventSetDescriptor eventSetDescriptor: eventSetDescriptors) { + if (Comparing.equal(eventSetDescriptor.getAddListenerMethod().getName(), method.getName())) { + final String eventName = eventSetDescriptor.getName(); + final PsiExpression[] args = methodCall.getArgumentList().getExpressions(); + if (args.length > 0) { + addListenerRef(actionGroup, eventName, args[0]); } } } } } - return true; } + return true; }); return actionGroup; diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/PasteProcessor.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/PasteProcessor.java index dba3bbb38d72..826e8a6cfa01 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/PasteProcessor.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/PasteProcessor.java @@ -126,22 +126,20 @@ public class PasteProcessor extends EventProcessor { final RadComponent[] componentsToPaste = myComponentsToPaste.toArray(new RadComponent[myComponentsToPaste.size()]); CommandProcessor.getInstance().executeCommand( myEditor.getProject(), - new Runnable() { - public void run() { - location.processDrop(myEditor, componentsToPaste, null, myPastedComponentList); - for(RadComponent c: componentsToPaste) { - FormEditingUtil.iterate(c, new FormEditingUtil.ComponentVisitor() { - public boolean visit(final IComponent component) { - if (component.getBinding() != null) { - InsertComponentProcessor.createBindingField(myEditor, (RadComponent) component); - } - return true; + () -> { + location.processDrop(myEditor, componentsToPaste, null, myPastedComponentList); + for(RadComponent c: componentsToPaste) { + FormEditingUtil.iterate(c, new FormEditingUtil.ComponentVisitor() { + public boolean visit(final IComponent component) { + if (component.getBinding() != null) { + InsertComponentProcessor.createBindingField(myEditor, (RadComponent) component); } - }); - } - FormEditingUtil.selectComponents(myEditor, myComponentsToPaste); - myEditor.refreshAndSave(true); + return true; + } + }); } + FormEditingUtil.selectComponents(myEditor, myComponentsToPaste); + myEditor.refreshAndSave(true); }, UIDesignerBundle.message("command.paste"), null); endPaste(); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/i18n/I18nizeFormQuickFix.java b/plugins/ui-designer/src/com/intellij/uiDesigner/i18n/I18nizeFormQuickFix.java index 88de4b980072..932253a13d11 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/i18n/I18nizeFormQuickFix.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/i18n/I18nizeFormQuickFix.java @@ -79,20 +79,14 @@ public abstract class I18nizeFormQuickFix extends QuickFix { } } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - JavaI18nUtil.createProperty(project, propertiesFiles, dialog.getKey(), dialog.getValue()); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + JavaI18nUtil.createProperty(project, propertiesFiles, dialog.getKey(), dialog.getValue()); } - }, CodeInsightBundle.message("quickfix.i18n.command.name"), project); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), CodeInsightBundle.message("quickfix.i18n.command.name"), project); // saving files is necessary to ensure correct reload of properties files by UI Designer for (PropertiesFile file : propertiesFiles) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/FormSpellCheckingInspection.java b/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/FormSpellCheckingInspection.java index f5a5884b1957..41677c37a0de 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/FormSpellCheckingInspection.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/FormSpellCheckingInspection.java @@ -57,52 +57,49 @@ public class FormSpellCheckingInspection extends StringDescriptorInspection { return; } final SpellCheckerManager manager = SpellCheckerManager.getInstance(module.getProject()); - PlainTextSplitter.getInstance().split(value, TextRange.allOf(value), new Consumer() { - @Override - public void consume(TextRange textRange) { - final String word = textRange.substring(value); - if (manager.hasProblem(word)) { - final List suggestions = manager.getSuggestions(value); - if (suggestions.size() > 0 && prop instanceof IntroStringProperty) { - EditorQuickFixProvider changeToProvider = new EditorQuickFixProvider() { - @Override - public QuickFix createQuickFix(final GuiEditor editor, final RadComponent component) { - return new PopupQuickFix(editor, "Change to...", component) { - @Override - public void run() { - ListPopup popup = JBPopupFactory.getInstance().createListPopup(getPopupStep()); - popup.showUnderneathOf(component.getDelegee()); - } + PlainTextSplitter.getInstance().split(value, TextRange.allOf(value), textRange -> { + final String word = textRange.substring(value); + if (manager.hasProblem(word)) { + final List suggestions = manager.getSuggestions(value); + if (suggestions.size() > 0 && prop instanceof IntroStringProperty) { + EditorQuickFixProvider changeToProvider = new EditorQuickFixProvider() { + @Override + public QuickFix createQuickFix(final GuiEditor editor, final RadComponent component1) { + return new PopupQuickFix(editor, "Change to...", component1) { + @Override + public void run() { + ListPopup popup = JBPopupFactory.getInstance().createListPopup(getPopupStep()); + popup.showUnderneathOf(component1.getDelegee()); + } - @Override - public ListPopupStep getPopupStep() { - return new BaseListPopupStep("Select Replacement", suggestions) { - @Override - public PopupStep onChosen(String selectedValue, boolean finalChoice) { - FormInspectionUtil.updateStringPropertyValue(editor, component, (IntroStringProperty) prop, descriptor, selectedValue); - return FINAL_CHOICE; - } - }; - } - }; - } - }; - EditorQuickFixProvider acceptProvider = new EditorQuickFixProvider() { - @Override - public QuickFix createQuickFix(final GuiEditor editor, RadComponent component) { - return new QuickFix(editor, "Save '" + word + "' to dictionary", component) { - @Override - public void run() { - manager.acceptWordAsCorrect(word, editor.getProject()); - } - }; - } - }; - collector.addError(getID(), component, prop, "Typo in word '" + word + "'", changeToProvider, acceptProvider); - } - else { - collector.addError(getID(), component, prop, "Typo in word '" + word + "'"); - } + @Override + public ListPopupStep getPopupStep() { + return new BaseListPopupStep("Select Replacement", suggestions) { + @Override + public PopupStep onChosen(String selectedValue, boolean finalChoice) { + FormInspectionUtil.updateStringPropertyValue(editor, component1, (IntroStringProperty) prop, descriptor, selectedValue); + return FINAL_CHOICE; + } + }; + } + }; + } + }; + EditorQuickFixProvider acceptProvider = new EditorQuickFixProvider() { + @Override + public QuickFix createQuickFix(final GuiEditor editor, RadComponent component1) { + return new QuickFix(editor, "Save '" + word + "' to dictionary", component1) { + @Override + public void run() { + manager.acceptWordAsCorrect(word, editor.getProject()); + } + }; + } + }; + collector.addError(getID(), component, prop, "Typo in word '" + word + "'", changeToProvider, acceptProvider); + } + else { + collector.addError(getID(), component, prop, "Typo in word '" + word + "'"); } } }); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoButtonGroupInspection.java b/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoButtonGroupInspection.java index 4a3d65da3d7c..6684b8102431 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoButtonGroupInspection.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoButtonGroupInspection.java @@ -124,13 +124,11 @@ public class NoButtonGroupInspection extends BaseFormInspection { buttonsToGroup.add(component); } } - Collections.sort(buttonsToGroup, new Comparator() { - public int compare(final RadComponent o1, final RadComponent o2) { - if (myVerticalGroup) { - return o1.getConstraints().getRow() - o2.getConstraints().getRow(); - } - return o1.getConstraints().getColumn() - o2.getConstraints().getColumn(); + Collections.sort(buttonsToGroup, (o1, o2) -> { + if (myVerticalGroup) { + return o1.getConstraints().getRow() - o2.getConstraints().getRow(); } + return o1.getConstraints().getColumn() - o2.getConstraints().getColumn(); }); // ensure that selected radio buttons are in adjacent cells, and exclude from grouping diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoLabelForInspection.java b/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoLabelForInspection.java index 9b4672341a85..4e54b2a2d1f9 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoLabelForInspection.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/inspections/NoLabelForInspection.java @@ -121,21 +121,19 @@ public class NoLabelForInspection extends BaseFormInspection { if (!myEditor.ensureEditable()) { return; } - Runnable runnable = new Runnable() { - public void run() { - final Palette palette = Palette.getInstance(myEditor.getProject()); - IntrospectedProperty[] props = palette.getIntrospectedProperties(myLabel); - boolean modified = false; - for(IntrospectedProperty prop: props) { - if (prop.getName().equals(SwingProperties.LABEL_FOR) && prop instanceof IntroComponentProperty) { - IntroComponentProperty icp = (IntroComponentProperty) prop; - icp.setValueEx(myLabel, myComponent.getId()); - modified = true; - break; - } + Runnable runnable = () -> { + final Palette palette = Palette.getInstance(myEditor.getProject()); + IntrospectedProperty[] props = palette.getIntrospectedProperties(myLabel); + boolean modified = false; + for(IntrospectedProperty prop: props) { + if (prop.getName().equals(SwingProperties.LABEL_FOR) && prop instanceof IntroComponentProperty) { + IntroComponentProperty icp = (IntroComponentProperty) prop; + icp.setValueEx(myLabel, myComponent.getId()); + modified = true; + break; } - if (modified) myEditor.refreshAndSave(false); } + if (modified) myEditor.refreshAndSave(false); }; CommandProcessor.getInstance().executeCommand(myEditor.getProject(), runnable, UIDesignerBundle.message("inspection.no.label.for.command"), null); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java b/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java index 015e56bba6eb..7819927bc3be 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java @@ -83,69 +83,67 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ } final ArrayList items = new ArrayList(); - DumbService.getInstance(project).runReadActionInSmartMode(new Runnable() { - public void run() { - final CompileScope scope = context.getCompileScope(); - final CompileScope projectScope = context.getProjectCompileScope(); + DumbService.getInstance(project).runReadActionInSmartMode(() -> { + final CompileScope scope = context.getCompileScope(); + final CompileScope projectScope = context.getProjectCompileScope(); - final VirtualFile[] formFiles = projectScope.getFiles(StdFileTypes.GUI_DESIGNER_FORM, true); - final CompilerManager compilerManager = CompilerManager.getInstance(project); - final BindingsCache bindingsCache = new BindingsCache(project); + final VirtualFile[] formFiles = projectScope.getFiles(StdFileTypes.GUI_DESIGNER_FORM, true); + final CompilerManager compilerManager = CompilerManager.getInstance(project); + final BindingsCache bindingsCache = new BindingsCache(project); - try { - final HashMap class2form = new HashMap(); + try { + final HashMap class2form = new HashMap(); - for (final VirtualFile formFile : formFiles) { - if (compilerManager.isExcludedFromCompilation(formFile)) { - continue; - } - - final String classToBind; - try { - classToBind = bindingsCache.getBoundClassName(formFile); - } - catch (AlienFormFileException e) { - // ignore non-IDEA forms - continue; - } - catch (Exception e) { - addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), formFile); - continue; - } - - if (classToBind == null) { - continue; - } - - final VirtualFile sourceFile = findSourceFile(context, formFile, classToBind); - if (sourceFile == null) { - if (scope.belongs(formFile.getUrl())) { - addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), formFile); - } - continue; - } - - final boolean inScope = scope.belongs(sourceFile.getUrl()) || scope.belongs(formFile.getUrl()); - - final VirtualFile alreadyProcessedForm = class2form.get(classToBind); - if (alreadyProcessedForm != null) { - if (inScope) { - addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", classToBind, alreadyProcessedForm.getPresentableUrl())), formFile); - } - continue; - } - class2form.put(classToBind, formFile); - - if (!inScope) { - continue; - } - - items.add(new MyInstrumentationItem(sourceFile, formFile)); + for (final VirtualFile formFile : formFiles) { + if (compilerManager.isExcludedFromCompilation(formFile)) { + continue; } + + final String classToBind; + try { + classToBind = bindingsCache.getBoundClassName(formFile); + } + catch (AlienFormFileException e) { + // ignore non-IDEA forms + continue; + } + catch (Exception e) { + addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), formFile); + continue; + } + + if (classToBind == null) { + continue; + } + + final VirtualFile sourceFile = findSourceFile(context, formFile, classToBind); + if (sourceFile == null) { + if (scope.belongs(formFile.getUrl())) { + addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), formFile); + } + continue; + } + + final boolean inScope = scope.belongs(sourceFile.getUrl()) || scope.belongs(formFile.getUrl()); + + final VirtualFile alreadyProcessedForm = class2form.get(classToBind); + if (alreadyProcessedForm != null) { + if (inScope) { + addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", classToBind, alreadyProcessedForm.getPresentableUrl())), formFile); + } + continue; + } + class2form.put(classToBind, formFile); + + if (!inScope) { + continue; + } + + items.add(new MyInstrumentationItem(sourceFile, formFile)); } - finally { - bindingsCache.close(); - } + } + finally { + bindingsCache.close(); } }); @@ -173,57 +171,47 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ final VirtualFile formFile = item.getFormFile(); if (GuiDesignerConfiguration.getInstance(project).COPY_FORMS_RUNTIME_TO_OUTPUT) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final Module module = ModuleUtilCore.findModuleForFile(formFile, project); - if (module != null && !processedModules.contains(module)) { - processedModules.add(module); - final String moduleOutputPath = CompilerPaths.getModuleOutputPath(module, false); - try { - if (moduleOutputPath != null) { - filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(moduleOutputPath, false)); - } - final String testsOutputPath = CompilerPaths.getModuleOutputPath(module, true); - if (testsOutputPath != null && !testsOutputPath.equals(moduleOutputPath)) { - filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(testsOutputPath, false)); - } + ApplicationManager.getApplication().runReadAction(() -> { + final Module module = ModuleUtilCore.findModuleForFile(formFile, project); + if (module != null && !processedModules.contains(module)) { + processedModules.add(module); + final String moduleOutputPath = CompilerPaths.getModuleOutputPath(module, false); + try { + if (moduleOutputPath != null) { + filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(moduleOutputPath, false)); } - catch (IOException e) { - addError( - context, - new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.copy.gui.designer.form.runtime", - module.getName(), e.toString())), - null - ); + final String testsOutputPath = CompilerPaths.getModuleOutputPath(module, true); + if (testsOutputPath != null && !testsOutputPath.equals(moduleOutputPath)) { + filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(testsOutputPath, false)); } } + catch (IOException e) { + addError( + context, + new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.copy.gui.designer.form.runtime", + module.getName(), e.toString())), + null + ); + } } }); } - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiDocumentManager.getInstance(project).commitAllDocuments(); - generator.generate(formFile); - final ArrayList errors = generator.getErrors(); - if (errors.size() == 0) { - compiledItems.add(item); - } - else { - for (final FormErrorInfo e : errors) { - addError(context, e, formFile); - } - } - } - }); + ApplicationManager.getApplication().invokeAndWait(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(project).commitAllDocuments(); + generator.generate(formFile); + final ArrayList errors = generator.getErrors(); + if (errors.size() == 0) { + compiledItems.add(item); + } + else { + for (final FormErrorInfo e : errors) { + addError(context, e, formFile); } - }, "", null); - FileDocumentManager.getInstance().saveAllDocuments(); - } + } + }), "", null); + FileDocumentManager.getInstance().saveAllDocuments(); }, ModalityState.NON_MODAL); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java b/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java index 21e72aa42078..23541f2c8c8c 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java @@ -551,11 +551,7 @@ public final class FormSourceCodeGenerator { final LwIntrospectedProperty[] introspectedProperties = component.getAssignedIntrospectedProperties(); // see SCR #35990 - Arrays.sort(introspectedProperties, new Comparator() { - public int compare(LwIntrospectedProperty p1, LwIntrospectedProperty p2) { - return p1.getName().compareTo(p2.getName()); - } - }); + Arrays.sort(introspectedProperties, (p1, p2) -> p1.getName().compareTo(p2.getName())); for (final LwIntrospectedProperty property : introspectedProperties) { if (property instanceof LwIntroComponentProperty) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java index 042860a3f9f1..7f31d0b6a4c7 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java @@ -921,12 +921,10 @@ public final class PropertyInspectorTable extends Table implements DataProvider{ return false; } final Ref result = new Ref(Boolean.FALSE); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - result.set(setSelectionValue(property, newValue)); + CommandProcessor.getInstance().executeCommand(myProject, () -> { + result.set(setSelectionValue(property, newValue)); - editor.refreshAndSave(false); - } + editor.refreshAndSave(false); }, UIDesignerBundle.message("command.set.property.value"), null); retVal = result.get().booleanValue(); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/BindingEditor.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/BindingEditor.java index c7547c7ff710..83cb05029e79 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/BindingEditor.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/BindingEditor.java @@ -65,12 +65,8 @@ public final class BindingEditor extends ComboBoxPropertyEditor { if (!myCbx.isPopupVisible()) { fireEditingCancelled(); SwingUtilities.invokeLater( - new Runnable(){ - public void run(){ - DesignerToolWindowManager.getInstance(DesignerToolWindowManager.getInstance(project).getActiveFormEditor()) - .getPropertyInspector().requestFocus(); - } - } + () -> DesignerToolWindowManager.getInstance(DesignerToolWindowManager.getInstance(project).getActiveFormEditor()) + .getPropertyInspector().requestFocus() ); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/FontEditorDialog.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/FontEditorDialog.java index 139d801810cc..a26cd5bfce66 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/FontEditorDialog.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/FontEditorDialog.java @@ -153,11 +153,7 @@ public class FontEditorDialog extends DialogWrapper { result.add(FontDescriptor.fromSwingFont((String) key)); } } - Collections.sort(result, new Comparator() { - public int compare(final FontDescriptor o1, final FontDescriptor o2) { - return o1.getSwingFont().compareTo(o2.getSwingFont()); - } - }); + Collections.sort(result, (o1, o2) -> o1.getSwingFont().compareTo(o2.getSwingFont())); return result.toArray(new FontDescriptor[result.size()]); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditor.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditor.java index 4b8da912f617..fefaf998a807 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditor.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditor.java @@ -182,28 +182,26 @@ public final class StringEditor extends PropertyEditor { CommandProcessor.getInstance().executeCommand( myProject, - new Runnable() { - public void run() { - if (!guiEditor.ensureEditable()) { - return; - } - if (!dialog.showAndGet()) { - return; - } - - // 2. Apply new value - final StringDescriptor descriptor = dialog.getDescriptor(); - if (descriptor == null) { - return; - } - setValue(descriptor); - fireValueCommitted(true, false); - if (myProperty != null) { - myProperty.refreshValue(myComponent); - } - guiEditor.refreshAndSave(false); + () -> { + if (!guiEditor.ensureEditable()) { + return; } - }, UIDesignerBundle.message("command.edit.string.property"), null); + if (!dialog.showAndGet()) { + return; + } + + // 2. Apply new value + final StringDescriptor descriptor = dialog.getDescriptor(); + if (descriptor == null) { + return; + } + setValue(descriptor); + fireValueCommitted(true, false); + if (myProperty != null) { + myProperty.refreshValue(myComponent); + } + guiEditor.refreshAndSave(false); + }, UIDesignerBundle.message("command.edit.string.property"), null); } } } \ No newline at end of file diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditorDialog.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditorDialog.java index 26e5765ff931..a59e127fdda9 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditorDialog.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/editors/string/StringEditorDialog.java @@ -171,29 +171,25 @@ public final class StringEditorDialog extends DialogWrapper{ final String newKeyName1 = newKeyName; CommandProcessor.getInstance().executeCommand( module.getProject(), - new Runnable() { - public void run() { - UndoUtil.markPsiFileForUndo(formFile); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiDocumentManager.getInstance(module.getProject()).commitAllDocuments(); - try { - if (newKeyName1 != null) { - propFile.addProperty(newKeyName1, editedValue); - } - else { - final IProperty propertyByKey = propFile.findPropertyByKey(descriptor.getKey()); - if (propertyByKey != null) { - propertyByKey.setValue(editedValue); - } - } - } - catch (IncorrectOperationException e) { - LOG.error(e); + () -> { + UndoUtil.markPsiFileForUndo(formFile); + ApplicationManager.getApplication().runWriteAction(() -> { + PsiDocumentManager.getInstance(module.getProject()).commitAllDocuments(); + try { + if (newKeyName1 != null) { + propFile.addProperty(newKeyName1, editedValue); + } + else { + final IProperty propertyByKey1 = propFile.findPropertyByKey(descriptor.getKey()); + if (propertyByKey1 != null) { + propertyByKey1.setValue(editedValue); } } - }); - } + } + catch (IncorrectOperationException e) { + LOG.error(e); + } + }); }, UIDesignerBundle.message("command.update.property"), null); return newKeyName; } @@ -204,19 +200,13 @@ public final class StringEditorDialog extends DialogWrapper{ private static Collection findPropertyReferences(final Property pproperty, final Module module) { final Collection references = Collections.synchronizedList(new ArrayList()); ProgressManager.getInstance().runProcessWithProgressSynchronously( - new Runnable() { - public void run() { - ReferencesSearch.search(pproperty).forEach(new Processor() { - public boolean process(final PsiReference psiReference) { - PsiMethod method = PsiTreeUtil.getParentOfType(psiReference.getElement(), PsiMethod.class); - if (method == null || !AsmCodeGenerator.SETUP_METHOD_NAME.equals(method.getName())) { - references.add(psiReference); - } - return true; - } - }); + (Runnable)() -> ReferencesSearch.search(pproperty).forEach(psiReference -> { + PsiMethod method = PsiTreeUtil.getParentOfType(psiReference.getElement(), PsiMethod.class); + if (method == null || !AsmCodeGenerator.SETUP_METHOD_NAME.equals(method.getName())) { + references.add(psiReference); } - }, UIDesignerBundle.message("edit.text.searching.references"), false, module.getProject() + return true; + }), UIDesignerBundle.message("edit.text.searching.references"), false, module.getProject() ); return references; } @@ -252,20 +242,16 @@ public final class StringEditorDialog extends DialogWrapper{ } CommandProcessor.getInstance().executeCommand( bundle.getProject(), - new Runnable() { - public void run() { - UndoUtil.markPsiFileForUndo(formFile); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - bundle.addProperty(name, value); - } - catch (IncorrectOperationException e1) { - LOG.error(e1); - } - } - }); - } + () -> { + UndoUtil.markPsiFileForUndo(formFile); + ApplicationManager.getApplication().runWriteAction(() -> { + try { + bundle.addProperty(name, value); + } + catch (IncorrectOperationException e1) { + LOG.error(e1); + } + }); }, UIDesignerBundle.message("command.create.property"), null); return true; } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/BindingProperty.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/BindingProperty.java index 70d7d3017a95..9d8870f937b4 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/BindingProperty.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/BindingProperty.java @@ -236,24 +236,20 @@ public final class BindingProperty extends Property { return; } ApplicationManager.getApplication().runWriteAction( - new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand( - project, - new Runnable() { - public void run() { - try { - oldBindingField.delete(); - } - catch (IncorrectOperationException e) { - Messages.showErrorDialog(project, UIDesignerBundle.message("error.cannot.delete.unused.field", e.getMessage()), - CommonBundle.getErrorTitle()); - } - } - }, - UIDesignerBundle.message("command.delete.unused.field"), undoGroupId - ); - } + () -> { + CommandProcessor.getInstance().executeCommand( + project, + () -> { + try { + oldBindingField.delete(); + } + catch (IncorrectOperationException e) { + Messages.showErrorDialog(project, UIDesignerBundle.message("error.cannot.delete.unused.field", e.getMessage()), + CommonBundle.getErrorTitle()); + } + }, + UIDesignerBundle.message("command.delete.unused.field"), undoGroupId + ); } ); } @@ -261,18 +257,16 @@ public final class BindingProperty extends Property { private static boolean isFieldUnreferenced(final PsiField field) { try { - return ReferencesSearch.search(field).forEach(new Processor() { - public boolean process(final PsiReference t) { - PsiFile f = t.getElement().getContainingFile(); - if (f != null && f.getFileType().equals(StdFileTypes.GUI_DESIGNER_FORM)) { - return true; - } - PsiMethod method = PsiTreeUtil.getParentOfType(t.getElement(), PsiMethod.class); - if (method != null && method.getName().equals(AsmCodeGenerator.SETUP_METHOD_NAME)) { - return true; - } - return false; + return ReferencesSearch.search(field).forEach(t -> { + PsiFile f = t.getElement().getContainingFile(); + if (f != null && f.getFileType().equals(StdFileTypes.GUI_DESIGNER_FORM)) { + return true; } + PsiMethod method = PsiTreeUtil.getParentOfType(t.getElement(), PsiMethod.class); + if (method != null && method.getName().equals(AsmCodeGenerator.SETUP_METHOD_NAME)) { + return true; + } + return false; }); } catch (IndexNotReadyException e) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/CustomCreateProperty.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/CustomCreateProperty.java index d9b22102cb53..9e94393c4e8c 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/CustomCreateProperty.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/CustomCreateProperty.java @@ -145,40 +145,32 @@ public class CustomCreateProperty extends Property { final Ref refMethod = new Ref(); CommandProcessor.getInstance().executeCommand( aClass.getProject(), - new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); - try { - PsiMethod method = factory.createMethodFromText("private void " + - AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME + - "() { \n // TODO: place custom component creation code here \n }", aClass); - final PsiMethod psiMethod = (PsiMethod)aClass.add(method); - refMethod.set(SmartPointerManager.getInstance(aClass.getProject()).createSmartPsiElementPointer(psiMethod)); - CodeStyleManager.getInstance(aClass.getProject()).reformat(psiMethod); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + () -> ApplicationManager.getApplication().runWriteAction(() -> { + PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); + try { + PsiMethod method = factory.createMethodFromText("private void " + + AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME + + "() { \n // TODO: place custom component creation code here \n }", aClass); + final PsiMethod psiMethod = (PsiMethod)aClass.add(method); + refMethod.set(SmartPointerManager.getInstance(aClass.getProject()).createSmartPsiElementPointer(psiMethod)); + CodeStyleManager.getInstance(aClass.getProject()).reformat(psiMethod); } - }, null, null + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), null, null ); if (!refMethod.isNull()) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final PsiMethod element = (PsiMethod) refMethod.get().getElement(); - if (element != null) { - final PsiCodeBlock body = element.getBody(); - assert body != null; - final PsiComment comment = PsiTreeUtil.getChildOfType(body, PsiComment.class); - if (comment != null) { - new OpenFileDescriptor(comment.getProject(), vFile, - comment.getTextOffset()).navigate(true); - } + SwingUtilities.invokeLater(() -> { + final PsiMethod element = (PsiMethod) refMethod.get().getElement(); + if (element != null) { + final PsiCodeBlock body = element.getBody(); + assert body != null; + final PsiComment comment = PsiTreeUtil.getChildOfType(body, PsiComment.class); + if (comment != null) { + new OpenFileDescriptor(comment.getProject(), vFile, + comment.getTextOffset()).navigate(true); } } }); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/ChangeFieldTypeFix.java b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/ChangeFieldTypeFix.java index 014d282649ad..da3ba9c06a7d 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/ChangeFieldTypeFix.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/ChangeFieldTypeFix.java @@ -48,25 +48,18 @@ public class ChangeFieldTypeFix extends QuickFix { final PsiFile psiFile = myField.getContainingFile(); if (psiFile == null) return; if (!FileModificationService.getInstance().preparePsiElementForWrite(psiFile)) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(myField.getProject(), new Runnable() { - public void run() { - try { - final PsiManager manager = myField.getManager(); - myField.getTypeElement().replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createTypeElement(myNewType)); - } - catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Messages.showErrorDialog(myEditor, UIDesignerBundle.message("error.cannot.change.field.type", myField.getName(), e.getMessage()), - CommonBundle.getErrorTitle()); - } - }); - } - } - }, getName(), null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(myField.getProject(), () -> { + try { + final PsiManager manager = myField.getManager(); + myField.getTypeElement().replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createTypeElement(myNewType)); + } + catch (final IncorrectOperationException e) { + ApplicationManager.getApplication().invokeLater( + () -> Messages.showErrorDialog(myEditor, UIDesignerBundle.message("error.cannot.change.field.type", myField.getName(), e.getMessage()), + CommonBundle.getErrorTitle())); + } + }, getName(), null); }); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateClassToBindFix.java b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateClassToBindFix.java index af7756b76bb5..e444426d5b35 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateClassToBindFix.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateClassToBindFix.java @@ -65,63 +65,51 @@ public final class CreateClassToBindFix extends QuickFix{ } ApplicationManager.getApplication().runWriteAction( - new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand( - project, - new Runnable() { - public void run() { - // 1. Create all necessary packages - final int indexOfLastDot = myClassName.lastIndexOf('.'); - final String packageName = myClassName.substring(0, indexOfLastDot != -1 ? indexOfLastDot : 0); - final PsiDirectory psiDirectory; - if(packageName.length() > 0){ - final PackageWrapper packageWrapper = new PackageWrapper(PsiManager.getInstance(project), packageName); - try { - psiDirectory = RefactoringUtil.createPackageDirectoryInSourceRoot(packageWrapper, sourceRoot); - LOG.assertTrue(psiDirectory != null); - } - catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable(){ - public void run() { - Messages.showErrorDialog( - myEditor, - UIDesignerBundle.message("error.cannot.create.package", packageName, e.getMessage()), - CommonBundle.getErrorTitle() - ); - } - }); - return; - } - } - else{ - psiDirectory = PsiManager.getInstance(project).findDirectory(sourceRoot); - LOG.assertTrue(psiDirectory != null); - } - - // 2. Create class in the package - try { - final String name = myClassName.substring(indexOfLastDot != -1 ? indexOfLastDot + 1 : 0); - final PsiClass aClass = JavaDirectoryService.getInstance().createClass(psiDirectory, name); - createBoundFields(aClass); - } - catch (final IncorrectOperationException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - Messages.showErrorDialog( - myEditor, - UIDesignerBundle.message("error.cannot.create.class", packageName, e.getMessage()), - CommonBundle.getErrorTitle() - ); - } - }); - } + () -> { + CommandProcessor.getInstance().executeCommand( + project, + () -> { + // 1. Create all necessary packages + final int indexOfLastDot = myClassName.lastIndexOf('.'); + final String packageName = myClassName.substring(0, indexOfLastDot != -1 ? indexOfLastDot : 0); + final PsiDirectory psiDirectory; + if(packageName.length() > 0){ + final PackageWrapper packageWrapper = new PackageWrapper(PsiManager.getInstance(project), packageName); + try { + psiDirectory = RefactoringUtil.createPackageDirectoryInSourceRoot(packageWrapper, sourceRoot); + LOG.assertTrue(psiDirectory != null); } - }, - getName(), - null - ); - } + catch (final IncorrectOperationException e) { + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog( + myEditor, + UIDesignerBundle.message("error.cannot.create.package", packageName, e.getMessage()), + CommonBundle.getErrorTitle() + )); + return; + } + } + else{ + psiDirectory = PsiManager.getInstance(project).findDirectory(sourceRoot); + LOG.assertTrue(psiDirectory != null); + } + + // 2. Create class in the package + try { + final String name = myClassName.substring(indexOfLastDot != -1 ? indexOfLastDot + 1 : 0); + final PsiClass aClass = JavaDirectoryService.getInstance().createClass(psiDirectory, name); + createBoundFields(aClass); + } + catch (final IncorrectOperationException e) { + ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog( + myEditor, + UIDesignerBundle.message("error.cannot.create.class", packageName, e.getMessage()), + CommonBundle.getErrorTitle() + )); + } + }, + getName(), + null + ); } ); } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateFieldFix.java b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateFieldFix.java index 758065c943fe..b37ecbe59ed5 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateFieldFix.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/CreateFieldFix.java @@ -101,17 +101,11 @@ public final class CreateFieldFix extends QuickFix{ CommandProcessor.getInstance().executeCommand( project, - new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction( - new Runnable() { - public void run() { - createField(project, fieldClass, fieldName, boundClass, showErrors, rootContainer); - } - } - ); + () -> ApplicationManager.getApplication().runWriteAction( + () -> { + createField(project, fieldClass, fieldName, boundClass, showErrors, rootContainer); } - }, + ), UIDesignerBundle.message("command.create.field"), undoGroupId ); @@ -151,15 +145,11 @@ public final class CreateFieldFix extends QuickFix{ catch (final IncorrectOperationException exc) { if (showErrors) { ApplicationManager.getApplication().invokeLater( - new Runnable() { - public void run() { - Messages.showErrorDialog( - project, - UIDesignerBundle.message("error.cannot.create.field.reason", fieldName, exc.getMessage()), - CommonBundle.getErrorTitle() - ); - } - } + () -> Messages.showErrorDialog( + project, + UIDesignerBundle.message("error.cannot.create.field.reason", fieldName, exc.getMessage()), + CommonBundle.getErrorTitle() + ) ); } } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/QuickFixManager.java b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/QuickFixManager.java index 62269b3ecbdd..377fcfaca844 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/QuickFixManager.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/quickFixes/QuickFixManager.java @@ -277,15 +277,8 @@ public abstract class QuickFixManager { return ((PopupQuickFix) selectedValue.second).getPopupStep(); } if (finalChoice || !myShowSuppresses) { - return doFinalStep(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(myEditor.getProject(), new Runnable() { - public void run() { - selectedValue.second.run(); - } - }, selectedValue.second.getName(), null); - } - }); + return doFinalStep( + () -> CommandProcessor.getInstance().executeCommand(myEditor.getProject(), () -> selectedValue.second.run(), selectedValue.second.getName(), null)); } if (selectedValue.first.getInspectionId() != null && selectedValue.second.getComponent() != null && !(selectedValue.second instanceof SuppressFix)) { diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/CreateSnapShotAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/CreateSnapShotAction.java index 6ecb61920100..eb9b154cb9a9 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/CreateSnapShotAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/CreateSnapShotAction.java @@ -151,25 +151,19 @@ public class CreateSnapShotAction extends AnAction { if (rc == Messages.NO) return; final ApplicationConfiguration appConfig = (ApplicationConfiguration) snapshotConfiguration.getConfiguration(); final SnapShooterConfigurationSettings settings = SnapShooterConfigurationSettings.get(appConfig); - settings.setNotifyRunnable(new Runnable() { - public void run() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.prepare.notice"), - UIDesignerBundle.message("snapshot.title"), Messages.getInformationIcon()); - try { - client.connect(settings.getLastPort()); - } - catch(IOException ex) { - Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.connection.error"), - UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon()); - return; - } - runSnapShooterSession(client, project, dir, view); - } - }); + settings.setNotifyRunnable(() -> SwingUtilities.invokeLater(() -> { + Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.prepare.notice"), + UIDesignerBundle.message("snapshot.title"), Messages.getInformationIcon()); + try { + client.connect(settings.getLastPort()); } - }); + catch(IOException ex) { + Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.connection.error"), + UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon()); + return; + } + runSnapShooterSession(client, project, dir, view); + })); try { ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), snapshotConfiguration).buildAndExecute(); @@ -199,14 +193,12 @@ public class CreateSnapShotAction extends AnAction { if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) { final int id = dlg.getSelectedComponentId(); final Ref result = new Ref(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - try { - result.set(client.createSnapshot(id)); - } - catch (Exception ex) { - result.set(ex); - } + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + try { + result.set(client.createSnapshot(id)); + } + catch (Exception ex) { + result.set(ex); } }, UIDesignerBundle.message("progress.creating.snapshot"), false, project); @@ -222,25 +214,21 @@ public class CreateSnapShotAction extends AnAction { if (snapshot != null) { final String snapshot1 = snapshot; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - try { - PsiFile formFile = PsiFileFactory.getInstance(dir.getProject()) - .createFileFromText(dlg.getFormName() + GuiFormFileType.DOT_DEFAULT_EXTENSION, snapshot1); - formFile = (PsiFile)dir.add(formFile); - formFile.getVirtualFile().setCharset(CharsetToolkit.UTF8_CHARSET); - formFile.getViewProvider().getDocument().setText(snapshot1); - view.selectElement(formFile); - } - catch (IncorrectOperationException ex) { - Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.save.error", ex.getMessage()), - UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon()); - } - } - }, "", null); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> { + try { + PsiFile formFile = PsiFileFactory.getInstance(dir.getProject()) + .createFileFromText(dlg.getFormName() + GuiFormFileType.DOT_DEFAULT_EXTENSION, snapshot1); + formFile = (PsiFile)dir.add(formFile); + formFile.getVirtualFile().setCharset(CharsetToolkit.UTF8_CHARSET); + formFile.getViewProvider().getDocument().setText(snapshot1); + view.selectElement(formFile); + } + catch (IncorrectOperationException ex) { + Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.save.error", ex.getMessage()), + UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon()); + } + }, "", null); }); } } @@ -483,14 +471,12 @@ public class CreateSnapShotAction extends AnAction { final SnapShotRemoteComponent rc = (SnapShotRemoteComponent) myComponentTree.getSelectionPath().getLastPathComponent(); assert rc != null; final Ref err = new Ref(); - Runnable runnable = new Runnable() { - public void run() { - try { - collectUnknownLayoutManagerClasses(project, rc, layoutManagerClasses); - } - catch (IOException e) { - err.set(e); - } + Runnable runnable = () -> { + try { + collectUnknownLayoutManagerClasses(project, rc, layoutManagerClasses); + } + catch (IOException e) { + err.set(e); } }; if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/wizard/DataBindingWizard.java b/plugins/ui-designer/src/com/intellij/uiDesigner/wizard/DataBindingWizard.java index dff8a97d1a0a..13a44d1fe430 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/wizard/DataBindingWizard.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/wizard/DataBindingWizard.java @@ -59,27 +59,21 @@ public final class DataBindingWizard extends AbstractWizard { protected void doOKAction() { CommandProcessor.getInstance().executeCommand( myProject, - new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction( - new Runnable() { - public void run() { - try { - Generator.generateDataBindingMethods(myData); - DataBindingWizard.super.doOKAction(); - } - catch (Generator.MyException exc) { - Messages.showErrorDialog( - getContentPane(), - exc.getMessage(), - CommonBundle.getErrorTitle() - ); - } - } - } - ); + () -> ApplicationManager.getApplication().runWriteAction( + () -> { + try { + Generator.generateDataBindingMethods(myData); + DataBindingWizard.super.doOKAction(); + } + catch (Generator.MyException exc) { + Messages.showErrorDialog( + getContentPane(), + exc.getMessage(), + CommonBundle.getErrorTitle() + ); + } } - }, + ), "", null ); diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java index a57e4d078508..093b014a53e3 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/binding/FormEnumUsageTest.java @@ -56,17 +56,14 @@ public class FormEnumUsageTest extends PsiTestCase { public void testEnumUsage() throws IncorrectOperationException { LanguageLevelProjectExtension.getInstance(myJavaFacade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - try { - createFile(myModule, myTestProjectRoot, "PropEnum.java", "public enum PropEnum { valueA, valueB }"); - createFile(myModule, myTestProjectRoot, "CustomComponent.java", - "public class CustomComponent extends JLabel { private PropEnum e; public PropEnum getE() { return e; } public void setE(E newE) { e = newE; } }"); - } - catch (Exception e) { - fail(e.getMessage()); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + try { + createFile(myModule, myTestProjectRoot, "PropEnum.java", "public enum PropEnum { valueA, valueB }"); + createFile(myModule, myTestProjectRoot, "CustomComponent.java", + "public class CustomComponent extends JLabel { private PropEnum e; public PropEnum getE() { return e; } public void setE(E newE) { e = newE; } }"); + } + catch (Exception e) { + fail(e.getMessage()); } }, "", null); diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java index 358f381c9f4a..a8216d447945 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java @@ -129,12 +129,7 @@ public class AsmCodeGeneratorTest extends TestCase { finally { classStream.close(); FileUtil.delete(classFile); - final File[] inners = new File(tmpPath).listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.startsWith(className + "$") && name.endsWith(".class"); - } - }); + final File[] inners = new File(tmpPath).listFiles((dir, name) -> name.startsWith(className + "$") && name.endsWith(".class")); if (inners != null) { for (File file : inners) FileUtil.delete(file); } diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java index 98bf25a3aa7b..5295305f32cc 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java @@ -89,20 +89,14 @@ public class FormSourceCodeGeneratorTest extends PsiTestCase { private void doTest() throws IOException { final VirtualFile form = myTestProjectRoot.findChild("Test.form"); assertNotNull(form); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - try { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myGenerator.generate(form); - } - }); - } - catch (Exception e) { - fail(e.getMessage()); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + try { + ApplicationManager.getApplication().runWriteAction(() -> { + myGenerator.generate(form); + }); + } + catch (Exception e) { + fail(e.getMessage()); } }, "", null); diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/CompletionLists.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/CompletionLists.java index bfd8a9bdb612..5cc9ddc3835f 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/CompletionLists.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/CompletionLists.java @@ -69,14 +69,11 @@ public class CompletionLists { "self" )); - private static final com.intellij.util.Function FUNCTION_MAPPING = new com.intellij.util.Function() { - @Override - public Lookup fun(String s) { - if (s.equals("processing-instruction")) { - return new FunctionLookup(s, s + "(pi-target?)"); - } else { - return new FunctionLookup(s, s + "()"); - } + private static final com.intellij.util.Function FUNCTION_MAPPING = s -> { + if (s.equals("processing-instruction")) { + return new FunctionLookup(s, s + "(pi-target?)"); + } else { + return new FunctionLookup(s, s + "()"); } }; diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/XPathCompletionContributor.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/XPathCompletionContributor.java index 5710cf8d6fc9..afcd4aa86ae9 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/XPathCompletionContributor.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/completion/XPathCompletionContributor.java @@ -92,11 +92,8 @@ public class XPathCompletionContributor extends CompletionContributor { if (namespaceContext != null) { final String prefixForURI = namespaceContext.getPrefixForURI(XPath2Type.XMLSCHEMA_NS, parent.getXPathContext().getContextElement()); if (prefixForURI != null && prefixForURI.length() > 0) { - addResult(result, ContainerUtil.map(XPath2Type.SchemaType.listSchemaTypes(), new Function() { - @Override - public Lookup fun(XPath2Type type) { - return new MyLookup(prefixForURI + ":" + type.getQName().getLocalPart()); - } + addResult(result, ContainerUtil.map(XPath2Type.SchemaType.listSchemaTypes(), type -> { + return new MyLookup(prefixForURI + ":" + type.getQName().getLocalPart()); }), parameters.getPosition(), parameters.getOffset()); } } @@ -109,11 +106,8 @@ public class XPathCompletionContributor extends CompletionContributor { final QName qName = parent.getXPathContext().getQName(parent); if (qName != null && qName.getNamespaceURI().equals(XPath2Type.XMLSCHEMA_NS)) { - addResult(result, ContainerUtil.map(XPath2Type.SchemaType.listSchemaTypes(), new Function() { - @Override - public Lookup fun(XPath2Type type) { - return new MyLookup(type.getQName().getLocalPart()); - } + addResult(result, ContainerUtil.map(XPath2Type.SchemaType.listSchemaTypes(), type -> { + return new MyLookup(type.getQName().getLocalPart()); }), parameters.getPosition(), parameters.getOffset()); } } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/context/ContextProvider.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/context/ContextProvider.java index 6b2fb3697269..bd88fe37e976 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/context/ContextProvider.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/context/ContextProvider.java @@ -236,15 +236,12 @@ public abstract class ContextProvider { // Another (possibly perferred) solution might be to make org.intellij.lang.xpath.xslt.impl.XsltImplicitUsagesProvider run // unconditionally or - even better - pull its functionality into the platform. if (flag == null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (file.getUserData(XML_FILE_WITH_XPATH_INJECTTION) == null) { - file.putUserData(XML_FILE_WITH_XPATH_INJECTTION, Boolean.TRUE); - // TODO workaround for highlighting tests - if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { - DaemonCodeAnalyzer.getInstance(file.getProject()).restart(file); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (file.getUserData(XML_FILE_WITH_XPATH_INJECTTION) == null) { + file.putUserData(XML_FILE_WITH_XPATH_INJECTTION, Boolean.TRUE); + // TODO workaround for highlighting tests + if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { + DaemonCodeAnalyzer.getInstance(file.getProject()).restart(file); } } }); diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/validation/inspections/ImplicitTypeConversion.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/validation/inspections/ImplicitTypeConversion.java index c9ccaab1c61f..b6bd051b04a5 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/validation/inspections/ImplicitTypeConversion.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/validation/inspections/ImplicitTypeConversion.java @@ -229,14 +229,12 @@ public class ImplicitTypeConversion extends XPathInspection { public void setEnabled(final boolean enabled) { super.setEnabled(enabled); - new Alarm().addRequest(new Runnable() { - public void run() { - for (int i = 0; i < matrix.length; i++) { - JCheckBox[] row = matrix[i]; - for (int j = 0; j < row.length; j++) { - JCheckBox to = row[j]; - to.setEnabled(enabled && j != i + 1); - } + new Alarm().addRequest(() -> { + for (int i = 0; i < matrix.length; i++) { + JCheckBox[] row = matrix[i]; + for (int j = 0; j < row.length; j++) { + JCheckBox to = row[j]; + to.setEnabled(enabled && j != i + 1); } } }, 200); diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java index 41593b1c1f6d..03f181411415 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/AssociationsEditor.java @@ -80,22 +80,14 @@ class AssociationsEditor { myTree.setCellRenderer(new MyNodeRenderer(myManager)); new TreeSpeedSearch(myTree); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (oldState == null) { - expandTree(treeModel); - } - else { - oldState.applyTo(myTree); - } - } - }); + SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().invokeLater(() -> { + if (oldState == null) { + expandTree(treeModel); } - }); + else { + oldState.applyTo(myTree); + } + })); myListModel = new AssociationsModel(myTree, myManager); myListModel.addListDataListener(new ListDataListener() { @@ -202,12 +194,7 @@ class AssociationsEditor { } public void select(final PsiFile file) { - myBuilder.getReady(this).doWhenDone(new Runnable() { - @Override - public void run() { - myBuilder.select(file, file.getVirtualFile(), true); - } - }); + myBuilder.getReady(this).doWhenDone(() -> myBuilder.select(file, file.getVirtualFile(), true)); } class AddAssociationActionWrapper extends AddAssociationAction { diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/FileAssociationsConfigurable.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/FileAssociationsConfigurable.java index b70279f81771..c873bb1750e1 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/FileAssociationsConfigurable.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/associations/impl/FileAssociationsConfigurable.java @@ -94,13 +94,10 @@ public class FileAssociationsConfigurable implements SearchableConfigurable, Con public static void editAssociations(Project project, final PsiFile file) { final FileAssociationsConfigurable instance = new FileAssociationsConfigurable(project); - ShowSettingsUtil.getInstance().editConfigurable(project, instance, new Runnable() { - @Override - public void run() { - final AssociationsEditor editor = instance.getEditor(); - if (file != null) { - editor.select(file); - } + ShowSettingsUtil.getInstance().editConfigurable(project, instance, () -> { + final AssociationsEditor editor = instance.getEditor(); + if (file != null) { + editor.select(file); } }); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProviderBase.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProviderBase.java index f70c4f82ccab..f38c9278dbd2 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProviderBase.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltContextProviderBase.java @@ -150,12 +150,7 @@ public abstract class XsltContextProviderBase extends ContextProvider { } } catch (StopProcessingException e1) { Logger.getInstance(XsltContextProviderBase.class).error("Maximum recursion depth reached. Missing equals()/hashCode() implementation?", StringUtil - .join(history, new Function() { - @Override - public String fun(XmlElementDescriptor descriptor) { - return descriptor.getClass().getName() + "[" + descriptor.getQualifiedName() + "]"; - } - }, ", ")); + .join(history, descriptor -> descriptor.getClass().getName() + "[" + descriptor.getQualifiedName() + "]", ", ")); } } names.validateNames = names.elementNames.size() > noSchemaNamespaces; diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltVariableContext.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltVariableContext.java index 23aabcebefc0..18e4f3981479 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltVariableContext.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/context/XsltVariableContext.java @@ -80,11 +80,9 @@ public class XsltVariableContext implements VariableContext { if (!processForwardGlobals(context, processor)) { final XmlFile file = PsiTreeUtil.getParentOfType(context, XmlFile.class, true); if (file != null) { - XsltIncludeIndex.processBackwardDependencies(file, new Processor() { - public boolean process(XmlFile xmlFile) { - processor.processExternalFile(xmlFile, context); - return processor.shouldContinue(); - } + XsltIncludeIndex.processBackwardDependencies(file, xmlFile -> { + processor.processExternalFile(xmlFile, context); + return processor.shouldContinue(); }); } } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltImplicitUsagesProvider.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltImplicitUsagesProvider.java index 64b8c2c4f6c8..31365604c264 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltImplicitUsagesProvider.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltImplicitUsagesProvider.java @@ -63,13 +63,11 @@ public final class XsltImplicitUsagesProvider implements ImplicitUsageProvider { final String prefix = attr.getLocalName(); final SchemaPrefix target = new SchemaPrefix(attr, TextRange.from("xmlns:".length(), prefix.length()), prefix); final Query q = ReferencesSearch.search(target, new LocalSearchScope(attr.getParent())); - return !q.forEach(new Processor() { - public boolean process(PsiReference psiReference) { - if (psiReference.getElement() == attr) { - return true; - } - return false; + return !q.forEach(psiReference -> { + if (psiReference.getElement() == attr) { + return true; } + return false; }); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltIncludeIndex.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltIncludeIndex.java index 1c3866c13162..f183f8a23555 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltIncludeIndex.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/XsltIncludeIndex.java @@ -78,10 +78,8 @@ public class XsltIncludeIndex { private static boolean _process(VirtualFile[] files, Project project, Processor processor) { final PsiManager psiManager = PsiManager.getInstance(project); - final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, new NullableFunction() { - public PsiFile fun(VirtualFile file) { - return psiManager.findFile(file); - } + final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, (NullableFunction)file -> { + return psiManager.findFile(file); }); for (final PsiFile psiFile : psiFiles) { if (XsltSupport.isXsltFile(psiFile)) { diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/TemplateReference.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/TemplateReference.java index ec0934120982..f26409382a66 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/TemplateReference.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/impl/references/TemplateReference.java @@ -66,14 +66,12 @@ class TemplateReference extends AttributeReference implements EmptyResolveMessag final XmlFile xmlFile = (XmlFile)getElement().getContainingFile(); if (xmlFile != null) { final List targets = new SmartList(); - XsltIncludeIndex.processBackwardDependencies(xmlFile, new Processor() { - public boolean process(XmlFile xmlFile) { - final PsiElement e = ResolveUtil.resolve(new NamedTemplateMatcher(xmlFile.getDocument(), myName)); - if (e != null) { - targets.add(new PsiElementResolveResult(e)); - } - return true; + XsltIncludeIndex.processBackwardDependencies(xmlFile, xmlFile1 -> { + final PsiElement e = ResolveUtil.resolve(new NamedTemplateMatcher(xmlFile1.getDocument(), myName)); + if (e != null) { + targets.add(new PsiElementResolveResult(e)); } + return true; }); return targets.toArray(new ResolveResult[targets.size()]); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/psi/impl/XsltFunctionImpl.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/psi/impl/XsltFunctionImpl.java index bc3a7bb0cd8a..27a56bfcacab 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/psi/impl/XsltFunctionImpl.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/psi/impl/XsltFunctionImpl.java @@ -44,13 +44,9 @@ import javax.xml.namespace.QName; * Date: 11.01.11 */ public class XsltFunctionImpl extends XsltElementImpl implements XsltFunction, ItemPresentation { - private static final NotNullFunction PARAM_MAPPER = new NotNullFunction() { - @NotNull - @Override - public Parameter fun(XmlTag param) { - final XPathType type = XsltCodeInsightUtil.getDeclaredType(param); - return new Parameter(type != null ? type : XPath2Type.SEQUENCE, Parameter.Kind.REQUIRED); - } + private static final NotNullFunction PARAM_MAPPER = param -> { + final XPathType type = XsltCodeInsightUtil.getDeclaredType(param); + return new Parameter(type != null ? type : XPath2Type.SEQUENCE, Parameter.Kind.REQUIRED); }; protected XsltFunctionImpl(XmlTag target) { diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadManager.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadManager.java index 6ca2bdd84a6e..60b8406b4bdf 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadManager.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadManager.java @@ -81,11 +81,8 @@ public abstract class DownloadManager { resourceManager.addResource(location, file.getAbsolutePath()); } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog(myProject, "Not a valid file: " + vf.getPresentableUrl(), "Download Problem"); - } + ApplicationManager.getApplication().invokeLater(() -> { + Messages.showErrorDialog(myProject, "Not a valid file: " + vf.getPresentableUrl(), "Download Problem"); }, myProject.getDisposed()); } } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadResourceFix.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadResourceFix.java index 998d6588d667..8ea56429f8d9 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadResourceFix.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/quickfix/DownloadResourceFix.java @@ -55,17 +55,15 @@ public class DownloadResourceFix implements LocalQuickFix { boolean tryAgain = true; final DownloadManager.DownloadException[] ex = new DownloadManager.DownloadException[1]; - final Runnable runnable = new Runnable() { - public void run() { - final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - final DownloadManager downloadManager = new MyDownloadManager(project, progress); + final Runnable runnable = () -> { + final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + final DownloadManager downloadManager = new MyDownloadManager(project, progress); - try { - downloadManager.fetch(myLocation); - } - catch (DownloadManager.DownloadException e) { - ex[0] = e; - } + try { + downloadManager.fetch(myLocation); + } + catch (DownloadManager.DownloadException e) { + ex[0] = e; } }; diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/VariableInlineHandler.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/VariableInlineHandler.java index ca8f0cf76199..f40d764927be 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/VariableInlineHandler.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/VariableInlineHandler.java @@ -152,15 +152,13 @@ public class VariableInlineHandler extends InlineActionHandler { final HighlightManager highlighter = HighlightManager.getInstance(project); final ArrayList highlighters = new ArrayList(); final PsiReference[] psiReferences = references.toArray(new PsiReference[references.size()]); - TextRange[] ranges = ContainerUtil.map2Array(psiReferences, TextRange.class, new Function() { - public TextRange fun(PsiReference s) { - final PsiElement psiElement = s.getElement(); - final XmlAttributeValue context = PsiTreeUtil.getContextOfType(psiElement, XmlAttributeValue.class, true); - if (psiElement instanceof XPathElement && context != null) { - return XsltCodeInsightUtil.getRangeInsideHostingFile((XPathElement)psiElement).cutOut(s.getRangeInElement()); - } - return psiElement.getTextRange().cutOut(s.getRangeInElement()); + TextRange[] ranges = ContainerUtil.map2Array(psiReferences, TextRange.class, s -> { + final PsiElement psiElement = s.getElement(); + final XmlAttributeValue context = PsiTreeUtil.getContextOfType(psiElement, XmlAttributeValue.class, true); + if (psiElement instanceof XPathElement && context != null) { + return XsltCodeInsightUtil.getRangeInsideHostingFile((XPathElement)psiElement).cutOut(s.getRangeInElement()); } + return psiElement.getTextRange().cutOut(s.getRangeInElement()); }); final Editor e = editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor; for (TextRange range : ranges) { diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java index 98d2f63ab5ab..96b70f59288c 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java @@ -214,31 +214,25 @@ public class XsltCommandLineState extends CommandLineState { public void processTerminated(final ProcessEvent event) { if (myXsltRunConfiguration.isSaveToFile()) { - Runnable runnable = new Runnable() { - @Override - public void run() { - Runnable runnable = new Runnable() { - @Override - public void run() { - if (event.getExitCode() == 0) { - if (myXsltRunConfiguration.myOpenInBrowser) { - BrowserUtil.browse(myXsltRunConfiguration.myOutputFile); - } - if (myXsltRunConfiguration.myOpenOutputFile) { - final String url = VfsUtilCore.pathToUrl(myXsltRunConfiguration.myOutputFile); - final VirtualFile fileByUrl = VirtualFileManager.getInstance().refreshAndFindFileByUrl(url.replace(File.separatorChar, '/')); - if (fileByUrl != null) { - fileByUrl.refresh(false, false); - new OpenFileDescriptor(myXsltRunConfiguration.getProject(), fileByUrl).navigate(true); - return; - } - } - VirtualFileManager.getInstance().asyncRefresh(null); + Runnable runnable = () -> { + Runnable runnable1 = () -> { + if (event.getExitCode() == 0) { + if (myXsltRunConfiguration.myOpenInBrowser) { + BrowserUtil.browse(myXsltRunConfiguration.myOutputFile); + } + if (myXsltRunConfiguration.myOpenOutputFile) { + final String url = VfsUtilCore.pathToUrl(myXsltRunConfiguration.myOutputFile); + final VirtualFile fileByUrl = VirtualFileManager.getInstance().refreshAndFindFileByUrl(url.replace(File.separatorChar, '/')); + if (fileByUrl != null) { + fileByUrl.refresh(false, false); + new OpenFileDescriptor(myXsltRunConfiguration.getProject(), fileByUrl).navigate(true); + return; } } - }; - ApplicationManager.getApplication().runWriteAction(runnable); - } + VirtualFileManager.getInstance().asyncRefresh(null); + } + }; + ApplicationManager.getApplication().runWriteAction(runnable1); }; SwingUtilities.invokeLater(runnable); } diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltRunSettingsEditor.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltRunSettingsEditor.java index a8cf1f8834c9..be8453eeebdb 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltRunSettingsEditor.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltRunSettingsEditor.java @@ -377,11 +377,7 @@ class XsltRunSettingsEditor extends SettingsEditor { Logger.getInstance(XsltRunSettingsEditor.class.getName()).info("Encountered incompatible FileType: " + fileType.getName(), e); } } - Collections.sort(v, new Comparator() { - public int compare(FileType o1, FileType o2) { - return o1.getDescription().compareTo(o2.getDescription()); - } - }); + Collections.sort(v, (o1, o2) -> o1.getDescription().compareTo(o2.getDescription())); // off v.insertElementAt(null, 0); diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/util/XsltCodeInsightUtil.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/util/XsltCodeInsightUtil.java index 38df41dde977..db1cbc0bb969 100644 --- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/util/XsltCodeInsightUtil.java +++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/util/XsltCodeInsightUtil.java @@ -45,11 +45,7 @@ public class XsltCodeInsightUtil { return element instanceof XmlTag && XsltSupport.isParam((XmlTag)element); } }; - public static final Comparator POSITION_COMPARATOR = new Comparator() { - public int compare(PsiElement o1, PsiElement o2) { - return o1.getTextOffset() - o2.getTextOffset(); - } - }; + public static final Comparator POSITION_COMPARATOR = (o1, o2) -> o1.getTextOffset() - o2.getTextOffset(); private XsltCodeInsightUtil() { } diff --git a/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/Xslt2HighlightingTest.java b/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/Xslt2HighlightingTest.java index a6f58e51f260..5e83903f2b19 100644 --- a/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/Xslt2HighlightingTest.java +++ b/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/Xslt2HighlightingTest.java @@ -31,11 +31,9 @@ public class Xslt2HighlightingTest extends TestBase { protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(XsltStuffProvider.INSPECTION_CLASSES); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("urn:my"); - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("nsx"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("urn:my"); + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("nsx"); }); } diff --git a/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/XsltHighlightingTest.java b/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/XsltHighlightingTest.java index ba8a10a13bc2..2ddd6fd20574 100644 --- a/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/XsltHighlightingTest.java +++ b/plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/XsltHighlightingTest.java @@ -36,10 +36,8 @@ public class XsltHighlightingTest extends TestBase { protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(XsltStuffProvider.INSPECTION_CLASSES); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("urn:my"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("urn:my"); }); } diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java index 53acb8928f79..0373c1844c19 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/XPathEvalAction.java @@ -398,13 +398,10 @@ public class XPathEvalAction extends XPathAction { editor.getCaretModel().moveToOffset(lowestOffset); } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - final StatusBar statusBar = WindowManager.getInstance().getStatusBar(editor.getProject()); - final String s = StringUtil.pluralize("match", list.size()); - statusBar.setInfo(list.size() + " XPath " + s + " found (press Escape to remove the highlighting)"); - } + SwingUtilities.invokeLater(() -> { + final StatusBar statusBar = WindowManager.getInstance().getStatusBar(editor.getProject()); + final String s = StringUtil.pluralize("match", list.size()); + statusBar.setInfo(list.size() + " XPath " + s + " found (press Escape to remove the highlighting)"); }); } @@ -498,50 +495,46 @@ public class XPathEvalAction extends XPathAction { @Override public void generate(@NotNull final Processor processor) { - Runnable runnable = new Runnable() { - @Override - @SuppressWarnings({"unchecked"}) - public void run() { - final List list; - if (myResult.isEmpty()) { - try { - list = (List)myXPath.selectNodes(myContextNode); - } catch (JaxenException e) { - LOG.debug(e); - Messages.showMessageDialog(myContextNode.getProject(), e.getMessage(), "XPath error", Messages.getErrorIcon()); - return; - } - } else { - list = myResult; + Runnable runnable = () -> { + final List list; + if (myResult.isEmpty()) { + try { + list = (List)myXPath.selectNodes(myContextNode); + } catch (JaxenException e) { + LOG.debug(e); + Messages.showMessageDialog(myContextNode.getProject(), e.getMessage(), "XPath error", Messages.getErrorIcon()); + return; } - - final int size = list.size(); - final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - indicator.setText("Collecting matches..."); - - Collections.sort(list, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - indicator.checkCanceled(); - if (o1 instanceof PsiElement && o2 instanceof PsiElement) { - return ((PsiElement)o1).getTextRange().getStartOffset() - ((PsiElement)o2).getTextRange().getStartOffset(); - } else { - return String.valueOf(o1).compareTo(String.valueOf(o2)); - } - } - }); - for (int i = 0; i < size; i++) { - indicator.checkCanceled(); - Object o = list.get(i); - if (o instanceof PsiElement) { - final PsiElement element = (PsiElement)o; - processor.process(new UsageInfo2UsageAdapter(new UsageInfo(element))); - indicator.setText2(element.getContainingFile().getName()); - } - indicator.setFraction(i / (double)size); - } - list.clear(); + } else { + list = myResult; } + + final int size = list.size(); + final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + indicator.setText("Collecting matches..."); + + Collections.sort(list, new Comparator() { + @Override + public int compare(Object o1, Object o2) { + indicator.checkCanceled(); + if (o1 instanceof PsiElement && o2 instanceof PsiElement) { + return ((PsiElement)o1).getTextRange().getStartOffset() - ((PsiElement)o2).getTextRange().getStartOffset(); + } else { + return String.valueOf(o1).compareTo(String.valueOf(o2)); + } + } + }); + for (int i = 0; i < size; i++) { + indicator.checkCanceled(); + Object o = list.get(i); + if (o instanceof PsiElement) { + final PsiElement element = (PsiElement)o; + processor.process(new UsageInfo2UsageAdapter(new UsageInfo(element))); + indicator.setText2(element.getContainingFile().getName()); + } + indicator.setFraction(i / (double)size); + } + list.clear(); }; ApplicationManager.getApplication().runReadAction(runnable); } diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/SearchScope.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/SearchScope.java index 46b484a239d7..ccf66210ceaa 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/SearchScope.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/SearchScope.java @@ -204,12 +204,7 @@ public final class SearchScope { final Collection libraryFiles = new THashSet(); Collections.addAll(libraryFiles, enumerator.getClassesRoots()); Collections.addAll(libraryFiles, enumerator.getSourceRoots()); - final Processor adapter = new Processor() { - @Override - public boolean process(VirtualFile virtualFile) { - return iterator.processFile(virtualFile); - } - }; + final Processor adapter = virtualFile1 -> iterator.processFile(virtualFile1); for (final VirtualFile file : libraryFiles) { iterateRecursively(file, adapter, true); } diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/XPathUsageSearcher.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/XPathUsageSearcher.java index 90eb7c9f9cfb..9a8825c47095 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/XPathUsageSearcher.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/search/XPathUsageSearcher.java @@ -69,17 +69,15 @@ class XPathUsageSearcher implements UsageSearcher { } public void generate(@NotNull final Processor processor) { - Runnable runnable = new Runnable() { - public void run() { - myIndicator.setIndeterminate(true); - myIndicator.setText2(findBundleMessage("find.searching.for.string.in.file.occurrences.progress", 0)); - final CountProcessor counter = new CountProcessor(); - myScope.iterateContent(myProject, counter); + Runnable runnable = () -> { + myIndicator.setIndeterminate(true); + myIndicator.setText2(findBundleMessage("find.searching.for.string.in.file.occurrences.progress", 0)); + final CountProcessor counter = new CountProcessor(); + myScope.iterateContent(myProject, counter); - myIndicator.setIndeterminate(false); - myIndicator.setFraction(0); - myScope.iterateContent(myProject, new MyProcessor(processor, counter.getFileCount())); - } + myIndicator.setIndeterminate(false); + myIndicator.setFraction(0); + myScope.iterateContent(myProject, new MyProcessor(processor, counter.getFileCount())); }; ApplicationManager.getApplication().runReadAction(runnable); } diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/ExpressionCellEditor.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/ExpressionCellEditor.java index c0e9583f348e..f740d90f293d 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/ExpressionCellEditor.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/ExpressionCellEditor.java @@ -48,12 +48,10 @@ public class ExpressionCellEditor extends AbstractCellEditor implements TableCel public void addNotify() { super.addNotify(); - Runnable runnable = new Runnable() { - public void run() { - final Editor editor = getEditor(); - if (editor != null) { - editor.getContentComponent().requestFocus(); - } + Runnable runnable = () -> { + final Editor editor = getEditor(); + if (editor != null) { + editor.getContentComponent().requestFocus(); } }; SwingUtilities.invokeLater(runnable); diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/InputExpressionDialog.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/InputExpressionDialog.java index d868ef744dcc..43fd10850255 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/InputExpressionDialog.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/InputExpressionDialog.java @@ -167,12 +167,10 @@ public abstract class InputExpressionDialog extends updateContext(newNamespaces, newVariables); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final Editor editor = getEditor(); - if (editor != null) { - editor.getContentComponent().grabFocus(); - } + SwingUtilities.invokeLater(() -> { + final Editor editor = getEditor(); + if (editor != null) { + editor.getContentComponent().grabFocus(); } }); } @@ -264,12 +262,10 @@ public abstract class InputExpressionDialog extends myComboBox.getEditor().selectAll(); } - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final Editor editor = getEditor(); - if (editor != null) { - editor.getContentComponent().grabFocus(); - } + SwingUtilities.invokeLater(() -> { + final Editor editor = getEditor(); + if (editor != null) { + editor.getContentComponent().grabFocus(); } }); } diff --git a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/MultilineEditor.java b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/MultilineEditor.java index f2674382f872..5c0cecbc1e39 100644 --- a/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/MultilineEditor.java +++ b/plugins/xpath/xpath-view/src/org/intellij/plugins/xpathView/ui/MultilineEditor.java @@ -129,14 +129,12 @@ public class MultilineEditor extends JPanel { } private void refocus() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final Editor editor = myEditorTextField.getEditor(); - if (editor != null) { - editor.getContentComponent().requestFocus(); - } - myEditorTextField.selectAll(); + SwingUtilities.invokeLater(() -> { + final Editor editor = myEditorTextField.getEditor(); + if (editor != null) { + editor.getContentComponent().requestFocus(); } + myEditorTextField.selectAll(); }); } diff --git a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/EDTGuard.java b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/EDTGuard.java index 4a770ad57c08..946bd5473214 100644 --- a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/EDTGuard.java +++ b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/EDTGuard.java @@ -209,12 +209,7 @@ class EDTGuard implements InvocationHandler { final Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD, d); final Alarm alarm2 = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, alarm); - final Runnable watchdog = new Runnable() { - @Override - public void run() { - ref.set(true); - } - }; + final Runnable watchdog = () -> ref.set(true); final Runnable ping = new Runnable() { @Override diff --git a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/GeneratedStructureModel.java b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/GeneratedStructureModel.java index 195ad1b5c693..540560e4e479 100644 --- a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/GeneratedStructureModel.java +++ b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/GeneratedStructureModel.java @@ -79,11 +79,7 @@ public class GeneratedStructureModel extends DefaultTreeModel { public void update(final List eventQueue) { if (!SwingUtilities.isEventDispatchThread()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - updateImpl(eventQueue); - } - }); + ApplicationManager.getApplication().invokeLater(() -> updateImpl(eventQueue)); return; } updateImpl(eventQueue); @@ -242,15 +238,13 @@ public class GeneratedStructureModel extends DefaultTreeModel { } public void finalUpdate(final List events) { - Runnable runnable = new Runnable() { - public void run() { - myListenersDisabled = true; - try { - updateImpl(events); - } finally { - myListenersDisabled = false; - nodeStructureChanged((TreeNode)getRoot()); - } + Runnable runnable = () -> { + myListenersDisabled = true; + try { + updateImpl(events); + } finally { + myListenersDisabled = false; + nodeStructureChanged((TreeNode)getRoot()); } }; ApplicationManager.getApplication().invokeLater(runnable); diff --git a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/SmartStructureTracker.java b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/SmartStructureTracker.java index 4673d55c559e..59518272e610 100644 --- a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/SmartStructureTracker.java +++ b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/ui/SmartStructureTracker.java @@ -48,11 +48,9 @@ public class SmartStructureTracker extends TreeModelAdapter { final Object child = e.getChildren()[0]; if (path != null && child != null) { myAlarm.cancelAllRequests(); - final Runnable runnable = new Runnable() { - public void run() { - myEventTree.expandPath(path); - TreeUtil.showRowCentered(myEventTree, myEventTree.getRowForPath(TreeUtil.getPathFromRoot((TreeNode)child)), false); - } + final Runnable runnable = () -> { + myEventTree.expandPath(path); + TreeUtil.showRowCentered(myEventTree, myEventTree.getRowForPath(TreeUtil.getPathFromRoot((TreeNode)child)), false); }; myAlarm.addRequest(runnable, 300); } @@ -63,13 +61,12 @@ public class SmartStructureTracker extends TreeModelAdapter { final TreePath p = e.getTreePath(); if (p != null) { if (p.getPathCount() > 1) { - final Runnable runnable = new Runnable() { - public void run() { - DefaultMutableTreeNode last = (DefaultMutableTreeNode)p.getLastPathComponent(); - if (last.getChildCount() > 0) { - DefaultMutableTreeNode next = (DefaultMutableTreeNode)last.getFirstChild(); - while (next != null) { - boolean collapse = true; + final Runnable runnable = () -> { + DefaultMutableTreeNode last = (DefaultMutableTreeNode)p.getLastPathComponent(); + if (last.getChildCount() > 0) { + DefaultMutableTreeNode next = (DefaultMutableTreeNode)last.getFirstChild(); + while (next != null) { + boolean collapse = true; // final int count = next.getChildCount(); // if (count > 0) { // for (int i = 0; i < count; i++) { @@ -81,11 +78,10 @@ public class SmartStructureTracker extends TreeModelAdapter { // } // } // } - if (collapse) { - myEventTree.collapsePath(TreeUtil.getPathFromRoot(next)); - } - next = next.getNextSibling(); + if (collapse) { + myEventTree.collapsePath(TreeUtil.getPathFromRoot(next)); } + next = next.getNextSibling(); } } }; diff --git a/plugins/yaml/src/org/jetbrains/yaml/completion/YamlKeyCompletionInsertHandler.java b/plugins/yaml/src/org/jetbrains/yaml/completion/YamlKeyCompletionInsertHandler.java index 543008a8b203..5566607057bb 100644 --- a/plugins/yaml/src/org/jetbrains/yaml/completion/YamlKeyCompletionInsertHandler.java +++ b/plugins/yaml/src/org/jetbrains/yaml/completion/YamlKeyCompletionInsertHandler.java @@ -36,11 +36,8 @@ public abstract class YamlKeyCompletionInsertHandler im context.getEditor().getCaretModel().moveToOffset(created.getTextRange().getEndOffset()); if (oldValue != null) { - WriteCommandAction.runWriteCommandAction(context.getProject(), new Runnable() { - @Override - public void run() { - created.setValue(oldValue); - } + WriteCommandAction.runWriteCommandAction(context.getProject(), () -> { + created.setValue(oldValue); }); } @@ -77,11 +74,8 @@ public abstract class YamlKeyCompletionInsertHandler im } context.setTailOffset(keyValue.getTextRange().getEndOffset()); - WriteCommandAction.runWriteCommandAction(context.getProject(), new Runnable() { - @Override - public void run() { - keyValue.getParentMapping().deleteKeyValue(keyValue); - } + WriteCommandAction.runWriteCommandAction(context.getProject(), () -> { + keyValue.getParentMapping().deleteKeyValue(keyValue); }); return oldValue; } diff --git a/plugins/yaml/testSrc/org/jetbrains/yaml/psiModification/YAMLMappingModificationTest.java b/plugins/yaml/testSrc/org/jetbrains/yaml/psiModification/YAMLMappingModificationTest.java index b03d7af4a839..5e9409960968 100644 --- a/plugins/yaml/testSrc/org/jetbrains/yaml/psiModification/YAMLMappingModificationTest.java +++ b/plugins/yaml/testSrc/org/jetbrains/yaml/psiModification/YAMLMappingModificationTest.java @@ -70,11 +70,8 @@ public class YAMLMappingModificationTest extends LightPlatformCodeInsightFixture final YAMLKeyValue dummyKV = YAMLElementGenerator.getInstance(myFixture.getProject()).createYamlKeyValue("foo", valueText); assertNotNull(dummyKV.getValue()); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - keyValue.setValue(dummyKV.getValue()); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + keyValue.setValue(dummyKV.getValue()); }); assertSameLinesWithFile(getTestDataPath() + getTestName(true) + ".txt", myFixture.getFile().getText(), false); @@ -101,11 +98,8 @@ public class YAMLMappingModificationTest extends LightPlatformCodeInsightFixture final YAMLKeyValue dummyKeyValue = YAMLElementGenerator.getInstance(myFixture.getProject()).createYamlKeyValue(key, content); assertNotNull(dummyKeyValue); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - mapping.putKeyValue(dummyKeyValue); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + mapping.putKeyValue(dummyKeyValue); }); } diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCRefactoringElementListenerProvider.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCRefactoringElementListenerProvider.java index 7dbd894d8980..d828102bfb22 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCRefactoringElementListenerProvider.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCRefactoringElementListenerProvider.java @@ -92,17 +92,14 @@ public class CCRefactoringElementListenerProvider implements RefactoringElementL if (taskFile == null) { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - VirtualFile patternFile = StudyUtils.getPatternFile(taskFile, oldName); - if (patternFile != null) { - try { - patternFile.delete(CCRefactoringElementListenerProvider.class); - } - catch (IOException e) { - LOG.info(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + VirtualFile patternFile = StudyUtils.getPatternFile(taskFile, oldName); + if (patternFile != null) { + try { + patternFile.delete(CCRefactoringElementListenerProvider.class); + } + catch (IOException e) { + LOG.info(e); } } }); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCUtils.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCUtils.java index f6dd7417a32d..6ac5ab418049 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCUtils.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCUtils.java @@ -70,14 +70,11 @@ public class CCUtils { return index > threshold; } })); - Collections.sort(dirsToRename, new Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - StudyItem item1 = getStudyItem.fun(o1); - StudyItem item2 = getStudyItem.fun(o2); - //if we delete some dir we should start increasing numbers in dir names from the end - return (-delta) * EduUtils.INDEX_COMPARATOR.compare(item1, item2); - } + Collections.sort(dirsToRename, (o1, o2) -> { + StudyItem item1 = getStudyItem.fun(o1); + StudyItem item2 = getStudyItem.fun(o2); + //if we delete some dir we should start increasing numbers in dir names from the end + return (-delta) * EduUtils.INDEX_COMPARATOR.compare(item1, item2); }); for (final VirtualFile dir : dirsToRename) { diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCVirtualFileListener.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCVirtualFileListener.java index 3c3be598ca7f..70fa712c1c0d 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCVirtualFileListener.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/CCVirtualFileListener.java @@ -90,12 +90,7 @@ public class CCVirtualFileListener extends VirtualFileAdapter { return; } VirtualFile courseDir = project.getBaseDir(); - CCUtils.updateHigherElements(courseDir.getChildren(), new Function() { - @Override - public StudyItem fun(VirtualFile file) { - return course.getLesson(file.getName()); - } - }, removedLesson.getIndex(), EduNames.LESSON, -1); + CCUtils.updateHigherElements(courseDir.getChildren(), file -> course.getLesson(file.getName()), removedLesson.getIndex(), EduNames.LESSON, -1); course.getLessons().remove(removedLesson); } @@ -112,12 +107,7 @@ public class CCVirtualFileListener extends VirtualFileAdapter { if (task == null) { return; } - CCUtils.updateHigherElements(lessonDir.getChildren(), new Function() { - @Override - public StudyItem fun(VirtualFile file) { - return lesson.getTask(file.getName()); - } - }, task.getIndex(), EduNames.TASK, -1); + CCUtils.updateHigherElements(lessonDir.getChildren(), file -> lesson.getTask(file.getName()), task.getIndex(), EduNames.TASK, -1); lesson.getTaskList().remove(task); } diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateCourseArchive.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateCourseArchive.java index 66604dac86b5..cbf71f341b24 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateCourseArchive.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateCourseArchive.java @@ -90,12 +90,7 @@ public class CCCreateCourseArchive extends DumbAwareAction { if (manager == null) { return; } - FileFilter filter = new FileFilter() { - @Override - public boolean accept(File pathname) { - return !manager.doNotPackFile(pathname); - } - }; + FileFilter filter = pathname -> !manager.doNotPackFile(pathname); for (VirtualFile child : baseDir.getChildren()) { String name = child.getName(); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java index 2353e43c12b1..6952f319dcf7 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java @@ -38,14 +38,11 @@ public class CCCreateLesson extends CCCreateStudyItemActionBase { @Override protected Function getStudyOrderable(@NotNull final StudyItem item) { - return new Function() { - @Override - public StudyItem fun(VirtualFile file) { - if (item instanceof Lesson) { - return ((Lesson)item).getCourse().getLesson(file.getName()); - } - return null; + return (Function)file -> { + if (item instanceof Lesson) { + return ((Lesson)item).getCourse().getLesson(file.getName()); } + return null; }; } @@ -55,11 +52,8 @@ public class CCCreateLesson extends CCCreateStudyItemActionBase { @Nullable final IdeView view, @NotNull final PsiDirectory parentDirectory, @NotNull final Course course) { final PsiDirectory[] lessonDirectory = new PsiDirectory[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - lessonDirectory[0] = DirectoryUtil.createSubdirectories(EduNames.LESSON + item.getIndex(), parentDirectory, "\\/"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + lessonDirectory[0] = DirectoryUtil.createSubdirectories(EduNames.LESSON + item.getIndex(), parentDirectory, "\\/"); }); if (lessonDirectory[0] != null) { if (view != null) { diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java index 844fc9ad3796..0f582614e969 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java @@ -75,14 +75,11 @@ public class CCCreateTask extends CCCreateStudyItemActionBase { @Override protected Function getStudyOrderable(@NotNull final StudyItem item) { - return new Function() { - @Override - public StudyItem fun(VirtualFile file) { - if (item instanceof Task) { - return ((Task)item).getLesson().getTask(file.getName()); - } - return null; + return (Function)file -> { + if (item instanceof Task) { + return ((Task)item).getLesson().getTask(file.getName()); } + return null; }; } @@ -93,23 +90,20 @@ public class CCCreateTask extends CCCreateStudyItemActionBase { @NotNull final Course course) { final Ref taskDirectory = new Ref<>(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - String taskDirName = EduNames.TASK + item.getIndex(); - taskDirectory.set(DirectoryUtil.createSubdirectories(taskDirName, parentDirectory, "\\/")); - if (taskDirectory.get() != null) { - CCLanguageManager manager = CCUtils.getStudyLanguageManager(course); - if (manager == null) { - return; - } - createFromTemplate(taskDirectory.get(), manager.getTestsTemplate(project), view, false); - createFromTemplate(taskDirectory.get(), FileTemplateManager.getInstance(project).getInternalTemplate(EduNames.TASK_HTML), view, false); - String defaultExtension = manager.getDefaultTaskFileExtension(); - if (defaultExtension != null) { - FileTemplate taskFileTemplate = manager.getTaskFileTemplateForExtension(project, defaultExtension); - createFromTemplate(taskDirectory.get(), taskFileTemplate, view, true); - } + ApplicationManager.getApplication().runWriteAction(() -> { + String taskDirName = EduNames.TASK + item.getIndex(); + taskDirectory.set(DirectoryUtil.createSubdirectories(taskDirName, parentDirectory, "\\/")); + if (taskDirectory.get() != null) { + CCLanguageManager manager = CCUtils.getStudyLanguageManager(course); + if (manager == null) { + return; + } + createFromTemplate(taskDirectory.get(), manager.getTestsTemplate(project), view, false); + createFromTemplate(taskDirectory.get(), FileTemplateManager.getInstance(project).getInternalTemplate(EduNames.TASK_HTML), view, false); + String defaultExtension = manager.getDefaultTaskFileExtension(); + if (defaultExtension != null) { + FileTemplate taskFileTemplate = manager.getTaskFileTemplateForExtension(project, defaultExtension); + createFromTemplate(taskDirectory.get(), taskFileTemplate, view, true); } } }); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCFromCourseArchive.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCFromCourseArchive.java index 97fdb1ec2e57..72c5b5826edd 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCFromCourseArchive.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCFromCourseArchive.java @@ -92,11 +92,8 @@ public class CCFromCourseArchive extends DumbAwareAction { task.setLesson(lesson); if (taskDir == null) continue; for (final Map.Entry entry : task.getTaskFiles().entrySet()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - createAnswerFile(project, taskDir, entry); - } + ApplicationManager.getApplication().runWriteAction(() -> { + createAnswerFile(project, taskDir, entry); }); } taskIndex += 1; @@ -142,17 +139,9 @@ public class CCFromCourseArchive extends DumbAwareAction { final Document document = FileDocumentManager.getInstance().getDocument(file); if (document == null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(0, document.getTextLength(), originDocument.getCharsSequence()); - } - }); - } - }, "Create answer document", "Create answer document"); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(0, document.getTextLength(), originDocument.getCharsSequence()); + }), "Create answer document", "Create answer document"); EduDocumentListener listener = new EduDocumentListener(taskFile, false); document.addDocumentListener(listener); taskFile.sortAnswerPlaceholders(); @@ -160,17 +149,9 @@ public class CCFromCourseArchive extends DumbAwareAction { final AnswerPlaceholder answerPlaceholder = taskFile.getAnswerPlaceholders().get(i); replaceAnswerPlaceholder(project, document, answerPlaceholder); } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileDocumentManager.getInstance().saveDocument(document); - } - }); - } - }, "x", "qwe"); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + FileDocumentManager.getInstance().saveDocument(document); + }), "x", "qwe"); document.removeDocumentListener(listener); } @@ -178,34 +159,26 @@ public class CCFromCourseArchive extends DumbAwareAction { @NotNull final Document document, @NotNull final AnswerPlaceholder answerPlaceholder) { final int offset = answerPlaceholder.getRealStartOffset(document); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final String text = document.getText(TextRange.create(offset, offset + answerPlaceholder.getRealLength())); - answerPlaceholder.setTaskText(text); - answerPlaceholder.init(); - final VirtualFile hints = project.getBaseDir().findChild(EduNames.HINTS); - if (hints != null) { - final String hintFile = answerPlaceholder.getHint(); - final VirtualFile virtualFile = hints.findChild(hintFile); - if (virtualFile != null) { - final Document hintDocument = FileDocumentManager.getInstance().getDocument(virtualFile); - if (hintDocument != null) { - final String hintText = hintDocument.getText(); - answerPlaceholder.setHint(hintText); - } - } - } - - document.replaceString(offset, offset + answerPlaceholder.getRealLength(), answerPlaceholder.getPossibleAnswer()); - FileDocumentManager.getInstance().saveDocument(document); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + final String text = document.getText(TextRange.create(offset, offset + answerPlaceholder.getRealLength())); + answerPlaceholder.setTaskText(text); + answerPlaceholder.init(); + final VirtualFile hints = project.getBaseDir().findChild(EduNames.HINTS); + if (hints != null) { + final String hintFile = answerPlaceholder.getHint(); + final VirtualFile virtualFile = hints.findChild(hintFile); + if (virtualFile != null) { + final Document hintDocument = FileDocumentManager.getInstance().getDocument(virtualFile); + if (hintDocument != null) { + final String hintText = hintDocument.getText(); + answerPlaceholder.setHint(hintText); } - }); + } } - }, "x", "qwe"); + + document.replaceString(offset, offset + answerPlaceholder.getRealLength(), answerPlaceholder.getPossibleAnswer()); + FileDocumentManager.getInstance().saveDocument(document); + }), "x", "qwe"); } private static void synchronize(@NotNull final Project project) { diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCShowPreview.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCShowPreview.java index 39a2ce7f4e0d..a3a381f1ad64 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCShowPreview.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCShowPreview.java @@ -121,11 +121,8 @@ public class CCShowPreview extends DumbAwareAction { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - EduUtils.createStudentFileFromAnswer(project, generatedFilesFolder, taskDir.getVirtualFile(), virtualFile.getName(), taskFileCopy); - } + ApplicationManager.getApplication().runWriteAction(() -> { + EduUtils.createStudentFileFromAnswer(project, generatedFilesFolder, taskDir.getVirtualFile(), virtualFile.getName(), taskFileCopy); }); VirtualFile userFile = generatedFilesFolder.findChild(virtualFile.getName()); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCLessonMoveHandlerDelegate.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCLessonMoveHandlerDelegate.java index 18ca9364c96f..d9d6f5adc3df 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCLessonMoveHandlerDelegate.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCLessonMoveHandlerDelegate.java @@ -98,12 +98,7 @@ public class CCLessonMoveHandlerDelegate extends MoveHandlerDelegate { } }); final VirtualFile[] lessonDirs = project.getBaseDir().getChildren(); - final Function getStudyItem = new Function() { - @Override - public StudyItem fun(VirtualFile file) { - return course.getLesson(file.getName()); - } - }; + final Function getStudyItem = file -> course.getLesson(file.getName()); int sourceLessonIndex = sourceLesson.getIndex(); sourceLesson.setIndex(-1); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCTaskMoveHandlerDelegate.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCTaskMoveHandlerDelegate.java index 91083e9f9edb..e69a1eeb8523 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCTaskMoveHandlerDelegate.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/handlers/CCTaskMoveHandlerDelegate.java @@ -147,23 +147,13 @@ public class CCTaskMoveHandlerDelegate extends MoveHandlerDelegate { if (sourceLessonDir == null) { return; } - CCUtils.updateHigherElements(sourceLessonDir.getChildren(), new Function() { - @Override - public StudyItem fun(VirtualFile file) { - return taskToMove.getLesson().getTask(file.getName()); - } - }, taskToMove.getIndex(), EduNames.TASK, -1); + CCUtils.updateHigherElements(sourceLessonDir.getChildren(), file -> taskToMove.getLesson().getTask(file.getName()), taskToMove.getIndex(), EduNames.TASK, -1); final int newItemIndex = targetTask != null ? targetTask.getIndex() + indexDelta : 1; taskToMove.setIndex(-1); taskToMove.getLesson().getTaskList().remove(taskToMove); final Lesson finalTargetLesson = targetLesson; - CCUtils.updateHigherElements(targetDirectory.getChildren(), new Function() { - @Override - public StudyItem fun(VirtualFile file) { - return finalTargetLesson.getTask(file.getName()); - } - }, + CCUtils.updateHigherElements(targetDirectory.getChildren(), file -> finalTargetLesson.getTask(file.getName()), newItemIndex - 1, EduNames.TASK, 1); taskToMove.setIndex(newItemIndex); diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/StudyTaskManager.java b/python/educational-core/student/src/com/jetbrains/edu/learning/StudyTaskManager.java index 024cd09e9245..0ee3584adfd6 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/StudyTaskManager.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/StudyTaskManager.java @@ -218,12 +218,9 @@ public class StudyTaskManager implements PersistentStateComponent, Dumb if (oldCourseElement != null) { myOldCourse = XmlSerializer.deserialize(oldCourseElement, OldCourse.class); if (myOldCourse != null) { - myCourse = EduUtils.transformOldCourse(myOldCourse, new Function, Void>() { - @Override - public Void fun(Pair pair) { - setStatus(pair.first, pair.second); - return null; - } + myCourse = EduUtils.transformOldCourse(myOldCourse, pair -> { + setStatus(pair.first, pair.second); + return null; }); myOldCourse = null; } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyEditInputAction.java b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyEditInputAction.java index eb8045c10053..ddd63673e839 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyEditInputAction.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyEditInputAction.java @@ -174,15 +174,12 @@ public class StudyEditInputAction extends DumbAwareAction { @Override public void onClosed(LightweightWindowEvent event) { for (final UserTest userTest : myStudyTaskManager.getUserTests(myTask)) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (userTest.isEditable()) { - File inputFile = new File(userTest.getInput()); - File outputFile = new File(userTest.getOutput()); - flushBuffer(userTest.getInputBuffer(), inputFile); - flushBuffer(userTest.getOutputBuffer(), outputFile); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (userTest.isEditable()) { + File inputFile = new File(userTest.getInput()); + File outputFile = new File(userTest.getOutput()); + flushBuffer(userTest.getInputBuffer(), inputFile); + flushBuffer(userTest.getOutputBuffer(), outputFile); } }); } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyFillPlaceholdersAction.java b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyFillPlaceholdersAction.java index 73e0a9f20a9c..dced38434bda 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyFillPlaceholdersAction.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyFillPlaceholdersAction.java @@ -28,25 +28,17 @@ public class StudyFillPlaceholdersAction extends AnAction { } final TaskFile taskFile = studyState.getTaskFile(); final Document document = studyState.getEditor().getDocument(); - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (AnswerPlaceholder placeholder : taskFile.getAnswerPlaceholders()) { - String answer = placeholder.getPossibleAnswer(); - if (answer == null) { - continue; - } - int offset = placeholder.getRealStartOffset(document); - document.deleteString(offset, offset + placeholder.getRealLength()); - document.insertString(offset, answer); - } - } - }); + CommandProcessor.getInstance().runUndoTransparentAction(() -> ApplicationManager.getApplication().runWriteAction(() -> { + for (AnswerPlaceholder placeholder : taskFile.getAnswerPlaceholders()) { + String answer = placeholder.getPossibleAnswer(); + if (answer == null) { + continue; + } + int offset = placeholder.getRealStartOffset(document); + document.deleteString(offset, offset + placeholder.getRealLength()); + document.insertString(offset, answer); } - }); + })); } } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshAnswerPlaceholder.java b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshAnswerPlaceholder.java index 7fbd271f1db1..fc3acfd7870a 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshAnswerPlaceholder.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshAnswerPlaceholder.java @@ -52,20 +52,12 @@ public class StudyRefreshAnswerPlaceholder extends DumbAwareAction { AnswerPlaceholder.MyInitialState initialState = answerPlaceholder.getInitialState(); int startOffset = patternDocument.getLineStartOffset(initialState.myLine) + initialState.myStart; final String text = patternDocument.getText(new TextRange(startOffset, startOffset + initialState.myLength)); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - Document document = studyState.getEditor().getDocument(); - int offset = answerPlaceholder.getRealStartOffset(document); - document.deleteString(offset, offset + answerPlaceholder.getRealLength()); - document.insertString(offset, text); - } - }); - } - }, NAME, null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + Document document = studyState.getEditor().getDocument(); + int offset = answerPlaceholder.getRealStartOffset(document); + document.deleteString(offset, offset + answerPlaceholder.getRealLength()); + document.insertString(offset, text); + }), NAME, null); } @Override diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshTaskFileAction.java b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshTaskFileAction.java index 13eac8fc18ac..b19b56a3578d 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshTaskFileAction.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudyRefreshTaskFileAction.java @@ -48,24 +48,15 @@ public class StudyRefreshTaskFileAction extends StudyActionWithShortcut { } public static void refresh(@NotNull final Project project) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") - @Override - public void run() { - StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project); - StudyState studyState = new StudyState(studyEditor); - if (studyEditor == null || !studyState.isValid()) { - LOG.info("RefreshTaskFileAction was invoked outside of Study Editor"); - return; - } - refreshFile(studyState, project); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> { + StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project); + StudyState studyState = new StudyState(studyEditor); + if (studyEditor == null || !studyState.isValid()) { + LOG.info("RefreshTaskFileAction was invoked outside of Study Editor"); + return; } - }); + refreshFile(studyState, project); + })); } private static void refreshFile(@NotNull final StudyState studyState, @NotNull final Project project) { @@ -79,12 +70,8 @@ public class StudyRefreshTaskFileAction extends StudyActionWithShortcut { taskFile.setHighlightErrors(false); StudyUtils.drawAllWindows(editor, taskFile); EduAnswerPlaceholderPainter.createGuardedBlocks(editor, taskFile); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - IdeFocusManager.getInstance(project).requestFocus(editor.getContentComponent(), true); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> IdeFocusManager.getInstance(project).requestFocus(editor.getContentComponent(), true)); StudyNavigator.navigateToFirstAnswerPlaceholder(editor, taskFile); showBalloon(project, "You can start again now", MessageType.INFO); @@ -141,12 +128,7 @@ public class StudyRefreshTaskFileAction extends StudyActionWithShortcut { private static void clearDocument(@NotNull final Document document) { final int lineCount = document.getLineCount(); if (lineCount != 0) { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - document.deleteString(0, document.getLineEndOffset(lineCount - 1)); - } - }); + CommandProcessor.getInstance().runUndoTransparentAction(() -> document.deleteString(0, document.getLineEndOffset(lineCount - 1))); } } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/core/EduUtils.java b/python/educational-core/student/src/com/jetbrains/edu/learning/core/EduUtils.java index b095bc94815e..ce7b3fe21790 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/core/EduUtils.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/core/EduUtils.java @@ -40,12 +40,7 @@ public class EduUtils { } private static final Logger LOG = Logger.getInstance(EduUtils.class.getName()); - public static Comparator INDEX_COMPARATOR = new Comparator() { - @Override - public int compare(StudyItem o1, StudyItem o2) { - return o1.getIndex() - o2.getIndex(); - } - }; + public static Comparator INDEX_COMPARATOR = (o1, o2) -> o1.getIndex() - o2.getIndex(); public static void enableAction(@NotNull final AnActionEvent event, boolean isEnable) { final Presentation presentation = event.getPresentation(); @@ -104,11 +99,8 @@ public class EduUtils { final String windowDescription = document.getText(new TextRange(start, start + length)); printWriter.println("#educational_plugin_window = " + windowDescription); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileDocumentManager.getInstance().saveDocument(document); - } + ApplicationManager.getApplication().runWriteAction(() -> { + FileDocumentManager.getInstance().saveDocument(document); }); } catch (IOException e) { @@ -180,18 +172,10 @@ public class EduUtils { final Document document = FileDocumentManager.getInstance().getDocument(file); if (document == null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(0, document.getTextLength(), answerDocument.getCharsSequence()); - FileDocumentManager.getInstance().saveDocument(document); - } - }); - } - }, "Create Student File", "Create Student File"); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(0, document.getTextLength(), answerDocument.getCharsSequence()); + FileDocumentManager.getInstance().saveDocument(document); + }), "Create Student File", "Create Student File"); createStudentDocument(project, taskFile, file, document); } @@ -210,17 +194,9 @@ public class EduUtils { } replaceAnswerPlaceholder(project, document, answerPlaceholder); } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileDocumentManager.getInstance().saveDocument(document); - } - }); - } - }, "Create Student File", "Create Student File"); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + FileDocumentManager.getInstance().saveDocument(document); + }), "Create Student File", "Create Student File"); document.removeDocumentListener(listener); } @@ -229,18 +205,10 @@ public class EduUtils { @NotNull final AnswerPlaceholder answerPlaceholder) { final String taskText = answerPlaceholder.getTaskText(); final int offset = answerPlaceholder.getRealStartOffset(document); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(offset, offset + answerPlaceholder.getPossibleAnswerLength(), taskText); - FileDocumentManager.getInstance().saveDocument(document); - } - }); - } - }, "Replace Answer Placeholders", "Replace Answer Placeholders"); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(offset, offset + answerPlaceholder.getPossibleAnswerLength(), taskText); + FileDocumentManager.getInstance().saveDocument(document); + }), "Replace Answer Placeholders", "Replace Answer Placeholders"); } public static void deleteWindowDescriptions(@NotNull final Task task, @NotNull final VirtualFile taskDir) { @@ -258,15 +226,12 @@ public class EduUtils { private static void deleteWindowsFile(@NotNull final VirtualFile taskDir, @NotNull final String name) { final VirtualFile fileWindows = taskDir.findChild(name); if (fileWindows != null && fileWindows.exists()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - fileWindows.delete(taskDir); - } - catch (IOException e) { - LOG.warn("Tried to delete non existed _windows file"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + fileWindows.delete(taskDir); + } + catch (IOException e) { + LOG.warn("Tried to delete non existed _windows file"); } }); } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/courseFormat/Course.java b/python/educational-core/student/src/com/jetbrains/edu/learning/courseFormat/Course.java index e643d9470cc9..21b4c6001973 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/courseFormat/Course.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/courseFormat/Course.java @@ -77,11 +77,8 @@ public class Course { } public static String getAuthorsString(@NotNull List authors) { - return StringUtil.join(authors, new Function() { - @Override - public String fun(CourseInfo.Author author) { - return author.getName(); - } + return StringUtil.join(authors, author -> { + return author.getName(); }, ", "); } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/courseGeneration/StudyGenerator.java b/python/educational-core/student/src/com/jetbrains/edu/learning/courseGeneration/StudyGenerator.java index 9af4dc7af1a5..0fd1000866a5 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/courseGeneration/StudyGenerator.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/courseGeneration/StudyGenerator.java @@ -115,12 +115,8 @@ public class StudyGenerator { createLesson(lesson, baseDir, resourceRoot, project); } baseDir.createChildDirectory(project, EduNames.SANDBOX_DIR); - File[] files = resourceRoot.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return !name.contains(EduNames.LESSON) && !name.equals(EduNames.COURSE_META_FILE) && !name.equals(EduNames.HINTS); - } - }); + File[] files = resourceRoot.listFiles( + (dir, name) -> !name.contains(EduNames.LESSON) && !name.equals(EduNames.COURSE_META_FILE) && !name.equals(EduNames.HINTS)); for (File file : files) { File dir = new File(baseDir.getPath(), file.getName()); if (file.isDirectory()) { diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicConnector.java b/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicConnector.java index 8d871be6a2e2..eac6c6c7c720 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicConnector.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicConnector.java @@ -317,13 +317,10 @@ public class EduStepicConnector { public static boolean showLoginDialog() { final boolean[] logged = {false}; - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - final LoginDialog dialog = new LoginDialog(); - dialog.show(); - logged[0] = dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE; - } + ApplicationManager.getApplication().invokeAndWait(() -> { + final LoginDialog dialog = new LoginDialog(); + dialog.show(); + logged[0] = dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE; }, ModalityState.defaultModalityState()); return logged[0]; } @@ -435,11 +432,8 @@ public class EduStepicConnector { postUnit(lessonId, position, sectionId); position += 1; } - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - postAdditionalFiles(project, postedCourse.id, indicator); - } + ApplicationManager.getApplication().runReadAction(() -> { + postAdditionalFiles(project, postedCourse.id, indicator); }); } catch (IOException e) { @@ -633,22 +627,19 @@ public class EduStepicConnector { public static void deleteTask(@NotNull final Integer task) { final HttpDelete request = new HttpDelete(stepicApiUrl + "step-sources/" + task); setHeaders(request, "application/json"); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - try { - final CloseableHttpResponse response = ourClient.execute(request); - final StatusLine line = response.getStatusLine(); - if (line.getStatusCode() != HttpStatus.SC_NO_CONTENT) { - final HttpEntity responseEntity = response.getEntity(); - final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; - LOG.error("Failed to delete task " + responseString); - } - } - catch (IOException e) { - LOG.error(e.getMessage()); + ApplicationManager.getApplication().invokeLater(() -> { + try { + final CloseableHttpResponse response = ourClient.execute(request); + final StatusLine line = response.getStatusLine(); + if (line.getStatusCode() != HttpStatus.SC_NO_CONTENT) { + final HttpEntity responseEntity = response.getEntity(); + final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; + LOG.error("Failed to delete task " + responseString); } } + catch (IOException e) { + LOG.error(e.getMessage()); + } }); } @@ -656,25 +647,22 @@ public class EduStepicConnector { final HttpPost request = new HttpPost(stepicApiUrl + "step-sources"); setHeaders(request, "application/json"); final Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final String requestBody = gson.toJson(new StepSourceWrapper(project, task, lessonId)); - request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); + ApplicationManager.getApplication().invokeLater(() -> { + final String requestBody = gson.toJson(new StepSourceWrapper(project, task, lessonId)); + request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); - try { - final CloseableHttpResponse response = ourClient.execute(request); - final StatusLine line = response.getStatusLine(); - if (line.getStatusCode() != HttpStatus.SC_CREATED) { - final HttpEntity responseEntity = response.getEntity(); - final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; - LOG.error("Failed to push " + responseString); - } - } - catch (IOException e) { - LOG.error(e.getMessage()); + try { + final CloseableHttpResponse response = ourClient.execute(request); + final StatusLine line = response.getStatusLine(); + if (line.getStatusCode() != HttpStatus.SC_CREATED) { + final HttpEntity responseEntity = response.getEntity(); + final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; + LOG.error("Failed to push " + responseString); } } + catch (IOException e) { + LOG.error(e.getMessage()); + } }); } @@ -716,15 +704,12 @@ public class EduStepicConnector { for (final Map.Entry entry : task.getTaskFiles().entrySet()) { final TaskFile taskFile = new TaskFile(); TaskFile.copy(entry.getValue(), taskFile); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final VirtualFile taskDir = task.getTaskDir(project); - assert taskDir != null; - VirtualFile ideaDir = project.getBaseDir().findChild(".idea"); - assert ideaDir != null; - EduUtils.createStudentFileFromAnswer(project, ideaDir, taskDir, entry.getKey(), taskFile); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final VirtualFile taskDir = task.getTaskDir(project); + assert taskDir != null; + VirtualFile ideaDir = project.getBaseDir().findChild(".idea"); + assert ideaDir != null; + EduUtils.createStudentFileFromAnswer(project, ideaDir, taskDir, entry.getKey(), taskFile); }); taskFile.name = entry.getKey(); @@ -753,11 +738,8 @@ public class EduStepicConnector { private static void setTests(@NotNull final Task task, @NotNull final StepOptions source, @NotNull final Project project) { final Map testsText = task.getTestsText(); if (testsText.isEmpty()) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - source.test = Collections.singletonList(new TestFileWrapper(EduNames.TESTS_FILE, task.getTestsText(project))); - } + ApplicationManager.getApplication().runReadAction(() -> { + source.test = Collections.singletonList(new TestFileWrapper(EduNames.TESTS_FILE, task.getTestsText(project))); }); } else { diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/StudyCoursesUpdater.java b/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/StudyCoursesUpdater.java index 01cad4c8b6b9..40bdaff318bb 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/StudyCoursesUpdater.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/stepic/StudyCoursesUpdater.java @@ -44,12 +44,9 @@ public class StudyCoursesUpdater implements StartupActivity { return; } if (checkNeeded()) { - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - final List courses = EduStepicConnector.getCourses(); - StudyProjectGenerator.flushCache(courses); - } + application.executeOnPooledThread(() -> { + final List courses = EduStepicConnector.getCourses(); + StudyProjectGenerator.flushCache(courses); }); } } diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java b/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java index 89fa41319b72..065ada094360 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java @@ -100,41 +100,36 @@ public class StudyNewProjectPanel{ final BaseListPopupStep popupStep = new BaseListPopupStep("", "Add local course", "Load private courses") { @Override public PopupStep onChosen(final String selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - public void run() { - if ("Add local course".equals(selectedValue)) { + return doFinalStep(() -> { + if ("Add local course".equals(selectedValue)) { - Project[] projects = ProjectManager.getInstance().getOpenProjects(); - FileChooser.chooseFile(fileChooser, null, projects.length == 0 ? null : projects[0].getBaseDir(), - new Consumer() { - @Override - public void consume(VirtualFile file) { - String fileName = file.getPath(); - int oldSize = myAvailableCourses.size(); - CourseInfo courseInfo = myGenerator.addLocalCourse(fileName); - if (courseInfo != null) { - if (oldSize != myAvailableCourses.size()) { - myCoursesComboBox.addItem(courseInfo); - } - myCoursesComboBox.setSelectedItem(courseInfo); - setOK(); - } - else { - setError(INVALID_COURSE); - myCoursesComboBox.removeAllItems(); - myCoursesComboBox.addItem(CourseInfo.INVALID_COURSE); - for (CourseInfo course : myAvailableCourses) { - myCoursesComboBox.addItem(course); - } - myCoursesComboBox.setSelectedItem(CourseInfo.INVALID_COURSE); - } + Project[] projects = ProjectManager.getInstance().getOpenProjects(); + FileChooser.chooseFile(fileChooser, null, projects.length == 0 ? null : projects[0].getBaseDir(), + file -> { + String fileName = file.getPath(); + int oldSize = myAvailableCourses.size(); + CourseInfo courseInfo = myGenerator.addLocalCourse(fileName); + if (courseInfo != null) { + if (oldSize != myAvailableCourses.size()) { + myCoursesComboBox.addItem(courseInfo); } - }); - } - else if ("Load private courses".equals(selectedValue)) { - final AddRemoteDialog dialog = new AddRemoteDialog(); - dialog.show(); - } + myCoursesComboBox.setSelectedItem(courseInfo); + setOK(); + } + else { + setError(INVALID_COURSE); + myCoursesComboBox.removeAllItems(); + myCoursesComboBox.addItem(CourseInfo.INVALID_COURSE); + for (CourseInfo course : myAvailableCourses) { + myCoursesComboBox.addItem(course); + } + myCoursesComboBox.setSelectedItem(CourseInfo.INVALID_COURSE); + } + }); + } + else if ("Load private courses".equals(selectedValue)) { + final AddRemoteDialog dialog = new AddRemoteDialog(); + dialog.show(); } }); } diff --git a/python/educational-python/src/com/jetbrains/python/edu/PyCharmEduInitialConfigurator.java b/python/educational-python/src/com/jetbrains/python/edu/PyCharmEduInitialConfigurator.java index 4e8345bc1591..3c3d756e4b80 100644 --- a/python/educational-python/src/com/jetbrains/python/edu/PyCharmEduInitialConfigurator.java +++ b/python/educational-python/src/com/jetbrains/python/edu/PyCharmEduInitialConfigurator.java @@ -163,17 +163,9 @@ public class PyCharmEduInitialConfigurator { uiSettings.SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES = true; uiSettings.SHOW_MEMORY_INDICATOR = false; final String ignoredFilesList = fileTypeManager.getIgnoredFilesList(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileTypeManager.getInstance().setIgnoredFilesList(ignoredFilesList + ";*$py.class"); - } - }); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> { + FileTypeManager.getInstance().setIgnoredFilesList(ignoredFilesList + ";*$py.class"); + })); PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP = false; } final EditorColorsScheme editorColorsScheme = EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME); @@ -185,15 +177,12 @@ public class PyCharmEduInitialConfigurator { @Override public void welcomeScreenDisplayed() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!propertiesComponent.isValueSet(DISPLAYED_PROPERTY)) { - GeneralSettings.getInstance().setShowTipsOnStartup(false); - propertiesComponent.setValue(DISPLAYED_PROPERTY, "true"); + ApplicationManager.getApplication().invokeLater(() -> { + if (!propertiesComponent.isValueSet(DISPLAYED_PROPERTY)) { + GeneralSettings.getInstance().setShowTipsOnStartup(false); + propertiesComponent.setValue(DISPLAYED_PROPERTY, "true"); - patchKeymap(); - } + patchKeymap(); } }); } diff --git a/python/educational-python/src/com/jetbrains/python/edu/PyExecuteFileLineMarkerProvider.java b/python/educational-python/src/com/jetbrains/python/edu/PyExecuteFileLineMarkerProvider.java index 9e2853a7b0ac..1e281c870656 100644 --- a/python/educational-python/src/com/jetbrains/python/edu/PyExecuteFileLineMarkerProvider.java +++ b/python/educational-python/src/com/jetbrains/python/edu/PyExecuteFileLineMarkerProvider.java @@ -62,12 +62,9 @@ public class PyExecuteFileLineMarkerProvider implements LineMarkerProvider { Icon icon = PlatformUtils.isPyCharmEducational() ? AllIcons.Actions.Execute : actions.get(0).getTemplatePresentation().getIcon(); final LineMarkerInfo markerInfo = new LineMarkerInfo( file, file.getTextRange(), icon, Pass.UPDATE_OVERRIDDEN_MARKERS, - new Function() { - @Override - public String fun(PsiElement e) { - String text = "Execute '" + e.getContainingFile().getName() + "'"; - return PlatformUtils.isPyCharmEducational() ? text : actions.get(0).getTemplatePresentation().getText(); - } + e -> { + String text = "Execute '" + e.getContainingFile().getName() + "'"; + return PlatformUtils.isPyCharmEducational() ? text : actions.get(0).getTemplatePresentation().getText(); }, null, GutterIconRenderer.Alignment.RIGHT) { @Nullable diff --git a/python/educational-python/student-python/src/com/jetbrains/edu/learning/PyStudyShowTutorial.java b/python/educational-python/student-python/src/com/jetbrains/edu/learning/PyStudyShowTutorial.java index ebcf808b5f52..9adf0f45dfb5 100644 --- a/python/educational-python/student-python/src/com/jetbrains/edu/learning/PyStudyShowTutorial.java +++ b/python/educational-python/student-python/src/com/jetbrains/edu/learning/PyStudyShowTutorial.java @@ -44,12 +44,7 @@ public class PyStudyShowTutorial extends AbstractProjectComponent { } }); } - notification.whenExpired(new Runnable() { - @Override - public void run() { - PropertiesComponent.getInstance().setValue(ourShowPopup, false, true); - } - }); + notification.whenExpired(() -> PropertiesComponent.getInstance().setValue(ourShowPopup, false, true)); } } }); diff --git a/python/ide/src/com/jetbrains/python/PyCharmInitialConfigurator.java b/python/ide/src/com/jetbrains/python/PyCharmInitialConfigurator.java index 2ed6694c6975..10b68db1c3af 100644 --- a/python/ide/src/com/jetbrains/python/PyCharmInitialConfigurator.java +++ b/python/ide/src/com/jetbrains/python/PyCharmInitialConfigurator.java @@ -56,17 +56,9 @@ public class PyCharmInitialConfigurator { propertiesComponent.setValue("PyCharm.InitialConfiguration.V3", "true"); UISettings.getInstance().SHOW_MEMORY_INDICATOR = false; final String ignoredFilesList = fileTypeManager.getIgnoredFilesList(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileTypeManager.getInstance().setIgnoredFilesList(ignoredFilesList + ";*$py.class"); - } - }); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> { + FileTypeManager.getInstance().setIgnoredFilesList(ignoredFilesList + ";*$py.class"); + })); } if (!propertiesComponent.getBoolean("PyCharm.InitialConfiguration.V4")) { propertiesComponent.setValue("PyCharm.InitialConfiguration.V4", true); @@ -85,11 +77,9 @@ public class PyCharmInitialConfigurator { bus.connect().subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() { @Override public void welcomeScreenDisplayed() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - propertiesComponent.setValue(DISPLAYED_PROPERTY, "true"); - showInitialConfigurationDialog(); - } + ApplicationManager.getApplication().invokeLater(() -> { + propertiesComponent.setValue(DISPLAYED_PROPERTY, "true"); + showInitialConfigurationDialog(); }); } }); diff --git a/python/ide/src/com/jetbrains/python/PythonSdkChooserCombo.java b/python/ide/src/com/jetbrains/python/PythonSdkChooserCombo.java index 3cc4e4b71905..7c9335ba62bd 100644 --- a/python/ide/src/com/jetbrains/python/PythonSdkChooserCombo.java +++ b/python/ide/src/com/jetbrains/python/PythonSdkChooserCombo.java @@ -78,26 +78,23 @@ public class PythonSdkChooserCombo extends ComboboxWithBrowseButton { private void showOptions(final Project project) { final PyConfigurableInterpreterList interpreterList = PyConfigurableInterpreterList.getInstance(project); final Sdk[] sdks = interpreterList.getModel().getSdks(); - PythonSdkDetailsStep.show(project, sdks, null, this, getButton().getLocationOnScreen(), new NullableConsumer() { - @Override - public void consume(@Nullable Sdk sdk) { - if (sdk == null) return; - final PySdkService sdkService = PySdkService.getInstance(); - sdkService.restoreSdk(sdk); + PythonSdkDetailsStep.show(project, sdks, null, this, getButton().getLocationOnScreen(), sdk -> { + if (sdk == null) return; + final PySdkService sdkService = PySdkService.getInstance(); + sdkService.restoreSdk(sdk); - final ProjectSdksModel projectSdksModel = interpreterList.getModel(); - if (projectSdksModel.findSdk(sdk) == null) { - projectSdksModel.addSdk(sdk); - try { - projectSdksModel.apply(); - } - catch (ConfigurationException e) { - LOG.error("Error adding new python interpreter " + e.getMessage()); - } + final ProjectSdksModel projectSdksModel = interpreterList.getModel(); + if (projectSdksModel.findSdk(sdk) == null) { + projectSdksModel.addSdk(sdk); + try { + projectSdksModel.apply(); + } + catch (ConfigurationException e) { + LOG.error("Error adding new python interpreter " + e.getMessage()); } - //noinspection unchecked - getComboBox().setModel(new CollectionComboBoxModel(interpreterList.getAllPythonSdks(), sdk)); } + //noinspection unchecked + getComboBox().setModel(new CollectionComboBoxModel(interpreterList.getAllPythonSdks(), sdk)); }, true); } diff --git a/python/ide/src/com/jetbrains/python/PythonSourceRootConfigurator.java b/python/ide/src/com/jetbrains/python/PythonSourceRootConfigurator.java index f22bb9413beb..e85a315cd877 100644 --- a/python/ide/src/com/jetbrains/python/PythonSourceRootConfigurator.java +++ b/python/ide/src/com/jetbrains/python/PythonSourceRootConfigurator.java @@ -59,20 +59,18 @@ public class PythonSourceRootConfigurator implements DirectoryProjectConfigurato private static void addSourceRoot(Project project, final VirtualFile baseDir, final VirtualFile root, final boolean unique) { final Module[] modules = ModuleManager.getInstance(project).getModules(); if (modules.length > 0 && root != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final ModifiableRootModel model = ModuleRootManager.getInstance(modules[0]).getModifiableModel(); - final ContentEntry[] contentEntries = model.getContentEntries(); - for (ContentEntry contentEntry : contentEntries) { - if (Comparing.equal(contentEntry.getFile(), baseDir)) { - final SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); - if (!unique || sourceFolders.length == 0) { - contentEntry.addSourceFolder(root, false); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final ModifiableRootModel model = ModuleRootManager.getInstance(modules[0]).getModifiableModel(); + final ContentEntry[] contentEntries = model.getContentEntries(); + for (ContentEntry contentEntry : contentEntries) { + if (Comparing.equal(contentEntry.getFile(), baseDir)) { + final SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); + if (!unique || sourceFolders.length == 0) { + contentEntry.addSourceFolder(root, false); } } - model.commit(); } + model.commit(); }); } } diff --git a/python/ide/src/com/jetbrains/python/buildout/BuildoutConfigurable.java b/python/ide/src/com/jetbrains/python/buildout/BuildoutConfigurable.java index 15268cdecf58..0d5bc35953f9 100644 --- a/python/ide/src/com/jetbrains/python/buildout/BuildoutConfigurable.java +++ b/python/ide/src/com/jetbrains/python/buildout/BuildoutConfigurable.java @@ -144,10 +144,8 @@ public class BuildoutConfigurable implements Configurable, NonDefaultProjectConf private void removeFacet(BuildoutFacet facet) { final ModifiableFacetModel model = FacetManager.getInstance(myModule).createModifiableModel(); model.removeFacet(facet); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - model.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + model.commit(); }); } diff --git a/python/ide/src/com/jetbrains/python/newProject/PythonBaseProjectGenerator.java b/python/ide/src/com/jetbrains/python/newProject/PythonBaseProjectGenerator.java index c1a33744b475..18947ab1dcb4 100644 --- a/python/ide/src/com/jetbrains/python/newProject/PythonBaseProjectGenerator.java +++ b/python/ide/src/com/jetbrains/python/newProject/PythonBaseProjectGenerator.java @@ -69,11 +69,8 @@ public class PythonBaseProjectGenerator extends PythonProjectGenerator implement (RemoteSdkCredentials)((RemoteProjectSettings)settings).getSdk().getSdkAdditionalData()); } else if (settings instanceof PyNewProjectSettings) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ModuleRootModificationUtil.setModuleSdk(module, ((PyNewProjectSettings)settings).getSdk()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ModuleRootModificationUtil.setModuleSdk(module, ((PyNewProjectSettings)settings).getSdk()); }); } } diff --git a/python/ide/src/com/jetbrains/python/newProject/actions/GenerateProjectCallback.java b/python/ide/src/com/jetbrains/python/newProject/actions/GenerateProjectCallback.java index ee5498510bb6..40603b07d766 100644 --- a/python/ide/src/com/jetbrains/python/newProject/actions/GenerateProjectCallback.java +++ b/python/ide/src/com/jetbrains/python/newProject/actions/GenerateProjectCallback.java @@ -95,12 +95,7 @@ public class GenerateProjectCallback implements NullableConsumer() { - @Override - public Object fun(VirtualFile file) { - return computeProjectSettings(generator, (ProjectSpecificSettingsStep)settings); - } - }); + file -> computeProjectSettings(generator, (ProjectSpecificSettingsStep)settings)); } public static Object computeProjectSettings(DirectoryProjectGenerator generator, ProjectSpecificSettingsStep settings) { diff --git a/python/ide/src/com/jetbrains/python/newProject/actions/PyCharmNewProjectStep.java b/python/ide/src/com/jetbrains/python/newProject/actions/PyCharmNewProjectStep.java index 7fd82d9e15d4..a248fb2eefee 100644 --- a/python/ide/src/com/jetbrains/python/newProject/actions/PyCharmNewProjectStep.java +++ b/python/ide/src/com/jetbrains/python/newProject/actions/PyCharmNewProjectStep.java @@ -67,13 +67,10 @@ public class PyCharmNewProjectStep extends AbstractNewProjectStep { protected DirectoryProjectGenerator[] getProjectGenerators() { DirectoryProjectGenerator[] generators = super.getProjectGenerators(); - Arrays.sort(generators, new Comparator() { - @Override - public int compare(DirectoryProjectGenerator o1, DirectoryProjectGenerator o2) { - if (o1 instanceof PyFrameworkProjectGenerator && !(o2 instanceof PyFrameworkProjectGenerator)) return -1; - if (!(o1 instanceof PyFrameworkProjectGenerator) && o2 instanceof PyFrameworkProjectGenerator) return 1; - return o1.getName().compareTo(o2.getName()); - } + Arrays.sort(generators, (o1, o2) -> { + if (o1 instanceof PyFrameworkProjectGenerator && !(o2 instanceof PyFrameworkProjectGenerator)) return -1; + if (!(o1 instanceof PyFrameworkProjectGenerator) && o2 instanceof PyFrameworkProjectGenerator) return 1; + return o1.getName().compareTo(o2.getName()); }); return generators; } diff --git a/python/openapi/src/com/jetbrains/python/packaging/PyRequirement.java b/python/openapi/src/com/jetbrains/python/packaging/PyRequirement.java index 4337586363be..7879722ad09b 100644 --- a/python/openapi/src/com/jetbrains/python/packaging/PyRequirement.java +++ b/python/openapi/src/com/jetbrains/python/packaging/PyRequirement.java @@ -170,11 +170,8 @@ public class PyRequirement { @Override public String toString() { return myName + StringUtil.join(myVersionSpecs, - new Function() { - @Override - public String fun(VersionSpec spec) { - return spec.toString(); - } + spec -> { + return spec.toString(); }, "," ); diff --git a/python/pluginJava/com/jetbrains/python/facet/PythonFacet.java b/python/pluginJava/com/jetbrains/python/facet/PythonFacet.java index 53392024328d..95f278a1682e 100644 --- a/python/pluginJava/com/jetbrains/python/facet/PythonFacet.java +++ b/python/pluginJava/com/jetbrains/python/facet/PythonFacet.java @@ -38,78 +38,74 @@ public class PythonFacet extends Facet implements Libr } public void updateLibrary() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final Module module = getModule(); - final ModuleRootManager rootManager = ModuleRootManager.getInstance(module); - final ModifiableRootModel model = rootManager.getModifiableModel(); - boolean modelChanged = false; - try { - // Just remove all old facet libraries except one, that is necessary - final Sdk sdk = getConfiguration().getSdk(); - final String name = (sdk != null) ? getFacetLibraryName(sdk.getName()) : null; - boolean librarySeen = false; - for (OrderEntry entry : model.getOrderEntries()) { - if (entry instanceof LibraryOrderEntry) { - final String libraryName = ((LibraryOrderEntry)entry).getLibraryName(); - if (name != null && name.equals(libraryName)) { - librarySeen = true; - continue; - } - if (libraryName != null && libraryName.endsWith(PYTHON_FACET_LIBRARY_NAME_SUFFIX)) { - model.removeOrderEntry(entry); - modelChanged = true; - } + ApplicationManager.getApplication().runWriteAction(() -> { + final Module module = getModule(); + final ModuleRootManager rootManager = ModuleRootManager.getInstance(module); + final ModifiableRootModel model = rootManager.getModifiableModel(); + boolean modelChanged = false; + try { + // Just remove all old facet libraries except one, that is necessary + final Sdk sdk = getConfiguration().getSdk(); + final String name = (sdk != null) ? getFacetLibraryName(sdk.getName()) : null; + boolean librarySeen = false; + for (OrderEntry entry : model.getOrderEntries()) { + if (entry instanceof LibraryOrderEntry) { + final String libraryName = ((LibraryOrderEntry)entry).getLibraryName(); + if (name != null && name.equals(libraryName)) { + librarySeen = true; + continue; } - } - if (name != null) { - final ModifiableModelsProvider provider = ModifiableModelsProvider.SERVICE.getInstance(); - final LibraryTable.ModifiableModel libraryTableModifiableModel = provider.getLibraryTableModifiableModel(); - Library library = libraryTableModifiableModel.getLibraryByName(name); - provider.disposeLibraryTableModifiableModel(libraryTableModifiableModel); - if (library == null) { - // we just create new project library - library = PythonSdkTableListener.addLibrary(sdk); - } - if (!librarySeen) { - model.addLibraryEntry(library); + if (libraryName != null && libraryName.endsWith(PYTHON_FACET_LIBRARY_NAME_SUFFIX)) { + model.removeOrderEntry(entry); modelChanged = true; } } } - finally { - if (modelChanged){ - model.commit(); + if (name != null) { + final ModifiableModelsProvider provider = ModifiableModelsProvider.SERVICE.getInstance(); + final LibraryTable.ModifiableModel libraryTableModifiableModel = provider.getLibraryTableModifiableModel(); + Library library = libraryTableModifiableModel.getLibraryByName(name); + provider.disposeLibraryTableModifiableModel(libraryTableModifiableModel); + if (library == null) { + // we just create new project library + library = PythonSdkTableListener.addLibrary(sdk); } - else { - model.dispose(); + if (!librarySeen) { + model.addLibraryEntry(library); + modelChanged = true; } } } + finally { + if (modelChanged){ + model.commit(); + } + else { + model.dispose(); + } + } }); } public void removeLibrary() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final Module module = getModule(); - final ModuleRootManager rootManager = ModuleRootManager.getInstance(module); - final ModifiableRootModel model = rootManager.getModifiableModel(); - // Just remove all old facet libraries - for (OrderEntry entry : model.getOrderEntries()) { - if (entry instanceof LibraryOrderEntry) { - final Library library = ((LibraryOrderEntry)entry).getLibrary(); - if (library != null) { - final String libraryName = library.getName(); - if (libraryName!=null && libraryName.endsWith(PYTHON_FACET_LIBRARY_NAME_SUFFIX)) { - model.removeOrderEntry(entry); - //PyBuiltinCache.clearInstanceCache(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final Module module = getModule(); + final ModuleRootManager rootManager = ModuleRootManager.getInstance(module); + final ModifiableRootModel model = rootManager.getModifiableModel(); + // Just remove all old facet libraries + for (OrderEntry entry : model.getOrderEntries()) { + if (entry instanceof LibraryOrderEntry) { + final Library library = ((LibraryOrderEntry)entry).getLibrary(); + if (library != null) { + final String libraryName = library.getName(); + if (libraryName!=null && libraryName.endsWith(PYTHON_FACET_LIBRARY_NAME_SUFFIX)) { + model.removeOrderEntry(entry); + //PyBuiltinCache.clearInstanceCache(); } } } - model.commit(); } + model.commit(); }); } diff --git a/python/pluginJava/com/jetbrains/python/facet/PythonSdkTableListener.java b/python/pluginJava/com/jetbrains/python/facet/PythonSdkTableListener.java index d8958d74d847..f931adfa39dd 100644 --- a/python/pluginJava/com/jetbrains/python/facet/PythonSdkTableListener.java +++ b/python/pluginJava/com/jetbrains/python/facet/PythonSdkTableListener.java @@ -36,15 +36,9 @@ public class PythonSdkTableListener implements ApplicationComponent { ProjectJdkTable.Listener jdkTableListener = new ProjectJdkTable.Listener() { public void jdkAdded(final Sdk sdk) { if (sdk.getSdkType() instanceof PythonSdkType) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - addLibrary(sdk); - } - }); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> { + addLibrary(sdk); + })); } } @@ -77,40 +71,32 @@ public class PythonSdkTableListener implements ApplicationComponent { } private static void removeLibrary(final Sdk sdk) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final LibraryTable.ModifiableModel libraryTableModel = - ModifiableModelsProvider.SERVICE.getInstance().getLibraryTableModifiableModel(); - final Library library = libraryTableModel.getLibraryByName(PythonFacet.getFacetLibraryName(sdk.getName())); - if (library != null) { - libraryTableModel.removeLibrary(library); - } - libraryTableModel.commit(); - } - }); - } + ApplicationManager.getApplication().invokeLater(() -> { + ApplicationManager.getApplication().runWriteAction(() -> { + final LibraryTable.ModifiableModel libraryTableModel = + ModifiableModelsProvider.SERVICE.getInstance().getLibraryTableModifiableModel(); + final Library library = libraryTableModel.getLibraryByName(PythonFacet.getFacetLibraryName(sdk.getName())); + if (library != null) { + libraryTableModel.removeLibrary(library); + } + libraryTableModel.commit(); + }); }, ModalityState.NON_MODAL); } private static void renameLibrary(final Sdk sdk, final String previousName) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final LibraryTable.ModifiableModel libraryTableModel = - ModifiableModelsProvider.SERVICE.getInstance().getLibraryTableModifiableModel(); - final Library library = libraryTableModel.getLibraryByName(PythonFacet.getFacetLibraryName(previousName)); - if (library != null) { - final Library.ModifiableModel model = library.getModifiableModel(); - model.setName(PythonFacet.getFacetLibraryName(sdk.getName())); - model.commit(); - } - libraryTableModel.commit(); - } - }); - } + ApplicationManager.getApplication().invokeLater(() -> { + ApplicationManager.getApplication().runWriteAction(() -> { + final LibraryTable.ModifiableModel libraryTableModel = + ModifiableModelsProvider.SERVICE.getInstance().getLibraryTableModifiableModel(); + final Library library = libraryTableModel.getLibraryByName(PythonFacet.getFacetLibraryName(previousName)); + if (library != null) { + final Library.ModifiableModel model = library.getModifiableModel(); + model.setName(PythonFacet.getFacetLibraryName(sdk.getName())); + model.commit(); + } + libraryTableModel.commit(); + }); }, ModalityState.NON_MODAL); } diff --git a/python/pluginJava/com/jetbrains/python/psi/impl/PyJavaTypeProvider.java b/python/pluginJava/com/jetbrains/python/psi/impl/PyJavaTypeProvider.java index dcc1990d3c41..e91b55bab249 100644 --- a/python/pluginJava/com/jetbrains/python/psi/impl/PyJavaTypeProvider.java +++ b/python/pluginJava/com/jetbrains/python/psi/impl/PyJavaTypeProvider.java @@ -74,24 +74,22 @@ public class PyJavaTypeProvider extends PyTypeProviderBase { final int index = params.indexOf(param); if (index < 0) return null; final List superMethodParameterTypes = new ArrayList(); - PySuperMethodsSearch.search(func, context).forEach(new Processor() { - public boolean process(final PsiElement psiElement) { - if (psiElement instanceof PsiMethod) { - final PsiMethod method = (PsiMethod)psiElement; - final PsiParameter[] psiParameters = method.getParameterList().getParameters(); - int javaIndex = method.hasModifierProperty(PsiModifier.STATIC) ? index : index-1; // adjust for 'self' parameter - if (javaIndex < psiParameters.length) { - PsiType paramType = psiParameters [javaIndex].getType(); - if (paramType instanceof PsiClassType) { - final PsiClass psiClass = ((PsiClassType)paramType).resolve(); - if (psiClass != null) { - superMethodParameterTypes.add(new PyJavaClassType(psiClass, false)); - } + PySuperMethodsSearch.search(func, context).forEach(psiElement -> { + if (psiElement instanceof PsiMethod) { + final PsiMethod method = (PsiMethod)psiElement; + final PsiParameter[] psiParameters = method.getParameterList().getParameters(); + int javaIndex = method.hasModifierProperty(PsiModifier.STATIC) ? index : index-1; // adjust for 'self' parameter + if (javaIndex < psiParameters.length) { + PsiType paramType = psiParameters [javaIndex].getType(); + if (paramType instanceof PsiClassType) { + final PsiClass psiClass = ((PsiClassType)paramType).resolve(); + if (psiClass != null) { + superMethodParameterTypes.add(new PyJavaClassType(psiClass, false)); } } } - return true; } + return true; }); if (superMethodParameterTypes.size() > 0) { final PyType type = superMethodParameterTypes.get(0); diff --git a/python/psi-api/src/com/jetbrains/python/psi/PyClass.java b/python/psi-api/src/com/jetbrains/python/psi/PyClass.java index f018c14c651a..ede0a007a927 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/PyClass.java +++ b/python/psi-api/src/com/jetbrains/python/psi/PyClass.java @@ -39,13 +39,7 @@ import java.util.Map; */ public interface PyClass extends PsiNameIdentifierOwner, PyStatement, PyDocStringOwner, StubBasedPsiElement, ScopeOwner, PyDecoratable, PyTypedElement, PyQualifiedNameOwner, PyStatementListContainer, PyWithAncestors { - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public PyClass[] create(int count) { - return new PyClass[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new PyClass[count]; @Nullable ASTNode getNameNode(); diff --git a/python/psi-api/src/com/jetbrains/python/psi/PyFunction.java b/python/psi-api/src/com/jetbrains/python/psi/PyFunction.java index 577712f33ee0..f49001b62674 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/PyFunction.java +++ b/python/psi-api/src/com/jetbrains/python/psi/PyFunction.java @@ -38,13 +38,7 @@ public interface PyFunction extends PsiNamedElement, StubBasedPsiElement ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public PyFunction[] create(int count) { - return new PyFunction[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new PyFunction[count]; /** * Returns the AST node for the function name identifier. diff --git a/python/psi-api/src/com/jetbrains/python/psi/resolve/RatedResolveResult.java b/python/psi-api/src/com/jetbrains/python/psi/resolve/RatedResolveResult.java index 8485d2f45cb1..4025c7afe9e5 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/resolve/RatedResolveResult.java +++ b/python/psi-api/src/com/jetbrains/python/psi/resolve/RatedResolveResult.java @@ -83,11 +83,7 @@ public class RatedResolveResult implements ResolveResult { if (targets.size() == 1) { return targets; } - List ret = new SortedList(new Comparator() { - public int compare(final RatedResolveResult one, final RatedResolveResult another) { - return another.getRate() - one.getRate(); - } - }); + List ret = new SortedList((one, another) -> another.getRate() - one.getRate()); ret.addAll(targets); return ret; } diff --git a/python/pydevSrc/com/jetbrains/python/debugger/PyDebugValue.java b/python/pydevSrc/com/jetbrains/python/debugger/PyDebugValue.java index 02b1b591684e..8b218d297bae 100644 --- a/python/pydevSrc/com/jetbrains/python/debugger/PyDebugValue.java +++ b/python/pydevSrc/com/jetbrains/python/debugger/PyDebugValue.java @@ -179,23 +179,20 @@ public class PyDebugValue extends XNamedValue { @Override public void computeChildren(@NotNull final XCompositeNode node) { if (node.isObsolete()) return; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - if (myFrameAccessor == null) return; + ApplicationManager.getApplication().executeOnPooledThread(() -> { + if (myFrameAccessor == null) return; - try { - final XValueChildrenList values = myFrameAccessor.loadVariable(PyDebugValue.this); - if (!node.isObsolete()) { - node.addChildren(values, true); - } + try { + final XValueChildrenList values = myFrameAccessor.loadVariable(PyDebugValue.this); + if (!node.isObsolete()) { + node.addChildren(values, true); } - catch (PyDebuggerException e) { - if (!node.isObsolete()) { - node.setErrorMessage("Unable to display children:" + e.getMessage()); - } - LOG.warn(e); + } + catch (PyDebuggerException e) { + if (!node.isObsolete()) { + node.setErrorMessage("Unable to display children:" + e.getMessage()); } + LOG.warn(e); } }); } diff --git a/python/pydevSrc/com/jetbrains/python/debugger/PyValueModifier.java b/python/pydevSrc/com/jetbrains/python/debugger/PyValueModifier.java index 558baaa45171..8be3557f7aab 100644 --- a/python/pydevSrc/com/jetbrains/python/debugger/PyValueModifier.java +++ b/python/pydevSrc/com/jetbrains/python/debugger/PyValueModifier.java @@ -17,15 +17,13 @@ public class PyValueModifier extends XValueModifier { @Override public void setValue(@NotNull final String expression, @NotNull final XModificationCallback callback) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - try { - myDebugProcess.changeVariable(myVariable, expression); - callback.valueModified(); - } - catch (PyDebuggerException e) { - callback.errorOccurred(e.getTracebackError()); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + myDebugProcess.changeVariable(myVariable, expression); + callback.valueModified(); + } + catch (PyDebuggerException e) { + callback.errorOccurred(e.getTracebackError()); } }); } diff --git a/python/pydevSrc/com/jetbrains/python/debugger/pydev/AbstractCommand.java b/python/pydevSrc/com/jetbrains/python/debugger/pydev/AbstractCommand.java index 94e4adb12a41..e2b745f5b19a 100644 --- a/python/pydevSrc/com/jetbrains/python/debugger/pydev/AbstractCommand.java +++ b/python/pydevSrc/com/jetbrains/python/debugger/pydev/AbstractCommand.java @@ -148,22 +148,19 @@ public abstract class AbstractCommand { return; } - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - ProtocolFrame frame = myDebugger.waitForResponse(sequence); - if (frame == null) { - if (!myDebugger.isConnected()) { - throw new PyDebuggerException("No connection (command: " + myCommandCode + " )"); - } - throw new PyDebuggerException("Timeout waiting for response on " + myCommandCode); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + ProtocolFrame frame = myDebugger.waitForResponse(sequence); + if (frame == null) { + if (!myDebugger.isConnected()) { + throw new PyDebuggerException("No connection (command: " + myCommandCode + " )"); } - callback.ok(processor.processResponse(frame)); - } - catch (PyDebuggerException e) { - callback.error(e); + throw new PyDebuggerException("Timeout waiting for response on " + myCommandCode); } + callback.ok(processor.processResponse(frame)); + } + catch (PyDebuggerException e) { + callback.error(e); } }); } diff --git a/python/pydevSrc/com/jetbrains/python/debugger/pydev/MultiProcessDebugger.java b/python/pydevSrc/com/jetbrains/python/debugger/pydev/MultiProcessDebugger.java index 12ee08cf0f22..518948b3d536 100644 --- a/python/pydevSrc/com/jetbrains/python/debugger/pydev/MultiProcessDebugger.java +++ b/python/pydevSrc/com/jetbrains/python/debugger/pydev/MultiProcessDebugger.java @@ -65,16 +65,13 @@ public class MultiProcessDebugger implements ProcessDebugger { //noinspection SocketOpenedButNotSafelyClosed final Socket socket = myServerSocket.accept(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - //do we need any synchronization here with myMainDebugger.waitForConnect() ??? TODO - sendDebuggerPort(socket, myDebugServerSocket, myDebugProcess); - } - catch (Exception e) { - throw new RuntimeException(e); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + //do we need any synchronization here with myMainDebugger.waitForConnect() ??? TODO + sendDebuggerPort(socket, myDebugServerSocket, myDebugProcess); + } + catch (Exception e) { + throw new RuntimeException(e); } }); diff --git a/python/python-community-configure/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java b/python/python-community-configure/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java index df01a1c3130d..ce85b6f1b542 100644 --- a/python/python-community-configure/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java +++ b/python/python-community-configure/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java @@ -98,13 +98,11 @@ public class PyActiveSdkConfigurable implements UnnamedConfigurable { @Override public void setSelectedItem(Object item) { if (SHOW_ALL.equals(item)) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - PythonSdkDetailsDialog moreDialog = myModule == null - ? new PythonSdkDetailsDialog(myProject, myAddSdkCallback, getSettingsModifiedCallback()) - : new PythonSdkDetailsDialog(myModule, myAddSdkCallback, getSettingsModifiedCallback()); - moreDialog.show(); - } + ApplicationManager.getApplication().invokeLater(() -> { + PythonSdkDetailsDialog moreDialog = myModule == null + ? new PythonSdkDetailsDialog(myProject, myAddSdkCallback, getSettingsModifiedCallback()) + : new PythonSdkDetailsDialog(myModule, myAddSdkCallback, getSettingsModifiedCallback()); + moreDialog.show(); }); return; } @@ -187,12 +185,7 @@ public class PyActiveSdkConfigurable implements UnnamedConfigurable { @NotNull private Runnable getSettingsModifiedCallback() { - return new Runnable() { - @Override - public void run() { - mySdkSettingsWereModified = true; - } - }; + return () -> mySdkSettingsWereModified = true; } private void initContent() { @@ -322,11 +315,8 @@ public class PyActiveSdkConfigurable implements UnnamedConfigurable { } private void setSdk(final Sdk item) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectRootManager.getInstance(myProject).setProjectSdk(item); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManager.getInstance(myProject).setProjectSdk(item); }); if (myModule != null) { ModuleRootModificationUtil.setModuleSdk(myModule, item); diff --git a/python/python-community-configure/src/com/jetbrains/python/configuration/PyContentEntriesModuleConfigurable.java b/python/python-community-configure/src/com/jetbrains/python/configuration/PyContentEntriesModuleConfigurable.java index 1e8c8e24a247..8767ffe7f8e4 100644 --- a/python/python-community-configure/src/com/jetbrains/python/configuration/PyContentEntriesModuleConfigurable.java +++ b/python/python-community-configure/src/com/jetbrains/python/configuration/PyContentEntriesModuleConfigurable.java @@ -107,11 +107,8 @@ public class PyContentEntriesModuleConfigurable extends SearchableConfigurable.P final boolean editorWasModified = myEditor.isModified(); myEditor.apply(); if (editorWasModified) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myModifiableModel.commit(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myModifiableModel.commit(); }); resetEditor(); } diff --git a/python/python-community-configure/src/com/jetbrains/python/configuration/PyModuleDependenciesConfigurable.java b/python/python-community-configure/src/com/jetbrains/python/configuration/PyModuleDependenciesConfigurable.java index 0fb7233bf426..3abf8309c4c5 100644 --- a/python/python-community-configure/src/com/jetbrains/python/configuration/PyModuleDependenciesConfigurable.java +++ b/python/python-community-configure/src/com/jetbrains/python/configuration/PyModuleDependenciesConfigurable.java @@ -65,12 +65,7 @@ public class PyModuleDependenciesConfigurable implements UnnamedConfigurable { possibleDependencies.add(otherModule); } } - myDependenciesList.setItems(possibleDependencies, new Function() { - @Override - public String fun(Module module) { - return module.getName(); - } - }); + myDependenciesList.setItems(possibleDependencies, module -> module.getName()); myDependenciesList.setBorder(null); for (Module dependency : myInitialDependencies) { myDependenciesList.setItemSelected(dependency, true); @@ -101,24 +96,21 @@ public class PyModuleDependenciesConfigurable implements UnnamedConfigurable { @Override public void apply() throws ConfigurationException { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); - List entries = new ArrayList(); - for (OrderEntry entry : model.getOrderEntries()) { - if (entry instanceof ModuleOrderEntry) { - entries.add((ModuleOrderEntry) entry); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); + List entries = new ArrayList(); + for (OrderEntry entry : model.getOrderEntries()) { + if (entry instanceof ModuleOrderEntry) { + entries.add((ModuleOrderEntry) entry); } - for (ModuleOrderEntry entry : entries) { - model.removeOrderEntry(entry); - } - for (Module module : collectDependencies()) { - model.addModuleOrderEntry(module); - } - model.commit(); } + for (ModuleOrderEntry entry : entries) { + model.removeOrderEntry(entry); + } + for (Module module : collectDependencies()) { + model.addModuleOrderEntry(module); + } + model.commit(); }); } diff --git a/python/python-community-configure/src/com/jetbrains/python/configuration/PythonSdkDetailsDialog.java b/python/python-community-configure/src/com/jetbrains/python/configuration/PythonSdkDetailsDialog.java index 326671eb84f3..ed458a4e9938 100644 --- a/python/python-community-configure/src/com/jetbrains/python/configuration/PythonSdkDetailsDialog.java +++ b/python/python-community-configure/src/com/jetbrains/python/configuration/PythonSdkDetailsDialog.java @@ -275,12 +275,7 @@ public class PythonSdkDetailsDialog extends DialogWrapper { private void addSdk(AnActionButton button) { PythonSdkDetailsStep .show(myProject, myProjectSdksModel.getSdks(), null, myMainPanel, button.getPreferredPopupPoint().getScreenPoint(), - new NullableConsumer() { - @Override - public void consume(Sdk sdk) { - addCreatedSdk(sdk, true); - } - }); + sdk -> addCreatedSdk(sdk, true)); } private void addCreatedSdk(@Nullable final Sdk sdk, boolean newVirtualEnv) { @@ -335,14 +330,11 @@ public class PythonSdkDetailsDialog extends DialogWrapper { private void editSdk(final Sdk currentSdk) { final SdkModificator modificator = myModificators.get(currentSdk); - final EditSdkDialog dialog = new EditSdkDialog(myProject, modificator, new NullableFunction() { - @Override - public String fun(String s) { - if (isDuplicateSdkName(s, currentSdk)) { - return PyBundle.message("sdk.details.dialog.error.duplicate.name"); - } - return null; + final EditSdkDialog dialog = new EditSdkDialog(myProject, modificator, s -> { + if (isDuplicateSdkName(s, currentSdk)) { + return PyBundle.message("sdk.details.dialog.error.duplicate.name"); } + return null; }); if (dialog.showAndGet()) { mySdkList.repaint(); @@ -401,12 +393,7 @@ public class PythonSdkDetailsDialog extends DialogWrapper { final Sdk sdk = myProjectSdksModel.findSdk(currentSdk); final PySdkService sdkService = PySdkService.getInstance(); sdkService.removeSdk(currentSdk); - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() { - @Override - public void run() { - SdkConfigurationUtil.removeSdk(sdk); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, () -> SdkConfigurationUtil.removeSdk(sdk)); myProjectSdksModel.removeSdk(sdk); myProjectSdksModel.removeSdk(currentSdk); diff --git a/python/python-rest/src/com/jetbrains/rest/run/docutils/DocutilsCommandLineState.java b/python/python-rest/src/com/jetbrains/rest/run/docutils/DocutilsCommandLineState.java index e677f37b9763..e5a9f1894253 100644 --- a/python/python-rest/src/com/jetbrains/rest/run/docutils/DocutilsCommandLineState.java +++ b/python/python-rest/src/com/jetbrains/rest/run/docutils/DocutilsCommandLineState.java @@ -36,17 +36,14 @@ public class DocutilsCommandLineState extends RestCommandLineState { @Override protected Runnable getAfterTask() { - return new Runnable() { - @Override - public void run() { - VirtualFile virtualFile = findOutput(); - if (virtualFile != null) { - if (myConfiguration.openInBrowser()) { - BrowserUtil.browse(virtualFile); - } - else { - FileEditorManager.getInstance(myConfiguration.getProject()).openFile(virtualFile, true); - } + return () -> { + VirtualFile virtualFile = findOutput(); + if (virtualFile != null) { + if (myConfiguration.openInBrowser()) { + BrowserUtil.browse(virtualFile); + } + else { + FileEditorManager.getInstance(myConfiguration.getProject()).openFile(virtualFile, true); } } }; diff --git a/python/python-rest/src/com/jetbrains/rest/run/sphinx/SphinxCommandLineState.java b/python/python-rest/src/com/jetbrains/rest/run/sphinx/SphinxCommandLineState.java index 8bb913f178fd..7cbbf8c0493a 100644 --- a/python/python-rest/src/com/jetbrains/rest/run/sphinx/SphinxCommandLineState.java +++ b/python/python-rest/src/com/jetbrains/rest/run/sphinx/SphinxCommandLineState.java @@ -36,13 +36,10 @@ public class SphinxCommandLineState extends RestCommandLineState { @Override protected Runnable getAfterTask() { - return new Runnable() { - @Override - public void run() { - VirtualFile virtualFile = findOutput(); - if (virtualFile != null) - LocalFileSystem.getInstance().refreshFiles(Collections.singleton(virtualFile), false, true, null); - } + return () -> { + VirtualFile virtualFile = findOutput(); + if (virtualFile != null) + LocalFileSystem.getInstance().refreshFiles(Collections.singleton(virtualFile), false, true, null); }; } diff --git a/python/python-rest/src/com/jetbrains/rest/sphinx/RunSphinxQuickStartAction.java b/python/python-rest/src/com/jetbrains/rest/sphinx/RunSphinxQuickStartAction.java index 3891efc7a0aa..b32deb971a69 100644 --- a/python/python-rest/src/com/jetbrains/rest/sphinx/RunSphinxQuickStartAction.java +++ b/python/python-rest/src/com/jetbrains/rest/sphinx/RunSphinxQuickStartAction.java @@ -52,10 +52,8 @@ public class RunSphinxQuickStartAction extends AnAction implements DumbAware { if (module == null) return; final SphinxBaseCommand action = new SphinxBaseCommand(); final Module finalModule = module; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - action.execute(finalModule); - } + ApplicationManager.getApplication().invokeLater(() -> { + action.execute(finalModule); }, ModalityState.NON_MODAL); } } diff --git a/python/python-rest/src/com/jetbrains/rest/sphinx/SphinxBaseCommand.java b/python/python-rest/src/com/jetbrains/rest/sphinx/SphinxBaseCommand.java index f828623194be..62483d74cccc 100644 --- a/python/python-rest/src/com/jetbrains/rest/sphinx/SphinxBaseCommand.java +++ b/python/python-rest/src/com/jetbrains/rest/sphinx/SphinxBaseCommand.java @@ -108,12 +108,7 @@ public class SphinxBaseCommand { new RunContentExecutor(project, process) .withFilter(new PythonTracebackFilter(project)) .withTitle("reStructuredText") - .withRerun(new Runnable() { - @Override - public void run() { - execute(module); - } - }) + .withRerun(() -> execute(module)) .withAfterCompletion(getAfterTask(module)) .run(); } @@ -124,11 +119,9 @@ public class SphinxBaseCommand { @Nullable protected Runnable getAfterTask(final Module module) { - return new Runnable() { - public void run() { - final ReSTService service = ReSTService.getInstance(module); - LocalFileSystem.getInstance().refreshAndFindFileByPath(service.getWorkdir()); - } + return () -> { + final ReSTService service = ReSTService.getInstance(module); + LocalFileSystem.getInstance().refreshAndFindFileByPath(service.getWorkdir()); }; } diff --git a/python/src/com/jetbrains/commandInterface/console/CommandConsole.java b/python/src/com/jetbrains/commandInterface/console/CommandConsole.java index a2e497e3bae9..7a8abec8fd41 100644 --- a/python/src/com/jetbrains/commandInterface/console/CommandConsole.java +++ b/python/src/com/jetbrains/commandInterface/console/CommandConsole.java @@ -191,21 +191,18 @@ final class CommandConsole extends LanguageConsoleImpl implements Consumer "); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - notifyStateChangeListeners(); - configureLeftBorder(true, getConsoleEditor(), getHistoryViewer()); - setLanguage(CommandLineLanguage.INSTANCE); - final CommandLineFile file = PyUtil.as(getFile(), CommandLineFile.class); - resetConsumer(null); - if (file == null || myCommandsAndDefaultExecutor == null) { - return; - } - file.setCommands(myCommandsAndDefaultExecutor.first); - final CommandConsole console = CommandConsole.this; - resetConsumer(new CommandModeConsumer(myCommandsAndDefaultExecutor.first, myModule, console, myCommandsAndDefaultExecutor.second)); + ApplicationManager.getApplication().invokeAndWait(() -> { + notifyStateChangeListeners(); + configureLeftBorder(true, getConsoleEditor(), getHistoryViewer()); + setLanguage(CommandLineLanguage.INSTANCE); + final CommandLineFile file = PyUtil.as(getFile(), CommandLineFile.class); + resetConsumer(null); + if (file == null || myCommandsAndDefaultExecutor == null) { + return; } + file.setCommands(myCommandsAndDefaultExecutor.first); + final CommandConsole console = CommandConsole.this; + resetConsumer(new CommandModeConsumer(myCommandsAndDefaultExecutor.first, myModule, console, myCommandsAndDefaultExecutor.second)); }, ModalityState.NON_MODAL); } @@ -216,17 +213,14 @@ final class CommandConsole extends LanguageConsoleImpl implements Consumer { + configureLeftBorder(false, + getConsoleEditor()); // "bottom" part of console do not need padding now because it is used for user inputA + notifyStateChangeListeners(); + resetConsumer(new ProcessModeConsumer(processHandler)); + // In process mode we do not need prompt and highlighting + setLanguage(PlainTextLanguage.INSTANCE); + setPrompt(""); }, ModalityState.NON_MODAL); } diff --git a/python/src/com/jetbrains/python/PyCustomType.java b/python/src/com/jetbrains/python/PyCustomType.java index f8dd377fa589..f9a9713fa695 100644 --- a/python/src/com/jetbrains/python/PyCustomType.java +++ b/python/src/com/jetbrains/python/PyCustomType.java @@ -261,17 +261,14 @@ public class PyCustomType implements PyClassLikeType { @NotNull final TypeEvalContext context) { for (final PyClassLikeType type : myTypesToMimic) { // Only visit methods that are allowed by filter (if any) - type.visitMembers(new Processor() { - @Override - public boolean process(final PsiElement t) { - if (!(t instanceof PyElement)) { - return true; - } - if (myFilter == null || myFilter.process((PyElement)t)) { - return processor.process(t); - } + type.visitMembers(t -> { + if (!(t instanceof PyElement)) { return true; } + if (myFilter == null || myFilter.process((PyElement)t)) { + return processor.process(t); + } + return true; }, inherited, context); } } diff --git a/python/src/com/jetbrains/python/actions/CleanPycAction.java b/python/src/com/jetbrains/python/actions/CleanPycAction.java index 01eb5cedc20f..19cb3120b16b 100644 --- a/python/src/com/jetbrains/python/actions/CleanPycAction.java +++ b/python/src/com/jetbrains/python/actions/CleanPycAction.java @@ -43,32 +43,26 @@ public class CleanPycAction extends AnAction { final PsiElement[] elements = e.getData(LangDataKeys.PSI_ELEMENT_ARRAY); if (elements == null) return; final List pycFiles = new ArrayList(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - for (PsiElement element : elements) { - PsiDirectory dir = (PsiDirectory) element; - collectPycFiles(new File(dir.getVirtualFile().getPath()), pycFiles); - } - FileUtil.asyncDelete(pycFiles); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + for (PsiElement element : elements) { + PsiDirectory dir = (PsiDirectory) element; + collectPycFiles(new File(dir.getVirtualFile().getPath()), pycFiles); } + FileUtil.asyncDelete(pycFiles); }, "Cleaning up .pyc files...", false, e.getProject()); final StatusBar statusBar = WindowManager.getInstance().getIdeFrame(e.getProject()).getStatusBar(); statusBar.setInfo("Deleted " + pycFiles.size() + " bytecode file" + (pycFiles.size() != 1 ? "s" : "")); } private static void collectPycFiles(File directory, final List pycFiles) { - FileUtil.processFilesRecursively(directory, new Processor() { - @Override - public boolean process(File file) { - if (file.getParentFile().getName().equals(PyNames.PYCACHE) || - FileUtilRt.extensionEquals(file.getName(), "pyc") || - FileUtilRt.extensionEquals(file.getName(), "pyo") || - file.getName().endsWith("$py.class")) { - pycFiles.add(file); - } - return true; + FileUtil.processFilesRecursively(directory, file -> { + if (file.getParentFile().getName().equals(PyNames.PYCACHE) || + FileUtilRt.extensionEquals(file.getName(), "pyc") || + FileUtilRt.extensionEquals(file.getName(), "pyo") || + file.getName().endsWith("$py.class")) { + pycFiles.add(file); } + return true; }); } diff --git a/python/src/com/jetbrains/python/actions/CreatePackageAction.java b/python/src/com/jetbrains/python/actions/CreatePackageAction.java index d2fa4ac893b9..91a62e32d14e 100644 --- a/python/src/com/jetbrains/python/actions/CreatePackageAction.java +++ b/python/src/com/jetbrains/python/actions/CreatePackageAction.java @@ -63,13 +63,10 @@ public class CreatePackageAction extends DumbAwareAction { } } }; - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - public void run() { - Messages.showInputDialog(project, IdeBundle.message("prompt.enter.new.package.name"), - IdeBundle.message("title.new.package"), - Messages.getQuestionIcon(), "", validator); - } - }); + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> Messages.showInputDialog(project, IdeBundle.message("prompt.enter.new.package.name"), + IdeBundle.message("title.new.package"), + Messages.getQuestionIcon(), "", validator)); final PsiFileSystemItem result = validator.getCreatedElement(); if (result != null) { view.selectElement(result); diff --git a/python/src/com/jetbrains/python/actions/PyExecuteSelectionAction.java b/python/src/com/jetbrains/python/actions/PyExecuteSelectionAction.java index a1c412604e36..47334013ecce 100644 --- a/python/src/com/jetbrains/python/actions/PyExecuteSelectionAction.java +++ b/python/src/com/jetbrains/python/actions/PyExecuteSelectionAction.java @@ -99,12 +99,7 @@ public class PyExecuteSelectionAction extends AnAction { Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); Module module = e.getData(LangDataKeys.MODULE); - findCodeExecutor(e, new Consumer() { - @Override - public void consume(PyCodeExecutor codeExecutor) { - executeInConsole(codeExecutor, selectionText, editor); - } - }, editor, project, module); + findCodeExecutor(e, codeExecutor -> executeInConsole(codeExecutor, selectionText, editor), editor, project, module); } private static String getLineUnderCaret(Editor editor) { @@ -178,12 +173,9 @@ public class PyExecuteSelectionAction extends AnAction { Collection consoles = getConsoles(project); ExecutionHelper - .selectContentDescriptor(dataContext, project, consoles, "Select console to execute in", new Consumer() { - @Override - public void consume(RunContentDescriptor descriptor) { - if (descriptor != null && descriptor.getExecutionConsole() instanceof PyCodeExecutor) { - consumer.consume((PyCodeExecutor)descriptor.getExecutionConsole()); - } + .selectContentDescriptor(dataContext, project, consoles, "Select console to execute in", descriptor -> { + if (descriptor != null && descriptor.getExecutionConsole() instanceof PyCodeExecutor) { + consumer.consume((PyCodeExecutor)descriptor.getExecutionConsole()); } }); } @@ -197,13 +189,7 @@ public class PyExecuteSelectionAction extends AnAction { } Collection descriptors = - ExecutionHelper.findRunningConsole(project, new NotNullFunction() { - @NotNull - @Override - public Boolean fun(RunContentDescriptor dom) { - return dom.getExecutionConsole() instanceof PyCodeExecutor && isAlive(dom); - } - }); + ExecutionHelper.findRunningConsole(project, dom -> dom.getExecutionConsole() instanceof PyCodeExecutor && isAlive(dom)); if (descriptors.isEmpty() && toolWindow != null) { return toolWindow.getConsoleContentDescriptors(); @@ -235,15 +221,12 @@ public class PyExecuteSelectionAction extends AnAction { final PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(project); if (toolWindow != null) { - toolWindow.activate(new Runnable() { - @Override - public void run() { - List descs = toolWindow.getConsoleContentDescriptors(); + toolWindow.activate(() -> { + List descs = toolWindow.getConsoleContentDescriptors(); - RunContentDescriptor descriptor = descs.get(0); - if (descriptor != null && descriptor.getExecutionConsole() instanceof PyCodeExecutor) { - consumer.consume((PyCodeExecutor)descriptor.getExecutionConsole()); - } + RunContentDescriptor descriptor = descs.get(0); + if (descriptor != null && descriptor.getExecutionConsole() instanceof PyCodeExecutor) { + consumer.consume((PyCodeExecutor)descriptor.getExecutionConsole()); } }); } diff --git a/python/src/com/jetbrains/python/buildout/BuildoutConfigPanel.java b/python/src/com/jetbrains/python/buildout/BuildoutConfigPanel.java index eceedeb00050..9a880acbbf1d 100644 --- a/python/src/com/jetbrains/python/buildout/BuildoutConfigPanel.java +++ b/python/src/com/jetbrains/python/buildout/BuildoutConfigPanel.java @@ -119,11 +119,8 @@ public class BuildoutConfigPanel extends JPanel { public void reset() { final List scriptFiles = BuildoutFacet.getScripts(BuildoutFacet.getInstance(myModule), myModule.getProject().getBaseDir()); - final List scripts = ContainerUtil.map(scriptFiles, new Function() { - @Override - public String fun(File file) { - return file.getPath(); - } + final List scripts = ContainerUtil.map(scriptFiles, file -> { + return file.getPath(); }); myScript.getComboBox().setModel(new CollectionComboBoxModel(scripts, myConfiguration.getScriptName())); myScript.getComboBox().getEditor().setItem(myConfiguration.getScriptName()); diff --git a/python/src/com/jetbrains/python/buildout/BuildoutFacet.java b/python/src/com/jetbrains/python/buildout/BuildoutFacet.java index 322f5c42ee80..c592b7880a60 100644 --- a/python/src/com/jetbrains/python/buildout/BuildoutFacet.java +++ b/python/src/com/jetbrains/python/buildout/BuildoutFacet.java @@ -355,15 +355,12 @@ public class BuildoutFacet extends Facet implements } } if (rootPath != null) { - final File[] scripts = new File(rootPath, "bin").listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - if (SystemInfo.isWindows) { - return name.endsWith("-script.py"); - } - String ext = FileUtilRt.getExtension(name); - return ext.length() == 0 || FileUtil.namesEqual(ext, "py"); + final File[] scripts = new File(rootPath, "bin").listFiles((dir, name) -> { + if (SystemInfo.isWindows) { + return name.endsWith("-script.py"); } + String ext = FileUtilRt.getExtension(name); + return ext.length() == 0 || FileUtil.namesEqual(ext, "py"); }); if (scripts != null) { return Arrays.asList(scripts); diff --git a/python/src/com/jetbrains/python/codeInsight/PyLineMarkerNavigator.java b/python/src/com/jetbrains/python/codeInsight/PyLineMarkerNavigator.java index 8635876c2c6e..29ec36c6a6a8 100644 --- a/python/src/com/jetbrains/python/codeInsight/PyLineMarkerNavigator.java +++ b/python/src/com/jetbrains/python/codeInsight/PyLineMarkerNavigator.java @@ -48,13 +48,11 @@ abstract class PyLineMarkerNavigator implements GutterIcon if (elementQuery == null) { return; } - elementQuery.forEach(new Processor() { - public boolean process(final T psiElement) { - if (psiElement instanceof NavigatablePsiElement) { - navElements.add((NavigatablePsiElement)psiElement); - } - return true; + elementQuery.forEach(psiElement -> { + if (psiElement instanceof NavigatablePsiElement) { + navElements.add((NavigatablePsiElement)psiElement); } + return true; }); /** * For test purposes, we should be able to access list of methods to check em. diff --git a/python/src/com/jetbrains/python/codeInsight/PyLineMarkerProvider.java b/python/src/com/jetbrains/python/codeInsight/PyLineMarkerProvider.java index ea831fdd95d6..47688a516af9 100644 --- a/python/src/com/jetbrains/python/codeInsight/PyLineMarkerProvider.java +++ b/python/src/com/jetbrains/python/codeInsight/PyLineMarkerProvider.java @@ -62,44 +62,36 @@ public class PyLineMarkerProvider implements LineMarkerProvider, PyLineSeparator } } - private static final Function ourSubclassTooltipProvider = new Function() { - public String fun(PyClass pyClass) { - final StringBuilder builder = new StringBuilder("Is subclassed by:"); - final AtomicInteger count = new AtomicInteger(); - PyClassInheritorsSearch.search(pyClass, true).forEach(new Processor() { - public boolean process(PyClass pyClass) { - if (count.incrementAndGet() >= 10) { - builder.setLength(0); - builder.append("Has subclasses"); - return false; - } - builder.append("
        ").append(pyClass.getName()); - return true; - } - }); - return builder.toString(); - } + private static final Function ourSubclassTooltipProvider = pyClass -> { + final StringBuilder builder = new StringBuilder("Is subclassed by:"); + final AtomicInteger count = new AtomicInteger(); + PyClassInheritorsSearch.search(pyClass, true).forEach(pyClass1 -> { + if (count.incrementAndGet() >= 10) { + builder.setLength(0); + builder.append("Has subclasses"); + return false; + } + builder.append("
        ").append(pyClass1.getName()); + return true; + }); + return builder.toString(); }; - private static final Function ourOverridingMethodTooltipProvider = new Function() { - public String fun(final PyFunction pyFunction) { - final StringBuilder builder = new StringBuilder("Is overridden in:"); - final AtomicInteger count = new AtomicInteger(); - PyClassInheritorsSearch.search(pyFunction.getContainingClass(), true).forEach(new Processor() { - public boolean process(PyClass pyClass) { - if (count.incrementAndGet() >= 10) { - builder.setLength(0); - builder.append("Has overridden methods"); - return false; - } - if (pyClass.findMethodByName(pyFunction.getName(), false, null) != null) { - builder.append("
        ").append(pyClass.getName()); - } - return true; - } - }); - return builder.toString(); - } + private static final Function ourOverridingMethodTooltipProvider = pyFunction -> { + final StringBuilder builder = new StringBuilder("Is overridden in:"); + final AtomicInteger count = new AtomicInteger(); + PyClassInheritorsSearch.search(pyFunction.getContainingClass(), true).forEach(pyClass -> { + if (count.incrementAndGet() >= 10) { + builder.setLength(0); + builder.append("Has overridden methods"); + return false; + } + if (pyClass.findMethodByName(pyFunction.getName(), false, null) != null) { + builder.append("
        ").append(pyClass.getName()); + } + return true; + }); + return builder.toString(); }; private static final PyLineMarkerNavigator ourSuperMethodNavigator = new PyLineMarkerNavigator() { @@ -249,17 +241,15 @@ public class PyLineMarkerProvider implements LineMarkerProvider, PyLineSeparator } final Set overridden = new HashSet(); for (final PyClass pyClass : classes) { - PyClassInheritorsSearch.search(pyClass, true).forEach(new Processor() { - public boolean process(final PyClass inheritor) { - for (Iterator it = candidates.get(pyClass).iterator(); it.hasNext(); ) { - PyFunction func = it.next(); - if (inheritor.findMethodByName(func.getName(), false, null) != null) { - overridden.add(func); - it.remove(); - } + PyClassInheritorsSearch.search(pyClass, true).forEach(inheritor -> { + for (Iterator it = candidates.get(pyClass).iterator(); it.hasNext(); ) { + PyFunction func = it.next(); + if (inheritor.findMethodByName(func.getName(), false, null) != null) { + overridden.add(func); + it.remove(); } - return !candidates.isEmpty(); } + return !candidates.isEmpty(); }); if (candidates.isEmpty()) break; } diff --git a/python/src/com/jetbrains/python/codeInsight/PyLineSeparatorUtil.java b/python/src/com/jetbrains/python/codeInsight/PyLineSeparatorUtil.java index c22445815079..81686b980dee 100644 --- a/python/src/com/jetbrains/python/codeInsight/PyLineSeparatorUtil.java +++ b/python/src/com/jetbrains/python/codeInsight/PyLineSeparatorUtil.java @@ -41,30 +41,28 @@ public class PyLineSeparatorUtil { public static LineMarkerInfo addLineSeparatorIfNeeded(final Provider provider, final PsiElement element) { final Ref info = new Ref(null); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - if (!provider.isSeparatorAllowed(element)) { - return; - } - boolean hasSeparableBefore = false; - final PsiElement parent = element.getParent(); - if (parent == null) { - return; - } - for (PsiElement child : parent.getChildren()) { - if (child == element){ - break; - } - if (provider.isSeparatorAllowed(child)) { - hasSeparableBefore = true; - break; - } - } - if (!hasSeparableBefore) { - return; - } - info.set(createLineSeparatorByElement(element)); + ApplicationManager.getApplication().runReadAction(() -> { + if (!provider.isSeparatorAllowed(element)) { + return; } + boolean hasSeparableBefore = false; + final PsiElement parent = element.getParent(); + if (parent == null) { + return; + } + for (PsiElement child : parent.getChildren()) { + if (child == element){ + break; + } + if (provider.isSeparatorAllowed(child)) { + hasSeparableBefore = true; + break; + } + } + if (!hasSeparableBefore) { + return; + } + info.set(createLineSeparatorByElement(element)); }); return info.get(); } diff --git a/python/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java b/python/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java index bac27082b23f..1087f711ba1f 100644 --- a/python/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java +++ b/python/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java @@ -38,12 +38,7 @@ public class PyMetaClassCompletionContributor extends CompletionContributor { .psiElement() .withLanguage(PythonLanguage.getInstance()) .withParents(PyReferenceExpression.class, PyExpressionStatement.class, PyStatementList.class, PyClass.class) - .and(hasLanguageLevel(new Processor() { - @Override - public boolean process(LanguageLevel level) { - return level.isOlderThan(LanguageLevel.PYTHON30); - } - })), + .and(hasLanguageLevel(level -> level.isOlderThan(LanguageLevel.PYTHON30))), new CompletionProvider() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, @@ -57,12 +52,7 @@ public class PyMetaClassCompletionContributor extends CompletionContributor { .psiElement() .withLanguage(PythonLanguage.getInstance()) .withParents(PyReferenceExpression.class, PyArgumentList.class, PyClass.class) - .and(hasLanguageLevel(new Processor() { - @Override - public boolean process(LanguageLevel level) { - return level.isAtLeast(LanguageLevel.PYTHON30); - } - })), + .and(hasLanguageLevel(level -> level.isAtLeast(LanguageLevel.PYTHON30))), new CompletionProvider() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, diff --git a/python/src/com/jetbrains/python/codeInsight/editorActions/moveUpDown/PyStatementMover.java b/python/src/com/jetbrains/python/codeInsight/editorActions/moveUpDown/PyStatementMover.java index 684bd0c65e07..fba97072271a 100644 --- a/python/src/com/jetbrains/python/codeInsight/editorActions/moveUpDown/PyStatementMover.java +++ b/python/src/com/jetbrains/python/codeInsight/editorActions/moveUpDown/PyStatementMover.java @@ -328,33 +328,30 @@ public class PyStatementMover extends LineMover { if (toMove instanceof MyLineRange && toMove2 instanceof ScopeRange) { - PostprocessReformattingAspect.getInstance(editor.getProject()).disablePostprocessFormattingInside(new Runnable() { - @Override - public void run() { - final PsiElement startToMove = ((MyLineRange)toMove).myStartElement; - final PsiElement endToMove = ((MyLineRange)toMove).myEndElement; - final PsiFile file = startToMove.getContainingFile(); - final SelectionModel selectionModel = editor.getSelectionModel(); - final CaretModel caretModel = editor.getCaretModel(); + PostprocessReformattingAspect.getInstance(editor.getProject()).disablePostprocessFormattingInside(() -> { + final PsiElement startToMove = ((MyLineRange)toMove).myStartElement; + final PsiElement endToMove = ((MyLineRange)toMove).myEndElement; + final PsiFile file = startToMove.getContainingFile(); + final SelectionModel selectionModel = editor.getSelectionModel(); + final CaretModel caretModel = editor.getCaretModel(); - final int selectionStart = selectionModel.getSelectionStart(); - boolean isSelectionStartAtCaret = caretModel.getOffset() == selectionStart; - final SelectionContainer selectionLen = getSelectionLenContainer(editor, ((MyLineRange)toMove)); + final int selectionStart = selectionModel.getSelectionStart(); + boolean isSelectionStartAtCaret = caretModel.getOffset() == selectionStart; + final SelectionContainer selectionLen = getSelectionLenContainer(editor, ((MyLineRange)toMove)); - int shift = getCaretShift(startToMove, endToMove, caretModel, isSelectionStartAtCaret); + int shift = getCaretShift(startToMove, endToMove, caretModel, isSelectionStartAtCaret); - final boolean hasSelection = selectionModel.hasSelection(); - int offset; - if (((ScopeRange)toMove2).isTheSameLevel()) { - offset = moveTheSameLevel((ScopeRange)toMove2, (MyLineRange)toMove); - } - else { - offset = moveInOut(((MyLineRange)toMove), editor, info); - } - restoreCaretAndSelection(file, editor, isSelectionStartAtCaret, hasSelection, selectionLen, - shift, offset, (MyLineRange)toMove); - info.toMove2 = info.toMove; //do not move further + final boolean hasSelection = selectionModel.hasSelection(); + int offset; + if (((ScopeRange)toMove2).isTheSameLevel()) { + offset = moveTheSameLevel((ScopeRange)toMove2, (MyLineRange)toMove); } + else { + offset = moveInOut(((MyLineRange)toMove), editor, info); + } + restoreCaretAndSelection(file, editor, isSelectionStartAtCaret, hasSelection, selectionLen, + shift, offset, (MyLineRange)toMove); + info.toMove2 = info.toMove; //do not move further }); } @@ -532,16 +529,13 @@ public class PyStatementMover extends LineMover { adjustLineIndents(editor, scope, project, addedElement, toMove.size); if (removePass) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final Document document = editor.getDocument(); - final int lineNumber = document.getLineNumber(anchor.getTextOffset()); - final int endOffset = document.getLineCount() <= lineNumber + 1 ? document.getLineEndOffset(lineNumber) - : document.getLineStartOffset(lineNumber + 1); - document.deleteString(document.getLineStartOffset(lineNumber), endOffset); - PsiDocumentManager.getInstance(startElement.getProject()).commitAllDocuments(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final Document document = editor.getDocument(); + final int lineNumber = document.getLineNumber(anchor.getTextOffset()); + final int endOffset = document.getLineCount() <= lineNumber + 1 ? document.getLineEndOffset(lineNumber) + : document.getLineStartOffset(lineNumber + 1); + document.deleteString(document.getLineStartOffset(lineNumber), endOffset); + PsiDocumentManager.getInstance(startElement.getProject()).commitAllDocuments(); }); } diff --git a/python/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java b/python/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java index b547a5b254d6..51a91b94a752 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java @@ -136,11 +136,7 @@ public class AutoImportQuickFix extends LocalQuickFixOnPsiElement implements Hig ImportCandidateHolder.getQualifiedName(myInitialName, myImports.get(0).getPath(), myImports.get(0).getImportElement()) ); final ImportFromExistingAction action = new ImportFromExistingAction(element, myImports, myInitialName, myUseQualifiedImport, false); - action.onDone(new Runnable() { - public void run() { - myExpended = true; - } - }); + action.onDone(() -> myExpended = true); HintManager.getInstance().showQuestionHint( editor, message, element.getTextOffset(), diff --git a/python/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java b/python/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java index bb4dada71ddf..7a89e911db52 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java @@ -140,12 +140,8 @@ class ImportCandidateHolder implements Comparable { sb.append(((PyFunction)myImportable).getParameterList().getPresentableText(false)); } else if (myImportable instanceof PyClass) { - final List supers = ContainerUtil.mapNotNull(((PyClass)myImportable).getSuperClasses(null), new Function() { - @Override - public String fun(PyClass cls) { - return PyUtil.isObjectClass(cls) ? null : cls.getName(); - } - }); + final List supers = ContainerUtil.mapNotNull(((PyClass)myImportable).getSuperClasses(null), + cls -> PyUtil.isObjectClass(cls) ? null : cls.getName()); if (!supers.isEmpty()) { sb.append("("); StringUtil.join(supers, ", ", sb); diff --git a/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java b/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java index eafcb8284ec3..b1bfd4d6f06d 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java @@ -108,14 +108,12 @@ public class ImportFromExistingAction implements QuestionAction { final JList list = new JBList(items); list.setCellRenderer(new CellRenderer(myName)); - final Runnable runnable = new Runnable() { - public void run() { - final Object selected = list.getSelectedValue(); - if (selected instanceof ImportCandidateHolder) { - final ImportCandidateHolder item = (ImportCandidateHolder)selected; - PsiDocumentManager.getInstance(myTarget.getProject()).commitAllDocuments(); - doWriteAction(item); - } + final Runnable runnable = () -> { + final Object selected = list.getSelectedValue(); + if (selected instanceof ImportCandidateHolder) { + final ImportCandidateHolder item = (ImportCandidateHolder)selected; + PsiDocumentManager.getInstance(myTarget.getProject()).commitAllDocuments(); + doWriteAction(item); } }; @@ -125,12 +123,7 @@ public class ImportFromExistingAction implements QuestionAction { new PopupChooserBuilder(list) .setTitle(myUseQualifiedImport? PyBundle.message("ACT.qualify.with.module") : PyBundle.message("ACT.from.some.module.import")) .setItemChoosenCallback(runnable) - .setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return ((ImportCandidateHolder) o).getPresentableText(myName); - } - }) + .setFilteringEnabled(o -> ((ImportCandidateHolder) o).getPresentableText(myName)) .createPopup() .showInBestPositionFor(dataContext); } diff --git a/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java b/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java index a4e9ca4abb24..176d1535b034 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/PyImportOptimizer.java @@ -55,13 +55,10 @@ public class PyImportOptimizer implements ImportOptimizer { node.accept(visitor); } }); - return new Runnable() { - @Override - public void run() { - visitor.optimizeImports(); - if (file instanceof PyFile) { - new ImportSorter((PyFile)file).run(); - } + return () -> { + visitor.optimizeImports(); + if (file instanceof PyFile) { + new ImportSorter((PyFile)file).run(); } }; } diff --git a/python/src/com/jetbrains/python/codeInsight/intentions/PyConvertTripleQuotedStringIntention.java b/python/src/com/jetbrains/python/codeInsight/intentions/PyConvertTripleQuotedStringIntention.java index f5be2b97273a..ae6e61198042 100644 --- a/python/src/com/jetbrains/python/codeInsight/intentions/PyConvertTripleQuotedStringIntention.java +++ b/python/src/com/jetbrains/python/codeInsight/intentions/PyConvertTripleQuotedStringIntention.java @@ -181,11 +181,8 @@ public class PyConvertTripleQuotedStringIntention extends BaseIntentionAction { @NotNull private static List extractStringNodesInfo(@NotNull PyStringLiteralExpression expression) { - return ContainerUtil.map(expression.getStringNodes(), new Function() { - @Override - public StringNodeInfo fun(ASTNode node) { - return new StringNodeInfo(node); - } + return ContainerUtil.map(expression.getStringNodes(), node -> { + return new StringNodeInfo(node); }); } } diff --git a/python/src/com/jetbrains/python/codeInsight/override/PyMethodMember.java b/python/src/com/jetbrains/python/codeInsight/override/PyMethodMember.java index f7819f6cdade..e9490dd57b29 100644 --- a/python/src/com/jetbrains/python/codeInsight/override/PyMethodMember.java +++ b/python/src/com/jetbrains/python/codeInsight/override/PyMethodMember.java @@ -38,11 +38,8 @@ public class PyMethodMember extends PsiElementMemberChooserObject implements Cla if (element instanceof PyFunction) { final TypeEvalContext context = TypeEvalContext.userInitiated(element.getProject(), element.getContainingFile()); final List parameters = PyUtil.getParameters((PyFunction)element, context); - return element.getName() + "(" + StringUtil.join(parameters, new Function() { - @Override - public String fun(PyParameter parameter) { - return PyUtil.getReadableRepr(parameter, false); - } + return element.getName() + "(" + StringUtil.join(parameters, parameter -> { + return PyUtil.getReadableRepr(parameter, false); }, ", ") + ")"; } if (element instanceof PyClass && PyNames.FAKE_OLD_BASE.equals(element.getName())) { diff --git a/python/src/com/jetbrains/python/codeInsight/testIntegration/CreateTestAction.java b/python/src/com/jetbrains/python/codeInsight/testIntegration/CreateTestAction.java index 217f60f5a959..dbcdf3d7549b 100644 --- a/python/src/com/jetbrains/python/codeInsight/testIntegration/CreateTestAction.java +++ b/python/src/com/jetbrains/python/codeInsight/testIntegration/CreateTestAction.java @@ -76,13 +76,10 @@ public class CreateTestAction extends PsiElementBaseIntentionAction { } else { final List methods = Lists.newArrayList(); - srcClass.visitMethods(new Processor() { - @Override - public boolean process(PyFunction pyFunction) { - if (pyFunction.getName() != null && !pyFunction.getName().startsWith("__")) - methods.add(pyFunction); - return true; - } + srcClass.visitMethods(pyFunction -> { + if (pyFunction.getName() != null && !pyFunction.getName().startsWith("__")) + methods.add(pyFunction); + return true; }, false, null); d.methodsSize(methods.size()); @@ -106,13 +103,10 @@ public class CreateTestAction extends PsiElementBaseIntentionAction { if (!d.showAndGet()) { return; } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - PsiFile e = PyTestCreator.generateTestAndNavigate(project, d); - final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); - documentManager.commitAllDocuments(); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + PsiFile e = PyTestCreator.generateTestAndNavigate(project, d); + final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); + documentManager.commitAllDocuments(); }, CodeInsightBundle.message("intention.create.test"), this); } } \ No newline at end of file diff --git a/python/src/com/jetbrains/python/codeInsight/userSkeletons/PyUserSkeletonsLineMarkerProvider.java b/python/src/com/jetbrains/python/codeInsight/userSkeletons/PyUserSkeletonsLineMarkerProvider.java index 6c7c211671b6..596c178f1485 100644 --- a/python/src/com/jetbrains/python/codeInsight/userSkeletons/PyUserSkeletonsLineMarkerProvider.java +++ b/python/src/com/jetbrains/python/codeInsight/userSkeletons/PyUserSkeletonsLineMarkerProvider.java @@ -55,12 +55,7 @@ public class PyUserSkeletonsLineMarkerProvider implements LineMarkerProvider { if (skeleton != null) { result.add(new LineMarkerInfo( element, element.getTextRange(), ICON, Pass.UPDATE_OVERRIDDEN_MARKERS, - new Function() { - @Override - public String fun(PsiElement e) { - return "Has user skeleton"; - } - }, + e -> "Has user skeleton", new GutterIconNavigationHandler() { @Override public void navigate(MouseEvent e, PsiElement elt) { diff --git a/python/src/com/jetbrains/python/console/PyConsoleDebugProcess.java b/python/src/com/jetbrains/python/console/PyConsoleDebugProcess.java index 71ec989dbc89..56199e8bf12b 100644 --- a/python/src/com/jetbrains/python/console/PyConsoleDebugProcess.java +++ b/python/src/com/jetbrains/python/console/PyConsoleDebugProcess.java @@ -120,12 +120,7 @@ public class PyConsoleDebugProcess extends PyDebugProcess { if (!isWaitingForConnection()) { setWaitingForConnection(true); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - waitForConnection(getCurrentStateMessage(), getConnectionTitle()); - } - }); + UIUtil.invokeLaterIfNeeded(() -> waitForConnection(getCurrentStateMessage(), getConnectionTitle())); } } } diff --git a/python/src/com/jetbrains/python/console/PyConsoleSpecificOptionsPanel.java b/python/src/com/jetbrains/python/console/PyConsoleSpecificOptionsPanel.java index 2dabd93224ab..9c948f0c9095 100644 --- a/python/src/com/jetbrains/python/console/PyConsoleSpecificOptionsPanel.java +++ b/python/src/com/jetbrains/python/console/PyConsoleSpecificOptionsPanel.java @@ -73,12 +73,7 @@ public class PyConsoleSpecificOptionsPanel { } public void reset() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myEditorTextField.setText(myConsoleSettings.myCustomStartScript); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myEditorTextField.setText(myConsoleSettings.myCustomStartScript)); myConsoleSettings.reset(myProject, myCommonOptionsForm); } diff --git a/python/src/com/jetbrains/python/console/PyConsoleUtil.java b/python/src/com/jetbrains/python/console/PyConsoleUtil.java index 18129128dce4..f37ed1eb78f5 100644 --- a/python/src/com/jetbrains/python/console/PyConsoleUtil.java +++ b/python/src/com/jetbrains/python/console/PyConsoleUtil.java @@ -95,12 +95,8 @@ public class PyConsoleUtil { } public static void scrollDown(final Editor currentEditor) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - currentEditor.getCaretModel().moveToOffset(currentEditor.getDocument().getTextLength()); - } - }); + ApplicationManager.getApplication().invokeLater( + () -> currentEditor.getCaretModel().moveToOffset(currentEditor.getDocument().getTextLength())); } public static boolean isSingleQuoteMultilineStarts(String line) { diff --git a/python/src/com/jetbrains/python/console/PyOpenDebugConsoleAction.java b/python/src/com/jetbrains/python/console/PyOpenDebugConsoleAction.java index de671e33464b..4cf9a7321871 100644 --- a/python/src/com/jetbrains/python/console/PyOpenDebugConsoleAction.java +++ b/python/src/com/jetbrains/python/console/PyOpenDebugConsoleAction.java @@ -56,12 +56,9 @@ public class PyOpenDebugConsoleAction extends AnAction implements DumbAware { public void actionPerformed(final AnActionEvent e) { final Project project = e.getData(CommonDataKeys.PROJECT); if (project != null) { - selectRunningProcess(e.getDataContext(), project, new Consumer() { - @Override - public void consume(PythonDebugLanguageConsoleView view) { - view.enableConsole(false); - IdeFocusManager.getInstance(project).requestFocus(view.getPydevConsoleView().getComponent(), true); - } + selectRunningProcess(e.getDataContext(), project, view -> { + view.enableConsole(false); + IdeFocusManager.getInstance(project).requestFocus(view.getPydevConsoleView().getComponent(), true); }); } } @@ -72,24 +69,16 @@ public class PyOpenDebugConsoleAction extends AnAction implements DumbAware { Collection consoles = getConsoles(project); ExecutionHelper - .selectContentDescriptor(dataContext, project, consoles, "Select running python process", new Consumer() { - @Override - public void consume(RunContentDescriptor descriptor) { - if (descriptor != null && descriptor.getExecutionConsole() instanceof PythonDebugLanguageConsoleView) { - consumer.consume((PythonDebugLanguageConsoleView)descriptor.getExecutionConsole()); - } + .selectContentDescriptor(dataContext, project, consoles, "Select running python process", descriptor -> { + if (descriptor != null && descriptor.getExecutionConsole() instanceof PythonDebugLanguageConsoleView) { + consumer.consume((PythonDebugLanguageConsoleView)descriptor.getExecutionConsole()); } }); } private static Collection getConsoles(Project project) { - return ExecutionHelper.findRunningConsole(project, new NotNullFunction() { - @NotNull - @Override - public Boolean fun(RunContentDescriptor dom) { - return dom.getExecutionConsole() instanceof PythonDebugLanguageConsoleView && isAlive(dom); - } - }); + return ExecutionHelper.findRunningConsole(project, + dom -> dom.getExecutionConsole() instanceof PythonDebugLanguageConsoleView && isAlive(dom)); } private static boolean isAlive(RunContentDescriptor dom) { diff --git a/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java b/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java index 29dd576405ec..f8fcd61e8483 100644 --- a/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java +++ b/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java @@ -209,17 +209,14 @@ public class PydevConsoleCommunication extends AbstractConsoleCommunication impl final VirtualFile file = StringUtil.isEmpty(path) ? null : LocalFileSystem.getInstance().findFileByPath(path); if (file != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - AccessToken at = ApplicationManager.getApplication().acquireReadActionLock(); + ApplicationManager.getApplication().invokeLater(() -> { + AccessToken at = ApplicationManager.getApplication().acquireReadActionLock(); - try { - FileEditorManager.getInstance(myProject).openFile(file, true); - } - finally { - at.finish(); - } + try { + FileEditorManager.getInstance(myProject).openFile(file, true); + } + finally { + at.finish(); } }); @@ -416,35 +413,32 @@ public class PydevConsoleCommunication extends AbstractConsoleCommunication impl //busy loop waiting for the answer (or having the console die). - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - progressIndicator.setText("Waiting for REPL response with " + (int)(TIMEOUT / 10e8) + "s timeout"); - final long startTime = System.nanoTime(); - while (nextResponse == null) { - if (progressIndicator.isCanceled()) { - LOG.debug("Canceled"); - nextResponse = new InterpreterResponse(false, false); - } + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + progressIndicator.setText("Waiting for REPL response with " + (int)(TIMEOUT / 10e8) + "s timeout"); + final long startTime = System.nanoTime(); + while (nextResponse == null) { + if (progressIndicator.isCanceled()) { + LOG.debug("Canceled"); + nextResponse = new InterpreterResponse(false, false); + } - final long time = System.nanoTime() - startTime; - progressIndicator.setFraction(((double)time) / TIMEOUT); - if (time > TIMEOUT) { - LOG.debug("Timeout exceeded"); - nextResponse = new InterpreterResponse(false, false); + final long time = System.nanoTime() - startTime; + progressIndicator.setFraction(((double)time) / TIMEOUT); + if (time > TIMEOUT) { + LOG.debug("Timeout exceeded"); + nextResponse = new InterpreterResponse(false, false); + } + synchronized (lock2) { + try { + lock2.wait(20); } - synchronized (lock2) { - try { - lock2.wait(20); - } - catch (InterruptedException e) { - LOG.error(e); - } + catch (InterruptedException e) { + LOG.error(e); } } - onResponseReceived.fun(nextResponse); } + onResponseReceived.fun(nextResponse); }, "Waiting for REPL response", true, myProject); } } diff --git a/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java b/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java index 2eaa25b67ee9..4f1b10b78692 100644 --- a/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java +++ b/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java @@ -203,41 +203,33 @@ public class PydevConsoleExecuteActionHandler extends ProcessBackedConsoleExecut else { executingPrompt(); } - myConsoleCommunication.execInterpreter(code, new Function() { - @Override - public Object fun(final InterpreterResponse interpreterResponse) { - // clear - myInputBuffer = null; + myConsoleCommunication.execInterpreter(code, interpreterResponse -> { + // clear + myInputBuffer = null; - //notify listeners like xdebugger variables view re-builder - getConsoleCommunication().notifyCommandExecuted(interpreterResponse.more); + //notify listeners like xdebugger variables view re-builder + getConsoleCommunication().notifyCommandExecuted(interpreterResponse.more); - // Handle prompt - if (interpreterResponse.more) { - more(); - if (myCurrentIndentSize == 0) { - // compute current indentation - setCurrentIndentSize( - IndentHelperImpl.getIndent(getProject(), PythonFileType.INSTANCE, lastLine(code.getText()), false) + getPythonIndent()); - // In this case we can insert indent automatically - final EditorEx editor = myConsoleView.getConsoleEditor(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - indentEditor(editor, myCurrentIndentSize); - } - }); - } + // Handle prompt + if (interpreterResponse.more) { + more(); + if (myCurrentIndentSize == 0) { + // compute current indentation + setCurrentIndentSize( + IndentHelperImpl.getIndent(getProject(), PythonFileType.INSTANCE, lastLine(code.getText()), false) + getPythonIndent()); + // In this case we can insert indent automatically + final EditorEx editor = myConsoleView.getConsoleEditor(); + UIUtil.invokeLaterIfNeeded(() -> indentEditor(editor, myCurrentIndentSize)); } - else { - if (!myConsoleCommunication.isWaitingForInput()) { - inPrompt(); - } - setCurrentIndentSize(0); - } - - return null; } + else { + if (!myConsoleCommunication.isWaitingForInput()) { + inPrompt(); + } + setCurrentIndentSize(0); + } + + return null; }); // After requesting input we got no call back to change prompt, change it manually if (waitedForInputBefore && !myConsoleCommunication.isWaitingForInput()) { diff --git a/python/src/com/jetbrains/python/console/PydevConsoleRunner.java b/python/src/com/jetbrains/python/console/PydevConsoleRunner.java index d081d33fa864..80c450934e49 100644 --- a/python/src/com/jetbrains/python/console/PydevConsoleRunner.java +++ b/python/src/com/jetbrains/python/console/PydevConsoleRunner.java @@ -385,29 +385,24 @@ public class PydevConsoleRunner extends AbstractConsoleRunnerWithHistory ProgressManager.getInstance().run(new Task.Backgroundable(getProject(), "Connecting to Console", false) { @Override - public void run() { - ProgressManager.getInstance().run(new Task.Backgroundable(getProject(), "Connecting to Console", false) { - @Override - public void run(@NotNull final ProgressIndicator indicator) { - indicator.setText("Connecting to console..."); - try { - initAndRun(myStatementsToExecute); + public void run(@NotNull final ProgressIndicator indicator) { + indicator.setText("Connecting to console..."); + try { + initAndRun(myStatementsToExecute); + } + catch (final Exception e) { + LOG.warn("Error running console", e); + UIUtil.invokeAndWaitIfNeeded(new Runnable() { + @Override + public void run() { + showErrorsInConsole(e); } - catch (final Exception e) { - LOG.warn("Error running console", e); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - showErrorsInConsole(e); - } - }); - } - } - }); + }); + } } - }); + })); } private void showErrorsInConsole(Exception e) { @@ -671,31 +666,27 @@ public class PydevConsoleRunner extends AbstractConsoleRunnerWithHistory { + // Propagate console communication to language console + final PythonConsoleView consoleView = getConsoleView(); - @Override - public void run() { - // Propagate console communication to language console - final PythonConsoleView consoleView = getConsoleView(); - - consoleView.setConsoleCommunication(myPydevConsoleCommunication); - consoleView.setSdk(mySdk); - consoleView.setExecutionHandler(myConsoleExecuteActionHandler); - myProcessHandler.addProcessListener(new ProcessAdapter() { - @Override - public void onTextAvailable(ProcessEvent event, Key outputType) { - consoleView.print(event.getText(), outputType); - } - }); - - enableConsoleExecuteAction(); - - for (String statement : statements2execute) { - consoleView.executeStatement(statement + "\n", ProcessOutputTypes.SYSTEM); + consoleView.setConsoleCommunication(myPydevConsoleCommunication); + consoleView.setSdk(mySdk); + consoleView.setExecutionHandler(myConsoleExecuteActionHandler); + myProcessHandler.addProcessListener(new ProcessAdapter() { + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + consoleView.print(event.getText(), outputType); } + }); - fireConsoleInitializedEvent(consoleView); + enableConsoleExecuteAction(); + + for (String statement : statements2execute) { + consoleView.executeStatement(statement + "\n", ProcessOutputTypes.SYSTEM); } + + fireConsoleInitializedEvent(consoleView); }); } else { @@ -1012,22 +1003,12 @@ public class PydevConsoleRunner extends AbstractConsoleRunnerWithHistory closeCommunication()); myProcessHandler.waitFor(); } - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - PydevConsoleRunner.this.run(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> PydevConsoleRunner.this.run()); } }.queue(); } diff --git a/python/src/com/jetbrains/python/console/PythonConsoleView.java b/python/src/com/jetbrains/python/console/PythonConsoleView.java index a8a18a59ec76..e3e17b295f02 100644 --- a/python/src/com/jetbrains/python/console/PythonConsoleView.java +++ b/python/src/com/jetbrains/python/console/PythonConsoleView.java @@ -102,37 +102,28 @@ public class PythonConsoleView extends LanguageConsoleImpl implements Observable @Override public void executeCode(final @NotNull String code, @Nullable final Editor editor) { - showConsole(new Runnable() { + showConsole(() -> ProgressManager.getInstance().run(new Task.Backgroundable(null, "Executing Code in Console...", false) { @Override - public void run() { - ProgressManager.getInstance().run(new Task.Backgroundable(null, "Executing Code in Console...", false) { - @Override - public void run(@NotNull final ProgressIndicator indicator) { - long time = System.currentTimeMillis(); - while (!myExecuteActionHandler.isEnabled() || !myExecuteActionHandler.canExecuteNow()) { - if (indicator.isCanceled()) { - break; - } - if (System.currentTimeMillis() - time > 1000) { - if (editor != null) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - HintManager.getInstance().showErrorHint(editor, myExecuteActionHandler.getCantExecuteMessage()); - } - }); - } - return; - } - TimeoutUtil.sleep(300); - } - if (!indicator.isCanceled()) { - doExecute(code); - } + public void run(@NotNull final ProgressIndicator indicator) { + long time = System.currentTimeMillis(); + while (!myExecuteActionHandler.isEnabled() || !myExecuteActionHandler.canExecuteNow()) { + if (indicator.isCanceled()) { + break; } - }); + if (System.currentTimeMillis() - time > 1000) { + if (editor != null) { + UIUtil.invokeLaterIfNeeded( + () -> HintManager.getInstance().showErrorHint(editor, myExecuteActionHandler.getCantExecuteMessage())); + } + return; + } + TimeoutUtil.sleep(300); + } + if (!indicator.isCanceled()) { + doExecute(code); + } } - }); + })); } private void showConsole(@NotNull Runnable runnable) { @@ -152,17 +143,14 @@ public class PythonConsoleView extends LanguageConsoleImpl implements Observable } public void executeInConsole(final String code) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - String text = getConsoleEditor().getDocument().getText(); + UIUtil.invokeLaterIfNeeded(() -> { + String text = getConsoleEditor().getDocument().getText(); - setInputText(code); - myExecuteActionHandler.runExecuteAction(PythonConsoleView.this); + setInputText(code); + myExecuteActionHandler.runExecuteAction(PythonConsoleView.this); - if (!StringUtil.isEmpty(text)) { - setInputText(text); - } + if (!StringUtil.isEmpty(text)) { + setInputText(text); } }); } diff --git a/python/src/com/jetbrains/python/console/PythonToolWindowConsoleRunner.java b/python/src/com/jetbrains/python/console/PythonToolWindowConsoleRunner.java index 6252a46d7134..bc209aadbf51 100644 --- a/python/src/com/jetbrains/python/console/PythonToolWindowConsoleRunner.java +++ b/python/src/com/jetbrains/python/console/PythonToolWindowConsoleRunner.java @@ -49,10 +49,7 @@ public class PythonToolWindowConsoleRunner extends PydevConsoleRunner { @Override public void open() { - getToolWindow().activate(new Runnable() { - @Override - public void run() { - } + getToolWindow().activate(() -> { }, true); } diff --git a/python/src/com/jetbrains/python/debugger/PyDebugProcess.java b/python/src/com/jetbrains/python/debugger/PyDebugProcess.java index 1ffd3798d11e..874f79e2b7e5 100644 --- a/python/src/com/jetbrains/python/debugger/PyDebugProcess.java +++ b/python/src/com/jetbrains/python/debugger/PyDebugProcess.java @@ -257,12 +257,8 @@ public class PyDebugProcess extends XDebugProcess implements IPyDebugProcess, Pr myProcessHandler.destroyProcess(); } if (!myClosing) { - invokeLater(new Runnable() { - @Override - public void run() { - Messages.showErrorDialog("Unable to establish connection with debugger:\n" + e.getMessage(), getConnectionTitle()); - } - }); + invokeLater( + () -> Messages.showErrorDialog("Unable to establish connection with debugger:\n" + e.getMessage(), getConnectionTitle())); } } } @@ -308,12 +304,7 @@ public class PyDebugProcess extends XDebugProcess implements IPyDebugProcess, Pr public void showConsole(PyThreadInfo thread) { myConsoleContextFrame = new PyExecutionStack(this, thread).getTopFrame(); if (myExecutionConsole instanceof PythonDebugLanguageConsoleView) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - ((PythonDebugLanguageConsoleView)myExecutionConsole).enableConsole(false); - } - }); + UIUtil.invokeLaterIfNeeded(() -> ((PythonDebugLanguageConsoleView)myExecutionConsole).enableConsole(false)); } } diff --git a/python/src/com/jetbrains/python/debugger/PyDebuggerEvaluator.java b/python/src/com/jetbrains/python/debugger/PyDebuggerEvaluator.java index 29cef063f1b3..303c50f63d08 100644 --- a/python/src/com/jetbrains/python/debugger/PyDebuggerEvaluator.java +++ b/python/src/com/jetbrains/python/debugger/PyDebuggerEvaluator.java @@ -44,30 +44,27 @@ public class PyDebuggerEvaluator extends XDebuggerEvaluator { } private void doEvaluate(final String expr, final XEvaluationCallback callback, final boolean doTrunc) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - String expression = expr.trim(); - if (expression.isEmpty()) { - callback.evaluated(NONE); - return; - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + String expression = expr.trim(); + if (expression.isEmpty()) { + callback.evaluated(NONE); + return; + } - final boolean isExpression = PyDebugSupportUtils.isExpression(myProject, expression); - try { - // todo: think on getting results from EXEC - final PyDebugValue value = myDebugProcess.evaluate(expression, !isExpression, doTrunc); - if (value.isErrorOnEval()) { - callback.errorOccurred("{" + value.getType() + "}" + value.getValue()); - } - else { - callback.evaluated(value); - } + final boolean isExpression = PyDebugSupportUtils.isExpression(myProject, expression); + try { + // todo: think on getting results from EXEC + final PyDebugValue value = myDebugProcess.evaluate(expression, !isExpression, doTrunc); + if (value.isErrorOnEval()) { + callback.errorOccurred("{" + value.getType() + "}" + value.getValue()); } - catch (PyDebuggerException e) { - callback.errorOccurred(e.getTracebackError()); + else { + callback.evaluated(value); } } + catch (PyDebuggerException e) { + callback.errorOccurred(e.getTracebackError()); + } }); } diff --git a/python/src/com/jetbrains/python/debugger/PyLineBreakpointType.java b/python/src/com/jetbrains/python/debugger/PyLineBreakpointType.java index c71494a0bf5d..d8fde36e1cbe 100644 --- a/python/src/com/jetbrains/python/debugger/PyLineBreakpointType.java +++ b/python/src/com/jetbrains/python/debugger/PyLineBreakpointType.java @@ -49,16 +49,13 @@ public class PyLineBreakpointType extends XLineBreakpointTypeBase { final Document document = FileDocumentManager.getInstance().getDocument(file); if (document != null) { if (file.getFileType() == PythonFileType.INSTANCE || isPythonScratch(project, file)) { - XDebuggerUtil.getInstance().iterateLine(project, document, line, new Processor() { - @Override - public boolean process(PsiElement psiElement) { - if (psiElement instanceof PsiWhiteSpace || psiElement instanceof PsiComment) return true; - if (psiElement.getNode() != null && notStoppableElementType(psiElement.getNode().getElementType())) return true; + XDebuggerUtil.getInstance().iterateLine(project, document, line, psiElement -> { + if (psiElement instanceof PsiWhiteSpace || psiElement instanceof PsiComment) return true; + if (psiElement.getNode() != null && notStoppableElementType(psiElement.getNode().getElementType())) return true; - // Python debugger seems to be able to stop on pretty much everything - stoppable.set(true); - return false; - } + // Python debugger seems to be able to stop on pretty much everything + stoppable.set(true); + return false; }); if (PyDebugSupportUtils.isContinuationLine(document, line - 1)) { diff --git a/python/src/com/jetbrains/python/debugger/PyRemoteDebugProcess.java b/python/src/com/jetbrains/python/debugger/PyRemoteDebugProcess.java index 50624de7e75a..23d4245fe81d 100644 --- a/python/src/com/jetbrains/python/debugger/PyRemoteDebugProcess.java +++ b/python/src/com/jetbrains/python/debugger/PyRemoteDebugProcess.java @@ -80,12 +80,7 @@ public class PyRemoteDebugProcess extends PyDebugProcess { if (!isWaitingForConnection()) { setWaitingForConnection(true); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - waitForConnection(getCurrentStateMessage(), getConnectionTitle()); - } - }); + UIUtil.invokeLaterIfNeeded(() -> waitForConnection(getCurrentStateMessage(), getConnectionTitle())); } } diff --git a/python/src/com/jetbrains/python/debugger/PyRunCythonExtensionsFilter.java b/python/src/com/jetbrains/python/debugger/PyRunCythonExtensionsFilter.java index 0deb2448a67e..91dc2e4ba398 100644 --- a/python/src/com/jetbrains/python/debugger/PyRunCythonExtensionsFilter.java +++ b/python/src/com/jetbrains/python/debugger/PyRunCythonExtensionsFilter.java @@ -140,12 +140,7 @@ public class PyRunCythonExtensionsFilter implements Filter { final String message = StringUtil.isEmptyOrSpaces(result.getStdout()) && StringUtil.isEmptyOrSpaces(result.getStderr()) ? "Permission denied" : "Non-zero exit code (" + exitCode + "): \n" + result.getStderr(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - showErrorDialog(message); - } - }); + UIUtil.invokeLaterIfNeeded(() -> showErrorDialog(message)); } } }); diff --git a/python/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java b/python/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java index 04ba6c9352fa..e3df75ca35ec 100644 --- a/python/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java +++ b/python/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java @@ -273,25 +273,20 @@ public class PySignatureCacheManagerImpl extends PySignatureCacheManager { @Override public void clearCache() { final Ref deleted = Ref.create(false); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - - @Override - public void run() { - ProjectFileIndex.SERVICE.getInstance(myProject).iterateContent(new ContentIterator() { - @Override - public boolean processFile(VirtualFile fileOrDir) { - if (readAttribute(fileOrDir) != null) { - writeAttribute(fileOrDir, ""); - deleted.set(true); - } - if (ProgressManager.getInstance().getProgressIndicator().isCanceled()) { - return false; - } - return true; + ProgressManager.getInstance().runProcessWithProgressSynchronously( + (Runnable)() -> ProjectFileIndex.SERVICE.getInstance(myProject).iterateContent(new ContentIterator() { + @Override + public boolean processFile(VirtualFile fileOrDir) { + if (readAttribute(fileOrDir) != null) { + writeAttribute(fileOrDir, ""); + deleted.set(true); } - }); - } - }, "Cleaning the Cache of Dynamically Collected Types", true, myProject); + if (ProgressManager.getInstance().getProgressIndicator().isCanceled()) { + return false; + } + return true; + } + }), "Cleaning the Cache of Dynamically Collected Types", true, myProject); String message; diff --git a/python/src/com/jetbrains/python/debugger/PySmartStepIntoHandler.java b/python/src/com/jetbrains/python/debugger/PySmartStepIntoHandler.java index 0ce6dcadf4a7..289f7709801b 100644 --- a/python/src/com/jetbrains/python/debugger/PySmartStepIntoHandler.java +++ b/python/src/com/jetbrains/python/debugger/PySmartStepIntoHandler.java @@ -57,12 +57,9 @@ public class PySmartStepIntoHandler extends XSmartStepIntoHandler visitedCalls = Sets.newHashSet(); final int line = position.getLine(); - XDebuggerUtil.getInstance().iterateLine(mySession.getProject(), document, line, new Processor() { - @Override - public boolean process(PsiElement psiElement) { - addVariants(document, line, psiElement, variants, visitedCalls); - return true; - } + XDebuggerUtil.getInstance().iterateLine(mySession.getProject(), document, line, psiElement -> { + addVariants(document, line, psiElement, variants, visitedCalls); + return true; }); return variants; diff --git a/python/src/com/jetbrains/python/debugger/PyStackFrame.java b/python/src/com/jetbrains/python/debugger/PyStackFrame.java index 97a6e5673952..a3a9e2010a11 100644 --- a/python/src/com/jetbrains/python/debugger/PyStackFrame.java +++ b/python/src/com/jetbrains/python/debugger/PyStackFrame.java @@ -116,21 +116,18 @@ public class PyStackFrame extends XStackFrame { @Override public void computeChildren(@NotNull final XCompositeNode node) { if (node.isObsolete()) return; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - XValueChildrenList values = myDebugProcess.loadFrame(); - if (!node.isObsolete()) { - addChildren(node, values); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + XValueChildrenList values = myDebugProcess.loadFrame(); + if (!node.isObsolete()) { + addChildren(node, values); } - catch (PyDebuggerException e) { - if (!node.isObsolete()) { - node.setErrorMessage("Unable to display frame variables"); - } - LOG.warn(e); + } + catch (PyDebuggerException e) { + if (!node.isObsolete()) { + node.setErrorMessage("Unable to display frame variables"); } + LOG.warn(e); } }); } diff --git a/python/src/com/jetbrains/python/debugger/array/AsyncArrayTableModel.java b/python/src/com/jetbrains/python/debugger/array/AsyncArrayTableModel.java index 5ada5f65f18b..e620dd20e680 100644 --- a/python/src/com/jetbrains/python/debugger/array/AsyncArrayTableModel.java +++ b/python/src/com/jetbrains/python/debugger/array/AsyncArrayTableModel.java @@ -54,15 +54,10 @@ public class AsyncArrayTableModel extends AbstractTableModel { new PyDebugValue(myProvider.getSliceText(), value.getType(), value.getTypeQualifier(), value.getValue(), value.isContainer(), value.isErrorOnEval(), value.getParent(), value.getFrameAccessor()); - ListenableFutureTask task = ListenableFutureTask.create(new Callable() { - @Override - public ArrayChunk call() throws Exception { - return value.getFrameAccessor() - .getArrayItems(slicedValue, key.first, key.second, Math.min(CHUNK_ROW_SIZE, getRowCount() - key.first), - Math.min(CHUNK_COL_SIZE, getColumnCount() - key.second), - myProvider.getFormat()); - } - }); + ListenableFutureTask task = ListenableFutureTask.create(() -> value.getFrameAccessor() + .getArrayItems(slicedValue, key.first, key.second, Math.min(CHUNK_ROW_SIZE, getRowCount() - key.first), + Math.min(CHUNK_COL_SIZE, getColumnCount() - key.second), + myProvider.getFormat())); myExecutorService.execute(task); @@ -107,17 +102,7 @@ public class AsyncArrayTableModel extends AbstractTableModel { } } else { - chunk.addListener(new Runnable() { - @Override - public void run() { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - fireTableCellUpdated(row, col); - } - }); - } - }, myExecutorService); + chunk.addListener(() -> UIUtil.invokeLaterIfNeeded(() -> fireTableCellUpdated(row, col)), myExecutorService); } return EMPTY_CELL_VALUE; } diff --git a/python/src/com/jetbrains/python/debugger/array/NumpyArrayTable.java b/python/src/com/jetbrains/python/debugger/array/NumpyArrayTable.java index 0ae8bed9ebb9..b59c221df6b2 100644 --- a/python/src/com/jetbrains/python/debugger/array/NumpyArrayTable.java +++ b/python/src/com/jetbrains/python/debugger/array/NumpyArrayTable.java @@ -132,14 +132,11 @@ public class NumpyArrayTable { myTableCellRenderer.setMin(Double.MAX_VALUE); myTableCellRenderer.setMax(Double.MIN_VALUE); myTableCellRenderer.setColored(false); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myComponent.getColoredCheckbox().setSelected(false); - myComponent.getColoredCheckbox().setEnabled(false); - if (myTable.getColumnCount() > 0) { - myTable.setDefaultRenderer(myTable.getColumnClass(0), myTableCellRenderer); - } + UIUtil.invokeLaterIfNeeded(() -> { + myComponent.getColoredCheckbox().setSelected(false); + myComponent.getColoredCheckbox().setEnabled(false); + if (myTable.getColumnCount() > 0) { + myTable.setDefaultRenderer(myTable.getColumnClass(0), myTableCellRenderer); } }); } @@ -159,24 +156,21 @@ public class NumpyArrayTable { public void init(final String slice, final boolean inPlace) { initComponent(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final PyDebugValue value = getDebugValue(); - PyDebugValue parent = value.getParent(); - final PyDebugValue slicedValue = - new PyDebugValue(slice, value.getType(), null, value.getValue(), value.isContainer(), value.isErrorOnEval(), - parent, value.getFrameAccessor()); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + final PyDebugValue value = getDebugValue(); + PyDebugValue parent = value.getParent(); + final PyDebugValue slicedValue = + new PyDebugValue(slice, value.getType(), null, value.getValue(), value.isContainer(), value.isErrorOnEval(), + parent, value.getFrameAccessor()); - final String format = getFormat().isEmpty() ? "%" : getFormat(); + final String format = getFormat().isEmpty() ? "%" : getFormat(); - try { - initUi(value.getFrameAccessor() - .getArrayItems(slicedValue, 0, 0, -1, -1, format), inPlace); - } - catch (PyDebuggerException e) { - showError(e.getMessage()); - } + try { + initUi(value.getFrameAccessor() + .getArrayItems(slicedValue, 0, 0, -1, -1, format), inPlace); + } + catch (PyDebuggerException e) { + showError(e.getMessage()); } }); } @@ -187,32 +181,29 @@ public class NumpyArrayTable { myPagingModel.addToCache(chunk); myDtypeKind = chunk.getType(); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myTable.setModel(myPagingModel); - myComponent.getSliceTextField().setText(chunk.getSlicePresentation()); - myComponent.getFormatTextField().setText(chunk.getFormat()); - myDialog.setTitle(getTitlePresentation(chunk.getSlicePresentation())); - myTableCellRenderer = new ArrayTableCellRenderer(Double.MIN_VALUE, Double.MIN_VALUE, chunk.getType()); - fillColorRange(chunk.getMin(), chunk.getMax()); - if (!isNumeric()) { - disableColor(); - } - else { - myComponent.getColoredCheckbox().setEnabled(true); - } + UIUtil.invokeLaterIfNeeded(() -> { + myTable.setModel(myPagingModel); + myComponent.getSliceTextField().setText(chunk.getSlicePresentation()); + myComponent.getFormatTextField().setText(chunk.getFormat()); + myDialog.setTitle(getTitlePresentation(chunk.getSlicePresentation())); + myTableCellRenderer = new ArrayTableCellRenderer(Double.MIN_VALUE, Double.MIN_VALUE, chunk.getType()); + fillColorRange(chunk.getMin(), chunk.getMax()); + if (!isNumeric()) { + disableColor(); + } + else { + myComponent.getColoredCheckbox().setEnabled(true); + } - if (!inPlace) { - myComponent.getScrollPane().getViewport().setViewPosition(new Point(0, 0)); - JBTableWithRowHeaders.RowHeaderTable rowTable = ((JBTableWithRowHeaders)myTable).getRowHeaderTable(); - rowTable.setRowShift(0); - } - ((AsyncArrayTableModel)myTable.getModel()).fireTableDataChanged(); - ((AsyncArrayTableModel)myTable.getModel()).fireTableCellUpdated(0, 0); - if (myTable.getColumnCount() > 0) { - myTable.setDefaultRenderer(myTable.getColumnClass(0), myTableCellRenderer); - } + if (!inPlace) { + myComponent.getScrollPane().getViewport().setViewPosition(new Point(0, 0)); + JBTableWithRowHeaders.RowHeaderTable rowTable = ((JBTableWithRowHeaders)myTable).getRowHeaderTable(); + rowTable.setRowShift(0); + } + ((AsyncArrayTableModel)myTable.getModel()).fireTableDataChanged(); + ((AsyncArrayTableModel)myTable.getModel()).fireTableCellUpdated(0, 0); + if (myTable.getColumnCount() > 0) { + myTable.setDefaultRenderer(myTable.getColumnClass(0), myTableCellRenderer); } }); } @@ -257,20 +248,17 @@ public class NumpyArrayTable { private void initTableModel(final boolean inPlace) { myPagingModel = new AsyncArrayTableModel(myPagingModel.getRowCount(), myPagingModel.getColumnCount(), this); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myTable.setModel(myPagingModel); - if (!inPlace) { - myComponent.getScrollPane().getViewport().setViewPosition(new Point(0, 0)); - JBTableWithRowHeaders.RowHeaderTable rowTable = ((JBTableWithRowHeaders)myTable).getRowHeaderTable(); - rowTable.setRowShift(0); - } - ((AsyncArrayTableModel)myTable.getModel()).fireTableDataChanged(); - ((AsyncArrayTableModel)myTable.getModel()).fireTableCellUpdated(0, 0); - if (myTable.getColumnCount() > 0) { - myTable.setDefaultRenderer(myTable.getColumnClass(0), myTableCellRenderer); - } + UIUtil.invokeLaterIfNeeded(() -> { + myTable.setModel(myPagingModel); + if (!inPlace) { + myComponent.getScrollPane().getViewport().setViewPosition(new Point(0, 0)); + JBTableWithRowHeaders.RowHeaderTable rowTable = ((JBTableWithRowHeaders)myTable).getRowHeaderTable(); + rowTable.setRowShift(0); + } + ((AsyncArrayTableModel)myTable.getModel()).fireTableDataChanged(); + ((AsyncArrayTableModel)myTable.getModel()).fireTableCellUpdated(0, 0); + if (myTable.getColumnCount() > 0) { + myTable.setDefaultRenderer(myTable.getColumnClass(0), myTableCellRenderer); } }); } @@ -300,12 +288,9 @@ public class NumpyArrayTable { } public void showInfoHint(final String message) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myComponent.getSliceTextField().getEditor() != null) { - HintManager.getInstance().showInformationHint(myComponent.getSliceTextField().getEditor(), message); - } + UIUtil.invokeLaterIfNeeded(() -> { + if (myComponent.getSliceTextField().getEditor() != null) { + HintManager.getInstance().showInformationHint(myComponent.getSliceTextField().getEditor(), message); } }); } diff --git a/python/src/com/jetbrains/python/debugger/attach/PyLocalAttachDebuggerProvider.java b/python/src/com/jetbrains/python/debugger/attach/PyLocalAttachDebuggerProvider.java index b6c139a8a507..22e80275c145 100644 --- a/python/src/com/jetbrains/python/debugger/attach/PyLocalAttachDebuggerProvider.java +++ b/python/src/com/jetbrains/python/debugger/attach/PyLocalAttachDebuggerProvider.java @@ -61,21 +61,13 @@ public class PyLocalAttachDebuggerProvider implements XLocalAttachDebuggerProvid Lists.newArrayList(new PyLocalAttachDebugger(processInfo.getExecutableCannonicalPath().get())); } else { - result = ContainerUtil.map(PythonSdkType.getAllLocalCPythons(), new Function() { - @Override - public XLocalAttachDebugger fun(Sdk sdk) { - return new PyLocalAttachDebugger(sdk); - } + result = ContainerUtil.map(PythonSdkType.getAllLocalCPythons(), sdk -> { + return new PyLocalAttachDebugger(sdk); }); } // most recent python version goes first - Collections.sort(result, new Comparator() { - @Override - public int compare(XLocalAttachDebugger a, XLocalAttachDebugger b) { - return -a.getDebuggerDisplayName().compareToIgnoreCase(b.getDebuggerDisplayName()); - } - }); + Collections.sort(result, (a, b) -> -a.getDebuggerDisplayName().compareToIgnoreCase(b.getDebuggerDisplayName())); contextHolder.putUserData(DEBUGGERS_KEY, Collections.unmodifiableList(result)); return result; diff --git a/python/src/com/jetbrains/python/documentation/PythonDocumentationProvider.java b/python/src/com/jetbrains/python/documentation/PythonDocumentationProvider.java index 4ee90b7aad7d..bab50d539039 100644 --- a/python/src/com/jetbrains/python/documentation/PythonDocumentationProvider.java +++ b/python/src/com/jetbrains/python/documentation/PythonDocumentationProvider.java @@ -145,12 +145,8 @@ public class PythonDocumentationProvider extends AbstractDocumentationProvider i final List parameters = PyUtil.getParameters(fun, context); final String paramStr = "(" + StringUtil.join(parameters, - new Function() { - @NotNull - @Override - public String fun(PyParameter parameter) { - return PyUtil.getReadableRepr(parameter, false); - } + parameter -> { + return PyUtil.getReadableRepr(parameter, false); }, ", ") + ")"; @@ -468,17 +464,14 @@ public class PythonDocumentationProvider extends AbstractDocumentationProvider i final Project project = element.getProject(); final QualifiedName qName = QualifiedNameFinder.findCanonicalImportPath(element, element); if (qName != null && qName.getComponentCount() > 0) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final int rc = Messages.showOkCancelDialog(project, - "No external documentation URL configured for module " + qName.getComponents().get(0) + - ".\nWould you like to configure it now?", - "Python External Documentation", - Messages.getQuestionIcon()); - if (rc == Messages.OK) { - ShowSettingsUtilImpl.showSettingsDialog(project, PythonDocumentationConfigurable.ID, ""); - } + ApplicationManager.getApplication().invokeLater(() -> { + final int rc = Messages.showOkCancelDialog(project, + "No external documentation URL configured for module " + qName.getComponents().get(0) + + ".\nWould you like to configure it now?", + "Python External Documentation", + Messages.getQuestionIcon()); + if (rc == Messages.OK) { + ShowSettingsUtilImpl.showSettingsDialog(project, PythonDocumentationConfigurable.ID, ""); } }, ModalityState.NON_MODAL); } diff --git a/python/src/com/jetbrains/python/documentation/docstrings/DocStringFormat.java b/python/src/com/jetbrains/python/documentation/docstrings/DocStringFormat.java index 35b4148ddba3..991ddbdaf660 100644 --- a/python/src/com/jetbrains/python/documentation/docstrings/DocStringFormat.java +++ b/python/src/com/jetbrains/python/documentation/docstrings/DocStringFormat.java @@ -42,11 +42,8 @@ public enum DocStringFormat { @NotNull private static List getAllNames() { - return Collections.unmodifiableList(ContainerUtil.map(values(), new Function() { - @Override - public String fun(DocStringFormat format) { - return format.getName(); - } + return Collections.unmodifiableList(ContainerUtil.map(values(), format -> { + return format.getName(); })); } @@ -54,12 +51,7 @@ public enum DocStringFormat { @NotNull private static List getAllNamesButPlain() { - return Collections.unmodifiableList(ContainerUtil.mapNotNull(values(), new Function() { - @Override - public String fun(DocStringFormat format) { - return format == PLAIN ? null : format.getName(); - } - })); + return Collections.unmodifiableList(ContainerUtil.mapNotNull(values(), format -> format == PLAIN ? null : format.getName())); } @Nullable diff --git a/python/src/com/jetbrains/python/documentation/docstrings/SectionBasedDocString.java b/python/src/com/jetbrains/python/documentation/docstrings/SectionBasedDocString.java index b2d0d31cb864..e3c563c715b6 100644 --- a/python/src/com/jetbrains/python/documentation/docstrings/SectionBasedDocString.java +++ b/python/src/com/jetbrains/python/documentation/docstrings/SectionBasedDocString.java @@ -307,11 +307,8 @@ public abstract class SectionBasedDocString extends DocStringLineParser implemen @NotNull @Override public List getParameters() { - return ContainerUtil.map(getParameterSubstrings(), new Function() { - @Override - public String fun(Substring substring) { - return substring.toString(); - } + return ContainerUtil.map(getParameterSubstrings(), substring -> { + return substring.toString(); }); } @@ -470,11 +467,8 @@ public abstract class SectionBasedDocString extends DocStringLineParser implemen @NotNull @Override public List getRaisedExceptions() { - return ContainerUtil.mapNotNull(getExceptionFields(), new Function() { - @Override - public String fun(SectionField field) { - return StringUtil.nullize(field.getType()); - } + return ContainerUtil.mapNotNull(getExceptionFields(), field -> { + return StringUtil.nullize(field.getType()); }); } @@ -520,12 +514,8 @@ public abstract class SectionBasedDocString extends DocStringLineParser implemen @NotNull public List
      getSectionsWithNormalizedTitle(@NotNull final String title) { - return ContainerUtil.mapNotNull(mySections, new Function() { - @Override - public Section fun(Section section) { - return section.getNormalizedTitle().equals(getNormalizedSectionTitle(title)) ? section : null; - } - }); + return ContainerUtil.mapNotNull(mySections, + section -> section.getNormalizedTitle().equals(getNormalizedSectionTitle(title)) ? section : null); } @Nullable @@ -631,11 +621,8 @@ public abstract class SectionBasedDocString extends DocStringLineParser implemen @NotNull public List getNames() { - return ContainerUtil.map(myNames, new Function() { - @Override - public String fun(Substring substring) { - return substring.toString(); - } + return ContainerUtil.map(myNames, substring -> { + return substring.toString(); }); } diff --git a/python/src/com/jetbrains/python/editor/PythonCopyPasteProcessor.java b/python/src/com/jetbrains/python/editor/PythonCopyPasteProcessor.java index 79fdeae30e29..d91ac782450d 100644 --- a/python/src/com/jetbrains/python/editor/PythonCopyPasteProcessor.java +++ b/python/src/com/jetbrains/python/editor/PythonCopyPasteProcessor.java @@ -95,11 +95,8 @@ public class PythonCopyPasteProcessor implements CopyPastePreProcessor { editor.getSelectionModel().setSelection(lineStartOffset, selectionModel.getSelectionEnd()); if (StringUtil.isEmptyOrSpaces(line)) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.deleteString(lineStartOffset, lineEndOffset); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.deleteString(lineStartOffset, lineEndOffset); }); } } diff --git a/python/src/com/jetbrains/python/facet/FacetLibraryConfigurator.java b/python/src/com/jetbrains/python/facet/FacetLibraryConfigurator.java index 0420b11005ea..cfcaf32bc124 100644 --- a/python/src/com/jetbrains/python/facet/FacetLibraryConfigurator.java +++ b/python/src/com/jetbrains/python/facet/FacetLibraryConfigurator.java @@ -119,18 +119,16 @@ public class FacetLibraryConfigurator { public static void detachPythonLibrary(final Module module, final String libraryName) { final ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - // remove the library - final ModifiableRootModel model = modelsProvider.getModuleModifiableModel(module); - OrderEntry entry = OrderEntryUtil.findLibraryOrderEntry(model, libraryName); - if (entry == null) { - modelsProvider.disposeModuleModifiableModel(model); - } - else { - model.removeOrderEntry(entry); - modelsProvider.commitModuleModifiableModel(model); - } + ApplicationManager.getApplication().runWriteAction(() -> { + // remove the library + final ModifiableRootModel model = modelsProvider.getModuleModifiableModel(module); + OrderEntry entry = OrderEntryUtil.findLibraryOrderEntry(model, libraryName); + if (entry == null) { + modelsProvider.disposeModuleModifiableModel(model); + } + else { + model.removeOrderEntry(entry); + modelsProvider.commitModuleModifiableModel(model); } }); } diff --git a/python/src/com/jetbrains/python/hierarchy/PyHierarchyUtils.java b/python/src/com/jetbrains/python/hierarchy/PyHierarchyUtils.java index 03e3436bccd2..9a8fc7c88d24 100644 --- a/python/src/com/jetbrains/python/hierarchy/PyHierarchyUtils.java +++ b/python/src/com/jetbrains/python/hierarchy/PyHierarchyUtils.java @@ -30,11 +30,7 @@ import java.util.Comparator; * Time: 8:30:36 PM */ public class PyHierarchyUtils { - private static final Comparator NODE_DESCRIPTOR_COMPARATOR = new Comparator() { - public int compare(final NodeDescriptor first, final NodeDescriptor second) { - return first.getIndex() - second.getIndex(); - } - }; + private static final Comparator NODE_DESCRIPTOR_COMPARATOR = (first, second) -> first.getIndex() - second.getIndex(); private PyHierarchyUtils() { } diff --git a/python/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java b/python/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java index d84acde7ae28..2d9fd8d0c4f2 100644 --- a/python/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java @@ -257,14 +257,11 @@ public class PyChainedComparisonsInspection extends PyInspection { @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiFile file = descriptor.getStartElement().getContainingFile(); - InspectionProjectProfileManager.getInstance(project).getInspectionProfile().modifyProfile(new Consumer() { - @Override - public void consume(ModifiableModel model) { - PyChainedComparisonsInspection tool = - (PyChainedComparisonsInspection)model.getUnwrappedTool(INSPECTION_SHORT_NAME, - file); - tool.ignoreConstantInTheMiddle = false; - } + InspectionProjectProfileManager.getInstance(project).getInspectionProfile().modifyProfile(model -> { + PyChainedComparisonsInspection tool = + (PyChainedComparisonsInspection)model.getUnwrappedTool(INSPECTION_SHORT_NAME, + file); + tool.ignoreConstantInTheMiddle = false; }); } } diff --git a/python/src/com/jetbrains/python/inspections/PyInterpreterInspection.java b/python/src/com/jetbrains/python/inspections/PyInterpreterInspection.java index e00912818449..42ecb02ab090 100644 --- a/python/src/com/jetbrains/python/inspections/PyInterpreterInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyInterpreterInspection.java @@ -94,12 +94,9 @@ public class PyInterpreterInspection extends PyInspection { @Override public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - // outside of read action - ShowSettingsUtil.getInstance().showSettingsDialog(project, "Project Interpreter"); - } + ApplicationManager.getApplication().invokeLater(() -> { + // outside of read action + ShowSettingsUtil.getInstance().showSettingsDialog(project, "Project Interpreter"); }); } } diff --git a/python/src/com/jetbrains/python/inspections/PyPackageRequirementsInspection.java b/python/src/com/jetbrains/python/inspections/PyPackageRequirementsInspection.java index 6a38c9d7b7d6..05db484640a7 100644 --- a/python/src/com/jetbrains/python/inspections/PyPackageRequirementsInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyPackageRequirementsInspection.java @@ -237,11 +237,8 @@ public class PyPackageRequirementsInspection extends PyInspection { @NotNull private static String requirementsToString(@NotNull List requirements) { - return StringUtil.join(requirements, new Function() { - @Override - public String fun(PyRequirement requirement) { - return String.format("'%s'", requirement.toString()); - } + return StringUtil.join(requirements, requirement -> { + return String.format("'%s'", requirement.toString()); }, ", "); } @@ -407,18 +404,10 @@ public class PyPackageRequirementsInspection extends PyInspection { final PyElement element = myNode.getElement(); if (element == null) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - AddImportHelper.addImportStatement(element.getContainingFile(), myPackageName, myAsName, - AddImportHelper.ImportPriority.THIRD_PARTY, element); - } - }); - } - }, "Add import", "Add import"); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + AddImportHelper.addImportStatement(element.getContainingFile(), myPackageName, myAsName, + AddImportHelper.ImportPriority.THIRD_PARTY, element); + }), "Add import", "Add import"); } } }); @@ -539,60 +528,55 @@ public class PyPackageRequirementsInspection extends PyInspection { public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { final VirtualFile requirementsTxt = PyPackageUtil.findRequirementsTxt(myModule); final PyListLiteralExpression setupPyRequires = PyPackageUtil.findSetupPyRequires(myModule); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (requirementsTxt != null) { - if (requirementsTxt.isWritable()) { - final Document document = FileDocumentManager.getInstance().getDocument(requirementsTxt); - if (document != null) { - document.insertString(0, myPackageName + "\n"); - } - } - } - else { - final PyElementGenerator generator = PyElementGenerator.getInstance(project); - final PyArgumentList argumentList = findSetupArgumentList(); - if (setupPyRequires != null) { - if (setupPyRequires.getContainingFile().isWritable()) { - final String text = String.format("'%s'", myPackageName); - final PyExpression generated = generator.createExpressionFromText(myLanguageLevel, text); - setupPyRequires.add(generated); - } - } - else if (argumentList != null) { - final PyKeywordArgument requiresArg = generateRequiresKwarg(generator); - if (requiresArg != null) { - argumentList.addArgument(requiresArg); - } - } + if (requirementsTxt != null) { + if (requirementsTxt.isWritable()) { + final Document document = FileDocumentManager.getInstance().getDocument(requirementsTxt); + if (document != null) { + document.insertString(0, myPackageName + "\n"); } } - - @Nullable - private PyKeywordArgument generateRequiresKwarg(PyElementGenerator generator) { - final String text = String.format("foo(requires=['%s'])", myPackageName); - final PyExpression generated = generator.createExpressionFromText(myLanguageLevel, text); - PyKeywordArgument installRequiresArg = null; - if (generated instanceof PyCallExpression) { - final PyCallExpression foo = (PyCallExpression)generated; - for (PyExpression arg : foo.getArguments()) { - if (arg instanceof PyKeywordArgument) { - final PyKeywordArgument kwarg = (PyKeywordArgument)arg; - if ("requires".equals(kwarg.getKeyword())) { - installRequiresArg = kwarg; - } - } - } + } + else { + final PyElementGenerator generator = PyElementGenerator.getInstance(project); + final PyArgumentList argumentList = findSetupArgumentList(); + if (setupPyRequires != null) { + if (setupPyRequires.getContainingFile().isWritable()) { + final String text = String.format("'%s'", myPackageName); + final PyExpression generated = generator.createExpressionFromText(myLanguageLevel, text); + setupPyRequires.add(generated); } - return installRequiresArg; } - }); + else if (argumentList != null) { + final PyKeywordArgument requiresArg = generateRequiresKwarg(generator); + if (requiresArg != null) { + argumentList.addArgument(requiresArg); + } + } + } } - }, getName(), null); + + @Nullable + private PyKeywordArgument generateRequiresKwarg(PyElementGenerator generator) { + final String text = String.format("foo(requires=['%s'])", myPackageName); + final PyExpression generated = generator.createExpressionFromText(myLanguageLevel, text); + PyKeywordArgument installRequiresArg = null; + if (generated instanceof PyCallExpression) { + final PyCallExpression foo = (PyCallExpression)generated; + for (PyExpression arg : foo.getArguments()) { + if (arg instanceof PyKeywordArgument) { + final PyKeywordArgument kwarg = (PyKeywordArgument)arg; + if ("requires".equals(kwarg.getKeyword())) { + installRequiresArg = kwarg; + } + } + } + } + return installRequiresArg; + } + }), getName(), null); } } } diff --git a/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java b/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java index 8f7460072259..101d2beed95c 100644 --- a/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java @@ -283,19 +283,13 @@ public class PyPep8NamingInspection extends PyInspection { @Override public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) { final JBList list = new JBList(getBaseClassNames()); - final Runnable updateBlackList = new Runnable() { - @Override - public void run() { - final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); - profile.modifyProfile(new Consumer() { - @Override - public void consume(ModifiableModel model) { - final PyPep8NamingInspection inspection = (PyPep8NamingInspection)model - .getUnwrappedTool(PyPep8NamingInspection.class.getSimpleName(), descriptor.getPsiElement()); - addIfNotNull(inspection.ignoredBaseClasses, (String)list.getSelectedValue()); - } - }); - } + final Runnable updateBlackList = () -> { + final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); + profile.modifyProfile(model -> { + final PyPep8NamingInspection inspection = (PyPep8NamingInspection)model + .getUnwrappedTool(PyPep8NamingInspection.class.getSimpleName(), descriptor.getPsiElement()); + addIfNotNull(inspection.ignoredBaseClasses, (String)list.getSelectedValue()); + }); }; DataManager.getInstance().getDataContextFromFocus().doWhenDone(new Consumer() { @Override @@ -303,12 +297,7 @@ public class PyPep8NamingInspection extends PyInspection { new PopupChooserBuilder(list) .setTitle("Ignore base class") .setItemChoosenCallback(updateBlackList) - .setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return (String)o; - } - }) + .setFilteringEnabled(o -> (String)o) .createPopup() .showInBestPositionFor(dataContext); } @@ -345,13 +334,10 @@ public class PyPep8NamingInspection extends PyInspection { @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiFile file = descriptor.getStartElement().getContainingFile(); - InspectionProjectProfileManager.getInstance(project).getInspectionProfile().modifyProfile(new Consumer() { - @Override - public void consume(ModifiableModel model) { - PyPep8NamingInspection tool = (PyPep8NamingInspection)model.getUnwrappedTool(INSPECTION_SHORT_NAME, file); - if (!tool.ignoredErrors.contains(myCode)) { - tool.ignoredErrors.add(myCode); - } + InspectionProjectProfileManager.getInstance(project).getInspectionProfile().modifyProfile(model -> { + PyPep8NamingInspection tool = (PyPep8NamingInspection)model.getUnwrappedTool(INSPECTION_SHORT_NAME, file); + if (!tool.ignoredErrors.contains(myCode)) { + tool.ignoredErrors.add(myCode); } }); } diff --git a/python/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java b/python/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java index a6e04166e41c..1ad191325580 100644 --- a/python/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java @@ -109,34 +109,31 @@ public class PyPropertyDefinitionInspection extends PyInspection { public void visitPyClass(final PyClass node) { super.visitPyClass(node); // check property() and @property - node.scanProperties(new Processor() { - @Override - public boolean process(Property property) { - PyTargetExpression target = property.getDefinitionSite(); - if (target != null) { - // target = property(); args may be all funny - PyCallExpression call = (PyCallExpression)target.findAssignedValue(); - assert call != null : "Property has a null call assigned to it"; - final PyArgumentList arglist = call.getArgumentList(); - assert arglist != null : "Property call has null arglist"; - // we assume fget, fset, fdel, doc names - final PyCallExpression.PyArgumentsMapping mapping = call.mapArguments(getResolveContext()); - for (Map.Entry entry : mapping.getMappedParameters().entrySet()) { - final String paramName = entry.getValue().getName(); - PyExpression argument = PyUtil.peelArgument(entry.getKey()); - checkPropertyCallArgument(paramName, argument, node.getContainingFile()); - } + node.scanProperties(property -> { + PyTargetExpression target = property.getDefinitionSite(); + if (target != null) { + // target = property(); args may be all funny + PyCallExpression call = (PyCallExpression)target.findAssignedValue(); + assert call != null : "Property has a null call assigned to it"; + final PyArgumentList arglist = call.getArgumentList(); + assert arglist != null : "Property call has null arglist"; + // we assume fget, fset, fdel, doc names + final PyCallExpression.PyArgumentsMapping mapping = call.mapArguments(getResolveContext()); + for (Map.Entry entry : mapping.getMappedParameters().entrySet()) { + final String paramName = entry.getValue().getName(); + PyExpression argument = PyUtil.peelArgument(entry.getKey()); + checkPropertyCallArgument(paramName, argument, node.getContainingFile()); } - else { - // @property; we only check getter, others are checked by visitPyFunction - // getter is always present with this form - final PyCallable callable = property.getGetter().valueOrNull(); - if (callable instanceof PyFunction) { - checkGetter(callable, getFunctionMarkingElement((PyFunction)callable)); - } - } - return false; // always want more } + else { + // @property; we only check getter, others are checked by visitPyFunction + // getter is always present with this form + final PyCallable callable = property.getGetter().valueOrNull(); + if (callable instanceof PyFunction) { + checkGetter(callable, getFunctionMarkingElement((PyFunction)callable)); + } + } + return false; // always want more }, false); } diff --git a/python/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java b/python/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java index 943d832c1381..3448a78097f7 100644 --- a/python/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java @@ -127,28 +127,25 @@ public class PyRedeclarationInspection extends PyInspection { } final Ref readElementRef = Ref.create(null); final Ref writeElementRef = Ref.create(null); - ControlFlowUtil.iteratePrev(startInstruction, instructions, new Function() { - @Override - public ControlFlowUtil.Operation fun(Instruction instruction) { - if (instruction instanceof ReadWriteInstruction && instruction.num() != startInstruction) { - final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; - if (name.equals(rwInstruction.getName())) { - final PsiElement originalElement = rwInstruction.getElement(); - if (originalElement != null) { - if (rwInstruction.getAccess().isReadAccess()) { - readElementRef.set(originalElement); - } - if (rwInstruction.getAccess().isWriteAccess()) { - if (originalElement != element) { - writeElementRef.set(originalElement); - } + ControlFlowUtil.iteratePrev(startInstruction, instructions, instruction -> { + if (instruction instanceof ReadWriteInstruction && instruction.num() != startInstruction) { + final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; + if (name.equals(rwInstruction.getName())) { + final PsiElement originalElement = rwInstruction.getElement(); + if (originalElement != null) { + if (rwInstruction.getAccess().isReadAccess()) { + readElementRef.set(originalElement); + } + if (rwInstruction.getAccess().isWriteAccess()) { + if (originalElement != element) { + writeElementRef.set(originalElement); } } - return ControlFlowUtil.Operation.CONTINUE; } + return ControlFlowUtil.Operation.CONTINUE; } - return ControlFlowUtil.Operation.NEXT; } + return ControlFlowUtil.Operation.NEXT; }); final PsiElement writeElement = writeElementRef.get(); if (writeElement != null && readElementRef.get() == null) { diff --git a/python/src/com/jetbrains/python/inspections/PyShadowingBuiltinsInspection.java b/python/src/com/jetbrains/python/inspections/PyShadowingBuiltinsInspection.java index d37edad38b74..fb04c5c96184 100644 --- a/python/src/com/jetbrains/python/inspections/PyShadowingBuiltinsInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyShadowingBuiltinsInspection.java @@ -140,15 +140,12 @@ public class PyShadowingBuiltinsInspection extends PyInspection { final PsiElement element = descriptor.getPsiElement(); if (element != null) { final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); - profile.modifyProfile(new Consumer() { - @Override - public void consume(ModifiableModel model) { - final String toolName = PyShadowingBuiltinsInspection.class.getSimpleName(); - final PyShadowingBuiltinsInspection inspection = (PyShadowingBuiltinsInspection)model.getUnwrappedTool(toolName, element); - if (inspection != null) { - if (!inspection.ignoredNames.contains(myName)) { - inspection.ignoredNames.add(myName); - } + profile.modifyProfile(model -> { + final String toolName = PyShadowingBuiltinsInspection.class.getSimpleName(); + final PyShadowingBuiltinsInspection inspection = (PyShadowingBuiltinsInspection)model.getUnwrappedTool(toolName, element); + if (inspection != null) { + if (!inspection.ignoredNames.contains(myName)) { + inspection.ignoredNames.add(myName); } } }); diff --git a/python/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java b/python/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java index a4858898a3f2..8f64185a8481 100644 --- a/python/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java @@ -97,13 +97,7 @@ public class PyTypeCheckerInspection extends PyInspection { if (!problemsSet.isEmpty()) { Map> minProblems = Collections.min( problemsSet, - new Comparator>>() { - @Override - public int compare(Map> o1, - Map> o2) { - return o1.size() - o2.size(); - } - } + (o1, o2) -> o1.size() - o2.size() ); for (Map.Entry> entry : minProblems.entrySet()) { registerProblem(entry.getKey(), entry.getValue().getFirst(), entry.getValue().getSecond()); @@ -174,11 +168,8 @@ public class PyTypeCheckerInspection extends PyInspection { else { msg = String.format("Type '%s' doesn't have expected attributes %s", actualName, - StringUtil.join(missingAttributes, new Function() { - @Override - public String fun(String s) { - return String.format("'%s'", s); - } + StringUtil.join(missingAttributes, s -> { + return String.format("'%s'", s); }, ", ")); } } diff --git a/python/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java b/python/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java index 3ff3ee2e63fd..c55a3b0e84e3 100644 --- a/python/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java @@ -169,31 +169,28 @@ public class PyUnboundLocalVariableInspection extends PyInspection { return true; } final Ref first = Ref.create(true); - ControlFlowUtil.iteratePrev(num, instructions, new Function() { - @Override - public ControlFlowUtil.Operation fun(Instruction instruction) { - if (instruction instanceof ReadWriteInstruction) { - final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; - final String name = rwInstruction.getName(); - final PsiElement element = rwInstruction.getElement(); - if (element != null && name != null && name.equals(nodeName) && instruction.num() != num) { - try { - if (scope.getDeclaredVariable(element, name) == null) { - final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); - if (access.isReadAccess()) { - first.set(false); - return ControlFlowUtil.Operation.BREAK; - } + ControlFlowUtil.iteratePrev(num, instructions, instruction -> { + if (instruction instanceof ReadWriteInstruction) { + final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; + final String name = rwInstruction.getName(); + final PsiElement element = rwInstruction.getElement(); + if (element != null && name != null && name.equals(nodeName) && instruction.num() != num) { + try { + if (scope.getDeclaredVariable(element, name) == null) { + final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); + if (access.isReadAccess()) { + first.set(false); + return ControlFlowUtil.Operation.BREAK; } } - catch (DFALimitExceededException e) { - first.set(false); - } - return ControlFlowUtil.Operation.CONTINUE; } + catch (DFALimitExceededException e) { + first.set(false); + } + return ControlFlowUtil.Operation.CONTINUE; } - return ControlFlowUtil.Operation.NEXT; } + return ControlFlowUtil.Operation.NEXT; }); return first.get(); } diff --git a/python/src/com/jetbrains/python/inspections/PyUnreachableCodeInspection.java b/python/src/com/jetbrains/python/inspections/PyUnreachableCodeInspection.java index f61f95ff7336..efa47a1c19d8 100644 --- a/python/src/com/jetbrains/python/inspections/PyUnreachableCodeInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyUnreachableCodeInspection.java @@ -64,14 +64,11 @@ public class PyUnreachableCodeInspection extends PyInspection { final Instruction[] instructions = flow.getInstructions(); final List unreachable = new ArrayList(); if (instructions.length > 0) { - ControlFlowUtil.iteratePrev(instructions.length - 1, instructions, new Function() { - @Override - public ControlFlowUtil.Operation fun(Instruction instruction) { - if (instruction.allPred().isEmpty() && !isFirstInstruction(instruction)) { - unreachable.add(instruction.getElement()); - } - return ControlFlowUtil.Operation.NEXT; + ControlFlowUtil.iteratePrev(instructions.length - 1, instructions, instruction -> { + if (instruction.allPred().isEmpty() && !isFirstInstruction(instruction)) { + unreachable.add(instruction.getElement()); } + return ControlFlowUtil.Operation.NEXT; }); } for (PsiElement e : unreachable) { @@ -89,15 +86,12 @@ public class PyUnreachableCodeInspection extends PyInspection { final int start = ControlFlowUtil.findInstructionNumberByElement(instructions, element); if (start >= 0) { final Ref resultRef = Ref.create(false); - ControlFlowUtil.iteratePrev(start, instructions, new Function() { - @Override - public ControlFlowUtil.Operation fun(Instruction instruction) { - if (instruction.allPred().isEmpty() && !isFirstInstruction(instruction)) { - resultRef.set(true); - return ControlFlowUtil.Operation.BREAK; - } - return ControlFlowUtil.Operation.NEXT; + ControlFlowUtil.iteratePrev(start, instructions, instruction -> { + if (instruction.allPred().isEmpty() && !isFirstInstruction(instruction)) { + resultRef.set(true); + return ControlFlowUtil.Operation.BREAK; } + return ControlFlowUtil.Operation.NEXT; }); return resultRef.get(); } diff --git a/python/src/com/jetbrains/python/inspections/PyUnusedLocalInspectionVisitor.java b/python/src/com/jetbrains/python/inspections/PyUnusedLocalInspectionVisitor.java index 03410e2fb8e4..032600677dd7 100644 --- a/python/src/com/jetbrains/python/inspections/PyUnusedLocalInspectionVisitor.java +++ b/python/src/com/jetbrains/python/inspections/PyUnusedLocalInspectionVisitor.java @@ -177,31 +177,29 @@ public class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { } } } - ControlFlowUtil.iteratePrev(startInstruction, instructions, new Function() { - public ControlFlowUtil.Operation fun(final Instruction inst) { - final PsiElement element = inst.getElement(); - // Mark function as used - if (element instanceof PyFunction) { - if (name.equals(((PyFunction)element).getName())){ - myUsedElements.add(element); - myUnusedElements.remove(element); - return ControlFlowUtil.Operation.CONTINUE; - } + ControlFlowUtil.iteratePrev(startInstruction, instructions, inst -> { + final PsiElement element1 = inst.getElement(); + // Mark function as used + if (element1 instanceof PyFunction) { + if (name.equals(((PyFunction)element1).getName())){ + myUsedElements.add(element1); + myUnusedElements.remove(element1); + return ControlFlowUtil.Operation.CONTINUE; } - // Mark write access as used - else if (inst instanceof ReadWriteInstruction) { - final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)inst; - if (rwInstruction.getAccess().isWriteAccess() && name.equals(rwInstruction.getName())) { - // For elements in scope - if (element != null && PsiTreeUtil.isAncestor(owner, element, false)) { - myUsedElements.add(element); - myUnusedElements.remove(element); - } - return ControlFlowUtil.Operation.CONTINUE; - } - } - return ControlFlowUtil.Operation.NEXT; } + // Mark write access as used + else if (inst instanceof ReadWriteInstruction) { + final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)inst; + if (rwInstruction.getAccess().isWriteAccess() && name.equals(rwInstruction.getName())) { + // For elements in scope + if (element1 != null && PsiTreeUtil.isAncestor(owner, element1, false)) { + myUsedElements.add(element1); + myUnusedElements.remove(element1); + } + return ControlFlowUtil.Operation.CONTINUE; + } + } + return ControlFlowUtil.Operation.NEXT; }); } } @@ -409,17 +407,11 @@ public class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { "for _ in tuples:\n pass" ); final PyExpression target = ((PyForStatement)pyFile.getStatements().get(0)).getForPart().getTarget(); - CommandProcessor.getInstance().executeCommand(psiElement.getProject(), new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - if (target != null) { - psiElement.replace(target); - } - } - }); + CommandProcessor.getInstance().executeCommand(psiElement.getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + if (target != null) { + psiElement.replace(target); } - }, getName(), null); + }), getName(), null); } @NotNull diff --git a/python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java b/python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java index 2024a5831e2d..28ce146fb5c5 100644 --- a/python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java +++ b/python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java @@ -63,19 +63,16 @@ public class AddIgnoredIdentifierQuickFix implements LocalQuickFix, LowPriorityA public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement context = descriptor.getPsiElement(); InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); - profile.modifyProfile(new Consumer() { - @Override - public void consume(ModifiableModel model) { - PyUnresolvedReferencesInspection inspection = - (PyUnresolvedReferencesInspection)model.getUnwrappedTool(PyUnresolvedReferencesInspection.class.getSimpleName(), context); - String name = myIdentifier.toString(); - if (myIgnoreAllAttributes) { - name += END_WILDCARD; - } - assert inspection != null; - if (!inspection.ignoredIdentifiers.contains(name)) { - inspection.ignoredIdentifiers.add(name); - } + profile.modifyProfile(model -> { + PyUnresolvedReferencesInspection inspection = + (PyUnresolvedReferencesInspection)model.getUnwrappedTool(PyUnresolvedReferencesInspection.class.getSimpleName(), context); + String name = myIdentifier.toString(); + if (myIgnoreAllAttributes) { + name += END_WILDCARD; + } + assert inspection != null; + if (!inspection.ignoredIdentifiers.contains(name)) { + inspection.ignoredIdentifiers.add(name); } }); } diff --git a/python/src/com/jetbrains/python/inspections/quickfix/CompatibilityPrintCallQuickFix.java b/python/src/com/jetbrains/python/inspections/quickfix/CompatibilityPrintCallQuickFix.java index d7a705198e1e..5d38258f2ad1 100644 --- a/python/src/com/jetbrains/python/inspections/quickfix/CompatibilityPrintCallQuickFix.java +++ b/python/src/com/jetbrains/python/inspections/quickfix/CompatibilityPrintCallQuickFix.java @@ -53,11 +53,8 @@ public class CompatibilityPrintCallQuickFix implements LocalQuickFix { final PyFile file = (PyFile)expression.getContainingFile(); final PyExpression[] target = PsiTreeUtil.getChildrenOfType(expression, PyExpression.class); if (target != null) { - stringBuilder.append(StringUtil.join(target, new Function() { - @Override - public String fun(PyExpression o) { - return o.getText(); - } + stringBuilder.append(StringUtil.join(target, o -> { + return o.getText(); }, ", ")); } stringBuilder.append(")"); diff --git a/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java b/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java index dff036a47f82..d56719302ff5 100644 --- a/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java +++ b/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java @@ -1010,11 +1010,7 @@ public class PyUnresolvedReferencesInspection extends PyInspection { private static void addPluginQuickFixes(PsiReference reference, final List actions) { for (PyUnresolvedReferenceQuickFixProvider provider : Extensions.getExtensions(PyUnresolvedReferenceQuickFixProvider.EP_NAME)) { - provider.registerQuickFixes(reference, new Consumer() { - public void consume(LocalQuickFix localQuickFix) { - actions.add(localQuickFix); - } - }); + provider.registerQuickFixes(reference, localQuickFix -> actions.add(localQuickFix)); } } diff --git a/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java b/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java index 5f17a74cfa9a..0de50fe83f5d 100644 --- a/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java +++ b/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java @@ -91,20 +91,14 @@ public class PyPackageManagerImpl extends PyPackageManager { public void refresh() { LOG.debug("Refreshing SDK roots and packages cache"); final Application application = ApplicationManager.getApplication(); - application.invokeLater(new Runnable() { - @Override - public void run() { - final Sdk sdk = getSdk(); - application.runWriteAction(new Runnable() { - @Override - public void run() { - final VirtualFile[] files = sdk.getRootProvider().getFiles(OrderRootType.CLASSES); - VfsUtil.markDirtyAndRefresh(true, true, true, files); - } - }); - PythonSdkType.getInstance().setupSdkPaths(sdk); - clearCaches(); - } + application.invokeLater(() -> { + final Sdk sdk = getSdk(); + application.runWriteAction(() -> { + final VirtualFile[] files = sdk.getRootProvider().getFiles(OrderRootType.CLASSES); + VfsUtil.markDirtyAndRefresh(true, true, true, files); + }); + PythonSdkType.getInstance().setupSdkPaths(sdk); + clearCaches(); }); } diff --git a/python/src/com/jetbrains/python/packaging/PyPackageManagerUI.java b/python/src/com/jetbrains/python/packaging/PyPackageManagerUI.java index 0b6c848f1039..8e87627a8900 100644 --- a/python/src/com/jetbrains/python/packaging/PyPackageManagerUI.java +++ b/python/src/com/jetbrains/python/packaging/PyPackageManagerUI.java @@ -85,35 +85,32 @@ public class PyPackageManagerUI { final Map> dependentPackages = collectDependents(packages, mySdk); final int[] warning = {0}; if (!dependentPackages.isEmpty()) { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - if (dependentPackages.size() == 1) { - String message = "You are attempting to uninstall "; - List dep = new ArrayList(); - int size = 1; - for (Map.Entry> entry : dependentPackages.entrySet()) { - final Set value = entry.getValue(); - size = value.size(); - dep.add(entry.getKey() + " package which is required for " + StringUtil.join(value, ", ")); - } - message += StringUtil.join(dep, "\n"); - message += size == 1 ? " package" : " packages"; - message += "\n\nDo you want to proceed?"; - warning[0] = Messages.showYesNoDialog(message, "Warning", - AllIcons.General.BalloonWarning); + ApplicationManager.getApplication().invokeAndWait(() -> { + if (dependentPackages.size() == 1) { + String message = "You are attempting to uninstall "; + List dep = new ArrayList(); + int size = 1; + for (Map.Entry> entry : dependentPackages.entrySet()) { + final Set value = entry.getValue(); + size = value.size(); + dep.add(entry.getKey() + " package which is required for " + StringUtil.join(value, ", ")); } - else { - String message = "You are attempting to uninstall packages which are required for another packages.\n\n"; - List dep = new ArrayList(); - for (Map.Entry> entry : dependentPackages.entrySet()) { - dep.add(entry.getKey() + " -> " + StringUtil.join(entry.getValue(), ", ")); - } - message += StringUtil.join(dep, "\n"); - message += "\n\nDo you want to proceed?"; - warning[0] = Messages.showYesNoDialog(message, "Warning", - AllIcons.General.BalloonWarning); + message += StringUtil.join(dep, "\n"); + message += size == 1 ? " package" : " packages"; + message += "\n\nDo you want to proceed?"; + warning[0] = Messages.showYesNoDialog(message, "Warning", + AllIcons.General.BalloonWarning); + } + else { + String message = "You are attempting to uninstall packages which are required for another packages.\n\n"; + List dep = new ArrayList(); + for (Map.Entry> entry : dependentPackages.entrySet()) { + dep.add(entry.getKey() + " -> " + StringUtil.join(entry.getValue(), ", ")); } + message += StringUtil.join(dep, "\n"); + message += "\n\nDo you want to proceed?"; + warning[0] = Messages.showYesNoDialog(message, "Warning", + AllIcons.General.BalloonWarning); } }, ModalityState.current()); } @@ -179,12 +176,7 @@ public class PyPackageManagerUI { } indicator.setText(getTitle() + "..."); if (myListener != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myListener.started(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> myListener.started()); } } @@ -211,16 +203,13 @@ public class PyPackageManagerUI { NotificationType.ERROR, listener)); } } - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myListener != null) { - myListener.finished(exceptions); - } - final Notification notification = notificationRef.get(); - if (notification != null) { - notification.notify(myProject); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myListener != null) { + myListener.finished(exceptions); + } + final Notification notification = notificationRef.get(); + if (notification != null) { + notification.notify(myProject); } }); } @@ -369,12 +358,7 @@ public class PyPackageManagerUI { @NotNull @Override protected String getSuccessDescription() { - final String packagesString = StringUtil.join(myPackages, new Function() { - @Override - public String fun(PyPackage pkg) { - return "'" + pkg.getName() + "'"; - } - }, ", "); + final String packagesString = StringUtil.join(myPackages, pkg -> "'" + pkg.getName() + "'", ", "); return "Uninstalled packages: " + packagesString; } diff --git a/python/src/com/jetbrains/python/packaging/PyPackageUtil.java b/python/src/com/jetbrains/python/packaging/PyPackageUtil.java index 178ede13f93c..5d6f6401a3bc 100644 --- a/python/src/com/jetbrains/python/packaging/PyPackageUtil.java +++ b/python/src/com/jetbrains/python/packaging/PyPackageUtil.java @@ -149,11 +149,8 @@ public class PyPackageUtil { @NotNull public static String requirementsToString(@NotNull List requirements) { - return StringUtil.join(requirements, new Function() { - @Override - public String fun(PyRequirement requirement) { - return String.format("'%s'", requirement.toString()); - } + return StringUtil.join(requirements, requirement -> { + return String.format("'%s'", requirement.toString()); }, ", "); } diff --git a/python/src/com/jetbrains/python/packaging/PyPackagesUpdater.java b/python/src/com/jetbrains/python/packaging/PyPackagesUpdater.java index 1c721ba6aa6a..6331f905cf0a 100644 --- a/python/src/com/jetbrains/python/packaging/PyPackagesUpdater.java +++ b/python/src/com/jetbrains/python/packaging/PyPackagesUpdater.java @@ -44,26 +44,18 @@ public class PyPackagesUpdater implements StartupActivity { } final PyPackageService service = PyPackageService.getInstance(); if (checkNeeded(project, service)) { - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - PyPIPackageUtil.INSTANCE.updatePyPICache(service); - service.LAST_TIME_CHECKED = System.currentTimeMillis(); - } - catch (IOException e) { - LOG.warn(e.getMessage()); - } + application.executeOnPooledThread(() -> { + try { + PyPIPackageUtil.INSTANCE.updatePyPICache(service); + service.LAST_TIME_CHECKED = System.currentTimeMillis(); + } + catch (IOException e) { + LOG.warn(e.getMessage()); } }); } if (checkCondaUpdateNeeded(project)) { - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - PyCondaPackageService.getInstance().updatePackagesCache(); - } - }); + application.executeOnPooledThread(() -> PyCondaPackageService.getInstance().updatePackagesCache()); } } diff --git a/python/src/com/jetbrains/python/packaging/setupPy/SetupTaskChooserAction.java b/python/src/com/jetbrains/python/packaging/setupPy/SetupTaskChooserAction.java index f4cb4f2fbdca..a8a88a78ff30 100644 --- a/python/src/com/jetbrains/python/packaging/setupPy/SetupTaskChooserAction.java +++ b/python/src/com/jetbrains/python/packaging/setupPy/SetupTaskChooserAction.java @@ -64,10 +64,8 @@ public class SetupTaskChooserAction extends AnAction { public void elementChosen(Object element) { if (element != null) { final SetupTask task = (SetupTask) element; - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - runSetupTask(task.getName(), module); - } + ApplicationManager.getApplication().invokeLater(() -> { + runSetupTask(task.getName(), module); }, ModalityState.NON_MODAL); } } @@ -99,12 +97,7 @@ public class SetupTaskChooserAction extends AnAction { task.setRunnerScript(virtualFile.getPath()); task.setWorkingDirectory(virtualFile.getParent().getPath()); task.setParameters(parameters); - task.setAfterCompletion(new Runnable() { - @Override - public void run() { - LocalFileSystem.getInstance().refresh(true); - } - }); + task.setAfterCompletion(() -> LocalFileSystem.getInstance().refresh(true)); task.run(null, null); } catch (ExecutionException ee) { diff --git a/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java b/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java index d90abbb7683d..f0a5a850751a 100644 --- a/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java +++ b/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java @@ -90,60 +90,51 @@ public class PyInstalledPackagesPanel extends InstalledPackagesPanel { return; } final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - @Override - public void run() { - PyExecutionException exception = null; - try { - myHasManagement = PyPackageManager.getInstance(selectedSdk).hasManagement(false); - if (!myHasManagement) { - throw new PyExecutionException("Python packaging tools not found", "pip", Collections.emptyList(), "", "", 0, - ImmutableList.of(new PyInstallPackageManagementFix())); - } + application.executeOnPooledThread(() -> { + PyExecutionException exception = null; + try { + myHasManagement = PyPackageManager.getInstance(selectedSdk).hasManagement(false); + if (!myHasManagement) { + throw new PyExecutionException("Python packaging tools not found", "pip", Collections.emptyList(), "", "", 0, + ImmutableList.of(new PyInstallPackageManagementFix())); } - catch (PyExecutionException e) { - exception = e; - } - catch (ExecutionException e) { - return; - } - final PyExecutionException problem = exception; - application.invokeLater(new Runnable() { - @Override - public void run() { - if (selectedSdk == getSelectedSdk()) { - myNotificationArea.hide(); - if (problem != null) { - final boolean invalid = PythonSdkType.isInvalid(selectedSdk); - if (!invalid) { - final StringBuilder builder = new StringBuilder(problem.getMessage()); - builder.append(". "); - for (final PyExecutionFix fix : problem.getFixes()) { - final String key = "id" + fix.hashCode(); - final String link = "" + fix.getName() + ""; - builder.append(link); - builder.append(" "); - myNotificationArea.addLinkHandler(key, new Runnable() { - @Override - public void run() { - final Sdk sdk = getSelectedSdk(); - if (sdk != null) { - fix.run(sdk); - myNotificationArea.removeLinkHandler(key); - updatePackages(PyPackageManagers.getInstance().getManagementService(myProject, sdk)); - updateNotifications(sdk); - } - } - }); - } - myNotificationArea.showWarning(builder.toString()); - } - myInstallButton.setEnabled(!invalid && installEnabled()); - } - } - } - }, ModalityState.any()); } + catch (PyExecutionException e) { + exception = e; + } + catch (ExecutionException e) { + return; + } + final PyExecutionException problem = exception; + application.invokeLater(() -> { + if (selectedSdk == getSelectedSdk()) { + myNotificationArea.hide(); + if (problem != null) { + final boolean invalid = PythonSdkType.isInvalid(selectedSdk); + if (!invalid) { + final StringBuilder builder = new StringBuilder(problem.getMessage()); + builder.append(". "); + for (final PyExecutionFix fix : problem.getFixes()) { + final String key = "id" + fix.hashCode(); + final String link = "" + fix.getName() + ""; + builder.append(link); + builder.append(" "); + myNotificationArea.addLinkHandler(key, () -> { + final Sdk sdk = getSelectedSdk(); + if (sdk != null) { + fix.run(sdk); + myNotificationArea.removeLinkHandler(key); + updatePackages(PyPackageManagers.getInstance().getManagementService(myProject, sdk)); + updateNotifications(sdk); + } + }); + } + myNotificationArea.showWarning(builder.toString()); + } + myInstallButton.setEnabled(!invalid && installEnabled()); + } + } + }, ModalityState.any()); }); } diff --git a/python/src/com/jetbrains/python/packaging/ui/PyPackageManagementService.java b/python/src/com/jetbrains/python/packaging/ui/PyPackageManagementService.java index 3c87c8a1a938..4096539aef49 100644 --- a/python/src/com/jetbrains/python/packaging/ui/PyPackageManagementService.java +++ b/python/src/com/jetbrains/python/packaging/ui/PyPackageManagementService.java @@ -143,12 +143,7 @@ public class PyPackageManagementService extends PackageManagementServiceEx { try { packages = PyPackageManager.getInstance(mySdk).getPackages(false); if (packages != null) { - Collections.sort(packages, new Comparator() { - @Override - public int compare(@NotNull PyPackage pkg1, @NotNull PyPackage pkg2) { - return pkg1.getName().compareTo(pkg2.getName()); - } - }); + Collections.sort(packages, (pkg1, pkg2) -> pkg1.getName().compareTo(pkg2.getName())); } } catch (ExecutionException e) { diff --git a/python/src/com/jetbrains/python/psi/PyIndentUtil.java b/python/src/com/jetbrains/python/psi/PyIndentUtil.java index 9cca87af44c1..5aa766b99c0a 100644 --- a/python/src/com/jetbrains/python/psi/PyIndentUtil.java +++ b/python/src/com/jetbrains/python/psi/PyIndentUtil.java @@ -190,15 +190,12 @@ public class PyIndentUtil { return Collections.emptyList(); } - final List result = ContainerUtil.map(Iterables.skip(lines, ignoreFirstLine ? 1 : 0), new Function() { - @Override - public String fun(String line) { - if (StringUtil.isEmptyOrSpaces(line)) { - return ""; - } - else { - return newIndent + line.substring(oldIndent.length()); - } + final List result = ContainerUtil.map(Iterables.skip(lines, ignoreFirstLine ? 1 : 0), line -> { + if (StringUtil.isEmptyOrSpaces(line)) { + return ""; + } + else { + return newIndent + line.substring(oldIndent.length()); } }); if (ignoreFirstLine) { diff --git a/python/src/com/jetbrains/python/psi/PyUtil.java b/python/src/com/jetbrains/python/psi/PyUtil.java index 490e1c9ac9ba..ad1eee4c86ca 100644 --- a/python/src/com/jetbrains/python/psi/PyUtil.java +++ b/python/src/com/jetbrains/python/psi/PyUtil.java @@ -491,13 +491,10 @@ public class PyUtil { File pycache = new File(file.getParentFile(), PyNames.PYCACHE); if (pycache.isDirectory()) { final String shortName = FileUtil.getNameWithoutExtension(file); - Collections.addAll(filesToDelete, pycache.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - if (!FileUtilRt.extensionEquals(pathname.getName(), "pyc")) return false; - String nameWithMagic = FileUtil.getNameWithoutExtension(pathname); - return FileUtil.getNameWithoutExtension(nameWithMagic).equals(shortName); - } + Collections.addAll(filesToDelete, pycache.listFiles(pathname -> { + if (!FileUtilRt.extensionEquals(pathname.getName(), "pyc")) return false; + String nameWithMagic = FileUtil.getNameWithoutExtension(pathname); + return FileUtil.getNameWithoutExtension(nameWithMagic).equals(shortName); })); } FileUtil.asyncDelete(filesToDelete); @@ -831,17 +828,14 @@ public class PyUtil { * Force re-highlighting in all open editors that belong to specified project. */ public static void rehighlightOpenEditors(final @NotNull Project project) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { + ApplicationManager.getApplication().runWriteAction(() -> { - for (Editor editor : EditorFactory.getInstance().getAllEditors()) { - if (editor instanceof EditorEx && editor.getProject() == project) { - final VirtualFile vFile = ((EditorEx)editor).getVirtualFile(); - if (vFile != null) { - final EditorHighlighter highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, vFile); - ((EditorEx)editor).setHighlighter(highlighter); - } + for (Editor editor : EditorFactory.getInstance().getAllEditors()) { + if (editor instanceof EditorEx && editor.getProject() == project) { + final VirtualFile vFile = ((EditorEx)editor).getVirtualFile(); + if (vFile != null) { + final EditorHighlighter highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, vFile); + ((EditorEx)editor).setHighlighter(highlighter); } } } diff --git a/python/src/com/jetbrains/python/psi/impl/PyBuiltinCache.java b/python/src/com/jetbrains/python/psi/impl/PyBuiltinCache.java index 618da46e352e..4b83f9000c8c 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyBuiltinCache.java +++ b/python/src/com/jetbrains/python/psi/impl/PyBuiltinCache.java @@ -143,13 +143,10 @@ public class PyBuiltinCache { final VirtualFile builtins_vfile = LocalFileSystem.getInstance().findFileByIoFile(builtins); if (builtins_vfile != null) { final Ref result = Ref.create(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiFile file = PsiManager.getInstance(project).findFile(builtins_vfile); - if (file instanceof PyFile) { - result.set((PyFile)file); - } + ApplicationManager.getApplication().runReadAction(() -> { + PsiFile file = PsiManager.getInstance(project).findFile(builtins_vfile); + if (file instanceof PyFile) { + result.set((PyFile)file); } }); return result.get(); diff --git a/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java b/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java index b2b011a6182a..d805b26ddcca 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java @@ -367,11 +367,9 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla final PyExpression[] superClassExpressions = getSuperClassExpressions(); if (superClassExpressions.length > 0) { result.append("("); - result.append(join(Arrays.asList(superClassExpressions), new Function() { - public String fun(PyExpression expr) { - String name = expr.getText(); - return notNullize(name, PyNames.UNNAMED_ELEMENT); - } + result.append(join(Arrays.asList(superClassExpressions), expr -> { + String name = expr.getText(); + return notNullize(name, PyNames.UNNAMED_ELEMENT); }, ", ")); result.append(")"); } @@ -737,12 +735,9 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla private Map initializePropertyCache() { final Map result = new HashMap(); - processProperties(null, new Processor() { - @Override - public boolean process(Property property) { - result.put(property.getName(), property); - return false; - } + processProperties(null, property -> { + result.put(property.getName(), property); + return false; }, false); return result; } diff --git a/python/src/com/jetbrains/python/psi/impl/PyFileImpl.java b/python/src/com/jetbrains/python/psi/impl/PyFileImpl.java index 424c5e43de59..61aac21a1e98 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyFileImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/PyFileImpl.java @@ -82,37 +82,34 @@ public class PyFileImpl extends PsiFileBase implements PyFile, PyExpression { private ExportedNameCache(long modificationStamp) { myModificationStamp = modificationStamp; - processDeclarations(PyPsiUtils.collectAllStubChildren(PyFileImpl.this, getStub()), new Processor() { - @Override - public boolean process(PsiElement element) { - if (element instanceof PsiNamedElement && !(element instanceof PyKeywordArgument)) { - final PsiNamedElement namedElement = (PsiNamedElement)element; - final String name = namedElement.getName(); - if (!myNamedElements.containsKey(name)) { - myNamedElements.put(name, Lists.newArrayList()); - } - final List elements = myNamedElements.get(name); - elements.add(namedElement); + processDeclarations(PyPsiUtils.collectAllStubChildren(PyFileImpl.this, getStub()), element -> { + if (element instanceof PsiNamedElement && !(element instanceof PyKeywordArgument)) { + final PsiNamedElement namedElement = (PsiNamedElement)element; + final String name = namedElement.getName(); + if (!myNamedElements.containsKey(name)) { + myNamedElements.put(name, Lists.newArrayList()); } - if (element instanceof PyImportedNameDefiner) { - myImportedNameDefiners.add((PyImportedNameDefiner)element); - } - if (element instanceof PyFromImportStatement) { - final PyFromImportStatement fromImportStatement = (PyFromImportStatement)element; - final PyStarImportElement starImportElement = fromImportStatement.getStarImportElement(); - if (starImportElement != null) { - myImportedNameDefiners.add(starImportElement); - } - else { - Collections.addAll(myImportedNameDefiners, fromImportStatement.getImportElements()); - } - } - else if (element instanceof PyImportStatement) { - final PyImportStatement importStatement = (PyImportStatement)element; - Collections.addAll(myImportedNameDefiners, importStatement.getImportElements()); - } - return true; + final List elements = myNamedElements.get(name); + elements.add(namedElement); } + if (element instanceof PyImportedNameDefiner) { + myImportedNameDefiners.add((PyImportedNameDefiner)element); + } + if (element instanceof PyFromImportStatement) { + final PyFromImportStatement fromImportStatement = (PyFromImportStatement)element; + final PyStarImportElement starImportElement = fromImportStatement.getStarImportElement(); + if (starImportElement != null) { + myImportedNameDefiners.add(starImportElement); + } + else { + Collections.addAll(myImportedNameDefiners, fromImportStatement.getImportElements()); + } + } + else if (element instanceof PyImportStatement) { + final PyImportStatement importStatement = (PyImportStatement)element; + Collections.addAll(myImportedNameDefiners, importStatement.getImportElements()); + } + return true; }); for (List elements : myNamedElements.values()) { Collections.reverse(elements); diff --git a/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java b/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java index c7aea1740694..0d719b75b1b5 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java @@ -96,11 +96,8 @@ public class PyFromImportStatementImpl extends PyBaseElementImpl() { - @NotNull - public PyImportElement[] create(int count) { - return new PyImportElement[count]; - } + return stub.getChildrenByType(PyElementTypes.IMPORT_ELEMENT, count -> { + return new PyImportElement[count]; }); } List result = new ArrayList(); diff --git a/python/src/com/jetbrains/python/psi/impl/PyImportStatementImpl.java b/python/src/com/jetbrains/python/psi/impl/PyImportStatementImpl.java index 97a5f5d6624e..e8289a86c90a 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyImportStatementImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/PyImportStatementImpl.java @@ -58,11 +58,8 @@ public class PyImportStatementImpl extends PyBaseElementImpl() { - @NotNull - public PyImportElement[] create(int count) { - return new PyImportElement[count]; - } + return stub.getChildrenByType(PyElementTypes.IMPORT_ELEMENT, count -> { + return new PyImportElement[count]; }); } return childrenToPsi(TokenSet.create(PyElementTypes.IMPORT_ELEMENT), new PyImportElement[0]); diff --git a/python/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java b/python/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java index 92641ec6974d..46b96e6ea9ca 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java @@ -249,28 +249,25 @@ public class PyNamedParameterImpl extends PyBaseElementImpl types = new ArrayList(); - processLocalCalls(func, new Processor() { - @Override - public boolean process(@NotNull PyCallExpression call) { - final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context); - final PyArgumentList argumentList = call.getArgumentList(); - if (argumentList != null) { - final PyCallExpression.PyArgumentsMapping mapping = call.mapArguments(resolveContext); - for (Map.Entry entry : mapping.getMappedParameters().entrySet()) { - if (entry.getValue() == PyNamedParameterImpl.this) { - final PyExpression argument = entry.getKey(); - if (argument != null) { - final PyType type = context.getType(argument); - if (type != null) { - types.add(type); - return true; - } + processLocalCalls(func, call -> { + final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context); + final PyArgumentList argumentList = call.getArgumentList(); + if (argumentList != null) { + final PyCallExpression.PyArgumentsMapping mapping = call.mapArguments(resolveContext); + for (Map.Entry entry : mapping.getMappedParameters().entrySet()) { + if (entry.getValue() == PyNamedParameterImpl.this) { + final PyExpression argument = entry.getKey(); + if (argument != null) { + final PyType type = context.getType(argument); + if (type != null) { + types.add(type); + return true; } } } } - return true; } + return true; }); if (!types.isEmpty()) { return PyUnionType.createWeakType(PyUnionType.union(types)); diff --git a/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java b/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java index 3c1f2678436d..4e9089924097 100644 --- a/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java +++ b/python/src/com/jetbrains/python/psi/impl/PythonLanguageLevelPusher.java @@ -224,14 +224,11 @@ public class PythonLanguageLevelPusher implements FilePropertyPusheremptyList(), true); + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) { + return; } + FileContentUtil.reparseFiles(project, Collections.emptyList(), true); }); } } @@ -253,29 +250,21 @@ public class PythonLanguageLevelPusher implements FilePropertyPusher application.runReadAction(() -> { + if (project.isDisposed()) { + return; } - }); + for (VirtualFile file : files) { + if (file.isValid()) { + VirtualFile parent = file.getParent(); + boolean suppressSizeLimit = false; + if (parent != null && parent.getName().equals(PythonSdkType.SKELETON_DIR_NAME)) { + suppressSizeLimit = true; + } + markRecursively(project, file, languageLevel, suppressSizeLimit); + } + } + })); } private void markRecursively(final Project project, diff --git a/python/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java b/python/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java index a5a08600f27f..16a18e1fc860 100644 --- a/python/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java +++ b/python/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java @@ -70,11 +70,8 @@ public class CompletionVariantsProcessor extends VariantsProcessor { item = item.withInsertHandler(PyFunctionInsertHandler.INSTANCE); final TypeEvalContext context = TypeEvalContext.codeCompletion(project, myContext != null ? myContext.getContainingFile() : null); final List parameters = PyUtil.getParameters((PyFunction)element, context); - final String params = StringUtil.join(parameters, new Function() { - @Override - public String fun(PyParameter pyParameter) { - return pyParameter.getName(); - } + final String params = StringUtil.join(parameters, pyParameter -> { + return pyParameter.getName(); }, ", "); item = item.withTailText("(" + params + ")"); } diff --git a/python/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java b/python/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java index 87c2204adbe4..b78cb08e56e3 100644 --- a/python/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java +++ b/python/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java @@ -54,14 +54,11 @@ public class RootVisitorHost { if (skipSdk) { enumerator = enumerator.withoutSdk(); } - enumerator.forEach(new Processor() { - @Override - public boolean process(OrderEntry orderEntry) { - if (orderEntry instanceof ModuleSourceOrderEntry) { - return visitModuleContentEntries(((ModuleSourceOrderEntry)orderEntry).getRootModel(), visitor); - } - return visitOrderEntryRoots(visitor, orderEntry); + enumerator.forEach(orderEntry -> { + if (orderEntry instanceof ModuleSourceOrderEntry) { + return visitModuleContentEntries(((ModuleSourceOrderEntry)orderEntry).getRootModel(), visitor); } + return visitOrderEntryRoots(visitor, orderEntry); }); } diff --git a/python/src/com/jetbrains/python/psi/search/PyDefinitionsSearch.java b/python/src/com/jetbrains/python/psi/search/PyDefinitionsSearch.java index 78999419ff80..88d2dea84db5 100644 --- a/python/src/com/jetbrains/python/psi/search/PyDefinitionsSearch.java +++ b/python/src/com/jetbrains/python/psi/search/PyDefinitionsSearch.java @@ -34,10 +34,8 @@ public class PyDefinitionsSearch implements QueryExecutor consumer) { if (queryParameters instanceof PyClass) { final Query query = PyClassInheritorsSearch.search((PyClass)queryParameters, true); - return query.forEach(new Processor() { - public boolean process(final PyClass pyClass) { - return consumer.process(pyClass); - } + return query.forEach(pyClass -> { + return consumer.process(pyClass); }); } else if (queryParameters instanceof PyFunction) { @@ -51,10 +49,8 @@ public class PyDefinitionsSearch implements QueryExecutor() { - public boolean process(final PyFunction pyFunction) { - return consumer.process(pyFunction); - } + pyFunction -> { + return consumer.process(pyFunction); } ); } diff --git a/python/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java b/python/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java index 2aa7d86b18c7..89a249856827 100644 --- a/python/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java +++ b/python/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java @@ -47,22 +47,19 @@ public class PyKeywordArgumentSearchExecutor extends QueryExecutorBase() { - @Override - public boolean process(PsiReference reference) { - final PsiElement refElement = reference.getElement(); - final PyCallExpression call = PsiTreeUtil.getParentOfType(refElement, PyCallExpression.class); - if (call != null && PsiTreeUtil.isAncestor(call.getCallee(), refElement, false)) { - final PyArgumentList argumentList = call.getArgumentList(); - if (argumentList != null) { - final PyKeywordArgument keywordArgument = argumentList.getKeywordArgument(((PyNamedParameter)element).getName()); - if (keywordArgument != null) { - return consumer.process(keywordArgument.getReference()); - } + ReferencesSearch.search(owner, queryParameters.getScopeDeterminedByUser()).forEach(reference -> { + final PsiElement refElement = reference.getElement(); + final PyCallExpression call = PsiTreeUtil.getParentOfType(refElement, PyCallExpression.class); + if (call != null && PsiTreeUtil.isAncestor(call.getCallee(), refElement, false)) { + final PyArgumentList argumentList = call.getArgumentList(); + if (argumentList != null) { + final PyKeywordArgument keywordArgument = argumentList.getKeywordArgument(((PyNamedParameter)element).getName()); + if (keywordArgument != null) { + return consumer.process(keywordArgument.getReference()); } } - return true; } + return true; }); } } diff --git a/python/src/com/jetbrains/python/psi/search/PyOverridingMethodsSearchExecutor.java b/python/src/com/jetbrains/python/psi/search/PyOverridingMethodsSearchExecutor.java index 99a54daf975c..b7ac6dadc1c6 100644 --- a/python/src/com/jetbrains/python/psi/search/PyOverridingMethodsSearchExecutor.java +++ b/python/src/com/jetbrains/python/psi/search/PyOverridingMethodsSearchExecutor.java @@ -40,31 +40,29 @@ public class PyOverridingMethodsSearchExecutor implements QueryExecutor() { - public boolean process(final PyClass pyClass) { - final AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); - PyFunction overridingMethod; - try { - overridingMethod = pyClass.findMethodByName(baseMethod.getName(), false, null); - if (overridingMethod != null) { - final Property baseProperty = baseMethod.getProperty(); - final Property overridingProperty = overridingMethod.getProperty(); - if (baseProperty != null && overridingProperty != null) { - final AccessDirection direction = PyUtil.getPropertyAccessDirection(baseMethod); - final PyCallable callable = overridingProperty.getByDirection(direction).valueOrNull(); - overridingMethod = (callable instanceof PyFunction) ? (PyFunction)callable : null; - } + return PyClassInheritorsSearch.search(containingClass, queryParameters.isCheckDeep()).forEach(pyClass -> { + final AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); + PyFunction overridingMethod; + try { + overridingMethod = pyClass.findMethodByName(baseMethod.getName(), false, null); + if (overridingMethod != null) { + final Property baseProperty = baseMethod.getProperty(); + final Property overridingProperty = overridingMethod.getProperty(); + if (baseProperty != null && overridingProperty != null) { + final AccessDirection direction = PyUtil.getPropertyAccessDirection(baseMethod); + final PyCallable callable = overridingProperty.getByDirection(direction).valueOrNull(); + overridingMethod = (callable instanceof PyFunction) ? (PyFunction)callable : null; } } - finally { - accessToken.finish(); - } - //noinspection SimplifiableIfStatement - if (overridingMethod != null) { - return consumer.process(overridingMethod); - } - return true; } + finally { + accessToken.finish(); + } + //noinspection SimplifiableIfStatement + if (overridingMethod != null) { + return consumer.process(overridingMethod); + } + return true; }); } } diff --git a/python/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java b/python/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java index 62036e848a6c..44655ad0bd34 100644 --- a/python/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java +++ b/python/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java @@ -43,12 +43,9 @@ public class PyClassAttributesIndex extends StringStubIndexExtension { pyClass.getClassAttributes(), Arrays.asList(pyClass.getMethods())); - return ContainerUtil.mapNotNull(members, new Function() { - @Override - public String fun(PsiNamedElement expression) { - final String attrName = expression.getName(); - return attrName != null ? attrName : null; - } + return ContainerUtil.mapNotNull(members, expression -> { + final String attrName = expression.getName(); + return attrName != null ? attrName : null; }); } } diff --git a/python/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java b/python/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java index 202ad05c300d..8867454ff6ae 100644 --- a/python/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java +++ b/python/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java @@ -86,24 +86,21 @@ public class PyCallableTypeImpl implements PyCallableType { return String.format("(%s) -> %s", myParameters != null ? StringUtil.join(myParameters, - new Function() { - @Override - public String fun(PyCallableParameter param) { - if (param != null) { - final StringBuilder builder = new StringBuilder(); - final String name = param.getName(); - final PyType type = param.getType(context); - if (name != null) { - builder.append(name); - if (type != null) { - builder.append(": "); - } + param -> { + if (param != null) { + final StringBuilder builder = new StringBuilder(); + final String name = param.getName(); + final PyType type = param.getType(context); + if (name != null) { + builder.append(name); + if (type != null) { + builder.append(": "); } - builder.append(type != null ? type.getName() : PyNames.UNKNOWN_TYPE); - return builder.toString(); } - return PyNames.UNKNOWN_TYPE; + builder.append(type != null ? type.getName() : PyNames.UNKNOWN_TYPE); + return builder.toString(); } + return PyNames.UNKNOWN_TYPE; }, ", ") : "...", diff --git a/python/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java b/python/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java index fae80a8b1260..3660c809f15f 100644 --- a/python/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java +++ b/python/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java @@ -311,21 +311,18 @@ public class PyClassTypeImpl extends UserDataHolderBase implements PyClassType { return null; } try { - return Collections.max(classTypes, new Comparator() { - @Override - public int compare(@Nullable PyClassLikeType t1, @Nullable PyClassLikeType t2) { - if (t1 == t2 || t1 != null && t1.equals(t2)) { - return 0; - } - else if (t2 == null || t1 != null && Sets.newHashSet(t1.getAncestorTypes(context)).contains(t2)) { - return 1; - } - else if (t1 == null || Sets.newHashSet(t2.getAncestorTypes(context)).contains(t1)) { - return -1; - } - else { - throw new NotDerivedClassTypeException(); - } + return Collections.max(classTypes, (t1, t2) -> { + if (t1 == t2 || t1 != null && t1.equals(t2)) { + return 0; + } + else if (t2 == null || t1 != null && Sets.newHashSet(t1.getAncestorTypes(context)).contains(t2)) { + return 1; + } + else if (t1 == null || Sets.newHashSet(t2.getAncestorTypes(context)).contains(t1)) { + return -1; + } + else { + throw new NotDerivedClassTypeException(); } }); } diff --git a/python/src/com/jetbrains/python/psi/types/PyGenericType.java b/python/src/com/jetbrains/python/psi/types/PyGenericType.java index c43f14235ab5..b3f47fb9a4ae 100644 --- a/python/src/com/jetbrains/python/psi/types/PyGenericType.java +++ b/python/src/com/jetbrains/python/psi/types/PyGenericType.java @@ -60,12 +60,7 @@ public class PyGenericType implements PyType { public String getName() { if (myBound instanceof PyUnionType) { final PyUnionType bounds = (PyUnionType)myBound; - final String boundsString = StringUtil.join(bounds.getMembers(), new Function() { - @Override - public String fun(PyType type) { - return type != null ? type.getName() : PyNames.UNKNOWN_TYPE; - } - }, ", "); + final String boundsString = StringUtil.join(bounds.getMembers(), type -> type != null ? type.getName() : PyNames.UNKNOWN_TYPE, ", "); return "TypeVar('" + myName + "', " + boundsString + ")"; } else { diff --git a/python/src/com/jetbrains/python/psi/types/PyModuleType.java b/python/src/com/jetbrains/python/psi/types/PyModuleType.java index e3d10786380d..c761c08a52fc 100644 --- a/python/src/com/jetbrains/python/psi/types/PyModuleType.java +++ b/python/src/com/jetbrains/python/psi/types/PyModuleType.java @@ -389,18 +389,15 @@ public class PyModuleType implements PyType { // Modules don't descend from obje final List elements = collectImportedSubmodules(pyPackage, location); return elements != null ? ContainerUtil.mapNotNull(elements, - new Function() { - @Override - public LookupElement fun(PsiElement element) { - if (element instanceof PsiFileSystemItem) { - return buildFileLookupElement((PsiFileSystemItem)element, existingNames); - } - else if (element instanceof PsiNamedElement) { - return LookupElementBuilder.createWithIcon((PsiNamedElement)element); - } - return null; - } - }) : Collections.emptyList(); + (Function)element -> { + if (element instanceof PsiFileSystemItem) { + return buildFileLookupElement((PsiFileSystemItem)element, existingNames); + } + else if (element instanceof PsiNamedElement) { + return LookupElementBuilder.createWithIcon((PsiNamedElement)element); + } + return null; + }) : Collections.emptyList(); } @Nullable diff --git a/python/src/com/jetbrains/python/psi/types/PyTypeUtil.java b/python/src/com/jetbrains/python/psi/types/PyTypeUtil.java index 429a76aaca00..1351e4d98c72 100644 --- a/python/src/com/jetbrains/python/psi/types/PyTypeUtil.java +++ b/python/src/com/jetbrains/python/psi/types/PyTypeUtil.java @@ -44,16 +44,13 @@ public final class PyTypeUtil { @NotNull final TypeEvalContext context) { final List result = new ArrayList(); - type.visitMembers(new Processor() { - @Override - public boolean process(final PsiElement t) { - if (expectedMemberType.isInstance(t)) { - @SuppressWarnings("unchecked") // Already checked - final T castedElement = (T)t; - result.add(castedElement); - } - return true; + type.visitMembers(t -> { + if (expectedMemberType.isInstance(t)) { + @SuppressWarnings("unchecked") // Already checked + final T castedElement = (T)t; + result.add(castedElement); } + return true; }, inherited, context); return result; } diff --git a/python/src/com/jetbrains/python/psi/types/PyUnionType.java b/python/src/com/jetbrains/python/psi/types/PyUnionType.java index 6b26cfeba8d8..235331bdcde4 100644 --- a/python/src/com/jetbrains/python/psi/types/PyUnionType.java +++ b/python/src/com/jetbrains/python/psi/types/PyUnionType.java @@ -69,11 +69,7 @@ public class PyUnionType implements PyType { } public String getName() { - return StringUtil.join(myMembers, new NullableFunction() { - public String fun(PyType type) { - return type != null ? type.getName() : null; - } - }, " | "); + return StringUtil.join(myMembers, (NullableFunction)type -> type != null ? type.getName() : null, " | "); } /** diff --git a/python/src/com/jetbrains/python/pyi/PyiRelatedItemLineMarkerProvider.java b/python/src/com/jetbrains/python/pyi/PyiRelatedItemLineMarkerProvider.java index d2d3d1d216c9..c76e9dd37e37 100644 --- a/python/src/com/jetbrains/python/pyi/PyiRelatedItemLineMarkerProvider.java +++ b/python/src/com/jetbrains/python/pyi/PyiRelatedItemLineMarkerProvider.java @@ -51,12 +51,7 @@ public class PyiRelatedItemLineMarkerProvider extends RelatedItemLineMarkerProvi final List relatedItems = GotoRelatedItem.createItems(Collections.singletonList(pythonStub)); result.add(new RelatedItemLineMarkerInfo( element, element.getTextRange(), ICON, Pass.UPDATE_OVERRIDDEN_MARKERS, - new Function() { - @Override - public String fun(PsiElement element) { - return "Has stub item in " + pythonStub.getContainingFile().getName(); - } - }, new GutterIconNavigationHandler() { + element1 -> "Has stub item in " + pythonStub.getContainingFile().getName(), new GutterIconNavigationHandler() { @Override public void navigate(MouseEvent e, PsiElement elt) { final PsiElement pythonStub = getPythonStub(elt); diff --git a/python/src/com/jetbrains/python/pyi/PyiTypeProvider.java b/python/src/com/jetbrains/python/pyi/PyiTypeProvider.java index 221817a5f578..a5b6a78f6c7a 100644 --- a/python/src/com/jetbrains/python/pyi/PyiTypeProvider.java +++ b/python/src/com/jetbrains/python/pyi/PyiTypeProvider.java @@ -160,14 +160,11 @@ public class PyiTypeProvider extends PyTypeProviderBase { final ScopeOwner owner = ScopeUtil.getScopeOwner(function); final String name = function.getName(); final List overloads = new ArrayList(); - final Processor overloadsProcessor = new Processor() { - @Override - public boolean process(@NotNull PyFunction f) { - if (name != null && name.equals(f.getName()) && isOverload(f, context)) { - overloads.add(f); - } - return true; + final Processor overloadsProcessor = f -> { + if (name != null && name.equals(f.getName()) && isOverload(f, context)) { + overloads.add(f); } + return true; }; if (owner instanceof PyClass) { final PyClass cls = (PyClass)owner; diff --git a/python/src/com/jetbrains/python/refactoring/PyDefUseUtil.java b/python/src/com/jetbrains/python/refactoring/PyDefUseUtil.java index 09b56325ce73..f4d6af60cff1 100644 --- a/python/src/com/jetbrains/python/refactoring/PyDefUseUtil.java +++ b/python/src/com/jetbrains/python/refactoring/PyDefUseUtil.java @@ -67,30 +67,27 @@ public class PyDefUseUtil { final boolean acceptTypeAssertions, final boolean acceptImplicitImports) { final Collection result = new LinkedHashSet(); ControlFlowUtil.iteratePrev(instr, instructions, - new Function() { - @Override - public ControlFlowUtil.Operation fun(Instruction instruction) { - final PsiElement element = instruction.getElement(); - final PyImplicitImportNameDefiner implicit = PyUtil.as(element, PyImplicitImportNameDefiner.class); - if (instruction instanceof ReadWriteInstruction) { - final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; - final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); - if (access.isWriteAccess() || acceptTypeAssertions && access.isAssertTypeAccess()) { - final String name = elementName(element); - if (Comparing.strEqual(name, varName)) { - result.add(rwInstruction); - return ControlFlowUtil.Operation.CONTINUE; - } - } - } - else if (acceptImplicitImports && implicit != null) { - if (!implicit.multiResolveName(varName).isEmpty()) { - result.add(instruction); + instruction -> { + final PsiElement element = instruction.getElement(); + final PyImplicitImportNameDefiner implicit = PyUtil.as(element, PyImplicitImportNameDefiner.class); + if (instruction instanceof ReadWriteInstruction) { + final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; + final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); + if (access.isWriteAccess() || acceptTypeAssertions && access.isAssertTypeAccess()) { + final String name = elementName(element); + if (Comparing.strEqual(name, varName)) { + result.add(rwInstruction); return ControlFlowUtil.Operation.CONTINUE; } } - return ControlFlowUtil.Operation.NEXT; } + else if (acceptImplicitImports && implicit != null) { + if (!implicit.multiResolveName(varName).isEmpty()) { + result.add(instruction); + return ControlFlowUtil.Operation.CONTINUE; + } + } + return ControlFlowUtil.Operation.NEXT; }); return result; } diff --git a/python/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java b/python/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java index db4b8d217a55..e334d7d021f9 100644 --- a/python/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java +++ b/python/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java @@ -300,14 +300,11 @@ public class PyRefactoringUtil { Collections.addAll(elementsToProcess, handler.getPrimaryElements()); Collections.addAll(elementsToProcess, handler.getSecondaryElements()); for (PsiElement e : elementsToProcess) { - handler.processElementUsages(e, new Processor() { - @Override - public boolean process(UsageInfo usageInfo) { - if (!usageInfo.isNonCodeUsage) { - usages.add(usageInfo); - } - return true; + handler.processElementUsages(e, usageInfo -> { + if (!usageInfo.isNonCodeUsage) { + usages.add(usageInfo); } + return true; }, FindUsagesHandler.createFindUsagesOptions(element.getProject(), null)); } return usages; diff --git a/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java b/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java index daad4a037230..6d71201c5a02 100644 --- a/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java +++ b/python/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java @@ -236,11 +236,8 @@ public class PyReplaceExpressionUtil implements PyElementTypes { final StringBuilder builder = new StringBuilder(); builder.append("{"); final PyKeyValueExpression[] elements = dict.getElements(); - builder.append(StringUtil.join(elements, new Function() { - @Override - public String fun(PyKeyValueExpression expression) { - return expression.getText(); - } + builder.append(StringUtil.join(elements, expression -> { + return expression.getText(); }, ",")); if (elements.length > 0) { builder.append(","); diff --git a/python/src/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureDialog.java b/python/src/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureDialog.java index 69b7a168b0dd..6970e8384470 100644 --- a/python/src/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureDialog.java +++ b/python/src/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureDialog.java @@ -221,11 +221,9 @@ public class PyChangeSignatureDialog extends ChangeSignatureDialogBase { + getRefactorAction().setEnabled(message == null); + getPreviewAction().setEnabled(message == null); }); if (message != null) return new ValidationInfo(message); return super.doValidate(); diff --git a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java index af0a3b8f01dc..b1a622bd9978 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java +++ b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java @@ -420,11 +420,8 @@ public final class PyClassRefactoringUtil { @NotNull private static List multiResolveExpression(@NotNull PyReferenceExpression expr) { - return ContainerUtil.mapNotNull(expr.getReference().multiResolve(false), new Function() { - @Override - public PsiElement fun(ResolveResult result) { - return result.getElement(); - } + return ContainerUtil.mapNotNull(expr.getReference().multiResolve(false), result -> { + return result.getElement(); }); } diff --git a/python/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java b/python/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java index de7b3bcc60d3..d408ab096d74 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java +++ b/python/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java @@ -71,12 +71,8 @@ public final class PyExtractSuperclassHelper { selectedMemberInfos = new ArrayList>(selectedMemberInfos); final RefactoringEventData beforeData = new RefactoringEventData(); - beforeData.addElements(JBIterable.from(selectedMemberInfos).transform(new Function, PsiElement>() { - @Override - public PsiElement fun(PyMemberInfo info) { - return info.getMember(); - } - }).toList()); + beforeData.addElements(JBIterable.from(selectedMemberInfos).transform( + (Function, PsiElement>)info -> info.getMember()).toList()); project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringStarted(getRefactoringId(), beforeData); diff --git a/python/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java b/python/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java index 3eb59ab36380..cbc6d9c4e8d0 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java +++ b/python/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java @@ -105,12 +105,7 @@ public abstract class MembersManager implements Function> memberInfosSorted = new ArrayList>(memberInfos); - Collections.sort(memberInfosSorted, new Comparator>() { - @Override - public int compare(PyMemberInfo o1, PyMemberInfo o2) { - return PyDependenciesComparator.INSTANCE.compare(o1.getMember(), o2.getMember()); - } - }); + Collections.sort(memberInfosSorted, (o1, o2) -> PyDependenciesComparator.INSTANCE.compare(o1.getMember(), o2.getMember())); for (PyMemberInfo info : memberInfosSorted) { TypeSafeMovingStrategy.moveCheckingTypesAtRunTime(from, info.getMembersManager(), Collections.singleton(info), to); diff --git a/python/src/com/jetbrains/python/refactoring/classes/membersManager/PyMembersRefactoringBaseProcessor.java b/python/src/com/jetbrains/python/refactoring/classes/membersManager/PyMembersRefactoringBaseProcessor.java index 350d7a2b9cfe..40337e1d15c5 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/membersManager/PyMembersRefactoringBaseProcessor.java +++ b/python/src/com/jetbrains/python/refactoring/classes/membersManager/PyMembersRefactoringBaseProcessor.java @@ -107,12 +107,7 @@ public abstract class PyMembersRefactoringBaseProcessor extends BaseRefactoringP protected RefactoringEventData getBeforeData() { RefactoringEventData data = new RefactoringEventData(); data.addElement(myFrom); - data.addMembers(myMembersToMove.toArray(new PyMemberInfo[myMembersToMove.size()]), new Function() { - @Override - public PsiElement fun(PyMemberInfo info) { - return info.getMember(); - } - }); + data.addMembers(myMembersToMove.toArray(new PyMemberInfo[myMembersToMove.size()]), info -> info.getMember()); return data; } diff --git a/python/src/com/jetbrains/python/refactoring/classes/membersManager/vp/MembersBasedPresenterNoPreviewImpl.java b/python/src/com/jetbrains/python/refactoring/classes/membersManager/vp/MembersBasedPresenterNoPreviewImpl.java index 7aec83316901..33bfdd42bc75 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/membersManager/vp/MembersBasedPresenterNoPreviewImpl.java +++ b/python/src/com/jetbrains/python/refactoring/classes/membersManager/vp/MembersBasedPresenterNoPreviewImpl.java @@ -55,12 +55,8 @@ public abstract class MembersBasedPresenterNoPreviewImpl ApplicationManager.getApplication().runWriteAction(new MyRunnableRefactoring()), getCommandName(), null); myView.close(); } diff --git a/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertModuleToPackageAction.java b/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertModuleToPackageAction.java index 2808e806af71..4950c02f2390 100644 --- a/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertModuleToPackageAction.java +++ b/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertModuleToPackageAction.java @@ -59,16 +59,14 @@ public class PyConvertModuleToPackageAction extends PyBaseConvertModulePackageAc showFileExistsErrorMessage(existing, ID, file.getProject()); return; } - WriteCommandAction.runWriteCommandAction(file.getProject(), new Runnable() { - public void run() { - try { - final VirtualFile packageDir = parentDir.createChildDirectory(PyConvertModuleToPackageAction.this, newPackageName); - vFile.move(PyConvertModuleToPackageAction.this, packageDir); - vFile.rename(PyConvertModuleToPackageAction.this, PyNames.INIT_DOT_PY); - } - catch (IOException e) { - LOG.error(e); - } + WriteCommandAction.runWriteCommandAction(file.getProject(), () -> { + try { + final VirtualFile packageDir = parentDir.createChildDirectory(PyConvertModuleToPackageAction.this, newPackageName); + vFile.move(PyConvertModuleToPackageAction.this, packageDir); + vFile.rename(PyConvertModuleToPackageAction.this, PyNames.INIT_DOT_PY); + } + catch (IOException e) { + LOG.error(e); } }); } diff --git a/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertPackageToModuleAction.java b/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertPackageToModuleAction.java index 70496fed58fe..7fb2d12dc173 100644 --- a/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertPackageToModuleAction.java +++ b/python/src/com/jetbrains/python/refactoring/convertModulePackage/PyConvertPackageToModuleAction.java @@ -104,22 +104,20 @@ public class PyConvertPackageToModuleAction extends PyBaseConvertModulePackageAc return; } final PsiFile initPy = pyPackage.findFile(PyNames.INIT_DOT_PY); - WriteCommandAction.runWriteCommandAction(pyPackage.getProject(), new Runnable() { - public void run() { - try { - if (initPy != null) { - final VirtualFile initPyVFile = initPy.getVirtualFile(); - initPyVFile.rename(PyConvertPackageToModuleAction.this, moduleName); - initPyVFile.move(PyConvertPackageToModuleAction.this, parentDirVFile); - } - else { - PyUtil.getOrCreateFile(parentDirVFile.getPath() + "/" + moduleName, pyPackage.getProject()); - } - pyPackage.getVirtualFile().delete(PyConvertPackageToModuleAction.this); + WriteCommandAction.runWriteCommandAction(pyPackage.getProject(), () -> { + try { + if (initPy != null) { + final VirtualFile initPyVFile = initPy.getVirtualFile(); + initPyVFile.rename(PyConvertPackageToModuleAction.this, moduleName); + initPyVFile.move(PyConvertPackageToModuleAction.this, parentDirVFile); } - catch (IOException e) { - LOG.error(e); + else { + PyUtil.getOrCreateFile(parentDirVFile.getPath() + "/" + moduleName, pyPackage.getProject()); } + pyPackage.getVirtualFile().delete(PyConvertPackageToModuleAction.this); + } + catch (IOException e) { + LOG.error(e); } }); } diff --git a/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java b/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java index a47c87a6c0e4..f0b20df676bc 100644 --- a/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java +++ b/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java @@ -108,87 +108,81 @@ public class PyExtractMethodUtil { final SimpleDuplicatesFinder finder = new SimpleDuplicatesFinder(statement1, statement2, fragment.getOutputVariables(), variableData); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final RefactoringEventData beforeData = new RefactoringEventData(); - beforeData.addElements(new PsiElement[]{statement1, statement2}); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) - .refactoringStarted(getRefactoringId(), beforeData); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + final RefactoringEventData beforeData = new RefactoringEventData(); + beforeData.addElements(new PsiElement[]{statement1, statement2}); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) + .refactoringStarted(getRefactoringId(), beforeData); - final StringBuilder builder = new StringBuilder(); - final boolean isAsync = fragment.isAsync(); - if (isAsync) { - builder.append("async "); - } - builder.append("def f():\n "); - final List newMethodElements = new ArrayList(elementsRange); - final boolean hasOutputVariables = !fragment.getOutputVariables().isEmpty(); - - final PyElementGenerator generator = PyElementGenerator.getInstance(project); - final LanguageLevel languageLevel = LanguageLevel.forElement(statement1); - if (hasOutputVariables) { - // Generate return modified variables statements - final String outputVariables = StringUtil.join(fragment.getOutputVariables(), ", "); - String newMethodText = builder + "return " + outputVariables; - builder.append(outputVariables); - - final PyFunction function = generator.createFromText(languageLevel, PyFunction.class, newMethodText); - final PsiElement returnStatement = function.getStatementList().getStatements()[0]; - newMethodElements.add(returnStatement); - } - - // Generate method - PyFunction generatedMethod = generateMethodFromElements(project, methodName, variableData, newMethodElements, flags, isAsync); - generatedMethod = insertGeneratedMethod(statement1, generatedMethod); - - // Process parameters - final PsiElement firstElement = elementsRange.get(0); - final boolean isMethod = PyPsiUtils.isMethodContext(firstElement); - processParameters(project, generatedMethod, variableData, isMethod, isClassMethod, isStaticMethod); - processGlobalWrites(generatedMethod, fragment); - processNonlocalWrites(generatedMethod, fragment); - - // Generate call element - if (hasOutputVariables) { - builder.append(" = "); - } - else if (fragment.isReturnInstructionInside()) { - builder.append("return "); - } - if (isAsync) { - builder.append("await "); - } - else if (fragment.isYieldInside()) { - builder.append("yield from "); - } - if (isMethod) { - appendSelf(firstElement, builder, isStaticMethod); - } - builder.append(methodName).append("("); - builder.append(createCallArgsString(variableData)).append(")"); - final PyFunction function = generator.createFromText(languageLevel, PyFunction.class, builder.toString()); - PsiElement callElement = function.getStatementList().getStatements()[0]; - - // replace statements with call - callElement = replaceElements(elementsRange, callElement); - callElement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(callElement); - if (callElement != null) { - processDuplicates(callElement, generatedMethod, finder, editor); - } - - // Set editor - setSelectionAndCaret(editor, callElement); - - final RefactoringEventData afterData = new RefactoringEventData(); - afterData.addElement(generatedMethod); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) - .refactoringDone(getRefactoringId(), afterData); - } - }); + final StringBuilder builder = new StringBuilder(); + final boolean isAsync = fragment.isAsync(); + if (isAsync) { + builder.append("async "); } - }, PyBundle.message("refactoring.extract.method"), null); + builder.append("def f():\n "); + final List newMethodElements = new ArrayList(elementsRange); + final boolean hasOutputVariables = !fragment.getOutputVariables().isEmpty(); + + final PyElementGenerator generator = PyElementGenerator.getInstance(project); + final LanguageLevel languageLevel = LanguageLevel.forElement(statement1); + if (hasOutputVariables) { + // Generate return modified variables statements + final String outputVariables = StringUtil.join(fragment.getOutputVariables(), ", "); + String newMethodText = builder + "return " + outputVariables; + builder.append(outputVariables); + + final PyFunction function1 = generator.createFromText(languageLevel, PyFunction.class, newMethodText); + final PsiElement returnStatement = function1.getStatementList().getStatements()[0]; + newMethodElements.add(returnStatement); + } + + // Generate method + PyFunction generatedMethod = generateMethodFromElements(project, methodName, variableData, newMethodElements, flags, isAsync); + generatedMethod = insertGeneratedMethod(statement1, generatedMethod); + + // Process parameters + final PsiElement firstElement = elementsRange.get(0); + final boolean isMethod = PyPsiUtils.isMethodContext(firstElement); + processParameters(project, generatedMethod, variableData, isMethod, isClassMethod, isStaticMethod); + processGlobalWrites(generatedMethod, fragment); + processNonlocalWrites(generatedMethod, fragment); + + // Generate call element + if (hasOutputVariables) { + builder.append(" = "); + } + else if (fragment.isReturnInstructionInside()) { + builder.append("return "); + } + if (isAsync) { + builder.append("await "); + } + else if (fragment.isYieldInside()) { + builder.append("yield from "); + } + if (isMethod) { + appendSelf(firstElement, builder, isStaticMethod); + } + builder.append(methodName).append("("); + builder.append(createCallArgsString(variableData)).append(")"); + final PyFunction function1 = generator.createFromText(languageLevel, PyFunction.class, builder.toString()); + PsiElement callElement = function1.getStatementList().getStatements()[0]; + + // replace statements with call + callElement = replaceElements(elementsRange, callElement); + callElement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(callElement); + if (callElement != null) { + processDuplicates(callElement, generatedMethod, finder, editor); + } + + // Set editor + setSelectionAndCaret(editor, callElement); + + final RefactoringEventData afterData = new RefactoringEventData(); + afterData.addElement(generatedMethod); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) + .refactoringDone(getRefactoringId(), afterData); + }), PyBundle.message("refactoring.extract.method"), null); } private static void processDuplicates(@NotNull final PsiElement callElement, @@ -210,12 +204,7 @@ public class PyExtractMethodUtil { } } ExtractMethodHelper.processDuplicates(callElement, generatedMethod, scope, finder, editor, - new Consumer>() { - @Override - public void consume(@NotNull Pair pair) { - replaceElements(pair.first, pair.second.copy()); - } - } + pair -> replaceElements(pair.first, pair.second.copy()) ); } @@ -303,66 +292,58 @@ public class PyExtractMethodUtil { final SimpleDuplicatesFinder finder = new SimpleDuplicatesFinder(expression, expression, fragment.getOutputVariables(), variableData); if (fragment.getOutputVariables().isEmpty()) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - // Generate method - final boolean isAsync = fragment.isAsync(); - PyFunction generatedMethod = generateMethodFromExpression(project, methodName, variableData, expression, flags, isAsync); - generatedMethod = insertGeneratedMethod(expression, generatedMethod); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + // Generate method + final boolean isAsync = fragment.isAsync(); + PyFunction generatedMethod = generateMethodFromExpression(project, methodName, variableData, expression, flags, isAsync); + generatedMethod = insertGeneratedMethod(expression, generatedMethod); - // Process parameters - final boolean isMethod = PyPsiUtils.isMethodContext(expression); - processParameters(project, generatedMethod, variableData, isMethod, isClassMethod, isStaticMethod); + // Process parameters + final boolean isMethod = PyPsiUtils.isMethodContext(expression); + processParameters(project, generatedMethod, variableData, isMethod, isClassMethod, isStaticMethod); - // Generating call element - final StringBuilder builder = new StringBuilder(); - if (isAsync) { - builder.append("async "); - } - builder.append("def f():\n "); - if (isAsync) { - builder.append("await "); - } - else if (fragment.isYieldInside()) { - builder.append("yield from "); - } - else { - builder.append("return "); - } - if (isMethod) { - appendSelf(expression, builder, isStaticMethod); - } - builder.append(methodName); - builder.append("(").append(createCallArgsString(variableData)).append(")"); - final PyElementGenerator generator = PyElementGenerator.getInstance(project); - final PyFunction function = generator.createFromText(LanguageLevel.forElement(expression), PyFunction.class, - builder.toString()); - final PyElement generated = function.getStatementList().getStatements()[0]; - PsiElement callElement = null; - if (generated instanceof PyReturnStatement) { - callElement = ((PyReturnStatement)generated).getExpression(); - } - else if (generated instanceof PyExpressionStatement) { - callElement = ((PyExpressionStatement)generated).getExpression(); - } - - // replace statements with call - if (callElement != null) { - callElement = PyReplaceExpressionUtil.replaceExpression(expression, callElement); - } - if (callElement != null) { - processDuplicates(callElement, generatedMethod, finder, editor); - } - // Set editor - setSelectionAndCaret(editor, callElement); - } - }); + // Generating call element + final StringBuilder builder = new StringBuilder(); + if (isAsync) { + builder.append("async "); } - }, PyBundle.message("refactoring.extract.method"), null); + builder.append("def f():\n "); + if (isAsync) { + builder.append("await "); + } + else if (fragment.isYieldInside()) { + builder.append("yield from "); + } + else { + builder.append("return "); + } + if (isMethod) { + appendSelf(expression, builder, isStaticMethod); + } + builder.append(methodName); + builder.append("(").append(createCallArgsString(variableData)).append(")"); + final PyElementGenerator generator = PyElementGenerator.getInstance(project); + final PyFunction function1 = generator.createFromText(LanguageLevel.forElement(expression), PyFunction.class, + builder.toString()); + final PyElement generated = function1.getStatementList().getStatements()[0]; + PsiElement callElement = null; + if (generated instanceof PyReturnStatement) { + callElement = ((PyReturnStatement)generated).getExpression(); + } + else if (generated instanceof PyExpressionStatement) { + callElement = ((PyExpressionStatement)generated).getExpression(); + } + + // replace statements with call + if (callElement != null) { + callElement = PyReplaceExpressionUtil.replaceExpression(expression, callElement); + } + if (callElement != null) { + processDuplicates(callElement, generatedMethod, finder, editor); + } + // Set editor + setSelectionAndCaret(editor, callElement); + }), PyBundle.message("refactoring.extract.method"), null); } } @@ -423,12 +404,7 @@ public class PyExtractMethodUtil { // Creates string for call @NotNull private static String createCallArgsString(@NotNull final AbstractVariableData[] variableDatas) { - return StringUtil.join(ContainerUtil.mapNotNull(variableDatas, new Function() { - @Override - public String fun(AbstractVariableData data) { - return data.isPassAsParameter() ? data.getOriginalName() : null; - } - }), ","); + return StringUtil.join(ContainerUtil.mapNotNull(variableDatas, data -> data.isPassAsParameter() ? data.getOriginalName() : null), ","); } private static void processParameters(@NotNull final Project project, @@ -681,25 +657,21 @@ public class PyExtractMethodUtil { myElement = element; myProject = project; final ScopeOwner parent = ScopeUtil.getScopeOwner(myElement); - myFunction = new Function() { - @NotNull - @Override - public Boolean fun(String s) { - ScopeOwner owner = parent; - while (owner != null) { - if (owner instanceof PyClass) { - if (((PyClass)owner).findMethodByName(s, true, null) != null) { - return false; - } - } - final Scope scope = ControlFlowCache.getScope(owner); - if (scope.containsDeclaration(s)) { + myFunction = s -> { + ScopeOwner owner = parent; + while (owner != null) { + if (owner instanceof PyClass) { + if (((PyClass)owner).findMethodByName(s, true, null) != null) { return false; } - owner = ScopeUtil.getScopeOwner(owner); } - return true; + final Scope scope = ControlFlowCache.getScope(owner); + if (scope.containsDeclaration(s)) { + return false; + } + owner = ScopeUtil.getScopeOwner(owner); } + return true; }; } diff --git a/python/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java b/python/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java index 8806c73774bd..1c7b385c34f3 100644 --- a/python/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java +++ b/python/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java @@ -186,67 +186,58 @@ public class PyInlineLocalHandler extends InlineActionHandler { } - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - final RefactoringEventData afterData = new RefactoringEventData(); - afterData.addElement(local); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) - .refactoringStarted(getRefactoringId(), afterData); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + final RefactoringEventData afterData = new RefactoringEventData(); + afterData.addElement(local); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) + .refactoringStarted(getRefactoringId(), afterData); - final PsiElement[] exprs = new PsiElement[refsToInline.length]; - final PyExpression value = prepareValue(def, localName, project); - final PyExpression withParenthesis = - PyElementGenerator.getInstance(project).createExpressionFromText("(" + value.getText() + ")"); - final PsiElement lastChild = def.getLastChild(); - if (lastChild != null && lastChild.getNode().getElementType() == PyTokenTypes.END_OF_LINE_COMMENT) { - final PsiElement parent = def.getParent(); - if (parent != null) parent.addBefore(lastChild, def); - } + final PsiElement[] exprs = new PsiElement[refsToInline.length]; + final PyExpression value = prepareValue(def, localName, project); + final PyExpression withParenthesis = + PyElementGenerator.getInstance(project).createExpressionFromText("(" + value.getText() + ")"); + final PsiElement lastChild = def.getLastChild(); + if (lastChild != null && lastChild.getNode().getElementType() == PyTokenTypes.END_OF_LINE_COMMENT) { + final PsiElement parent = def.getParent(); + if (parent != null) parent.addBefore(lastChild, def); + } - for (int i = 0, refsToInlineLength = refsToInline.length; i < refsToInlineLength; i++) { - final PsiElement element = refsToInline[i]; - if (PyReplaceExpressionUtil.isNeedParenthesis((PyExpression)element, value)) { - exprs[i] = element.replace(withParenthesis); - } - else { - exprs[i] = element.replace(value); - } - } - final PsiElement next = def.getNextSibling(); - if (next instanceof PsiWhiteSpace) { - PyPsiUtils.removeElements(next); - } - PyPsiUtils.removeElements(def); - - final List ranges = ContainerUtil.mapNotNull(exprs, new Function() { - @Override - public TextRange fun(PsiElement element) { - final PyStatement parentalStatement = PsiTreeUtil.getParentOfType(element, PyStatement.class, false); - return parentalStatement != null ? parentalStatement.getTextRange() : null; - } - }); - PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); - CodeStyleManager.getInstance(project).reformatText(workingFile, ranges); - - if (!ApplicationManager.getApplication().isUnitTestMode()) { - highlightManager.addOccurrenceHighlights(editor, exprs, attributes, true, null); - WindowManager.getInstance().getStatusBar(project) - .setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting")); - } - } - finally { - final RefactoringEventData afterData = new RefactoringEventData(); - afterData.addElement(local); - project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) - .refactoringDone(getRefactoringId(), afterData); - } + for (int i = 0, refsToInlineLength = refsToInline.length; i < refsToInlineLength; i++) { + final PsiElement element = refsToInline[i]; + if (PyReplaceExpressionUtil.isNeedParenthesis((PyExpression)element, value)) { + exprs[i] = element.replace(withParenthesis); } + else { + exprs[i] = element.replace(value); + } + } + final PsiElement next = def.getNextSibling(); + if (next instanceof PsiWhiteSpace) { + PyPsiUtils.removeElements(next); + } + PyPsiUtils.removeElements(def); + + final List ranges = ContainerUtil.mapNotNull(exprs, element -> { + final PyStatement parentalStatement = PsiTreeUtil.getParentOfType(element, PyStatement.class, false); + return parentalStatement != null ? parentalStatement.getTextRange() : null; }); + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + CodeStyleManager.getInstance(project).reformatText(workingFile, ranges); + + if (!ApplicationManager.getApplication().isUnitTestMode()) { + highlightManager.addOccurrenceHighlights(editor, exprs, attributes, true, null); + WindowManager.getInstance().getStatusBar(project) + .setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting")); + } } - }, RefactoringBundle.message("inline.command", localName), null); + finally { + final RefactoringEventData afterData = new RefactoringEventData(); + afterData.addElement(local); + project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) + .refactoringDone(getRefactoringId(), afterData); + } + }), RefactoringBundle.message("inline.command", localName), null); } private static boolean isSameDefinition(PyStatement def, PsiElement otherDef) { diff --git a/python/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java b/python/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java index d1d9bdf13492..8f6645e7dee0 100644 --- a/python/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java +++ b/python/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java @@ -390,11 +390,7 @@ abstract public class IntroduceHandler implements RefactoringActionHandler { operation.setElement(pyExpression); performActionOnElement(operation); } - }, new Function() { - public String fun(PyExpression pyExpression) { - return pyExpression.getText(); - } - }); + }, pyExpression -> pyExpression.getText()); return true; } return false; diff --git a/python/src/com/jetbrains/python/refactoring/makeFunctionTopLevel/PyMakeMethodTopLevelProcessor.java b/python/src/com/jetbrains/python/refactoring/makeFunctionTopLevel/PyMakeMethodTopLevelProcessor.java index ae516b00f3bb..52d4a3d83dc8 100644 --- a/python/src/com/jetbrains/python/refactoring/makeFunctionTopLevel/PyMakeMethodTopLevelProcessor.java +++ b/python/src/com/jetbrains/python/refactoring/makeFunctionTopLevel/PyMakeMethodTopLevelProcessor.java @@ -120,12 +120,7 @@ public class PyMakeMethodTopLevelProcessor extends PyBaseMakeFunctionTopLevelPro } else { final String instanceExprText = instanceExpr.getText(); - addArguments(argumentList, ContainerUtil.map(attrNames, new Function() { - @Override - public String fun(String attribute) { - return instanceExprText + "." + attribute; - } - })); + addArguments(argumentList, ContainerUtil.map(attrNames, attribute -> instanceExprText + "." + attribute)); } } // Class().method() -> method(Class().foo) @@ -142,12 +137,7 @@ public class PyMakeMethodTopLevelProcessor extends PyBaseMakeFunctionTopLevelPro assignmentText); //noinspection ConstantConditions anchor.getParent().addBefore(assignment, anchor); - addArguments(argumentList, ContainerUtil.map(attrNames, new Function() { - @Override - public String fun(String attribute) { - return targetName + "." + attribute; - } - })); + addArguments(argumentList, ContainerUtil.map(attrNames, attribute -> targetName + "." + attribute)); } } } diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersDialog.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersDialog.java index d14ca0ebc8c3..a016537a09d4 100644 --- a/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersDialog.java +++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersDialog.java @@ -188,12 +188,9 @@ public class PyMoveModuleMembersDialog extends RefactoringDialog { } }); - UiNotifyConnector.doWhenFirstShown(myCenterPanel, new Runnable() { - @Override - public void run() { - enlargeDialogHeightIfNecessary(); - preselectLastPathComponent(myBrowseFieldWithButton.getTextField()); - } + UiNotifyConnector.doWhenFirstShown(myCenterPanel, () -> { + enlargeDialogHeightIfNecessary(); + preselectLastPathComponent(myBrowseFieldWithButton.getTextField()); }); init(); } @@ -262,28 +259,17 @@ public class PyMoveModuleMembersDialog extends RefactoringDialog { @NotNull public List getSelectedTopLevelSymbols() { final Collection selectedMembers = myMemberSelectionTable.getSelectedMemberInfos(); - final List selectedElements = ContainerUtil.map(selectedMembers, new Function() { - @Override - public PyElement fun(PyModuleMemberInfo info) { - return info.getMember(); - } - }); - return ContainerUtil.sorted(selectedElements, new Comparator() { - @Override - public int compare(PyElement e1, PyElement e2) { - return PyPsiUtils.isBefore(e1, e2) ? -1 : 1; - } + final List selectedElements = ContainerUtil.map(selectedMembers, info -> { + return info.getMember(); }); + return ContainerUtil.sorted(selectedElements, (e1, e2) -> PyPsiUtils.isBefore(e1, e2) ? -1 : 1); } @NotNull private static List collectModuleMemberInfos(@NotNull PyFile pyFile) { final List moduleMembers = PyMoveModuleMembersHelper.getTopLevelModuleMembers(pyFile); - return ContainerUtil.mapNotNull(moduleMembers, new Function() { - @Override - public PyModuleMemberInfo fun(PyElement element) { - return new PyModuleMemberInfo(element); - } + return ContainerUtil.mapNotNull(moduleMembers, element -> { + return new PyModuleMemberInfo(element); }); } diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersProcessor.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersProcessor.java index e018af93ca9d..21cd107d44f6 100644 --- a/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersProcessor.java +++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveModuleMembersProcessor.java @@ -89,11 +89,8 @@ public class PyMoveModuleMembersProcessor extends BaseRefactoringProcessor { protected UsageInfo[] findUsages() { final List result = new ArrayList(); for (final PsiNamedElement element : myElements) { - result.addAll(ContainerUtil.map(PyRefactoringUtil.findUsages(element, false), new Function() { - @Override - public MyUsageInfo fun(UsageInfo usageInfo) { - return new MyUsageInfo(usageInfo, element); - } + result.addAll(ContainerUtil.map(PyRefactoringUtil.findUsages(element, false), usageInfo -> { + return new MyUsageInfo(usageInfo, element); })); } return result.toArray(new UsageInfo[result.size()]); @@ -105,45 +102,39 @@ public class PyMoveModuleMembersProcessor extends BaseRefactoringProcessor { for (UsageInfo usage : usages) { usagesByElement.putValue(((MyUsageInfo)usage).myMovedElement, usage); } - CommandProcessor.getInstance().executeCommand(myElements[0].getProject(), new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - final PyFile destination = PyUtil.getOrCreateFile(myDestination, myProject); - CommonRefactoringUtil.checkReadOnlyStatus(myProject, destination); - for (final PsiNamedElement e : myElements) { - // TODO: Check for resulting circular imports - CommonRefactoringUtil.checkReadOnlyStatus(myProject, e); - assert e instanceof PyClass || e instanceof PyFunction || e instanceof PyTargetExpression; - if (e instanceof PyClass && destination.findTopLevelClass(e.getName()) != null) { - throw new IncorrectOperationException( - PyBundle.message("refactoring.move.module.members.error.destination.file.contains.class.$0", e.getName())); - } - if (e instanceof PyFunction && destination.findTopLevelFunction(e.getName()) != null) { - throw new IncorrectOperationException( - PyBundle.message("refactoring.move.module.members.error.destination.file.contains.function.$0", e.getName())); - } - if (e instanceof PyTargetExpression && destination.findTopLevelAttribute(e.getName()) != null) { - throw new IncorrectOperationException( - PyBundle.message("refactoring.move.module.members.error.destination.file.contains.global.variable.$0", e.getName())); - } - final Collection usageInfos = usagesByElement.get(e); - final boolean usedFromOutside = ContainerUtil.exists(usageInfos, new Condition() { - @Override - public boolean value(UsageInfo usageInfo) { - final PsiElement element = usageInfo.getElement(); - return element != null && !PsiTreeUtil.isAncestor(e, element, false); - } - }); - if (usedFromOutside) { - checkValidImportableFile(e, destination.getVirtualFile()); - } - new PyMoveSymbolProcessor(e, destination, usageInfos, myElements).moveElement(); - } + CommandProcessor.getInstance().executeCommand(myElements[0].getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + final PyFile destination = PyUtil.getOrCreateFile(myDestination, myProject); + CommonRefactoringUtil.checkReadOnlyStatus(myProject, destination); + for (final PsiNamedElement e : myElements) { + // TODO: Check for resulting circular imports + CommonRefactoringUtil.checkReadOnlyStatus(myProject, e); + assert e instanceof PyClass || e instanceof PyFunction || e instanceof PyTargetExpression; + if (e instanceof PyClass && destination.findTopLevelClass(e.getName()) != null) { + throw new IncorrectOperationException( + PyBundle.message("refactoring.move.module.members.error.destination.file.contains.class.$0", e.getName())); + } + if (e instanceof PyFunction && destination.findTopLevelFunction(e.getName()) != null) { + throw new IncorrectOperationException( + PyBundle.message("refactoring.move.module.members.error.destination.file.contains.function.$0", e.getName())); + } + if (e instanceof PyTargetExpression && destination.findTopLevelAttribute(e.getName()) != null) { + throw new IncorrectOperationException( + PyBundle.message("refactoring.move.module.members.error.destination.file.contains.global.variable.$0", e.getName())); + } + final Collection usageInfos = usagesByElement.get(e); + final boolean usedFromOutside = ContainerUtil.exists(usageInfos, new Condition() { + @Override + public boolean value(UsageInfo usageInfo) { + final PsiElement element = usageInfo.getElement(); + return element != null && !PsiTreeUtil.isAncestor(e, element, false); } }); + if (usedFromOutside) { + checkValidImportableFile(e, destination.getVirtualFile()); + } + new PyMoveSymbolProcessor(e, destination, usageInfos, myElements).moveElement(); } - }, REFACTORING_NAME, null); + }), REFACTORING_NAME, null); } @NotNull diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveSymbolProcessor.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveSymbolProcessor.java index 8c24ebcac5dc..f06f78e6f53f 100644 --- a/python/src/com/jetbrains/python/refactoring/move/PyMoveSymbolProcessor.java +++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveSymbolProcessor.java @@ -40,12 +40,7 @@ public class PyMoveSymbolProcessor { myMovedElement = element; myDestinationFile = destination; myAllMovedElements = otherElements; - myUsages = ContainerUtil.sorted(usages, new Comparator() { - @Override - public int compare(UsageInfo u1, UsageInfo u2) { - return PsiUtilCore.compareElementsByPosition(u1.getElement(), u2.getElement()); - } - }); + myUsages = ContainerUtil.sorted(usages, (u1, u2) -> PsiUtilCore.compareElementsByPosition(u1.getElement(), u2.getElement())); } public final void moveElement() { @@ -96,25 +91,17 @@ public class PyMoveSymbolProcessor { @Nullable private PsiElement findFirstTopLevelWithUsageAtDestination() { - final List topLevelAtDestination = ContainerUtil.mapNotNull(myUsages, new Function() { - @Override - public PsiElement fun(UsageInfo usage) { - final PsiElement element = usage.getElement(); - if (element != null && ScopeUtil.getScopeOwner(element) == myDestinationFile && getImportStatementByElement(element) == null) { - return findTopLevelParent(element); - } - return null; + final List topLevelAtDestination = ContainerUtil.mapNotNull(myUsages, usage -> { + final PsiElement element = usage.getElement(); + if (element != null && ScopeUtil.getScopeOwner(element) == myDestinationFile && getImportStatementByElement(element) == null) { + return findTopLevelParent(element); } + return null; }); if (topLevelAtDestination.isEmpty()) { return null; } - return Collections.min(topLevelAtDestination, new Comparator() { - @Override - public int compare(PsiElement e1, PsiElement e2) { - return PsiUtilCore.compareElementsByPosition(e1, e2); - } - }); + return Collections.min(topLevelAtDestination, (e1, e2) -> PsiUtilCore.compareElementsByPosition(e1, e2)); } @Nullable diff --git a/python/src/com/jetbrains/python/refactoring/rename/PyParametersRenameFactory.java b/python/src/com/jetbrains/python/refactoring/rename/PyParametersRenameFactory.java index 0b5a9c02ce57..95c2a779cc68 100644 --- a/python/src/com/jetbrains/python/refactoring/rename/PyParametersRenameFactory.java +++ b/python/src/com/jetbrains/python/refactoring/rename/PyParametersRenameFactory.java @@ -67,18 +67,15 @@ public class PyParametersRenameFactory implements AutomaticRenamerFactory { public PyParametersRenamer(final PyParameter element, String newName) { PyFunction function = PsiTreeUtil.getParentOfType(element, PyFunction.class); - PyOverridingMethodsSearch.search(function, true).forEach(new Processor() { - @Override - public boolean process(PyFunction pyFunction) { - PyParameter[] parameters = pyFunction.getParameterList().getParameters(); - for (PyParameter parameter : parameters) { - PyNamedParameter named = parameter.getAsNamed(); - if (named != null && Comparing.equal(named.getName(), element.getName())) { - myElements.add(named); - } + PyOverridingMethodsSearch.search(function, true).forEach(pyFunction -> { + PyParameter[] parameters = pyFunction.getParameterList().getParameters(); + for (PyParameter parameter : parameters) { + PyNamedParameter named = parameter.getAsNamed(); + if (named != null && Comparing.equal(named.getName(), element.getName())) { + myElements.add(named); } - return true; } + return true; }); suggestAllNames(element.getName(), newName); } diff --git a/python/src/com/jetbrains/python/refactoring/rename/RenamePyClassProcessor.java b/python/src/com/jetbrains/python/refactoring/rename/RenamePyClassProcessor.java index 0e20885b5751..f261566729f0 100644 --- a/python/src/com/jetbrains/python/refactoring/rename/RenamePyClassProcessor.java +++ b/python/src/com/jetbrains/python/refactoring/rename/RenamePyClassProcessor.java @@ -68,14 +68,11 @@ public class RenamePyClassProcessor extends RenamePyElementProcessor { if (initMethod != null) { final List allRefs = Collections.synchronizedList(new ArrayList()); allRefs.addAll(super.findReferences(element)); - ReferencesSearch.search(initMethod, GlobalSearchScope.projectScope(element.getProject())).forEach(new Processor() { - @Override - public boolean process(PsiReference psiReference) { - if (psiReference.getCanonicalText().equals(((PyClass)element).getName())) { - allRefs.add(psiReference); - } - return true; + ReferencesSearch.search(initMethod, GlobalSearchScope.projectScope(element.getProject())).forEach(psiReference -> { + if (psiReference.getCanonicalText().equals(((PyClass)element).getName())) { + allRefs.add(psiReference); } + return true; }); return allRefs; } diff --git a/python/src/com/jetbrains/python/refactoring/rename/RenamePyFunctionProcessor.java b/python/src/com/jetbrains/python/refactoring/rename/RenamePyFunctionProcessor.java index 026cd3a4a641..882beeef5ec8 100644 --- a/python/src/com/jetbrains/python/refactoring/rename/RenamePyFunctionProcessor.java +++ b/python/src/com/jetbrains/python/refactoring/rename/RenamePyFunctionProcessor.java @@ -110,12 +110,9 @@ public class RenamePyFunctionProcessor extends RenamePyElementProcessor { @Override public void prepareRenaming(PsiElement element, final String newName, final Map allRenames) { PyFunction function = (PyFunction) element; - PyOverridingMethodsSearch.search(function, true).forEach(new Processor() { - @Override - public boolean process(PyFunction pyFunction) { - allRenames.put(pyFunction, newName); - return true; - } + PyOverridingMethodsSearch.search(function, true).forEach(pyFunction -> { + allRenames.put(pyFunction, newName); + return true; }); final PyClass containingClass = function.getContainingClass(); if (containingClass != null) { diff --git a/python/src/com/jetbrains/python/run/PythonTask.java b/python/src/com/jetbrains/python/run/PythonTask.java index 4f9ed28caeba..37769dd89127 100644 --- a/python/src/com/jetbrains/python/run/PythonTask.java +++ b/python/src/com/jetbrains/python/run/PythonTask.java @@ -224,29 +224,21 @@ public class PythonTask { .withFilter(new PythonTracebackFilter(project)) .withConsole(consoleView) .withTitle(myRunTabTitle) - .withRerun(new Runnable() { - @Override - public void run() { - try { - process.destroyProcess(); // Stop process before rerunning it - if (process.waitFor(TIME_TO_WAIT_PROCESS_STOP)) { - PythonTask.this.run(env, consoleView); - } - else { - Messages.showErrorDialog(PyBundle.message("unable.to.stop"), myRunTabTitle); - } + .withRerun(() -> { + try { + process.destroyProcess(); // Stop process before rerunning it + if (process.waitFor(TIME_TO_WAIT_PROCESS_STOP)) { + PythonTask.this.run(env, consoleView); } - catch (ExecutionException e) { - Messages.showErrorDialog(e.getMessage(), myRunTabTitle); + else { + Messages.showErrorDialog(PyBundle.message("unable.to.stop"), myRunTabTitle); } } + catch (ExecutionException e) { + Messages.showErrorDialog(e.getMessage(), myRunTabTitle); + } }) - .withStop(new Runnable() { - @Override - public void run() { - process.destroyProcess(); - } - }, new Computable() { + .withStop(() -> process.destroyProcess(), new Computable() { @Override public Boolean compute() { diff --git a/python/src/com/jetbrains/python/sdk/AbstractCreateVirtualEnvDialog.java b/python/src/com/jetbrains/python/sdk/AbstractCreateVirtualEnvDialog.java index af2542ab6193..da5b3779871e 100644 --- a/python/src/com/jetbrains/python/sdk/AbstractCreateVirtualEnvDialog.java +++ b/python/src/com/jetbrains/python/sdk/AbstractCreateVirtualEnvDialog.java @@ -249,14 +249,11 @@ public abstract class AbstractCreateVirtualEnvDialog extends IdeaDialog { myPath = createEnvironment(basicSdk); } catch (final ExecutionException e) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final PackageManagementService.ErrorDescription description = - PyPackageManagementService.toErrorDescription(Collections.singletonList(e), basicSdk); - if (description != null) { - PackagesNotificationPanel.showError(PyBundle.message("sdk.create.venv.dialog.error.failed.to.create.venv"), description); - } + ApplicationManager.getApplication().invokeLater(() -> { + final PackageManagementService.ErrorDescription description = + PyPackageManagementService.toErrorDescription(Collections.singletonList(e), basicSdk); + if (description != null) { + PackagesNotificationPanel.showError(PyBundle.message("sdk.create.venv.dialog.error.failed.to.create.venv"), description); } }, ModalityState.any()); } @@ -266,17 +263,8 @@ public abstract class AbstractCreateVirtualEnvDialog extends IdeaDialog { @Override public void onSuccess() { if (myPath != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - setupVirtualEnvSdk(myPath, associateWithProject(), callback); - } - }); - } - }); + ApplicationManager.getApplication().invokeLater(() -> DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, + () -> setupVirtualEnvSdk(myPath, associateWithProject(), callback))); } } }; diff --git a/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java b/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java index d943e29d86f0..2aa0e24d685e 100644 --- a/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java +++ b/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java @@ -148,16 +148,13 @@ public class CreateVirtualEnvDialog extends AbstractCreateVirtualEnvDialog { VirtualFile suggestedDir = suggestedPath == null ? null : LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(suggestedPath)); - final NullableConsumer consumer = new NullableConsumer() { - @Override - public void consume(@Nullable Sdk sdk) { - if (sdk == null) return; - if (!allSdks.contains(sdk)) { - allSdks.add(sdk); - sdkService.addSdk(sdk); - } - updateSdkList(allSdks, sdk); + final NullableConsumer consumer = sdk -> { + if (sdk == null) return; + if (!allSdks.contains(sdk)) { + allSdks.add(sdk); + sdkService.addSdk(sdk); } + updateSdkList(allSdks, sdk); }; FileChooser.chooseFiles(descriptor, myProject, suggestedDir, new FileChooser.FileChooserConsumer() { @Override diff --git a/python/src/com/jetbrains/python/sdk/PythonSdkType.java b/python/src/com/jetbrains/python/sdk/PythonSdkType.java index 479572d0229e..864a172c976c 100644 --- a/python/src/com/jetbrains/python/sdk/PythonSdkType.java +++ b/python/src/com/jetbrains/python/sdk/PythonSdkType.java @@ -109,12 +109,7 @@ public final class PythonSdkType extends SdkType { private static final String[] WIN_BINARY_NAMES = new String[]{"jython.bat", "ipy.exe", "pypy.exe", "python.exe"}; private static final Key> SDK_CREATOR_COMPONENT_KEY = Key.create("#com.jetbrains.python.sdk.creatorComponent"); - public static final Predicate REMOTE_SDK_PREDICATE = new Predicate() { - @Override - public boolean test(Sdk sdk) { - return isRemote(sdk); - } - }; + public static final Predicate REMOTE_SDK_PREDICATE = sdk -> isRemote(sdk); public static PythonSdkType getInstance() { return SdkType.findInstance(PythonSdkType.class); @@ -202,10 +197,8 @@ public final class PythonSdkType extends SdkType { } private static TreeSet createVersionSet() { - return new TreeSet(new Comparator() { - public int compare(String o1, String o2) { - return findDigits(o1).compareTo(findDigits(o2)); - } + return new TreeSet((o1, o2) -> { + return findDigits(o1).compareTo(findDigits(o2)); }); } @@ -306,13 +299,10 @@ public final class PythonSdkType extends SdkType { if (pointerInfo == null) return; final Point point = pointerInfo.getLocation(); PythonSdkDetailsStep - .show(project, sdkModel.getSdks(), null, parentComponent, point, new NullableConsumer() { - @Override - public void consume(@Nullable Sdk sdk) { - if (sdk != null) { - sdk.putUserData(SDK_CREATOR_COMPONENT_KEY, new WeakReference(parentComponent)); - sdkCreatedCallback.consume(sdk); - } + .show(project, sdkModel.getSdks(), null, parentComponent, point, sdk -> { + if (sdk != null) { + sdk.putUserData(SDK_CREATOR_COMPONENT_KEY, new WeakReference(parentComponent)); + sdkCreatedCallback.consume(sdk); } }); } diff --git a/python/src/com/jetbrains/python/sdk/PythonSdkUpdater.java b/python/src/com/jetbrains/python/sdk/PythonSdkUpdater.java index 13321b94c6c2..abe2ee703857 100644 --- a/python/src/com/jetbrains/python/sdk/PythonSdkUpdater.java +++ b/python/src/com/jetbrains/python/sdk/PythonSdkUpdater.java @@ -133,67 +133,61 @@ public class PythonSdkUpdater implements StartupActivity { return true; } - application.invokeLater(new Runnable() { - @Override - public void run() { - synchronized (ourLock) { - if (!ourScheduledToRefresh.contains(homePath)) { - return; - } - ourScheduledToRefresh.remove(homePath); + application.invokeLater(() -> { + synchronized (ourLock) { + if (!ourScheduledToRefresh.contains(homePath)) { + return; } - ProgressManager.getInstance().run(new Task.Backgroundable(project, PyBundle.message("sdk.gen.updating.skeletons"), false) { - @Override - public void run(@NotNull ProgressIndicator indicator) { - final Project project = getProject(); - final Sdk sdk = PythonSdkType.findSdkByPath(homePath); - if (sdk != null) { - ourUnderRefresh.put(homePath); + ourScheduledToRefresh.remove(homePath); + } + ProgressManager.getInstance().run(new Task.Backgroundable(project, PyBundle.message("sdk.gen.updating.skeletons"), false) { + @Override + public void run(@NotNull ProgressIndicator indicator) { + final Project project1 = getProject(); + final Sdk sdk12 = PythonSdkType.findSdkByPath(homePath); + if (sdk12 != null) { + ourUnderRefresh.put(homePath); + try { + final String skeletonsPath = getBinarySkeletonsPath(homePath); try { - final String skeletonsPath = getBinarySkeletonsPath(homePath); - try { - if (PythonSdkType.isRemote(sdk) && project == null && ownerComponent == null) { - LOG.error("For refreshing skeletons of remote SDK, either project or owner component must be specified"); - } - LOG.info("Performing background update of skeletons for SDK " + sdk.getHomePath()); - PySkeletonRefresher.refreshSkeletonsOfSdk(project, ownerComponent, skeletonsPath, sdk); - updateRemoteSdkPaths(sdk); - } - catch (InvalidSdkException e) { - if (PythonSdkType.isVagrant(sdk) - || new CredentialsTypeExChecker() { - @Override - protected boolean checkLanguageContribution(PyCredentialsContribution languageContribution) { - return languageContribution.shouldNotifySdkSkeletonFail(); - } - }.check(sdk)) { - PythonSdkType.notifyRemoteSdkSkeletonsFail(e, new Runnable() { - @Override - public void run() { - final Sdk sdk = PythonSdkType.findSdkByPath(homePath); - if (sdk != null) { - update(sdk, null, project, ownerComponent); - } - } - }); - } - else if (!PythonSdkType.isInvalid(sdk)) { - LOG.error(e); - } + if (PythonSdkType.isRemote(sdk12) && project1 == null && ownerComponent == null) { + LOG.error("For refreshing skeletons of remote SDK, either project or owner component must be specified"); } + LOG.info("Performing background update of skeletons for SDK " + sdk12.getHomePath()); + PySkeletonRefresher.refreshSkeletonsOfSdk(project1, ownerComponent, skeletonsPath, sdk12); + updateRemoteSdkPaths(sdk12); } - finally { - try { - ourUnderRefresh.remove(homePath); + catch (InvalidSdkException e) { + if (PythonSdkType.isVagrant(sdk12) + || new CredentialsTypeExChecker() { + @Override + protected boolean checkLanguageContribution(PyCredentialsContribution languageContribution) { + return languageContribution.shouldNotifySdkSkeletonFail(); + } + }.check(sdk12)) { + PythonSdkType.notifyRemoteSdkSkeletonsFail(e, () -> { + final Sdk sdk1 = PythonSdkType.findSdkByPath(homePath); + if (sdk1 != null) { + update(sdk1, null, project1, ownerComponent); + } + }); } - catch (IllegalStateException e) { + else if (!PythonSdkType.isInvalid(sdk12)) { LOG.error(e); } } } + finally { + try { + ourUnderRefresh.remove(homePath); + } + catch (IllegalStateException e) { + LOG.error(e); + } + } } - }); - } + } + }); }, ModalityState.NON_MODAL); return true; } @@ -402,18 +396,15 @@ public class PythonSdkUpdater implements StartupActivity { final SdkModificator modificatorToGetRoots = sdkModificator != null ? sdkModificator : sdk.getSdkModificator(); final List currentSdkPaths = Arrays.asList(modificatorToGetRoots.getRoots(OrderRootType.CLASSES)); if (forceCommit || !Sets.newHashSet(sdkPaths).equals(Sets.newHashSet(currentSdkPaths))) { - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - final Sdk sdk = PythonSdkType.findSdkByPath(homePath); - final SdkModificator modificatorToCommit = sdkModificator != null ? sdkModificator : - sdk != null ? sdk.getSdkModificator() : modificatorToGetRoots; - modificatorToCommit.removeAllRoots(); - for (VirtualFile sdkPath : sdkPaths) { - modificatorToCommit.addRoot(PythonSdkType.getSdkRootVirtualFile(sdkPath), OrderRootType.CLASSES); - } - modificatorToCommit.commitChanges(); + ApplicationManager.getApplication().invokeAndWait(() -> { + final Sdk sdk1 = PythonSdkType.findSdkByPath(homePath); + final SdkModificator modificatorToCommit = sdkModificator != null ? sdkModificator : + sdk1 != null ? sdk1.getSdkModificator() : modificatorToGetRoots; + modificatorToCommit.removeAllRoots(); + for (VirtualFile sdkPath : sdkPaths) { + modificatorToCommit.addRoot(PythonSdkType.getSdkRootVirtualFile(sdkPath), OrderRootType.CLASSES); } + modificatorToCommit.commitChanges(); }, ModalityState.defaultModalityState()); } } diff --git a/python/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java b/python/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java index c9c7d636a1a1..f70dc3b28b52 100644 --- a/python/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java +++ b/python/src/com/jetbrains/python/sdk/skeletons/PySkeletonRefresher.java @@ -243,22 +243,18 @@ public class PySkeletonRefresher { paths.addAll(Arrays.asList(sdk.getRootProvider().getFiles(OrderRootType.CLASSES))); paths.addAll(BuildoutFacet.getExtraPathForAllOpenModules()); - return Joiner.on(File.pathSeparator).join(ContainerUtil.mapNotNull(paths, new Function() { - - @Override - public Object fun(VirtualFile file) { - if (file.isInLocalFileSystem()) { - // We compare canonical files, not strings because "c:/some/folder" equals "c:\\some\\bin\\..\\folder\\" - final File canonicalFile = new File(file.getPath()); - if (canonicalFile.exists() && - !FileUtil.filesEqual(canonicalFile, skeletons) && - !FileUtil.filesEqual(canonicalFile, userSkeletons) && - !FileUtil.filesEqual(canonicalFile, remoteSources)) { - return file.getPath(); - } + return Joiner.on(File.pathSeparator).join(ContainerUtil.mapNotNull(paths, (Function)file -> { + if (file.isInLocalFileSystem()) { + // We compare canonical files, not strings because "c:/some/folder" equals "c:\\some\\bin\\..\\folder\\" + final File canonicalFile = new File(file.getPath()); + if (canonicalFile.exists() && + !FileUtil.filesEqual(canonicalFile, skeletons) && + !FileUtil.filesEqual(canonicalFile, userSkeletons) && + !FileUtil.filesEqual(canonicalFile, remoteSources)) { + return file.getPath(); } - return null; } + return null; })); } @@ -360,11 +356,8 @@ public class PySkeletonRefresher { } if ((builtinsUpdated || PySdkUtil.isRemote(mySdk)) && myProject != null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - DaemonCodeAnalyzer.getInstance(myProject).restart(); - } + ApplicationManager.getApplication().invokeLater(() -> { + DaemonCodeAnalyzer.getInstance(myProject).restart(); }, myProject.getDisposed()); } @@ -737,12 +730,9 @@ public class PySkeletonRefresher { } LOG.info("Skeleton for " + moduleName); - generateSkeleton(moduleName, binaryItem.getPath(), null, new Consumer() { - @Override - public void consume(Boolean generated) { - if (!generated) { - errorList.add(new UpdateResult(moduleName, binaryItem.getPath(), binaryItem.lastModified(), true)); - } + generateSkeleton(moduleName, binaryItem.getPath(), null, generated -> { + if (!generated) { + errorList.add(new UpdateResult(moduleName, binaryItem.getPath(), binaryItem.lastModified(), true)); } }); } diff --git a/python/src/com/jetbrains/python/sdk/skeletons/SkeletonVersionChecker.java b/python/src/com/jetbrains/python/sdk/skeletons/SkeletonVersionChecker.java index f4477dbd4365..27882c276697 100644 --- a/python/src/com/jetbrains/python/sdk/skeletons/SkeletonVersionChecker.java +++ b/python/src/com/jetbrains/python/sdk/skeletons/SkeletonVersionChecker.java @@ -58,19 +58,16 @@ public class SkeletonVersionChecker { } private static TreeMap createTreeMap() { - return new TreeMap(new Comparator() { - @Override - public int compare(QualifiedName left, QualifiedName right) { - Iterator lefts = left.getComponents().iterator(); - Iterator rights = right.getComponents().iterator(); - while (lefts.hasNext() && rights.hasNext()) { - int res = lefts.next().compareTo(rights.next()); - if (res != 0) return res; - } - if (lefts.hasNext()) return 1; - if (rights.hasNext()) return -1; - return 0; // equal + return new TreeMap((left, right) -> { + Iterator lefts = left.getComponents().iterator(); + Iterator rights = right.getComponents().iterator(); + while (lefts.hasNext() && rights.hasNext()) { + int res = lefts.next().compareTo(rights.next()); + if (res != 0) return res; } + if (lefts.hasNext()) return 1; + if (rights.hasNext()) return -1; + return 0; // equal }); } diff --git a/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerDictionaryGenerator.java b/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerDictionaryGenerator.java index c8c091f45c99..d23fdc3d9b33 100644 --- a/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerDictionaryGenerator.java +++ b/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerDictionaryGenerator.java @@ -42,12 +42,9 @@ public class PythonSpellcheckerDictionaryGenerator extends SpellCheckerDictionar protected void processFolder(final HashSet seenNames, PsiManager manager, VirtualFile folder) { if (!myExcludedFolders.contains(folder)) { final String name = folder.getName(); - IdentifierSplitter.getInstance().split(name, TextRange.allOf(name), new Consumer() { - @Override - public void consume(TextRange textRange) { - final String word = textRange.substring(name); - addSeenWord(seenNames, word, Language.ANY); - } + IdentifierSplitter.getInstance().split(name, TextRange.allOf(name), textRange -> { + final String word = textRange.substring(name); + addSeenWord(seenNames, word, Language.ANY); }); } super.processFolder(seenNames, manager, folder); diff --git a/python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.java b/python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.java index 3e3dc7037924..94843e3bc2d6 100644 --- a/python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.java +++ b/python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.java @@ -48,17 +48,14 @@ public class PyPackageUsagesCollector extends AbstractApplicationUsagesCollector for(final Module m: ModuleManager.getInstance(project).getModules()) { final Sdk pythonSdk = PythonSdkType.findPythonSdk(m); if (pythonSdk != null) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - List requirements = PyPackageManager.getInstance(pythonSdk).getRequirements(m); - if (requirements != null) { - Collection packages = new HashSet(PyPIPackageUtil.INSTANCE.getPackageNames()); - for (PyRequirement requirement : requirements) { - String name = requirement.getName(); - if (packages.contains(name)) { - result.add(new UsageDescriptor(name, 1)); - } + ApplicationManager.getApplication().runReadAction(() -> { + List requirements = PyPackageManager.getInstance(pythonSdk).getRequirements(m); + if (requirements != null) { + Collection packages = new HashSet(PyPIPackageUtil.INSTANCE.getPackageNames()); + for (PyRequirement requirement : requirements) { + String name = requirement.getName(); + if (packages.contains(name)) { + result.add(new UsageDescriptor(name, 1)); } } } diff --git a/python/src/com/jetbrains/python/structureView/PyStructureViewElement.java b/python/src/com/jetbrains/python/structureView/PyStructureViewElement.java index 8144f0ee869c..75ec33995509 100644 --- a/python/src/com/jetbrains/python/structureView/PyStructureViewElement.java +++ b/python/src/com/jetbrains/python/structureView/PyStructureViewElement.java @@ -176,13 +176,10 @@ public class PyStructureViewElement implements StructureViewTreeElement { } names.add(name); } - final Comparator comparator = new Comparator() { - @Override - public int compare(PyElement e1, PyElement e2) { - final String n1 = e1.getName(); - final String n2 = e2.getName(); - return (n1 != null && n2 != null) ? n1.compareTo(n2) : 0; - } + final Comparator comparator = (e1, e2) -> { + final String n1 = e1.getName(); + final String n2 = e2.getName(); + return (n1 != null && n2 != null) ? n1.compareTo(n2) : 0; }; Collections.sort(filtered, comparator); children.addAll(filtered); diff --git a/python/src/com/jetbrains/python/validation/Pep8ExternalAnnotator.java b/python/src/com/jetbrains/python/validation/Pep8ExternalAnnotator.java index 71dffe98d14d..52512c853e87 100644 --- a/python/src/com/jetbrains/python/validation/Pep8ExternalAnnotator.java +++ b/python/src/com/jetbrains/python/validation/Pep8ExternalAnnotator.java @@ -412,13 +412,10 @@ public class Pep8ExternalAnnotator extends ExternalAnnotator() { - @Override - public void consume(ModifiableModel model) { - PyPep8Inspection tool = (PyPep8Inspection)model.getUnwrappedTool(PyPep8Inspection.INSPECTION_SHORT_NAME, file); - if (!tool.ignoredErrors.contains(myCode)) { - tool.ignoredErrors.add(myCode); - } + InspectionProjectProfileManager.getInstance(project).getInspectionProfile(file).modifyProfile(model -> { + PyPep8Inspection tool = (PyPep8Inspection)model.getUnwrappedTool(PyPep8Inspection.INSPECTION_SHORT_NAME, file); + if (!tool.ignoredErrors.contains(myCode)) { + tool.ignoredErrors.add(myCode); } }); } diff --git a/python/testSrc/com/intellij/execution/testframework/actions/RerunFailedActionsTestTools.java b/python/testSrc/com/intellij/execution/testframework/actions/RerunFailedActionsTestTools.java index b04488112f23..1d0f231ea1e1 100644 --- a/python/testSrc/com/intellij/execution/testframework/actions/RerunFailedActionsTestTools.java +++ b/python/testSrc/com/intellij/execution/testframework/actions/RerunFailedActionsTestTools.java @@ -38,12 +38,7 @@ public final class RerunFailedActionsTestTools { return null; } final Ref stateRef = new Ref(); - UsefulTestCase.edt(new Runnable() { - @Override - public void run() { - stateRef.set(ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), profile).build()); - } - }); + UsefulTestCase.edt(() -> stateRef.set(ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), profile).build())); return stateRef.get(); } @@ -61,15 +56,12 @@ public final class RerunFailedActionsTestTools { return null; } final Ref stateRef = new Ref(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - try { - stateRef.set(action.getState()); - } - catch (final ExecutionException e) { - throw new IllegalStateException("Error obtaining execution state", e); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + try { + stateRef.set(action.getState()); + } + catch (final ExecutionException e) { + throw new IllegalStateException("Error obtaining execution state", e); } }, ModalityState.NON_MODAL); diff --git a/python/testSrc/com/jetbrains/commandInterface/commandLine/CommandTestTools.java b/python/testSrc/com/jetbrains/commandInterface/commandLine/CommandTestTools.java index a8a01354defa..ecf34b3c7041 100644 --- a/python/testSrc/com/jetbrains/commandInterface/commandLine/CommandTestTools.java +++ b/python/testSrc/com/jetbrains/commandInterface/commandLine/CommandTestTools.java @@ -86,11 +86,8 @@ final class CommandTestTools { * Hack to register file type (not registered for some reason?) */ static void initFileType() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileTypeManager.getInstance().associateExtension(CommandLineFileType.INSTANCE, CommandLineFileType.EXTENSION); - } + ApplicationManager.getApplication().runWriteAction(() -> { + FileTypeManager.getInstance().associateExtension(CommandLineFileType.INSTANCE, CommandLineFileType.EXTENSION); }); } diff --git a/python/testSrc/com/jetbrains/env/ConfigurationBasedProcessRunner.java b/python/testSrc/com/jetbrains/env/ConfigurationBasedProcessRunner.java index 15e5a24be636..df6105ba2c16 100644 --- a/python/testSrc/com/jetbrains/env/ConfigurationBasedProcessRunner.java +++ b/python/testSrc/com/jetbrains/env/ConfigurationBasedProcessRunner.java @@ -104,12 +104,7 @@ public abstract class ConfigurationBasedProcessRunner prepareConsoleAfterProcessEnd(), ModalityState.NON_MODAL); } }; diff --git a/python/testSrc/com/jetbrains/env/ProcessWithConsoleRunner.java b/python/testSrc/com/jetbrains/env/ProcessWithConsoleRunner.java index 6ca093b1eb62..481471e30916 100644 --- a/python/testSrc/com/jetbrains/env/ProcessWithConsoleRunner.java +++ b/python/testSrc/com/jetbrains/env/ProcessWithConsoleRunner.java @@ -76,18 +76,15 @@ public abstract class ProcessWithConsoleRunner implements Disposable { public Pair>, List> getHighlightedStringsInConsole() { final List resultStrings = new ArrayList(); final List> resultRanges = new ArrayList>(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - myConsole.flushDeferredText(); - final Editor editor = myConsole.getEditor(); - for (final RangeHighlighter highlighter : editor.getMarkupModel().getAllHighlighters()) { - if (highlighter instanceof RangeHighlighterEx) { - final int start = ((RangeHighlighterEx)highlighter).getAffectedAreaStartOffset(); - final int end = ((RangeHighlighterEx)highlighter).getAffectedAreaEndOffset(); - resultRanges.add(Pair.create(start, end)); - resultStrings.add(editor.getDocument().getText().substring(start, end)); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + myConsole.flushDeferredText(); + final Editor editor = myConsole.getEditor(); + for (final RangeHighlighter highlighter : editor.getMarkupModel().getAllHighlighters()) { + if (highlighter instanceof RangeHighlighterEx) { + final int start = ((RangeHighlighterEx)highlighter).getAffectedAreaStartOffset(); + final int end = ((RangeHighlighterEx)highlighter).getAffectedAreaEndOffset(); + resultRanges.add(Pair.create(start, end)); + resultStrings.add(editor.getDocument().getText().substring(start, end)); } } }, ModalityState.NON_MODAL); diff --git a/python/testSrc/com/jetbrains/env/PyAbstractTestProcessRunner.java b/python/testSrc/com/jetbrains/env/PyAbstractTestProcessRunner.java index 1e76a783957b..ad8d37a349f2 100644 --- a/python/testSrc/com/jetbrains/env/PyAbstractTestProcessRunner.java +++ b/python/testSrc/com/jetbrains/env/PyAbstractTestProcessRunner.java @@ -65,12 +65,9 @@ public class PyAbstractTestProcessRunner { + // Print output of tests to console (because console may be scrolled) + myProxyManager.getProxy().getAllTests().get(0).printOn(myExecutionConsole.getPrinter()); }, ModalityState.NON_MODAL); } diff --git a/python/testSrc/com/jetbrains/env/PyProcessWithConsoleTestTask.java b/python/testSrc/com/jetbrains/env/PyProcessWithConsoleTestTask.java index 47b575f16709..9c9c30c099c8 100644 --- a/python/testSrc/com/jetbrains/env/PyProcessWithConsoleTestTask.java +++ b/python/testSrc/com/jetbrains/env/PyProcessWithConsoleTestTask.java @@ -108,18 +108,15 @@ public abstract class PyProcessWithConsoleTestTask { + try { + runner.runProcess(sdkHome, getProject(), processListener); + } + catch (final Throwable e) { + final IllegalStateException exception = new IllegalStateException("Exception thrown while running test", e); + failed.set(true); + processFinishedSemaphore.up(); + throw exception; } }, ModalityState.NON_MODAL); diff --git a/python/testSrc/com/jetbrains/env/python/IPythonConsoleTest.java b/python/testSrc/com/jetbrains/env/python/IPythonConsoleTest.java index 686f926218a4..cc926ef52568 100644 --- a/python/testSrc/com/jetbrains/env/python/IPythonConsoleTest.java +++ b/python/testSrc/com/jetbrains/env/python/IPythonConsoleTest.java @@ -44,14 +44,11 @@ public class IPythonConsoleTest extends PyEnvTestCase { public void testing() throws Exception { waitForReady(); addTextToEditor("sys?"); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiFile psi = - PsiDocumentManager.getInstance(getProject()) - .getPsiFile(getConsoleView().getConsoleEditor().getDocument()); - Assert.assertThat("No errors expected", getErrors(psi), Matchers.empty()); - } + ApplicationManager.getApplication().runReadAction(() -> { + PsiFile psi = + PsiDocumentManager.getInstance(getProject()) + .getPsiFile(getConsoleView().getConsoleEditor().getDocument()); + Assert.assertThat("No errors expected", getErrors(psi), Matchers.empty()); }); } }); @@ -78,14 +75,11 @@ public class IPythonConsoleTest extends PyEnvTestCase { public void testing() throws Exception { waitForReady(); addTextToEditor("sys?"); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiFile psi = - PsiDocumentManager.getInstance(getProject()).getPsiFile(getConsoleView().getConsoleEditor().getDocument()); - //TreeUtil.ensureParsed(psi.getNode()); - assertTrue(PsiTreeUtil.hasErrorElements(psi)); - } + ApplicationManager.getApplication().runReadAction(() -> { + PsiFile psi = + PsiDocumentManager.getInstance(getProject()).getPsiFile(getConsoleView().getConsoleEditor().getDocument()); + //TreeUtil.ensureParsed(psi.getNode()); + assertTrue(PsiTreeUtil.hasErrorElements(psi)); }); } diff --git a/python/testSrc/com/jetbrains/env/python/console/PyConsoleTask.java b/python/testSrc/com/jetbrains/env/python/console/PyConsoleTask.java index a467f656cc38..9c08062a4bbb 100644 --- a/python/testSrc/com/jetbrains/env/python/console/PyConsoleTask.java +++ b/python/testSrc/com/jetbrains/env/python/console/PyConsoleTask.java @@ -296,12 +296,9 @@ public class PyConsoleTask extends PyExecutionFixtureTestTask { private int myLen = 0; public void start() { - myThread = new Thread(new Runnable() { - @Override - public void run() { - doJob(); - } - },"py console printer"); + myThread = new Thread(() -> { + doJob(); + }, "py console printer"); myThread.setDaemon(true); myThread.start(); } @@ -388,12 +385,7 @@ public class PyConsoleTask extends PyExecutionFixtureTestTask { } protected void execNoWait(final String command) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myConsoleView.executeCode(command, null); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myConsoleView.executeCode(command, null)); } protected void interrupt() { diff --git a/python/testSrc/com/jetbrains/env/python/debug/PyBaseDebuggerTask.java b/python/testSrc/com/jetbrains/env/python/debug/PyBaseDebuggerTask.java index 43240606aece..cbf159403320 100644 --- a/python/testSrc/com/jetbrains/env/python/debug/PyBaseDebuggerTask.java +++ b/python/testSrc/com/jetbrains/env/python/debug/PyBaseDebuggerTask.java @@ -297,12 +297,7 @@ public abstract class PyBaseDebuggerTask extends PyExecutionFixtureTestTask { final ExecutionResult result = myExecutionResult; if (myExecutionResult != null) { - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - Disposer.dispose(result.getExecutionConsole()); - } - }); + UIUtil.invokeLaterIfNeeded(() -> Disposer.dispose(result.getExecutionConsole())); myExecutionResult = null; } } @@ -359,12 +354,9 @@ public abstract class PyBaseDebuggerTask extends PyExecutionFixtureTestTask { private Thread myThread; public void start() { - myThread = new Thread(new Runnable() { - @Override - public void run() { - doJob(); - } - },"py debugger job"); + myThread = new Thread(() -> { + doJob(); + }, "py debugger job"); myThread.setDaemon(true); myThread.start(); } diff --git a/python/testSrc/com/jetbrains/env/python/dotNet/SkeletonTestTask.java b/python/testSrc/com/jetbrains/env/python/dotNet/SkeletonTestTask.java index a2be8c32fca1..ee5205e39be5 100644 --- a/python/testSrc/com/jetbrains/env/python/dotNet/SkeletonTestTask.java +++ b/python/testSrc/com/jetbrains/env/python/dotNet/SkeletonTestTask.java @@ -106,14 +106,11 @@ class SkeletonTestTask extends PyExecutionFixtureTestTask { assert skeletonFile.delete() : "Failed to delete file " + skeletonFile; } - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - myFixture.copyFileToProject("dotNet/" + mySourceFileToRunGenerationOn, mySourceFileToRunGenerationOn); // File that uses CLR library - myFixture.copyFileToProject("dotNet/PythonLibs.dll", "PythonLibs.dll"); // Library itself - myFixture.copyFileToProject("dotNet/SingleNameSpace.dll", "SingleNameSpace.dll"); // Another library - myFixture.configureByFile(mySourceFileToRunGenerationOn); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + myFixture.copyFileToProject("dotNet/" + mySourceFileToRunGenerationOn, mySourceFileToRunGenerationOn); // File that uses CLR library + myFixture.copyFileToProject("dotNet/PythonLibs.dll", "PythonLibs.dll"); // Library itself + myFixture.copyFileToProject("dotNet/SingleNameSpace.dll", "SingleNameSpace.dll"); // Another library + myFixture.configureByFile(mySourceFileToRunGenerationOn); }, ModalityState.NON_MODAL); myFixture.enableInspections(PyUnresolvedReferencesInspection.class); // This inspection should suggest us to generate stubs diff --git a/python/testSrc/com/jetbrains/env/ut/PyUnitTestTask.java b/python/testSrc/com/jetbrains/env/ut/PyUnitTestTask.java index b6195c09cd55..a651d03e6400 100644 --- a/python/testSrc/com/jetbrains/env/ut/PyUnitTestTask.java +++ b/python/testSrc/com/jetbrains/env/ut/PyUnitTestTask.java @@ -99,17 +99,14 @@ public abstract class PyUnitTestTask extends PyExecutionFixtureTestTask { } private static void deletePycFiles(@NotNull final File directory) { - FileUtil.processFilesRecursively(directory, new Processor() { - @Override - public boolean process(File file) { - if (file.getParentFile().getName().equals(PyNames.PYCACHE) || - FileUtilRt.extensionEquals(file.getName(), "pyc") || - FileUtilRt.extensionEquals(file.getName(), "pyo") || - file.getName().endsWith("$py.class")) { - FileUtil.delete(file); - } - return true; + FileUtil.processFilesRecursively(directory, file -> { + if (file.getParentFile().getName().equals(PyNames.PYCACHE) || + FileUtilRt.extensionEquals(file.getName(), "pyc") || + FileUtilRt.extensionEquals(file.getName(), "pyo") || + file.getName().endsWith("$py.class")) { + FileUtil.delete(file); } + return true; }); } diff --git a/python/testSrc/com/jetbrains/python/Py3CompletionTest.java b/python/testSrc/com/jetbrains/python/Py3CompletionTest.java index e20f0f403768..32f8efe5fb8e 100644 --- a/python/testSrc/com/jetbrains/python/Py3CompletionTest.java +++ b/python/testSrc/com/jetbrains/python/Py3CompletionTest.java @@ -144,12 +144,7 @@ public class Py3CompletionTest extends PyTestCase { // PY-15390 public void testMatMul() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest()); } // PY-11214 @@ -158,21 +153,11 @@ public class Py3CompletionTest extends PyTestCase { } public void testAsync() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest()); } public void testAwait() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest()); } @Override diff --git a/python/testSrc/com/jetbrains/python/Py3QuickFixTest.java b/python/testSrc/com/jetbrains/python/Py3QuickFixTest.java index c00d677c8536..92cb9bfd56ae 100644 --- a/python/testSrc/com/jetbrains/python/Py3QuickFixTest.java +++ b/python/testSrc/com/jetbrains/python/Py3QuickFixTest.java @@ -38,79 +38,50 @@ public class Py3QuickFixTest extends PyTestCase { // PY-13685 public void testReplacePrintEnd() { - runWithLanguageLevel(LanguageLevel.PYTHON34, new Runnable() { - @Override - public void run() { - doInspectionTest(PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON34, + () -> doInspectionTest(PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true)); } // PY-13685 public void testReplacePrintComment() { - runWithLanguageLevel(LanguageLevel.PYTHON34, new Runnable() { - @Override - public void run() { - doInspectionTest(PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON34, + () -> doInspectionTest(PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true)); } // PY-13685 public void testReplaceExecComment() { - runWithLanguageLevel(LanguageLevel.PYTHON34, new Runnable() { - @Override - public void run() { - doInspectionTest(PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON34, + () -> doInspectionTest(PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true)); } // PY-15867 public void testAddCallSuperKeywordOnlyParamInSuperInit() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-15867 public void testAddCallSuperKeywordOnlyParamInInit() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-15867 public void testAddCallSuperSingleStarParamInSuperInit() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-15867 public void testAddCallSuperSingleStarParamInSuperInitAndVarargInInit() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-11561 public void testAddCallSuperTypeAnnotationsPreserved() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-16036, PY-11561 @@ -120,69 +91,49 @@ public class Py3QuickFixTest extends PyTestCase { // PY-15867 public void testAddCallSuperNoRequiredKeywordOnlyParamAfterSingleStarInSuperInit() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-16421 public void testAddCallSuperSingleStarParamPreserved() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-15867 public void testAddCallSuperRequiredKeywordOnlyParamAfterSingleStarInSuperInitIsMerged() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doInspectionTest(PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true)); } // PY-16428 public void testAddParameterNotAvailableInsideAnnotation() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doInspectionTest(PyUnresolvedReferencesInspection.class, - PyBundle.message("QFIX.unresolved.reference.add.param.$0", "unresolved"), false, false); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doInspectionTest(PyUnresolvedReferencesInspection.class, + PyBundle.message("QFIX.unresolved.reference.add.param.$0", "unresolved"), false, false)); } // PY-8991 public void testRemoveUnicodePrefixFromGluedStringNodesWithSlash() { - runWithLanguageLevel(LanguageLevel.PYTHON32, new Runnable() { - public void run() { - myFixture.configureByFile(getTestName(false) + ".py"); - myFixture.checkHighlighting(true, false, false); - final IntentionAction intentionAction = myFixture.findSingleIntention(PyBundle.message("INTN.remove.leading.$0", "U")); - assertNotNull(intentionAction); - myFixture.launchAction(intentionAction); - myFixture.checkResultByFile(getTestName(false) + "_after.py"); - } + runWithLanguageLevel(LanguageLevel.PYTHON32, () -> { + myFixture.configureByFile(getTestName(false) + ".py"); + myFixture.checkHighlighting(true, false, false); + final IntentionAction intentionAction = myFixture.findSingleIntention(PyBundle.message("INTN.remove.leading.$0", "U")); + assertNotNull(intentionAction); + myFixture.launchAction(intentionAction); + myFixture.checkResultByFile(getTestName(false) + "_after.py"); }); } // PY-8990 public void testRemoveUnicodePrefixFromGluedStringNodesInParenthesis() { - runWithLanguageLevel(LanguageLevel.PYTHON32, new Runnable() { - public void run() { - myFixture.configureByFile(getTestName(false) + ".py"); - myFixture.checkHighlighting(true, false, false); - final IntentionAction intentionAction = myFixture.findSingleIntention(PyBundle.message("INTN.remove.leading.$0", "U")); - assertNotNull(intentionAction); - myFixture.launchAction(intentionAction); - myFixture.checkResultByFile(getTestName(false) + "_after.py"); - } + runWithLanguageLevel(LanguageLevel.PYTHON32, () -> { + myFixture.configureByFile(getTestName(false) + ".py"); + myFixture.checkHighlighting(true, false, false); + final IntentionAction intentionAction = myFixture.findSingleIntention(PyBundle.message("INTN.remove.leading.$0", "U")); + assertNotNull(intentionAction); + myFixture.launchAction(intentionAction); + myFixture.checkResultByFile(getTestName(false) + "_after.py"); }); } diff --git a/python/testSrc/com/jetbrains/python/Py3TypeTest.java b/python/testSrc/com/jetbrains/python/Py3TypeTest.java index a70fead0608a..820f660bec71 100644 --- a/python/testSrc/com/jetbrains/python/Py3TypeTest.java +++ b/python/testSrc/com/jetbrains/python/Py3TypeTest.java @@ -38,161 +38,111 @@ public class Py3TypeTest extends PyTestCase { // PY-6702 public void testYieldFromType() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doTest("Union[str, int, float]", - "def subgen():\n" + - " for i in [1, 2, 3]:\n" + - " yield i\n" + - "\n" + - "def gen():\n" + - " yield 'foo'\n" + - " yield from subgen()\n" + - " yield 3.14\n" + - "\n" + - "for expr in gen():\n" + - " pass\n"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doTest("Union[str, int, float]", + "def subgen():\n" + + " for i in [1, 2, 3]:\n" + + " yield i\n" + + "\n" + + "def gen():\n" + + " yield 'foo'\n" + + " yield from subgen()\n" + + " yield 3.14\n" + + "\n" + + "for expr in gen():\n" + + " pass\n")); } public void testAwaitAwaitable() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest("int", - "class C:\n" + - " def __await__(self):\n" + - " yield 'foo'\n" + - " return 0\n" + - "\n" + - "async def foo():\n" + - " c = C()\n" + - " expr = await c\n"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest("int", + "class C:\n" + + " def __await__(self):\n" + + " yield 'foo'\n" + + " return 0\n" + + "\n" + + "async def foo():\n" + + " c = C()\n" + + " expr = await c\n")); } public void testAsyncDefReturnType() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest("__coroutine[int]", - "async def foo(x):\n" + - " await x\n" + - " return 0\n" + - "\n" + - "def bar(y):\n" + - " expr = foo(y)\n"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest("__coroutine[int]", + "async def foo(x):\n" + + " await x\n" + + " return 0\n" + + "\n" + + "def bar(y):\n" + + " expr = foo(y)\n")); } public void testAwaitCoroutine() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest("int", - "async def foo(x):\n" + - " await x\n" + - " return 0\n" + - "\n" + - "async def bar(y):\n" + - " expr = await foo(y)\n"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest("int", + "async def foo(x):\n" + + " await x\n" + + " return 0\n" + + "\n" + + "async def bar(y):\n" + + " expr = await foo(y)\n")); } // Not in PEP 484 as for now, see https://github.com/ambv/typehinting/issues/119 public void testCoroutineReturnTypeAnnotation() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - doTest("int", - "async def foo() -> int: ...\n" + - "\n" + - "async def bar():\n" + - " expr = await foo()\n"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doTest("int", + "async def foo() -> int: ...\n" + + "\n" + + "async def bar():\n" + + " expr = await foo()\n")); } // PY-16987 public void testNoTypeInGoogleDocstringParamAnnotation() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTest("int", "def f(x: int):\n" + - " \"\"\"\n" + - " Args:\n" + - " x: foo\n" + - " \"\"\" \n" + - " expr = x"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTest("int", "def f(x: int):\n" + + " \"\"\"\n" + + " Args:\n" + + " x: foo\n" + + " \"\"\" \n" + + " expr = x")); } // PY-16987 public void testUnfilledTypeInGoogleDocstringParamAnnotation() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTest("int", "def f(x: int):\n" + - " \"\"\"\n" + - " Args:\n" + - " x (): foo\n" + - " \"\"\" \n" + - " expr = x"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTest("int", "def f(x: int):\n" + + " \"\"\"\n" + + " Args:\n" + + " x (): foo\n" + + " \"\"\" \n" + + " expr = x")); } // PY-16987 public void testNoTypeInNumpyDocstringParamAnnotation() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTest("int", "def f(x: int):\n" + - " \"\"\"\n" + - " Parameters\n" + - " ----------\n" + - " x\n" + - " foo\n" + - " \"\"\"\n" + - " expr = x"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTest("int", "def f(x: int):\n" + + " \"\"\"\n" + + " Parameters\n" + + " ----------\n" + + " x\n" + + " foo\n" + + " \"\"\"\n" + + " expr = x")); } // PY-17010 public void testAnnotatedReturnTypePrecedesDocstring() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTest("int", "def func() -> int:\n" + - " \"\"\"\n" + - " Returns:\n" + - " str\n" + - " \"\"\"\n" + - "expr = func()"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTest("int", "def func() -> int:\n" + + " \"\"\"\n" + + " Returns:\n" + + " str\n" + + " \"\"\"\n" + + "expr = func()")); } // PY-17010 public void testAnnotatedParamTypePrecedesDocstring() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTest("int", "def func(x: int):\n" + - " \"\"\"\n" + - " Args:\n" + - " x (str):\n" + - " \"\"\"\n" + - " expr = x"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTest("int", "def func(x: int):\n" + + " \"\"\"\n" + + " Args:\n" + + " x (str):\n" + + " \"\"\"\n" + + " expr = x")); } public void testOpenDefault() { diff --git a/python/testSrc/com/jetbrains/python/PyAddImportTest.java b/python/testSrc/com/jetbrains/python/PyAddImportTest.java index 587bb3c580c1..7df6e801626f 100644 --- a/python/testSrc/com/jetbrains/python/PyAddImportTest.java +++ b/python/testSrc/com/jetbrains/python/PyAddImportTest.java @@ -114,33 +114,24 @@ public class PyAddImportTest extends PyTestCase { private void doAddOrUpdateFromImport(final String path, final String name, final ImportPriority priority) { myFixture.configureByFile(getTestName(true) + ".py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - AddImportHelper.addOrUpdateFromImportStatement(myFixture.getFile(), path, name, null, priority, null); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + AddImportHelper.addOrUpdateFromImportStatement(myFixture.getFile(), path, name, null, priority, null); }); myFixture.checkResultByFile(getTestName(true) + ".after.py"); } private void doAddFromImport(final String path, final String name, final ImportPriority priority) { myFixture.configureByFile(getTestName(true) + ".py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - AddImportHelper.addFromImportStatement(myFixture.getFile(), path, name, null, priority, null); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + AddImportHelper.addFromImportStatement(myFixture.getFile(), path, name, null, priority, null); }); myFixture.checkResultByFile(getTestName(true) + ".after.py"); } private void doAddImport(final String name, final ImportPriority priority) { myFixture.configureByFile(getTestName(true) + ".py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - AddImportHelper.addImportStatement(myFixture.getFile(), name, null, priority, null); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + AddImportHelper.addImportStatement(myFixture.getFile(), name, null, priority, null); }); myFixture.checkResultByFile(getTestName(true) + ".after.py"); } @@ -149,11 +140,8 @@ public class PyAddImportTest extends PyTestCase { final String testName = getTestName(true); myFixture.copyDirectoryToProject(testName, ""); myFixture.configureByFile("main.py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - AddImportHelper.addImportStatement(myFixture.getFile(), name, null, priority, null); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + AddImportHelper.addImportStatement(myFixture.getFile(), name, null, priority, null); }); myFixture.checkResultByFile(testName + "/main.after.py"); } @@ -166,16 +154,13 @@ public class PyAddImportTest extends PyTestCase { */ private void doAddLocalImport(@NotNull final String name, @Nullable final String qualifier) { myFixture.configureByFile(getTestName(true) + ".py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - final PsiReference reference = PyResolveTestCase.findReferenceByMarker(myFixture.getFile()); - if (qualifier != null) { - AddImportHelper.addLocalFromImportStatement(reference.getElement(), qualifier, name); - } - else { - AddImportHelper.addLocalImportStatement(reference.getElement(), name); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + final PsiReference reference = PyResolveTestCase.findReferenceByMarker(myFixture.getFile()); + if (qualifier != null) { + AddImportHelper.addLocalFromImportStatement(reference.getElement(), qualifier, name); + } + else { + AddImportHelper.addLocalImportStatement(reference.getElement(), name); } }); myFixture.checkResultByFile(getTestName(true) + ".after.py"); diff --git a/python/testSrc/com/jetbrains/python/PyEditingTest.java b/python/testSrc/com/jetbrains/python/PyEditingTest.java index b4747d18e47e..1c177ba67752 100644 --- a/python/testSrc/com/jetbrains/python/PyEditingTest.java +++ b/python/testSrc/com/jetbrains/python/PyEditingTest.java @@ -124,12 +124,9 @@ public class PyEditingTest extends PyTestCase { public void testUncommentWithSpace() throws Exception { // PY-980 myFixture.configureByFile("/editing/uncommentWithSpace.before.py"); myFixture.getEditor().getCaretModel().moveToLogicalPosition(new LogicalPosition(0, 1)); - CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() { - @Override - public void run() { - CommentByLineCommentAction action = new CommentByLineCommentAction(); - action.actionPerformed(AnActionEvent.createFromAnAction(action, null, "", DataManager.getInstance().getDataContext())); - } + CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> { + CommentByLineCommentAction action = new CommentByLineCommentAction(); + action.actionPerformed(AnActionEvent.createFromAnAction(action, null, "", DataManager.getInstance().getDataContext())); }, "", null); myFixture.checkResultByFile("/editing/uncommentWithSpace.after.py", true); } @@ -210,14 +207,10 @@ public class PyEditingTest extends PyTestCase { } public void testEnterStubInDocstring() { // CR-PY-144 - runWithDocStringFormat(DocStringFormat.PLAIN, new Runnable() { - public void run() { - doTestEnter("def foo():\n \"\"\"", "def foo():\n" + - " \"\"\"\n" + - " \n" + - " \"\"\""); - } - }); + runWithDocStringFormat(DocStringFormat.PLAIN, () -> doTestEnter("def foo():\n \"\"\"", "def foo():\n" + + " \"\"\"\n" + + " \n" + + " \"\"\"")); } // PY-18486 @@ -432,42 +425,29 @@ public class PyEditingTest extends PyTestCase { // PY-15469 public void testEnterBeforeArrowInFunction() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doTestEnter("def func() -> int:\n" + - " pass", - "def func() \\\n" + - " -> int:\n" + - " pass"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTestEnter("def func() -> int:\n" + + " pass", + "def func() \\\n" + + " -> int:\n" + + " pass")); } // PY-15469 public void testEnterAfterArrowInFunction() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doTestEnter("def func() -> int:\n" + - " pass", - "def func() ->\\\n" + - " int:\n" + - " pass"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTestEnter("def func() -> int:\n" + + " pass", + "def func() ->\\\n" + + " int:\n" + + " pass")); } // PY-15469 public void testEnterDoesNotInsertSlashInsideArrow() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTestEnter("def func() -> int:\n" + - " pass", - "def func() -\n" + - "> int:\n" + - " pass"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTestEnter("def func() -> int:\n" + + " pass", + "def func() -\n" + + "> int:\n" + + " pass")); } private void doTestEnter(String before, final String after) { @@ -505,33 +485,22 @@ public class PyEditingTest extends PyTestCase { } private void doDocStringTypingTest(final String text, @NotNull DocStringFormat format) { - runWithDocStringFormat(format, new Runnable() { - @Override - public void run() { - doTypingTest(text); - } - }); + runWithDocStringFormat(format, () -> doTypingTest(text)); } private void doTyping(final char character) { final int offset = myFixture.getEditor().getCaretModel().getOffset(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myFixture.getEditor().getCaretModel().moveToOffset(offset); - myFixture.type(character); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myFixture.getEditor().getCaretModel().moveToOffset(offset); + myFixture.type(character); }); } private void doTyping(final String text) { final int offset = myFixture.getEditor().getCaretModel().getOffset(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myFixture.getEditor().getCaretModel().moveToOffset(offset); - myFixture.type(text); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myFixture.getEditor().getCaretModel().moveToOffset(offset); + myFixture.type(text); }); } diff --git a/python/testSrc/com/jetbrains/python/PyEmacsTabTest.java b/python/testSrc/com/jetbrains/python/PyEmacsTabTest.java index 7087bb2f1e5e..dea3957fa40a 100644 --- a/python/testSrc/com/jetbrains/python/PyEmacsTabTest.java +++ b/python/testSrc/com/jetbrains/python/PyEmacsTabTest.java @@ -319,12 +319,7 @@ public class PyEmacsTabTest extends PyTestCase { private void doTest(String before, String after) { final String fileName = getTestName(false); myFixture.configureByText(fileName + ".py", before); - CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() { - @Override - public void run() { - myFixture.testAction(new EmacsStyleIndentAction()); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> myFixture.testAction(new EmacsStyleIndentAction()), "", null); myFixture.checkResult(after); } diff --git a/python/testSrc/com/jetbrains/python/PyFillParagraphTest.java b/python/testSrc/com/jetbrains/python/PyFillParagraphTest.java index ec4dfcade287..36e32180176c 100644 --- a/python/testSrc/com/jetbrains/python/PyFillParagraphTest.java +++ b/python/testSrc/com/jetbrains/python/PyFillParagraphTest.java @@ -78,12 +78,9 @@ public class PyFillParagraphTest extends PyTestCase { try { String baseName = "/fillParagraph/" + getTestName(true); myFixture.configureByFile(baseName + ".py"); - CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() { - @Override - public void run() { - FillParagraphAction action = new FillParagraphAction(); - action.actionPerformed(AnActionEvent.createFromAnAction(action, null, "", DataManager.getInstance().getDataContext())); - } + CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> { + FillParagraphAction action = new FillParagraphAction(); + action.actionPerformed(AnActionEvent.createFromAnAction(action, null, "", DataManager.getInstance().getDataContext())); }, "", null); myFixture.checkResultByFile(baseName + "_after.py", true); } diff --git a/python/testSrc/com/jetbrains/python/PyFindUsagesTest.java b/python/testSrc/com/jetbrains/python/PyFindUsagesTest.java index 102b29cd1c3b..9cd48c2342a2 100644 --- a/python/testSrc/com/jetbrains/python/PyFindUsagesTest.java +++ b/python/testSrc/com/jetbrains/python/PyFindUsagesTest.java @@ -95,12 +95,8 @@ public class PyFindUsagesTest extends PyTestCase { private void assertUsages(Collection usages, String... usageTexts) { assertEquals(usageTexts.length, usages.size()); List sortedUsages = new ArrayList(usages); - Collections.sort(sortedUsages, new Comparator() { - @Override - public int compare(UsageInfo o1, UsageInfo o2) { - return o1.getElement().getTextRange().getStartOffset() - o2.getElement().getTextRange().getStartOffset(); - } - }); + Collections.sort(sortedUsages, + (o1, o2) -> o1.getElement().getTextRange().getStartOffset() - o2.getElement().getTextRange().getStartOffset()); for (int i = 0; i < usageTexts.length; i++) { assertSameUsage(usageTexts[i], sortedUsages.get(i)); } diff --git a/python/testSrc/com/jetbrains/python/PyFormatterTest.java b/python/testSrc/com/jetbrains/python/PyFormatterTest.java index cfa037e098a5..7e83af7d5e33 100644 --- a/python/testSrc/com/jetbrains/python/PyFormatterTest.java +++ b/python/testSrc/com/jetbrains/python/PyFormatterTest.java @@ -426,17 +426,14 @@ public class PyFormatterTest extends PyTestCase { private void doTest(final boolean reformatText) { myFixture.configureByFile("formatter/" + getTestName(true) + ".py"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject()); - PsiFile file = myFixture.getFile(); - if (reformatText) { - codeStyleManager.reformatText(file, 0, file.getTextLength()); - } - else { - codeStyleManager.reformat(file); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject()); + PsiFile file = myFixture.getFile(); + if (reformatText) { + codeStyleManager.reformatText(file, 0, file.getTextLength()); + } + else { + codeStyleManager.reformat(file); } }); myFixture.checkResultByFile("formatter/" + getTestName(true) + "_after.py"); @@ -458,11 +455,8 @@ public class PyFormatterTest extends PyTestCase { getCommonCodeStyleSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS = true; final String testName = "formatter/" + getTestName(true); myFixture.configureByFile(testName + ".py"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myFixture.type("\n("); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myFixture.type("\n("); }); myFixture.checkResultByFile(testName + "_after.py"); } @@ -537,16 +531,13 @@ public class PyFormatterTest extends PyTestCase { */ public void testReformatOfSingleElementPossible() { myFixture.configureByFile("formatter/" + getTestName(true) + ".py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); - assertNotNull(elementAtCaret); - final PyStatement statement = PsiTreeUtil.getParentOfType(elementAtCaret, PyStatement.class, false); - assertNotNull(statement); - final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject()); - codeStyleManager.reformat(statement); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); + assertNotNull(elementAtCaret); + final PyStatement statement = PsiTreeUtil.getParentOfType(elementAtCaret, PyStatement.class, false); + assertNotNull(statement); + final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject()); + codeStyleManager.reformat(statement); }); myFixture.checkResultByFile("formatter/" + getTestName(true) + "_after.py"); } diff --git a/python/testSrc/com/jetbrains/python/PyMultiFileResolveTest.java b/python/testSrc/com/jetbrains/python/PyMultiFileResolveTest.java index cc0a62fc64f1..c0294660b7ff 100644 --- a/python/testSrc/com/jetbrains/python/PyMultiFileResolveTest.java +++ b/python/testSrc/com/jetbrains/python/PyMultiFileResolveTest.java @@ -387,12 +387,7 @@ public class PyMultiFileResolveTest extends PyMultiFileResolveTestCase { // PY-7378 public void testModuleInDeeplyNestedNamespacePackage() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - assertResolvesTo(PyFile.class, "m1.py"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> assertResolvesTo(PyFile.class, "m1.py")); } public void testKeywordArgument() { diff --git a/python/testSrc/com/jetbrains/python/PyOverrideTest.java b/python/testSrc/com/jetbrains/python/PyOverrideTest.java index f08155870735..84b59c3a1aef 100644 --- a/python/testSrc/com/jetbrains/python/PyOverrideTest.java +++ b/python/testSrc/com/jetbrains/python/PyOverrideTest.java @@ -41,12 +41,7 @@ public class PyOverrideTest extends PyTestCase { } private void doTest3k() { - runWithLanguageLevel(LanguageLevel.PYTHON32, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON32, () -> doTest()); } private PyClass getTopLevelClass(int index) { diff --git a/python/testSrc/com/jetbrains/python/PyQuickFixTest.java b/python/testSrc/com/jetbrains/python/PyQuickFixTest.java index 96deaf719141..1be6df897014 100644 --- a/python/testSrc/com/jetbrains/python/PyQuickFixTest.java +++ b/python/testSrc/com/jetbrains/python/PyQuickFixTest.java @@ -296,12 +296,7 @@ public class PyQuickFixTest extends PyTestCase { // PY-2083 public void testUnresolvedWith() { - runWithLanguageLevel(LanguageLevel.PYTHON25, new Runnable() { - @Override - public void run() { - doInspectionTest(PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference.add.future"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON25, () -> doInspectionTest(PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference.add.future"), true, true)); } // PY-2092 @@ -434,12 +429,7 @@ public class PyQuickFixTest extends PyTestCase { // PY-3120 public void testSetFunctionToLiteral() { - runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() { - @Override - public void run() { - doInspectionTest(PySetFunctionToLiteralInspection.class, PyBundle.message("QFIX.replace.function.set.with.literal"), true, true); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON27, () -> doInspectionTest(PySetFunctionToLiteralInspection.class, PyBundle.message("QFIX.replace.function.set.with.literal"), true, true)); } public void testDictComprehensionToCall() { @@ -449,119 +439,73 @@ public class PyQuickFixTest extends PyTestCase { // PY-3394 public void testDocstringParams() { getIndentOptions().INDENT_SIZE = 2; - runWithDocStringFormat(DocStringFormat.EPYTEXT, new Runnable() { - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "b"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.EPYTEXT, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "b"), true, true)); } public void testDocstringParams1() { getIndentOptions().INDENT_SIZE = 2; - runWithDocStringFormat(DocStringFormat.EPYTEXT, new Runnable() { - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.EPYTEXT, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true)); } // PY-4964 public void testDocstringParams2() { - runWithDocStringFormat(DocStringFormat.EPYTEXT, new Runnable() { - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "ham"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.EPYTEXT, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "ham"), true, true)); } // PY-9795 public void testGoogleDocStringAddParam() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "b"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "b"), true, true)); } // PY-9795 public void testGoogleDocStringRemoveParam() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true)); } // PY-9795 public void testGoogleDocStringRemoveParamWithSection() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true)); } // PY-16761 public void testGoogleDocStringRemovePositionalVararg() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "args"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "args"), true, true)); } // PY-16761 public void testGoogleDocStringRemoveKeywordVararg() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "kwargs"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "kwargs"), true, true)); } // PY-16908 public void testNumpyDocStringRemoveFirstOfCombinedParams() { - runWithDocStringFormat(DocStringFormat.NUMPY, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "x"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.NUMPY, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "x"), true, true)); } // PY-16908 public void testNumpyDocStringRemoveMidOfCombinedParams() { - runWithDocStringFormat(DocStringFormat.NUMPY, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "y"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.NUMPY, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "y"), true, true)); } // PY-16908 public void testNumpyDocStringRemoveLastOfCombinedParams() { - runWithDocStringFormat(DocStringFormat.NUMPY, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "z"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.NUMPY, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "z"), true, true)); } // PY-16908 public void testNumpyDocStringRemoveCombinedVarargParam() { - runWithDocStringFormat(DocStringFormat.NUMPY, new Runnable() { - @Override - public void run() { - doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "args"), true, true); - } - }); + runWithDocStringFormat(DocStringFormat.NUMPY, + () -> doInspectionTest(PyIncorrectDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "args"), true, true)); } public void testUnnecessaryBackslash() { diff --git a/python/testSrc/com/jetbrains/python/PyResolveTest.java b/python/testSrc/com/jetbrains/python/PyResolveTest.java index f27f7e4dbf88..0ba634018415 100644 --- a/python/testSrc/com/jetbrains/python/PyResolveTest.java +++ b/python/testSrc/com/jetbrains/python/PyResolveTest.java @@ -512,30 +512,17 @@ public class PyResolveTest extends PyResolveTestCase { // PY-9795 public void testGoogleDocstringParamType() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - public void run() { - assertResolvesTo(PyClass.class, "datetime"); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> assertResolvesTo(PyClass.class, "datetime")); } // PY-9795 public void testGoogleDocstringReturnType() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - public void run() { - assertResolvesTo(PyClass.class, "MyClass"); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> assertResolvesTo(PyClass.class, "MyClass")); } // PY-16906 public void testGoogleDocstringModuleAttribute() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - assertResolvesTo(PyTargetExpression.class, "module_level_variable1"); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> assertResolvesTo(PyTargetExpression.class, "module_level_variable1")); } // PY-7541 diff --git a/python/testSrc/com/jetbrains/python/PyStructureViewTest.java b/python/testSrc/com/jetbrains/python/PyStructureViewTest.java index b1ed6037412c..d30bba454b52 100644 --- a/python/testSrc/com/jetbrains/python/PyStructureViewTest.java +++ b/python/testSrc/com/jetbrains/python/PyStructureViewTest.java @@ -97,12 +97,9 @@ public class PyStructureViewTest extends PyTestCase { } private void doTest(final String expected, final boolean inherited) { - myFixture.testStructureView(new Consumer() { - @Override - public void consume(StructureViewComponent component) { - component.setActionActive("SHOW_INHERITED", !inherited); - assertTreeEqual(component.getTree(), expected); - } + myFixture.testStructureView(component -> { + component.setActionActive("SHOW_INHERITED", !inherited); + assertTreeEqual(component.getTree(), expected); }); } } diff --git a/python/testSrc/com/jetbrains/python/PythonCompletionTest.java b/python/testSrc/com/jetbrains/python/PythonCompletionTest.java index 7a86eea87a4a..643c91bc3051 100644 --- a/python/testSrc/com/jetbrains/python/PythonCompletionTest.java +++ b/python/testSrc/com/jetbrains/python/PythonCompletionTest.java @@ -416,117 +416,81 @@ public class PythonCompletionTest extends PyTestCase { // PY-16877 public void testSectionNamesInGoogleDocstring() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertContainsElements(variants, "Args", "Keyword Args", "Returns"); - assertDoesntContain(variants, "Parameters", "Return", "Yield"); - } + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertContainsElements(variants, "Args", "Keyword Args", "Returns"); + assertDoesntContain(variants, "Parameters", "Return", "Yield"); }); } // PY-17023 public void testSectionNamesInNumpyDocstrings() { - runWithDocStringFormat(DocStringFormat.NUMPY, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertContainsElements(variants, "Parameters", "Other Parameters", "Returns"); - assertDoesntContain(variants, "Args", "Return", "Yield"); - } + runWithDocStringFormat(DocStringFormat.NUMPY, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertContainsElements(variants, "Parameters", "Other Parameters", "Returns"); + assertDoesntContain(variants, "Args", "Return", "Yield"); }); } // PY-16991 public void testSecondSectionNameInGoogleDocstring() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> doTest()); } // PY-16877 public void testTwoWordsSectionNameInGoogleDocstring() throws Exception { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> doTest()); } // PY-16870 public void testParamNameInGoogleDocstring() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertSameElements(variants, "param1", "param2"); - } + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertSameElements(variants, "param1", "param2"); }); } // PY-16870 public void testOverrideParamNameInGoogleDocstring() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertSameElements(variants, "param2"); - } + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertSameElements(variants, "param2"); }); } // PY-16870 public void testOverrideParamNameInRestDocstring() { - runWithDocStringFormat(DocStringFormat.REST, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertSameElements(variants, "param2"); - } + runWithDocStringFormat(DocStringFormat.REST, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertSameElements(variants, "param2"); }); } // PY-16870, PY-16972 public void testClassNameInDocstring() { - runWithDocStringFormat(DocStringFormat.EPYTEXT, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithDocStringFormat(DocStringFormat.EPYTEXT, () -> doTest()); } // PY-17002 public void testParamTypeInGoogleDocstringWithoutClosingParenthesis() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertSameElements(variants, "str", "basestring"); - } + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertSameElements(variants, "str", "basestring"); }); } // PY-17635 public void testParamNameInTypeDeclarationInRestDocstring() { - runWithDocStringFormat(DocStringFormat.REST, new Runnable() { - @Override - public void run() { - final List variants = doTestByFile(); - assertNotNull(variants); - assertContainsElements(variants, "foo"); - } + runWithDocStringFormat(DocStringFormat.REST, () -> { + final List variants = doTestByFile(); + assertNotNull(variants); + assertContainsElements(variants, "foo"); }); } @@ -635,15 +599,12 @@ public class PythonCompletionTest extends PyTestCase { } public void testRelativeImportExcludeToplevel() { // PY-6304 - runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() { - @Override - public void run() { - myFixture.copyDirectoryToProject("relativeImportExcludeToplevel", ""); - myFixture.configureByFile("pack/subpack/modX.py"); - myFixture.completeBasic(); - assertNull(myFixture.getLookupElementStrings()); - myFixture.checkResult("from ...subpack import"); - } + runWithLanguageLevel(LanguageLevel.PYTHON27, () -> { + myFixture.copyDirectoryToProject("relativeImportExcludeToplevel", ""); + myFixture.configureByFile("pack/subpack/modX.py"); + myFixture.completeBasic(); + assertNull(myFixture.getLookupElementStrings()); + myFixture.checkResult("from ...subpack import"); }); } @@ -753,18 +714,15 @@ public class PythonCompletionTest extends PyTestCase { // PY-4073 public void testFunctionSpecialAttributes() { - runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() { - @Override - public void run() { - List suggested = doTestByText("def func(): pass; func.func_"); - assertNotNull(suggested); - assertContainsElements(suggested, PyNames.LEGACY_FUNCTION_SPECIAL_ATTRIBUTES); + runWithLanguageLevel(LanguageLevel.PYTHON27, () -> { + List suggested = doTestByText("def func(): pass; func.func_"); + assertNotNull(suggested); + assertContainsElements(suggested, PyNames.LEGACY_FUNCTION_SPECIAL_ATTRIBUTES); - suggested = doTestByText("def func(): pass; func.__"); - assertNotNull(suggested); - assertContainsElements(suggested, PyNames.FUNCTION_SPECIAL_ATTRIBUTES); - assertDoesntContain(suggested, PyNames.PY3_ONLY_FUNCTION_SPECIAL_ATTRIBUTES); - } + suggested = doTestByText("def func(): pass; func.__"); + assertNotNull(suggested); + assertContainsElements(suggested, PyNames.FUNCTION_SPECIAL_ATTRIBUTES); + assertDoesntContain(suggested, PyNames.PY3_ONLY_FUNCTION_SPECIAL_ATTRIBUTES); }); } @@ -794,18 +752,8 @@ public class PythonCompletionTest extends PyTestCase { // PY-9342 public void testUnboundMethodSpecialAttributes() { - runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() { - @Override - public void run() { - assertUnderscoredMethodSpecialAttributesSuggested(); - } - }); - runWithLanguageLevel(LanguageLevel.PYTHON32, new Runnable() { - @Override - public void run() { - assertUnderscoredFunctionAttributesSuggested(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON27, () -> assertUnderscoredMethodSpecialAttributesSuggested()); + runWithLanguageLevel(LanguageLevel.PYTHON32, () -> assertUnderscoredFunctionAttributesSuggested()); } // PY-9342 diff --git a/python/testSrc/com/jetbrains/python/PythonInspectionsTest.java b/python/testSrc/com/jetbrains/python/PythonInspectionsTest.java index 3cc930d23f9e..bc70a252c58d 100644 --- a/python/testSrc/com/jetbrains/python/PythonInspectionsTest.java +++ b/python/testSrc/com/jetbrains/python/PythonInspectionsTest.java @@ -152,20 +152,12 @@ public class PythonInspectionsTest extends PyTestCase { //PY-3373 public void testPyDocstringParametersInspection() { - runWithDocStringFormat(DocStringFormat.EPYTEXT, new Runnable() { - public void run() { - doHighlightingTest(PyIncorrectDocstringInspection.class, LanguageLevel.PYTHON33); - } - }); + runWithDocStringFormat(DocStringFormat.EPYTEXT, () -> doHighlightingTest(PyIncorrectDocstringInspection.class, LanguageLevel.PYTHON33)); } // PY-9795 public void testGoogleDocstringParametersInspection() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - public void run() { - doHighlightingTest(PyIncorrectDocstringInspection.class, LanguageLevel.PYTHON33); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> doHighlightingTest(PyIncorrectDocstringInspection.class, LanguageLevel.PYTHON33)); } public void testPySimplifyBooleanCheckInspection() { diff --git a/python/testSrc/com/jetbrains/python/fixtures/PyMultiFileResolveTestCase.java b/python/testSrc/com/jetbrains/python/fixtures/PyMultiFileResolveTestCase.java index 76d76c439c61..f0b41b38afba 100644 --- a/python/testSrc/com/jetbrains/python/fixtures/PyMultiFileResolveTestCase.java +++ b/python/testSrc/com/jetbrains/python/fixtures/PyMultiFileResolveTestCase.java @@ -94,11 +94,8 @@ public abstract class PyMultiFileResolveTestCase extends PyResolveTestCase { final PsiFile psiFile = prepareFile(); final PsiReference ref = PyResolveTestCase.findReferenceByMarker(psiFile); if (ref instanceof PsiPolyVariantReference) { - return ContainerUtil.map(((PsiPolyVariantReference)ref).multiResolve(false), new Function() { - @Override - public PsiElement fun(ResolveResult result) { - return result.getElement(); - } + return ContainerUtil.map(((PsiPolyVariantReference)ref).multiResolve(false), result -> { + return result.getElement(); }); } return Collections.singletonList(ref.resolve()); diff --git a/python/testSrc/com/jetbrains/python/fixtures/PyTestCase.java b/python/testSrc/com/jetbrains/python/fixtures/PyTestCase.java index f9381c9fc09c..cc70fbf9c954 100644 --- a/python/testSrc/com/jetbrains/python/fixtures/PyTestCase.java +++ b/python/testSrc/com/jetbrains/python/fixtures/PyTestCase.java @@ -107,11 +107,8 @@ public abstract class PyTestCase extends UsefulTestCase { * Reformats currently configured file. */ protected final void reformatFile() { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - doPerformFormatting(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + doPerformFormatting(); }); } @@ -321,19 +318,11 @@ public abstract class PyTestCase extends UsefulTestCase { * @param file file to clear */ protected void clearFile(@NotNull final PsiFile file) { - CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (final PsiElement element : file.getChildren()) { - element.delete(); - } - } - }); + CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + for (final PsiElement element : file.getChildren()) { + element.delete(); } - }, null, null); + }), null, null); } /** @@ -413,12 +402,7 @@ public abstract class PyTestCase extends UsefulTestCase { * @see IdeActions */ protected final void pressButton(@NotNull final String action) { - CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() { - @Override - public void run() { - myFixture.performEditorAction(action); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> myFixture.performEditorAction(action), "", null); } @NotNull diff --git a/python/testSrc/com/jetbrains/python/inspections/Py3TypeCheckerInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/Py3TypeCheckerInspectionTest.java index ef709ac03086..de12d7c1a672 100644 --- a/python/testSrc/com/jetbrains/python/inspections/Py3TypeCheckerInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/Py3TypeCheckerInspectionTest.java @@ -31,27 +31,21 @@ public class Py3TypeCheckerInspectionTest extends PyTestCase { } private void doTest() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - myFixture.copyDirectoryToProject("typing", ""); - myFixture.configureByFile(TEST_DIRECTORY + getTestName(false) + ".py"); - myFixture.enableInspections(PyTypeCheckerInspection.class); - myFixture.checkHighlighting(true, false, true); - } + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> { + myFixture.copyDirectoryToProject("typing", ""); + myFixture.configureByFile(TEST_DIRECTORY + getTestName(false) + ".py"); + myFixture.enableInspections(PyTypeCheckerInspection.class); + myFixture.checkHighlighting(true, false, true); }); } private void doMultiFileTest() { - runWithLanguageLevel(LanguageLevel.PYTHON35, new Runnable() { - @Override - public void run() { - myFixture.copyDirectoryToProject(TEST_DIRECTORY + getTestName(false), ""); - myFixture.copyDirectoryToProject("typing", ""); - myFixture.configureFromTempProjectFile("a.py"); - myFixture.enableInspections(PyTypeCheckerInspection.class); - myFixture.checkHighlighting(true, false, true); - } + runWithLanguageLevel(LanguageLevel.PYTHON35, () -> { + myFixture.copyDirectoryToProject(TEST_DIRECTORY + getTestName(false), ""); + myFixture.copyDirectoryToProject("typing", ""); + myFixture.configureFromTempProjectFile("a.py"); + myFixture.enableInspections(PyTypeCheckerInspection.class); + myFixture.checkHighlighting(true, false, true); }); } diff --git a/python/testSrc/com/jetbrains/python/inspections/Py3UnresolvedReferencesInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/Py3UnresolvedReferencesInspectionTest.java index e859d31491f7..dc43bc8b5f3a 100644 --- a/python/testSrc/com/jetbrains/python/inspections/Py3UnresolvedReferencesInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/Py3UnresolvedReferencesInspectionTest.java @@ -41,26 +41,20 @@ public class Py3UnresolvedReferencesInspectionTest extends PyTestCase { } private void doTest() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - myFixture.configureByFile(TEST_DIRECTORY + getTestName(true) + ".py"); - myFixture.enableInspections(PyUnresolvedReferencesInspection.class); - myFixture.checkHighlighting(true, false, false); - } + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> { + myFixture.configureByFile(TEST_DIRECTORY + getTestName(true) + ".py"); + myFixture.enableInspections(PyUnresolvedReferencesInspection.class); + myFixture.checkHighlighting(true, false, false); }); } private void doMultiFileTest(@NotNull final String filename) { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - final String testName = getTestName(false); - myFixture.copyDirectoryToProject(TEST_DIRECTORY + testName, ""); - myFixture.configureFromTempProjectFile(filename); - myFixture.enableInspections(PyUnresolvedReferencesInspection.class); - myFixture.checkHighlighting(true, false, false); - } + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> { + final String testName = getTestName(false); + myFixture.copyDirectoryToProject(TEST_DIRECTORY + testName, ""); + myFixture.configureFromTempProjectFile(filename); + myFixture.enableInspections(PyUnresolvedReferencesInspection.class); + myFixture.checkHighlighting(true, false, false); }); } diff --git a/python/testSrc/com/jetbrains/python/inspections/PyAbstractClassInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyAbstractClassInspectionTest.java index c91e21730c31..1214ab9a611e 100644 --- a/python/testSrc/com/jetbrains/python/inspections/PyAbstractClassInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/PyAbstractClassInspectionTest.java @@ -40,11 +40,7 @@ public class PyAbstractClassInspectionTest extends PyInspectionTestCase { // PY-16035 public void testHiddenForAbstractSubclassWithExplicitMetaclassPy3() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTest()); } // PY-16035 diff --git a/python/testSrc/com/jetbrains/python/inspections/PyCompatibilityInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyCompatibilityInspectionTest.java index e2448ebab5f3..e869d715e5fe 100644 --- a/python/testSrc/com/jetbrains/python/inspections/PyCompatibilityInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/PyCompatibilityInspectionTest.java @@ -168,12 +168,7 @@ public class PyCompatibilityInspectionTest extends PyTestCase { } private void doTest(@NotNull LanguageLevel level) { - runWithLanguageLevel(level, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(level, () -> doTest()); } private void doTest() { diff --git a/python/testSrc/com/jetbrains/python/inspections/PyStatementEffectInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyStatementEffectInspectionTest.java index c61ddd5cf081..2b687f293924 100644 --- a/python/testSrc/com/jetbrains/python/inspections/PyStatementEffectInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/PyStatementEffectInspectionTest.java @@ -32,12 +32,7 @@ public class PyStatementEffectInspectionTest extends PyInspectionTestCase { } private void doTest(@NotNull LanguageLevel level) { - runWithLanguageLevel(level, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(level, () -> doTest()); } @NotNull diff --git a/python/testSrc/com/jetbrains/python/inspections/PyUnboundLocalVariableInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyUnboundLocalVariableInspectionTest.java index 3c4aa85d68df..feb634b6faad 100644 --- a/python/testSrc/com/jetbrains/python/inspections/PyUnboundLocalVariableInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/PyUnboundLocalVariableInspectionTest.java @@ -45,12 +45,7 @@ public class PyUnboundLocalVariableInspectionTest extends PyTestCase { // PY-1408 public void testUnboundExceptAs() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doTest()); } // PY-1434 @@ -90,12 +85,7 @@ public class PyUnboundLocalVariableInspectionTest extends PyTestCase { // PY-3603 public void testUnboundNonLocal() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doTest()); } // PY-3671 diff --git a/python/testSrc/com/jetbrains/python/inspections/PyUnreachableCodeInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyUnreachableCodeInspectionTest.java index c67e56ef3319..82dcb5e90df5 100644 --- a/python/testSrc/com/jetbrains/python/inspections/PyUnreachableCodeInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/PyUnreachableCodeInspectionTest.java @@ -26,22 +26,12 @@ public class PyUnreachableCodeInspectionTest extends PyTestCase { // All previous unreachable tests, feel free to split them public void testUnreachable() { - runWithLanguageLevel(LanguageLevel.PYTHON26, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON26, () -> doTest()); } // PY-7420 public void testWithSuppressedExceptions() { - runWithLanguageLevel(LanguageLevel.PYTHON26, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON26, () -> doTest()); } private void doTest() { diff --git a/python/testSrc/com/jetbrains/python/inspections/PyUnresolvedReferencesInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyUnresolvedReferencesInspectionTest.java index ebac9efccb66..471e48ecac7a 100644 --- a/python/testSrc/com/jetbrains/python/inspections/PyUnresolvedReferencesInspectionTest.java +++ b/python/testSrc/com/jetbrains/python/inspections/PyUnresolvedReferencesInspectionTest.java @@ -234,32 +234,17 @@ public class PyUnresolvedReferencesInspectionTest extends PyInspectionTestCase { // PY-6745 public void testQualNameAttribute() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doTest()); } // PY-7389 public void testComprehensionScope27() { - runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON27, () -> doTest()); } // PY-7389 public void testComprehensionScope33() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doTest(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doTest()); } // PY-7516 diff --git a/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java b/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java index 5bbc03d56b42..649dbcf273f7 100644 --- a/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java +++ b/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java @@ -52,11 +52,7 @@ public class PyConvertCollectionLiteralIntentionTest extends PyIntentionTestCase // PY-9419 public void testConvertTupleToSetNotAvailableWithoutSetLiterals() { - runWithLanguageLevel(LanguageLevel.PYTHON25, new Runnable() { - public void run() { - doNegativeTest(CONVERT_TUPLE_TO_SET); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON25, () -> doNegativeTest(CONVERT_TUPLE_TO_SET)); } // PY-9419 diff --git a/python/testSrc/com/jetbrains/python/intentions/PyIntentionTest.java b/python/testSrc/com/jetbrains/python/intentions/PyIntentionTest.java index c6ff7f7fbd52..21977c432d81 100644 --- a/python/testSrc/com/jetbrains/python/intentions/PyIntentionTest.java +++ b/python/testSrc/com/jetbrains/python/intentions/PyIntentionTest.java @@ -415,11 +415,7 @@ public class PyIntentionTest extends PyTestCase { public void testDocStubKeywordOnly() { getIndentOptions().INDENT_SIZE = 2; - runWithLanguageLevel(LanguageLevel.PYTHON27, new Runnable() { - public void run() { - doDocStubTest(DocStringFormat.REST); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON27, () -> doDocStubTest(DocStringFormat.REST)); } // PY-16765 @@ -700,39 +696,23 @@ public class PyIntentionTest extends PyTestCase { } private void doDocStubTest(@NotNull DocStringFormat format) { - runWithDocStringFormat(format, new Runnable() { - @Override - public void run() { - CodeInsightSettings.getInstance().JAVADOC_STUB_ON_ENTER = true; - doTest(PyBundle.message("INTN.doc.string.stub"), true); - } + runWithDocStringFormat(format, () -> { + CodeInsightSettings.getInstance().JAVADOC_STUB_ON_ENTER = true; + doTest(PyBundle.message("INTN.doc.string.stub"), true); }); } private void doDocParamTypeTest(@NotNull DocStringFormat format) { - runWithDocStringFormat(format, new Runnable() { - public void run() { - doTest(PyBundle.message("INTN.specify.type")); - } - }); + runWithDocStringFormat(format, () -> doTest(PyBundle.message("INTN.specify.type"))); } private void doDocReturnTypeTest(@NotNull DocStringFormat format) { - runWithDocStringFormat(format, new Runnable() { - public void run() { - doTest(PyBundle.message("INTN.specify.return.type")); - } - }); + runWithDocStringFormat(format, () -> doTest(PyBundle.message("INTN.specify.return.type"))); } public void doDocAddMissingParamsTest(@NotNull DocStringFormat format) { - runWithDocStringFormat(format, new Runnable() { - @Override - public void run() { - doTest(PyBundle.message("INTN.add.parameters.to.docstring")); - } - }); + runWithDocStringFormat(format, () -> doTest(PyBundle.message("INTN.add.parameters.to.docstring"))); } } diff --git a/python/testSrc/com/jetbrains/python/intentions/PyStringConcatenationToFormatIntentionTest.java b/python/testSrc/com/jetbrains/python/intentions/PyStringConcatenationToFormatIntentionTest.java index 39c678e24d06..8a2423680798 100644 --- a/python/testSrc/com/jetbrains/python/intentions/PyStringConcatenationToFormatIntentionTest.java +++ b/python/testSrc/com/jetbrains/python/intentions/PyStringConcatenationToFormatIntentionTest.java @@ -32,12 +32,7 @@ public class PyStringConcatenationToFormatIntentionTest extends PyIntentionTestC } public void testNegative() { //PY-6505 - runWithLanguageLevel(LanguageLevel.PYTHON25, new Runnable() { - @Override - public void run() { - doNegativeTest(PyBundle.message("INTN.replace.plus.with.format.operator")); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON25, () -> doNegativeTest(PyBundle.message("INTN.replace.plus.with.format.operator"))); } public void testTwoStrings() { //PY-6505 diff --git a/python/testSrc/com/jetbrains/python/psi/impl/PyArgumentListImplTest.java b/python/testSrc/com/jetbrains/python/psi/impl/PyArgumentListImplTest.java index 7aa1a5c0864c..ddb37158eedf 100644 --- a/python/testSrc/com/jetbrains/python/psi/impl/PyArgumentListImplTest.java +++ b/python/testSrc/com/jetbrains/python/psi/impl/PyArgumentListImplTest.java @@ -61,29 +61,22 @@ public class PyArgumentListImplTest extends PyClassRefactoringTest { myFixture.configureByFile(getMultiFileBaseName() + "/addArgumentFile.py"); //TODO: newly created expressions has no indent info, it leads to errors in postprocessing formatting. Need to investigate. - PostprocessReformattingAspect.getInstance(myFixture.getProject()).disablePostprocessFormattingInside(new Runnable() { - @Override - public void run() { - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { + PostprocessReformattingAspect.getInstance(myFixture.getProject()).disablePostprocessFormattingInside( + () -> WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { - for (final PyClass aClass : PsiTreeUtil.findChildrenOfType(myFixture.getFile(), PyClass.class)) { - final PyArgumentList superClassExpressionList = aClass.getSuperClassExpressionList(); - assert superClassExpressionList != null : "Class has no expression list!"; - superClassExpressionList.addArgument(superClassExpression); - } + for (final PyClass aClass : PsiTreeUtil.findChildrenOfType(myFixture.getFile(), PyClass.class)) { + final PyArgumentList superClassExpressionList = aClass.getSuperClassExpressionList(); + assert superClassExpressionList != null : "Class has no expression list!"; + superClassExpressionList.addArgument(superClassExpression); + } - for (final PyCallExpression expression : PsiTreeUtil.findChildrenOfType(myFixture.getFile(), PyCallExpression.class)) { - final PyArgumentList list = expression.getArgumentList(); - assert list != null : "Callable statement has no argument list?"; - list.addArgument(functionExpression); - } - } - }); - } - }); + for (final PyCallExpression expression : PsiTreeUtil.findChildrenOfType(myFixture.getFile(), PyCallExpression.class)) { + final PyArgumentList list = expression.getArgumentList(); + assert list != null : "Callable statement has no argument list?"; + list.addArgument(functionExpression); + } + })); myFixture.checkResultByFile(getMultiFileBaseName() + "/addArgumentFile.after.py"); } } diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java index 6656044d58dc..f76e6dc510c8 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyInlineLocalTest.java @@ -151,11 +151,8 @@ public class PyInlineLocalTest extends PyTestCase { private void checkOperatorPrecedence(@NotNull final String firstLine, @NotNull String resultPrefix) throws Exception { myFixture.configureByFile("/refactoring/inlinelocal/operatorPrecedence/template.py"); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - myFixture.getEditor().getDocument().insertString(0, firstLine + "\n"); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + myFixture.getEditor().getDocument().insertString(0, firstLine + "\n"); }); performRefactoring(null); myFixture.checkResultByFile("/refactoring/inlinelocal/operatorPrecedence/" + resultPrefix + ".after.py"); diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyIntroduceTestCase.java b/python/testSrc/com/jetbrains/python/refactoring/PyIntroduceTestCase.java index 948debfda3e4..15a043b5e6c1 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyIntroduceTestCase.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyIntroduceTestCase.java @@ -89,13 +89,10 @@ public abstract class PyIntroduceTestCase extends PyTestCase { } handler.performAction(introduceOperation); - WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { - @Override - public void run() { - TemplateState state = TemplateManagerImpl.getTemplateState(myFixture.getEditor()); - assert state != null; - state.gotoEnd(false); - } + WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { + TemplateState state = TemplateManagerImpl.getTemplateState(myFixture.getEditor()); + assert state != null; + state.gotoEnd(false); }); myFixture.checkResultByFile(name + ".after.py", true); diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyMakeFunctionTopLevelTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyMakeFunctionTopLevelTest.java index 6e8c3a8a791a..048d9c08d9a7 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyMakeFunctionTopLevelTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyMakeFunctionTopLevelTest.java @@ -127,22 +127,13 @@ public class PyMakeFunctionTopLevelTest extends PyTestCase { // PY-6637 public void testLocalFunctionNonlocalReferenceToOuterScope() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTestFailure(PyBundle.message("refactoring.make.function.top.level.error.nonlocal.writes")); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doTestFailure(PyBundle.message("refactoring.make.function.top.level.error.nonlocal.writes"))); } // PY-6637 public void testLocalFunctionNonlocalReferencesInInnerFunction() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTestSuccess(); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> doTestSuccess()); } // PY-6637 @@ -151,12 +142,8 @@ public class PyMakeFunctionTopLevelTest extends PyTestCase { } public void testMethodNonlocalReferenceToOuterScope() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @Override - public void run() { - doTestFailure(PyBundle.message("refactoring.make.function.top.level.error.nonlocal.writes")); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON30, + () -> doTestFailure(PyBundle.message("refactoring.make.function.top.level.error.nonlocal.writes"))); } public void testMethodOuterScopeReads() { diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java index 91db92b20a1b..4758b43b0599 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyMoveTest.java @@ -70,19 +70,16 @@ public class PyMoveTest extends PyTestCase { // PY-11923 public void testMovableTopLevelAssignmentDetection() { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - @SuppressWarnings("ConstantConditions") - public void run() { - myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); - assertFalse(isMovableModuleMember(findFirstNamedElement("X1"))); - assertFalse(isMovableModuleMember(findFirstNamedElement("X3"))); - assertFalse(isMovableModuleMember(findFirstNamedElement("X2"))); - assertFalse(isMovableModuleMember(findFirstNamedElement("X4"))); - assertFalse(isMovableModuleMember(findFirstNamedElement("X5"))); - assertFalse(isMovableModuleMember(findFirstNamedElement("X6"))); - assertFalse(isMovableModuleMember(findFirstNamedElement("X7"))); - assertTrue(isMovableModuleMember(findFirstNamedElement("X8"))); - } + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> { + myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); + assertFalse(isMovableModuleMember(findFirstNamedElement("X1"))); + assertFalse(isMovableModuleMember(findFirstNamedElement("X3"))); + assertFalse(isMovableModuleMember(findFirstNamedElement("X2"))); + assertFalse(isMovableModuleMember(findFirstNamedElement("X4"))); + assertFalse(isMovableModuleMember(findFirstNamedElement("X5"))); + assertFalse(isMovableModuleMember(findFirstNamedElement("X6"))); + assertFalse(isMovableModuleMember(findFirstNamedElement("X7"))); + assertTrue(isMovableModuleMember(findFirstNamedElement("X8"))); }); } @@ -90,11 +87,8 @@ public class PyMoveTest extends PyTestCase { public void testCollectMovableModuleMembers() { myFixture.configureByFile("/refactoring/move/" + getTestName(true) + ".py"); final List members = PyMoveModuleMembersHelper.getTopLevelModuleMembers((PyFile)myFixture.getFile()); - final List names = ContainerUtil.map(members, new Function() { - @Override - public String fun(PyElement element) { - return element.getName(); - } + final List names = ContainerUtil.map(members, element -> { + return element.getName(); }); assertSameElements(names, "CONST", "C", "outer_func"); } @@ -213,42 +207,22 @@ public class PyMoveTest extends PyTestCase { // PY-7378 public void testMoveNamespacePackage1() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doMoveFileTest("nspkg/nssubpkg", ""); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg", "")); } // PY-7378 public void testMoveNamespacePackage2() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doMoveFileTest("nspkg/nssubpkg/a.py", ""); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg/a.py", "")); } // PY-7378 public void testMoveNamespacePackage3() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doMoveFileTest("nspkg/nssubpkg/a.py", "nspkg"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg/a.py", "nspkg")); } // PY-14384 public void testRelativeImportInsideNamespacePackage() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doMoveFileTest("nspkg/nssubpkg", ""); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveFileTest("nspkg/nssubpkg", "")); } // PY-14384 @@ -269,12 +243,7 @@ public class PyMoveTest extends PyTestCase { // PY-14595 public void testNamespacePackageUsedInMovedFunction() { - runWithLanguageLevel(LanguageLevel.PYTHON33, new Runnable() { - @Override - public void run() { - doMoveSymbolTest("func", "b.py"); - } - }); + runWithLanguageLevel(LanguageLevel.PYTHON33, () -> doMoveSymbolTest("func", "b.py")); } // PY-14599 @@ -423,13 +392,10 @@ public class PyMoveTest extends PyTestCase { VirtualFile dir1 = myFixture.copyDirectoryToProject(rootBefore, ""); PsiDocumentManager.getInstance(myFixture.getProject()).commitAllDocuments(); - final PsiNamedElement[] symbols = ContainerUtil.map2Array(symbolNames, PsiNamedElement.class, new Function() { - @Override - public PsiNamedElement fun(String name) { - final PsiNamedElement found = findFirstNamedElement(name); - assertNotNull("Symbol '" + name + "' does not exist", found); - return found; - } + final PsiNamedElement[] symbols = ContainerUtil.map2Array(symbolNames, PsiNamedElement.class, name -> { + final PsiNamedElement found = findFirstNamedElement(name); + assertNotNull("Symbol '" + name + "' does not exist", found); + return found; }); VirtualFile toVirtualFile = dir1.findFileByRelativePath(toFileName); diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyRenameTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyRenameTest.java index 7764d3aa6cdc..c398a6a98bae 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyRenameTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyRenameTest.java @@ -293,11 +293,7 @@ public class PyRenameTest extends PyTestCase { } private void renameWithDocStringFormat(DocStringFormat format, final String newName) { - runWithDocStringFormat(format, new Runnable() { - public void run() { - doTest(newName); - } - }); + runWithDocStringFormat(format, () -> doTest(newName)); } private void doUnsupportedOperationTest() { diff --git a/python/testSrc/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureTest.java b/python/testSrc/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureTest.java index 590dcee680f9..0da1e6fb692f 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureTest.java @@ -108,31 +108,19 @@ public class PyChangeSignatureTest extends PyTestCase { // PY-9795 public void testFixGoogleDocStringRemoveMultiple() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - public void run() { - doChangeSignatureTest(null, Arrays.asList(new PyParameterInfo(0, "a", null, false), - new PyParameterInfo(3, "d", null, false))); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, () -> doChangeSignatureTest(null, Arrays.asList(new PyParameterInfo(0, "a", null, false), + new PyParameterInfo(3, "d", null, false)))); } // PY-16761 public void testGoogleDocStringRemoveVarargs() { - runWithDocStringFormat(DocStringFormat.GOOGLE, new Runnable() { - public void run() { - doChangeSignatureTest(null, Arrays.asList(new PyParameterInfo(0, "x", null, false))); - } - }); + runWithDocStringFormat(DocStringFormat.GOOGLE, + () -> doChangeSignatureTest(null, Arrays.asList(new PyParameterInfo(0, "x", null, false)))); } public void testFixSphinxDocStringRemoveMultiple() { - runWithDocStringFormat(DocStringFormat.REST, new Runnable() { - @Override - public void run() { - doChangeSignatureTest(null, Arrays.asList(new PyParameterInfo(0, "a", null, false), - new PyParameterInfo(3, "d", null, false))); - } - }); + runWithDocStringFormat(DocStringFormat.REST, () -> doChangeSignatureTest(null, Arrays.asList(new PyParameterInfo(0, "a", null, false), + new PyParameterInfo(3, "d", null, false)))); } public void testClassMethod() { @@ -243,21 +231,16 @@ public class PyChangeSignatureTest extends PyTestCase { // PY-14774 public void testAnnotationsForStarredParametersAreNotShownInDialog() throws Exception { - runWithLanguageLevel(LanguageLevel.PYTHON30, new Runnable() { - public void run() { - myFixture.configureByText(PythonFileType.INSTANCE, "def func(a, b:int, *args: tuple, c:list, d:str='foo', ** kwargs:dict):\n" + - " pass"); - final PyFunction function = (PyFunction)new PyChangeSignatureHandler().findTargetMember(myFixture.getFile(), myFixture.getEditor()); - assertNotNull(function); - final List expected = Arrays.asList("a", "b", "*args", "c", "d", "**kwargs"); - final List parameters = new PyMethodDescriptor(function).getParameters(); - assertEquals(expected, ContainerUtil.map(parameters, new Function() { - @Override - public String fun(PyParameterInfo info) { - return info.getOldName(); - } - })); - } + runWithLanguageLevel(LanguageLevel.PYTHON30, () -> { + myFixture.configureByText(PythonFileType.INSTANCE, "def func(a, b:int, *args: tuple, c:list, d:str='foo', ** kwargs:dict):\n" + + " pass"); + final PyFunction function = (PyFunction)new PyChangeSignatureHandler().findTargetMember(myFixture.getFile(), myFixture.getEditor()); + assertNotNull(function); + final List expected = Arrays.asList("a", "b", "*args", "c", "d", "**kwargs"); + final List parameters = new PyMethodDescriptor(function).getParameters(); + assertEquals(expected, ContainerUtil.map(parameters, info -> { + return info.getOldName(); + })); }); } diff --git a/python/testSrc/com/jetbrains/python/refactoring/classes/PyClassRefactoringTest.java b/python/testSrc/com/jetbrains/python/refactoring/classes/PyClassRefactoringTest.java index dd24256021aa..62ae52488342 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/classes/PyClassRefactoringTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/classes/PyClassRefactoringTest.java @@ -108,17 +108,9 @@ public abstract class PyClassRefactoringTest extends PyTestCase { protected void moveViaProcessor(@NotNull Project project, @NotNull final BaseRefactoringProcessor processor) { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - processor.run(); - } - }); - } - }, null, null); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + processor.run(); + }), null, null); } /** diff --git a/python/testSrc/com/jetbrains/python/sdkTools/PyTestSdkTools.java b/python/testSrc/com/jetbrains/python/sdkTools/PyTestSdkTools.java index e14356f626f4..db9559f73660 100644 --- a/python/testSrc/com/jetbrains/python/sdkTools/PyTestSdkTools.java +++ b/python/testSrc/com/jetbrains/python/sdkTools/PyTestSdkTools.java @@ -93,17 +93,9 @@ public final class PyTestSdkTools { // Associate with module ModuleRootModificationUtil.setModuleSdk(module, sdk); - UsefulTestCase.edt(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ProjectRootManager.getInstance(finalProject).setProjectSdk(sdk); - } - }); - } - }); + UsefulTestCase.edt(() -> ApplicationManager.getApplication().runWriteAction(() -> { + ProjectRootManager.getInstance(finalProject).setProjectSdk(sdk); + })); } diff --git a/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java b/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java index 57106fecbdac..9d08be52e8d7 100644 --- a/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java +++ b/spellchecker/src/com/intellij/spellchecker/SpellCheckerManager.java @@ -92,19 +92,16 @@ public class SpellCheckerManager { if (settings != null && settings.getDictionaryFoldersPaths() != null) { final Set disabledDictionaries = settings.getDisabledDictionariesPaths(); for (String folder : settings.getDictionaryFoldersPaths()) { - SPFileUtil.processFilesRecursively(folder, new Consumer() { - @Override - public void consume(final String s) { - boolean dictionaryShouldBeLoad =!disabledDictionaries.contains(s); - boolean dictionaryIsLoad = spellChecker.isDictionaryLoad(s); - if (dictionaryIsLoad && !dictionaryShouldBeLoad) { - spellChecker.removeDictionary(s); - } - else if (!dictionaryIsLoad && dictionaryShouldBeLoad) { - spellChecker.loadDictionary(new FileLoader(s, s)); - } - + SPFileUtil.processFilesRecursively(folder, s -> { + boolean dictionaryShouldBeLoad =!disabledDictionaries.contains(s); + boolean dictionaryIsLoad = spellChecker.isDictionaryLoad(s); + if (dictionaryIsLoad && !dictionaryShouldBeLoad) { + spellChecker.removeDictionary(s); } + else if (!dictionaryIsLoad && dictionaryShouldBeLoad) { + spellChecker.loadDictionary(new FileLoader(s, s)); + } + }); } @@ -130,11 +127,8 @@ public class SpellCheckerManager { private void fillEngineDictionary() { spellChecker.reset(); final StateLoader stateLoader = new StateLoader(project); - stateLoader.load(new Consumer() { - @Override - public void consume(String s) { - //do nothing - in this loader we don't worry about word list itself - the whole dictionary will be restored - } + stateLoader.load(s -> { + //do nothing - in this loader we don't worry about word list itself - the whole dictionary will be restored }); final List loaders = new ArrayList(); // Load bundled dictionaries from corresponding jars @@ -155,12 +149,9 @@ public class SpellCheckerManager { if (settings != null && settings.getDictionaryFoldersPaths() != null) { final Set disabledDictionaries = settings.getDisabledDictionariesPaths(); for (String folder : settings.getDictionaryFoldersPaths()) { - SPFileUtil.processFilesRecursively(folder, new Consumer() { - @Override - public void consume(final String s) { - if (!disabledDictionaries.contains(s)) { - loaders.add(new FileLoader(s, s)); - } + SPFileUtil.processFilesRecursively(folder, s -> { + if (!disabledDictionaries.contains(s)) { + loaders.add(new FileLoader(s, s)); } }); @@ -230,14 +221,11 @@ public class SpellCheckerManager { } public static void restartInspections() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Project[] projects = ProjectManager.getInstance().getOpenProjects(); - for (Project project : projects) { - if (project.isInitialized() && project.isOpen() && !project.isDefault()) { - DaemonCodeAnalyzer.getInstance(project).restart(); - } + ApplicationManager.getApplication().invokeLater(() -> { + Project[] projects = ProjectManager.getInstance().getOpenProjects(); + for (Project project1 : projects) { + if (project1.isInitialized() && project1.isOpen() && !project1.isDefault()) { + DaemonCodeAnalyzer.getInstance(project1).restart(); } } }); diff --git a/spellchecker/src/com/intellij/spellchecker/actions/SpellingPopupActionGroup.java b/spellchecker/src/com/intellij/spellchecker/actions/SpellingPopupActionGroup.java index b8a45953b303..b9f3553a603b 100644 --- a/spellchecker/src/com/intellij/spellchecker/actions/SpellingPopupActionGroup.java +++ b/spellchecker/src/com/intellij/spellchecker/actions/SpellingPopupActionGroup.java @@ -128,19 +128,15 @@ public final class SpellingPopupActionGroup extends ActionGroup { final Project project = e.getData(LangDataKeys.PROJECT); final Editor editor = e.getData(LangDataKeys.EDITOR); if (psiFile != null && project != null && editor != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - public void run() { - try { - intention.invoke(project, editor, psiFile); - } - catch (IncorrectOperationException ex) { - LOGGER.error(ex); - } - } - }, e.getPresentation().getText(), e.getActionManager().getId(SpellCheckerIntentionAction.this)); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(project, () -> { + try { + intention.invoke(project, editor, psiFile); + } + catch (IncorrectOperationException ex) { + LOGGER.error(ex); + } + }, e.getPresentation().getText(), e.getActionManager().getId(SpellCheckerIntentionAction.this)); }); } } diff --git a/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java b/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java index 7914aded01a8..c320c2dec3d5 100644 --- a/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java +++ b/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java @@ -38,12 +38,7 @@ public final class CompressedDictionary implements Dictionary { private final String name; private TIntObjectHashMap> rawData = new TIntObjectHashMap>(); - private static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(byte[] o1, byte[] o2) { - return compareArrays(o1, o2); - } - }; + private static final Comparator COMPARATOR = (o1, o2) -> compareArrays(o1, o2); private CompressedDictionary(@NotNull Alphabet alphabet, @NotNull Encoder encoder, @NotNull String name) { this.alphabet = alphabet; @@ -180,15 +175,12 @@ public final class CompressedDictionary implements Dictionary { final Encoder encoder = new Encoder(alphabet); final CompressedDictionary dictionary = new CompressedDictionary(alphabet, encoder, loader.getName()); final List bss = new ArrayList(); - loader.load(new Consumer() { - @Override - public void consume(String s) { - String transformed = transform.transform(s); - if (transformed != null) { - UnitBitSet bs = encoder.encode(transformed, true); - if (bs == null) return; - bss.add(bs); - } + loader.load(s -> { + String transformed = transform.transform(s); + if (transformed != null) { + UnitBitSet bs = encoder.encode(transformed, true); + if (bs == null) return; + bss.add(bs); } }); for (UnitBitSet bs : bss) { diff --git a/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java b/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java index df3f8b65ffa4..90bb7944ae87 100644 --- a/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java +++ b/spellchecker/src/com/intellij/spellchecker/generator/SpellCheckerDictionaryGenerator.java @@ -71,25 +71,22 @@ public abstract class SpellCheckerDictionaryGenerator { } public void generate() { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - // let's do result a bit more predictable + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + // let's do result a bit more predictable - // ruby dictionary - generate(myDefaultDictName, progressIndicator); + // ruby dictionary + generate(myDefaultDictName, progressIndicator); - // other gem-related dictionaries in alphabet order - final List dictionaries = new ArrayList(myDict2FolderMap.keySet()); - Collections.sort(dictionaries); + // other gem-related dictionaries in alphabet order + final List dictionaries = new ArrayList(myDict2FolderMap.keySet()); + Collections.sort(dictionaries); - for (String dict : dictionaries) { - if (myDefaultDictName.equals(dict)) { - continue; - } - generate(dict, progressIndicator); + for (String dict : dictionaries) { + if (myDefaultDictName.equals(dict)) { + continue; } + generate(dict, progressIndicator); } }, "Generating Dictionaries", false, myProject); } @@ -187,12 +184,9 @@ public abstract class SpellCheckerDictionaryGenerator { SpellCheckingInspection.tokenize(leafElement, language, new TokenConsumer() { @Override public void consumeToken(PsiElement element, final String text, boolean useRename, int offset, TextRange rangeToCheck, Splitter splitter) { - splitter.split(text, rangeToCheck, new Consumer() { - @Override - public void consume(TextRange textRange) { - final String word = textRange.substring(text); - addSeenWord(seenNames, word, language); - } + splitter.split(text, rangeToCheck, textRange -> { + final String word = textRange.substring(text); + addSeenWord(seenNames, word, language); }); } }); diff --git a/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java b/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java index 61d71135806e..1c9fe98d007c 100644 --- a/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java +++ b/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java @@ -71,11 +71,8 @@ public class SpellCheckerSettingsPane implements Disposable { if (allSettings != null) { final ErrorsConfigurable errorsConfigurable = allSettings.find(ErrorsConfigurable.class); if (errorsConfigurable != null) { - allSettings.select(errorsConfigurable).doWhenDone(new Runnable() { - public void run() { - errorsConfigurable.selectInspectionTool(SpellCheckingInspection.SPELL_CHECKING_INSPECTION_TOOL_NAME); - } - }); + allSettings.select(errorsConfigurable).doWhenDone( + () -> errorsConfigurable.selectInspectionTool(SpellCheckingInspection.SPELL_CHECKING_INSPECTION_TOOL_NAME)); } } } @@ -99,11 +96,7 @@ public class SpellCheckerSettingsPane implements Disposable { paths.add(path); final ArrayList> currentDictionaries = optionalChooserComponent.getCurrentModel(); - SPFileUtil.processFilesRecursively(path, new Consumer() { - public void consume(final String s) { - currentDictionaries.add(Pair.create(s, true)); - } - }); + SPFileUtil.processFilesRecursively(path, s -> currentDictionaries.add(Pair.create(s, true))); optionalChooserComponent.refresh(); return true; } @@ -229,11 +222,7 @@ public class SpellCheckerSettingsPane implements Disposable { //todo [shkate]: refactoring - SpellCheckerManager contains the same code withing reloadConfiguration() final Set disabledDictionaries = settings.getDisabledDictionariesPaths(); for (String folder : dictionariesFolders) { - SPFileUtil.processFilesRecursively(folder, new Consumer() { - public void consume(final String s) { - allDictionaries.add(Pair.create(s, !disabledDictionaries.contains(s))); - } - }); + SPFileUtil.processFilesRecursively(folder, s -> allDictionaries.add(Pair.create(s, !disabledDictionaries.contains(s)))); } } diff --git a/spellchecker/src/com/intellij/spellchecker/util/SPFileUtil.java b/spellchecker/src/com/intellij/spellchecker/util/SPFileUtil.java index 1de914758a76..520d071ff625 100644 --- a/spellchecker/src/com/intellij/spellchecker/util/SPFileUtil.java +++ b/spellchecker/src/com/intellij/spellchecker/util/SPFileUtil.java @@ -28,16 +28,14 @@ public class SPFileUtil { public static void processFilesRecursively(final String rootPath, final Consumer consumer){ final File rootFile = new File(rootPath); if (rootFile.exists() && rootFile.isDirectory()){ - FileUtil.processFilesRecursively(rootFile, new Processor() { - public boolean process(final File file) { - if (!file.isDirectory()){ - final String path = file.getPath(); - if (path.endsWith(".dic")){ - consumer.consume(path); - } + FileUtil.processFilesRecursively(rootFile, file -> { + if (!file.isDirectory()){ + final String path = file.getPath(); + if (path.endsWith(".dic")){ + consumer.consume(path); } - return true; } + return true; }); } } diff --git a/spellchecker/testSrc/com/intellij/spellchecker/compress/DictionaryTest.java b/spellchecker/testSrc/com/intellij/spellchecker/compress/DictionaryTest.java index edf6a2d3b26f..bf7b176d56fc 100644 --- a/spellchecker/testSrc/com/intellij/spellchecker/compress/DictionaryTest.java +++ b/spellchecker/testSrc/com/intellij/spellchecker/compress/DictionaryTest.java @@ -57,14 +57,11 @@ public class DictionaryTest { @Test public void testDictionaryLoadedFully() { final Set onDisk = new THashSet(); - getLoader(JETBRAINS_DIC).load(new Consumer() { - @Override - public void consume(String s) { - assertNotNull(s); - String t = myTransformation.transform(s); - if (t != null) { - onDisk.add(t); - } + getLoader(JETBRAINS_DIC).load(s -> { + assertNotNull(s); + String t = myTransformation.transform(s); + if (t != null) { + onDisk.add(t); } }); @@ -76,12 +73,8 @@ public class DictionaryTest { private Dictionary loadDictionaryPerformanceTest(final String name, int time) { final Ref ref = Ref.create(); - PlatformTestUtil.startPerformanceTest("load dictionary", time, new ThrowableRunnable() { - @Override - public void run() { - ref.set(CompressedDictionary.create(getLoader(name), myTransformation)); - } - }).cpuBound().useLegacyScaling().assertTiming(); + PlatformTestUtil.startPerformanceTest("load dictionary", time, + () -> ref.set(CompressedDictionary.create(getLoader(name), myTransformation))).cpuBound().useLegacyScaling().assertTiming(); assertFalse(ref.isNull()); return ref.get(); @@ -91,12 +84,9 @@ public class DictionaryTest { if (PlatformTestUtil.COVERAGE_ENABLED_BUILD) return; final Set wordsToCheck = createWordSets(dictionary, 50000, 1).first; - PlatformTestUtil.startPerformanceTest("contains word", time, new ThrowableRunnable() { - @Override - public void run() { - for (String s : wordsToCheck) { - assertEquals(Boolean.TRUE, dictionary.contains(s)); - } + PlatformTestUtil.startPerformanceTest("contains word", time, () -> { + for (String s : wordsToCheck) { + assertEquals(Boolean.TRUE, dictionary.contains(s)); } }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java b/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java index 5e42e5abb0ec..7f9e8046a367 100644 --- a/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java +++ b/spellchecker/testSrc/com/intellij/spellchecker/inspector/SplitterTest.java @@ -385,12 +385,7 @@ public class SplitterTest { private static List wordsToCheck(Splitter splitter, final String text) { final List words = new ArrayList(); - splitter.split(text, TextRange.allOf(text), new Consumer() { - @Override - public void consume(TextRange textRange) { - words.add(textRange.substring(text)); - } - }); + splitter.split(text, TextRange.allOf(text), textRange -> words.add(textRange.substring(text))); return words; } diff --git a/updater/src/com/intellij/updater/Digester.java b/updater/src/com/intellij/updater/Digester.java index ba45c49f349e..41d76f4b3872 100644 --- a/updater/src/com/intellij/updater/Digester.java +++ b/updater/src/com/intellij/updater/Digester.java @@ -42,11 +42,7 @@ public class Digester { if (!each.isDirectory()) sorted.add(each); } - Collections.sort(sorted, new Comparator() { - public int compare(ZipEntry o1, ZipEntry o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(sorted, (o1, o2) -> o1.getName().compareTo(o2.getName())); CRC32 crc = new CRC32(); for (ZipEntry each : sorted) { diff --git a/updater/src/com/intellij/updater/SwingUpdaterUI.java b/updater/src/com/intellij/updater/SwingUpdaterUI.java index 0b8250387b75..d36dbf211c71 100644 --- a/updater/src/com/intellij/updater/SwingUpdaterUI.java +++ b/updater/src/com/intellij/updater/SwingUpdaterUI.java @@ -138,33 +138,29 @@ public class SwingUpdaterUI implements UpdaterUI { } private void startRequestDispatching() { - new Thread(new Runnable() { - public void run() { - while (true) { - try { - Thread.sleep(100); - } - catch (InterruptedException e) { - Runner.printStackTrace(e); - return; - } - - final List pendingRequests = new ArrayList(); - UpdateRequest request; - while ((request = myQueue.poll()) != null) { - pendingRequests.add(request); - } - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - for (UpdateRequest each : pendingRequests) { - each.perform(); - } - } - }); + new Thread(() -> { + while (true) { + try { + Thread.sleep(100); } + catch (InterruptedException e) { + Runner.printStackTrace(e); + return; + } + + final List pendingRequests = new ArrayList(); + UpdateRequest request; + while ((request = myQueue.poll()) != null) { + pendingRequests.add(request); + } + + SwingUtilities.invokeLater(() -> { + for (UpdateRequest each : pendingRequests) { + each.perform(); + } + }); } - },"swing updater dispatch").start(); + }, "swing updater dispatch").start(); } private void doCancel() { @@ -185,32 +181,30 @@ public class SwingUpdaterUI implements UpdaterUI { private void doPerform() { isRunning.set(true); - new Thread(new Runnable() { - public void run() { - try { - myApplied = myOperation.execute(SwingUpdaterUI.this); - } - catch (OperationCancelledException ignore) { - Runner.printStackTrace(ignore); - } - catch(Throwable e) { - Runner.printStackTrace(e); - showError(e); - } - finally { - isRunning.set(false); + new Thread(() -> { + try { + myApplied = myOperation.execute(SwingUpdaterUI.this); + } + catch (OperationCancelledException ignore) { + Runner.printStackTrace(ignore); + } + catch(Throwable e) { + Runner.printStackTrace(e); + showError(e); + } + finally { + isRunning.set(false); - if (hasError.get()) { - startProcess("Failed to apply patch"); - setProgress(100); - myCancelButton.setText(EXIT_BUTTON_TITLE); - myCancelButton.setEnabled(true); - } else { - exit(); - } + if (hasError.get()) { + startProcess("Failed to apply patch"); + setProgress(100); + myCancelButton.setText(EXIT_BUTTON_TITLE); + myCancelButton.setEnabled(true); + } else { + exit(); } } - },"swing updater").start(); + }, "swing updater").start(); } private void exit() { @@ -222,86 +216,84 @@ public class SwingUpdaterUI implements UpdaterUI { final Map result = new HashMap(); try { - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - boolean proceed = true; - for (ValidationResult result : validationResults) { - if (result.options.contains(ValidationResult.Option.NONE)) { - proceed = false; - break; - } + SwingUtilities.invokeAndWait(() -> { + boolean proceed = true; + for (ValidationResult result1 : validationResults) { + if (result1.options.contains(ValidationResult.Option.NONE)) { + proceed = false; + break; } + } - final JDialog dialog = new JDialog(myFrame, TITLE, true); - dialog.setLayout(new BorderLayout()); - dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); + final JDialog dialog = new JDialog(myFrame, TITLE, true); + dialog.setLayout(new BorderLayout()); + dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); - JPanel buttonsPanel = new JPanel(); - buttonsPanel.setBorder(BUTTONS_BORDER); - buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS)); - buttonsPanel.add(Box.createHorizontalGlue()); + JPanel buttonsPanel = new JPanel(); + buttonsPanel.setBorder(BUTTONS_BORDER); + buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS)); + buttonsPanel.add(Box.createHorizontalGlue()); - JButton cancelButton = new JButton(CANCEL_BUTTON_TITLE); - cancelButton.addActionListener(new ActionListener() { + JButton cancelButton = new JButton(CANCEL_BUTTON_TITLE); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + isCancelled.set(true); + myCancelButton.setEnabled(false); + dialog.setVisible(false); + } + }); + buttonsPanel.add(cancelButton); + + if (proceed) { + JButton proceedButton = new JButton(PROCEED_BUTTON_TITLE); + proceedButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - isCancelled.set(true); - myCancelButton.setEnabled(false); dialog.setVisible(false); } }); - buttonsPanel.add(cancelButton); - - if (proceed) { - JButton proceedButton = new JButton(PROCEED_BUTTON_TITLE); - proceedButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - dialog.setVisible(false); - } - }); - buttonsPanel.add(proceedButton); - dialog.getRootPane().setDefaultButton(proceedButton); - } else { - dialog.getRootPane().setDefaultButton(cancelButton); - } - - JTable table = new JTable(); - - table.setCellSelectionEnabled(true); - table.setDefaultEditor(ValidationResult.Option.class, new MyCellEditor()); - table.setDefaultRenderer(Object.class, new MyCellRenderer()); - MyTableModel model = new MyTableModel(validationResults); - table.setModel(model); - - for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) { - TableColumn each = table.getColumnModel().getColumn(i); - each.setPreferredWidth(MyTableModel.getColumnWidth(i, new Dimension(600, 400).width)); - } - - String message = "Some conflicts were found in the installation area.

      "; - - if (proceed) { - message += "Please select desired solutions from the " + MyTableModel.COLUMNS[MyTableModel.OPTIONS_COLUMN_INDEX] + - " column and press " + PROCEED_BUTTON_TITLE + ".
      " + - "If you do not want to proceed with the update, please press " + CANCEL_BUTTON_TITLE + "."; - } else { - message += "Some of the conflicts below do not have a solution, so the patch cannot be applied.
      " + - "Press " + CANCEL_BUTTON_TITLE + " to exit."; - } - - JLabel label = new JLabel(message); - label.setBorder(LABEL_BORDER); - dialog.add(label, BorderLayout.NORTH); - dialog.add(new JScrollPane(table), BorderLayout.CENTER); - dialog.add(buttonsPanel, BorderLayout.SOUTH); - - dialog.getRootPane().setBorder(FRAME_BORDER); - - dialog.setSize(new Dimension(600, 400)); - dialog.setLocationRelativeTo(null); - dialog.setVisible(true); - - result.putAll(model.getResult()); + buttonsPanel.add(proceedButton); + dialog.getRootPane().setDefaultButton(proceedButton); + } else { + dialog.getRootPane().setDefaultButton(cancelButton); } + + JTable table = new JTable(); + + table.setCellSelectionEnabled(true); + table.setDefaultEditor(ValidationResult.Option.class, new MyCellEditor()); + table.setDefaultRenderer(Object.class, new MyCellRenderer()); + MyTableModel model = new MyTableModel(validationResults); + table.setModel(model); + + for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) { + TableColumn each = table.getColumnModel().getColumn(i); + each.setPreferredWidth(MyTableModel.getColumnWidth(i, new Dimension(600, 400).width)); + } + + String message = "Some conflicts were found in the installation area.

      "; + + if (proceed) { + message += "Please select desired solutions from the " + MyTableModel.COLUMNS[MyTableModel.OPTIONS_COLUMN_INDEX] + + " column and press " + PROCEED_BUTTON_TITLE + ".
      " + + "If you do not want to proceed with the update, please press " + CANCEL_BUTTON_TITLE + "."; + } else { + message += "Some of the conflicts below do not have a solution, so the patch cannot be applied.
      " + + "Press " + CANCEL_BUTTON_TITLE + " to exit."; + } + + JLabel label = new JLabel(message); + label.setBorder(LABEL_BORDER); + dialog.add(label, BorderLayout.NORTH); + dialog.add(new JScrollPane(table), BorderLayout.CENTER); + dialog.add(buttonsPanel, BorderLayout.SOUTH); + + dialog.getRootPane().setBorder(FRAME_BORDER); + + dialog.setSize(new Dimension(600, 400)); + dialog.setLocationRelativeTo(null); + dialog.setVisible(true); + + result.putAll(model.getResult()); }); } catch (InterruptedException e) { diff --git a/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconBuilder.java b/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconBuilder.java index b1d309251ed9..8d5c2f6ea0e3 100644 --- a/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconBuilder.java +++ b/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconBuilder.java @@ -57,13 +57,8 @@ import java.util.*; */ public class NavigationGutterIconBuilder { @NonNls private static final String PATTERN = "    {0}"; - private static final NotNullFunction> DEFAULT_PSI_CONVERTOR = new NotNullFunction>() { - @Override - @NotNull - public Collection fun(final PsiElement element) { - return ContainerUtil.createMaybeSingletonList(element); - } - }; + private static final NotNullFunction> DEFAULT_PSI_CONVERTOR = + element -> ContainerUtil.createMaybeSingletonList(element); private final Icon myIcon; private final NotNullFunction> myConverter; @@ -78,30 +73,16 @@ public class NavigationGutterIconBuilder { private Computable myCellRenderer; private NullableFunction myNamer = ElementPresentationManager.namer(); private final NotNullFunction> myGotoRelatedItemProvider; - public static final NotNullFunction> DEFAULT_DOM_CONVERTOR = new NotNullFunction>() { - @Override - @NotNull - public Collection fun(final DomElement o) { - return ContainerUtil.createMaybeSingletonList(o.getXmlElement()); - } - }; - public static final NotNullFunction> DOM_GOTO_RELATED_ITEM_PROVIDER = new NotNullFunction>() { - @NotNull - @Override - public Collection fun(DomElement dom) { - if (dom.getXmlElement() != null) { - return Collections.singletonList(new DomGotoRelatedItem(dom)); - } - return Collections.emptyList(); - } - }; - public static final NotNullFunction> PSI_GOTO_RELATED_ITEM_PROVIDER = new NotNullFunction>() { - @NotNull - @Override - public Collection fun(PsiElement dom) { - return Collections.singletonList(new GotoRelatedItem(dom, "XML")); + public static final NotNullFunction> DEFAULT_DOM_CONVERTOR = + o -> ContainerUtil.createMaybeSingletonList(o.getXmlElement()); + public static final NotNullFunction> DOM_GOTO_RELATED_ITEM_PROVIDER = dom -> { + if (dom.getXmlElement() != null) { + return Collections.singletonList(new DomGotoRelatedItem(dom)); } + return Collections.emptyList(); }; + public static final NotNullFunction> PSI_GOTO_RELATED_ITEM_PROVIDER = + dom -> Collections.singletonList(new GotoRelatedItem(dom, "XML")); protected NavigationGutterIconBuilder(@NotNull final Icon icon, @NotNull NotNullFunction> converter) { this(icon, converter, null); diff --git a/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconRenderer.java b/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconRenderer.java index 43108617914d..c3f461122cc5 100644 --- a/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconRenderer.java +++ b/xml/dom-impl/src/com/intellij/codeInsight/navigation/NavigationGutterIconRenderer.java @@ -67,11 +67,8 @@ public abstract class NavigationGutterIconRenderer extends GutterIconRenderer } public List getTargetElements() { - return ContainerUtil.mapNotNull(myPointers.getValue(), new NullableFunction() { - @Override - public PsiElement fun(final SmartPsiElementPointer smartPsiElementPointer) { - return smartPsiElementPointer.getElement(); - } + return ContainerUtil.mapNotNull(myPointers.getValue(), (NullableFunction)smartPsiElementPointer -> { + return smartPsiElementPointer.getElement(); }); } diff --git a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java index c147324e75c6..9df04c4571d3 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java +++ b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java @@ -106,20 +106,11 @@ public class DomElementsErrorPanel extends JPanel implements CommittablePanel, H } private void addUpdateRequest() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - - @Override - public void run() { - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (myProject.isOpen() && !myProject.isDisposed()) { - updatePanel(); - } - } - }, ALARM_PERIOD); + ApplicationManager.getApplication().invokeLater(() -> myAlarm.addRequest(() -> { + if (myProject.isOpen() && !myProject.isDisposed()) { + updatePanel(); } - }); + }, ALARM_PERIOD)); } @Override diff --git a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java index 6fb09e193270..f05467113d6d 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java +++ b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsHighlightingUtil.java @@ -42,12 +42,9 @@ public class DomElementsHighlightingUtil { @Nullable public static ProblemDescriptor createProblemDescriptors(final InspectionManager manager, final DomElementProblemDescriptor problemDescriptor) { final ProblemHighlightType type = getProblemHighlightType(problemDescriptor); - return createProblemDescriptors(problemDescriptor, new Function, ProblemDescriptor>() { - @Override - public ProblemDescriptor fun(final Pair s) { - return manager - .createProblemDescriptor(s.second, s.first, problemDescriptor.getDescriptionTemplate(), type, true, problemDescriptor.getFixes()); - } + return createProblemDescriptors(problemDescriptor, s -> { + return manager + .createProblemDescriptor(s.second, s.first, problemDescriptor.getDescriptionTemplate(), type, true, problemDescriptor.getFixes()); }); } @@ -68,27 +65,24 @@ public class DomElementsHighlightingUtil { @Nullable public static Annotation createAnnotation(final DomElementProblemDescriptor problemDescriptor) { - return createProblemDescriptors(problemDescriptor, new Function, Annotation>() { - @Override - public Annotation fun(final Pair s) { - String text = problemDescriptor.getDescriptionTemplate(); - if (StringUtil.isEmpty(text)) text = null; - final HighlightSeverity severity = problemDescriptor.getHighlightSeverity(); + return createProblemDescriptors(problemDescriptor, s -> { + String text = problemDescriptor.getDescriptionTemplate(); + if (StringUtil.isEmpty(text)) text = null; + final HighlightSeverity severity = problemDescriptor.getHighlightSeverity(); - TextRange range = s.first; - if (text == null) range = TextRange.from(range.getStartOffset(), 0); - range = range.shiftRight(s.second.getTextRange().getStartOffset()); - final Annotation annotation = createAnnotation(severity, range, text); + TextRange range = s.first; + if (text == null) range = TextRange.from(range.getStartOffset(), 0); + range = range.shiftRight(s.second.getTextRange().getStartOffset()); + final Annotation annotation = createAnnotation(severity, range, text); - if (problemDescriptor instanceof DomElementResolveProblemDescriptor) { - annotation.setTextAttributes(CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES); - } - - for(LocalQuickFix fix:problemDescriptor.getFixes()) { - if (fix instanceof IntentionAction) annotation.registerFix((IntentionAction)fix); - } - return annotation; + if (problemDescriptor instanceof DomElementResolveProblemDescriptor) { + annotation.setTextAttributes(CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES); } + + for(LocalQuickFix fix:problemDescriptor.getFixes()) { + if (fix instanceof IntentionAction) annotation.registerFix((IntentionAction)fix); + } + return annotation; }); } diff --git a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java index 8bde5190502c..e9404f24dd5e 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java @@ -43,12 +43,9 @@ public class DomElementsProblemsHolderImpl implements DomElementsProblemsHolder private final List myAnnotations = new ArrayList(); private final Function> myDomProblemsGetter = - new Function>() { - @Override - public List fun(final DomElement s) { - final Map, List> map = myCachedErrors.get(s); - return map != null ? ContainerUtil.concat(map.values()) : Collections.emptyList(); - } + s -> { + final Map, List> map = myCachedErrors.get(s); + return map != null ? ContainerUtil.concat(map.values()) : Collections.emptyList(); }; private final DomFileElement myElement; diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/AttributeChildInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/AttributeChildInvocationHandler.java index 1222b4b224ab..a484875cdd59 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/AttributeChildInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/AttributeChildInvocationHandler.java @@ -123,16 +123,13 @@ public class AttributeChildInvocationHandler extends DomInvocationHandler { + try { + setXmlElement(null); + tag.setAttribute(getXmlElementName(), getXmlApiCompatibleNamespace(getParentHandler()), null); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); fireUndefinedEvent(); @@ -178,17 +175,14 @@ public class AttributeChildInvocationHandler extends DomInvocationHandler { + try { + XmlAttribute attribute = tag.setAttribute(attributeName, namespace, newValue); + setXmlElement(attribute); + getManager().cacheHandler(DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY, attribute, AttributeChildInvocationHandler.this); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); final DomElement proxy = getProxy(); diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/CollectionChildDescriptionImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/CollectionChildDescriptionImpl.java index 669a615a7f3a..02052c74b2eb 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/CollectionChildDescriptionImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/CollectionChildDescriptionImpl.java @@ -102,13 +102,10 @@ public class CollectionChildDescriptionImpl extends DomChildDescriptionImpl impl final JavaMethod getterMethod = getGetterMethod(); if (getterMethod == null) { final Collection collection = ModelMergerUtil.getFilteredImplementations(element); - return ContainerUtil.concat(collection, new Function>() { - @Override - public Collection fun(final DomElement domElement) { - final DomInvocationHandler handler = DomManagerImpl.getDomInvocationHandler(domElement); - assert handler != null : domElement; - return handler.getCollectionChildren(CollectionChildDescriptionImpl.this); - } + return ContainerUtil.concat(collection, (Function>)domElement -> { + final DomInvocationHandler handler1 = DomManagerImpl.getDomInvocationHandler(domElement); + assert handler1 != null : domElement; + return handler1.getCollectionChildren(CollectionChildDescriptionImpl.this); }); } //noinspection unchecked diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java index 0d8ace4c24f1..30b7b99d2687 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java @@ -147,12 +147,7 @@ public abstract class DomInvocationHandler setTagValue(tag, value)); myManager.fireEvent(new DomEvent(getProxy(), false)); } @@ -166,44 +161,41 @@ public abstract class DomInvocationHandler { + ensureXmlElementExists(); + final DomInvocationHandler otherInvocationHandler = DomManagerImpl.getDomInvocationHandler(other); + assert otherInvocationHandler != null : other; - final DomGenericInfoEx genericInfo = otherInvocationHandler.getGenericInfo(); - for (final AttributeChildDescriptionImpl description : genericInfo.getAttributeChildrenDescriptions()) { - description.getDomAttributeValue(DomInvocationHandler.this).setStringValue(description.getDomAttributeValue(other).getStringValue()); - } - for (final DomFixedChildDescription description : genericInfo.getFixedChildrenDescriptions()) { - final List list = description.getValues(getProxy()); - final List otherValues = description.getValues(other); - for (int i = 0; i < list.size(); i++) { - final DomElement otherValue = otherValues.get(i); - final DomElement value = list.get(i); - if (!DomUtil.hasXml(otherValue)) { - value.undefine(); - } - else { - value.copyFrom(otherValue); - } - } - } - for (final DomCollectionChildDescription description : genericInfo.getCollectionChildrenDescriptions()) { - for (final DomElement value : description.getValues(getProxy())) { + final DomGenericInfoEx genericInfo = otherInvocationHandler.getGenericInfo(); + for (final AttributeChildDescriptionImpl description : genericInfo.getAttributeChildrenDescriptions()) { + description.getDomAttributeValue(DomInvocationHandler.this).setStringValue(description.getDomAttributeValue(other).getStringValue()); + } + for (final DomFixedChildDescription description : genericInfo.getFixedChildrenDescriptions()) { + final List list = description.getValues(getProxy()); + final List otherValues = description.getValues(other); + for (int i = 0; i < list.size(); i++) { + final DomElement otherValue = otherValues.get(i); + final DomElement value = list.get(i); + if (!DomUtil.hasXml(otherValue)) { value.undefine(); } - for (final DomElement otherValue : description.getValues(other)) { - description.addValue(getProxy(), otherValue.getDomElementType()).copyFrom(otherValue); + else { + value.copyFrom(otherValue); } } - - final String stringValue = otherInvocationHandler.getValue(); - if (StringUtil.isNotEmpty(stringValue)) { - setValue(stringValue); + } + for (final DomCollectionChildDescription description : genericInfo.getCollectionChildrenDescriptions()) { + for (final DomElement value : description.getValues(getProxy())) { + value.undefine(); } + for (final DomElement otherValue : description.getValues(other)) { + description.addValue(getProxy(), otherValue.getDomElementType()).copyFrom(otherValue); + } + } + + final String stringValue = otherInvocationHandler.getValue(); + if (StringUtil.isNotEmpty(stringValue)) { + setValue(stringValue); } }); @@ -842,25 +834,18 @@ public abstract class DomInvocationHandler stubs = myStub.getChildrenByName(xmlName.getLocalName(), xmlName.getNamespaceKey()); - return ContainerUtil.map(stubs, new Function() { - @Override - public DomElement fun(DomStub stub) { - return stub.getOrCreateHandler((DomChildDescriptionImpl)description, myManager).getProxy(); - } + return ContainerUtil.map(stubs, stub -> { + return stub.getOrCreateHandler((DomChildDescriptionImpl)description, myManager).getProxy(); }); } else if (description instanceof CustomDomChildrenDescriptionImpl) { List stubs = myStub.getChildrenStubs(); - return ContainerUtil.mapNotNull(stubs, new NullableFunction() { - @Nullable - @Override - public DomElement fun(DomStub stub) { - if (stub instanceof ElementStub && stub.isCustom()) { - EvaluatedXmlName name = new DummyEvaluatedXmlName(stub.getName(), ""); - return new CollectionElementInvocationHandler(name, (CustomDomChildrenDescriptionImpl)description, myManager, (ElementStub)stub).getProxy(); - } - return null; + return ContainerUtil.mapNotNull(stubs, (NullableFunction)stub -> { + if (stub instanceof ElementStub && stub.isCustom()) { + EvaluatedXmlName name = new DummyEvaluatedXmlName(stub.getName(), ""); + return new CollectionElementInvocationHandler(name, (CustomDomChildrenDescriptionImpl)description, myManager, (ElementStub)stub).getProxy(); } + return null; }); } } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomRootInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomRootInvocationHandler.java index f7d831ebec23..4ee53c43fddc 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomRootInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomRootInvocationHandler.java @@ -135,19 +135,16 @@ public class DomRootInvocationHandler extends DomInvocationHandler"); - result[0] = ((XmlDocument)xmlFile.getDocument().replace(((XmlFile)tag.getContainingFile()).getDocument())).getRootTag(); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } + getManager().runChange(() -> { + try { + final String namespace = getXmlElementNamespace(); + @NonNls final String nsDecl = StringUtil.isEmpty(namespace) ? "" : " xmlns=\"" + namespace + "\""; + final XmlFile xmlFile = getFile(); + final XmlTag tag = XmlElementFactory.getInstance(xmlFile.getProject()).createTagFromText("<" + getXmlElementName() + nsDecl + "/>"); + result[0] = ((XmlDocument)xmlFile.getDocument().replace(((XmlFile)tag.getContainingFile()).getDocument())).getRootTag(); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); return result[0]; diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomSemContributor.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomSemContributor.java index d1145d297dc2..126d7be818ef 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomSemContributor.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomSemContributor.java @@ -62,100 +62,89 @@ public class DomSemContributor extends SemContributor { @Override public void registerSemProviders(SemRegistrar registrar) { - registrar.registerSemElementProvider(DomManagerImpl.FILE_DESCRIPTION_KEY, xmlFile(), new NullableFunction() { - @Override - public FileDescriptionCachedValueProvider fun(XmlFile xmlFile) { - ApplicationManager.getApplication().assertReadAccessAllowed(); - return new FileDescriptionCachedValueProvider(DomManagerImpl.getDomManager(xmlFile.getProject()), xmlFile); - } + registrar.registerSemElementProvider(DomManagerImpl.FILE_DESCRIPTION_KEY, xmlFile(), xmlFile -> { + ApplicationManager.getApplication().assertReadAccessAllowed(); + return new FileDescriptionCachedValueProvider(DomManagerImpl.getDomManager(xmlFile.getProject()), xmlFile); }); - registrar.registerSemElementProvider(DomManagerImpl.DOM_HANDLER_KEY, xmlTag().withParent(psiElement(XmlElementType.XML_DOCUMENT).withParent(xmlFile())), new NullableFunction() { - @Override - public DomInvocationHandler fun(XmlTag xmlTag) { - final FileDescriptionCachedValueProvider provider = - mySemService.getSemElement(DomManagerImpl.FILE_DESCRIPTION_KEY, xmlTag.getContainingFile()); - assert provider != null; - final DomFileElementImpl element = provider.getFileElement(); - if (element != null) { - final DomRootInvocationHandler handler = element.getRootHandler(); - if (handler.getXmlTag() == xmlTag) { - return handler; - } - } - return null; - } - }); + registrar.registerSemElementProvider(DomManagerImpl.DOM_HANDLER_KEY, xmlTag().withParent(psiElement(XmlElementType.XML_DOCUMENT).withParent(xmlFile())), + xmlTag -> { + final FileDescriptionCachedValueProvider provider = + mySemService.getSemElement(DomManagerImpl.FILE_DESCRIPTION_KEY, xmlTag.getContainingFile()); + assert provider != null; + final DomFileElementImpl element = provider.getFileElement(); + if (element != null) { + final DomRootInvocationHandler handler = element.getRootHandler(); + if (handler.getXmlTag() == xmlTag) { + return handler; + } + } + return null; + }); final ElementPattern nonRootTag = xmlTag().withParent(or(xmlTag(), xmlEntityRef().withParent(xmlTag()))); - registrar.registerSemElementProvider(DomManagerImpl.DOM_INDEXED_HANDLER_KEY, nonRootTag, new NullableFunction() { - @Override - public IndexedElementInvocationHandler fun(XmlTag tag) { - final XmlTag parentTag = PhysicalDomParentStrategy.getParentTag(tag); - assert parentTag != null; - DomInvocationHandler parent = getParentDom(parentTag); - if (parent == null) return null; + registrar.registerSemElementProvider(DomManagerImpl.DOM_INDEXED_HANDLER_KEY, nonRootTag, tag -> { + final XmlTag parentTag = PhysicalDomParentStrategy.getParentTag(tag); + assert parentTag != null; + DomInvocationHandler parent = getParentDom(parentTag); + if (parent == null) return null; - final String localName = tag.getLocalName(); - final String namespace = tag.getNamespace(); + final String localName = tag.getLocalName(); + final String namespace = tag.getNamespace(); - final DomFixedChildDescription description = - findChildrenDescription(parent.getGenericInfo().getFixedChildrenDescriptions(), tag, parent); + final DomFixedChildDescription description = + findChildrenDescription(parent.getGenericInfo().getFixedChildrenDescriptions(), tag, parent); - if (description != null) { + if (description != null) { - final int totalCount = description.getCount(); + final int totalCount = description.getCount(); - int index = 0; - PsiElement current = tag; - while (true) { - current = current.getPrevSibling(); - if (current == null) { - break; - } - if (current instanceof XmlTag) { - final XmlTag xmlTag = (XmlTag)current; - if (localName.equals(xmlTag.getLocalName()) && namespace.equals(xmlTag.getNamespace())) { - index++; - if (index >= totalCount) { - return null; - } + int index = 0; + PsiElement current = tag; + while (true) { + current = current.getPrevSibling(); + if (current == null) { + break; + } + if (current instanceof XmlTag) { + final XmlTag xmlTag = (XmlTag)current; + if (localName.equals(xmlTag.getLocalName()) && namespace.equals(xmlTag.getNamespace())) { + index++; + if (index >= totalCount) { + return null; } } } - - final DomManagerImpl myDomManager = parent.getManager(); - return new IndexedElementInvocationHandler(parent.createEvaluatedXmlName(description.getXmlName()), (FixedChildDescriptionImpl)description, index, - new PhysicalDomParentStrategy(tag, myDomManager), myDomManager, null); } - return null; + + final DomManagerImpl myDomManager = parent.getManager(); + return new IndexedElementInvocationHandler(parent.createEvaluatedXmlName(description.getXmlName()), (FixedChildDescriptionImpl)description, index, + new PhysicalDomParentStrategy(tag, myDomManager), myDomManager, null); } + return null; }); - registrar.registerSemElementProvider(DomManagerImpl.DOM_COLLECTION_HANDLER_KEY, nonRootTag, new NullableFunction() { - @Override - public CollectionElementInvocationHandler fun(XmlTag tag) { - final XmlTag parentTag = PhysicalDomParentStrategy.getParentTag(tag); - assert parentTag != null; - DomInvocationHandler parent = getParentDom(parentTag); - if (parent == null) return null; + registrar.registerSemElementProvider(DomManagerImpl.DOM_COLLECTION_HANDLER_KEY, nonRootTag, tag -> { + final XmlTag parentTag = PhysicalDomParentStrategy.getParentTag(tag); + assert parentTag != null; + DomInvocationHandler parent = getParentDom(parentTag); + if (parent == null) return null; - final DomCollectionChildDescription description = findChildrenDescription(parent.getGenericInfo().getCollectionChildrenDescriptions(), tag, parent); - if (description != null) { - DomStub parentStub = parent.getStub(); - if (parentStub != null) { - int index = ArrayUtil.indexOf(parentTag.findSubTags(tag.getName(), tag.getNamespace()), tag); - ElementStub stub = parentStub.getElementStub(tag.getLocalName(), index); - if (stub != null) { - XmlName name = description.getXmlName(); - EvaluatedXmlNameImpl evaluatedXmlName = EvaluatedXmlNameImpl.createEvaluatedXmlName(name, name.getNamespaceKey(), true); - return new CollectionElementInvocationHandler(evaluatedXmlName, (AbstractDomChildDescriptionImpl)description, parent.getManager(), stub); - } + final DomCollectionChildDescription description = findChildrenDescription(parent.getGenericInfo().getCollectionChildrenDescriptions(), tag, parent); + if (description != null) { + DomStub parentStub = parent.getStub(); + if (parentStub != null) { + int index = ArrayUtil.indexOf(parentTag.findSubTags(tag.getName(), tag.getNamespace()), tag); + ElementStub stub = parentStub.getElementStub(tag.getLocalName(), index); + if (stub != null) { + XmlName name = description.getXmlName(); + EvaluatedXmlNameImpl evaluatedXmlName = EvaluatedXmlNameImpl.createEvaluatedXmlName(name, name.getNamespaceKey(), true); + return new CollectionElementInvocationHandler(evaluatedXmlName, (AbstractDomChildDescriptionImpl)description, parent.getManager(), stub); } - return new CollectionElementInvocationHandler(description.getType(), tag, (AbstractCollectionChildDescription)description, parent, null); } - return null; + return new CollectionElementInvocationHandler(description.getType(), tag, (AbstractCollectionChildDescription)description, parent, null); } + return null; }); registrar.registerSemElementProvider(DomManagerImpl.DOM_CUSTOM_HANDLER_KEY, nonRootTag, new NullableFunction() { @@ -204,39 +193,33 @@ public class DomSemContributor extends SemContributor { } }); - registrar.registerSemElementProvider(DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY, xmlAttribute(), new NullableFunction() { - @Override - public AttributeChildInvocationHandler fun(final XmlAttribute attribute) { - final XmlTag tag = PhysicalDomParentStrategy.getParentTag(attribute); - final DomInvocationHandler handler = tag == null ? null : getParentDom(tag); - if (handler == null) return null; + registrar.registerSemElementProvider(DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY, xmlAttribute(), attribute -> { + final XmlTag tag = PhysicalDomParentStrategy.getParentTag(attribute); + final DomInvocationHandler handler = tag == null ? null : getParentDom(tag); + if (handler == null) return null; - final String localName = attribute.getLocalName(); - final Ref result = Ref.create(null); - handler.getGenericInfo().processAttributeChildrenDescriptions(new Processor() { - @Override - public boolean process(AttributeChildDescriptionImpl description) { - if (description.getXmlName().getLocalName().equals(localName)) { - final EvaluatedXmlName evaluatedXmlName = handler.createEvaluatedXmlName(description.getXmlName()); + final String localName = attribute.getLocalName(); + final Ref result = Ref.create(null); + handler.getGenericInfo().processAttributeChildrenDescriptions(description -> { + if (description.getXmlName().getLocalName().equals(localName)) { + final EvaluatedXmlName evaluatedXmlName = handler.createEvaluatedXmlName(description.getXmlName()); - final String ns = evaluatedXmlName.getNamespace(tag, handler.getFile()); - //see XmlTagImpl.getAttribute(localName, namespace) - if (ns.equals(tag.getNamespace()) && localName.equals(attribute.getName()) || - ns.equals(attribute.getNamespace())) { - final DomManagerImpl myDomManager = handler.getManager(); - final AttributeChildInvocationHandler attributeHandler = - new AttributeChildInvocationHandler(evaluatedXmlName, description, myDomManager, - new PhysicalDomParentStrategy(attribute, myDomManager), null); - result.set(attributeHandler); - return false; - } - } - return true; + final String ns = evaluatedXmlName.getNamespace(tag, handler.getFile()); + //see XmlTagImpl.getAttribute(localName, namespace) + if (ns.equals(tag.getNamespace()) && localName.equals(attribute.getName()) || + ns.equals(attribute.getNamespace())) { + final DomManagerImpl myDomManager = handler.getManager(); + final AttributeChildInvocationHandler attributeHandler = + new AttributeChildInvocationHandler(evaluatedXmlName, description, myDomManager, + new PhysicalDomParentStrategy(attribute, myDomManager), null); + result.set(attributeHandler); + return false; } - }); + } + return true; + }); - return result.get(); - } + return result.get(); }); } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DynamicGenericInfo.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DynamicGenericInfo.java index ee73684a8748..2712dc9a4dff 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/DynamicGenericInfo.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DynamicGenericInfo.java @@ -130,11 +130,8 @@ public class DynamicGenericInfo extends DomGenericInfoEx { } final List customs = registrar.getCustoms(); - myCustomChildren = customs.isEmpty() ? null : ContainerUtil.map(customs, new Function() { - @Override - public CustomDomChildrenDescriptionImpl fun(DomExtensionImpl extension) { - return new CustomDomChildrenDescriptionImpl(extension); - } + myCustomChildren = customs.isEmpty() ? null : ContainerUtil.map(customs, extension -> { + return new CustomDomChildrenDescriptionImpl(extension); }); } @@ -275,12 +272,9 @@ public class DynamicGenericInfo extends DomGenericInfoEx { @Override public boolean processAttributeChildrenDescriptions(final Processor processor) { final Set visited = new THashSet(); - if (!myStaticGenericInfo.processAttributeChildrenDescriptions(new Processor() { - @Override - public boolean process(AttributeChildDescriptionImpl attributeChildDescription) { - visited.add(attributeChildDescription); - return processor.process(attributeChildDescription); - } + if (!myStaticGenericInfo.processAttributeChildrenDescriptions(attributeChildDescription -> { + visited.add(attributeChildDescription); + return processor.process(attributeChildDescription); })) { return false; } diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/ImplementationClassCache.java b/xml/dom-impl/src/com/intellij/util/xml/impl/ImplementationClassCache.java index 6a62938197cd..aca93d3c5579 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/ImplementationClassCache.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/ImplementationClassCache.java @@ -34,14 +34,11 @@ import java.util.TreeSet; * @author peter */ class ImplementationClassCache { - private static final Comparator CLASS_COMPARATOR = new Comparator() { - @Override - public int compare(final Class o1, final Class o2) { - if (o1.isAssignableFrom(o2)) return 1; - if (o2.isAssignableFrom(o1)) return -1; - if (o1.equals(o2)) return 0; - throw new AssertionError("Incompatible implementation classes: " + o1 + " & " + o2); - } + private static final Comparator CLASS_COMPARATOR = (o1, o2) -> { + if (o1.isAssignableFrom(o2)) return 1; + if (o2.isAssignableFrom(o1)) return -1; + if (o1.equals(o2)) return 0; + throw new AssertionError("Incompatible implementation classes: " + o1 + " & " + o2); }; diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/IndexedElementInvocationHandler.java b/xml/dom-impl/src/com/intellij/util/xml/impl/IndexedElementInvocationHandler.java index 0f29d940d671..d7e59273a33e 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/IndexedElementInvocationHandler.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/IndexedElementInvocationHandler.java @@ -87,16 +87,13 @@ public class IndexedElementInvocationHandler extends DomInvocationHandler { + try { + final XmlTag parentTag = parent.getXmlTag(); + newTag[0] = (XmlTag)parentTag.add(parent.createChildTag(getXmlName())); + } + catch (IncorrectOperationException e) { + LOG.error(e); } }); return newTag[0]; diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfo.java b/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfo.java index 8ce43dcd1f70..c20001f33681 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfo.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfo.java @@ -85,13 +85,8 @@ public class StaticGenericInfo extends DomGenericInfoEx { addAdders(description, builder.collectionClassAdders.get(name)); } - final NotNullFunction mapper = new NotNullFunction() { - @Override - @NotNull - public CollectionChildDescriptionImpl fun(final String xmlName) { - return ObjectUtils.assertNotNull(myCollections.findDescription(xmlName)); - } - }; + final NotNullFunction mapper = + xmlName -> ObjectUtils.assertNotNull(myCollections.findDescription(xmlName)); final Map getters = builder.getCompositeCollectionGetters(); for (final JavaMethodSignature signature : getters.keySet()) { myCompositeChildrenMethods.put(signature, ContainerUtil.map2Set(getters.get(signature), mapper)); @@ -179,20 +174,10 @@ public class StaticGenericInfo extends DomGenericInfoEx { } if (parameterTypes.length == 2 && parameterTypes[1].equals(Class.class)) { - return new Function() { - @Override - public Type fun(final Object[] s) { - return (Type)s[1]; - } - }; + return s -> (Type)s[1]; } - return new Function() { - @Override - public Type fun(final Object[] s) { - return method.getGenericReturnType(); - } - }; + return s -> method.getGenericReturnType(); } @@ -203,12 +188,7 @@ public class StaticGenericInfo extends DomGenericInfoEx { } if (parameterTypes.length == 2 && parameterTypes[1].equals(int.class)) { - return new Function() { - @Override - public Integer fun(final Object[] s) { - return (Integer)s[1]; - } - }; + return s -> (Integer)s[1]; } return new ConstantFunction(Integer.MAX_VALUE); diff --git a/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureViewBuilderProvider.java b/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureViewBuilderProvider.java index 88007741d179..e3682ee4fab8 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureViewBuilderProvider.java +++ b/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureViewBuilderProvider.java @@ -41,10 +41,5 @@ public final class DomStructureViewBuilderProvider implements XmlStructureViewBu } public static final Function DESCRIPTOR = - new Function() { - @Override - public DomService.StructureViewMode fun(DomElement element) { - return DomService.StructureViewMode.SHOW; - } - }; + element -> DomService.StructureViewMode.SHOW; } diff --git a/xml/dom-impl/src/com/intellij/util/xml/tree/actions/AddElementInCollectionAction.java b/xml/dom-impl/src/com/intellij/util/xml/tree/actions/AddElementInCollectionAction.java index 029feda9c59c..f21545391c1d 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/tree/actions/AddElementInCollectionAction.java +++ b/xml/dom-impl/src/com/intellij/util/xml/tree/actions/AddElementInCollectionAction.java @@ -219,12 +219,7 @@ public class AddElementInCollectionAction extends AddDomElementAction { protected void afterAddition(@NotNull final DomElement newElement) { final DomElement copy = newElement.createStableCopy(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myView.setSelectedDomElement(copy); - } - }); + ApplicationManager.getApplication().invokeLater(() -> myView.setSelectedDomElement(copy)); } } diff --git a/xml/dom-impl/src/com/intellij/util/xml/ui/DomUIFactoryImpl.java b/xml/dom-impl/src/com/intellij/util/xml/ui/DomUIFactoryImpl.java index fa638e057d85..729e4e1ba218 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/ui/DomUIFactoryImpl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/ui/DomUIFactoryImpl.java @@ -58,20 +58,10 @@ public class DomUIFactoryImpl extends DomUIFactory { private final ClassMap> myCustomCellEditorCreators = new ClassMap>(); public DomUIFactoryImpl() { - final Function booleanCreator = new Function() { - @Override - public TableCellEditor fun(final DomElement domElement) { - return new BooleanTableCellEditor(); - } - }; + final Function booleanCreator = domElement -> new BooleanTableCellEditor(); registerCustomCellEditor(Boolean.class, booleanCreator); registerCustomCellEditor(boolean.class, booleanCreator); - registerCustomCellEditor(String.class, new Function() { - @Override - public TableCellEditor fun(final DomElement domElement) { - return new DefaultCellEditor(removeBorder(new JTextField())); - } - }); + registerCustomCellEditor(String.class, domElement -> new DefaultCellEditor(removeBorder(new JTextField()))); Consumer[] extensions = Extensions.getExtensions(EXTENSION_POINT_NAME); for (Consumer extension : extensions) { extension.consume(this); diff --git a/xml/dom-impl/src/com/intellij/util/xml/ui/EditorTextFieldControl.java b/xml/dom-impl/src/com/intellij/util/xml/ui/EditorTextFieldControl.java index bb7f01df384e..28bb168058ae 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/ui/EditorTextFieldControl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/ui/EditorTextFieldControl.java @@ -119,19 +119,14 @@ public abstract class EditorTextFieldControl extends BaseM @Override protected void setValue(final String value) { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { + CommandProcessor.getInstance().runUndoTransparentAction(() -> new WriteAction() { @Override - public void run() { - new WriteAction() { - @Override - protected void run(@NotNull Result result) throws Throwable { - final T component = getComponent(); - final Document document = getEditorTextField(component).getDocument(); - document.replaceString(0, document.getTextLength(), value == null ? "" : value); - } - }.execute(); + protected void run(@NotNull Result result) throws Throwable { + final T component = getComponent(); + final Document document = getEditorTextField(component).getDocument(); + document.replaceString(0, document.getTextLength(), value == null ? "" : value); } - }); + }.execute()); } @Override @@ -141,44 +136,41 @@ public abstract class EditorTextFieldControl extends BaseM final EditorTextField textField = getEditorTextField(getComponent()); final Project project = getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!project.isOpen()) return; - if (!getDomWrapper().isValid()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (!project.isOpen()) return; + if (!getDomWrapper().isValid()) return; - final DomElement domElement = getDomElement(); - if (domElement == null || !domElement.isValid()) return; + final DomElement domElement1 = getDomElement(); + if (domElement1 == null || !domElement1.isValid()) return; - final DomElementAnnotationsManager manager = DomElementAnnotationsManager.getInstance(project); - final DomElementsProblemsHolder holder = manager.getCachedProblemHolder(domElement); - final List errorProblems = holder.getProblems(domElement); - final List warningProblems = new ArrayList(holder.getProblems(domElement, true, HighlightSeverity.WARNING)); - warningProblems.removeAll(errorProblems); + final DomElementAnnotationsManager manager = DomElementAnnotationsManager.getInstance(project); + final DomElementsProblemsHolder holder = manager.getCachedProblemHolder(domElement1); + final List errorProblems = holder.getProblems(domElement1); + final List warningProblems = new ArrayList(holder.getProblems(domElement1, true, HighlightSeverity.WARNING)); + warningProblems.removeAll(errorProblems); - Color background = getDefaultBackground(); - if (errorProblems.size() > 0 && textField.getText().trim().length() == 0) { - background = getErrorBackground(); - } - else if (warningProblems.size() > 0) { - background = getWarningBackground(); - } - - final Editor editor = textField.getEditor(); - if (editor != null) { - final MarkupModel markupModel = editor.getMarkupModel(); - markupModel.removeAllHighlighters(); - if (!errorProblems.isEmpty() && editor.getDocument().getLineCount() > 0) { - final TextAttributes attributes = SimpleTextAttributes.ERROR_ATTRIBUTES.toTextAttributes(); - attributes.setEffectType(EffectType.WAVE_UNDERSCORE); - attributes.setEffectColor(attributes.getForegroundColor()); - markupModel.addLineHighlighter(0, 0, attributes); - editor.getContentComponent().setToolTipText(errorProblems.get(0).getDescriptionTemplate()); - } - } - - textField.setBackground(background); + Color background = getDefaultBackground(); + if (errorProblems.size() > 0 && textField.getText().trim().length() == 0) { + background = getErrorBackground(); } + else if (warningProblems.size() > 0) { + background = getWarningBackground(); + } + + final Editor editor = textField.getEditor(); + if (editor != null) { + final MarkupModel markupModel = editor.getMarkupModel(); + markupModel.removeAllHighlighters(); + if (!errorProblems.isEmpty() && editor.getDocument().getLineCount() > 0) { + final TextAttributes attributes = SimpleTextAttributes.ERROR_ATTRIBUTES.toTextAttributes(); + attributes.setEffectType(EffectType.WAVE_UNDERSCORE); + attributes.setEffectColor(attributes.getForegroundColor()); + markupModel.addLineHighlighter(0, 0, attributes); + editor.getContentComponent().setToolTipText(errorProblems.get(0).getDescriptionTemplate()); + } + } + + textField.setBackground(background); }); } @@ -191,12 +183,9 @@ public abstract class EditorTextFieldControl extends BaseM @Override public void navigate(final DomElement element) { final EditorTextField field = getEditorTextField(getComponent()); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - field.requestFocus(); - field.selectAll(); - } + SwingUtilities.invokeLater(() -> { + field.requestFocus(); + field.selectAll(); }); } } diff --git a/xml/dom-impl/src/com/intellij/util/xml/ui/TextControl.java b/xml/dom-impl/src/com/intellij/util/xml/ui/TextControl.java index 51702cbea5f7..8fa0512c82c6 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/ui/TextControl.java +++ b/xml/dom-impl/src/com/intellij/util/xml/ui/TextControl.java @@ -62,13 +62,8 @@ public class TextControl extends EditorTextFieldControl { boundedComponent = new TextPanel(); } boundedComponent.removeAll(); - final Function factory = new Function() { - @Override - public Document fun(final String s) { - return PsiDocumentManager.getInstance(project) - .getDocument(PsiFileFactory.getInstance(project).createFileFromText("a.txt", PlainTextLanguage.INSTANCE, "", true, false)); - } - }; + final Function factory = s -> PsiDocumentManager.getInstance(project) + .getDocument(PsiFileFactory.getInstance(project).createFileFromText("a.txt", PlainTextLanguage.INSTANCE, "", true, false)); final TextPanel boundedComponent1 = boundedComponent; final EditorTextField editorTextField = new EditorTextField(factory.fun(""), project, FileTypes.PLAIN_TEXT) { @Override diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ElementPresentationManager.java b/xml/dom-openapi/src/com/intellij/util/xml/ElementPresentationManager.java index 72a33b8144d2..e3dc04a2597a 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ElementPresentationManager.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ElementPresentationManager.java @@ -55,13 +55,7 @@ public abstract class ElementPresentationManager { } }; - private final static Function DEFAULT_NAMER = new Function() { - @Override - @Nullable - public String fun(final Object element) { - return getElementName(element); - } - }; + private final static Function DEFAULT_NAMER = element -> getElementName(element); public static ElementPresentationManager getInstance() { return ServiceManager.getService(ElementPresentationManager.class); @@ -97,12 +91,8 @@ public abstract class ElementPresentationManager { private static final List> ourIconProviders = new ArrayList>(); static { - ourIconProviders.add(new NullableFunction() { - @Override - public Icon fun(final Object o) { - return o instanceof Iconable ? ((Iconable)o).getIcon(Iconable.ICON_FLAG_READ_STATUS) : null; - } - }); + ourIconProviders.add( + (NullableFunction)o -> o instanceof Iconable ? ((Iconable)o).getIcon(Iconable.ICON_FLAG_READ_STATUS) : null); } /** @@ -119,20 +109,10 @@ public abstract class ElementPresentationManager { public static NullableFunction NAMER() { - return new NullableFunction() { - @Override - public String fun(final T o) { - return getElementName(o); - } - }; + return o -> getElementName(o); } - public static final NullableFunction NAMER = new NullableFunction() { - @Override - public String fun(final Object o) { - return getElementName(o); - } - }; + public static final NullableFunction NAMER = o -> getElementName(o); public static NullableFunction namer() { //noinspection unchecked return (NullableFunction)NAMER; diff --git a/xml/dom-openapi/src/com/intellij/util/xml/GenericValueUtil.java b/xml/dom-openapi/src/com/intellij/util/xml/GenericValueUtil.java index 814f46ffe04f..ad3dbf217dd5 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/GenericValueUtil.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/GenericValueUtil.java @@ -30,18 +30,8 @@ public class GenericValueUtil { private GenericValueUtil() { } - public static NullableFunction STRING_VALUE = new NullableFunction() { - @Override - public String fun(final GenericValue genericValue) { - return genericValue.getStringValue(); - } - }; - public static NullableFunction OBJECT_VALUE = new NullableFunction() { - @Override - public Object fun(final GenericValue genericValue) { - return genericValue.getValue(); - } - }; + public static NullableFunction STRING_VALUE = genericValue -> genericValue.getStringValue(); + public static NullableFunction OBJECT_VALUE = genericValue -> genericValue.getValue(); public static boolean containsString(final Collection> collection, String value) { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/JavaNameStrategy.java b/xml/dom-openapi/src/com/intellij/util/xml/JavaNameStrategy.java index 998f4068b200..6125d149685b 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/JavaNameStrategy.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/JavaNameStrategy.java @@ -27,12 +27,7 @@ import java.util.Arrays; * @author peter */ public class JavaNameStrategy extends DomNameStrategy { - public static final Function DECAPITALIZE_FUNCTION = new Function() { - @Override - public String fun(final String s) { - return StringUtil.decapitalize(s); - } - }; + public static final Function DECAPITALIZE_FUNCTION = s -> StringUtil.decapitalize(s); @Override public final String convertName(String propertyName) { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/NamedEnumUtil.java b/xml/dom-openapi/src/com/intellij/util/xml/NamedEnumUtil.java index d8bada07207b..d1d4baf5a674 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/NamedEnumUtil.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/NamedEnumUtil.java @@ -23,18 +23,8 @@ import com.intellij.util.ReflectionUtil; * @author peter */ public class NamedEnumUtil { - private static final Function NAMED_SHOW = new Function() { - @Override - public String fun(final Enum s) { - return ((NamedEnum) s).getValue(); - } - }; - private static final Function SIMPLE_SHOW = new Function() { - @Override - public String fun(final Enum s) { - return s.name(); - } - }; + private static final Function NAMED_SHOW = s -> ((NamedEnum) s).getValue(); + private static final Function SIMPLE_SHOW = s -> s.name(); public static T getEnumElementByValue(final Class enumClass, final String value, Function show) { for (final T t : enumClass.getEnumConstants()) { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java b/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java index a951032b1b03..6755fc40fcb4 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java @@ -232,32 +232,26 @@ public abstract class DelimitedListConverter extends ResolvingConverter getSuperBindToElementFunction(final Ref ref) { - return new Function() { - @Override - public PsiElement fun(final PsiElement s) { - try { - return MyPsiReference.super.bindToElement(s); - } - catch (IncorrectOperationException e) { - ref.set(e); - } - return null; + return s -> { + try { + return MyPsiReference.super.bindToElement(s); } + catch (IncorrectOperationException e) { + ref.set(e); + } + return null; }; } private Function getSuperElementRenameFunction(final Ref ref) { - return new Function() { - @Override - public PsiElement fun(final String s) { - try { - return MyPsiReference.super.handleElementRename(s); - } - catch (IncorrectOperationException e) { - ref.set(e); - } - return null; + return s -> { + try { + return MyPsiReference.super.handleElementRename(s); } + catch (IncorrectOperationException e) { + ref.set(e); + } + return null; }; } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/highlighting/ResolvingElementQuickFix.java b/xml/dom-openapi/src/com/intellij/util/xml/highlighting/ResolvingElementQuickFix.java index 379d448b556e..695edb1e1820 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/highlighting/ResolvingElementQuickFix.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/highlighting/ResolvingElementQuickFix.java @@ -104,17 +104,12 @@ public class ResolvingElementQuickFix implements LocalQuickFix, IntentionAction } private void applyFix() { - chooseParent(myParents, new Consumer() { + chooseParent(myParents, parent -> new WriteCommandAction.Simple(parent.getManager().getProject(), DomUtil.getFile(parent)) { @Override - public void consume(final DomElement parent) { - new WriteCommandAction.Simple(parent.getManager().getProject(), DomUtil.getFile(parent)) { - @Override - protected void run() throws Throwable { - doFix(parent, myChildDescription, myNewName); - } - }.execute(); + protected void run() throws Throwable { + doFix(parent, myChildDescription, myNewName); } - }); + }.execute()); } protected DomElement doFix(DomElement parent, final DomCollectionChildDescription childDescription, String newName) { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/model/impl/DomModelImpl.java b/xml/dom-openapi/src/com/intellij/util/xml/model/impl/DomModelImpl.java index 5785048c281f..ffde2c300cff 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/model/impl/DomModelImpl.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/model/impl/DomModelImpl.java @@ -65,13 +65,11 @@ public class DomModelImpl implements DomModel { public T getMergedModel() { if (myMergedModel == null) { final DomManager domManager = DomManager.getDomManager(myProject); - return domManager.createModelMerger().mergeModels(myClass, ContainerUtil.mapNotNull(myConfigFiles, new NullableFunction() { - @Override - public T fun(XmlFile xmlFile) { - DomFileElement fileElement = domManager.getFileElement(xmlFile, myClass); - return fileElement == null ? null : fileElement.getRootElement(); - } - })); + return domManager.createModelMerger().mergeModels(myClass, ContainerUtil.mapNotNull(myConfigFiles, + (NullableFunction)xmlFile -> { + DomFileElement fileElement = domManager.getFileElement(xmlFile, myClass); + return fileElement == null ? null : fileElement.getRootElement(); + })); } return myMergedModel.getRootElement(); } @@ -86,11 +84,8 @@ public class DomModelImpl implements DomModel { @NotNull public List> getRoots() { if (myMergedModel == null) { - return ContainerUtil.mapNotNull(myConfigFiles, new NullableFunction>() { - @Override - public DomFileElement fun(XmlFile xmlFile) { - return DomManager.getDomManager(xmlFile.getProject()).getFileElement(xmlFile, myClass); - } + return ContainerUtil.mapNotNull(myConfigFiles, (NullableFunction>)xmlFile -> { + return DomManager.getDomManager(xmlFile.getProject()).getFileElement(xmlFile, myClass); }); } return myMergedModel instanceof MergedObject ? ((MergedObject) myMergedModel).getImplementations() : Collections.singletonList(myMergedModel); diff --git a/xml/dom-openapi/src/com/intellij/util/xml/tree/AbstractDomElementNode.java b/xml/dom-openapi/src/com/intellij/util/xml/tree/AbstractDomElementNode.java index 1beb01a0a1b3..fb1471f564c7 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/tree/AbstractDomElementNode.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/tree/AbstractDomElementNode.java @@ -31,12 +31,7 @@ abstract public class AbstractDomElementNode extends SimpleNode { public static final Key> TREE_NODES_HIDERS_KEY = Key.create("TREE_NODES_HIDERS_KEY"); - private final static Comparator INHERITORS_COMPARATOR = new Comparator() { - @Override - public int compare(final Class o1, final Class o2) { - return o1.isAssignableFrom(o2) ? 1 : -1; - } - }; + private final static Comparator INHERITORS_COMPARATOR = (o1, o2) -> o1.isAssignableFrom(o2) ? 1 : -1; private boolean isExpanded; diff --git a/xml/dom-openapi/src/com/intellij/util/xml/tree/BaseDomElementNode.java b/xml/dom-openapi/src/com/intellij/util/xml/tree/BaseDomElementNode.java index e5f08bbdf638..f0705e4bddff 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/tree/BaseDomElementNode.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/tree/BaseDomElementNode.java @@ -147,12 +147,7 @@ public class BaseDomElementNode extends AbstractDomElementNode { if (descriptor != null) { final XmlElementDescriptor[] childDescriptors = descriptor.getElementsDescriptors(tag); if (childDescriptors != null && childDescriptors.length > 1) { - return new Comparator() { - @Override - public int compare(final AbstractDomElementNode o1, final AbstractDomElementNode o2) { - return findDescriptor(childDescriptors, o1.getTagName()) - findDescriptor(childDescriptors, o2.getTagName()); - } - }; + return (o1, o2) -> findDescriptor(childDescriptors, o1.getTagName()) - findDescriptor(childDescriptors, o2.getTagName()); } } } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/tree/DomModelTreeView.java b/xml/dom-openapi/src/com/intellij/util/xml/tree/DomModelTreeView.java index 546cea563d1f..e98c66cf7143 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/tree/DomModelTreeView.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/tree/DomModelTreeView.java @@ -136,13 +136,10 @@ public class DomModelTreeView extends Wrapper implements DataProvider, Disposabl private void queueUpdate(final VirtualFile file) { if (file == null) return; if (getProject().isDisposed()) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (getProject().isDisposed()) return; - if (!file.isValid() || isRightFile(file)) { - myBuilder.updateFromRoot(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (getProject().isDisposed()) return; + if (!file.isValid() || isRightFile(file)) { + myBuilder.updateFromRoot(); } }); } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/AbstractTableView.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/AbstractTableView.java index cb26e85dcd36..ac22cb451ac3 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/AbstractTableView.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/AbstractTableView.java @@ -321,12 +321,8 @@ public abstract class AbstractTableView extends JPanel implements TypeSafeDat public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { final Object oldValue = getValueAt(rowIndex, columnIndex); if (!Comparing.equal(oldValue, aValue)) { - wrapValueSetting(getItems().get(rowIndex), new Runnable() { - @Override - public void run() { - MyListTableModel.super.setValueAt("".equals(aValue) ? null : aValue, rowIndex, columnIndex); - } - }); + wrapValueSetting(getItems().get(rowIndex), + () -> MyListTableModel.super.setValueAt("".equals(aValue) ? null : aValue, rowIndex, columnIndex)); } } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/BasicDomElementComponent.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/BasicDomElementComponent.java index 4acfbb48d936..ddbcc56b8993 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/BasicDomElementComponent.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/BasicDomElementComponent.java @@ -64,12 +64,9 @@ public abstract class BasicDomElementComponent extends Abs DomElementAnnotationsManager.getInstance(domElement.getManager().getProject()).addHighlightingListener(new DomElementAnnotationsManager.DomHighlightingListener() { @Override public void highlightingFinished(@NotNull final DomFileElement element) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (getComponent().isShowing() && element.isValid()) { - updateHighlighting(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (getComponent().isShowing() && element.isValid()) { + updateHighlighting(); } }); } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/ComboControl.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/ComboControl.java index 81b615f077f1..d130b959dbb5 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/ComboControl.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/ComboControl.java @@ -99,11 +99,8 @@ public class ComboControl extends BaseModifiableControl { final ResolvingConverter resolvingConverter = (ResolvingConverter)converter; final Collection variants = resolvingConverter.getVariants(context); final List> all = - new ArrayList>(ContainerUtil.map(variants, new Function>() { - @Override - public Pair fun(final Object s) { - return Pair.create(ElementPresentationManager.getElementName(s), ElementPresentationManager.getIcon(s)); - } + new ArrayList>(ContainerUtil.map(variants, s -> { + return Pair.create(ElementPresentationManager.getElementName(s), ElementPresentationManager.getIcon(s)); })); all.addAll(ContainerUtil.map(resolvingConverter.getAdditionalVariants(context), new Function() { @Override @@ -296,39 +293,36 @@ public class ComboControl extends BaseModifiableControl { final JComboBox comboBox = getComponent(); final Project project = getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!project.isOpen()) return; - if (!getDomWrapper().isValid()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (!project.isOpen()) return; + if (!getDomWrapper().isValid()) return; - final DomElement domElement = getDomElement(); - if (domElement == null || !domElement.isValid()) return; + final DomElement domElement1 = getDomElement(); + if (domElement1 == null || !domElement1.isValid()) return; - final DomElementAnnotationsManager manager = DomElementAnnotationsManager.getInstance(project); - final DomElementsProblemsHolder holder = manager.getCachedProblemHolder(domElement); - final List errorProblems = holder.getProblems(domElement); - final List warningProblems = holder.getProblems(domElement, true, HighlightSeverity.WARNING); + final DomElementAnnotationsManager manager = DomElementAnnotationsManager.getInstance(project); + final DomElementsProblemsHolder holder = manager.getCachedProblemHolder(domElement1); + final List errorProblems = holder.getProblems(domElement1); + final List warningProblems = holder.getProblems(domElement1, true, HighlightSeverity.WARNING); - Color background = getDefaultBackground(); - comboBox.setToolTipText(null); + Color background = getDefaultBackground(); + comboBox.setToolTipText(null); - if (errorProblems.size() > 0) { - background = getErrorBackground(); - comboBox.setToolTipText(TooltipUtils.getTooltipText(errorProblems)); - } - else if (warningProblems.size() > 0) { - background = getWarningBackground(); - comboBox.setToolTipText(TooltipUtils.getTooltipText(warningProblems)); - } - - final Pair pair = (Pair)comboBox.getSelectedItem(); - final String s = pair == null ? null : pair.first; - background = s != null && s.trim().length() > 0 ? getDefaultBackground() : background; - - comboBox.setBackground(background); - comboBox.getEditor().getEditorComponent().setBackground(background); + if (errorProblems.size() > 0) { + background = getErrorBackground(); + comboBox.setToolTipText(TooltipUtils.getTooltipText(errorProblems)); } + else if (warningProblems.size() > 0) { + background = getWarningBackground(); + comboBox.setToolTipText(TooltipUtils.getTooltipText(warningProblems)); + } + + final Pair pair = (Pair)comboBox.getSelectedItem(); + final String s = pair == null ? null : pair.first; + background = s != null && s.trim().length() > 0 ? getDefaultBackground() : background; + + comboBox.setBackground(background); + comboBox.getEditor().getEditorComponent().setBackground(background); }); } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/CommitablePanelUserActivityListener.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/CommitablePanelUserActivityListener.java index 6e008c500766..6027c49c3cef 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/CommitablePanelUserActivityListener.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/CommitablePanelUserActivityListener.java @@ -47,17 +47,14 @@ public class CommitablePanelUserActivityListener implements UserActivityListener if (myApplying) return; cancel(); cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - myApplying = true; - cancel(); - try { - applyChanges(); - } - finally { - myApplying = false; - } + myAlarm.addRequest(() -> { + myApplying = true; + cancel(); + try { + applyChanges(); + } + finally { + myApplying = false; } }, 717); } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java index 55b06c1db32b..8a15413424d7 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java @@ -223,25 +223,22 @@ public class DomCollectionControl extends DomUIControl imp } protected final void doRemove() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final int[] selected = myCollectionPanel.getTable().getSelectedRows(); - if (selected == null || selected.length == 0) return; - final List selectedElements = new ArrayList(selected.length); - for (final int i : selected) { - selectedElements.add(myCollectionElements.get(sortAdjustedIndex(i))); - } + ApplicationManager.getApplication().invokeLater(() -> { + final int[] selected = myCollectionPanel.getTable().getSelectedRows(); + if (selected == null || selected.length == 0) return; + final List selectedElements = new ArrayList(selected.length); + for (final int i : selected) { + selectedElements.add(myCollectionElements.get(sortAdjustedIndex(i))); + } - doRemove(selectedElements); - reset(); - int selection = selected[0]; - if (selection >= myCollectionElements.size()) { - selection = myCollectionElements.size() - 1; - } - if (selection >= 0) { - myCollectionPanel.getTable().setRowSelectionInterval(selection, selection); - } + doRemove(selectedElements); + reset(); + int selection = selected[0]; + if (selection >= myCollectionElements.size()) { + selection = myCollectionElements.size() - 1; + } + if (selection >= 0) { + myCollectionPanel.getTable().setRowSelectionInterval(selection, selection); } }); } diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/MockDomElementsEditor.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/MockDomElementsEditor.java index 1ec80708ece8..0f97759f4294 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/MockDomElementsEditor.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/MockDomElementsEditor.java @@ -151,12 +151,9 @@ public class MockDomElementsEditor { private T createMockElement(final Class aClass, final Module module) { final Project project = module.getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myFileEditor.isInitialised()) { - myContents.reset(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myFileEditor.isInitialised()) { + myContents.reset(); } }); final DomManager domManager = DomManager.getDomManager(project); diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java index ba86c0d2edb6..10e1b50bb41a 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java @@ -67,14 +67,11 @@ abstract public class PerspectiveFileEditor extends UserDataHolderBase implement public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (!isValid()) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (myUndoHelper.isShowing() && !getComponent().isShowing()) { - deselectNotify(); - } else if (!myUndoHelper.isShowing() && getComponent().isShowing()) { - selectNotify(); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (myUndoHelper.isShowing() && !getComponent().isShowing()) { + deselectNotify(); + } else if (!myUndoHelper.isShowing() && getComponent().isShowing()) { + selectNotify(); } }); diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementAction.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementAction.java index 4554511bce9e..74a7f5664455 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementAction.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementAction.java @@ -56,12 +56,9 @@ public class GenerateDomElementAction extends CodeInsightAction { return new CodeInsightActionHandler() { @Override public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { - final Runnable runnable = new Runnable() { - @Override - public void run() { - final DomElement element = myProvider.generate(project, editor, file); - myProvider.navigate(element); - } + final Runnable runnable = () -> { + final DomElement element = myProvider.generate(project, editor, file); + myProvider.navigate(element); }; if (GenerateDomElementAction.this.startInWriteAction()) { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementProvider.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementProvider.java index 1115521da25c..4336d66639fe 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementProvider.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/actions/generate/GenerateDomElementProvider.java @@ -50,12 +50,9 @@ public abstract class GenerateDomElementProvider { final DomElementNavigationProvider navigateProvider = getNavigationProviderName(project); if (navigateProvider != null && navigateProvider.canNavigate(copy)) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (!project.isDisposed()) { - doNavigate(navigateProvider, copy); - } + ApplicationManager.getApplication().invokeLater(() -> { + if (!project.isDisposed()) { + doNavigate(navigateProvider, copy); } }); } diff --git a/xml/dom-tests/tests/com/intellij/util/xml/DomChildrenTest.java b/xml/dom-tests/tests/com/intellij/util/xml/DomChildrenTest.java index 60cb32b093cb..7b5144d0ab46 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/DomChildrenTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/DomChildrenTest.java @@ -206,19 +206,16 @@ public class DomChildrenTest extends DomTestCase { assertTrue(child2.isValid()); assertEquals(element, child2.getParent()); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - child2.undefine(); - assertFalse(child2.isValid()); + WriteCommandAction.runWriteCommandAction(null, () -> { + child2.undefine(); + assertFalse(child2.isValid()); - oldChildren.remove(1); - assertEquals(oldChildren, Arrays.asList(element.getXmlTag().getSubTags())); + oldChildren.remove(1); + assertEquals(oldChildren, Arrays.asList(element.getXmlTag().getSubTags())); - assertEquals(Arrays.asList(child1, child3), element.getChildElements()); - assertCached(child1, element.getXmlTag().findSubTags("child-element")[0]); - assertCached(child3, element.getXmlTag().findSubTags("child-element")[1]); - } + assertEquals(Arrays.asList(child1, child3), element.getChildElements()); + assertCached(child1, element.getXmlTag().findSubTags("child-element")[0]); + assertCached(child3, element.getXmlTag().findSubTags("child-element")[1]); }); @@ -409,11 +406,8 @@ public class DomChildrenTest extends DomTestCase { public void testChildrenValidAfterUndefine() throws Throwable { final MyElement element = createElement(""); final MyElement child = element.getChild(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - element.undefine(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + element.undefine(); }); assertTrue(element.isValid()); @@ -483,33 +477,21 @@ public class DomChildrenTest extends DomTestCase { final XmlTag tag = myElement.getXmlTag(); final List customChildren = myElement.getCustomChildren(); assertOrderedEquals(customChildren, myElement.getGenericInfo().getCustomNameChildrenDescription().get(0).getValues(myElement)); - assertOrderedCollection(customChildren, new Consumer() { - @Override - public void consume(final MyElement element) { - assertInstanceOf(element, MyElement.class); - assertEquals(tag.getSubTags()[0], element.getXmlTag()); - } - }, new Consumer() { - @Override - public void consume(final MyElement element) { - assertInstanceOf(element, MyElement.class); - assertEquals(tag.getSubTags()[1], element.getXmlTag()); - } - }, new Consumer() { - @Override - public void consume(final MyElement element) { - assertInstanceOf(element, MyElement.class); - assertEquals(tag.getSubTags()[2], element.getXmlTag()); - } + assertOrderedCollection(customChildren, element -> { + assertInstanceOf(element, MyElement.class); + assertEquals(tag.getSubTags()[0], element.getXmlTag()); + }, element -> { + assertInstanceOf(element, MyElement.class); + assertEquals(tag.getSubTags()[1], element.getXmlTag()); + }, element -> { + assertInstanceOf(element, MyElement.class); + assertEquals(tag.getSubTags()[2], element.getXmlTag()); }); } private List getFixedPath(final DomElement element) { - return ContainerUtil.map2List(DomUtil.getFixedPath(element), new Function() { - @Override - public String fun(final JavaMethod s) { - return s.getName(); - } + return ContainerUtil.map2List(DomUtil.getFixedPath(element), s -> { + return s.getName(); }); } diff --git a/xml/dom-tests/tests/com/intellij/util/xml/DomExtensionsTest.java b/xml/dom-tests/tests/com/intellij/util/xml/DomExtensionsTest.java index c75fe42d2bc7..d1e980be2f5f 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/DomExtensionsTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/DomExtensionsTest.java @@ -75,66 +75,51 @@ public class DomExtensionsTest extends DomTestCase { public void testUseCustomConverter() throws Throwable { registerDomExtender(AttrDomExtender2.class); final MyElement myElement = createElement("", MyElement.class); - assertUnorderedCollection(getCustomChildren(myElement), new Consumer() { - @Override - public void consume(final DomElement element) { - final StringBuffer stringBuffer = ((GenericAttributeValue)element).getValue(); - assertEquals("zzz", stringBuffer.toString()); - assertInstanceOf(((GenericAttributeValue)element).getConverter(), StringBufferConverter.class); - assertNotNull(myElement.getGenericInfo().getAttributeChildDescription("xxx")); + assertUnorderedCollection(getCustomChildren(myElement), element -> { + final StringBuffer stringBuffer = ((GenericAttributeValue)element).getValue(); + assertEquals("zzz", stringBuffer.toString()); + assertInstanceOf(((GenericAttributeValue)element).getConverter(), StringBufferConverter.class); + assertNotNull(myElement.getGenericInfo().getAttributeChildDescription("xxx")); - Convert convert = element.getAnnotation(Convert.class); - assertNotNull(convert); - assertEquals(StringBufferConverter.class, convert.value()); - assertTrue(convert.soft()); - } - }, new Consumer() { - @Override - public void consume(final DomElement element) { - final StringBuffer stringBuffer = ((GenericAttributeValue)element).getValue(); - assertEquals("zzz", stringBuffer.toString()); - assertInstanceOf(((GenericAttributeValue)element).getConverter(), StringBufferConverter.class); - assertNotNull(myElement.getGenericInfo().getAttributeChildDescription("yyy")); + Convert convert = element.getAnnotation(Convert.class); + assertNotNull(convert); + assertEquals(StringBufferConverter.class, convert.value()); + assertTrue(convert.soft()); + }, element -> { + final StringBuffer stringBuffer = ((GenericAttributeValue)element).getValue(); + assertEquals("zzz", stringBuffer.toString()); + assertInstanceOf(((GenericAttributeValue)element).getConverter(), StringBufferConverter.class); + assertNotNull(myElement.getGenericInfo().getAttributeChildDescription("yyy")); - Convert convert = element.getAnnotation(Convert.class); - assertNotNull(convert); - assertEquals(StringBufferConverter.class, convert.value()); - assertFalse(convert.soft()); - } + Convert convert = element.getAnnotation(Convert.class); + assertNotNull(convert); + assertEquals(StringBufferConverter.class, convert.value()); + assertFalse(convert.soft()); }); } public void testFixedChildren() throws Throwable { registerDomExtender(FixedDomExtender.class); final MyElement myElement = createElement("zzz", MyElement.class); - assertUnorderedCollection(getCustomChildren(myElement), new Consumer() { - @Override - public void consume(final DomElement element) { - assertEquals(GenericDomValue.class, ReflectionUtil.getRawType(element.getDomElementType())); - final StringBuffer stringBuffer = ((GenericDomValue)element).getValue(); - assertEquals("zzz", stringBuffer.toString()); - assertInstanceOf(((GenericDomValue)element).getConverter(), MyStringBufferConverter.class); - assertNotNull(myElement.getGenericInfo().getFixedChildDescription("xxx")); + assertUnorderedCollection(getCustomChildren(myElement), element -> { + assertEquals(GenericDomValue.class, ReflectionUtil.getRawType(element.getDomElementType())); + final StringBuffer stringBuffer = ((GenericDomValue)element).getValue(); + assertEquals("zzz", stringBuffer.toString()); + assertInstanceOf(((GenericDomValue)element).getConverter(), MyStringBufferConverter.class); + assertNotNull(myElement.getGenericInfo().getFixedChildDescription("xxx")); - Convert convert = element.getAnnotation(Convert.class); - assertNotNull(convert); - assertEquals(MyStringBufferConverter.class, convert.value()); - assertTrue(convert.soft()); + Convert convert = element.getAnnotation(Convert.class); + assertNotNull(convert); + assertEquals(MyStringBufferConverter.class, convert.value()); + assertTrue(convert.soft()); - assertNotNull(element.getGenericInfo().getAttributeChildDescription("aaa")); - } - }, new Consumer() { - @Override - public void consume(final DomElement element) { - assertEquals("foo", ((MyElement) element).getAttr().getValue()); - assertNull(element.getAnnotation(Convert.class)); - } - }, new Consumer() { - @Override - public void consume(final DomElement element) { - assertEquals("bar", ((MyElement) element).getAttr().getValue()); - assertNull(element.getAnnotation(Convert.class)); - } + assertNotNull(element.getGenericInfo().getAttributeChildDescription("aaa")); + }, element -> { + assertEquals("foo", ((MyElement) element).getAttr().getValue()); + assertNull(element.getAnnotation(Convert.class)); + }, element -> { + assertEquals("bar", ((MyElement) element).getAttr().getValue()); + assertNull(element.getAnnotation(Convert.class)); }); final DomFixedChildDescription description = myElement.getGenericInfo().getFixedChildDescription("yyy"); assertNotNull(description); @@ -144,18 +129,12 @@ public class DomExtensionsTest extends DomTestCase { public void testCollectionChildren() throws Throwable { registerDomExtender(CollectionDomExtender.class); final MyElement myElement = createElement("zzz", MyElement.class); - assertUnorderedCollection(getCustomChildren(myElement), new Consumer() { - @Override - public void consume(final DomElement element) { - assertEquals("foo", ((MyElement) element).getAttr().getValue()); - assertNull(element.getAnnotation(Convert.class)); - } - }, new Consumer() { - @Override - public void consume(final DomElement element) { - assertNull(((MyElement) element).getAttr().getValue()); - assertNull(element.getAnnotation(Convert.class)); - } + assertUnorderedCollection(getCustomChildren(myElement), element -> { + assertEquals("foo", ((MyElement) element).getAttr().getValue()); + assertNull(element.getAnnotation(Convert.class)); + }, element -> { + assertNull(((MyElement) element).getAttr().getValue()); + assertNull(element.getAnnotation(Convert.class)); }); assertNotNull(myElement.getGenericInfo().getCollectionChildDescription("xxx")); } diff --git a/xml/dom-tests/tests/com/intellij/util/xml/DomFileDescriptionTest.java b/xml/dom-tests/tests/com/intellij/util/xml/DomFileDescriptionTest.java index 9fcb8818ed04..a6d413d3acac 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/DomFileDescriptionTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/DomFileDescriptionTest.java @@ -126,11 +126,8 @@ public class DomFileDescriptionTest extends DomHardCoreTestCase { final XmlFile file = (XmlFile)createFile("a.xml", "42"); getDomManager().registerFileDescription(new MockDomFileDescription(MyElement.class, "b", file), myDisposable); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - file.setName("b.xml"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + file.setName("b.xml"); }); assertTrue(getDomManager().isDomFile(file)); diff --git a/xml/dom-tests/tests/com/intellij/util/xml/DomIncludesTest.java b/xml/dom-tests/tests/com/intellij/util/xml/DomIncludesTest.java index 25458a6fd4f0..6a7f5f890f74 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/DomIncludesTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/DomIncludesTest.java @@ -47,23 +47,17 @@ public class DomIncludesTest extends LightCodeInsightFixtureTestCase { ""); createFile("b.xml", ""); final List children = rootElement.getChildren(); - Consumer consumer1 = new Consumer() { - @Override - public void consume(final MyElement element) { - assertFalse(element.getXmlElement().isPhysical()); - assertEquals(rootElement, element.getParent()); - assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); - assertEquals("b", element.getXxx().getValue()); - } + Consumer consumer1 = element -> { + assertFalse(element.getXmlElement().isPhysical()); + assertEquals(rootElement, element.getParent()); + assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); + assertEquals("b", element.getXxx().getValue()); }; - Consumer consumer2 = new Consumer() { - @Override - public void consume(final MyElement element) { - assertTrue(element.getXmlElement().isPhysical()); - assertEquals(rootElement, element.getParent()); - assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); - assertEquals("a", element.getXxx().getValue()); - } + Consumer consumer2 = element -> { + assertTrue(element.getXmlElement().isPhysical()); + assertEquals(rootElement, element.getParent()); + assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); + assertEquals("a", element.getXxx().getValue()); }; assertOrderedCollection(children, consumer1, consumer2); } @@ -77,22 +71,16 @@ public class DomIncludesTest extends LightCodeInsightFixtureTestCase { createFile("b.xml", ""); final List children = rootElement.getBoys(); - assertOrderedCollection(children, new Consumer() { - @Override - public void consume(final Boy element) { - assertFalse(element.getXmlElement().isPhysical()); - assertEquals(rootElement, element.getParent()); - assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); - assertEquals("b", element.getXxx().getValue()); - } - }, new Consumer() { - @Override - public void consume(final Boy element) { - assertTrue(element.getXmlElement().isPhysical()); - assertEquals(rootElement, element.getParent()); - assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); - assertEquals("a", element.getXxx().getValue()); - } + assertOrderedCollection(children, element -> { + assertFalse(element.getXmlElement().isPhysical()); + assertEquals(rootElement, element.getParent()); + assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); + assertEquals("b", element.getXxx().getValue()); + }, element -> { + assertTrue(element.getXmlElement().isPhysical()); + assertEquals(rootElement, element.getParent()); + assertEquals(DomUtil.getFileElement(rootElement), DomUtil.getFileElement(element)); + assertEquals("a", element.getXxx().getValue()); }); } @@ -120,64 +108,49 @@ public class DomIncludesTest extends LightCodeInsightFixtureTestCase { final AtomicReference ex = new AtomicReference(); for (int j = 0; j < threadCount; j++) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - for (int k = 0; k < iterationCount; k++) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final List boys = rootElement.getBoys(); - Thread.yield(); - final List children = rootElement.getChildren(); - Thread.yield(); - assertEquals(boys, rootElement.getBoys()); - assertEquals(children, rootElement.getChildren()); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + for (int k = 0; k < iterationCount; k++) { + ApplicationManager.getApplication().runReadAction(() -> { + final List boys = rootElement.getBoys(); Thread.yield(); - } - } - catch (Exception e) { - ex.set(e); - } - finally { - finished.countDown(); + final List children = rootElement.getChildren(); + Thread.yield(); + assertEquals(boys, rootElement.getBoys()); + assertEquals(children, rootElement.getChildren()); + }); + Thread.yield(); } } + catch (Exception e) { + ex.set(e); + } + finally { + finished.countDown(); + } }); } for (int i = 0; i < iterationCount; i++) { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - fileB.getViewProvider().getDocument().insertString(0, " "); - fileD.getViewProvider().getDocument().insertString(0, " "); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); //clear xinclude caches - } + WriteCommandAction.runWriteCommandAction(null, () -> { + fileB.getViewProvider().getDocument().insertString(0, " "); + fileD.getViewProvider().getDocument().insertString(0, " "); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); //clear xinclude caches }); Thread.sleep(10); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - fileC.getViewProvider().getDocument().insertString(0, " "); - fileE.getViewProvider().getDocument().insertString(0, " "); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); //clear xinclude caches - } + WriteCommandAction.runWriteCommandAction(null, () -> { + fileC.getViewProvider().getDocument().insertString(0, " "); + fileE.getViewProvider().getDocument().insertString(0, " "); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); //clear xinclude caches }); Thread.sleep(10); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { + WriteCommandAction.runWriteCommandAction(null, () -> { - fileB.getViewProvider().getDocument().setText(textB); - fileC.getViewProvider().getDocument().setText(textC); - fileD.getViewProvider().getDocument().setText(textD); - fileE.getViewProvider().getDocument().setText(textE); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); //clear xinclude caches - } + fileB.getViewProvider().getDocument().setText(textB); + fileC.getViewProvider().getDocument().setText(textC); + fileD.getViewProvider().getDocument().setText(textD); + fileE.getViewProvider().getDocument().setText(textE); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); //clear xinclude caches }); } diff --git a/xml/dom-tests/tests/com/intellij/util/xml/DomPerformanceTest.java b/xml/dom-tests/tests/com/intellij/util/xml/DomPerformanceTest.java index 9fd830f4dc79..368fe9787fa9 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/DomPerformanceTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/DomPerformanceTest.java @@ -54,19 +54,11 @@ public class DomPerformanceTest extends DomHardCoreTestCase{ child.addChildElement().addBarComposite().setValue("ssss"); child.addBarChild().getChild2().getAttr().setValue("234178956023"); - PlatformTestUtil.startPerformanceTest(getTestName(false), 80000, new ThrowableRunnable() { - @Override - public void run() throws Exception { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (int i = 0; i < 239; i++) { - element.addChildElement().copyFrom(child); - } - } - }); + PlatformTestUtil.startPerformanceTest(getTestName(false), 80000, () -> ApplicationManager.getApplication().runWriteAction(() -> { + for (int i = 0; i < 239; i++) { + element.addChildElement().copyFrom(child); } - }).cpuBound().attempts(1).useLegacyScaling().assertTiming(); + })).cpuBound().attempts(1).useLegacyScaling().assertTiming(); final MyElement newElement = createElement(DomUtil.getFile(element).getText(), MyElement.class); @@ -126,12 +118,7 @@ public class DomPerformanceTest extends DomHardCoreTestCase{ final XmlFile file = (XmlFile)getPsiManager().findFile(virtualFile); assertFalse(file.getNode().isParsed()); assertTrue(StringUtil.isNotEmpty(file.getText())); - PlatformTestUtil.startPerformanceTest("", 100, new ThrowableRunnable() { - @Override - public void run() throws Exception { - assertNull(getDomManager().getFileElement(file)); - } - }).cpuBound().useLegacyScaling().assertTiming(); + PlatformTestUtil.startPerformanceTest("", 100, () -> assertNull(getDomManager().getFileElement(file))).cpuBound().useLegacyScaling().assertTiming(); } public void testDontParseNamespacedDomFiles() throws Exception { diff --git a/xml/dom-tests/tests/com/intellij/util/xml/impl/IncrementalUpdateEventsTest.java b/xml/dom-tests/tests/com/intellij/util/xml/impl/IncrementalUpdateEventsTest.java index 66a3adaa2ee5..d49c52220a5f 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/impl/IncrementalUpdateEventsTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/impl/IncrementalUpdateEventsTest.java @@ -122,11 +122,8 @@ public class IncrementalUpdateEventsTest extends DomTestCase { private void deleteTag(final int index) { - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myElement.getXmlTag().getSubTags()[index].delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myElement.getXmlTag().getSubTags()[index].delete(); }); } diff --git a/xml/dom-tests/tests/com/intellij/util/xml/impl/TreeIncrementalUpdateTest.java b/xml/dom-tests/tests/com/intellij/util/xml/impl/TreeIncrementalUpdateTest.java index 98c6dbe638a8..da3036bbb12b 100644 --- a/xml/dom-tests/tests/com/intellij/util/xml/impl/TreeIncrementalUpdateTest.java +++ b/xml/dom-tests/tests/com/intellij/util/xml/impl/TreeIncrementalUpdateTest.java @@ -373,11 +373,8 @@ public class TreeIncrementalUpdateTest extends DomTestCase { final XmlTag tag = element.getXmlTag(); final XmlTag childTag = tag.getSubTags()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - childTag.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + childTag.delete(); }); putExpected(new DomEvent(element, false)); @@ -393,12 +390,9 @@ public class TreeIncrementalUpdateTest extends DomTestCase { final Sepulka element = createElement("", Sepulka.class); final List list = element.getCustomChildren(); final XmlTag tag = element.getXmlTag(); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - tag.getSubTags()[0].delete(); - tag.getSubTags()[0].delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tag.getSubTags()[0].delete(); + tag.getSubTags()[0].delete(); }); tag.add(createTag("")); @@ -423,21 +417,18 @@ public class TreeIncrementalUpdateTest extends DomTestCase { XmlTag leafTag = tag.getSubTags()[2].getSubTags()[0]; assertNoCache(leafTag); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.getSubTags()[1].delete(); + ApplicationManager.getApplication().runWriteAction(() -> { + tag.getSubTags()[1].delete(); - assertFalse(oldLeaf.isValid()); + assertFalse(oldLeaf.isValid()); - putExpected(new DomEvent(element, false)); - assertResultsAndClear(); + putExpected(new DomEvent(element, false)); + assertResultsAndClear(); - assertEquals(child, element.getChild()); - assertFalse(child2.isValid()); + assertEquals(child, element.getChild()); + assertFalse(child2.isValid()); - tag.getSubTags()[1].delete(); - } + tag.getSubTags()[1].delete(); }); putExpected(new DomEvent(element, false)); diff --git a/xml/impl/src/com/intellij/codeInsight/completion/TagNameReferenceCompletionProvider.java b/xml/impl/src/com/intellij/codeInsight/completion/TagNameReferenceCompletionProvider.java index 45220b08a552..58e05d13006c 100644 --- a/xml/impl/src/com/intellij/codeInsight/completion/TagNameReferenceCompletionProvider.java +++ b/xml/impl/src/com/intellij/codeInsight/completion/TagNameReferenceCompletionProvider.java @@ -51,17 +51,14 @@ public class TagNameReferenceCompletionProvider extends CompletionProvider() { - @Override - public void consume(PsiReference reference, CompletionResultSet set) { - if (reference instanceof TagNameReference) { - collectCompletionVariants((TagNameReference)reference, set); - } - else if (reference instanceof SchemaPrefixReference) { - TagNameReference tagNameReference = ((SchemaPrefixReference)reference).getTagNameReference(); - if (tagNameReference != null && !tagNameReference.isStartTagFlag()) { - set.consume(createClosingTagLookupElement((XmlTag)tagNameReference.getElement(), true, tagNameReference.getNameElement())); - } + LegacyCompletionContributor.processReferences(parameters, result, (reference, set) -> { + if (reference instanceof TagNameReference) { + collectCompletionVariants((TagNameReference)reference, set); + } + else if (reference instanceof SchemaPrefixReference) { + TagNameReference tagNameReference = ((SchemaPrefixReference)reference).getTagNameReference(); + if (tagNameReference != null && !tagNameReference.isStartTagFlag()) { + set.consume(createClosingTagLookupElement((XmlTag)tagNameReference.getElement(), true, tagNameReference.getNameElement())); } } }); diff --git a/xml/impl/src/com/intellij/codeInsight/completion/XmlCompletionContributor.java b/xml/impl/src/com/intellij/codeInsight/completion/XmlCompletionContributor.java index 857f6d0a158c..0dc23a4782c0 100644 --- a/xml/impl/src/com/intellij/codeInsight/completion/XmlCompletionContributor.java +++ b/xml/impl/src/com/intellij/codeInsight/completion/XmlCompletionContributor.java @@ -100,15 +100,12 @@ public class XmlCompletionContributor extends CompletionContributor { final Set usedWords = new THashSet(); final Ref addWordVariants = Ref.create(true); - result.runRemainingContributors(parameters, new Consumer() { - @Override - public void consume(CompletionResult r) { - if (r.getLookupElement().getUserData(WORD_COMPLETION_COMPATIBLE) == null) { - addWordVariants.set(false); - } - usedWords.add(r.getLookupElement().getLookupString()); - result.passResult(r.withLookupElement(LookupElementDecorator.withInsertHandler(r.getLookupElement(), QUOTE_EATER))); + result.runRemainingContributors(parameters, r -> { + if (r.getLookupElement().getUserData(WORD_COMPLETION_COMPATIBLE) == null) { + addWordVariants.set(false); } + usedWords.add(r.getLookupElement().getLookupString()); + result.passResult(r.withLookupElement(LookupElementDecorator.withInsertHandler(r.getLookupElement(), QUOTE_EATER))); }); if (addWordVariants.get().booleanValue()) { addWordVariants.set(attributeValue.getReferences().length == 0); diff --git a/xml/impl/src/com/intellij/codeInsight/completion/XmlLocationCompletionContributor.java b/xml/impl/src/com/intellij/codeInsight/completion/XmlLocationCompletionContributor.java index 25376153b7ed..9f25193e3bce 100644 --- a/xml/impl/src/com/intellij/codeInsight/completion/XmlLocationCompletionContributor.java +++ b/xml/impl/src/com/intellij/codeInsight/completion/XmlLocationCompletionContributor.java @@ -45,12 +45,8 @@ import java.util.Set; */ public class XmlLocationCompletionContributor extends CompletionContributor { - public static final Function MAPPING = new Function() { - @Override - public LookupElement fun(Object o) { - return o instanceof LookupElement ? (LookupElement)o : LookupElementBuilder.create(o); - } - }; + public static final Function MAPPING = + o -> o instanceof LookupElement ? (LookupElement)o : LookupElementBuilder.create(o); @Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { @@ -101,22 +97,16 @@ public class XmlLocationCompletionContributor extends CompletionContributor { assert document != null; XmlTag rootTag = document.getRootTag(); final ArrayList additionalNs = new ArrayList(); - if (rootTag != null) URLReference.processWsdlSchemas(rootTag, new Processor() { - @Override - public boolean process(final XmlTag xmlTag) { - final String s = xmlTag.getAttributeValue(URLReference.TARGET_NAMESPACE_ATTR_NAME); - if (s != null) { additionalNs.add(s); } - return true; - } + if (rootTag != null) URLReference.processWsdlSchemas(rootTag, xmlTag -> { + final String s = xmlTag.getAttributeValue(URLReference.TARGET_NAMESPACE_ATTR_NAME); + if (s != null) { additionalNs.add(s); } + return true; }); resourceUrls = ArrayUtil.mergeArrays(resourceUrls, ArrayUtil.toStringArray(additionalNs)); - return ContainerUtil.map2Array(resourceUrls, new Function() { - @Override - public Object fun(Object o) { - LookupElementBuilder builder = LookupElementBuilder.create(o); - return preferred.contains(o) ? PrioritizedLookupElement.withPriority(builder, 100) : builder; - } + return ContainerUtil.map2Array(resourceUrls, o -> { + LookupElementBuilder builder = LookupElementBuilder.create(o); + return preferred.contains(o) ? PrioritizedLookupElement.withPriority(builder, 100) : builder; }); } @@ -124,19 +114,16 @@ public class XmlLocationCompletionContributor extends CompletionContributor { XmlTag tag = (XmlTag)element.getParent().getParent(); XmlAttribute[] attributes = tag.getAttributes(); final PsiReference[] refs = element.getReferences(); - return ContainerUtil.mapNotNull(attributes, new Function() { - @Override - public Object fun(final XmlAttribute attribute) { - final String attributeValue = attribute.getValue(); - return attributeValue != null && - attribute.isNamespaceDeclaration() && - ContainerUtil.find(refs, new Condition() { - @Override - public boolean value(PsiReference ref) { - return ref.getCanonicalText().equals(attributeValue); - } - }) == null ? attributeValue + " " : null; - } + return ContainerUtil.mapNotNull(attributes, attribute -> { + final String attributeValue = attribute.getValue(); + return attributeValue != null && + attribute.isNamespaceDeclaration() && + ContainerUtil.find(refs, new Condition() { + @Override + public boolean value(PsiReference ref) { + return ref.getCanonicalText().equals(attributeValue); + } + }) == null ? attributeValue + " " : null; }, ArrayUtil.EMPTY_OBJECT_ARRAY); } } diff --git a/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartCompletionProvider.java b/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartCompletionProvider.java index 5321d8513506..4bca3232dcba 100644 --- a/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartCompletionProvider.java +++ b/xml/impl/src/com/intellij/codeInsight/completion/XmlSmartCompletionProvider.java @@ -45,19 +45,16 @@ public class XmlSmartCompletionProvider { if (parentTag == null) return; final XmlContentDFA dfa = XmlContentDFA.getContentDFA(parentTag); if (dfa == null) return; - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (XmlTag subTag : parentTag.getSubTags()) { - if (subTag == tag) { - break; - } - dfa.transition(subTag); - } - List elements = dfa.getPossibleElements(); - for (XmlElementDescriptor elementDescriptor: elements) { - addElementToResult(elementDescriptor, result); + ApplicationManager.getApplication().runReadAction(() -> { + for (XmlTag subTag : parentTag.getSubTags()) { + if (subTag == tag) { + break; } + dfa.transition(subTag); + } + List elements = dfa.getPossibleElements(); + for (XmlElementDescriptor elementDescriptor: elements) { + addElementToResult(elementDescriptor, result); } }); } diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java index fcd6beebd2c5..f11d113179ec 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ConvertSchemaPrefixToDefaultIntention.java @@ -91,17 +91,11 @@ public class ConvertSchemaPrefixToDefaultIntention extends PsiElementBaseIntenti if (!FileModificationService.getInstance().preparePsiElementsForWrite(xmlns.getContainingFile())) return; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - convertTagsAndAttributes(ns, tags, attrs, project); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - xmlns.setName("xmlns"); - } - }); - } + CommandProcessor.getInstance().executeCommand(project, () -> { + convertTagsAndAttributes(ns, tags, attrs, project); + ApplicationManager.getApplication().runWriteAction(() -> { + xmlns.setName("xmlns"); + }); }, NAME, null); new WriteCommandAction(project, NAME, xmlns.getContainingFile()) { @@ -133,22 +127,19 @@ public class ConvertSchemaPrefixToDefaultIntention extends PsiElementBaseIntenti @Override public boolean iteration() { progressTask.getIndicator().setFraction(((double) (tagIndex + attrIndex)) / totalCount); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (tagIndex < tags.size()) { - XmlTag tag = tags.get(tagIndex++); - final String s = tag.getName().substring(localNameIndex); - if (!s.isEmpty()) { - tag.setName(s); - } - } - else if (attrIndex < attrs.size()) { - XmlAttribute attr = attrs.get(attrIndex++); - //noinspection ConstantConditions - attr.setValue(attr.getValue().substring(localNameIndex)); + ApplicationManager.getApplication().runWriteAction(() -> { + if (tagIndex < tags.size()) { + XmlTag tag = tags.get(tagIndex++); + final String s = tag.getName().substring(localNameIndex); + if (!s.isEmpty()) { + tag.setName(s); } } + else if (attrIndex < attrs.size()) { + XmlAttribute attr = attrs.get(attrIndex++); + //noinspection ConstantConditions + attr.setValue(attr.getValue().substring(localNameIndex)); + } }); return isDone(); diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/CreateNSDeclarationIntentionFix.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/CreateNSDeclarationIntentionFix.java index 9e7f9fc08b15..9d438eb4ab96 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/CreateNSDeclarationIntentionFix.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/CreateNSDeclarationIntentionFix.java @@ -319,36 +319,25 @@ public class CreateNSDeclarationIntentionFix implements HintAction, LocalQuickFi if (namespacesToChooseFrom.length > 1 && !ApplicationManager.getApplication().isUnitTestMode()) { final JList list = new JBList(namespacesToChooseFrom); list.setCellRenderer(XmlNSRenderer.INSTANCE); - Runnable runnable = new Runnable() { - @Override - public void run() { - final int index = list.getSelectedIndex(); - if (index < 0) return; - PsiDocumentManager.getInstance(project).commitAllDocuments(); + Runnable runnable = () -> { + final int index = list.getSelectedIndex(); + if (index < 0) return; + PsiDocumentManager.getInstance(project).commitAllDocuments(); - CommandProcessor.getInstance().executeCommand( - project, - new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - try { - onSelection.doSomethingWithGivenStringToProduceXmlAttributeNowPlease(namespacesToChooseFrom[index]); - } catch (IncorrectOperationException ex) { - throw new RuntimeException(ex); - } - } - } - ); + CommandProcessor.getInstance().executeCommand( + project, + () -> ApplicationManager.getApplication().runWriteAction( + () -> { + try { + onSelection.doSomethingWithGivenStringToProduceXmlAttributeNowPlease(namespacesToChooseFrom[index]); + } catch (IncorrectOperationException ex) { + throw new RuntimeException(ex); } - }, - requestor.getText(), - requestor.getFamilyName() - ); - } + } + ), + requestor.getText(), + requestor.getFamilyName() + ); }; new PopupChooserBuilder(list). @@ -370,12 +359,7 @@ public class CreateNSDeclarationIntentionFix implements HintAction, LocalQuickFi } else { ProgressManager.getInstance().runProcessWithProgressSynchronously( - new Runnable() { - @Override - public void run() { - processExternalUrisImpl(metaHandler, file, processor); - } - }, + () -> processExternalUrisImpl(metaHandler, file, processor), XmlErrorMessages.message("finding.acceptable.uri"), false, file.getProject() diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ImportNSAction.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ImportNSAction.java index 24917fdeaee5..5c2450edf572 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ImportNSAction.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/ImportNSAction.java @@ -60,37 +60,33 @@ public class ImportNSAction implements QuestionAction { list.setSelectedIndex(0); final int offset = myElement.getTextOffset(); final RangeMarker marker = myEditor.getDocument().createRangeMarker(offset, offset); - final Runnable runnable = new Runnable() { + final Runnable runnable = () -> { + final String namespace = (String)list.getSelectedValue(); + if (namespace != null) { + final Project project = myFile.getProject(); + new WriteCommandAction.Simple(project, myFile) { - @Override - public void run() { - final String namespace = (String)list.getSelectedValue(); - if (namespace != null) { - final Project project = myFile.getProject(); - new WriteCommandAction.Simple(project, myFile) { - - @Override - protected void run() throws Throwable { - final XmlNamespaceHelper extension = XmlNamespaceHelper.getHelper(myFile); - final String prefix = extension.getNamespacePrefix(myElement); - extension.insertNamespaceDeclaration(myFile, - myEditor, - Collections.singleton(namespace), - prefix, - new XmlNamespaceHelper.Runner() { - @Override - public void run(final String s) throws IncorrectOperationException { - PsiDocumentManager.getInstance(myFile.getProject()).doPostponedOperationsAndUnblockDocument(myEditor.getDocument()); - PsiElement element = myFile.findElementAt(marker.getStartOffset()); - if (element != null) { - extension.qualifyWithPrefix(s, element, myEditor.getDocument()); - } + @Override + protected void run() throws Throwable { + final XmlNamespaceHelper extension = XmlNamespaceHelper.getHelper(myFile); + final String prefix = extension.getNamespacePrefix(myElement); + extension.insertNamespaceDeclaration(myFile, + myEditor, + Collections.singleton(namespace), + prefix, + new XmlNamespaceHelper.Runner() { + @Override + public void run(final String s) throws IncorrectOperationException { + PsiDocumentManager.getInstance(myFile.getProject()).doPostponedOperationsAndUnblockDocument(myEditor.getDocument()); + PsiElement element = myFile.findElementAt(marker.getStartOffset()); + if (element != null) { + extension.qualifyWithPrefix(s, element, myEditor.getDocument()); } } - ); - } - }.execute(); - } + } + ); + } + }.execute(); } }; if (list.getModel().getSize() == 1) { diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/InsertRequiredAttributeFix.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/InsertRequiredAttributeFix.java index b75749041ae4..6b261f5453ea 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/InsertRequiredAttributeFix.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/InsertRequiredAttributeFix.java @@ -144,38 +144,25 @@ public class InsertRequiredAttributeFix extends LocalQuickFixAndIntentionActionO final PsiElement anchor1 = anchor; - final Runnable runnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction( - new Runnable() { - @Override - public void run() { - int textOffset = anchor1.getTextOffset(); - if (!anchorIsEmptyTag && indirectSyntax) ++textOffset; - editor.getCaretModel().moveToOffset(textOffset); - if (anchorIsEmptyTag && indirectSyntax) { - editor.getDocument().deleteString(textOffset,textOffset + 2); - } - TemplateManager.getInstance(project).startTemplate(editor, template); - } - } - ); + final Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction( + () -> { + int textOffset = anchor1.getTextOffset(); + if (!anchorIsEmptyTag && indirectSyntax) ++textOffset; + editor.getCaretModel().moveToOffset(textOffset); + if (anchorIsEmptyTag && indirectSyntax) { + editor.getDocument().deleteString(textOffset,textOffset + 2); + } + TemplateManager.getInstance(project).startTemplate(editor, template); } - }; + ); if (!ApplicationManager.getApplication().isUnitTestMode()) { - Runnable commandRunnable = new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand( - project, - runnable, - getText(), - getFamilyName() - ); - } - }; + Runnable commandRunnable = () -> CommandProcessor.getInstance().executeCommand( + project, + runnable, + getText(), + getFamilyName() + ); ApplicationManager.getApplication().invokeLater(commandRunnable); } diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java index 04dbb4c2d152..28dacbd4c2e9 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FetchExtResourceAction.java @@ -155,12 +155,7 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat try { HttpConfigurable.getInstance().prepareURL(url); fetchDtd(project, uri, url, indicator); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - DaemonCodeAnalyzer.getInstance(project).restart(file); - } - }); + ApplicationManager.getApplication().invokeLater(() -> DaemonCodeAnalyzer.getInstance(project).restart(file)); return; } catch (IOException ex) { @@ -188,19 +183,16 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat LOG.assertTrue(extResources.mkdirs() || extResources.exists(), extResources); final PsiManager psiManager = PsiManager.getInstance(project); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - @SuppressWarnings("deprecation") - final AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(FetchExtResourceAction.class); - try { - final String path = FileUtil.toSystemIndependentName(extResources.getAbsolutePath()); - final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); - LOG.assertTrue(vFile != null, path); - } - finally { - token.finish(); - } + ApplicationManager.getApplication().invokeAndWait(() -> { + @SuppressWarnings("deprecation") + final AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(FetchExtResourceAction.class); + try { + final String path = FileUtil.toSystemIndependentName(extResources.getAbsolutePath()); + final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); + LOG.assertTrue(vFile != null, path); + } + finally { + token.finish(); } }, indicator.getModalityState()); @@ -278,20 +270,12 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat private static VirtualFile findFileByPath(final String resPath, @Nullable final String dtdUrl, ProgressIndicator indicator) { final Ref ref = new Ref(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ref.set(LocalFileSystem.getInstance().refreshAndFindFileByPath(resPath.replace(File.separatorChar, '/'))); - if (dtdUrl != null) { - ExternalResourceManager.getInstance().addResource(dtdUrl, resPath); - } - } - }); + ApplicationManager.getApplication().invokeAndWait(() -> ApplicationManager.getApplication().runWriteAction(() -> { + ref.set(LocalFileSystem.getInstance().refreshAndFindFileByPath(resPath.replace(File.separatorChar, '/'))); + if (dtdUrl != null) { + ExternalResourceManager.getInstance().addResource(dtdUrl, resPath); } - }, indicator.getModalityState()); + }), indicator.getModalityState()); return ref.get(); } @@ -334,12 +318,7 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat String extResourcesPath, @Nullable String refname) throws IOException { SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - indicator.setText(XmlBundle.message("fetching.progress.indicator", resourceUrl)); - } - } + () -> indicator.setText(XmlBundle.message("fetching.progress.indicator", resourceUrl)) ); FetchResult result = fetchData(project, resourceUrl, indicator); @@ -390,14 +369,11 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat result.contentType != null && result.contentType.contains(HTML_MIME) && new String(result.bytes).contains(" { + Messages.showMessageDialog(project, + XmlBundle.message("invalid.url.no.xml.file.at.location", resourceUrl), + XmlBundle.message("invalid.url.title"), + Messages.getErrorIcon()); }, indicator.getModalityState()); return false; } @@ -518,14 +494,11 @@ public class FetchExtResourceAction extends BaseExtResourceAction implements Wat } catch (MalformedURLException e) { if (!ApplicationManager.getApplication().isUnitTestMode()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Messages.showMessageDialog(project, - XmlBundle.message("invalid.url.message", dtdUrl), - XmlBundle.message("invalid.url.title"), - Messages.getErrorIcon()); - } + ApplicationManager.getApplication().invokeLater(() -> { + Messages.showMessageDialog(project, + XmlBundle.message("invalid.url.message", dtdUrl), + XmlBundle.message("invalid.url.title"), + Messages.getErrorIcon()); }, indicator.getModalityState()); } } diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/IgnoreExtResourceAction.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/IgnoreExtResourceAction.java index 57fd8a87f247..6fe2d2e799d6 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/IgnoreExtResourceAction.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/IgnoreExtResourceAction.java @@ -33,11 +33,8 @@ public class IgnoreExtResourceAction extends BaseExtResourceAction { @Override protected void doInvoke(@NotNull final PsiFile file, final int offset, @NotNull final String uri, final Editor editor) throws IncorrectOperationException { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource(uri); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource(uri); }); } } diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ManuallySetupExtResourceAction.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ManuallySetupExtResourceAction.java index 42d40786763c..289d1d95fcea 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ManuallySetupExtResourceAction.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ManuallySetupExtResourceAction.java @@ -37,12 +37,9 @@ public class ManuallySetupExtResourceAction extends BaseExtResourceAction { protected void doInvoke(@NotNull final PsiFile file, final int offset, @NotNull final String uri, final Editor editor) throws IncorrectOperationException { final MapExternalResourceDialog dialog = new MapExternalResourceDialog(uri, file.getProject(), file, null); if (dialog.showAndGet()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - String location = dialog.getResourceLocation(); - ExternalResourceManager.getInstance().addResource(dialog.getUri(), location); - } + ApplicationManager.getApplication().runWriteAction(() -> { + String location = dialog.getResourceLocation(); + ExternalResourceManager.getInstance().addResource(dialog.getUri(), location); }); } } diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java index 56f101395e1b..44ca9feb2a9f 100644 --- a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java +++ b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java @@ -119,12 +119,7 @@ public class XmlTagNameSynchronizer extends CommandAdapter implements NamedCompo if (!WebEditorOptions.getInstance().isSyncTagEditing() || document == null) return TagNameSynchronizer.EMPTY; final Editor[] editors = EditorFactory.getInstance().getEditors(document); - return ContainerUtil.mapNotNull(editors, new Function() { - @Override - public TagNameSynchronizer fun(Editor editor) { - return editor.getUserData(SYNCHRONIZER_KEY); - } - }, TagNameSynchronizer.EMPTY); + return ContainerUtil.mapNotNull(editors, editor -> editor.getUserData(SYNCHRONIZER_KEY), TagNameSynchronizer.EMPTY); } @Override @@ -297,29 +292,23 @@ public class XmlTagNameSynchronizer extends CommandAdapter implements NamedCompo myState = State.APPLYING; final Document document = myEditor.getDocument(); - final Runnable apply = new Runnable() { - @Override - public void run() { - for (Couple couple : myMarkers) { - final RangeMarker leader = couple.first; - final RangeMarker support = couple.second; - final String name = document.getText(new TextRange(leader.getStartOffset(), leader.getEndOffset())); - if (!name.equals(document.getText(new TextRange(support.getStartOffset(), support.getEndOffset())))) { - document.replaceString(support.getStartOffset(), support.getEndOffset(), name); - } + final Runnable apply = () -> { + for (Couple couple : myMarkers) { + final RangeMarker leader = couple.first; + final RangeMarker support = couple.second; + final String name = document.getText(new TextRange(leader.getStartOffset(), leader.getEndOffset())); + if (!name.equals(document.getText(new TextRange(support.getStartOffset(), support.getEndOffset())))) { + document.replaceString(support.getStartOffset(), support.getEndOffset(), name); } } }; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); - if (lookup != null) { - lookup.performGuardedChange(apply); - } - else { - apply.run(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor); + if (lookup != null) { + lookup.performGuardedChange(apply); + } + else { + apply.run(); } }); diff --git a/xml/impl/src/com/intellij/codeInsight/hint/api/impls/XmlParameterInfoHandler.java b/xml/impl/src/com/intellij/codeInsight/hint/api/impls/XmlParameterInfoHandler.java index 62e7a2255681..c042b47631fb 100644 --- a/xml/impl/src/com/intellij/codeInsight/hint/api/impls/XmlParameterInfoHandler.java +++ b/xml/impl/src/com/intellij/codeInsight/hint/api/impls/XmlParameterInfoHandler.java @@ -40,12 +40,7 @@ import java.util.Comparator; * @author Maxim.Mossienko */ public class XmlParameterInfoHandler implements ParameterInfoHandler { - private static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(final XmlAttributeDescriptor o1, final XmlAttributeDescriptor o2) { - return o1.getName().compareTo(o2.getName()); - } - }; + private static final Comparator COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName()); @Override public Object[] getParametersForLookup(LookupElement item, ParameterInfoContext context) { diff --git a/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java b/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java index 2ccfea7fce21..5eababe54083 100644 --- a/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java +++ b/xml/impl/src/com/intellij/codeInsight/intentions/XmlChooseColorIntentionAction.java @@ -83,13 +83,10 @@ public class XmlChooseColorIntentionAction extends PsiElementBaseIntentionAction final String newText = "#" + ColorUtil.toHex(color); final PsiManager manager = literal.getManager(); final XmlAttribute newAttribute = XmlElementFactory.getInstance(manager.getProject()).createAttribute("name", newText, element); - final Runnable replaceRunnable = new Runnable() { - @Override - public void run() { - final XmlAttributeValue valueElement = newAttribute.getValueElement(); - assert valueElement != null; - literal.replace(valueElement); - } + final Runnable replaceRunnable = () -> { + final XmlAttributeValue valueElement = newAttribute.getValueElement(); + assert valueElement != null; + literal.replace(valueElement); }; if (startInWriteAction) { new WriteCommandAction(element.getProject(), caption) { diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetAbbreviationBalloon.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetAbbreviationBalloon.java index 7e51343a6ca6..4babf06c88e4 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetAbbreviationBalloon.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetAbbreviationBalloon.java @@ -131,12 +131,9 @@ public class EmmetAbbreviationBalloon { balloon.show(popupFactory.guessBestPopupLocation(customTemplateCallback.getEditor()), Balloon.Position.below); final IdeFocusManager focusManager = IdeFocusManager.getInstance(customTemplateCallback.getProject()); - focusManager.doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - focusManager.requestFocus(field, true); - field.selectText(); - } + focusManager.doWhenFocusSettlesDown(() -> { + focusManager.requestFocus(field, true); + field.selectText(); }); } diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewHint.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewHint.java index 0783604047cc..ba24f9ff1506 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewHint.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewHint.java @@ -104,22 +104,14 @@ public class EmmetPreviewHint extends LightweightHint implements Disposable { public void updateText(@NotNull final Producer contentProducer) { myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - if (!isDisposed) { - final String newText = contentProducer.produce(); - if (StringUtil.isEmpty(newText)) { - hide(); - } - else if (!myEditor.getDocument().getText().equals(newText)) { - DocumentUtil.writeInRunUndoTransparentAction(new Runnable() { - @Override - public void run() { - myEditor.getDocument().setText(newText); - } - }); - } + myAlarm.addRequest(() -> { + if (!isDisposed) { + final String newText = contentProducer.produce(); + if (StringUtil.isEmpty(newText)) { + hide(); + } + else if (!myEditor.getDocument().getText().equals(newText)) { + DocumentUtil.writeInRunUndoTransparentAction(() -> myEditor.getDocument().setText(newText)); } } }, 100); @@ -201,12 +193,7 @@ public class EmmetPreviewHint extends LightweightHint implements Disposable { @Override public void hide(boolean ok) { super.hide(ok); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - Disposer.dispose(EmmetPreviewHint.this); - } - }); + ApplicationManager.getApplication().invokeLater(() -> Disposer.dispose(EmmetPreviewHint.this)); } @Override diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewUtil.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewUtil.java index a54b6812352f..60c12ddd28b3 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewUtil.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewUtil.java @@ -110,16 +110,8 @@ public class EmmetPreviewUtil { if (vFile != null) { vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE); } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { - @Override - public void run() { - CodeStyleManager.getInstance(file.getProject()).reformat(copy); - } - }); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().runUndoTransparentAction(() -> CodeStyleManager.getInstance(file.getProject()).reformat(copy)); }); return copy.getText(); } diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetUpdateTagAction.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetUpdateTagAction.java index 95b1f761eb9d..a16bdf3cca59 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetUpdateTagAction.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetUpdateTagAction.java @@ -98,37 +98,34 @@ public class EmmetUpdateTagAction extends BaseCodeInsightAction implements DumbA } final Map attributes = ContainerUtil.newLinkedHashMap(); final Ref newTagName = Ref.create(); - processTags(file.getProject(), templateText, new PairProcessor() { - @Override - public boolean process(XmlTag tag, Boolean firstTag) { - if (firstTag && !abbreviation.isEmpty() && StringUtil.isJavaIdentifierPart(abbreviation.charAt(0))) { - newTagName.set(tag.getName()); - } - - for (String clazz : StringUtil.tokenize(StringUtil.notNullize(tag.getAttributeValue(HtmlUtil.CLASS_ATTRIBUTE_NAME)), " \t")) { - if (StringUtil.startsWithChar(clazz, '+')) { - classNames.add(clazz.substring(1)); - } - else if (StringUtil.startsWithChar(clazz, '-')) { - classNames.remove(clazz.substring(1)); - } - else { - classNames.clear(); - classNames.add(clazz); - } - } - - if (!firstTag) { - classNames.add(tag.getName()); - } - - for (XmlAttribute xmlAttribute : tag.getAttributes()) { - if (!HtmlUtil.CLASS_ATTRIBUTE_NAME.equalsIgnoreCase(xmlAttribute.getName())) { - attributes.put(xmlAttribute.getName(), StringUtil.notNullize(xmlAttribute.getValue())); - } - } - return true; + processTags(file.getProject(), templateText, (tag1, firstTag) -> { + if (firstTag && !abbreviation.isEmpty() && StringUtil.isJavaIdentifierPart(abbreviation.charAt(0))) { + newTagName.set(tag1.getName()); } + + for (String clazz : StringUtil.tokenize(StringUtil.notNullize(tag1.getAttributeValue(HtmlUtil.CLASS_ATTRIBUTE_NAME)), " \t")) { + if (StringUtil.startsWithChar(clazz, '+')) { + classNames.add(clazz.substring(1)); + } + else if (StringUtil.startsWithChar(clazz, '-')) { + classNames.remove(clazz.substring(1)); + } + else { + classNames.clear(); + classNames.add(clazz); + } + } + + if (!firstTag) { + classNames.add(tag1.getName()); + } + + for (XmlAttribute xmlAttribute : tag1.getAttributes()) { + if (!HtmlUtil.CLASS_ATTRIBUTE_NAME.equalsIgnoreCase(xmlAttribute.getName())) { + attributes.put(xmlAttribute.getName(), StringUtil.notNullize(xmlAttribute.getValue())); + } + } + return true; }); doUpdateTagAttributes(tag, file, newTagName.get(), classNames, attributes).execute(); diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java index 978dec974a63..afee4d44836f 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java @@ -316,39 +316,31 @@ public class ZenCodingTemplate extends CustomLiveTemplateBase { public static void doWrap(@NotNull final String abbreviation, @NotNull final CustomTemplateCallback callback) { final ZenCodingGenerator defaultGenerator = findApplicableDefaultGenerator(callback.getContext(), true); assert defaultGenerator != null; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(callback.getProject(), new Runnable() { - @Override - public void run() { - callback.getEditor().getCaretModel().runForEachCaret(new CaretAction() { - @Override - public void perform(Caret caret) { - String selectedText = callback.getEditor().getSelectionModel().getSelectedText(); - if (selectedText != null) { - String selection = selectedText.trim(); - ZenCodingNode node = parse(abbreviation, callback, defaultGenerator, selection); - assert node != null; - PsiElement context = callback.getContext(); - ZenCodingGenerator generator = findApplicableGenerator(node, context, true); - List filters = getFilters(node, context); + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(callback.getProject(), () -> callback.getEditor().getCaretModel().runForEachCaret(new CaretAction() { + @Override + public void perform(Caret caret) { + String selectedText = callback.getEditor().getSelectionModel().getSelectedText(); + if (selectedText != null) { + String selection = selectedText.trim(); + ZenCodingNode node = parse(abbreviation, callback, defaultGenerator, selection); + assert node != null; + PsiElement context = callback.getContext(); + ZenCodingGenerator generator = findApplicableGenerator(node, context, true); + List filters = getFilters(node, context); - EditorModificationUtil.deleteSelectedText(callback.getEditor()); - PsiDocumentManager.getInstance(callback.getProject()).commitAllDocuments(); + EditorModificationUtil.deleteSelectedText(callback.getEditor()); + PsiDocumentManager.getInstance(callback.getProject()).commitAllDocuments(); - try { - expand(node, generator, filters, selection, callback, true, Registry.intValue("emmet.segments.limit")); - } - catch (EmmetException e) { - CommonRefactoringUtil.showErrorHint(callback.getProject(), callback.getEditor(), e.getMessage(), "Emmet error", ""); - } - } - } - }); + try { + expand(node, generator, filters, selection, callback, true, Registry.intValue("emmet.segments.limit")); + } + catch (EmmetException e) { + CommonRefactoringUtil.showErrorHint(callback.getProject(), callback.getEditor(), e.getMessage(), "Emmet error", ""); + } } - }, CodeInsightBundle.message("insert.code.template.command"), null); - } + } + }), CodeInsightBundle.message("insert.code.template.command"), null); }); } diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/completion/EmmetLookupActionProvider.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/completion/EmmetLookupActionProvider.java index b5e5f29f20a1..1f30e3572f62 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/completion/EmmetLookupActionProvider.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/completion/EmmetLookupActionProvider.java @@ -46,17 +46,14 @@ public class EmmetLookupActionProvider implements LookupActionProvider { @Override public Result performLookupAction() { final Project project = lookup.getProject(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - if (project.isDisposed()) return; + ApplicationManager.getApplication().invokeLater(() -> { + if (project.isDisposed()) return; - final Configurable generatorSpecificConfigurable = generator.createConfigurable(); - EmmetCompositeConfigurable configurable = generatorSpecificConfigurable != null - ? new EmmetCompositeConfigurable(generatorSpecificConfigurable) - : new EmmetCompositeConfigurable(new XmlEmmetConfigurable()); - ShowSettingsUtil.getInstance().editConfigurable(project, configurable); - } + final Configurable generatorSpecificConfigurable = generator.createConfigurable(); + EmmetCompositeConfigurable configurable = generatorSpecificConfigurable != null + ? new EmmetCompositeConfigurable(generatorSpecificConfigurable) + : new EmmetCompositeConfigurable(new XmlEmmetConfigurable()); + ShowSettingsUtil.getInstance().editConfigurable(project, configurable); }); return Result.HIDE_LOOKUP; } @@ -65,12 +62,7 @@ public class EmmetLookupActionProvider implements LookupActionProvider { consumer.consume(new LookupElementAction(AllIcons.Actions.Delete, "Disable Emmet") { @Override public Result performLookupAction() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - generator.disableEmmet(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> generator.disableEmmet()); return Result.HIDE_LOOKUP; } }); diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/TrimZenCodingFilter.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/TrimZenCodingFilter.java index 421fbdd46564..0bb4dd1e07e3 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/TrimZenCodingFilter.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/TrimZenCodingFilter.java @@ -66,11 +66,8 @@ public class TrimZenCodingFilter extends ZenCodingFilter { final XmlTagValue tagValue = tag.getValue(); final Matcher matcher = PATTERN.matcher(tagValue.getText()); if (matcher.matches()) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tagValue.setText(matcher.replaceAll("")); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tagValue.setText(matcher.replaceAll("")); }); } } diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/XslZenCodingFilter.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/XslZenCodingFilter.java index 5f3d420da1e0..e31622c6d92b 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/XslZenCodingFilter.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/filters/XslZenCodingFilter.java @@ -44,14 +44,11 @@ public class XslZenCodingFilter extends ZenCodingFilter { if (token.getAttributes().containsKey(SELECT_ATTR_NAME)) { return node; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - if (isOurTag(tag, node.getChildren().size() > 0)) { - XmlAttribute attribute = tag.getAttribute(SELECT_ATTR_NAME); - if (attribute != null) { - attribute.delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + if (isOurTag(tag, node.getChildren().size() > 0)) { + XmlAttribute attribute = tag.getAttribute(SELECT_ATTR_NAME); + if (attribute != null) { + attribute.delete(); } } }); diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java index d74ccf9b7274..8392fd259bce 100644 --- a/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java +++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/generators/XmlZenCodingGeneratorImpl.java @@ -131,12 +131,9 @@ public class XmlZenCodingGeneratorImpl extends XmlZenCodingGenerator { if (file != null) { final Document document = FileDocumentManager.getInstance().getDocument(file); documentManager.doPostponedOperationsAndUnblockDocument(document); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(offset, tag.getTextRange().getEndOffset(), "/>"); - documentManager.commitDocument(document); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(offset, tag.getTextRange().getEndOffset(), "/>"); + documentManager.commitDocument(document); }); } } diff --git a/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java b/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java index c9157185aaa2..01b47f9cb9d3 100644 --- a/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java +++ b/xml/impl/src/com/intellij/codeInspection/htmlInspections/HtmlUnknownTagInspection.java @@ -75,19 +75,9 @@ public class HtmlUnknownTagInspection extends HtmlUnknownTagInspectionBase { final FieldPanel additionalAttributesPanel = new FieldPanel(null, null, new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - Messages.showTextAreaDialog(panelRef.get().getTextField(), StringUtil.wordsToBeginFromUpperCase(inspection.getPanelTitle()), + Messages.showTextAreaDialog(panelRef.get().getTextField(), StringUtil.wordsToBeginFromUpperCase(inspection.getPanelTitle()), inspection.getClass().getSimpleName(), - new Function>() { - @Override - public List fun(String s) { - return reparseProperties(s); - } - }, new Function, String>() { - @Override - public String fun(List strings) { - return StringUtil.join(strings, ","); - } - } + s -> reparseProperties(s), strings -> StringUtil.join(strings, ",") ); } }, null); diff --git a/xml/impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.java b/xml/impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.java index ab47ac9d98f4..7d2a1e3ce92b 100644 --- a/xml/impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.java +++ b/xml/impl/src/com/intellij/ide/browsers/BrowserLauncherImpl.java @@ -76,22 +76,14 @@ public final class BrowserLauncherImpl extends BrowserLauncherAppless { @Nullable final Project project, final String title, @Nullable final Runnable launchTask) { - AppUIUtil.invokeOnEdt(new Runnable() { - @Override - public void run() { - if (Messages.showYesNoDialog(project, StringUtil.notNullize(error, "Unknown error"), - title == null ? IdeBundle.message("browser.error") : title, Messages.OK_BUTTON, - IdeBundle.message("button.fix"), null) == Messages.NO) { - final BrowserSettings browserSettings = new BrowserSettings(); - if (ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser == null ? null : new Runnable() { - @Override - public void run() { - browserSettings.selectBrowser(browser); - } - })) { - if (launchTask != null) { - launchTask.run(); - } + AppUIUtil.invokeOnEdt(() -> { + if (Messages.showYesNoDialog(project, StringUtil.notNullize(error, "Unknown error"), + title == null ? IdeBundle.message("browser.error") : title, Messages.OK_BUTTON, + IdeBundle.message("button.fix"), null) == Messages.NO) { + final BrowserSettings browserSettings = new BrowserSettings(); + if (ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser == null ? null : (Runnable)() -> browserSettings.selectBrowser(browser))) { + if (launchTask != null) { + launchTask.run(); } } } @@ -105,25 +97,17 @@ public final class BrowserLauncherImpl extends BrowserLauncherAppless { @NotNull final Process process, @Nullable final Runnable launchTask) { if (isOpenCommandUsed(commandLine)) { - final Future future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - if (process.waitFor() == 1) { - showError(ExecUtil.readFirstLine(process.getErrorStream(), null), browser, project, null, launchTask); - } - } - catch (InterruptedException ignored) { + final Future future = ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + if (process.waitFor() == 1) { + showError(ExecUtil.readFirstLine(process.getErrorStream(), null), browser, project, null, launchTask); } } + catch (InterruptedException ignored) { + } }); // 10 seconds is enough to start - JobScheduler.getScheduler().schedule(new Runnable() { - @Override - public void run() { - future.cancel(true); - } - }, 10, TimeUnit.SECONDS); + JobScheduler.getScheduler().schedule((Runnable)() -> future.cancel(true), 10, TimeUnit.SECONDS); } } } \ No newline at end of file diff --git a/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java b/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java index 6968dcb251fb..5332c6993078 100644 --- a/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java +++ b/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java @@ -75,12 +75,7 @@ public class BrowserStarter { } private void checkAndOpenPageLater(@NotNull final HostAndPort hostAndPort, final int attemptNumber, int delayMillis) { - JobScheduler.getScheduler().schedule(new Runnable() { - @Override - public void run() { - checkAndOpenPage(hostAndPort, attemptNumber); - } - }, delayMillis, TimeUnit.MILLISECONDS); + JobScheduler.getScheduler().schedule(() -> checkAndOpenPage(hostAndPort, attemptNumber), delayMillis, TimeUnit.MILLISECONDS); } private void checkAndOpenPage(@NotNull final HostAndPort hostAndPort, final int attemptNumber) { @@ -107,12 +102,7 @@ public class BrowserStarter { } private void openPageLater(int millis) { - JobScheduler.getScheduler().schedule(new Runnable() { - @Override - public void run() { - openPageNow(); - } - }, millis, TimeUnit.MILLISECONDS); + JobScheduler.getScheduler().schedule(() -> openPageNow(), millis, TimeUnit.MILLISECONDS); } private void openPageNow() { diff --git a/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java b/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java index f8c59ecbc587..13cd67a80b87 100644 --- a/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java +++ b/xml/impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.java @@ -171,12 +171,9 @@ public abstract class BaseOpenInBrowserAction extends DumbAwareAction { Collection urls = WebBrowserService.getInstance().getUrlsToOpen(request, preferLocalUrl); if (!urls.isEmpty()) { chooseUrl(urls) - .done(new Consumer() { - @Override - public void consume(Url url) { - ApplicationManager.getApplication().saveAll(); - BrowserLauncher.getInstance().browse(url.toExternalForm(), browser, request.getProject()); - } + .done(url -> { + ApplicationManager.getApplication().saveAll(); + BrowserLauncher.getInstance().browse(url.toExternalForm(), browser, request.getProject()); }); } } @@ -208,16 +205,13 @@ public abstract class BaseOpenInBrowserAction extends DumbAwareAction { JBPopupFactory.getInstance() .createListPopupBuilder(list) .setTitle("Choose Url") - .setItemChoosenCallback(new Runnable() { - @Override - public void run() { - Url value = (Url)list.getSelectedValue(); - if (value == null) { - result.setError("selected value is null"); - } - else { - result.setResult(value); - } + .setItemChoosenCallback(() -> { + Url value = (Url)list.getSelectedValue(); + if (value == null) { + result.setError("selected value is null"); + } + else { + result.setResult(value); } }) .createPopup() diff --git a/xml/impl/src/com/intellij/javaee/DefaultSchemasConfigurable.java b/xml/impl/src/com/intellij/javaee/DefaultSchemasConfigurable.java index 2c7938dc0dac..4e783ea1d438 100644 --- a/xml/impl/src/com/intellij/javaee/DefaultSchemasConfigurable.java +++ b/xml/impl/src/com/intellij/javaee/DefaultSchemasConfigurable.java @@ -123,15 +123,12 @@ public class DefaultSchemasConfigurable implements Configurable { else { myOtherRadioButton.setSelected(true); myDoctypeTextField.setEnabled(true); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - try { - myDoctypeTextField.setText(doctype); - } - catch (Exception e) { - throw new RuntimeException(e); - } + UIUtil.invokeLaterIfNeeded(() -> { + try { + myDoctypeTextField.setText(doctype); + } + catch (Exception e) { + throw new RuntimeException(e); } }); } diff --git a/xml/impl/src/com/intellij/javaee/EditLocationDialog.java b/xml/impl/src/com/intellij/javaee/EditLocationDialog.java index d8364019e85f..3cbecefdfa46 100644 --- a/xml/impl/src/com/intellij/javaee/EditLocationDialog.java +++ b/xml/impl/src/com/intellij/javaee/EditLocationDialog.java @@ -98,11 +98,8 @@ public class EditLocationDialog extends DialogWrapper { @Override public void actionPerformed(ActionEvent ignored) { FileChooserDescriptor descriptor = getChooserDescriptor(); - FileChooser.chooseFile(descriptor, myProject, null, new Consumer() { - @Override - public void consume(VirtualFile file) { - myTfPath.setText(file.getPath().replace('/', File.separatorChar)); - } + FileChooser.chooseFile(descriptor, myProject, null, file -> { + myTfPath.setText(file.getPath().replace('/', File.separatorChar)); }); } }); diff --git a/xml/impl/src/com/intellij/javaee/ExternalResourceConfigurable.java b/xml/impl/src/com/intellij/javaee/ExternalResourceConfigurable.java index 1b03bdc0eeba..b93041ed84a4 100644 --- a/xml/impl/src/com/intellij/javaee/ExternalResourceConfigurable.java +++ b/xml/impl/src/com/intellij/javaee/ExternalResourceConfigurable.java @@ -144,31 +144,28 @@ public class ExternalResourceConfigurable extends BaseConfigurable @Override public void apply() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManagerEx manager = ExternalResourceManagerEx.getInstanceEx(); + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx manager = ExternalResourceManagerEx.getInstanceEx(); - if (myProject == null) { - manager.clearAllResources(); + if (myProject == null) { + manager.clearAllResources(); + } + else { + manager.clearAllResources(myProject); + } + for (NameLocationPair pair : myPairs) { + String s = FileUtil.toSystemIndependentName(StringUtil.notNullize(pair.myLocation)); + if (myProject == null || pair.myShared) { + manager.addResource(pair.myName, s); } else { - manager.clearAllResources(myProject); - } - for (NameLocationPair pair : myPairs) { - String s = FileUtil.toSystemIndependentName(StringUtil.notNullize(pair.myLocation)); - if (myProject == null || pair.myShared) { - manager.addResource(pair.myName, s); - } - else { - manager.addResource(pair.myName, s, myProject); - } + manager.addResource(pair.myName, s, myProject); } + } - for (Object myIgnoredUrl : myIgnoredUrls) { - String url = (String)myIgnoredUrl; - manager.addIgnoredResource(url); - } + for (Object myIgnoredUrl : myIgnoredUrls) { + String url = (String)myIgnoredUrl; + manager.addIgnoredResource(url); } }); diff --git a/xml/impl/src/com/intellij/lang/xml/XmlUnwrapDescriptor.java b/xml/impl/src/com/intellij/lang/xml/XmlUnwrapDescriptor.java index 1462e97c46d9..2d532bc4cc4c 100644 --- a/xml/impl/src/com/intellij/lang/xml/XmlUnwrapDescriptor.java +++ b/xml/impl/src/com/intellij/lang/xml/XmlUnwrapDescriptor.java @@ -69,12 +69,7 @@ public class XmlUnwrapDescriptor implements UnwrapDescriptor { } } - Collections.sort(result, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - return o2.first.getTextOffset() - o1.first.getTextOffset(); - } - }); + Collections.sort(result, (o1, o2) -> o2.first.getTextOffset() - o1.first.getTextOffset()); return result; } diff --git a/xml/impl/src/com/intellij/navigation/LinkedToHtmlFilesContributor.java b/xml/impl/src/com/intellij/navigation/LinkedToHtmlFilesContributor.java index b87afcd1f78a..1b015b88d61b 100644 --- a/xml/impl/src/com/intellij/navigation/LinkedToHtmlFilesContributor.java +++ b/xml/impl/src/com/intellij/navigation/LinkedToHtmlFilesContributor.java @@ -32,39 +32,36 @@ import java.util.Set; public class LinkedToHtmlFilesContributor extends RelatedToHtmlFilesContributor { @Override public void fillRelatedFiles(@NotNull final XmlFile xmlFile, @NotNull final Set resultSet) { - HtmlLinkUtil.processLinks(xmlFile, new Processor() { - @Override - public boolean process(XmlTag tag) { - final XmlAttribute attribute = tag.getAttribute("href"); - if (attribute == null) { - return true; - } + HtmlLinkUtil.processLinks(xmlFile, tag -> { + final XmlAttribute attribute = tag.getAttribute("href"); + if (attribute == null) { + return true; + } - final XmlAttributeValue link = attribute.getValueElement(); - if (link == null) { - return true; - } + final XmlAttributeValue link = attribute.getValueElement(); + if (link == null) { + return true; + } - for (PsiReference reference : link.getReferences()) { - if (reference instanceof PsiPolyVariantReference) { - final ResolveResult[] results = ((PsiPolyVariantReference)reference).multiResolve(false); + for (PsiReference reference : link.getReferences()) { + if (reference instanceof PsiPolyVariantReference) { + final ResolveResult[] results = ((PsiPolyVariantReference)reference).multiResolve(false); - for (ResolveResult result : results) { - final PsiElement resolvedElement = result.getElement(); - if (resolvedElement instanceof PsiFile) { - resultSet.add((PsiFile)resolvedElement); - } - } - } - else { - final PsiElement resolvedElement = reference.resolve(); + for (ResolveResult result : results) { + final PsiElement resolvedElement = result.getElement(); if (resolvedElement instanceof PsiFile) { resultSet.add((PsiFile)resolvedElement); } } } - return true; + else { + final PsiElement resolvedElement = reference.resolve(); + if (resolvedElement instanceof PsiFile) { + resultSet.add((PsiFile)resolvedElement); + } + } } + return true; }); } diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/XsContentDFA.java b/xml/impl/src/com/intellij/psi/impl/source/xml/XsContentDFA.java index 94858761b683..1d9e09427e25 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/xml/XsContentDFA.java +++ b/xml/impl/src/com/intellij/psi/impl/source/xml/XsContentDFA.java @@ -204,12 +204,7 @@ class XsContentDFA extends XmlContentDFA { } Grammar[] grammars = grammarPool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA); - return grammars.length == 0 ? null : ((XSGrammar)grammars[0]).toXSModel(ContainerUtil.map(grammars, new Function() { - @Override - public XSGrammar fun(Grammar grammar) { - return (XSGrammar)grammar; - } - }, new XSGrammar[0])); + return grammars.length == 0 ? null : ((XSGrammar)grammars[0]).toXSModel(ContainerUtil.map(grammars, grammar -> (XSGrammar)grammar, new XSGrammar[0])); } private static class MyXSElementDeclHelper implements XSElementDeclHelper { diff --git a/xml/impl/src/com/intellij/xml/actions/EscapeEntitiesAction.java b/xml/impl/src/com/intellij/xml/actions/EscapeEntitiesAction.java index 22234e1b1cdd..1ba5a3ed442d 100644 --- a/xml/impl/src/com/intellij/xml/actions/EscapeEntitiesAction.java +++ b/xml/impl/src/com/intellij/xml/actions/EscapeEntitiesAction.java @@ -130,11 +130,8 @@ public class EscapeEntitiesAction extends BaseCodeInsightAction implements CodeI String oldText = document.getText(new TextRange(start, end)); final String newText = escape((XmlFile)file, oldText, start); if (!oldText.equals(newText)) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(start, end, newText); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(start, end, newText); }); } } diff --git a/xml/impl/src/com/intellij/xml/actions/GenerateXmlTagAction.java b/xml/impl/src/com/intellij/xml/actions/GenerateXmlTagAction.java index d091bbb3bdd1..6d3e46f7868e 100644 --- a/xml/impl/src/com/intellij/xml/actions/GenerateXmlTagAction.java +++ b/xml/impl/src/com/intellij/xml/actions/GenerateXmlTagAction.java @@ -82,41 +82,33 @@ public class GenerateXmlTagAction extends SimpleCodeInsightAction { XmlElementDescriptor currentTagDescriptor = contextTag.getDescriptor(); assert currentTagDescriptor != null; final XmlElementDescriptor[] descriptors = currentTagDescriptor.getElementsDescriptors(contextTag); - Arrays.sort(descriptors, new Comparator() { - @Override - public int compare(XmlElementDescriptor o1, XmlElementDescriptor o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Arrays.sort(descriptors, (o1, o2) -> o1.getName().compareTo(o2.getName())); final JBList list = new JBList(descriptors); list.setCellRenderer(new MyListCellRenderer()); - Runnable runnable = new Runnable() { - @Override - public void run() { - final XmlElementDescriptor selected = (XmlElementDescriptor)list.getSelectedValue(); - new WriteCommandAction.Simple(project, "Generate XML Tag", file) { - @Override - protected void run() { - if (selected == null) return; - XmlTag newTag = createTag(contextTag, selected); + Runnable runnable = () -> { + final XmlElementDescriptor selected = (XmlElementDescriptor)list.getSelectedValue(); + new WriteCommandAction.Simple(project, "Generate XML Tag", file) { + @Override + protected void run() { + if (selected == null) return; + XmlTag newTag = createTag(contextTag, selected); - PsiElement anchor = getAnchor(contextTag, editor, selected); - if (anchor == null) { // insert it in the cursor position - int offset = editor.getCaretModel().getOffset(); - Document document = editor.getDocument(); - document.insertString(offset, newTag.getText()); - PsiDocumentManager.getInstance(project).commitDocument(document); - newTag = PsiTreeUtil.getParentOfType(file.findElementAt(offset + 1), XmlTag.class, false); - } - else { - newTag = (XmlTag)contextTag.addAfter(newTag, anchor); - } - if (newTag != null) { - generateTag(newTag, editor); - } + PsiElement anchor = getAnchor(contextTag, editor, selected); + if (anchor == null) { // insert it in the cursor position + int offset = editor.getCaretModel().getOffset(); + Document document = editor.getDocument(); + document.insertString(offset, newTag.getText()); + PsiDocumentManager.getInstance(project).commitDocument(document); + newTag = PsiTreeUtil.getParentOfType(file.findElementAt(offset + 1), XmlTag.class, false); } - }.execute(); - } + else { + newTag = (XmlTag)contextTag.addAfter(newTag, anchor); + } + if (newTag != null) { + generateTag(newTag, editor); + } + } + }.execute(); }; if (ApplicationManager.getApplication().isUnitTestMode()) { XmlElementDescriptor descriptor = ContainerUtil.find(descriptors, new Condition() { @@ -132,12 +124,7 @@ public class GenerateXmlTagAction extends SimpleCodeInsightAction { JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle("Choose Tag Name") .setItemChoosenCallback(runnable) - .setFilteringEnabled(new Function() { - @Override - public String fun(Object o) { - return ((XmlElementDescriptor)o).getName(); - } - }) + .setFilteringEnabled(o -> ((XmlElementDescriptor)o).getName()) .createPopup() .showInBestPositionFor(editor); } diff --git a/xml/impl/src/com/intellij/xml/actions/validate/StdErrorReporter.java b/xml/impl/src/com/intellij/xml/actions/validate/StdErrorReporter.java index 88736b8ef9e0..10f13fde122c 100644 --- a/xml/impl/src/com/intellij/xml/actions/validate/StdErrorReporter.java +++ b/xml/impl/src/com/intellij/xml/actions/validate/StdErrorReporter.java @@ -52,40 +52,28 @@ public class StdErrorReporter extends ErrorReporter { @Override public void startProcessing() { - final Runnable task = new Runnable() { - @Override - public void run() { - try { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - StdErrorReporter.super.startProcessing(); - } - }); + final Runnable task = () -> { + try { + ApplicationManager.getApplication().runReadAction(() -> { + StdErrorReporter.super.startProcessing(); + }); - SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - if (!myErrorsDetected) { - SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - removeCompileContents(null); - WindowManager.getInstance().getStatusBar(myProject).setInfo( - XmlBundle.message("xml.validate.no.errors.detected.status.message")); - } - } - ); + SwingUtilities.invokeLater( + () -> { + if (!myErrorsDetected) { + SwingUtilities.invokeLater( + () -> { + removeCompileContents(null); + WindowManager.getInstance().getStatusBar(myProject).setInfo( + XmlBundle.message("xml.validate.no.errors.detected.status.message")); } - } + ); } - ); - } - finally { - Thread.interrupted(); // reset interrupted - } + } + ); + } + finally { + Thread.interrupted(); // reset interrupted } }; @@ -100,21 +88,18 @@ public class StdErrorReporter extends ErrorReporter { private void openMessageView() { CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand( - myProject, new Runnable() { - @Override - public void run() { - MessageView messageView = MessageView.SERVICE.getInstance(myProject); - final Content content = ContentFactory.SERVICE.getInstance().createContent(myErrorsView.getComponent(), CONTENT_NAME, true); - content.putUserData(KEY, myErrorsView); - messageView.getContentManager().addContent(content); - messageView.getContentManager().setSelectedContent(content); - messageView.getContentManager().addContentManagerListener(new CloseListener(content, messageView.getContentManager())); - removeCompileContents(content); - messageView.getContentManager().addContentManagerListener(new MyContentDisposer(content, messageView)); - } - }, - XmlBundle.message("validate.xml.open.message.view.command.name"), - null + myProject, () -> { + MessageView messageView = MessageView.SERVICE.getInstance(myProject); + final Content content = ContentFactory.SERVICE.getInstance().createContent(myErrorsView.getComponent(), CONTENT_NAME, true); + content.putUserData(KEY, myErrorsView); + messageView.getContentManager().addContent(content); + messageView.getContentManager().setSelectedContent(content); + messageView.getContentManager().addContentManagerListener(new CloseListener(content, messageView.getContentManager())); + removeCompileContents(content); + messageView.getContentManager().addContentManagerListener(new MyContentDisposer(content, messageView)); + }, + XmlBundle.message("validate.xml.open.message.view.command.name"), + null ); } private void removeCompileContents(Content notToRemove) { @@ -144,20 +129,17 @@ public class StdErrorReporter extends ErrorReporter { if (!ApplicationManager.getApplication().isUnitTestMode()) { SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - final VirtualFile file = myHandler.getProblemFile(ex); - myErrorsView.addMessage( - problemType == ValidateXmlActionHandler.ProblemType.WARNING ? MessageCategory.WARNING : MessageCategory.ERROR, - new String[]{ex.getLocalizedMessage()}, - file, - ex.getLineNumber() - 1, - ex.getColumnNumber() - 1, - null - ); - } - } + () -> { + final VirtualFile file = myHandler.getProblemFile(ex); + myErrorsView.addMessage( + problemType == ValidateXmlActionHandler.ProblemType.WARNING ? MessageCategory.WARNING : MessageCategory.ERROR, + new String[]{ex.getLocalizedMessage()}, + file, + ex.getLineNumber() - 1, + ex.getColumnNumber() - 1, + null + ); + } ); } } diff --git a/xml/impl/src/com/intellij/xml/actions/validate/ValidateXmlAction.java b/xml/impl/src/com/intellij/xml/actions/validate/ValidateXmlAction.java index ea26f4593c92..fc87b1679532 100644 --- a/xml/impl/src/com/intellij/xml/actions/validate/ValidateXmlAction.java +++ b/xml/impl/src/com/intellij/xml/actions/validate/ValidateXmlAction.java @@ -39,12 +39,7 @@ public class ValidateXmlAction extends AnAction { ValidateXmlActionHandler handler = new ValidateXmlActionHandler(true); handler.setErrorReporter( new StdErrorReporter(handler, file.getProject(), - new Runnable() { - @Override - public void run() { - doRunAction(file); - } - } + () -> doRunAction(file) ) ); return handler; @@ -60,28 +55,22 @@ public class ValidateXmlAction extends AnAction { private void doRunAction(final @NotNull PsiFile psiFile) { - CommandProcessor.getInstance().executeCommand(psiFile.getProject(), new Runnable(){ - @Override - public void run(){ - final Runnable action = new Runnable() { - @Override - public void run() { - try { - psiFile.putUserData(runningValidationKey, ""); - PsiDocumentManager.getInstance(psiFile.getProject()).commitAllDocuments(); + CommandProcessor.getInstance().executeCommand(psiFile.getProject(), () -> { + final Runnable action = () -> { + try { + psiFile.putUserData(runningValidationKey, ""); + PsiDocumentManager.getInstance(psiFile.getProject()).commitAllDocuments(); - getHandler(psiFile).doValidate((XmlFile)psiFile); - } - finally { - psiFile.putUserData(runningValidationKey, null); - } - } - }; - ApplicationManager.getApplication().runWriteAction(action); + getHandler(psiFile).doValidate((XmlFile)psiFile); } - }, - getCommandName(), - null + finally { + psiFile.putUserData(runningValidationKey, null); + } + }; + ApplicationManager.getApplication().runWriteAction(action); + }, + getCommandName(), + null ); } diff --git a/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateInstanceDocumentFromSchemaAction.java b/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateInstanceDocumentFromSchemaAction.java index 96814e7e864b..54c530db9db1 100644 --- a/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateInstanceDocumentFromSchemaAction.java +++ b/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateInstanceDocumentFromSchemaAction.java @@ -66,12 +66,7 @@ public class GenerateInstanceDocumentFromSchemaAction extends AnAction { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext()); final GenerateInstanceDocumentFromSchemaDialog dialog = new GenerateInstanceDocumentFromSchemaDialog(project, file); - dialog.setOkAction(new Runnable() { - @Override - public void run() { - doAction(project, dialog); - } - }); + dialog.setOkAction(() -> doAction(project, dialog)); dialog.show(); } diff --git a/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateSchemaFromInstanceDocumentAction.java b/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateSchemaFromInstanceDocumentAction.java index 4a84ad70f2dc..b1a0114b2990 100644 --- a/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateSchemaFromInstanceDocumentAction.java +++ b/xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateSchemaFromInstanceDocumentAction.java @@ -72,12 +72,7 @@ public class GenerateSchemaFromInstanceDocumentAction extends AnAction { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext()); final GenerateSchemaFromInstanceDocumentDialog dialog = new GenerateSchemaFromInstanceDocumentDialog(project, file); - dialog.setOkAction(new Runnable() { - @Override - public void run() { - doAction(project, dialog); - } - }); + dialog.setOkAction(() -> doAction(project, dialog)); dialog.show(); } @@ -129,13 +124,10 @@ public class GenerateSchemaFromInstanceDocumentAction extends AnAction { File xsd = new File(dirPath + File.separator + dialog.getTargetSchemaName()); final VirtualFile xsdFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(xsd); if (xsdFile != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - xsdFile.delete(null); - } catch (IOException e) {// - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + xsdFile.delete(null); + } catch (IOException e) {// } }); } diff --git a/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java b/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java index 7b464a242c59..7c1ed056f91c 100644 --- a/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java +++ b/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java @@ -316,12 +316,7 @@ public class BreadcrumbsXmlWrapper implements BreadcrumbsItemListener leafs = new PriorityQueue(3, new Comparator() { - @Override - public int compare(final PsiElement o1, final PsiElement o2) { - return o2.getTextRange().getStartOffset() - o1.getTextRange().getStartOffset(); - } - }); + PriorityQueue leafs = new PriorityQueue(3, (o1, o2) -> o2.getTextRange().getStartOffset() - o1.getTextRange().getStartOffset()); FileViewProvider viewProvider = findViewProvider(file, project); if (viewProvider == null) return null; diff --git a/xml/impl/src/com/intellij/xml/config/ConfigFilesTreeBuilder.java b/xml/impl/src/com/intellij/xml/config/ConfigFilesTreeBuilder.java index 4c4f076e549e..f9aa9125527f 100644 --- a/xml/impl/src/com/intellij/xml/config/ConfigFilesTreeBuilder.java +++ b/xml/impl/src/com/intellij/xml/config/ConfigFilesTreeBuilder.java @@ -115,12 +115,7 @@ public class ConfigFilesTreeBuilder { } List sortedJars = new ArrayList(jars.keySet()); - Collections.sort(sortedJars, new Comparator() { - @Override - public int compare(VirtualFile o1, VirtualFile o2) { - return StringUtil.naturalCompare(o1.getName(), o2.getName()); - } - }); + Collections.sort(sortedJars, (o1, o2) -> StringUtil.naturalCompare(o1.getName(), o2.getName())); for (VirtualFile file : sortedJars) { final List list = new ArrayList(jars.get(file)); final PsiFile jar = list.get(0).getManager().findFile(file); @@ -163,12 +158,7 @@ public class ConfigFilesTreeBuilder { return new DefaultMutableTreeNode(file); } - private static final Comparator FILE_COMPARATOR = new Comparator() { - @Override - public int compare(final PsiFile o1, final PsiFile o2) { - return StringUtil.naturalCompare(o1.getName(), o2.getName()); - } - }; + private static final Comparator FILE_COMPARATOR = (o1, o2) -> StringUtil.naturalCompare(o1.getName(), o2.getName()); public static void renderNode(Object value, boolean expanded, ColoredTreeCellRenderer renderer) { if (!(value instanceof DefaultMutableTreeNode)) return; diff --git a/xml/impl/src/com/intellij/xml/impl/schema/SchemaDefinitionsSearch.java b/xml/impl/src/com/intellij/xml/impl/schema/SchemaDefinitionsSearch.java index b3a77fb15077..cbfd60034e19 100644 --- a/xml/impl/src/com/intellij/xml/impl/schema/SchemaDefinitionsSearch.java +++ b/xml/impl/src/com/intellij/xml/impl/schema/SchemaDefinitionsSearch.java @@ -101,26 +101,23 @@ public class SchemaDefinitionsSearch implements QueryExecutor { + final String prefixByURI = XmlUtil.findNamespacePrefixByURI(targetFile, info.getNamespaceUri()); + if (prefixByURI == null) return; + final PsiElementProcessor processor = new PsiElementProcessor() { + @Override + public boolean execute(@NotNull PsiElement element) { + if (element instanceof XmlTagImpl) { + if (isCertainTypeElement((XmlTagImpl)element, info.getTagName(), prefixByURI) || + isElementWithEmbeddedType((XmlTagImpl)element, info.getTagName(), prefixByURI)) { + consumer.process(element); + return false; } - return true; } - }; - XmlUtil.processXmlElements(targetFile, processor, true); - } + return true; + } + }; + XmlUtil.processXmlElements(targetFile, processor, true); }); } } diff --git a/xml/impl/src/com/intellij/xml/refactoring/XmlTagInplaceRenamer.java b/xml/impl/src/com/intellij/xml/refactoring/XmlTagInplaceRenamer.java index 3ae92a71c1a7..1aa976609217 100644 --- a/xml/impl/src/com/intellij/xml/refactoring/XmlTagInplaceRenamer.java +++ b/xml/impl/src/com/intellij/xml/refactoring/XmlTagInplaceRenamer.java @@ -90,41 +90,28 @@ public class XmlTagInplaceRenamer { myHighlighters = new ArrayList(); - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final int offset = myEditor.getCaretModel().getOffset(); - myEditor.getCaretModel().moveToOffset(tag.getTextOffset()); + CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { + final int offset = myEditor.getCaretModel().getOffset(); + myEditor.getCaretModel().moveToOffset(tag.getTextOffset()); - final Template t = buildTemplate(tag, pair); - TemplateManager.getInstance(project).startTemplate(myEditor, t, new TemplateEditingAdapter() { - @Override - public void templateFinished(final Template template, boolean brokenOff) { - finish(); - } + final Template t = buildTemplate(tag, pair); + TemplateManager.getInstance(project).startTemplate(myEditor, t, new TemplateEditingAdapter() { + @Override + public void templateFinished(final Template template, boolean brokenOff) { + finish(); + } - @Override - public void templateCancelled(final Template template) { - finish(); - } - }, new PairProcessor() { - @Override - public boolean process(final String variableName, final String value) { - return value.length() == 0 || value.charAt(value.length() - 1) != ' '; - } - }); + @Override + public void templateCancelled(final Template template) { + finish(); + } + }, (variableName, value) -> value.length() == 0 || value.charAt(value.length() - 1) != ' '); - // restore old offset - myEditor.getCaretModel().moveToOffset(offset); + // restore old offset + myEditor.getCaretModel().moveToOffset(offset); - addHighlights(highlightRanges, myEditor, myHighlighters); - } - }); - } - }, RefactoringBundle.message("rename.title"), null); + addHighlights(highlightRanges, myEditor, myHighlighters); + }), RefactoringBundle.message("rename.title"), null); } } diff --git a/xml/impl/src/com/intellij/xml/refactoring/XmlTagRenameDialog.java b/xml/impl/src/com/intellij/xml/refactoring/XmlTagRenameDialog.java index 80d2b82eae8f..74df57bb50f2 100644 --- a/xml/impl/src/com/intellij/xml/refactoring/XmlTagRenameDialog.java +++ b/xml/impl/src/com/intellij/xml/refactoring/XmlTagRenameDialog.java @@ -137,22 +137,14 @@ public class XmlTagRenameDialog extends RefactoringDialog { protected void doAction() { LOG.assertTrue(myElement.isValid()); - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - myTag.setName(getNewName()); - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - } - }); + CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { + try { + myTag.setName(getNewName()); } - }, RefactoringBundle.message("rename.title"), null); + catch (IncorrectOperationException e) { + LOG.error(e); + } + }), RefactoringBundle.message("rename.title"), null); close(DialogWrapper.OK_EXIT_CODE); } diff --git a/xml/impl/src/com/intellij/xml/util/UserColorLookup.java b/xml/impl/src/com/intellij/xml/util/UserColorLookup.java index ac6f473e5be2..013cfff58547 100644 --- a/xml/impl/src/com/intellij/xml/util/UserColorLookup.java +++ b/xml/impl/src/com/intellij/xml/util/UserColorLookup.java @@ -43,12 +43,7 @@ import java.util.List; */ public class UserColorLookup extends LookupElementDecorator { private static final String COLOR_STRING = XmlBundle.message("choose.color.in.color.lookup"); - private static final Function COLOR_TO_STRING_CONVERTER = new Function() { - @Override - public String fun(Color color) { - return '#' + ColorUtil.toHex(color); - } - }; + private static final Function COLOR_TO_STRING_CONVERTER = color -> '#' + ColorUtil.toHex(color); public UserColorLookup() { this(COLOR_TO_STRING_CONVERTER); diff --git a/xml/impl/src/com/intellij/xml/util/XmlEnumeratedValueReferenceProvider.java b/xml/impl/src/com/intellij/xml/util/XmlEnumeratedValueReferenceProvider.java index 32887f477032..bc69a9a73862 100644 --- a/xml/impl/src/com/intellij/xml/util/XmlEnumeratedValueReferenceProvider.java +++ b/xml/impl/src/com/intellij/xml/util/XmlEnumeratedValueReferenceProvider.java @@ -65,11 +65,8 @@ public class XmlEnumeratedValueReferenceProvider extends P } else if (unquotedValue.equals(enumerationDescriptor.getDefaultValue())) { // todo case insensitive return ContainerUtil.map2Array(enumerationDescriptor.getValueReferences((XmlElement)element, unquotedValue), PsiReference.class, - new Function() { - @Override - public PsiReference fun(PsiReference reference) { - return PsiDelegateReference.createSoft(reference, true); - } + reference -> { + return PsiDelegateReference.createSoft(reference, true); }); } } diff --git a/xml/impl/src/com/intellij/xml/util/documentation/XmlDocumentationProvider.java b/xml/impl/src/com/intellij/xml/util/documentation/XmlDocumentationProvider.java index 901037bf35be..094a44d97460 100644 --- a/xml/impl/src/com/intellij/xml/util/documentation/XmlDocumentationProvider.java +++ b/xml/impl/src/com/intellij/xml/util/documentation/XmlDocumentationProvider.java @@ -182,14 +182,11 @@ public class XmlDocumentationProvider implements DocumentationProvider { private static XmlTag findEnumerationValue(final String text, XmlTag tag) { final Ref enumerationTag = new Ref(); - Processor processor = new Processor() { - @Override - public boolean process(XmlTag xmlTag) { - if (text.equals(xmlTag.getAttributeValue(XmlUtil.VALUE_ATTR_NAME))) { - enumerationTag.set(xmlTag); - } - return true; + Processor processor = xmlTag -> { + if (text.equals(xmlTag.getAttributeValue(XmlUtil.VALUE_ATTR_NAME))) { + enumerationTag.set(xmlTag); } + return true; }; XmlUtil.processEnumerationValues(tag, processor); diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/RncCompletionData.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/RncCompletionData.java index 9b2053d25416..9a3eed91e35f 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/RncCompletionData.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/RncCompletionData.java @@ -101,11 +101,8 @@ public class RncCompletionData extends CompletionData { @Override public Object[] get(PsiElement context, CompletionContext completionContext) { - return ContainerUtil.map2Array(doGetKeywords(context), LookupElement.class, new Function() { - @Override - public LookupElement fun(String s) { - return TailTypeDecorator.withTail(LookupElementBuilder.create(s).bold(), TailType.SPACE); - } + return ContainerUtil.map2Array(doGetKeywords(context), LookupElement.class, (Function)s -> { + return TailTypeDecorator.withTail(LookupElementBuilder.create(s).bold(), TailType.SPACE); }); } diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/psi/impl/PatternReference.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/psi/impl/PatternReference.java index cffc06c68a8d..05f68b05d6d0 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/psi/impl/PatternReference.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/compact/psi/impl/PatternReference.java @@ -146,12 +146,7 @@ class PatternReference extends PsiReferenceBase.Poly implements Function final Map> map = DefinitionResolver.getAllVariants(scope); if (map == null || map.size() == 0) return ArrayUtil.EMPTY_OBJECT_ARRAY; - return ContainerUtil.mapNotNull(map.values(), new Function, Object>() { - @Override - public Object fun(Set defines) { - return defines.size() == 0 ? null : defines.iterator().next().getPsiElement(); - } - }).toArray(); + return ContainerUtil.mapNotNull(map.values(), (Function, Object>)defines -> defines.size() == 0 ? null : defines.iterator().next().getPsiElement()).toArray(); } @Override diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/inspections/BaseInspection.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/inspections/BaseInspection.java index df6768e5f5f3..1d54ff09b464 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/inspections/BaseInspection.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/inspections/BaseInspection.java @@ -112,51 +112,41 @@ public abstract class BaseInspection extends XmlSuppressableInspectionTool { } private SuppressQuickFix[] getXmlOnlySuppressions(PsiElement element) { - return ContainerUtil.map(super.getBatchSuppressActions(element), new Function() { + return ContainerUtil.map(super.getBatchSuppressActions(element), action -> new SuppressQuickFix() { + @NotNull @Override - public SuppressQuickFix fun(final SuppressQuickFix action) { - return new SuppressQuickFix() { - @NotNull - @Override - public String getName() { - return action.getName(); - } + public String getName() { + return action.getName(); + } - @Override - public boolean isAvailable(@NotNull Project project, @NotNull PsiElement context) { - return context.isValid(); - } + @Override + public boolean isAvailable(@NotNull Project project, @NotNull PsiElement context) { + return context.isValid(); + } - @Override - public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { - PsiElement element = descriptor.getPsiElement(); - PsiFile file = element == null ? null : element.getContainingFile(); - if (file == null || file.getFileType() != StdFileTypes.XML) return; - action.applyFix(project, descriptor); - } + @Override + public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { + PsiElement element1 = descriptor.getPsiElement(); + PsiFile file = element1 == null ? null : element1.getContainingFile(); + if (file == null || file.getFileType() != StdFileTypes.XML) return; + action.applyFix(project, descriptor); + } - @Override - @NotNull - public String getFamilyName() { - return action.getFamilyName(); - } + @Override + @NotNull + public String getFamilyName() { + return action.getFamilyName(); + } - @Override - public boolean isSuppressAll() { - return action.isSuppressAll(); - } - }; + @Override + public boolean isSuppressAll() { + return action.isSuppressAll(); } }, SuppressQuickFix.EMPTY_ARRAY); } private void suppress(PsiFile file, @NotNull PsiElement location) { - suppress(file, location, "#suppress " + getID(), new Function() { - @Override - public String fun(final String text) { - return text + ", " + getID(); - } - }); + suppress(file, location, "#suppress " + getID(), text -> text + ", " + getID()); } @SuppressWarnings({ "SSBasedInspection" }) diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/model/annotation/OverridingDefineRenderer.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/model/annotation/OverridingDefineRenderer.java index cecd813d7545..aada783f765f 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/model/annotation/OverridingDefineRenderer.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/model/annotation/OverridingDefineRenderer.java @@ -83,12 +83,7 @@ class OverridingDefineRenderer extends GutterIconRenderer implements DumbAware { OpenSourceUtil.navigate(true, n); } else { final Define[] array = set.toArray(new Define[set.size()]); - NavigationUtil.getPsiElementPopup(ContainerUtil.map(array, new Function() { - @Override - public PsiElement fun(Define define) { - return define.getPsiElement(); - } - }, PsiElement.EMPTY_ARRAY), title).show(new RelativePoint((MouseEvent)e.getInputEvent())); + NavigationUtil.getPsiElementPopup(ContainerUtil.map(array, define -> define.getPsiElement(), PsiElement.EMPTY_ARRAY), title).show(new RelativePoint((MouseEvent)e.getInputEvent())); } } diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/model/descriptors/RngXmlAttributeDescriptor.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/model/descriptors/RngXmlAttributeDescriptor.java index 85dd71acf168..4caceeac3c54 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/model/descriptors/RngXmlAttributeDescriptor.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/model/descriptors/RngXmlAttributeDescriptor.java @@ -151,11 +151,8 @@ public class RngXmlAttributeDescriptor extends BasicXmlAttributeDescriptor { } public Collection getDeclarations() { - return ContainerUtil.map2List(myDeclarations, new Function() { - @Override - public PsiElement fun(Locator locator) { - return myElementDescriptor.getDeclaration(locator); - } + return ContainerUtil.map2List(myDeclarations, locator -> { + return myElementDescriptor.getDeclaration(locator); }); } diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/model/resolve/RelaxIncludeIndex.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/model/resolve/RelaxIncludeIndex.java index 6cbc2e164da7..5be2ea90fc30 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/model/resolve/RelaxIncludeIndex.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/model/resolve/RelaxIncludeIndex.java @@ -62,11 +62,8 @@ public class RelaxIncludeIndex { private static boolean processRelatedFiles(PsiFile file, VirtualFile[] files, PsiElementProcessor processor) { Project project = file.getProject(); final PsiManager psiManager = PsiManager.getInstance(project); - final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, new NullableFunction() { - @Override - public PsiFile fun(VirtualFile file) { - return psiManager.findFile(file); - } + final PsiFile[] psiFiles = ContainerUtil.map2Array(files, PsiFile.class, (NullableFunction)file1 -> { + return psiManager.findFile(file1); }); for (final PsiFile psiFile : psiFiles) { diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java index aefcd3f9004f..ffa0e9323830 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java @@ -43,12 +43,8 @@ public class FileReferenceUtil { public static PsiReference[] restrict(FileReferenceSet set, final Condition cond, final Boolean soft) { final FileReference[] references = set.getAllReferences(); - return ContainerUtil.map2Array(references, PsiReference.class, new NotNullFunction() { - @Override - @NotNull - public PsiReference fun(FileReference fileReference) { - return new MyFileReference(fileReference, cond, soft); - } + return ContainerUtil.map2Array(references, PsiReference.class, (NotNullFunction)fileReference -> { + return new MyFileReference(fileReference, cond, soft); }); } diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/MessageViewHelper.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/MessageViewHelper.java index a180cec5bca6..ef647df89176 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/MessageViewHelper.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/MessageViewHelper.java @@ -101,17 +101,12 @@ public class MessageViewHelper { final VirtualFile file1 = file; ApplicationManager.getApplication().invokeLater( - new Runnable() { - @Override - public void run() { - myErrorsView.addMessage( - warning ? MessageCategory.WARNING : MessageCategory.ERROR, - new String[]{ex.getLocalizedMessage()}, - file1, - ex.getLineNumber() - 1, - ex.getColumnNumber() - 1, null); - } - } + () -> myErrorsView.addMessage( + warning ? MessageCategory.WARNING : MessageCategory.ERROR, + new String[]{ex.getLocalizedMessage()}, + file1, + ex.getLineNumber() - 1, + ex.getColumnNumber() - 1, null) ); } @@ -137,18 +132,15 @@ public class MessageViewHelper { private void openMessageViewImpl() { CommandProcessor commandProcessor = CommandProcessor.getInstance(); - commandProcessor.executeCommand(myProject, new Runnable() { - @Override - public void run() { - MessageView messageView = MessageView.SERVICE.getInstance(myProject); - Content content = ContentFactory.SERVICE.getInstance().createContent(myErrorsView.getComponent(), myContentName, true); - content.putUserData(myKey, myErrorsView); - messageView.getContentManager().addContent(content); - messageView.getContentManager().setSelectedContent(content); - messageView.getContentManager().addContentManagerListener(new CloseListener(content, myContentName, myErrorsView)); - removeOldContents(content); - messageView.getContentManager().addContentManagerListener(new MyContentDisposer(content, messageView, myKey)); - } + commandProcessor.executeCommand(myProject, () -> { + MessageView messageView = MessageView.SERVICE.getInstance(myProject); + Content content = ContentFactory.SERVICE.getInstance().createContent(myErrorsView.getComponent(), myContentName, true); + content.putUserData(myKey, myErrorsView); + messageView.getContentManager().addContent(content); + messageView.getContentManager().setSelectedContent(content); + messageView.getContentManager().addContentManagerListener(new CloseListener(content, myContentName, myErrorsView)); + removeOldContents(content); + messageView.getContentManager().addContentManagerListener(new MyContentDisposer(content, messageView, myKey)); }, "Open Message View", null); ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW).activate(null); diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/ValidateAction.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/ValidateAction.java index b664180335a5..9d9ed93a23f5 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/ValidateAction.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/validation/ValidateAction.java @@ -125,50 +125,32 @@ public class ValidateAction extends AnAction { final MessageViewHelper helper = new MessageViewHelper(project, CONTENT_NAME, KEY); - helper.openMessageView(new Runnable() { - @Override - public void run() { - doRun(project, instanceFile, schemaFile); - } - }); + helper.openMessageView(() -> doRun(project, instanceFile, schemaFile)); - final Future future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final MessageViewHelper.ErrorHandler eh = helper.new ErrorHandler(); + final Future future = ApplicationManager.getApplication().executeOnPooledThread( + () -> ApplicationManager.getApplication().runReadAction(() -> { + final MessageViewHelper.ErrorHandler eh = helper.new ErrorHandler(); - instanceFile.putUserData(IN_PROGRESS_KEY, Boolean.TRUE); - try { - doValidation(instanceFile, schemaFile, eh); - } finally { - instanceFile.putUserData(IN_PROGRESS_KEY, null); - } + instanceFile.putUserData(IN_PROGRESS_KEY, Boolean.TRUE); + try { + doValidation(instanceFile, schemaFile, eh); + } finally { + instanceFile.putUserData(IN_PROGRESS_KEY, null); + } - SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - if (!eh.hadErrorOrWarning()) { - SwingUtilities.invokeLater( - new Runnable() { - @Override - public void run() { - helper.close(); - WindowManager.getInstance().getStatusBar(project).setInfo("No errors detected"); - } - } - ); - } - } + SwingUtilities.invokeLater( + () -> { + if (!eh.hadErrorOrWarning()) { + SwingUtilities.invokeLater( + () -> { + helper.close(); + WindowManager.getInstance().getStatusBar(project).setInfo("No errors detected"); } - ); + ); + } } - }); - } - }); + ); + })); helper.setProcessController(new NewErrorTreeViewPanel.ProcessController() { @Override diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/xml/dom/impl/DefinitionReference.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/xml/dom/impl/DefinitionReference.java index e424583acb8c..ef92f31e203f 100644 --- a/xml/relaxng/src/org/intellij/plugins/relaxNG/xml/dom/impl/DefinitionReference.java +++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/xml/dom/impl/DefinitionReference.java @@ -111,24 +111,21 @@ public class DefinitionReference extends PsiReferenceBase.Poly> map = DefinitionResolver.getAllVariants(scope); if (map == null || map.size() == 0) return ArrayUtil.EMPTY_OBJECT_ARRAY; - return ContainerUtil.mapNotNull(map.values(), new Function, Object>() { - @Override - public Object fun(Set defines) { - final Define define = defines.iterator().next(); - if (defines.size() == 0) { - return null; - } else { - final PsiElement element = define.getPsiElement(); - if (element != null) { - final PsiPresentableMetaData data = (PsiPresentableMetaData)((PsiMetaOwner)element).getMetaData(); - if (data != null) { - return LookupValueFactory.createLookupValue(data.getName(), data.getIcon()); - } else { - return define.getName(); - } + return ContainerUtil.mapNotNull(map.values(), defines -> { + final Define define = defines.iterator().next(); + if (defines.size() == 0) { + return null; + } else { + final PsiElement element = define.getPsiElement(); + if (element != null) { + final PsiPresentableMetaData data = (PsiPresentableMetaData)((PsiMetaOwner)element).getMetaData(); + if (data != null) { + return LookupValueFactory.createLookupValue(data.getName(), data.getIcon()); } else { return define.getName(); } + } else { + return define.getName(); } } }).toArray(); diff --git a/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java b/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java index dc8c9fe4606d..d7f8e672630b 100644 --- a/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java +++ b/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java @@ -122,11 +122,8 @@ public abstract class HighlightingTestBase extends UsefulTestCase implements Ide public abstract String getTestDataPath(); protected void init() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("urn:test:undefined"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("urn:test:undefined"); }); } diff --git a/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlHighlightingTest.java b/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlHighlightingTest.java index 4209f2fa569a..412b24e8d8f7 100644 --- a/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlHighlightingTest.java +++ b/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlHighlightingTest.java @@ -37,37 +37,34 @@ public class RngXmlHighlightingTest extends HighlightingTestBase { protected void init() { super.init(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final ExternalResourceManagerEx m = ExternalResourceManagerEx.getInstanceEx(); - ExternalResourceManagerExImpl - .addTestResource("urn:test:simple.rng", toAbsolutePath("highlighting/simple.rng"), myTestRootDisposable); - ExternalResourceManagerExImpl.addTestResource("urn:test:addressBook", toAbsolutePath("highlighting/rnc/addressbook.rnc"), - myTestRootDisposable); - //m.addResource("http://www.w3.org/1999/XSL/Transform", toAbsolutePath("highlighting/relaxng.rng")); - ExternalResourceManagerExImpl.addTestResource("http://www.w3.org/1999/XSL/Format", toAbsolutePath("highlighting/rnc/fo/main.rnc"), - myTestRootDisposable); - ExternalResourceManagerExImpl.addTestResource("http://docbook.org/ns/docbook", toAbsolutePath("highlighting/docbook.rng"), - myTestRootDisposable); - ExternalResourceManagerExImpl.addTestResource("urn:intelliForm:AttachmentFilter", - toAbsolutePath("highlighting/attachment-filter.rng"), myTestRootDisposable); - ExternalResourceManagerExImpl - .addTestResource("http://www.w3.org/1999/xhtml", toAbsolutePath("highlighting/html5/xhtml5.rnc"), myTestRootDisposable); + ApplicationManager.getApplication().runWriteAction(() -> { + final ExternalResourceManagerEx m = ExternalResourceManagerEx.getInstanceEx(); + ExternalResourceManagerExImpl + .addTestResource("urn:test:simple.rng", toAbsolutePath("highlighting/simple.rng"), myTestRootDisposable); + ExternalResourceManagerExImpl.addTestResource("urn:test:addressBook", toAbsolutePath("highlighting/rnc/addressbook.rnc"), + myTestRootDisposable); + //m.addResource("http://www.w3.org/1999/XSL/Transform", toAbsolutePath("highlighting/relaxng.rng")); + ExternalResourceManagerExImpl.addTestResource("http://www.w3.org/1999/XSL/Format", toAbsolutePath("highlighting/rnc/fo/main.rnc"), + myTestRootDisposable); + ExternalResourceManagerExImpl.addTestResource("http://docbook.org/ns/docbook", toAbsolutePath("highlighting/docbook.rng"), + myTestRootDisposable); + ExternalResourceManagerExImpl.addTestResource("urn:intelliForm:AttachmentFilter", + toAbsolutePath("highlighting/attachment-filter.rng"), myTestRootDisposable); + ExternalResourceManagerExImpl + .addTestResource("http://www.w3.org/1999/xhtml", toAbsolutePath("highlighting/html5/xhtml5.rnc"), myTestRootDisposable); - m.addIgnoredResource("urn:intelliForm:Spaces"); - m.addIgnoredResource("http://www.w3.org/1999/xlink"); - m.addIgnoredResource("http://www.w3.org/2000/svg"); - m.addIgnoredResource("http://www.ascc.net/xml/schematron"); - m.addIgnoredResource("http://www.w3.org/2000/svg"); - m.addIgnoredResource("http://www.w3.org/1998/Math/MathML"); - m.addIgnoredResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); - m.addIgnoredResource("http://nwalsh.com/xmlns/schema-control/"); - m.addIgnoredResource("http://xml.apache.org/fop/extensions"); - m.addIgnoredResource("http://www.antennahouse.com/names/XSL/Extensions"); - m.addIgnoredResource("http://www.renderx.com/XSL/Extensions"); - m.addIgnoredResource("http://relaxng.org/ns/compatibility/annotations/1.0"); - } + m.addIgnoredResource("urn:intelliForm:Spaces"); + m.addIgnoredResource("http://www.w3.org/1999/xlink"); + m.addIgnoredResource("http://www.w3.org/2000/svg"); + m.addIgnoredResource("http://www.ascc.net/xml/schematron"); + m.addIgnoredResource("http://www.w3.org/2000/svg"); + m.addIgnoredResource("http://www.w3.org/1998/Math/MathML"); + m.addIgnoredResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); + m.addIgnoredResource("http://nwalsh.com/xmlns/schema-control/"); + m.addIgnoredResource("http://xml.apache.org/fop/extensions"); + m.addIgnoredResource("http://www.antennahouse.com/names/XSL/Extensions"); + m.addIgnoredResource("http://www.renderx.com/XSL/Extensions"); + m.addIgnoredResource("http://relaxng.org/ns/compatibility/annotations/1.0"); }); } diff --git a/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlValidationTest.java b/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlValidationTest.java index 06bff38158a8..43889f9c4d29 100644 --- a/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlValidationTest.java +++ b/xml/relaxng/test/org/intellij/plugins/relaxNG/RngXmlValidationTest.java @@ -86,14 +86,11 @@ public class RngXmlValidationTest extends HighlightingTestBase { @Override protected void init() { super.init(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - final ExternalResourceManager mgr = ExternalResourceManager.getInstance(); - mgr.addResource("urn:test:simple.rng", toAbsolutePath("validation/simple.rng")); - mgr.addResource("urn:test:simple.rnc", toAbsolutePath("validation/simple.rnc")); - //mgr.addResource("http://www.w3.org/1999/XSL/Transform", toAbsolutePath("validation/relaxng.rng")); - } + ApplicationManager.getApplication().runWriteAction(() -> { + final ExternalResourceManager mgr = ExternalResourceManager.getInstance(); + mgr.addResource("urn:test:simple.rng", toAbsolutePath("validation/simple.rng")); + mgr.addResource("urn:test:simple.rnc", toAbsolutePath("validation/simple.rnc")); + //mgr.addResource("http://www.w3.org/1999/XSL/Transform", toAbsolutePath("validation/relaxng.rng")); }); } diff --git a/xml/tests/src/com/intellij/codeInsight/XmlEventsTest.java b/xml/tests/src/com/intellij/codeInsight/XmlEventsTest.java index dfc68b2cae2a..f05c2d3df339 100644 --- a/xml/tests/src/com/intellij/codeInsight/XmlEventsTest.java +++ b/xml/tests/src/com/intellij/codeInsight/XmlEventsTest.java @@ -39,11 +39,8 @@ public class XmlEventsTest extends LightCodeInsightTestCase { public void test1() throws Exception{ final Listener listener = addPomListener(); final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - tagFromText.setAttribute("a", "b"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tagFromText.setAttribute("a", "b"); }); assertEquals("(Attribute \"a\" for tag \"a\" set to \"b\")\n", listener.getEventString()); @@ -61,11 +58,8 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("aaa"); final XmlTag otherTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); final XmlText xmlText = tagFromText.getValue().getTextElements()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlText.insertAtOffset(otherTag, 2); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlText.insertAtOffset(otherTag, 2); }); assertEquals("(text changed to 'aa' was: 'aaa'), (child added to a child: XmlText), (child added to a child: XmlTag:a)\n", listener.getEventString()); @@ -75,11 +69,8 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final Listener listener = addPomListener(); final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("aaa"); final XmlText xmlText = tagFromText.getValue().getTextElements()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlText.insertText("bb", 2); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlText.insertText("bb", 2); }); assertEquals("(text changed to 'aabba' was: 'aaa')\n", listener.getEventString()); @@ -89,13 +80,10 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final Listener listener = addPomListener(); configureFromFileText("x.xml", "aaa\nxxx\nyyy"); final XmlTag x = ((XmlFile)getFile()).getRootTag().findSubTags("x")[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - TextRange range = x.getTextRange(); - getEditor().getDocument().deleteString(range.getStartOffset(), range.getEndOffset() + 1); // plus \n - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + TextRange range = x.getTextRange(); + getEditor().getDocument().deleteString(range.getStartOffset(), range.getEndOffset() + 1); // plus \n + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); }); assertEquals("(child removed from a child: XmlTag:x), (child removed from a child: XmlText)\n", listener.getEventString()); @@ -105,13 +93,10 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final Listener listener = addPomListener(); configureFromFileText("x.xml", "aaa\nxxx\nyyy"); final XmlTag x = ((XmlFile)getFile()).getRootTag().findSubTags("x")[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - TextRange range = x.getTextRange(); - getEditor().getDocument().insertString(range.getEndOffset() + 1, "zxzz\n"); // plus \n - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + TextRange range = x.getTextRange(); + getEditor().getDocument().insertString(range.getEndOffset() + 1, "zxzz\n"); // plus \n + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); }); assertEquals("(child added to a child: XmlText), (child added to a child: XmlTag:z)\n", listener.getEventString()); @@ -120,11 +105,8 @@ public class XmlEventsTest extends LightCodeInsightTestCase { public void test4() throws Exception{ final Listener listener = addPomListener(); final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("a "); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - tagFromText.addAfter(tagFromText.getValue().getTextElements()[0], tagFromText.getValue().getTextElements()[0]); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tagFromText.addAfter(tagFromText.getValue().getTextElements()[0], tagFromText.getValue().getTextElements()[0]); }); assertEquals("(text changed to 'a a ' was: 'a ')\n", listener.getEventString()); @@ -133,11 +115,8 @@ public class XmlEventsTest extends LightCodeInsightTestCase { public void test5() throws Exception{ final Listener listener = addPomListener(); final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText("aaa"); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - tagFromText.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tagFromText.delete(); }); assertEquals("(Xml document changed)\n", listener.getEventString()); @@ -191,11 +170,8 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText(text); final XmlAttribute attribute = tag.getAttribute("name", null); assert attribute != null; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - attribute.setValue("new"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + attribute.setValue("new"); }); @@ -210,12 +186,9 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final PsiFileImpl containingFile = (PsiFileImpl)tagFromText.getContainingFile(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); final Document document = documentManager.getDocument(containingFile); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - document.insertString(positionToInsert, stringToInsert); - documentManager.commitDocument(document); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + document.insertString(positionToInsert, stringToInsert); + documentManager.commitDocument(document); }); assertEquals(events, listener.getEventString()); @@ -278,22 +251,14 @@ public class XmlEventsTest extends LightCodeInsightTestCase { final TestListener listener = new TestListener(); PsiManager.getInstance(getProject()).addPsiTreeChangeListener(listener); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - int positionToInsert = xml.indexOf(" \n"; - document.insertString(positionToInsert, stringToInsert); - documentManager.commitDocument(document); - } - }); - } - }, "", null); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + int positionToInsert = xml.indexOf(" \n"; + document.insertString(positionToInsert, stringToInsert); + documentManager.commitDocument(document); + }), "", null); PsiManager.getInstance(getProject()).removePsiTreeChangeListener(listener); } diff --git a/xml/tests/src/com/intellij/codeInsight/XmlParsingTest.java b/xml/tests/src/com/intellij/codeInsight/XmlParsingTest.java index 322dcc3467a5..c5cf32691a49 100644 --- a/xml/tests/src/com/intellij/codeInsight/XmlParsingTest.java +++ b/xml/tests/src/com/intellij/codeInsight/XmlParsingTest.java @@ -259,15 +259,12 @@ public class XmlParsingTest extends ParsingTestCase { new WriteCommandAction(getProject(), file) { @Override protected void run(@NotNull final Result result) throws Throwable { - PlatformTestUtil.startPerformanceTest("XML reparse using PsiBuilder", 2500, new ThrowableRunnable() { - @Override - public void run() throws Exception { - for (int i = 0; i < 10; i++) { - final long tm = System.currentTimeMillis(); - doc.insertString(0, ""); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - System.out.println("Reparsed for: " + (System.currentTimeMillis() - tm)); - } + PlatformTestUtil.startPerformanceTest("XML reparse using PsiBuilder", 2500, () -> { + for (int i = 0; i < 10; i++) { + final long tm = System.currentTimeMillis(); + doc.insertString(0, ""); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + System.out.println("Reparsed for: " + (System.currentTimeMillis() - tm)); } }).cpuBound().useLegacyScaling().assertTiming(); } diff --git a/xml/tests/src/com/intellij/codeInsight/XmlReparseTest.java b/xml/tests/src/com/intellij/codeInsight/XmlReparseTest.java index 4ea26221b6c3..92b47923bba7 100644 --- a/xml/tests/src/com/intellij/codeInsight/XmlReparseTest.java +++ b/xml/tests/src/com/intellij/codeInsight/XmlReparseTest.java @@ -171,11 +171,8 @@ public class XmlReparseTest extends AbstractReparseTestCase { private static void removeGarbage(Document document) { int i = document.getText().indexOf(marker); if (i==-1) return; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(i, i + marker.length(), ""); - } + ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(i, i + marker.length(), ""); }); removeGarbage(document); diff --git a/xml/tests/src/com/intellij/codeInsight/XmlTagTest.java b/xml/tests/src/com/intellij/codeInsight/XmlTagTest.java index 66be6b8a618a..5115d70dc5c3 100644 --- a/xml/tests/src/com/intellij/codeInsight/XmlTagTest.java +++ b/xml/tests/src/com/intellij/codeInsight/XmlTagTest.java @@ -88,23 +88,17 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTag childTag = rootTag.createChildTag("b", "bNamespace", null, true); assertEquals("bNamespace", childTag.getNamespace()); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - XmlTag beanTag = (XmlTag)rootTag.add(childTag); - assertEquals("bNamespace", beanTag.getNamespace()); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + XmlTag beanTag = (XmlTag)rootTag.add(childTag); + assertEquals("bNamespace", beanTag.getNamespace()); }); } public void testDeleteTag() throws Throwable { XmlTag aTag = XmlElementFactory.getInstance(getProject()).createTagFromText(" "); final XmlTag bTag = aTag.findFirstSubTag("b"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - bTag.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + bTag.delete(); }); assertEquals(0, aTag.getSubTags().length); @@ -113,13 +107,10 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testReplaceTag() throws Throwable { final XmlTag aTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); final XmlTag bTag = aTag.findFirstSubTag("b"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - PsiElement cTag = bTag.replace(XmlElementFactory.getInstance(getProject()).createTagFromText("")); - assertEquals(1, aTag.getSubTags().length); - assertEquals(cTag, aTag.getSubTags()[0]); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + PsiElement cTag = bTag.replace(XmlElementFactory.getInstance(getProject()).createTagFromText("")); + assertEquals(1, aTag.getSubTags().length); + assertEquals(cTag, aTag.getSubTags()[0]); }); } @@ -128,21 +119,15 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTag aTag = elementFactory.createTagFromText("1"); final XmlText displayText = elementFactory.createDisplayText("2"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - final PsiElement psiElement = aTag.addAfter(displayText, aTag.getValue().getChildren()[0]); - assertEquals(psiElement.getContainingFile(), aTag.getContainingFile()); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + final PsiElement psiElement = aTag.addAfter(displayText, aTag.getValue().getChildren()[0]); + assertEquals(psiElement.getContainingFile(), aTag.getContainingFile()); }); } public void testWhitespaceInsideTag() throws Exception { - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - XmlElementFactory.getInstance(getProject()).createTagFromText("

      ").getValue().setText("\n"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + XmlElementFactory.getInstance(getProject()).createTagFromText("

      ").getValue().setText("\n"); }); } @@ -150,11 +135,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { XmlFile xhtmlFile = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.xhtml", ""); final XmlTag rootTag = xhtmlFile.getDocument().getRootTag(); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - rootTag.setAttribute("foo", "bar"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + rootTag.setAttribute("foo", "bar"); }); assertEquals(1, rootTag.getAttributes().length); @@ -164,11 +146,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testSetAttribute() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - rootTag.setAttribute("foo", "bar"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + rootTag.setAttribute("foo", "bar"); }); assertEquals(1, rootTag.getAttributes().length); @@ -180,11 +159,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testSetAttributeWithQuotes() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); final String value = "a \"b\" c"; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - rootTag.setAttribute("foo", value); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + rootTag.setAttribute("foo", value); }); assertEquals(1, rootTag.getAttributes().length); @@ -196,11 +172,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testSetAttributeWithQuotes2() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); final String value = "'a \"b\" c'"; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - rootTag.setAttribute("foo", value); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + rootTag.setAttribute("foo", value); }); final String expected = value.replaceAll("\"", """); @@ -228,11 +201,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testSetAttributeWithNamespaces() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - rootTag.setAttribute("foo", "", "bar"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + rootTag.setAttribute("foo", "", "bar"); }); assertEquals(2, rootTag.getAttributes().length); @@ -244,11 +214,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testTextEdit1() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("aaa"); final XmlText xmlText = rootTag.getValue().getTextElements()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlText.removeText(0, 3); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlText.removeText(0, 3); }); assertEquals("", rootTag.getText()); @@ -256,11 +223,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testTextEdit2() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("a<a"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - rootTag.getValue().getTextElements()[0].removeText(0, 3); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + rootTag.getValue().getTextElements()[0].removeText(0, 3); }); assertEquals("", rootTag.getText()); @@ -269,11 +233,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testTextEdit3() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("a<a"); final XmlText xmlText = rootTag.getValue().getTextElements()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlText.removeText(1, 2); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlText.removeText(1, 2); }); assertEquals(1, xmlText.getChildren().length); @@ -283,11 +244,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testTextEdit4() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("aaa"); final XmlText xmlText = rootTag.getValue().getTextElements()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlText.removeText(1, 2); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlText.removeText(1, 2); }); assertEquals(1, xmlText.getChildren().length); @@ -320,11 +278,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testTextEdit6() throws Exception { final XmlTag rootTag = XmlElementFactory.getInstance(getProject()).createTagFromText("a1c"); final XmlTag xmlTag = rootTag.findFirstSubTag("b"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlTag.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlTag.delete(); }); assertEquals("ac", rootTag.getText()); @@ -332,11 +287,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testBrace() throws Exception { final XmlTag tagFromText = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - tagFromText.getValue().setText("<"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tagFromText.getValue().setText("<"); }); assertEquals("<", tagFromText.getValue().getTextElements()[0].getValue()); @@ -375,24 +327,18 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTag root = file.getDocument().getRootTag(); final XmlTag tag = root.findFirstSubTag("b"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - final int offset = tag.getTextOffset(); + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + final int offset = tag.getTextOffset(); - Document document = PsiDocumentManager.getInstance(getProject()).getDocument(root.getContainingFile()); - RangeMarker marker = document.createRangeMarker(offset - 3, offset); - tag.delete(); + Document document = PsiDocumentManager.getInstance(getProject()).getDocument(root.getContainingFile()); + RangeMarker marker = document.createRangeMarker(offset - 3, offset); + tag.delete(); - assertEquals(4, marker.getStartOffset()); - assertEquals(7, marker.getEndOffset()); - } - }, "", null); - } + assertEquals(4, marker.getStartOffset()); + assertEquals(7, marker.getEndOffset()); + }, "", null); }); } @@ -400,32 +346,26 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testRangeMarker2() throws IOException, IncorrectOperationException { final XmlTag root = createTag("file.xhtml", "1234567"); final XmlTag tag = root.findFirstSubTag("b"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - Document document = PsiDocumentManager.getInstance(getProject()).getDocument(root.getContainingFile()); - XmlTagChild child = tag.getValue().getChildren()[0]; - assertTrue(child instanceof XmlText && child.getText().equals("234")); + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + Document document = PsiDocumentManager.getInstance(getProject()).getDocument(root.getContainingFile()); + XmlTagChild child = tag.getValue().getChildren()[0]; + assertTrue(child instanceof XmlText && child.getText().equals("234")); - try { - tag.getParent().addBefore(child, tag); + try { + tag.getParent().addBefore(child, tag); - assertEquals(7, tag.getTextOffset()); - RangeMarker marker = document.createRangeMarker(4, 7); - tag.delete(); + assertEquals(7, tag.getTextOffset()); + RangeMarker marker = document.createRangeMarker(4, 7); + tag.delete(); - assertEquals(4, marker.getStartOffset()); - assertEquals(7, marker.getEndOffset()); + assertEquals(4, marker.getStartOffset()); + assertEquals(7, marker.getEndOffset()); - } - catch (IncorrectOperationException e) { - } - } - }, "", null); - } + } + catch (IncorrectOperationException e) { + } + }, "", null); }); } @@ -437,12 +377,9 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTagChild child = tag.getValue().getChildren()[0]; assertTrue(child instanceof XmlText && child.getText().equals("234")); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - assertNotNull(tag.getParent().addBefore(child, tag)); - tag.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + assertNotNull(tag.getParent().addBefore(child, tag)); + tag.delete(); }); @@ -457,12 +394,9 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTagChild child = tag.getValue().getChildren()[0]; assertTrue(child instanceof XmlText && child.getText().equals("234")); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - assertNotNull(tag.getParent().addBefore(child, tag)); - tag.delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + assertNotNull(tag.getParent().addBefore(child, tag)); + tag.delete(); }); @@ -472,11 +406,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testDisplayText() throws Throwable { final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText(" "); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - tag.add(XmlElementFactory.getInstance(getProject()).createDisplayText("aaa\nbbb")); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tag.add(XmlElementFactory.getInstance(getProject()).createDisplayText("aaa\nbbb")); }); assertEquals("aaa\nbbb", tag.getValue().getTextElements()[0].getValue()); @@ -490,12 +421,9 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTagChild[] tagElements = tagB.getValue().getChildren(); final PsiElement parent = tagB.getParent(); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - PsiElement first = parent.addBefore(tagElements[0], tagB); - assertNotNull(first); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + PsiElement first = parent.addBefore(tagElements[0], tagB); + assertNotNull(first); }); } @@ -532,11 +460,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("test.xml", "\n \n"); final XmlTag tagB = file.getDocument().getRootTag(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tagB.getSubTags()[0].delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tagB.getSubTags()[0].delete(); }); assertEquals("\n ", tagB.getText()); @@ -546,11 +471,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()) .createFileFromText("test.xml", "\n \n \n hasgdgasjdgasdg asgdjhasgd\n \n"); final XmlTag tagB = file.getDocument().getRootTag(); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - tagB.getSubTags()[0].getSubTags()[0].delete(); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + tagB.getSubTags()[0].getSubTags()[0].delete(); }); assertEquals("\n \n \n", tagB.getText()); @@ -563,19 +485,13 @@ public class XmlTagTest extends LightCodeInsightTestCase { RangeMarker rangeMarker = document.createRangeMarker(5, 5); final XmlText text = (XmlText) tag.getValue().getChildren()[0]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - try{ - text.removeText(2, 3); - } - catch(IncorrectOperationException ioe){} - } - }, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + try{ + text.removeText(2, 3); + } + catch(IncorrectOperationException ioe){} + }, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION); }); assertEquals(5, rangeMarker.getStartOffset()); @@ -584,11 +500,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testXHTMLTextInsert() throws Exception { final XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("xyz"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.getValue().getTextElements()[0].insertText("<", 1); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tag.getValue().getTextElements()[0].insertText("<", 1); }); assertEquals("x<yz", tag.getText()); @@ -628,41 +541,35 @@ public class XmlTagTest extends LightCodeInsightTestCase { } private static void doTestSimpleDeletion(final String text) throws IncorrectOperationException { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (int i = 0; i < text.length(); i++) { - for (int j = i; j < text.length(); j++) { - XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("" + text + ""); - final PsiElement[] children = tag.getValue().getTextElements(); - assertEquals(1, children.length); - final XmlText xmlText = (XmlText)children[0]; - assertEquals(text, xmlText.getText()); - xmlText.removeText(i, j); - final StringBuilder expected = new StringBuilder(text); - expected.delete(i, j); - assertEquals(expected.toString(), xmlText.getValue()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (int i = 0; i < text.length(); i++) { + for (int j = i; j < text.length(); j++) { + XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("" + text + ""); + final PsiElement[] children = tag.getValue().getTextElements(); + assertEquals(1, children.length); + final XmlText xmlText = (XmlText)children[0]; + assertEquals(text, xmlText.getText()); + xmlText.removeText(i, j); + final StringBuilder expected = new StringBuilder(text); + expected.delete(i, j); + assertEquals(expected.toString(), xmlText.getValue()); } } }); } private static void doTestSimpleInsertion(final String text, final String textToInsert) throws IncorrectOperationException { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - for (int i = 0; i <= text.length(); i++) { - XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("" + text + ""); - final PsiElement[] children = tag.getValue().getTextElements(); - assertEquals(1, children.length); - final XmlText xmlText = (XmlText)children[0]; - assertEquals(text, xmlText.getValue()); - xmlText.insertText(textToInsert, i); - final StringBuilder expected = new StringBuilder(text); - expected.insert(i, textToInsert); - assertEquals(expected.toString(), xmlText.getValue()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + for (int i = 0; i <= text.length(); i++) { + XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("" + text + ""); + final PsiElement[] children = tag.getValue().getTextElements(); + assertEquals(1, children.length); + final XmlText xmlText = (XmlText)children[0]; + assertEquals(text, xmlText.getValue()); + xmlText.insertText(textToInsert, i); + final StringBuilder expected = new StringBuilder(text); + expected.insert(i, textToInsert); + assertEquals(expected.toString(), xmlText.getValue()); } }); } @@ -737,25 +644,22 @@ public class XmlTagTest extends LightCodeInsightTestCase { } private static void doTestEscapedDeletion(final String text) throws IncorrectOperationException { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - String tagText = toEscapedText(text); - for (int i = 0; i < text.length(); i++) { - for (int j = i; j < text.length(); j++) { - XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("" + tagText + ""); - final PsiElement[] children = tag.getValue().getTextElements(); - assertEquals(1, children.length); - final XmlText xmlText = (XmlText)children[0]; - assertEquals(tagText, xmlText.getText()); - xmlText.removeText(i, j); - final StringBuilder expectedDisplay = new StringBuilder(text.replace('_', ' ')); - expectedDisplay.delete(i, j); - assertEquals(expectedDisplay.toString(), xmlText.getValue()); + ApplicationManager.getApplication().runWriteAction(() -> { + String tagText = toEscapedText(text); + for (int i = 0; i < text.length(); i++) { + for (int j = i; j < text.length(); j++) { + XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText("" + tagText + ""); + final PsiElement[] children = tag.getValue().getTextElements(); + assertEquals(1, children.length); + final XmlText xmlText = (XmlText)children[0]; + assertEquals(tagText, xmlText.getText()); + xmlText.removeText(i, j); + final StringBuilder expectedDisplay = new StringBuilder(text.replace('_', ' ')); + expectedDisplay.delete(i, j); + assertEquals(expectedDisplay.toString(), xmlText.getValue()); - final String expectedText = toEscapedText(expectedDisplay.toString()); - assertEquals(expectedText, xmlText.getText()); - } + final String expectedText = toEscapedText(expectedDisplay.toString()); + assertEquals(expectedText, xmlText.getText()); } } }); @@ -763,11 +667,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { public void testWhitespacesInEmptyXHTMLTag() throws Exception{ final XmlTag tag = XmlElementFactory.getInstance(getProject()).createXHTMLTagFromText(" "); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.findFirstSubTag("b").delete(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tag.findFirstSubTag("b").delete(); }); assertEquals(" ", tag.getText()); @@ -778,21 +679,15 @@ public class XmlTagTest extends LightCodeInsightTestCase { XmlTag tag = file.getDocument().getRootTag(); final XmlText xmlText = tag.getValue().getTextElements()[0]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - try { - xmlText.insertText("z", 1); - } - catch (IncorrectOperationException e) { - throw new RuntimeException(e); - } - } - }, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + try { + xmlText.insertText("z", 1); + } + catch (IncorrectOperationException e) { + throw new RuntimeException(e); + } + }, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION); }); assertEquals("xz y", tag.getText()); } @@ -863,11 +758,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTag tagB = tagA.findFirstSubTag("b"); final XmlTagChild nbsp = tagB.getValue().getChildren()[0]; assertEquals(" ", nbsp.getText()); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tagA.addBefore(nbsp.copy(), tagB); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tagA.addBefore(nbsp.copy(), tagB); }); XmlTagChild nbsp1 = tagA.getValue().getChildren()[0]; @@ -898,11 +790,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { } public void testStrangeCharactesInText() throws Throwable { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - XmlElementFactory.getInstance(getProject()).createTagFromText("").getValue().setText("@#$%@$%$${${''}"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + XmlElementFactory.getInstance(getProject()).createTagFromText("").getValue().setText("@#$%@$%$${${''}"); }); } @@ -912,42 +801,32 @@ public class XmlTagTest extends LightCodeInsightTestCase { tempFile.createNewFile(); FileUtil.writeToFile(tempFile, text); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - @SuppressWarnings({"ConstantConditions"}) - public void run() { - VirtualFileManager.getInstance().syncRefresh(); - XmlFile file ;//createTemporaryFile("wpd.xml", text)); - try { - file = (XmlFile)getPsiManager().findFile(VfsUtil.findFileByURL(tempFile.toURL())); - } - catch (MalformedURLException e) { - throw new RuntimeException(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + VirtualFileManager.getInstance().syncRefresh(); + XmlFile file ;//createTemporaryFile("wpd.xml", text)); + try { + file = (XmlFile)getPsiManager().findFile(VfsUtil.findFileByURL(tempFile.toURL())); + } + catch (MalformedURLException e) { + throw new RuntimeException(e); + } - final XmlTag methodTag = file.getDocument().getRootTag().findFirstSubTag("methods"); - try { - methodTag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("")); - } - catch (IncorrectOperationException e) { - throw new RuntimeException(e); - } - } - }, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION); - } + final XmlTag methodTag = file.getDocument().getRootTag().findFirstSubTag("methods"); + try { + methodTag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("")); + } + catch (IncorrectOperationException e) { + throw new RuntimeException(e); + } + }, "", null, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION); }); } public void testXmlFormattingException() throws Throwable { final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("bar"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("")); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tag.add(XmlElementFactory.getInstance(getProject()).createTagFromText("")); }); } @@ -959,11 +838,8 @@ public class XmlTagTest extends LightCodeInsightTestCase { rootTag.getSubTags()[0].getNamespace(); // fill the cache - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - rootTag.setAttribute("xmlns", "http://www.ru"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + rootTag.setAttribute("xmlns", "http://www.ru"); }); assertEquals("http://www.ru", rootTag.getSubTags()[0].getNamespace()); @@ -976,31 +852,25 @@ public class XmlTagTest extends LightCodeInsightTestCase { final XmlTag hr = body.getSubTags()[0]; final XmlText text = XmlElementFactory.getInstance(getProject()).createDisplayText("p"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - PsiElement element = hr.getParentTag().addAfter(text, hr); - assertEquals(element.getParent(), hr.getParentTag()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + PsiElement element = hr.getParentTag().addAfter(text, hr); + assertEquals(element.getParent(), hr.getParentTag()); }); } public void testCollapse() throws IncorrectOperationException { final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.collapseIfEmpty(); - assertEquals("", tag.getText()); + ApplicationManager.getApplication().runWriteAction(() -> { + tag.collapseIfEmpty(); + assertEquals("", tag.getText()); - final XmlTag tag1 = XmlElementFactory.getInstance(getProject()).createTagFromText("abc"); - tag1.collapseIfEmpty(); - assertEquals("", tag1.getText()); + final XmlTag tag1 = XmlElementFactory.getInstance(getProject()).createTagFromText("abc"); + tag1.collapseIfEmpty(); + assertEquals("", tag1.getText()); - final XmlTag tag2 = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - tag2.collapseIfEmpty(); - assertEquals("", tag2.getText()); - } + final XmlTag tag2 = XmlElementFactory.getInstance(getProject()).createTagFromText(""); + tag2.collapseIfEmpty(); + assertEquals("", tag2.getText()); }); } @@ -1008,13 +878,10 @@ public class XmlTagTest extends LightCodeInsightTestCase { XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.xml", XmlFileType.INSTANCE, "1", 0, true); final XmlTag tag = file.getDocument().getRootTag(); final Document document = file.getViewProvider().getDocument(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.setName("xxx"); - assertEquals("1", tag.getText()); - assertEquals("1", document.getText()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tag.setName("xxx"); + assertEquals("1", tag.getText()); + assertEquals("1", document.getText()); }); } @@ -1022,13 +889,10 @@ public class XmlTagTest extends LightCodeInsightTestCase { XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.xml", XmlFileType.INSTANCE, "1", 0, true); final XmlTag tag = file.getDocument().getRootTag(); final Document document = file.getViewProvider().getDocument(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - tag.setAttribute("attr", ""); - assertEquals("1", tag.getText()); - assertEquals("1", document.getText()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + tag.setAttribute("attr", ""); + assertEquals("1", tag.getText()); + assertEquals("1", document.getText()); }); } } diff --git a/xml/tests/src/com/intellij/codeInsight/XmlTagWriteTest.java b/xml/tests/src/com/intellij/codeInsight/XmlTagWriteTest.java index 39c77f1ff37b..aefcd7382640 100644 --- a/xml/tests/src/com/intellij/codeInsight/XmlTagWriteTest.java +++ b/xml/tests/src/com/intellij/codeInsight/XmlTagWriteTest.java @@ -31,11 +31,8 @@ public class XmlTagWriteTest extends LightCodeInsightTestCase{ public void test1() throws IncorrectOperationException { XmlElementFactory elementFactory = XmlElementFactory.getInstance(getProject()); final XmlTag xmlTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - xmlTag.add(xmlTag.createChildTag("tag2", XmlUtil.EMPTY_URI, null, false)); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlTag.add(xmlTag.createChildTag("tag2", XmlUtil.EMPTY_URI, null, false)); }); @@ -48,11 +45,8 @@ public class XmlTagWriteTest extends LightCodeInsightTestCase{ public void test2() throws IncorrectOperationException { final XmlTag xmlTag = XmlElementFactory.getInstance(getProject()).createTagFromText(""); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - xmlTag.add(xmlTag.createChildTag("tag2", XmlUtil.EMPTY_URI, null, false)); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + xmlTag.add(xmlTag.createChildTag("tag2", XmlUtil.EMPTY_URI, null, false)); }); @@ -67,11 +61,8 @@ public class XmlTagWriteTest extends LightCodeInsightTestCase{ final XmlTag tag = XmlElementFactory.getInstance(getProject()).createTagFromText("\n0123456"); final XmlText text = (XmlText) tag.getValue().getChildren()[0]; String textS = text.getText(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - text.insertText("lala", 2); - } + ApplicationManager.getApplication().runWriteAction(() -> { + text.insertText("lala", 2); }); XmlText text2 = (XmlText)tag.getValue().getChildren()[0]; diff --git a/xml/tests/src/com/intellij/codeInsight/completion/XmlSyncTagTest.java b/xml/tests/src/com/intellij/codeInsight/completion/XmlSyncTagTest.java index 7bf24f7f81f3..88096e2338d3 100644 --- a/xml/tests/src/com/intellij/codeInsight/completion/XmlSyncTagTest.java +++ b/xml/tests/src/com/intellij/codeInsight/completion/XmlSyncTagTest.java @@ -45,16 +45,10 @@ public abstract class XmlSyncTagTest extends LightPlatformCodeInsightFixtureTest protected void type(String toType) { for (int i = 0; i < toType.length(); i++) { final char c = toType.charAt(i); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myFixture.type(c); - } - }); - } + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + ApplicationManager.getApplication().runWriteAction(() -> { + myFixture.type(c); + }); }, "Typing", DocCommandGroupId.noneGroupId(myFixture.getEditor().getDocument()), myFixture.getEditor().getDocument()); } } @@ -68,17 +62,11 @@ public abstract class XmlSyncTagTest extends LightPlatformCodeInsightFixtureTest final String toType, final String result) { myFixture.configureByText(fileType, text); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myFixture.completeBasic(); - if (toType != null) myFixture.type(toType); - } - }); - } + CommandProcessor.getInstance().executeCommand(getProject(), () -> { + ApplicationManager.getApplication().runWriteAction(() -> { + myFixture.completeBasic(); + if (toType != null) myFixture.type(toType); + }); }, "Typing", DocCommandGroupId.noneGroupId(myFixture.getEditor().getDocument()), myFixture.getEditor().getDocument()); myFixture.checkResult(result); } diff --git a/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java b/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java index abafd38781ff..c5ac3a6516f4 100644 --- a/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java +++ b/xml/tests/src/com/intellij/codeInsight/daemon/XmlHighlightingTest.java @@ -398,11 +398,8 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { try { doDoTest(true,true); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myEditor.getDocument().insertString(myEditor.getDocument().getCharsSequence().toString().indexOf("?>") + 2, "\n"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myEditor.getDocument().insertString(myEditor.getDocument().getCharsSequence().toString().indexOf("?>") + 2, "\n"); }); doDoTest(true,true); @@ -558,11 +555,8 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { final XmlAttribute attribute = t.getAttribute("name", null); final XmlAttributeValue valueElement = attribute.getValueElement(); final PsiReference nameReference = valueElement.getReferences()[0]; - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - nameReference.handleElementRename("zzz"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + nameReference.handleElementRename("zzz"); }); } @@ -573,13 +567,10 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { public void testExternalValidatorOnValidXmlWithNamespacesNotSetup() throws Exception { final ExternalResourceManagerEx instanceEx = ExternalResourceManagerEx.getInstanceEx(); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - instanceEx.addIgnoredResource("http://xml.apache.org/axis/wsdd2/"); - instanceEx.addIgnoredResource("http://xml.apache.org/axis/wsdd2/providers/java"); - instanceEx.addIgnoredResource("http://soapinterop.org/xsd2"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + instanceEx.addIgnoredResource("http://xml.apache.org/axis/wsdd2/"); + instanceEx.addIgnoredResource("http://xml.apache.org/axis/wsdd2/providers/java"); + instanceEx.addIgnoredResource("http://soapinterop.org/xsd2"); }); doTest(getFullRelativeTestName(".xml"), true, false); @@ -589,20 +580,14 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { public void testExternalValidatorOnValidXmlWithNamespacesNotSetup2() throws Exception { final ExternalResourceManagerEx instanceEx = ExternalResourceManagerEx.getInstanceEx(); try { - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - instanceEx.addIgnoredResource(""); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + instanceEx.addIgnoredResource(""); }); doTest(getFullRelativeTestName(".xml"), true, false); } finally { - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - instanceEx.removeIgnoredResource(""); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + instanceEx.removeIgnoredResource(""); }); } } @@ -676,23 +661,20 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { doManyFilesFromSeparateDirTest( "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd", "xhtml-basic11.dtd", - new Runnable() { - @Override - public void run() { - final List attrs = new ArrayList(); + () -> { + final List attrs = new ArrayList(); - myFile.acceptChildren(new XmlRecursiveElementVisitor() { - @Override - public void visitXmlAttribute(final XmlAttribute attribute) { - if (attribute.getDescriptor() != null) attrs.add(attribute); - } - }); - - assertEquals(8, attrs.size()); - for (XmlAttribute a : attrs) { - final PsiElement element = a.getDescriptor().getDeclaration(); - assertTrue(((Navigatable)element).canNavigate()); + myFile.acceptChildren(new XmlRecursiveElementVisitor() { + @Override + public void visitXmlAttribute(final XmlAttribute attribute) { + if (attribute.getDescriptor() != null) attrs.add(attribute); } + }); + + assertEquals(8, attrs.size()); + for (XmlAttribute a : attrs) { + final PsiElement element = a.getDescriptor().getDeclaration(); + assertTrue(((Navigatable)element).canNavigate()); } } ); @@ -818,17 +800,14 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { doSchemaTestWithManyFilesFromSeparateDir( urlLocationPairs, - new Processor>() { - @Override - public boolean process(final List files) { - try { - files.set(0, getVirtualFile(BASE_PATH + getTestName(false) + "_2.xml")); - doTest(VfsUtilCore.toVirtualFileArray(files), true, false); - return true; - } - catch (Exception e) { - throw new RuntimeException(e); - } + files -> { + try { + files.set(0, getVirtualFile(BASE_PATH + getTestName(false) + "_2.xml")); + doTest(VfsUtilCore.toVirtualFileArray(files), true, false); + return true; + } + catch (Exception e) { + throw new RuntimeException(e); } } ); @@ -1079,19 +1058,13 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { } public void testIgnoredNamespaceHighlighting() throws Exception { - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("http://ignored/uri"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("http://ignored/uri"); }); doTest(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManagerEx.getInstanceEx().removeIgnoredResource("http://ignored/uri"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx.getInstanceEx().removeIgnoredResource("http://ignored/uri"); }); } @@ -1257,11 +1230,8 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { doDoTest(true, false); final String text = myEditor.getDocument().getText(); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength()); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength()); }); AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_COMMENT_BLOCK); @@ -1321,13 +1291,10 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { @HighlightingFlags(HighlightingFlag.SkipExternalValidation) public void testDocBookHighlighting() throws Exception { - doManyFilesFromSeparateDirTest("http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd", "docbookx.dtd", new Runnable() { - @Override - public void run() { - XmlTag rootTag = ((XmlFile)myFile).getDocument().getRootTag(); - PsiElement psiElement = rootTag.getReferences()[0].resolve(); - assertTrue(((Navigatable)psiElement).canNavigate()); - } + doManyFilesFromSeparateDirTest("http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd", "docbookx.dtd", () -> { + XmlTag rootTag = ((XmlFile)myFile).getDocument().getRootTag(); + PsiElement psiElement = rootTag.getReferences()[0].resolve(); + assertTrue(((Navigatable)psiElement).canNavigate()); }); } @@ -1432,11 +1399,8 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { final Editor schemaEditor = allEditors[0] == myEditor ? allEditors[1]:allEditors[0]; final String text = schemaEditor.getDocument().getText(); final String newText = text.replaceAll("xsd", "xs"); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - schemaEditor.getDocument().replaceString(0, text.length(), newText); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + schemaEditor.getDocument().replaceString(0, text.length(), newText); }); doDoTest(true, false); @@ -1602,22 +1566,16 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { Collection infos = filterInfos(doHighlighting()); assertEquals(2, infos.size()); - WriteCommandAction.runWriteCommandAction(null, new Runnable(){ - @Override - public void run() { - EditorModificationUtil.deleteSelectedText(myEditor); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + EditorModificationUtil.deleteSelectedText(myEditor); }); infos = filterInfos(doHighlighting()); assertEquals(11, infos.size()); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - EditorModificationUtil.insertStringAtCaret(myEditor, "<"); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + EditorModificationUtil.insertStringAtCaret(myEditor, "<"); }); new CodeCompletionHandlerBase(CompletionType.BASIC).invokeCompletion(myProject, myEditor); @@ -1684,11 +1642,8 @@ public class XmlHighlightingTest extends DaemonAnalyzerTestCase { BASE_PATH +testName +"-inc.xml", BASE_PATH +testName +"TestSchema.xsd" ); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("oxf:/apps/somefile.xml"); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManagerEx.getInstanceEx().addIgnoredResource("oxf:/apps/somefile.xml"); }); doDoTest(true, false, true); diff --git a/xml/tests/src/com/intellij/html/MicrodataCompletionTest.java b/xml/tests/src/com/intellij/html/MicrodataCompletionTest.java index 51576782f383..62179c839e9d 100644 --- a/xml/tests/src/com/intellij/html/MicrodataCompletionTest.java +++ b/xml/tests/src/com/intellij/html/MicrodataCompletionTest.java @@ -108,11 +108,8 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValue() throws Throwable { final VirtualFile virtualFile = myFixture.copyFileToProject("Person.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", virtualFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", virtualFile.getPath()); }); doTestInHtml("

      ", "name", "nickname", "photo", "title", "role", "url", "affiliation", "friend", "acquaintance", "address" @@ -121,11 +118,8 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValueSchemaOrgFormat() throws Throwable { final VirtualFile virtualFile = myFixture.copyFileToProject("Product.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://schema.org/Product", virtualFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://schema.org/Product", virtualFile.getPath()); }); doTestInHtml("
      \">
      ", "additionalType", @@ -163,11 +157,8 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValueSchemaOrgFormatWithLinks() throws Throwable { final VirtualFile virtualFile = myFixture.copyFileToProject("Rating.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://schema.org/Rating", virtualFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://schema.org/Rating", virtualFile.getPath()); }); doTestInHtml("
      \">
      ", "alternateName", @@ -187,12 +178,9 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValueFromTwoTypes() throws Throwable { final VirtualFile personFile = myFixture.copyFileToProject("Person.html"); final VirtualFile addressFile = myFixture.copyFileToProject("Address.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", personFile.getPath()); - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Address", addressFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", personFile.getPath()); + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Address", addressFile.getPath()); }); doTestInHtml( "
      \">
      ", @@ -203,11 +191,8 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValueFromRef() throws Throwable { final VirtualFile virtualFile = myFixture.copyFileToProject("Person.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", virtualFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", virtualFile.getPath()); }); doTestInHtml("" + "
      " + @@ -220,12 +205,9 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValueNestedScopes() throws Throwable { final VirtualFile personFile = myFixture.copyFileToProject("Person.html"); final VirtualFile addressFile = myFixture.copyFileToProject("Address.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", personFile.getPath()); - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Address", addressFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", personFile.getPath()); + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Address", addressFile.getPath()); }); doTestInHtml("
      \n" + " My name is Smith\n" + @@ -241,12 +223,9 @@ public class MicrodataCompletionTest extends CodeInsightFixtureTestCase { public void testPropValueNestedScopesDifferentTrees() throws Throwable { final VirtualFile personFile = myFixture.copyFileToProject("Person.html"); final VirtualFile addressFile = myFixture.copyFileToProject("Address.html"); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", personFile.getPath()); - ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Address", addressFile.getPath()); - } + ApplicationManager.getApplication().runWriteAction(() -> { + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Person", personFile.getPath()); + ExternalResourceManager.getInstance().addResource("http://data-vocabulary.org/Address", addressFile.getPath()); }); doTestInHtml("
      \n" + " name is ann\n" + diff --git a/xml/tests/src/com/intellij/psi/formatter/XmlFormatterTestBase.java b/xml/tests/src/com/intellij/psi/formatter/XmlFormatterTestBase.java index 73727548743d..fd30ff10bba9 100644 --- a/xml/tests/src/com/intellij/psi/formatter/XmlFormatterTestBase.java +++ b/xml/tests/src/com/intellij/psi/formatter/XmlFormatterTestBase.java @@ -14,41 +14,17 @@ public abstract class XmlFormatterTestBase extends XmlFormatterTestCase { String text = loadFile(name + ".xml", null); final XmlFileImpl file = (XmlFileImpl)createFile(name + ".xml", text); myTextRange = new TextRange(10000, 10001); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - performFormatting(file); - } - }); - } - }, "", ""); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + performFormatting(file); + }), "", ""); myTextRange = new TextRange(1000000, 1000001); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - performFormatting(file); - } - }); - } - }, "", ""); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + performFormatting(file); + }), "", ""); myTextRange = new TextRange(0, text.length()); - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - performFormatting(file); - } - }); - } - }, "", ""); + CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> { + performFormatting(file); + }), "", ""); } } diff --git a/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java b/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java index 0176a76d9d87..260bd1dbace7 100644 --- a/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java +++ b/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java @@ -73,11 +73,8 @@ public class XmlSchemaIndexTest extends LightCodeInsightFixtureTestCase { assertEquals(new ArrayList(files1).toString(), 2, files1.size()); - List names = new ArrayList(ContainerUtil.map(files1, new Function() { - @Override - public String fun(VirtualFile virtualFile) { - return virtualFile.getName(); - } + List names = new ArrayList(ContainerUtil.map(files1, virtualFile -> { + return virtualFile.getName(); })); Collections.sort(names); assertEquals(Arrays.asList("web-app_2_5.xsd", "web-app_3_0.xsd"), names); diff --git a/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddCustomHtmlElementIntentionAction.java b/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddCustomHtmlElementIntentionAction.java index 2820af06bc65..9e4d98aace9a 100644 --- a/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddCustomHtmlElementIntentionAction.java +++ b/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddCustomHtmlElementIntentionAction.java @@ -55,11 +55,6 @@ public class AddCustomHtmlElementIntentionAction implements LocalQuickFix { final PsiElement element = descriptor.getPsiElement(); InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); - profile.modifyToolSettings(myInspectionKey, element, new Consumer() { - @Override - public void consume(HtmlUnknownElementInspection tool) { - tool.addEntry(myName); - } - }); + profile.modifyToolSettings(myInspectionKey, element, tool -> tool.addEntry(myName)); } } diff --git a/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java b/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java index 201b7943ce12..099b18e236f5 100644 --- a/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java +++ b/xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/AddHtmlTagOrAttributeToCustomsIntention.java @@ -63,12 +63,9 @@ public class AddHtmlTagOrAttributeToCustomsIntention implements IntentionAction @Override public void invoke(@NotNull Project project, Editor editor, final PsiFile file) throws IncorrectOperationException { InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); - profile.modifyToolSettings(myInspectionKey, file, new Consumer() { - @Override - public void consume(InspectionProfileEntry entry) { - XmlEntitiesInspection xmlEntitiesInspection = (XmlEntitiesInspection) entry; - xmlEntitiesInspection.addEntry(myName); - } + profile.modifyToolSettings(myInspectionKey, file, entry -> { + XmlEntitiesInspection xmlEntitiesInspection = (XmlEntitiesInspection) entry; + xmlEntitiesInspection.addEntry(myName); }); } diff --git a/xml/xml-analysis-impl/src/com/intellij/xml/util/XmlRefCountHolder.java b/xml/xml-analysis-impl/src/com/intellij/xml/util/XmlRefCountHolder.java index e24e55ce0173..f3234b0ade3e 100644 --- a/xml/xml-analysis-impl/src/com/intellij/xml/util/XmlRefCountHolder.java +++ b/xml/xml-analysis-impl/src/com/intellij/xml/util/XmlRefCountHolder.java @@ -108,23 +108,21 @@ public class XmlRefCountHolder { final boolean html5 = HtmlUtil.isHtml5Context(attributeValue); // mark as duplicate - List notSoft = ContainerUtil.mapNotNull(list, new NullableFunction, XmlAttributeValue>() { - @Override - public XmlAttributeValue fun(Pair pair) { - if (html5 && !"id".equalsIgnoreCase(((XmlAttribute)pair.first.getParent()).getName())) { - // according to HTML 5 (http://www.w3.org/TR/html5/dom.html#the-id-attribute) spec - // only id attribute is unique identifier - return null; - } - if (html && pair.first.getParent().getParent() == attributeValue.getParent().getParent()) { - // according to HTML 4 (http://www.w3.org/TR/html401/struct/global.html#adef-id, - // http://www.w3.org/TR/html401/struct/links.html#h-12.2.3) spec id and name occupy - // same namespace, but having same values on one tag is ok - return null; - } - return pair.second ? null : pair.first; - } - }); + List notSoft = ContainerUtil.mapNotNull(list, + (NullableFunction, XmlAttributeValue>)pair -> { + if (html5 && !"id".equalsIgnoreCase(((XmlAttribute)pair.first.getParent()).getName())) { + // according to HTML 5 (http://www.w3.org/TR/html5/dom.html#the-id-attribute) spec + // only id attribute is unique identifier + return null; + } + if (html && pair.first.getParent().getParent() == attributeValue.getParent().getParent()) { + // according to HTML 4 (http://www.w3.org/TR/html401/struct/global.html#adef-id, + // http://www.w3.org/TR/html401/struct/links.html#h-12.2.3) spec id and name occupy + // same namespace, but having same values on one tag is ok + return null; + } + return pair.second ? null : pair.first; + }); if (!notSoft.isEmpty()) { myPossiblyDuplicateIds.addAll(notSoft); myPossiblyDuplicateIds.add(attributeValue); diff --git a/xml/xml-psi-api/src/com/intellij/xml/XmlAttributeDescriptor.java b/xml/xml-psi-api/src/com/intellij/xml/XmlAttributeDescriptor.java index 56a9604a1af8..6f43cec3f7d0 100644 --- a/xml/xml-psi-api/src/com/intellij/xml/XmlAttributeDescriptor.java +++ b/xml/xml-psi-api/src/com/intellij/xml/XmlAttributeDescriptor.java @@ -27,13 +27,7 @@ import org.jetbrains.annotations.Nullable; */ public interface XmlAttributeDescriptor extends PsiMetaData { XmlAttributeDescriptor[] EMPTY = new XmlAttributeDescriptor[0]; - ArrayFactory ARRAY_FACTORY = new ArrayFactory() { - @NotNull - @Override - public XmlAttributeDescriptor[] create(int count) { - return new XmlAttributeDescriptor[count]; - } - }; + ArrayFactory ARRAY_FACTORY = count -> new XmlAttributeDescriptor[count]; boolean isRequired(); boolean isFixed(); diff --git a/xml/xml-psi-impl/src/com/intellij/html/impl/util/MicrodataUtil.java b/xml/xml-psi-impl/src/com/intellij/html/impl/util/MicrodataUtil.java index 37b7af269afc..587abbbbac58 100644 --- a/xml/xml-psi-impl/src/com/intellij/html/impl/util/MicrodataUtil.java +++ b/xml/xml-psi-impl/src/com/intellij/html/impl/util/MicrodataUtil.java @@ -81,13 +81,9 @@ public class MicrodataUtil { super.visitXmlTag(tag); XmlAttribute refAttr = tag.getAttribute(ITEM_REF); if (refAttr != null && tag.getAttribute(ITEM_SCOPE) != null) { - getReferencesForAttributeValue(refAttr.getValueElement(), new PairFunction() { - @Nullable - @Override - public PsiReference fun(String t, Integer v) { - result.put(t, tag); - return null; - } + getReferencesForAttributeValue(refAttr.getValueElement(), (t, v) -> { + result.put(t, tag); + return null; }); } } @@ -124,17 +120,13 @@ public class MicrodataUtil { } public static PsiReference[] getUrlReferencesForAttributeValue(final XmlAttributeValue element) { - return getReferencesForAttributeValue(element, new PairFunction() { - @Nullable - @Override - public PsiReference fun(String token, Integer offset) { - if (HtmlUtil.hasHtmlPrefix(token)) { - final TextRange range = TextRange.from(offset, token.length()); - final URLReference urlReference = new URLReference(element, range, true); - return new DependentNSReference(element, range, urlReference, true); - } - return null; + return getReferencesForAttributeValue(element, (token, offset) -> { + if (HtmlUtil.hasHtmlPrefix(token)) { + final TextRange range = TextRange.from(offset, token.length()); + final URLReference urlReference = new URLReference(element, range, true); + return new DependentNSReference(element, range, urlReference, true); } + return null; }); } diff --git a/xml/xml-psi-impl/src/com/intellij/javaee/ExternalResourceManagerExImpl.java b/xml/xml-psi-impl/src/com/intellij/javaee/ExternalResourceManagerExImpl.java index e4dc1bffbdaf..ef5fd1c4ddf0 100644 --- a/xml/xml-psi-impl/src/com/intellij/javaee/ExternalResourceManagerExImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/javaee/ExternalResourceManagerExImpl.java @@ -273,20 +273,14 @@ public class ExternalResourceManagerExImpl extends ExternalResourceManagerEx imp @TestOnly public static void addTestResource(final String url, final String location, Disposable parentDisposable) { final ExternalResourceManagerExImpl instance = (ExternalResourceManagerExImpl)getInstance(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - instance.addResource(url, location); - } + ApplicationManager.getApplication().runWriteAction(() -> { + instance.addResource(url, location); }); Disposer.register(parentDisposable, new Disposable() { @Override public void dispose() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - instance.removeResource(url); - } + ApplicationManager.getApplication().runWriteAction(() -> { + instance.removeResource(url); }); } }); @@ -630,21 +624,15 @@ public class ExternalResourceManagerExImpl extends ExternalResourceManagerEx imp @TestOnly public static void registerResourceTemporarily(final String url, final String location, Disposable disposable) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - getInstance().addResource(url, location); - } + ApplicationManager.getApplication().runWriteAction(() -> { + getInstance().addResource(url, location); }); Disposer.register(disposable, new Disposable() { @Override public void dispose() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - getInstance().removeResource(url); - } + ApplicationManager.getApplication().runWriteAction(() -> { + getInstance().removeResource(url); }); } }); diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/parsing/xml/XmlParser.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/parsing/xml/XmlParser.java index b0edbdabb916..c63700b6f80e 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/parsing/xml/XmlParser.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/parsing/xml/XmlParser.java @@ -36,27 +36,22 @@ import org.jetbrains.annotations.NotNull; public class XmlParser implements PsiParser { // tries to match an old and new XmlTag by name private static final TripleFunction,ThreeState> - REPARSE_XML_TAG_BY_NAME = new TripleFunction, ThreeState>() { - @Override - public ThreeState fun(ASTNode oldNode, - LighterASTNode newNode, - FlyweightCapableTreeStructure structure) { - if (oldNode instanceof XmlTag && newNode.getTokenType() == XmlElementType.XML_TAG) { - String oldName = ((XmlTag)oldNode).getName(); - Ref childrenRef = Ref.create(null); - int count = structure.getChildren(newNode, childrenRef); - if (count < 3) return ThreeState.UNSURE; - LighterASTNode[] children = childrenRef.get(); - if (children[0].getTokenType() != XmlTokenType.XML_START_TAG_START) return ThreeState.UNSURE; - if (children[1].getTokenType() != XmlTokenType.XML_NAME) return ThreeState.UNSURE; - if (children[2].getTokenType() != XmlTokenType.XML_TAG_END) return ThreeState.UNSURE; - LighterASTTokenNode name = (LighterASTTokenNode)children[1]; - CharSequence newName = name.getText(); - if (!Comparing.equal(oldName, newName)) return ThreeState.NO; - } - - return ThreeState.UNSURE; + REPARSE_XML_TAG_BY_NAME = (oldNode, newNode, structure) -> { + if (oldNode instanceof XmlTag && newNode.getTokenType() == XmlElementType.XML_TAG) { + String oldName = ((XmlTag)oldNode).getName(); + Ref childrenRef = Ref.create(null); + int count = structure.getChildren(newNode, childrenRef); + if (count < 3) return ThreeState.UNSURE; + LighterASTNode[] children = childrenRef.get(); + if (children[0].getTokenType() != XmlTokenType.XML_START_TAG_START) return ThreeState.UNSURE; + if (children[1].getTokenType() != XmlTokenType.XML_NAME) return ThreeState.UNSURE; + if (children[2].getTokenType() != XmlTokenType.XML_TAG_END) return ThreeState.UNSURE; + LighterASTTokenNode name = (LighterASTTokenNode)children[1]; + CharSequence newName = name.getText(); + if (!Comparing.equal(oldName, newName)) return ThreeState.NO; } + + return ThreeState.UNSURE; }; @Override diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/TypeOrElementOrAttributeReference.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/TypeOrElementOrAttributeReference.java index f666a29b1801..7e137f92dc78 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/TypeOrElementOrAttributeReference.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/TypeOrElementOrAttributeReference.java @@ -222,15 +222,12 @@ public class TypeOrElementOrAttributeReference implements PsiReference { URLReference.processWsdlSchemas( document.getRootTag(), - new Processor() { - @Override - public boolean process(final XmlTag xmlTag) { - if (namespace.equals(xmlTag.getAttributeValue(TARGET_NAMESPACE))) { - descrs[0] = (XmlNSDescriptor)xmlTag.getMetaData(); - return false; - } - return true; + xmlTag -> { + if (namespace.equals(xmlTag.getAttributeValue(TARGET_NAMESPACE))) { + descrs[0] = (XmlNSDescriptor)xmlTag.getMetaData(); + return false; } + return true; } ); diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URLReference.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URLReference.java index 034cde2d327a..aa86f830b01a 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URLReference.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/URLReference.java @@ -129,23 +129,20 @@ public class URLReference implements PsiReference, EmptyResolveMessageProvider { } final PsiElement[] result = new PsiElement[1]; - processWsdlSchemas(rootTag,new Processor() { - @Override - public boolean process(final XmlTag t) { - if (canonicalText.equals(t.getAttributeValue(TARGET_NAMESPACE_ATTR_NAME))) { - result[0] = t; - return false; - } - for (XmlTag anImport : t.findSubTags("import", t.getNamespace())) { - if (canonicalText.equals(anImport.getAttributeValue("namespace"))) { - final XmlAttribute location = anImport.getAttribute("schemaLocation"); - if (location != null) { - result[0] = FileReferenceUtil.findFile(location.getValueElement()); - } + processWsdlSchemas(rootTag, t -> { + if (canonicalText.equals(t.getAttributeValue(TARGET_NAMESPACE_ATTR_NAME))) { + result[0] = t; + return false; + } + for (XmlTag anImport : t.findSubTags("import", t.getNamespace())) { + if (canonicalText.equals(anImport.getAttributeValue("namespace"))) { + final XmlAttribute location = anImport.getAttribute("schemaLocation"); + if (location != null) { + result[0] = FileReferenceUtil.findFile(location.getValueElement()); } } - return true; } + return true; }); return result[0]; diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/XmlBaseReferenceProvider.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/XmlBaseReferenceProvider.java index 7481c9a3eee5..3c95b8d3b9cf 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/XmlBaseReferenceProvider.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/XmlBaseReferenceProvider.java @@ -46,12 +46,7 @@ public class XmlBaseReferenceProvider extends PsiReferenceProvider { PsiReference reference = URIReferenceProvider.getUrlReference(element, ElementManipulators.getValueText(element)); if (reference != null) return new PsiReference[] { reference }; FileReferenceSet referenceSet = FileReferenceSet.createSet(element, false, false, false); - referenceSet.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, new Function>() { - @Override - public Collection fun(PsiFile file) { - return getContext(element, file); - } - }); + referenceSet.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, file -> getContext(element, file)); return referenceSet.getAllReferences(); } @@ -68,12 +63,7 @@ public class XmlBaseReferenceProvider extends PsiReferenceProvider { PsiReference reference = value.getReference(); if (reference instanceof PsiPolyVariantReference) { ResolveResult[] results = ((PsiPolyVariantReference)reference).multiResolve(false); - return ContainerUtil.map(results, new Function() { - @Override - public PsiFileSystemItem fun(ResolveResult result) { - return (PsiFileSystemItem)result.getElement(); - } - }); + return ContainerUtil.map(results, result -> (PsiFileSystemItem)result.getElement()); } } } diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlElementContentGroupImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlElementContentGroupImpl.java index 13b4a9f3e978..b15e0e55c3df 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlElementContentGroupImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlElementContentGroupImpl.java @@ -38,13 +38,10 @@ public class XmlElementContentGroupImpl extends XmlElementImpl implements XmlEl @NotNull @Override protected XmlContentParticle[] compute() { - return ContainerUtil.map(getChildren(TokenSet.create(XML_ELEMENT_CONTENT_GROUP, XML_NAME)), new Function() { - @Override - public XmlContentParticle fun(ASTNode astNode) { - PsiElement element = astNode.getPsi(); - assert element != null; - return element instanceof XmlToken ? new XmlContentParticleImpl((XmlToken)element) : (XmlContentParticle)element; - } + return ContainerUtil.map(getChildren(TokenSet.create(XML_ELEMENT_CONTENT_GROUP, XML_NAME)), astNode -> { + PsiElement element = astNode.getPsi(); + assert element != null; + return element instanceof XmlToken ? new XmlContentParticleImpl((XmlToken)element) : (XmlContentParticle)element; }, new XmlContentParticle[0]); } }; diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java index 5559e940f564..475dbec685b7 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java @@ -94,12 +94,7 @@ public class XmlTagImpl extends XmlElementImpl implements XmlTag, HintedReferenc .create(tags, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, tag.getContainingFile()); } }; - private static final Comparator RANGE_COMPARATOR = new Comparator() { - @Override - public int compare(TextRange range1, TextRange range2) { - return range1.getStartOffset() - range2.getStartOffset(); - } - }; + private static final Comparator RANGE_COMPARATOR = (range1, range2) -> range1.getStartOffset() - range2.getStartOffset(); private final int myHC = ourHC++; private volatile String myName; private volatile String myLocalName; diff --git a/xml/xml-psi-impl/src/com/intellij/xml/actions/validate/ValidateXmlActionHandler.java b/xml/xml-psi-impl/src/com/intellij/xml/actions/validate/ValidateXmlActionHandler.java index 0079be214349..49e368b8fc01 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/actions/validate/ValidateXmlActionHandler.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/actions/validate/ValidateXmlActionHandler.java @@ -300,12 +300,7 @@ public class ValidateXmlActionHandler { private static String[] getNamespaces(XmlFile file) { XmlTag rootTag = file.getRootTag(); if (rootTag == null) return ArrayUtil.EMPTY_STRING_ARRAY; - return ContainerUtil.mapNotNull(rootTag.getAttributes(), new Function() { - @Override - public String fun(XmlAttribute attribute) { - return attribute.getValue(); - } - }, ArrayUtil.EMPTY_STRING_ARRAY); + return ContainerUtil.mapNotNull(rootTag.getAttributes(), attribute -> attribute.getValue(), ArrayUtil.EMPTY_STRING_ARRAY); } private static long calculateTimeStamp(final VirtualFile[] files, Project myProject) { diff --git a/xml/xml-psi-impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java b/xml/xml-psi-impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java index 7a14b4c6a015..1306c0f3a950 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/impl/ExternalDocumentValidator.java @@ -139,122 +139,119 @@ public class ExternalDocumentValidator { @Override public void processError(final SAXParseException e, final ValidateXmlActionHandler.ProblemType warning) { try { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - if (e.getPublicId() != null) { - return; - } + ApplicationManager.getApplication().runReadAction(() -> { + if (e.getPublicId() != null) { + return; + } - final VirtualFile errorFile = myHandler.getProblemFile(e); - if (!Comparing.equal(errorFile, file.getVirtualFile()) && errorFile != null) { - return; // error in attached schema - } + final VirtualFile errorFile = myHandler.getProblemFile(e); + if (!Comparing.equal(errorFile, file.getVirtualFile()) && errorFile != null) { + return; // error in attached schema + } - if (document.getLineCount() < e.getLineNumber() || e.getLineNumber() <= 0) { - return; - } + if (document.getLineCount() < e.getLineNumber() || e.getLineNumber() <= 0) { + return; + } - Validator.ValidationHost.ErrorType problemType = getProblemType(warning); - int offset = Math.max(0, document.getLineStartOffset(e.getLineNumber() - 1) + e.getColumnNumber() - 2); - if (offset >= document.getTextLength()) return; - PsiElement currentElement = PsiDocumentManager.getInstance(project).getPsiFile(document).findElementAt(offset); - PsiElement originalElement = currentElement; - final String elementText = currentElement.getText(); + Validator.ValidationHost.ErrorType problemType = getProblemType(warning); + int offset = Math.max(0, document.getLineStartOffset(e.getLineNumber() - 1) + e.getColumnNumber() - 2); + if (offset >= document.getTextLength()) return; + PsiElement currentElement = PsiDocumentManager.getInstance(project).getPsiFile(document).findElementAt(offset); + PsiElement originalElement = currentElement; + final String elementText = currentElement.getText(); - if (elementText.equals("") || elementText.equals("=")) { - currentElement = currentElement.getPrevSibling(); - } + if (elementText.equals("") || elementText.equals("=")) { + currentElement = currentElement.getPrevSibling(); + } - // Cannot find the declaration of element - String localizedMessage = e.getLocalizedMessage(); + // Cannot find the declaration of element + String localizedMessage = e.getLocalizedMessage(); - // Ideally would be to switch one messageIds - int endIndex = localizedMessage.indexOf(':'); - if (endIndex < localizedMessage.length() - 1 && localizedMessage.charAt(endIndex + 1) == '/') { - endIndex = -1; // ignore : in http:// - } - String messageId = endIndex != -1 ? localizedMessage.substring(0, endIndex ):""; - localizedMessage = localizedMessage.substring(endIndex + 1).trim(); + // Ideally would be to switch one messageIds + int endIndex = localizedMessage.indexOf(':'); + if (endIndex < localizedMessage.length() - 1 && localizedMessage.charAt(endIndex + 1) == '/') { + endIndex = -1; // ignore : in http:// + } + String messageId = endIndex != -1 ? localizedMessage.substring(0, endIndex ):""; + localizedMessage = localizedMessage.substring(endIndex + 1).trim(); - if (localizedMessage.startsWith(CANNOT_FIND_DECLARATION_ERROR_PREFIX) || - localizedMessage.startsWith(ELEMENT_ERROR_PREFIX) || - localizedMessage.startsWith(ROOT_ELEMENT_ERROR_PREFIX) || - localizedMessage.startsWith(CONTENT_OF_ELEMENT_TYPE_ERROR_PREFIX) - ) { - addProblemToTagName(currentElement, originalElement, localizedMessage, warning); - //return; - } else if (localizedMessage.startsWith(VALUE_ERROR_PREFIX)) { - addProblemToTagName(currentElement, originalElement, localizedMessage, warning); - } else { - if (messageId.startsWith(ATTRIBUTE_MESSAGE_PREFIX)) { - @NonNls String prefix = "of attribute "; - final int i = localizedMessage.indexOf(prefix); + if (localizedMessage.startsWith(CANNOT_FIND_DECLARATION_ERROR_PREFIX) || + localizedMessage.startsWith(ELEMENT_ERROR_PREFIX) || + localizedMessage.startsWith(ROOT_ELEMENT_ERROR_PREFIX) || + localizedMessage.startsWith(CONTENT_OF_ELEMENT_TYPE_ERROR_PREFIX) + ) { + addProblemToTagName(currentElement, originalElement, localizedMessage, warning); + //return; + } else if (localizedMessage.startsWith(VALUE_ERROR_PREFIX)) { + addProblemToTagName(currentElement, originalElement, localizedMessage, warning); + } else { + if (messageId.startsWith(ATTRIBUTE_MESSAGE_PREFIX)) { + @NonNls String prefix = "of attribute "; + final int i = localizedMessage.indexOf(prefix); - if (i != -1) { - int messagePrefixLength = prefix.length() + i; - final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1); - String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex); + if (i != -1) { + int messagePrefixLength = prefix.length() + i; + final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1); + String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex); - XmlTag parent = PsiTreeUtil.getParentOfType(originalElement,XmlTag.class); - currentElement = parent.getAttribute(attrName,null); + XmlTag parent = PsiTreeUtil.getParentOfType(originalElement,XmlTag.class); + currentElement = parent.getAttribute(attrName,null); - if (currentElement != null) { - currentElement = ((XmlAttribute)currentElement).getValueElement(); - } - } - - if (currentElement!=null) { - assertValidElement(currentElement, originalElement,localizedMessage); - myHost.addMessage(currentElement,localizedMessage, problemType); - } else { - addProblemToTagName(originalElement, originalElement, localizedMessage, warning); - } - } - else if (localizedMessage.startsWith(ATTRIBUTE_ERROR_PREFIX)) { - final int messagePrefixLength = ATTRIBUTE_ERROR_PREFIX.length(); - - if ( localizedMessage.charAt(messagePrefixLength) == '"' || - localizedMessage.charAt(messagePrefixLength) == '\'' - ) { - // extract the attribute name from message and get it from tag! - final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1); - String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex); - - XmlTag parent = PsiTreeUtil.getParentOfType(originalElement,XmlTag.class); - currentElement = parent.getAttribute(attrName,null); - - if (currentElement!=null) { - currentElement = SourceTreeToPsiMap.treeElementToPsi( - XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild( - SourceTreeToPsiMap.psiElementToTree(currentElement) - ) - ); - } - } else { - currentElement = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class, false); - } - - if (currentElement!=null) { - assertValidElement(currentElement, originalElement,localizedMessage); - myHost.addMessage(currentElement,localizedMessage, problemType); - } else { - addProblemToTagName(originalElement, originalElement, localizedMessage, warning); - } - } else if (localizedMessage.startsWith(STRING_ERROR_PREFIX)) { if (currentElement != null) { - myHost.addMessage(currentElement,localizedMessage, Validator.ValidationHost.ErrorType.WARNING); + currentElement = ((XmlAttribute)currentElement).getValueElement(); } } - else { - currentElement = getNodeForMessage(currentElement != null ? currentElement:originalElement); + + if (currentElement!=null) { assertValidElement(currentElement, originalElement,localizedMessage); + myHost.addMessage(currentElement,localizedMessage, problemType); + } else { + addProblemToTagName(originalElement, originalElement, localizedMessage, warning); + } + } + else if (localizedMessage.startsWith(ATTRIBUTE_ERROR_PREFIX)) { + final int messagePrefixLength = ATTRIBUTE_ERROR_PREFIX.length(); + + if ( localizedMessage.charAt(messagePrefixLength) == '"' || + localizedMessage.charAt(messagePrefixLength) == '\'' + ) { + // extract the attribute name from message and get it from tag! + final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1); + String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex); + + XmlTag parent = PsiTreeUtil.getParentOfType(originalElement,XmlTag.class); + currentElement = parent.getAttribute(attrName,null); + if (currentElement!=null) { - myHost.addMessage(currentElement,localizedMessage, problemType); + currentElement = SourceTreeToPsiMap.treeElementToPsi( + XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild( + SourceTreeToPsiMap.psiElementToTree(currentElement) + ) + ); } + } else { + currentElement = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class, false); + } + + if (currentElement!=null) { + assertValidElement(currentElement, originalElement,localizedMessage); + myHost.addMessage(currentElement,localizedMessage, problemType); + } else { + addProblemToTagName(originalElement, originalElement, localizedMessage, warning); + } + } else if (localizedMessage.startsWith(STRING_ERROR_PREFIX)) { + if (currentElement != null) { + myHost.addMessage(currentElement,localizedMessage, Validator.ValidationHost.ErrorType.WARNING); + } + } + else { + currentElement = getNodeForMessage(currentElement != null ? currentElement:originalElement); + assertValidElement(currentElement, originalElement,localizedMessage); + if (currentElement!=null) { + myHost.addMessage(currentElement,localizedMessage, problemType); } } } diff --git a/xml/xml-psi-impl/src/com/intellij/xml/impl/dtd/XmlElementsGroupImpl.java b/xml/xml-psi-impl/src/com/intellij/xml/impl/dtd/XmlElementsGroupImpl.java index 9f734164b9c6..3d0e90ff6686 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/impl/dtd/XmlElementsGroupImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/impl/dtd/XmlElementsGroupImpl.java @@ -36,11 +36,8 @@ public class XmlElementsGroupImpl implements XmlElementsGroup { @NotNull @Override protected List compute() { - return ContainerUtil.map(myParticle.getSubParticles(), new Function() { - @Override - public XmlElementsGroup fun(XmlContentParticle xmlContentParticle) { - return new XmlElementsGroupImpl(xmlContentParticle, XmlElementsGroupImpl.this); - } + return ContainerUtil.map(myParticle.getSubParticles(), xmlContentParticle -> { + return new XmlElementsGroupImpl(xmlContentParticle, XmlElementsGroupImpl.this); }); } }; diff --git a/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XsdEnumerationDescriptor.java b/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XsdEnumerationDescriptor.java index 0794b39a0efc..e2e2fb9511d1 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XsdEnumerationDescriptor.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XsdEnumerationDescriptor.java @@ -68,12 +68,9 @@ public abstract class XsdEnumerationDescriptor extends Xml private String[] getEnumeratedValues(boolean forCompletion) { final List list = new SmartList(); - processEnumeration(null, new PairProcessor() { - @Override - public boolean process(PsiElement element, String s) { - list.add(s); - return true; - } + processEnumeration(null, (element, s) -> { + list.add(s); + return true; }, forCompletion); String defaultValue = getDefaultValue(); if (defaultValue != null) { @@ -120,13 +117,10 @@ public abstract class XsdEnumerationDescriptor extends Xml else { final Ref found = new Ref(Boolean.FALSE); - myExhaustiveEnum = XmlUtil.processEnumerationValues(declaration, new Processor() { - @Override - public boolean process(XmlTag tag) { - found.set(Boolean.TRUE); - XmlAttribute name = tag.getAttribute("value"); - return name == null || pairProcessor.process(tag, name.getValue()); - } + myExhaustiveEnum = XmlUtil.processEnumerationValues(declaration, tag -> { + found.set(Boolean.TRUE); + XmlAttribute name1 = tag.getAttribute("value"); + return name1 == null || pairProcessor.process(tag, name1.getValue()); }); return found.get(); } @@ -150,15 +144,12 @@ public abstract class XsdEnumerationDescriptor extends Xml @Override public PsiElement getEnumeratedValueDeclaration(XmlElement xmlElement, final String value) { final Ref result = new Ref(); - processEnumeration(getDeclaration(), new PairProcessor() { - @Override - public boolean process(PsiElement element, String s) { - if (value.equals(s)) { - result.set(element); - return false; - } - return true; + processEnumeration(getDeclaration(), (element, s) -> { + if (value.equals(s)) { + result.set(element); + return false; } + return true; }, false); return result.get(); } diff --git a/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java b/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java index 4e1063f1b62c..d2c85d242758 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java @@ -166,22 +166,18 @@ public class XmlNamespaceIndex extends XmlIndex { if (resources.size() == 1) return resources.get(0); final String fileName = schemaLocation == null ? null : new File(schemaLocation).getName(); IndexedRelevantResource resource = - Collections.max(resources, new Comparator>() { - @Override - public int compare(IndexedRelevantResource o1, - IndexedRelevantResource o2) { - if (fileName != null) { - int i = Comparing.compare(fileName.equals(o1.getFile().getName()), fileName.equals(o2.getFile().getName())); - if (i != 0) return i; - } - if (tagName != null) { - int i = Comparing.compare(o1.getValue().hasTag(tagName), o2.getValue().hasTag(tagName)); - if (i != 0) return i; - } - int i = o1.compareTo(o2); + Collections.max(resources, (o1, o2) -> { + if (fileName != null) { + int i = Comparing.compare(fileName.equals(o1.getFile().getName()), fileName.equals(o2.getFile().getName())); if (i != 0) return i; - return o1.getValue().getRating(tagName, version) - o2.getValue().getRating(tagName, version); } + if (tagName != null) { + int i = Comparing.compare(o1.getValue().hasTag(tagName), o2.getValue().hasTag(tagName)); + if (i != 0) return i; + } + int i = o1.compareTo(o2); + if (i != 0) return i; + return o1.getValue().getRating(tagName, version) - o2.getValue().getRating(tagName, version); }); if (tagName != null && !resource.getValue().hasTag(tagName)) { return null; diff --git a/xml/xml-psi-impl/src/com/intellij/xml/util/XmlIncludeHandler.java b/xml/xml-psi-impl/src/com/intellij/xml/util/XmlIncludeHandler.java index 5a7033bde3eb..128149b4778a 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/util/XmlIncludeHandler.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/util/XmlIncludeHandler.java @@ -57,12 +57,7 @@ public class XmlIncludeHandler { List references = Arrays.asList(xmlAttributeValue.getReferences()); if (references.size() > 0) { - Collections.sort(references, new Comparator() { - @Override - public int compare(PsiReference reference1, PsiReference reference2) { - return reference2.getRangeInElement().getStartOffset() - reference1.getRangeInElement().getStartOffset(); - } - }); + Collections.sort(references, (reference1, reference2) -> reference2.getRangeInElement().getStartOffset() - reference1.getRangeInElement().getStartOffset()); PsiElement target = references.get(0).resolve(); if (target instanceof XmlFile) { return (XmlFile) target; diff --git a/xml/xml-psi-impl/src/com/intellij/xml/util/XmlUtil.java b/xml/xml-psi-impl/src/com/intellij/xml/util/XmlUtil.java index 595f7626cd4d..0f7b5883bf3d 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/util/XmlUtil.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/util/XmlUtil.java @@ -251,13 +251,11 @@ public class XmlUtil { final List> resources = XmlNamespaceIndex.getResourcesByNamespace(namespace, project, module); final PsiManager psiManager = PsiManager.getInstance(project); - return ContainerUtil.mapNotNull(resources, new NullableFunction, XmlFile>() { - @Override - public XmlFile fun(IndexedRelevantResource resource) { - PsiFile file = psiManager.findFile(resource.getFile()); - return file instanceof XmlFile ? (XmlFile)file : null; - } - }); + return ContainerUtil.mapNotNull(resources, + (NullableFunction, XmlFile>)resource -> { + PsiFile file = psiManager.findFile(resource.getFile()); + return file instanceof XmlFile ? (XmlFile)file : null; + }); } @Nullable @@ -817,12 +815,7 @@ public class XmlUtil { else { final XmlAttribute[] attributes = tag.getAttributes(); ContainerUtil.sort(list); - Arrays.sort(attributes, new Comparator() { - @Override - public int compare(XmlAttribute attr1, XmlAttribute attr2) { - return attr1.getName().compareTo(attr2.getName()); - } - }); + Arrays.sort(attributes, (attr1, attr2) -> attr1.getName().compareTo(attr2.getName())); final Iterator iter = list.iterator(); list = new ArrayList(); @@ -924,12 +917,9 @@ public class XmlUtil { } public static boolean collectEnumerationValues(final XmlTag element, final HashSet variants) { - return processEnumerationValues(element, new Processor() { - @Override - public boolean process(XmlTag xmlTag) { - variants.add(xmlTag.getAttributeValue(VALUE_ATTR_NAME)); - return true; - } + return processEnumerationValues(element, xmlTag -> { + variants.add(xmlTag.getAttributeValue(VALUE_ATTR_NAME)); + return true; }); } diff --git a/xml/xml-structure-view-impl/src/com/intellij/ide/structureView/impl/xml/AbstractXmlTagTreeElement.java b/xml/xml-structure-view-impl/src/com/intellij/ide/structureView/impl/xml/AbstractXmlTagTreeElement.java index 55e994d05619..28013a4d6967 100644 --- a/xml/xml-structure-view-impl/src/com/intellij/ide/structureView/impl/xml/AbstractXmlTagTreeElement.java +++ b/xml/xml-structure-view-impl/src/com/intellij/ide/structureView/impl/xml/AbstractXmlTagTreeElement.java @@ -35,17 +35,14 @@ public abstract class AbstractXmlTagTreeElement extends Ps final XmlStructureViewElementProvider[] providers = (XmlStructureViewElementProvider[])Extensions.getExtensions(XmlStructureViewElementProvider.EXTENSION_POINT_NAME); - return ContainerUtil.map2List(subTags, new Function() { - @Override - public StructureViewTreeElement fun(final XmlTag xmlTag) { - for (final XmlStructureViewElementProvider provider : providers) { - final StructureViewTreeElement element = provider.createCustomXmlTagTreeElement(xmlTag); - if (element != null) { - return element; - } + return ContainerUtil.map2List(subTags, xmlTag -> { + for (final XmlStructureViewElementProvider provider : providers) { + final StructureViewTreeElement element = provider.createCustomXmlTagTreeElement(xmlTag); + if (element != null) { + return element; } - return new XmlTagTreeElement(xmlTag); } + return new XmlTagTreeElement(xmlTag); }); } } diff --git a/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/Html5SectionsProcessor.java b/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/Html5SectionsProcessor.java index fc5361b11f53..ea1488e9f0ef 100644 --- a/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/Html5SectionsProcessor.java +++ b/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/Html5SectionsProcessor.java @@ -87,12 +87,8 @@ class Html5SectionsProcessor { private static final String[] HEADER_ELEMENTS = {"h1", "h2", "h3", "h4", "h5", "h6"}; private static final String HGROUP_ELEMENT = "hgroup"; - private final Collection myRootSectionHolders = new SortedList(new Comparator() { - @Override - public int compare(final SectionHolder first, final SectionHolder second) { - return first.getTag().getTextRange().getStartOffset() - second.getTag().getTextRange().getStartOffset(); - } - }); + private final Collection myRootSectionHolders = new SortedList( + (first, second) -> first.getTag().getTextRange().getStartOffset() - second.getTag().getTextRange().getStartOffset()); private SectionHolder myCurrentOutlinee = null; private Section myCurrentSection = null; diff --git a/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/HtmlTagTreeElement.java b/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/HtmlTagTreeElement.java index d1a9bf897b6e..fe1f94f414c0 100644 --- a/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/HtmlTagTreeElement.java +++ b/xml/xml-structure-view-impl/src/com/intellij/lang/html/structureView/HtmlTagTreeElement.java @@ -45,11 +45,8 @@ class HtmlTagTreeElement extends PsiTreeElementBase implements LocationP final XmlTag tag = getElement(); if (tag == null || !tag.isValid()) return Collections.emptyList(); - return ContainerUtil.map2List(tag.getSubTags(), new Function() { - @Override - public StructureViewTreeElement fun(final XmlTag subTag) { - return new HtmlTagTreeElement(subTag); - } + return ContainerUtil.map2List(tag.getSubTags(), subTag -> { + return new HtmlTagTreeElement(subTag); }); }
    EXAMPLES