From 8501fbbecd003c0c84b4cbd5b53dc72480a17832 Mon Sep 17 00:00:00 2001 From: Ekaterina Tuzova Date: Fri, 14 Nov 2014 18:42:37 +0300 Subject: [PATCH 01/31] updated ipython notebook format to work with nbformat == 4 --- .../plugins/ipnb/format/IpnbParser.java | 103 ++++++++++++++---- 1 file changed, 80 insertions(+), 23 deletions(-) diff --git a/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java b/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java index 0f1f001dc3b0..9e553c7c4906 100644 --- a/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java +++ b/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java @@ -3,6 +3,8 @@ package org.jetbrains.plugins.ipnb.format; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonWriter; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import org.jetbrains.annotations.NotNull; @@ -14,6 +16,7 @@ import org.jetbrains.plugins.ipnb.format.cells.output.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -35,12 +38,19 @@ public class IpnbParser { if (rawFile == null) return new IpnbFile(new IpnbFileRaw(), Lists.newArrayList(), path); List cells = new ArrayList(); final IpnbWorksheet[] worksheets = rawFile.worksheets; - for (IpnbWorksheet worksheet : worksheets) { - final List rawCells = worksheet.cells; - for (IpnbCellRaw rawCell : rawCells) { + if (worksheets == null) { + for (IpnbCellRaw rawCell : rawFile.cells) { cells.add(rawCell.createCell()); } } + else { + for (IpnbWorksheet worksheet : worksheets) { + final List rawCells = worksheet.cells; + for (IpnbCellRaw rawCell : rawCells) { + cells.add(rawCell.createCell()); + } + } + } return new IpnbFile(rawFile, cells, path); } @@ -65,12 +75,25 @@ public class IpnbParser { } final IpnbFileRaw fileRaw = ipnbFile.getRawFile(); - final IpnbWorksheet worksheet = new IpnbWorksheet(); - for (IpnbCell cell: ipnbFile.getCells()) { - worksheet.cells.add(IpnbCellRaw.fromCell(cell)); + if (fileRaw.nbformat == 4) { + fileRaw.cells.clear(); + for (IpnbCell cell: ipnbFile.getCells()) { + fileRaw.cells.add(IpnbCellRaw.fromCell(cell, fileRaw.nbformat)); + } } - fileRaw.worksheets = new IpnbWorksheet[]{worksheet}; - return gson.toJson(fileRaw); + else { + final IpnbWorksheet worksheet = new IpnbWorksheet(); + worksheet.cells.clear(); + for (IpnbCell cell : ipnbFile.getCells()) { + worksheet.cells.add(IpnbCellRaw.fromCell(cell, fileRaw.nbformat)); + } + fileRaw.worksheets = new IpnbWorksheet[]{worksheet}; + } + final StringWriter stringWriter = new StringWriter(); + final JsonWriter writer = new JsonWriter(stringWriter); + writer.setIndent(" "); + gson.toJson(fileRaw, fileRaw.getClass(), writer); + return stringWriter.toString(); } private static void writeToFile(@NotNull final String path, @NotNull final String json) { @@ -93,10 +116,11 @@ public class IpnbParser { } public static class IpnbFileRaw { + IpnbWorksheet[] worksheets; + List cells = new ArrayList(); Map metadata = new HashMap(); int nbformat = 3; int nbformat_minor; - IpnbWorksheet[] worksheets; } private static class IpnbWorksheet { @@ -105,14 +129,16 @@ public class IpnbParser { private static class IpnbCellRaw { String cell_type; + Integer execution_count; + Map metadata = new HashMap(); Integer level; + CellOutputRaw[] outputs; String[] source; String[] input; String language; - CellOutputRaw[] outputs; Integer prompt_number; - public static IpnbCellRaw fromCell(@NotNull final IpnbCell cell) { + public static IpnbCellRaw fromCell(@NotNull final IpnbCell cell, int nbformat) { final IpnbCellRaw raw = new IpnbCellRaw(); if (cell instanceof IpnbMarkdownCell) { raw.cell_type = "markdown"; @@ -122,13 +148,19 @@ public class IpnbParser { raw.cell_type = "code"; final ArrayList outputRaws = new ArrayList(); for (IpnbOutputCell outputCell : ((IpnbCodeCell)cell).getCellOutputs()) { - outputRaws.add(CellOutputRaw.fromOutput(outputCell)); + outputRaws.add(CellOutputRaw.fromOutput(outputCell, nbformat)); } raw.outputs = outputRaws.toArray(new CellOutputRaw[outputRaws.size()]); - raw.language = ((IpnbCodeCell)cell).getLanguage(); - raw.input = ((IpnbCodeCell)cell).getSource(); final Integer promptNumber = ((IpnbCodeCell)cell).getPromptNumber(); - raw.prompt_number = promptNumber != null && promptNumber >= 0 ? promptNumber : null; + if (nbformat == 4) { + raw.execution_count = promptNumber != null && promptNumber >= 0 ? promptNumber : null; + raw.source = ((IpnbCodeCell)cell).getSource(); + } + else { + raw.prompt_number = promptNumber != null && promptNumber >= 0 ? promptNumber : null; + raw.language = ((IpnbCodeCell)cell).getLanguage(); + raw.input = ((IpnbCodeCell)cell).getSource(); + } } else if (cell instanceof IpnbRawCell) { raw.cell_type = "raw"; @@ -151,7 +183,8 @@ public class IpnbParser { for (CellOutputRaw outputRaw : outputs) { outputCells.add(outputRaw.createOutput()); } - cell = new IpnbCodeCell(language, input, prompt_number, outputCells); + cell = new IpnbCodeCell(language == null ? "python" : language, input == null ? source : input, + prompt_number == null ? execution_count : prompt_number, outputCells); } else if (cell_type.equals("raw")) { cell = new IpnbRawCell(); @@ -168,7 +201,10 @@ public class IpnbParser { private static class CellOutputRaw { String ename; + String name; String evalue; + OutputDataRaw data; + Integer execution_count; String output_type; String png; String stream; @@ -181,7 +217,7 @@ public class IpnbParser { String[] traceback; - public static CellOutputRaw fromOutput(@NotNull final IpnbOutputCell outputCell) { + public static CellOutputRaw fromOutput(@NotNull final IpnbOutputCell outputCell, int nbformat) { final CellOutputRaw raw = new CellOutputRaw(); if (outputCell instanceof IpnbPngOutputCell) { @@ -203,7 +239,12 @@ public class IpnbParser { raw.text = outputCell.getText(); } else if (outputCell instanceof IpnbStreamOutputCell) { - raw.stream = ((IpnbStreamOutputCell)outputCell).getStream(); + if (nbformat == 4) { + raw.name = ((IpnbStreamOutputCell)outputCell).getStream(); + } + else { + raw.stream = ((IpnbStreamOutputCell)outputCell).getStream(); + } raw.output_type = "stream"; raw.text = outputCell.getText(); } @@ -218,9 +259,18 @@ public class IpnbParser { raw.traceback = outputCell.getText(); } else if (outputCell instanceof IpnbOutOutputCell) { - raw.output_type = "pyout"; - raw.text = outputCell.getText(); - raw.prompt_number = outputCell.getPromptNumber(); + if (nbformat == 4) { + raw.execution_count = outputCell.getPromptNumber(); + raw.output_type = "execute_result"; + final OutputDataRaw dataRaw = new OutputDataRaw(); + dataRaw.text = outputCell.getText(); + raw.data = dataRaw; + } + else { + raw.output_type = "pyout"; + raw.prompt_number = outputCell.getPromptNumber(); + raw.text = outputCell.getText(); + } } return raw; } @@ -239,8 +289,8 @@ public class IpnbParser { else if (latex != null) { outputCell = new IpnbLatexOutputCell(latex, prompt_number, text); } - else if (stream != null) { - outputCell = new IpnbStreamOutputCell(stream, text, prompt_number); + else if (stream != null || name != null) { + outputCell = new IpnbStreamOutputCell(stream == null ? name : stream, text, prompt_number); } else if (html != null) { outputCell = new IpnbHtmlOutputCell(html, text, prompt_number); @@ -251,10 +301,17 @@ public class IpnbParser { else if ("pyout".equals(output_type)) { outputCell = new IpnbOutOutputCell(text, prompt_number); } + else if ("execute_result".equals(output_type)) { + outputCell = new IpnbOutOutputCell(data.text, execution_count); + } else { outputCell = new IpnbOutputCell(text, prompt_number); } return outputCell; } } + + private static class OutputDataRaw { + @SerializedName("text/plain") String[] text; + } } From 956108b49f07aeda8ef59d22142c5e037e853e2b Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 17 Nov 2014 11:36:57 +0100 Subject: [PATCH 02/31] inline: restore braces when needed (IDEA-132946) --- .../inline/InlineMethodProcessor.java | 2 +- .../src/com/siyeh/ig/fixes/InlineCallFix.java | 8 +++-- .../simple_setter/Parentheses.after.java | 14 ++++++++ .../simple_setter/Parentheses.java | 13 ++++++++ .../fixes/performance/InlineCallFixTest.java | 33 +++++++++++++++++++ 5 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.after.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.java create mode 100644 plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/InlineCallFixTest.java 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 8ab4fe47ce7d..d158cb7b361f 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java @@ -1252,7 +1252,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor { private static final Key MARK_KEY = Key.create(""); - private PsiReferenceExpression[] addBracesWhenNeeded(PsiReferenceExpression[] refs) throws IncorrectOperationException { + public PsiReferenceExpression[] addBracesWhenNeeded(PsiReferenceExpression[] refs) throws IncorrectOperationException { ArrayList refsVector = new ArrayList(); ArrayList addedBracesVector = new ArrayList(); myAddedClassInitializers = new HashMap(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/InlineCallFix.java b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/InlineCallFix.java index b9503e220c68..7b7be2c8c795 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/InlineCallFix.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/InlineCallFix.java @@ -62,8 +62,10 @@ public class InlineCallFix extends InspectionGadgetsFix { } protected void inline(Project project, PsiReferenceExpression methodExpression, PsiMethod method) { - new InlineMethodProcessor(project, method, methodExpression, null, true, - JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD, - JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD).inlineMethodCall(methodExpression); + final JavaRefactoringSettings settings = JavaRefactoringSettings.getInstance(); + final InlineMethodProcessor processor = new InlineMethodProcessor(project, method, methodExpression, null, true, + settings.RENAME_SEARCH_IN_COMMENTS_FOR_METHOD, + settings.RENAME_SEARCH_FOR_TEXT_FOR_METHOD); + processor.inlineMethodCall(processor.addBracesWhenNeeded(new PsiReferenceExpression[]{methodExpression})[0]); } } diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.after.java new file mode 100644 index 000000000000..ee86691391b7 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.after.java @@ -0,0 +1,14 @@ +class Test { + + private int field = 5; + + private void reproduce() { + if (field == 5) { + field = 10; + } + } + + private void setField(int value) { + field = value; + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.java new file mode 100644 index 000000000000..d06849bae487 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/simple_setter/Parentheses.java @@ -0,0 +1,13 @@ +class Test { + + private int field = 5; + + private void reproduce() { + if (field == 5) + setField(10); + } + + private void setField(int value) { + field = value; + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/InlineCallFixTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/InlineCallFixTest.java new file mode 100644 index 000000000000..ae7dd26fbf1b --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/InlineCallFixTest.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.siyeh.ig.fixes.performance; + +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.IGQuickFixesTestCase; +import com.siyeh.ig.performance.CallToSimpleSetterInClassInspection; +import com.siyeh.ig.performance.TrivialStringConcatenationInspection; + +public class InlineCallFixTest extends IGQuickFixesTestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + myFixture.enableInspections(new CallToSimpleSetterInClassInspection()); + myRelativePath = "performance/simple_setter"; + } + + public void testParentheses() { doTest(InspectionGadgetsBundle.message("call.to.simple.setter.in.class.inline.quickfix")); } +} \ No newline at end of file From 57a097f90cbe290c91011fe17f00a937d7f81b8a Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 17 Nov 2014 12:08:51 +0100 Subject: [PATCH 03/31] introduce variable: common api (IDEA-94609; IDEA-125286; IDEA-131965; IDEA-131930) --- .../InplaceIntroduceConstantPopup.java | 2 +- .../InplaceIntroduceFieldPopup.java | 2 +- .../InplaceIntroduceParameterPopup.java | 2 +- .../IntroduceVariableBase.java | 164 ++++----- .../JavaVariableInplaceIntroducer.java | 330 ++++++++++-------- .../allIncomplete.java | 6 + .../allIncomplete_after.java | 6 + .../allInsertFinal.java | 11 + .../allInsertFinal_after.java | 12 + .../inplaceIntroduceVariable/cast.java | 5 + .../castToObject.java | 5 + .../castToObject_after.java | 6 + .../inplaceIntroduceVariable/cast_after.java | 6 + .../escapePosition.java | 5 + .../escapePositionIfTyped.java | 5 + .../escapePositionIfTyped_after.java | 5 + .../escapePosition_after.java | 5 + .../fromExpression.java | 5 + .../fromExpression_after.java | 6 + .../fromParenthesis.java | 5 + .../fromParenthesis_after.java | 5 + .../inplaceIntroduceVariable/noWritable.java | 7 + .../noWritable_after.java | 8 + .../inplaceIntroduceVariable/ranges.java | 9 + .../ranges_after.java | 10 + .../inplaceIntroduceVariable/stopEditing.java | 5 + .../stopEditing_after.java | 8 + .../inplaceIntroduceVariable/writable.java | 7 + .../writable_after.java | 8 + .../ReturnNonExportedArray.after.java | 2 +- .../AbstractJavaInplaceIntroduceTest.java | 6 +- .../InplaceIntroduceVariableTest.java | 250 +++++++++++++ .../inplace/AbstractInplaceIntroducer.java | 50 +-- .../rename/inplace/InplaceRefactoring.java | 9 +- .../AbstractInplaceIntroduceTest.java | 11 +- 35 files changed, 725 insertions(+), 263 deletions(-) create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing_after.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable.java create mode 100644 java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable_after.java create mode 100644 java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceVariableTest.java 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 98645dca001e..ac2c06c28f0f 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceConstantPopup.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceConstantPopup.java @@ -230,7 +230,7 @@ public class InplaceIntroduceConstantPopup extends AbstractInplaceIntroduceField @Override protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { - return super.startsOnTheSameElement(handler, element) && handler instanceof IntroduceConstantHandler; + return handler instanceof IntroduceConstantHandler && super.startsOnTheSameElement(handler, element); } @Override diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java index 11f2d4a64079..1ad65a6b1b44 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java @@ -172,7 +172,7 @@ public class InplaceIntroduceFieldPopup extends AbstractInplaceIntroduceFieldPop @Override protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { - return super.startsOnTheSameElement(handler, element) && handler instanceof IntroduceFieldHandler; + return handler instanceof IntroduceFieldHandler && super.startsOnTheSameElement(handler, element); } @Override 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 44b0d09dac09..f36212e505eb 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterPopup.java @@ -174,7 +174,7 @@ public class InplaceIntroduceParameterPopup extends AbstractJavaInplaceIntroduce @Override protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { - return super.startsOnTheSameElement(handler, element) && handler instanceof IntroduceParameterHandler; + return handler instanceof IntroduceParameterHandler && super.startsOnTheSameElement(handler, element); } 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 ca51d31a50c9..572221b8cf78 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package com.intellij.refactoring.introduceVariable; import com.intellij.codeInsight.CodeInsightUtil; import com.intellij.codeInsight.completion.JavaCompletionUtil; import com.intellij.codeInsight.highlighting.HighlightManager; -import com.intellij.codeInsight.intention.impl.TypeExpression; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.unwrap.ScopeHighlighter; import com.intellij.featureStatistics.FeatureUsageTracker; @@ -37,10 +36,7 @@ import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.Pass; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.WindowManager; @@ -77,6 +73,7 @@ import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; import java.util.*; @@ -91,6 +88,7 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { protected static final String REFACTORING_NAME = RefactoringBundle.message("introduce.variable.title"); public static final Key NEED_PARENTHESIS = Key.create("NEED_PARENTHESIS"); + private JavaVariableInplaceIntroducer myInplaceIntroducer; public static SuggestedNameInfo getSuggestedName(@Nullable PsiType type, @NotNull final PsiExpression expression) { return getSuggestedName(type, expression, expression); @@ -645,76 +643,74 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { final Pass callback = new Pass() { @Override public void pass(final OccurrencesChooser.ReplaceChoice choice) { - final boolean allOccurences = choice == OccurrencesChooser.ReplaceChoice.ALL || choice == OccurrencesChooser.ReplaceChoice.NO_WRITE; - final Ref> variable = new Ref>(); - - final Editor topLevelEditor; - if (!InjectedLanguageManager.getInstance(project).isInjectedFragment(anchorStatement.getContainingFile())) { - topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(editor); - } else { - topLevelEditor = editor; - } - - final IntroduceVariableSettings settings; - final PsiElement chosenAnchor; if (choice != null) { - chosenAnchor = chooseAnchor(allOccurences, choice == OccurrencesChooser.ReplaceChoice.NO_WRITE, nonWrite, anchorStatementIfAll, anchorStatement); - settings = getSettings(project, topLevelEditor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, chosenAnchor, choice); - } - else { - settings = getSettings(project, topLevelEditor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, anchorStatement, choice); - chosenAnchor = chooseAnchor(settings.isReplaceAllOccurrences(), hasWriteAccess, nonWrite, anchorStatementIfAll, anchorStatement); - } - if (!settings.isOK()) { - wasSucceed[0] = false; - return; - } - typeSelectorManager.setAllOccurrences(allOccurences); - final TypeExpression expression = new TypeExpression(project, allOccurences ? typeSelectorManager.getTypesForAll() : typeSelectorManager.getTypesForOne()); - final RangeMarker exprMarker = topLevelEditor.getDocument().createRangeMarker(expr.getTextRange()); - final SuggestedNameInfo suggestedName = getSuggestedName(settings.getSelectedType(), expr, chosenAnchor); - final List occurrenceMarkers = new ArrayList(); - final boolean noWrite = choice == OccurrencesChooser.ReplaceChoice.NO_WRITE; - for (PsiExpression occurrence : occurrences) { - if (allOccurences || (noWrite && !PsiUtil.isAccessedForWriting(occurrence))) { - occurrenceMarkers.add(topLevelEditor.getDocument().createRangeMarker(occurrence.getTextRange())); + final boolean replaceAll = choice == OccurrencesChooser.ReplaceChoice.ALL || choice == OccurrencesChooser.ReplaceChoice.NO_WRITE; + typeSelectorManager.setAllOccurrences(replaceAll); + + final PsiElement chosenAnchor = + chooseAnchor(replaceAll, choice == OccurrencesChooser.ReplaceChoice.NO_WRITE, nonWrite, anchorStatementIfAll, anchorStatement); + final IntroduceVariableSettings settings = + getSettings(project, editor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, chosenAnchor, choice); + + final boolean cantChangeFinalModifier = (hasWriteAccess || inFinalContext) && choice == OccurrencesChooser.ReplaceChoice.ALL; + + final boolean noWrite = choice == OccurrencesChooser.ReplaceChoice.NO_WRITE; + final List allOccurrences = new ArrayList(); + for (PsiExpression occurrence : occurrences) { + if (expr.equals(occurrence) && expr.getParent() instanceof PsiExpressionStatement) continue; + if (choice == OccurrencesChooser.ReplaceChoice.ALL || (noWrite && !PsiUtil.isAccessedForWriting(occurrence)) || expr.equals(occurrence)) { + allOccurrences.add(occurrence); + } + } + myInplaceIntroducer = new JavaVariableInplaceIntroducer(project, + settings, + chosenAnchor, + editor, expr, cantChangeFinalModifier, + allOccurrences.toArray(new PsiExpression[allOccurrences.size()]), + typeSelectorManager, + REFACTORING_NAME); + if (myInplaceIntroducer.startInplaceIntroduceTemplate()) { + return; } } - final RefactoringEventData beforeData = new RefactoringEventData(); - beforeData.addElement(expr); - project.getMessageBus() - .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, beforeData); - final String expressionText = expr.getText(); - final Runnable runnable = introduce(project, expr, topLevelEditor, chosenAnchor, occurrences, settings, variable); + 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; + } + + PsiVariable variable = null; try { - ApplicationManager.getApplication().runWriteAction(runnable); + 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 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(); - final SmartPsiElementPointer pointer = variable.get(); - afterData.addElement(pointer != null ? pointer.getElement() : null); + afterData.addElement(variable); project.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, afterData); } - - if (isInplaceAvailableOnDataContext) { - final PsiVariable elementToRename = variable.get().getElement(); - if (elementToRename != null) { - topLevelEditor.getCaretModel().moveToOffset(elementToRename.getTextOffset()); - final boolean cantChangeFinalModifier = (hasWriteAccess || inFinalContext) && choice == OccurrencesChooser.ReplaceChoice.ALL; - final JavaVariableInplaceIntroducer renamer = - new JavaVariableInplaceIntroducer(project, expression, topLevelEditor, elementToRename, cantChangeFinalModifier, - typeSelectorManager.getTypesForAll().length > 1, exprMarker, occurrenceMarkers, - REFACTORING_NAME); - renamer.initInitialText(expressionText); - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(topLevelEditor.getDocument()); - renamer.performInplaceRefactoring(new LinkedHashSet(Arrays.asList(suggestedName.names))); - } - } } }, REFACTORING_NAME, null); } @@ -724,16 +720,25 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { callback.pass(null); } else { - OccurrencesChooser.simpleChooser(editor).showChooser(callback, occurrencesMap); + OccurrencesChooser.ReplaceChoice choice = getOccurrencesChoice(); + if (choice != null) { + callback.pass(choice); + } else { + OccurrencesChooser.simpleChooser(editor).showChooser(callback, occurrencesMap); + } } return wasSucceed[0]; } + + protected OccurrencesChooser.ReplaceChoice getOccurrencesChoice() { + return null; + } - protected PsiElement chooseAnchor(boolean allOccurences, - boolean hasWriteAccess, - List nonWrite, - PsiElement anchorStatementIfAll, - PsiElement anchorStatement) { + protected static PsiElement chooseAnchor(boolean allOccurences, + boolean hasWriteAccess, + List nonWrite, + PsiElement anchorStatementIfAll, + PsiElement anchorStatement) { if (allOccurences) { if (hasWriteAccess) { return RefactoringUtil.getAnchorElementForMultipleExpressions(nonWrite.toArray(new PsiExpression[nonWrite.size()]), null); @@ -792,13 +797,12 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { return parent3 instanceof JspHolderMethod; } - private static Runnable introduce(final Project project, - final PsiExpression expr, - final Editor editor, - final PsiElement anchorStatement, - final PsiExpression[] occurrences, - final IntroduceVariableSettings settings, - final Ref> variable) { + public static Computable introduce(final Project project, + final PsiExpression expr, + final Editor editor, + final PsiElement anchorStatement, + final PsiExpression[] occurrences, + final IntroduceVariableSettings settings) { final PsiElement container = anchorStatement.getParent(); PsiElement child = anchorStatement; if (!RefactoringUtil.isLoopOrIf(container)) { @@ -837,8 +841,9 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { final PsiCodeBlock newDeclarationScope = PsiTreeUtil.getParentOfType(container, PsiCodeBlock.class, false); final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(settings.getEnteredName(), newDeclarationScope); - return new Runnable() { - public void run() { + return new Computable() { + @Override + public PsiVariable compute() { try { PsiStatement statement = null; final boolean isInsideLoop = RefactoringUtil.isLoopOrIf(container); @@ -913,11 +918,12 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { declaration = (PsiDeclarationStatement)JavaCodeStyleManager.getInstance(project).shortenClassReferences(declaration); PsiVariable var = (PsiVariable) declaration.getDeclaredElements()[0]; PsiUtil.setModifierProperty(var, PsiModifier.FINAL, settings.isDeclareFinal()); - variable.set(SmartPointerManager.getInstance(project).createSmartPsiElementPointer(var)); fieldConflictsResolver.fix(); + return var; } catch (IncorrectOperationException e) { LOG.error(e); } + return null; } private PsiDeclarationStatement addDeclaration(PsiDeclarationStatement declaration, PsiExpression initializer) { @@ -1165,6 +1171,6 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { @Override public AbstractInplaceIntroducer getInplaceIntroducer() { - return null; + return myInplaceIntroducer; } } 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 f9e88de162cf..438009068cb9 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/JavaVariableInplaceIntroducer.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/JavaVariableInplaceIntroducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; -import com.intellij.openapi.command.impl.StartMarkAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; @@ -30,87 +29,70 @@ import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.vfs.ReadonlyStatusHandler; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; -import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; +import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.scope.processor.VariablesProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.JavaRefactoringSettings; -import com.intellij.refactoring.introduce.inplace.InplaceVariableIntroducer; +import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.introduceParameter.AbstractJavaInplaceIntroducer; import com.intellij.refactoring.rename.ResolveSnapshotProvider; import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer; import com.intellij.refactoring.ui.TypeSelectorManagerImpl; +import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.ui.NonFocusableCheckBox; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.util.ArrayList; import java.util.List; /** * User: anna * Date: 12/8/10 */ -public class JavaVariableInplaceIntroducer extends InplaceVariableIntroducer { - protected final Project myProject; - private final SmartPsiElementPointer myPointer; +public class JavaVariableInplaceIntroducer extends AbstractJavaInplaceIntroducer { + + private SmartPsiElementPointer myPointer; private JCheckBox myCanBeFinalCb; - + private IntroduceVariableSettings mySettings; + private SmartPsiElementPointer myChosenAnchor; private final boolean myCantChangeFinalModifier; - private final String myTitle; - private String myExpressionText; - protected final SmartTypePointer myDefaultType; - protected final TypeExpression myExpression; - + private boolean myHasTypeSuggestion; private ResolveSnapshotProvider.ResolveSnapshot myConflictResolver; + private TypeExpression myExpression; + private boolean myReplaceSelf; + private boolean myDeleteSelf = true; public JavaVariableInplaceIntroducer(final Project project, - final TypeExpression expression, - final Editor editor, - @NotNull final PsiVariable elementToRename, + IntroduceVariableSettings settings, PsiElement chosenAnchor, final Editor editor, + final PsiExpression expr, final boolean cantChangeFinalModifier, - final boolean hasTypeSuggestion, - final RangeMarker exprMarker, - final List occurrenceMarkers, + final PsiExpression[] occurrences, + final TypeSelectorManagerImpl selectorManager, final String title) { - super(elementToRename, editor, project, title, new PsiExpression[0], null); - myProject = project; + super(project, editor, RefactoringUtil.outermostParenthesizedExpression(expr), null, occurrences, selectorManager, title); + mySettings = settings; + myChosenAnchor = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(chosenAnchor); myCantChangeFinalModifier = cantChangeFinalModifier; + myHasTypeSuggestion = selectorManager.getTypesForAll().length > 1; myTitle = title; - setExprMarker(exprMarker); - setOccurrenceMarkers(occurrenceMarkers); - final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementToRename, PsiDeclarationStatement.class); - myPointer = declarationStatement != null ? SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationStatement) : null; - editor.putUserData(ReassignVariableUtil.DECLARATION_KEY, myPointer); - if (occurrenceMarkers != null) { - final ArrayList rangeMarkers = new ArrayList(occurrenceMarkers); - rangeMarkers.add(exprMarker); - editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, - rangeMarkers.toArray(new RangeMarker[rangeMarkers.size()])); - } - myExpression = expression; - final PsiType defaultType = elementToRename.getType(); - myDefaultType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(defaultType); - setAdvertisementText(getAdvertisementText(declarationStatement, defaultType, hasTypeSuggestion)); - } + myExpression = new TypeExpression(myProject, isReplaceAllOccurrences() + ? myTypeSelectorManager.getTypesForAll() + : myTypeSelectorManager.getTypesForOne()); - public void initInitialText(String text) { - myExpressionText = text; - } - - @Override - protected StartMarkAction startRename() throws StartMarkAction.AlreadyStartedException { - return StartMarkAction.start(myEditor, myProject, getCommandName()); + final List rangeMarkers = getOccurrenceMarkers(); + editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, + rangeMarkers.toArray(new RangeMarker[rangeMarkers.size()])); + myReplaceSelf = myExpr.getParent() instanceof PsiExpressionStatement; } @Override @@ -122,7 +104,7 @@ public class JavaVariableInplaceIntroducer extends InplaceVariableIntroducer 0 && vars[0] instanceof PsiVariable) { - final PsiFile containingFile = element.getContainingFile(); - //todo pull up method restore state - final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); - final RangeMarker exprMarker = getExprMarker(); - if (exprMarker != null) { - myExpr = AbstractJavaInplaceIntroducer.restoreExpression(containingFile, (PsiVariable)vars[0], elementFactory, exprMarker, myExpressionText); - if (myExpr != null && myExpr.isPhysical()) { - myExprMarker = createMarker(myExpr); - } - } - List markers = getOccurrenceMarkers(); - for (RangeMarker occurrenceMarker : markers) { - if (getExprMarker() != null && occurrenceMarker.getStartOffset() == getExprMarker().getStartOffset() && myExpr != null) { - continue; - } - AbstractJavaInplaceIntroducer - .restoreExpression(containingFile, (PsiVariable)vars[0], elementFactory, occurrenceMarker, myExpressionText); - } - final PsiExpression initializer = ((PsiVariable)vars[0]).getInitializer(); - if (initializer != null && Comparing.strEqual(initializer.getText(), myExpressionText) && myExpr == null) { - element.replace(JavaPsiFacade.getInstance(myProject).getElementFactory().createStatementFromText(myExpressionText, element)); - } else { - element.delete(); - } - } - } - } - }); - } - } - } - finally { - myEditor.putUserData(ReassignVariableUtil.DECLARATION_KEY, null); - for (RangeMarker occurrenceMarker : getOccurrenceMarkers()) { - occurrenceMarker.dispose(); - } - myEditor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, null); - if (getExprMarker() != null) getExprMarker().dispose(); + @Override + protected void restoreState(PsiVariable psiField) { + if (myDeleteSelf) return; + super.restoreState(psiField); + } + + @Override + protected boolean ensureValid() { + final PsiVariable variable = getVariable(); + return variable != null && isIdentifier(getInputName(), variable.getLanguage()); + } + + @Override + protected void performCleanup() { + super.performCleanup(); + super.restoreState(getVariable()); + } + + @Override + protected void deleteTemplateField(PsiVariable variable) { + if (!myDeleteSelf) return; + if (myReplaceSelf) { + variable.replace(variable.getInitializer()); + } else { + super.deleteTemplateField(variable); } } + @Override + protected void performIntroduce() { + final PsiVariable psiVariable = getVariable(); + if (psiVariable == null) { + return; + } + + TypeSelectorManagerImpl.typeSelected(psiVariable.getType(), myTypeSelectorManager.getDefaultType()); + if (myCanBeFinalCb != null) { + JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS = psiVariable.hasModifierProperty(PsiModifier.FINAL); + } + + final Document document = myEditor.getDocument(); + LOG.assertTrue(psiVariable.isValid()); + adjustLine(psiVariable, document); + + int startOffset = getExprMarker() != null && getExprMarker().isValid() ? getExprMarker().getStartOffset() : psiVariable.getTextOffset(); + final PsiFile file = psiVariable.getContainingFile(); + final PsiReference referenceAt = file.findReferenceAt(startOffset); + if (referenceAt != null && referenceAt.resolve() instanceof PsiVariable) { + startOffset = referenceAt.getElement().getTextRange().getEndOffset(); + } + else { + final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(psiVariable, PsiDeclarationStatement.class); + if (declarationStatement != null) { + startOffset = declarationStatement.getTextRange().getEndOffset(); + } + } + + 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()); + } + } + }); + } + + @Override + public boolean isReplaceAllOccurrences() { + return mySettings.isReplaceAllOccurrences(); + } + + @Override + public void setReplaceAllOccurrences(boolean allOccurrences) {} + + @Override + protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { + return handler instanceof IntroduceVariableHandler && super.startsOnTheSameElement(handler, element); + } @Nullable protected JComponent getComponent() { @@ -265,8 +240,27 @@ public class JavaVariableInplaceIntroducer extends InplaceVariableIntroducer> stringUsages) { + if (isReplaceAllOccurrences()) { + for (PsiExpression expression : getOccurrences()) { + LOG.assertTrue(expression.isValid(), expression.getText()); + stringUsages.add(Pair.create(expression, new TextRange(0, expression.getTextLength()))); + } + } else if (getExpr() != null && !myReplaceSelf) { + final PsiExpression expr = getExpr(); + LOG.assertTrue(expr.isValid(), expr.getText()); + stringUsages.add(Pair.create(expr, new TextRange(0, expr.getTextLength()))); + } } private static void appendTypeCasts(List occurrenceMarkers, @@ -353,21 +347,49 @@ public class JavaVariableInplaceIntroducer extends InplaceVariableIntroducer 0) { - return "Press " + shortcuts[0] + " to change type"; + @Override + protected int getCaretOffset() { + final PsiVariable variable = getVariable(); + if (variable != null) { + final PsiIdentifier identifier = variable.getNameIdentifier(); + if (identifier != null) { + return identifier.getTextOffset(); } } - return null; + return super.getCaretOffset(); + } + + @Override + protected String[] suggestNames(PsiType defaultType, String propName) { + return IntroduceVariableBase.getSuggestedName(defaultType, myExpr).names; + } + + @Override + protected VariableKind getVariableKind() { + return VariableKind.LOCAL_VARIABLE; } } diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete.java new file mode 100644 index 000000000000..377da56e3975 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete.java @@ -0,0 +1,6 @@ +class C { + { + new C(); + new C(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete_after.java new file mode 100644 index 000000000000..f83b8e61cd52 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allIncomplete_after.java @@ -0,0 +1,6 @@ +class C { + { + C c = new C(); + c; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal.java new file mode 100644 index 000000000000..476e9111cdfb --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal.java @@ -0,0 +1,11 @@ +class C { + { + C c = new C(); + Runnable r = new Runnable() { + @Override + public void run() { + new C(); + } + }; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal_after.java new file mode 100644 index 000000000000..c6f2df805826 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/allInsertFinal_after.java @@ -0,0 +1,12 @@ +class C { + { + final C c1 = new C(); + C c = c1; + Runnable r = new Runnable() { + @Override + public void run() { + c1; + } + }; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast.java new file mode 100644 index 000000000000..f175eb2b1b32 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject.java new file mode 100644 index 000000000000..f175eb2b1b32 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject_after.java new file mode 100644 index 000000000000..0e98b27791c3 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/castToObject_after.java @@ -0,0 +1,6 @@ +class C { + { + Object c1 = new C(); + C c = (C) c1; + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast_after.java new file mode 100644 index 000000000000..04af17ef8d89 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/cast_after.java @@ -0,0 +1,6 @@ +class C { + { + Integer c1 = (Integer) new C(); + C c = (C) c1; + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition.java new file mode 100644 index 000000000000..f175eb2b1b32 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped.java new file mode 100644 index 000000000000..f175eb2b1b32 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped_after.java new file mode 100644 index 000000000000..2cbdef758fe1 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePositionIfTyped_after.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition_after.java new file mode 100644 index 000000000000..2cbdef758fe1 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/escapePosition_after.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression.java new file mode 100644 index 000000000000..ea322fae5609 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression_after.java new file mode 100644 index 000000000000..f9a85d873dd3 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromExpression_after.java @@ -0,0 +1,6 @@ +class C { + { + C expr = new C(); + C c = expr; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis.java new file mode 100644 index 000000000000..5cdaaed4c679 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis.java @@ -0,0 +1,5 @@ +class C { + { + (new C()); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis_after.java new file mode 100644 index 000000000000..eaf079348a53 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/fromParenthesis_after.java @@ -0,0 +1,5 @@ +class C { + { + C expr = new C(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable.java new file mode 100644 index 000000000000..f577e27bde64 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable.java @@ -0,0 +1,7 @@ +class C { + { + int[] a = new int[1]; + a[1] = 42; + System.out.println(a[1]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable_after.java new file mode 100644 index 000000000000..803af2c8f1da --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/noWritable_after.java @@ -0,0 +1,8 @@ +class C { + { + int[] a = new int[1]; + a[1] = 42; + int x = a[1]; + System.out.println(x); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges.java new file mode 100644 index 000000000000..52c72d38f322 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges.java @@ -0,0 +1,9 @@ +class Bar {} +class Foo { + static Bar bar; +} +class C { + { + Bar b = Foo.bar; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges_after.java new file mode 100644 index 000000000000..9c92767441f5 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/ranges_after.java @@ -0,0 +1,10 @@ +class Bar {} +class Foo { + static Bar bar; +} +class C { + { + Bar expr = Foo.bar; + Bar b = expr; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing.java new file mode 100644 index 000000000000..ea322fae5609 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing.java @@ -0,0 +1,5 @@ +class C { + { + C c = new C(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing_after.java new file mode 100644 index 000000000000..26a73045f173 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/stopEditing_after.java @@ -0,0 +1,8 @@ +class C { + { + C + + c1 = new C(); + C c = c1; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable.java new file mode 100644 index 000000000000..f577e27bde64 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable.java @@ -0,0 +1,7 @@ +class C { + { + int[] a = new int[1]; + a[1] = 42; + System.out.println(a[1]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable_after.java new file mode 100644 index 000000000000..66a0280705f0 --- /dev/null +++ b/java/java-tests/testData/refactoring/inplaceIntroduceVariable/writable_after.java @@ -0,0 +1,8 @@ +class C { + { + int[] a = new int[1]; + int x = a[1]; + x = 42; + System.out.println(x); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceVariable/ReturnNonExportedArray.after.java b/java/java-tests/testData/refactoring/introduceVariable/ReturnNonExportedArray.after.java index ebd5a17ad231..bcf896651037 100644 --- a/java/java-tests/testData/refactoring/introduceVariable/ReturnNonExportedArray.after.java +++ b/java/java-tests/testData/refactoring/introduceVariable/ReturnNonExportedArray.after.java @@ -3,6 +3,6 @@ import java.io.File; class Test { java.io.File[] get() {return null;} { - File[] files = get(); + File[] i = get(); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/AbstractJavaInplaceIntroduceTest.java b/java/java-tests/testSrc/com/intellij/refactoring/AbstractJavaInplaceIntroduceTest.java index 4f2cb602af67..9cd5d069c875 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/AbstractJavaInplaceIntroduceTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/AbstractJavaInplaceIntroduceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,6 +72,10 @@ public abstract class AbstractJavaInplaceIntroduceTest extends AbstractInplaceIn @Override protected AbstractInplaceIntroducer invokeRefactoring() { final MyIntroduceHandler introduceHandler = createIntroduceHandler(); + return invokeRefactoring(introduceHandler); + } + + protected AbstractInplaceIntroducer invokeRefactoring(MyIntroduceHandler introduceHandler) { final PsiExpression expression = getExpressionFromEditor(); if (expression != null) { introduceHandler.invokeImpl(LightPlatformTestCase.getProject(), expression, getEditor()); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceVariableTest.java b/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceVariableTest.java new file mode 100644 index 000000000000..6e75fbb2bdd8 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceVariableTest.java @@ -0,0 +1,250 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.refactoring; + +import com.intellij.codeInsight.template.impl.TemplateManagerImpl; +import com.intellij.codeInsight.template.impl.TemplateState; +import com.intellij.openapi.actionSystem.IdeActions; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.actionSystem.EditorActionManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Pass; +import com.intellij.psi.PsiExpression; +import com.intellij.psi.PsiLiteralExpression; +import com.intellij.psi.PsiLocalVariable; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.refactoring.introduce.inplace.AbstractInplaceIntroducer; +import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; +import com.intellij.refactoring.introduceVariable.IntroduceVariableHandler; +import com.intellij.testFramework.MapDataContext; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class InplaceIntroduceVariableTest extends AbstractJavaInplaceIntroduceTest { + + @Nullable + @Override + protected PsiExpression getExpressionFromEditor() { + final PsiExpression expression = super.getExpressionFromEditor(); + if (expression != null) { + return expression; + } + final PsiExpression expr = PsiTreeUtil.getParentOfType(getFile().findElementAt(getEditor().getCaretModel().getOffset()), PsiExpression.class); + return expr instanceof PsiLiteralExpression ? expr : null; + } + + public void testFromExpression() throws Exception { + doTest(new Pass() { + @Override + public void pass(AbstractInplaceIntroducer inplaceIntroduceFieldPopup) { + type("expr"); + } + }); + } + + public void testRanges() throws Exception { + doTest(new Pass() { + @Override + public void pass(AbstractInplaceIntroducer inplaceIntroduceFieldPopup) { + type("expr"); + } + }); + } + + public void testFromParenthesis() throws Exception { + doTest(new Pass() { + @Override + public void pass(AbstractInplaceIntroducer inplaceIntroduceFieldPopup) { + type("expr"); + } + }); + } + + public void testCast() throws Exception { + doTestTypeChange("Integer"); + } + + public void testCastToObject() throws Exception { + doTestTypeChange("Object"); + } + + public void testEscapePosition() { + doTestStopEditing(new Pass() { + @Override + public void pass(AbstractInplaceIntroducer introducer) { + invokeEditorAction(IdeActions.ACTION_EDITOR_ESCAPE); + invokeEditorAction(IdeActions.ACTION_EDITOR_ESCAPE); + } + }); + } + + public void testEscapePositionIfTyped() { + doTestStopEditing(new Pass() { + @Override + public void pass(AbstractInplaceIntroducer introducer) { + type("fooBar"); + invokeEditorAction(IdeActions.ACTION_EDITOR_ESCAPE); + } + }); + } + + public void testWritable() throws Exception { + doTestReplaceChoice(OccurrencesChooser.ReplaceChoice.ALL); + } + + public void testNoWritable() throws Exception { + doTestReplaceChoice(OccurrencesChooser.ReplaceChoice.NO_WRITE); + } + + public void testAllInsertFinal() throws Exception { + doTestReplaceChoice(OccurrencesChooser.ReplaceChoice.ALL); + } + + public void testAllIncomplete() throws Exception { + doTestReplaceChoice(OccurrencesChooser.ReplaceChoice.ALL); + } + + public void testStopEditing() { + doTestStopEditing(new Pass() { + @Override + public void pass(AbstractInplaceIntroducer introducer) { + invokeEditorAction(IdeActions.ACTION_EDITOR_MOVE_CARET_LEFT); + invokeEditorAction(IdeActions.ACTION_EDITOR_ENTER); + invokeEditorAction(IdeActions.ACTION_EDITOR_ENTER); + } + }); + } + + private void doTestStopEditing(Pass pass) { + String name = getTestName(true); + configureByFile(getBasePath() + name + getExtension()); + final boolean enabled = getEditor().getSettings().isVariableInplaceRenameEnabled(); + try { + TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable()); + getEditor().getSettings().setVariableInplaceRenameEnabled(true); + + final AbstractInplaceIntroducer introducer = invokeRefactoring(); + pass.pass(introducer); + checkResultByFile(getBasePath() + name + "_after" + getExtension()); + } + finally { + TemplateState state = TemplateManagerImpl.getTemplateState(getEditor()); + if (state != null) { + state.gotoEnd(true); + } + getEditor().getSettings().setVariableInplaceRenameEnabled(enabled); + } + } + + private void doTestTypeChange(final String newType) { + final Pass typeChanger = new Pass() { + @Override + public void pass(AbstractInplaceIntroducer inplaceIntroduceFieldPopup) { + type(newType); + } + }; + String name = getTestName(true); + configureByFile(getBasePath() + name + getExtension()); + final boolean enabled = getEditor().getSettings().isVariableInplaceRenameEnabled(); + try { + TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable()); + getEditor().getSettings().setVariableInplaceRenameEnabled(true); + + final AbstractInplaceIntroducer introducer = invokeRefactoring(); + TemplateState state = TemplateManagerImpl.getTemplateState(getEditor()); + assert state != null; + state.previousTab(); + typeChanger.pass(introducer); + state.gotoEnd(false); + checkResultByFile(getBasePath() + name + "_after" + getExtension()); + } + finally { + getEditor().getSettings().setVariableInplaceRenameEnabled(enabled); + } + } + + private void doTestReplaceChoice(OccurrencesChooser.ReplaceChoice choice) { + doTestReplaceChoice(choice, null); + } + + private void doTestReplaceChoice(OccurrencesChooser.ReplaceChoice choice, Pass pass) { + String name = getTestName(true); + configureByFile(getBasePath() + name + getExtension()); + final boolean enabled = getEditor().getSettings().isVariableInplaceRenameEnabled(); + try { + TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable()); + getEditor().getSettings().setVariableInplaceRenameEnabled(true); + + MyIntroduceHandler handler = createIntroduceHandler(); + ((MyIntroduceVariableHandler)handler).setChoice(choice); + final AbstractInplaceIntroducer introducer = invokeRefactoring(handler); + if (pass != null) { + pass.pass(introducer); + } + TemplateState state = TemplateManagerImpl.getTemplateState(getEditor()); + assert state != null; + state.gotoEnd(false); + checkResultByFile(getBasePath() + name + "_after" + getExtension()); + } + finally { + getEditor().getSettings().setVariableInplaceRenameEnabled(enabled); + } + } + + private static void invokeEditorAction(String actionId) { + EditorActionManager.getInstance().getActionHandler(actionId) + .execute(getEditor(), getEditor().getCaretModel().getCurrentCaret(), new MapDataContext()); + } + + + @Override + protected String getBasePath() { + return "/refactoring/inplaceIntroduceVariable/"; + } + + @Override + protected MyIntroduceHandler createIntroduceHandler() { + return new MyIntroduceVariableHandler(); + } + + public static class MyIntroduceVariableHandler extends IntroduceVariableHandler implements MyIntroduceHandler { + private OccurrencesChooser.ReplaceChoice myChoice = null; + + public void setChoice(OccurrencesChooser.ReplaceChoice choice) { + myChoice = choice; + } + + @Override + public boolean invokeImpl(Project project, @NotNull PsiExpression selectedExpr, Editor editor) { + return super.invokeImpl(project, selectedExpr, editor); + } + + @Override + public boolean invokeImpl(Project project, PsiLocalVariable localVariable, Editor editor) { + return super.invokeImpl(project, localVariable, editor); + } + + @Override + protected OccurrencesChooser.ReplaceChoice getOccurrencesChoice() { + return myChoice; + } + + @Override + protected boolean isInplaceAvailableInTestMode() { + return true; + } + } +} 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 d16183c7d069..b8063e1edbde 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -473,10 +473,8 @@ public abstract class AbstractInplaceIntroducer pass) { String name = getTestName(true); configureByFile(getBasePath() + name + getExtension()); final boolean enabled = getEditor().getSettings().isVariableInplaceRenameEnabled(); @@ -37,7 +41,10 @@ public abstract class AbstractInplaceIntroduceTest extends LightPlatformCodeInsi TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable()); getEditor().getSettings().setVariableInplaceRenameEnabled(true); - invokeRefactoring(); + final AbstractInplaceIntroducer introducer = invokeRefactoring(); + if (pass != null) { + pass.pass(introducer); + } TemplateState state = TemplateManagerImpl.getTemplateState(getEditor()); assert state != null; state.gotoEnd(true); From 1e3a1168f5fcb6c312b4de43ccc84ad8cce57cc8 Mon Sep 17 00:00:00 2001 From: Ekaterina Tuzova Date: Mon, 17 Nov 2014 14:17:31 +0300 Subject: [PATCH 04/31] updated ipython output cell notebook format to work with nbformat == 4 --- .../plugins/ipnb/format/IpnbParser.java | 82 ++++++++++++++----- 1 file changed, 63 insertions(+), 19 deletions(-) diff --git a/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java b/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java index 9e553c7c4906..15a12fd5dff0 100644 --- a/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java +++ b/python/ipnb/src/org/jetbrains/plugins/ipnb/format/IpnbParser.java @@ -7,6 +7,7 @@ import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonWriter; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; +import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.ipnb.editor.panels.IpnbEditablePanel; import org.jetbrains.plugins.ipnb.editor.panels.IpnbFilePanel; @@ -215,26 +216,57 @@ public class IpnbParser { Integer prompt_number; String[] text; String[] traceback; - + Map metadata; public static CellOutputRaw fromOutput(@NotNull final IpnbOutputCell outputCell, int nbformat) { final CellOutputRaw raw = new CellOutputRaw(); + if (!(outputCell instanceof IpnbStreamOutputCell) && !(outputCell instanceof IpnbErrorOutputCell)) { + raw.metadata = new HashMap(); + } if (outputCell instanceof IpnbPngOutputCell) { - raw.png = ((IpnbPngOutputCell)outputCell).getBase64String(); + if (nbformat == 4) { + final OutputDataRaw dataRaw = new OutputDataRaw(); + dataRaw.png = new String[]{((IpnbPngOutputCell)outputCell).getBase64String()}; + raw.data = dataRaw; + } + else { + raw.png = ((IpnbPngOutputCell)outputCell).getBase64String(); + } raw.text = outputCell.getText(); raw.output_type = "display_data"; } else if (outputCell instanceof IpnbSvgOutputCell) { - raw.svg = ((IpnbSvgOutputCell)outputCell).getSvg(); + if (nbformat == 4) { + final OutputDataRaw dataRaw = new OutputDataRaw(); + dataRaw.svg = ((IpnbSvgOutputCell)outputCell).getSvg(); + raw.data = dataRaw; + } + else { + raw.svg = ((IpnbSvgOutputCell)outputCell).getSvg(); + } raw.text = outputCell.getText(); } else if (outputCell instanceof IpnbJpegOutputCell) { - raw.jpeg = ((IpnbJpegOutputCell)outputCell).getBase64String(); + if (nbformat == 4) { + final OutputDataRaw dataRaw = new OutputDataRaw(); + dataRaw.jpeg = new String[]{((IpnbJpegOutputCell)outputCell).getBase64String()}; + raw.data = dataRaw; + } + else { + raw.jpeg = ((IpnbJpegOutputCell)outputCell).getBase64String(); + } raw.text = outputCell.getText(); } else if (outputCell instanceof IpnbLatexOutputCell) { - raw.latex = ((IpnbLatexOutputCell)outputCell).getLatex(); + if (nbformat == 4) { + final OutputDataRaw dataRaw = new OutputDataRaw(); + dataRaw.latex = ((IpnbLatexOutputCell)outputCell).getLatex(); + raw.data = dataRaw; + } + else { + raw.latex = ((IpnbLatexOutputCell)outputCell).getLatex(); + } raw.prompt_number = outputCell.getPromptNumber(); raw.text = outputCell.getText(); } @@ -249,11 +281,18 @@ public class IpnbParser { raw.text = outputCell.getText(); } else if (outputCell instanceof IpnbHtmlOutputCell) { - raw.html = ((IpnbHtmlOutputCell)outputCell).getHtmls(); + if (nbformat == 4) { + final OutputDataRaw dataRaw = new OutputDataRaw(); + dataRaw.html = ((IpnbHtmlOutputCell)outputCell).getHtmls(); + raw.data = dataRaw; + } + else { + raw.html = ((IpnbHtmlOutputCell)outputCell).getHtmls(); + } raw.text = outputCell.getText(); } else if (outputCell instanceof IpnbErrorOutputCell) { - raw.output_type = "pyerr"; + raw.output_type = nbformat == 4 ? "error" : "pyerr"; raw.evalue = ((IpnbErrorOutputCell)outputCell).getEvalue(); raw.ename = ((IpnbErrorOutputCell)outputCell).getEname(); raw.traceback = outputCell.getText(); @@ -277,31 +316,31 @@ public class IpnbParser { public IpnbOutputCell createOutput() { final IpnbOutputCell outputCell; - if (png != null) { - outputCell = new IpnbPngOutputCell(png, text, prompt_number); + if (png != null || (data != null && data.png != null)) { + outputCell = new IpnbPngOutputCell(png == null ? StringUtil.join(data.png) : png, text, prompt_number); } - else if (jpeg != null) { - outputCell = new IpnbJpegOutputCell(jpeg, text, prompt_number); + else if (jpeg != null || (data != null && data.jpeg != null)) { + outputCell = new IpnbJpegOutputCell(jpeg == null ? StringUtil.join(data.jpeg) : jpeg, text, prompt_number); } - else if (svg != null) { - outputCell = new IpnbSvgOutputCell(svg, text, prompt_number); + else if (svg != null || (data != null && data.svg != null)) { + outputCell = new IpnbSvgOutputCell(svg == null ? data.svg : svg, text, prompt_number); } - else if (latex != null) { - outputCell = new IpnbLatexOutputCell(latex, prompt_number, text); + else if (latex != null || (data != null && data.latex != null)) { + outputCell = new IpnbLatexOutputCell(latex == null ? data.latex : latex, prompt_number, text); } else if (stream != null || name != null) { outputCell = new IpnbStreamOutputCell(stream == null ? name : stream, text, prompt_number); } - else if (html != null) { - outputCell = new IpnbHtmlOutputCell(html, text, prompt_number); + else if (html != null || (data != null && data.html != null)) { + outputCell = new IpnbHtmlOutputCell(html == null ? data.html : html, text, prompt_number); } - else if ("pyerr".equals(output_type)) { + else if ("pyerr".equals(output_type) || "error".equals(output_type)) { outputCell = new IpnbErrorOutputCell(evalue, ename, traceback, prompt_number); } else if ("pyout".equals(output_type)) { outputCell = new IpnbOutOutputCell(text, prompt_number); } - else if ("execute_result".equals(output_type)) { + else if ("execute_result".equals(output_type) && data != null) { outputCell = new IpnbOutOutputCell(data.text, execution_count); } else { @@ -313,5 +352,10 @@ public class IpnbParser { private static class OutputDataRaw { @SerializedName("text/plain") String[] text; + @SerializedName("text/html") String[] html; + @SerializedName("image/svg+xml") String[] svg; + @SerializedName("image/png") String[] png; + @SerializedName("image/jpeg") String[] jpeg; + @SerializedName("text/latex") String[] latex; } } From a61091911c9ebda06fa148bbc60fac0902a15210 Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Mon, 17 Nov 2014 14:34:02 +0300 Subject: [PATCH 05/31] productivity guide entry for adding carets using DoubleCtrl+arrows --- .../actions/CloneCaretActionHandler.java | 5 ++ .../impl/ModifierKeyDoubleClickHandler.java | 50 ++++++++++++------- .../FeatureStatisticsBundle.properties | 1 + .../src/ProductivityFeaturesRegistry.xml | 3 ++ 4 files changed, 40 insertions(+), 19 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java index 5c5528a38153..00950a5fc0b3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java @@ -15,6 +15,7 @@ */ package com.intellij.openapi.editor.actions; +import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.editor.Caret; @@ -22,6 +23,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorLastActionTracker; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; +import com.intellij.openapi.keymap.impl.ModifierKeyDoubleClickHandler; import com.intellij.openapi.util.Key; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.Nullable; @@ -54,6 +56,9 @@ public class CloneCaretActionHandler extends EditorActionHandler { @Override protected void doExecute(Editor editor, @Nullable Caret targetCaret, DataContext dataContext) { + if (ModifierKeyDoubleClickHandler.getInstance().isRunningAction() && !isRepeatedActionInvocation()) { + FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.add.carets.using.double.ctrl"); + } if (targetCaret != null) { targetCaret.clone(myCloneAbove); return; diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java index 428ee596b465..245c212f39cc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java @@ -45,9 +45,19 @@ import java.util.concurrent.atomic.AtomicLong; * SearchEverywhere behaviour remains intact. */ public class ModifierKeyDoubleClickHandler { + private static final TIntIntHashMap KEY_CODE_TO_MODIFIER_MAP = new TIntIntHashMap(); + static { + KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_ALT, InputEvent.ALT_MASK); + KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_CONTROL, InputEvent.CTRL_MASK); + KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_META, InputEvent.META_MASK); + KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_SHIFT, InputEvent.SHIFT_MASK); + } + private static final ModifierKeyDoubleClickHandler INSTANCE = new ModifierKeyDoubleClickHandler(); private final ConcurrentMap myDispatchers = new ConcurrentHashMap(); + + private boolean myIsRunningAction; private ModifierKeyDoubleClickHandler() { } @@ -78,15 +88,11 @@ public class ModifierKeyDoubleClickHandler { } } - private static class MyDispatcher implements IdeEventQueue.EventDispatcher { - private static final TIntIntHashMap KEY_CODE_TO_MODIFIER_MAP = new TIntIntHashMap(); - static { - KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_ALT, InputEvent.ALT_MASK); - KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_CONTROL, InputEvent.CTRL_MASK); - KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_META, InputEvent.META_MASK); - KEY_CODE_TO_MODIFIER_MAP.put(KeyEvent.VK_SHIFT, InputEvent.SHIFT_MASK); - } + public boolean isRunningAction() { + return myIsRunningAction; + } + private class MyDispatcher implements IdeEventQueue.EventDispatcher { private final String myActionId; private final int myModifierKeyCode; private final int myActionKeyCode; @@ -196,17 +202,23 @@ public class ModifierKeyDoubleClickHandler { } private void run(KeyEvent event) { - final ActionManagerEx actionManager = ActionManagerEx.getInstanceEx(); - final AnAction action = actionManager.getAction(myActionId); - final AnActionEvent anActionEvent = new AnActionEvent(event, - DataManager.getInstance().getDataContext(IdeFocusManager.findInstance().getFocusOwner()), - ActionPlaces.MAIN_MENU, - action.getTemplatePresentation(), - actionManager, - 0); - actionManager.fireBeforeActionPerformed(action, anActionEvent.getDataContext(), anActionEvent); - action.actionPerformed(anActionEvent); - actionManager.fireAfterActionPerformed(action, anActionEvent.getDataContext(), anActionEvent); + myIsRunningAction = true; + try { + final ActionManagerEx actionManager = ActionManagerEx.getInstanceEx(); + final AnAction action = actionManager.getAction(myActionId); + final AnActionEvent anActionEvent = new AnActionEvent(event, + DataManager.getInstance().getDataContext(IdeFocusManager.findInstance().getFocusOwner()), + ActionPlaces.MAIN_MENU, + action.getTemplatePresentation(), + actionManager, + 0); + actionManager.fireBeforeActionPerformed(action, anActionEvent.getDataContext(), anActionEvent); + action.actionPerformed(anActionEvent); + actionManager.fireAfterActionPerformed(action, anActionEvent.getDataContext(), anActionEvent); + } + finally { + myIsRunningAction = false; + } } private boolean isActionBound() { diff --git a/platform/platform-resources-en/src/messages/FeatureStatisticsBundle.properties b/platform/platform-resources-en/src/messages/FeatureStatisticsBundle.properties index 71b4935cf4aa..ca949a52cb0b 100644 --- a/platform/platform-resources-en/src/messages/FeatureStatisticsBundle.properties +++ b/platform/platform-resources-en/src/messages/FeatureStatisticsBundle.properties @@ -61,6 +61,7 @@ editing.completion.changeSorting=Changing completion variants sorting editing.completion.postfix=Postfix completion editing.select.word=Syntax aware selection editing.incremental.search=Editor incremental search +editing.add.carets.using.double.ctrl=Multiple carets codeassists.quickjavadoc=Quick Documentation popup codeassists.quickdefinition=Quick Definition lookup codeassists.quickdefinition.lookup=Quick Definition in lookup lists diff --git a/resources/src/ProductivityFeaturesRegistry.xml b/resources/src/ProductivityFeaturesRegistry.xml index ecb81234f562..50201de3c73d 100644 --- a/resources/src/ProductivityFeaturesRegistry.xml +++ b/resources/src/ProductivityFeaturesRegistry.xml @@ -252,6 +252,9 @@ min-usage-count="10" first-show="2" successive-show="3"/> + From cd6229f9459eeb809a2eb34f4ad51f3bdb784280 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 14:34:14 +0300 Subject: [PATCH 06/31] removed cacheOrGet --- .../intellij/psi/impl/file/impl/JavaFileManagerImpl.java | 5 +++-- .../src/com/intellij/psi/impl/PsiElementFactoryImpl.java | 3 ++- .../com/intellij/util/containers/ConcurrentHashMap.java | 8 -------- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java index d5baa42ad2f8..724eecda2d53 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import com.intellij.psi.impl.file.PsiPackageImpl; import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiUtilCore; +import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Query; import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; @@ -127,7 +128,7 @@ public class JavaFileManagerImpl implements JavaFileManager, Disposable { if (cached == null) { cached = findClassInIndex(qName, scope); if (cached != null) { - cached = myCachedObjectClassMap.cacheOrGet(scope, cached); + cached = ConcurrencyUtil.cacheOrGet(myCachedObjectClassMap, scope, cached); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java index 2163057032d8..a5e2b67ff50e 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java @@ -35,6 +35,7 @@ import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtil; +import com.intellij.util.ConcurrencyUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.HashMap; @@ -408,7 +409,7 @@ public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements Ps PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope); if (aClass != null) { cachedObjectType = new PsiImmediateClassType(aClass, PsiSubstitutor.EMPTY); - cachedObjectType = myCachedObjectType.cacheOrGet(resolveScope, cachedObjectType); + cachedObjectType = ConcurrencyUtil.cacheOrGet(myCachedObjectType, resolveScope, cachedObjectType); return cachedObjectType; } } diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java index ff09f473d9d1..dc5470a65238 100644 --- a/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java +++ b/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java @@ -16,7 +16,6 @@ package com.intellij.util.containers; -import com.intellij.util.ConcurrencyUtil; import com.intellij.util.concurrency.AtomicFieldUpdater; import gnu.trove.TObjectHashingStrategy; import jsr166e.ForkJoinPool; @@ -3826,13 +3825,6 @@ public class ConcurrentHashMap extends AbstractMap implements Concur return o1.equals(o2); } - /** - * @return value if there is no entry in the map, or corresponding value if entry already exists - */ - public V cacheOrGet(final K key, final V value) { - return ConcurrencyUtil.cacheOrGet(this, key, value); - } - private int hash(K key) { return spread(myHashingStrategy.computeHashCode(key)); } From e02fa3c43a6ab8d17f90a7229337ed080bc04666 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 15:11:28 +0300 Subject: [PATCH 07/31] use interface where possible --- .../impl/file/impl/JavaFileManagerImpl.java | 3 ++- .../psi/impl/PsiElementFactoryImpl.java | 3 ++- .../client/ProtobufClientMessageHandler.java | 5 +++-- .../service/impl/JpsServiceManagerImpl.java | 7 ++++--- ...plePsiFilesPerDocumentFileViewProvider.java | 2 +- .../CompletionProgressIndicator.java | 3 ++- .../daemon/impl/PassExecutorService.java | 2 +- .../facet/impl/ProjectFacetManagerImpl.java | 5 +++-- .../ContributorsBasedGotoByModel.java | 5 +++-- .../intellij/util/indexing/IndexingStamp.java | 3 ++- .../vfs/newvfs/persistent/FSRecords.java | 3 ++- .../debugger/BreakpointManagerBase.java | 18 +++++++++++++++++- .../util/containers/ConcurrentHashMap.java | 1 - .../telemetry/InspectionGadgetsTelemetry.java | 3 ++- .../util/xml/impl/DynamicGenericInfo.java | 9 +++++---- .../psi/impl/source/xml/XmlDocumentImpl.java | 7 ++++--- 16 files changed, 53 insertions(+), 26 deletions(-) diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java index 724eecda2d53..595f5645ccfa 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java @@ -39,13 +39,14 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; import java.util.*; +import java.util.concurrent.ConcurrentMap; /** * Author: dmitrylomov */ public class JavaFileManagerImpl implements JavaFileManager, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.impl.JavaFileManagerImpl"); - private final ConcurrentHashMap myCachedObjectClassMap = new ConcurrentHashMap(); + private final ConcurrentMap myCachedObjectClassMap = new ConcurrentHashMap(); private final PsiManagerEx myManager; private volatile Set myNontrivialPackagePrefixes = null; private boolean myDisposed = false; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java index a5e2b67ff50e..b93c9e9a5de7 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java @@ -44,11 +44,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; +import java.util.concurrent.ConcurrentMap; public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements PsiElementFactory { private PsiClass myArrayClass; private PsiClass myArrayClass15; - private final ConcurrentHashMap myCachedObjectType = new ConcurrentHashMap(); + private final ConcurrentMap myCachedObjectType = new ConcurrentHashMap(); public PsiElementFactoryImpl(final PsiManagerEx manager) { super(manager); diff --git a/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java b/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java index 49515add53e0..3db5e139d6a7 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java +++ b/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; /** @@ -36,7 +37,7 @@ import java.util.concurrent.Executor; */ @ChannelHandler.Sharable final class ProtobufClientMessageHandler extends SimpleChannelInboundHandler { - private final ConcurrentHashMap> myHandlers = new ConcurrentHashMap>(16, 0.75f, 1); + private final ConcurrentMap> myHandlers = new ConcurrentHashMap>(16, 0.75f, 1); @NotNull private final UUIDGetter myUuidGetter; private final SimpleProtobufClient myClient; diff --git a/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java b/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java index a361e37dae80..b30e6cb9e042 100644 --- a/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java +++ b/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,14 @@ import org.jetbrains.jps.service.JpsServiceManager; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * @author nik */ public class JpsServiceManagerImpl extends JpsServiceManager { - private final ConcurrentHashMap myServices = new ConcurrentHashMap(16, 0.75f, 1); - private final ConcurrentHashMap> myExtensions = new ConcurrentHashMap>(16, 0.75f, 1); + private final ConcurrentMap myServices = new ConcurrentHashMap(16, 0.75f, 1); + private final ConcurrentMap> myExtensions = new ConcurrentHashMap>(16, 0.75f, 1); @Override public T getService(Class serviceClass) { diff --git a/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java b/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java index d8291fbd7f8d..83fcf392d5c3 100644 --- a/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java +++ b/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java @@ -39,7 +39,7 @@ import java.util.*; import java.util.concurrent.ConcurrentMap; public abstract class MultiplePsiFilesPerDocumentFileViewProvider extends SingleRootFileViewProvider { - private final ConcurrentMap myRoots = new ConcurrentHashMap(1, ConcurrentHashMap.DEFAULT_LOAD_FACTOR, 1); + private final ConcurrentMap myRoots = new ConcurrentHashMap(1, 0.75f, 1); private MultiplePsiFilesPerDocumentFileViewProvider myOriginal = null; public MultiplePsiFilesPerDocumentFileViewProvider(PsiManager manager, VirtualFile virtualFile, boolean eventSystemEnabled) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index 4b5b7b5c90e9..df7cbdd26f83 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -82,6 +82,7 @@ import java.beans.PropertyChangeListener; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentMap; /** * @author peter @@ -127,7 +128,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private volatile int myCount; private volatile boolean myHasPsiElements; private boolean myLookupUpdated; - private final ConcurrentHashMap myItemSorters = + private final ConcurrentMap myItemSorters = new ConcurrentHashMap( ContainerUtil.identityStrategy()); private final PropertyChangeListener myLookupManagerListener; 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 24c3d8b4a6fb..b4e5f250d4a5 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 @@ -554,7 +554,7 @@ public class PassExecutorService implements Disposable { }); } - private static final ConcurrentHashMap threads = new ConcurrentHashMap(); + private static final ConcurrentMap threads = new ConcurrentHashMap(); private static int getThreadNum() { return ConcurrencyUtil.cacheOrGet(threads, Thread.currentThread(), threads.size()); } diff --git a/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java b/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java index 83888001d1d9..94a7589c8e14 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,6 +42,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentMap; /** * @author nik @@ -59,7 +60,7 @@ public class ProjectFacetManagerImpl extends ProjectFacetManagerEx implements Pe private static final Logger LOG = Logger.getInstance("#com.intellij.facet.impl.ProjectFacetManagerImpl"); private ProjectFacetManagerState myState = new ProjectFacetManagerState(); private final Project myProject; - private final ConcurrentHashMap, ParameterizedCachedValue>> myCachedHasFacets = new ConcurrentHashMap, ParameterizedCachedValue>>(); + private final ConcurrentMap, ParameterizedCachedValue>> myCachedHasFacets = new ConcurrentHashMap, ParameterizedCachedValue>>(); private final ParameterizedCachedValueProvider> myCachedValueProvider; public ProjectFacetManagerImpl(Project project) { 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 c26bd353de50..1d02e9a9c203 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,6 +49,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.concurrent.ConcurrentMap; /** * Contributor-based goto model @@ -85,7 +86,7 @@ public abstract class ContributorsBasedGotoByModel implements ChooseByNameModelE return !ChooseByNameBase.ourLoadNamesEachTime; } - private final ConcurrentHashMap myContributorToItsSymbolsMap = new ConcurrentHashMap(); + private final ConcurrentMap myContributorToItsSymbolsMap = new ConcurrentHashMap(); private volatile IdFilter myIdFilter; private volatile boolean myIdFilterForLibraries; diff --git a/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java b/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java index e4cab03a7404..4a7a71c7a7eb 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java @@ -40,6 +40,7 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentMap; /** * @author Eugene Zhuravlev @@ -62,7 +63,7 @@ public class IndexingStamp { private static final long INDEX_DATA_OUTDATED_STAMP = -2L; private static final int VERSION = 13; - private static final ConcurrentHashMap, Long> ourIndexIdToCreationStamp = new ConcurrentHashMap, Long>(); + private static final ConcurrentMap, Long> ourIndexIdToCreationStamp = new ConcurrentHashMap, Long>(); static final int INVALID_FILE_ID = 0; private static volatile long ourLastStamp; // ensure any file index stamp increases 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 b8a55b333203..ce7d6db1cc34 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 @@ -48,6 +48,7 @@ import java.io.*; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.Arrays; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -136,7 +137,7 @@ public class FSRecords implements Forceable { static class DbConnection { private static boolean ourInitialized; - private static final ConcurrentHashMap myAttributeIds = new ConcurrentHashMap(); + private static final ConcurrentMap myAttributeIds = new ConcurrentHashMap(); private static PersistentStringEnumerator myNames; private static Storage myAttributes; diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java index 0cb431fd0bf8..a6cd9a78e757 100644 --- a/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java +++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.jetbrains.debugger; import com.intellij.openapi.util.text.StringUtil; @@ -13,10 +28,11 @@ import org.jetbrains.concurrency.Promise; import java.util.List; import java.util.Set; +import java.util.concurrent.ConcurrentMap; public abstract class BreakpointManagerBase> implements BreakpointManager { protected final Set breakpoints = new ConcurrentHashSet(); - protected final ConcurrentHashMap breakpointDuplicationByTarget = new ConcurrentHashMap(new TObjectHashingStrategy() { + protected final ConcurrentMap breakpointDuplicationByTarget = new ConcurrentHashMap(new TObjectHashingStrategy() { @Override public int computeHashCode(T b) { int result = b.getLine(); diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java index dc5470a65238..082e22f1a7bf 100644 --- a/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java +++ b/platform/util/src/com/intellij/util/containers/ConcurrentHashMap.java @@ -219,7 +219,6 @@ import java.util.concurrent.locks.LockSupport; // IJ specific: // copied from JDK1.8 ConcurrentHashMap except: // added hashing strategy argument -// added cacheOrGet convenience method // Null keys are NOT allowed // Null values are NOT allowed // NOT serializable diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/telemetry/InspectionGadgetsTelemetry.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/telemetry/InspectionGadgetsTelemetry.java index db545713ebfc..9e3f2ff2e0c9 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/telemetry/InspectionGadgetsTelemetry.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/telemetry/InspectionGadgetsTelemetry.java @@ -21,12 +21,13 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; public class InspectionGadgetsTelemetry { private static final InspectionGadgetsTelemetry telemetry = new InspectionGadgetsTelemetry(); private static volatile boolean telemetryEnabled = false; - private final ConcurrentHashMap inspectionRunTimes = + private final ConcurrentMap inspectionRunTimes = new ConcurrentHashMap(); public List buildList() { 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 eebe00d9e0bb..e95182cdb69f 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 @@ -42,12 +42,13 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; +import java.util.concurrent.ConcurrentMap; /** * @author peter */ public class DynamicGenericInfo extends DomGenericInfoEx { - private static final Key>> HOLDERS_CACHE = Key.create("DOM_CHILDREN_HOLDERS_CACHE"); + private static final Key>> HOLDERS_CACHE = Key.create("DOM_CHILDREN_HOLDERS_CACHE"); private static final RecursionGuard ourGuard = RecursionManager.createGuard("dynamicGenericInfo"); private final StaticGenericInfo myStaticGenericInfo; @NotNull private final DomInvocationHandler myInvocationHandler; @@ -139,11 +140,11 @@ public class DynamicGenericInfo extends DomGenericInfoEx { } private static ChildrenDescriptionsHolder internChildrenHolder(XmlFile file, ChildrenDescriptionsHolder holder) { - SoftReference> ref = file.getUserData(HOLDERS_CACHE); - ConcurrentHashMap cache = SoftReference.dereference(ref); + SoftReference> ref = file.getUserData(HOLDERS_CACHE); + ConcurrentMap cache = SoftReference.dereference(ref); if (cache == null) { cache = new ConcurrentHashMap(); - file.putUserData(HOLDERS_CACHE, new SoftReference>(cache)); + file.putUserData(HOLDERS_CACHE, new SoftReference>(cache)); } ChildrenDescriptionsHolder existing = cache.get(holder); if (existing != null) { diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java index c86139c4bbcd..8a26c162f993 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java @@ -57,6 +57,7 @@ import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentMap; /** * @author Mike @@ -148,8 +149,8 @@ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { return rootTag != null ? rootTag.getNSDescriptor(rootTag.getNamespace(), false) : null; } - private ConcurrentHashMap> myDefaultDescriptorsCacheStrict = new ConcurrentHashMap>(); - private ConcurrentHashMap> myDefaultDescriptorsCacheNotStrict = new ConcurrentHashMap>(); + private ConcurrentMap> myDefaultDescriptorsCacheStrict = new ConcurrentHashMap>(); + private ConcurrentMap> myDefaultDescriptorsCacheNotStrict = new ConcurrentHashMap>(); @Override public void clearCaches() { @@ -169,7 +170,7 @@ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { myExtResourcesModCount = curExtResourcesModCount; } - final ConcurrentHashMap> defaultDescriptorsCache; + final ConcurrentMap> defaultDescriptorsCache; if (strict) { defaultDescriptorsCache = myDefaultDescriptorsCacheStrict; } From 87f5480c9787b86a2126ca1fcb9be35c495ba2d3 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 15:40:42 +0300 Subject: [PATCH 08/31] instantiate ConcurrentHashMap via factory only --- .../java/JavaSpacePropertyProcessor.java | 4 +- .../intellij/slicer/SliceLeafAnalyzer.java | 3 +- .../impl/file/impl/JavaFileManagerImpl.java | 3 +- .../intellij/psi/impl/JavaPsiFacadeImpl.java | 5 +-- .../psi/impl/PsiElementFactoryImpl.java | 5 ++- .../daemon/impl/SeverityRegistrar.java | 7 ++-- .../editor/colors/TextAttributesKey.java | 4 +- .../openapi/util/KeyedExtensionCollector.java | 3 +- .../psi/util/CachedValuesManager.java | 4 +- .../util/SingletonInstancesCache.java | 4 +- .../components/impl/ComponentManagerImpl.java | 9 ++-- ...lePsiFilesPerDocumentFileViewProvider.java | 4 +- .../editor/impl/DocumentMarkupModel.java | 6 +-- .../extensions/impl/ExtensionsAreaImpl.java | 4 +- .../manage/ExternalProjectsDataStorage.java | 4 +- .../AbstractRemoteExternalSystemService.java | 8 ++-- ...SystemProgressNotificationManagerImpl.java | 29 +++++++++---- .../openapi/roots/impl/LibraryScopeCache.java | 9 ++-- .../CompletionProgressIndicator.java | 4 +- .../daemon/impl/LocalInspectionsPass.java | 4 +- .../codeInsight/lookup/impl/LookupImpl.java | 5 +-- .../facet/impl/ProjectFacetManagerImpl.java | 5 ++- .../formatting/FormattingProgressTask.java | 6 +-- .../ContributorsBasedGotoByModel.java | 3 +- .../tree/injected/ClassMapCachingNulls.java | 4 +- .../intellij/util/indexing/IndexingStamp.java | 3 +- .../vfs/newvfs/NewVirtualFileSystem.java | 5 ++- .../impl/ModifierKeyDoubleClickHandler.java | 8 ++-- .../impl/VirtualFilePointerManagerImpl.java | 4 +- .../vfs/newvfs/persistent/FSRecords.java | 4 +- .../impl/runtime/ServerConnectionImpl.java | 19 ++++++++- .../debugger/BreakpointManagerBase.java | 41 ++++++++++--------- .../openapi/application/ex/PathManagerEx.java | 13 +++--- .../ConcurrentWeakKeySoftValueHashMap.java | 13 +++++- .../LockFreeCopyOnWriteArrayList.java | 2 +- .../messages/impl/MessageListenerList.java | 4 +- .../vcs/changes/committed/CachesHolder.java | 8 ++-- .../committed/CommittedChangesCache.java | 3 +- ...SubstitutedExpressionEvaluationHelper.java | 4 +- .../plugins/groovy/dsl/FactorTree.java | 7 ++-- .../dsl/toplevel/ClassContextFilter.java | 4 +- .../lang/psi/impl/GroovyPsiManager.java | 9 ++-- .../embedder/TransferListenerAdapter.java | 6 +-- .../server/WagonTransferListenerAdapter.java | 6 +-- .../python/packaging/PyPackageService.java | 4 +- .../DomElementsProblemsHolderImpl.java | 7 ++-- .../util/xml/impl/DynamicGenericInfo.java | 3 +- .../intellij/util/xml/impl/SofterCache.java | 6 +-- .../intellij/util/xml/DomFileDescription.java | 5 ++- .../util/xml/EvaluatedXmlNameImpl.java | 5 ++- .../psi/impl/source/xml/XmlDocumentImpl.java | 12 +++--- 51 files changed, 199 insertions(+), 152 deletions(-) diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java b/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java index 8a89027e2d56..acab27107583 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java @@ -43,7 +43,7 @@ import com.intellij.psi.tree.ChildRoleBase; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.java.IJavaElementType; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -1683,7 +1683,7 @@ public class JavaSpacePropertyProcessor extends JavaElementVisitor { } private static final Map, Boolean> myCanStickJavaTokensMatrix = - new ConcurrentHashMap, Boolean>(); + ContainerUtil.newConcurrentMap(); public static boolean canStickChildrenTogether(final ASTNode child1, final ASTNode child2) { if (child1 == null || child2 == null) return true; diff --git a/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java b/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java index a08464fbd7ce..8be533f31f45 100644 --- a/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java +++ b/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java @@ -33,7 +33,6 @@ import com.intellij.psi.impl.source.tree.AstBufferUtil; import com.intellij.util.NullableFunction; import com.intellij.util.PairProcessor; import com.intellij.util.WalkingState; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; @@ -187,7 +186,7 @@ public class SliceLeafAnalyzer { return new FactoryMap>() { @Override protected Map> createMap() { - return new ConcurrentHashMap>(ContainerUtil.identityStrategy()); + return ContainerUtil.newConcurrentMap(ContainerUtil.identityStrategy()); } @Override diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java index 595f5645ccfa..0d445fd3fab9 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java @@ -32,7 +32,6 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Query; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -46,7 +45,7 @@ import java.util.concurrent.ConcurrentMap; */ public class JavaFileManagerImpl implements JavaFileManager, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.impl.JavaFileManagerImpl"); - private final ConcurrentMap myCachedObjectClassMap = new ConcurrentHashMap(); + private final ConcurrentMap myCachedObjectClassMap = ContainerUtil.newConcurrentMap(); private final PsiManagerEx myManager; private volatile Set myNontrivialPackagePrefixes = null; private boolean myDisposed = false; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java index 13ca6288f4a5..617e1ffd9b13 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,6 @@ import com.intellij.reference.SoftReference; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Processor; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.messages.MessageBus; @@ -177,7 +176,7 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx { public PsiPackage findPackage(@NotNull String qualifiedName) { ConcurrentMap cache = SoftReference.dereference(myPackageCache); if (cache == null) { - myPackageCache = new SoftReference>(cache = new ConcurrentHashMap()); + myPackageCache = new SoftReference>(cache = ContainerUtil.newConcurrentMap()); } PsiPackage aPackage = cache.get(qualifiedName); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java index b93c9e9a5de7..dda3ca55b901 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java @@ -37,7 +37,7 @@ import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -49,7 +49,8 @@ import java.util.concurrent.ConcurrentMap; public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements PsiElementFactory { private PsiClass myArrayClass; private PsiClass myArrayClass15; - private final ConcurrentMap myCachedObjectType = new ConcurrentHashMap(); + private final ConcurrentMap myCachedObjectType = + ContainerUtil.newConcurrentMap(); public PsiElementFactoryImpl(final PsiManagerEx manager) { super(manager); 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 88c8e59603e6..c55d30cd10b6 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 @@ -29,7 +29,6 @@ import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.util.IncorrectOperationException; import com.intellij.util.concurrency.AtomicFieldUpdater; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.Topic; @@ -53,8 +52,8 @@ import java.util.List; public class SeverityRegistrar implements JDOMExternalizable, Comparator { @NonNls private static final String INFO_TAG = "info"; @NonNls private static final String COLOR_ATTRIBUTE = "color"; - private final Map myMap = new ConcurrentHashMap(); - private final Map myRendererColors = new ConcurrentHashMap(); + private final Map myMap = ContainerUtil.newConcurrentMap(); + private final Map myRendererColors = ContainerUtil.newConcurrentMap(); public static final Topic SEVERITIES_CHANGED_TOPIC = Topic.create("SEVERITIES_CHANGED_TOPIC", Runnable.class, Topic.BroadcastDirection.TO_PARENT); @NotNull private final MessageBus myMessageBus; @@ -62,7 +61,7 @@ public class SeverityRegistrar implements JDOMExternalizable, Comparator STANDARD_SEVERITIES = new ConcurrentHashMap(); + private static final Map STANDARD_SEVERITIES = ContainerUtil.newConcurrentMap(); public SeverityRegistrar(@NotNull MessageBus messageBus) { myMessageBus = messageBus; diff --git a/platform/core-api/src/com/intellij/openapi/editor/colors/TextAttributesKey.java b/platform/core-api/src/com/intellij/openapi/editor/colors/TextAttributesKey.java index 807ee6102b7f..d9e4e249a0e9 100644 --- a/platform/core-api/src/com/intellij/openapi/editor/colors/TextAttributesKey.java +++ b/platform/core-api/src/com/intellij/openapi/editor/colors/TextAttributesKey.java @@ -19,7 +19,7 @@ import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.*; import com.intellij.util.ConcurrencyUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -33,7 +33,7 @@ import java.util.concurrent.ConcurrentMap; */ public final class TextAttributesKey implements Comparable { private static final TextAttributes NULL_ATTRIBUTES = new TextAttributes(); - private static final ConcurrentMap ourRegistry = new ConcurrentHashMap(); + private static final ConcurrentMap ourRegistry = ContainerUtil.newConcurrentMap(); private static final NullableLazyValue ourDefaultsProvider = new VolatileNullableLazyValue() { @Nullable @Override diff --git a/platform/core-api/src/com/intellij/openapi/util/KeyedExtensionCollector.java b/platform/core-api/src/com/intellij/openapi/util/KeyedExtensionCollector.java index 071a37e5bdbe..e0b245f71fdc 100644 --- a/platform/core-api/src/com/intellij/openapi/util/KeyedExtensionCollector.java +++ b/platform/core-api/src/com/intellij/openapi/util/KeyedExtensionCollector.java @@ -26,7 +26,6 @@ import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.KeyedLazyInstance; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; @@ -40,7 +39,7 @@ public class KeyedExtensionCollector { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.KeyedExtensionCollector"); private final Map> myExplicitExtensions = new THashMap>(); - private final ConcurrentMap> myCache = new ConcurrentHashMap>(); + private final ConcurrentMap> myCache = ContainerUtil.newConcurrentMap(); @NonNls private final String lock; diff --git a/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java b/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java index 3a775dadad05..bb3812f5bb4d 100644 --- a/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java +++ b/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java @@ -23,7 +23,7 @@ import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.UserDataHolderEx; import com.intellij.psi.PsiElement; import com.intellij.util.ConcurrencyUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.concurrent.ConcurrentMap; @@ -125,7 +125,7 @@ public abstract class CachedValuesManager { return manager.getCachedValue(psi, manager.getKeyForClass(provider.getClass()), provider, false); } - private final ConcurrentMap> keyForProvider = new ConcurrentHashMap>(); + private final ConcurrentMap> keyForProvider = ContainerUtil.newConcurrentMap(); @NotNull public Key> getKeyForClass(@NotNull Class providerClass) { String name = providerClass.getName(); diff --git a/platform/core-api/src/com/intellij/util/SingletonInstancesCache.java b/platform/core-api/src/com/intellij/util/SingletonInstancesCache.java index a31bfa928eb2..493b42e26404 100644 --- a/platform/core-api/src/com/intellij/util/SingletonInstancesCache.java +++ b/platform/core-api/src/com/intellij/util/SingletonInstancesCache.java @@ -15,7 +15,7 @@ */ package com.intellij.util; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.concurrent.ConcurrentMap; @@ -25,7 +25,7 @@ import java.util.concurrent.ConcurrentMap; */ public class SingletonInstancesCache { - private static final ConcurrentMap CACHE = new ConcurrentHashMap(); + private static final ConcurrentMap CACHE = ContainerUtil.newConcurrentMap(); private SingletonInstancesCache() { } diff --git a/platform/core-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java b/platform/core-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java index dfc6f6b254c3..df1bfa77a451 100644 --- a/platform/core-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java @@ -21,7 +21,10 @@ import com.intellij.openapi.components.*; import com.intellij.openapi.components.ex.ComponentManagerEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginDescriptor; -import com.intellij.openapi.progress.*; +import com.intellij.openapi.progress.ProcessCanceledException; +import com.intellij.openapi.progress.ProgressIndicator; +import com.intellij.openapi.progress.ProgressIndicatorProvider; +import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; @@ -29,7 +32,7 @@ import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ReflectionUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusFactory; import com.intellij.util.pico.ConstructorInjectionComponentAdapter; @@ -53,7 +56,7 @@ import java.util.Map; public abstract class ComponentManagerImpl extends UserDataHolderBase implements ComponentManagerEx, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.components.ComponentManager"); - private final Map myInitializedComponents = new ConcurrentHashMap(); + private final Map myInitializedComponents = ContainerUtil.newConcurrentMap(); private boolean myComponentsCreated = false; diff --git a/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java b/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java index 83fcf392d5c3..b957761c6249 100644 --- a/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java +++ b/platform/core-impl/src/com/intellij/psi/MultiplePsiFilesPerDocumentFileViewProvider.java @@ -30,7 +30,7 @@ import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.templateLanguages.OuterLanguageElement; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.ReflectionUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -39,7 +39,7 @@ import java.util.*; import java.util.concurrent.ConcurrentMap; public abstract class MultiplePsiFilesPerDocumentFileViewProvider extends SingleRootFileViewProvider { - private final ConcurrentMap myRoots = new ConcurrentHashMap(1, 0.75f, 1); + private final ConcurrentMap myRoots = ContainerUtil.newConcurrentMap(1, 0.75f, 1); private MultiplePsiFilesPerDocumentFileViewProvider myOriginal = null; public MultiplePsiFilesPerDocumentFileViewProvider(PsiManager manager, VirtualFile virtualFile, boolean eventSystemEnabled) { diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/impl/DocumentMarkupModel.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/impl/DocumentMarkupModel.java index 524fbdd35512..21c4674b2497 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/impl/DocumentMarkupModel.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/impl/DocumentMarkupModel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolderEx; import com.intellij.util.ConcurrencyUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -97,7 +97,7 @@ public class DocumentMarkupModel { private static ConcurrentMap getMarkupModelMap(@NotNull Document document) { ConcurrentMap markupModelMap = document.getUserData(MARKUP_MODEL_MAP_KEY); if (markupModelMap == null) { - ConcurrentMap newMap = new ConcurrentHashMap(); + ConcurrentMap newMap = ContainerUtil.newConcurrentMap(); markupModelMap = ((UserDataHolderEx)document).putUserDataIfAbsent(MARKUP_MODEL_MAP_KEY, newMap); } return markupModelMap; diff --git a/platform/extensions/src/com/intellij/openapi/extensions/impl/ExtensionsAreaImpl.java b/platform/extensions/src/com/intellij/openapi/extensions/impl/ExtensionsAreaImpl.java index 7e85012f68ff..ba7a2209d6fc 100644 --- a/platform/extensions/src/com/intellij/openapi/extensions/impl/ExtensionsAreaImpl.java +++ b/platform/extensions/src/com/intellij/openapi/extensions/impl/ExtensionsAreaImpl.java @@ -16,7 +16,7 @@ package com.intellij.openapi.extensions.impl; import com.intellij.openapi.extensions.*; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.pico.ConstructorInjectionComponentAdapter; import gnu.trove.THashMap; @@ -46,7 +46,7 @@ public class ExtensionsAreaImpl implements ExtensionsArea { private final AreaPicoContainerImpl myPicoContainer; private final Throwable myCreationTrace; - private final Map myExtensionPoints = new ConcurrentHashMap(); + private final Map myExtensionPoints = ContainerUtil.newConcurrentMap(); private final Map myEPTraces = DEBUG_REGISTRATION ? new THashMap():null; private final MultiMap myAvailabilityListeners = new MultiMap(); private final List mySuspendedListenerActions = new ArrayList(); diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java index 549841d16905..fb4102adc160 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorage.java @@ -25,7 +25,7 @@ import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjec import com.intellij.openapi.externalSystem.model.project.ProjectData; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -42,7 +42,7 @@ public class ExternalProjectsDataStorage implements SettingsSavingComponent { private final Project myProject; @NotNull private final Map, InternalExternalProjectInfo> myExternalRootProjects = - new ConcurrentHashMap, InternalExternalProjectInfo>(); + ContainerUtil.newConcurrentMap(); public static ExternalProjectsDataStorage getInstance(@NotNull Project project) { return ServiceManager.getService(project, ExternalProjectsDataStorage.class); diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/AbstractRemoteExternalSystemService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/AbstractRemoteExternalSystemService.java index 2e86c0e06f5c..b229867ee946 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/AbstractRemoteExternalSystemService.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/AbstractRemoteExternalSystemService.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,11 @@ package com.intellij.openapi.externalSystem.service.remote; import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; +import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType; import com.intellij.openapi.externalSystem.service.RemoteExternalSystemService; -import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; import com.intellij.util.Producer; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -41,7 +41,7 @@ public abstract class AbstractRemoteExternalSystemService> myTasksInProgress = - new ConcurrentHashMap>(); + ContainerUtil.newConcurrentMap(); private final AtomicReference mySettings = new AtomicReference(); diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java index 3afacbcd6c5a..30f98f407167 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java @@ -1,13 +1,28 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.openapi.externalSystem.service.remote; import com.intellij.execution.rmi.RemoteObject; -import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent; -import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager; -import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; -import com.intellij.util.containers.ConcurrentHashMap; -import com.intellij.util.containers.ConcurrentHashSet; -import org.jetbrains.annotations.NotNull; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; +import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent; +import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; +import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager; +import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; import java.rmi.RemoteException; import java.util.Collections; @@ -25,7 +40,7 @@ public class ExternalSystemProgressNotificationManagerImpl extends RemoteObject private final ConcurrentMap/* EMPTY_SET as a sign of 'all ids' */> myListeners - = new ConcurrentHashMap>(); + = ContainerUtil.newConcurrentMap(); @Override public boolean addNotificationListener(@NotNull ExternalSystemTaskNotificationListener listener) { 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 74962f340bbf..fa45227bbc2a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.SdkResolveScopeProvider; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.ConcurrencyUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -41,8 +41,9 @@ public class LibraryScopeCache { } private final Project myProject; - private final ConcurrentMap, GlobalSearchScope> myLibraryScopes = new ConcurrentHashMap, GlobalSearchScope>(); - private final ConcurrentMap mySdkScopes = new ConcurrentHashMap(); + private final ConcurrentMap, GlobalSearchScope> myLibraryScopes = + ContainerUtil.newConcurrentMap(); + private final ConcurrentMap mySdkScopes = ContainerUtil.newConcurrentMap(); public LibraryScopeCache(Project project) { myProject = project; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index df7cbdd26f83..25d8944101e6 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -64,7 +64,6 @@ import com.intellij.util.Alarm; import com.intellij.util.ObjectUtils; import com.intellij.util.ThreeState; import com.intellij.util.concurrency.Semaphore; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.update.MergingUpdateQueue; @@ -129,8 +128,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private volatile boolean myHasPsiElements; private boolean myLookupUpdated; private final ConcurrentMap myItemSorters = - new ConcurrentHashMap( - ContainerUtil.identityStrategy()); + ContainerUtil.newConcurrentMap(ContainerUtil.identityStrategy()); private final PropertyChangeListener myLookupManagerListener; private final Queue myAdvertiserChanges = new ConcurrentLinkedQueue(); private final int myStartCaret; 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 107771296a67..c3ff04036d31 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 @@ -55,7 +55,7 @@ import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Function; import com.intellij.util.Processor; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.containers.TransferToEDTQueue; import com.intellij.util.ui.UIUtil; @@ -85,7 +85,7 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass private final int myEndOffset; private final TextRange myPriorityRange; private final boolean myIgnoreSuppressed; - private final ConcurrentMap> result = new ConcurrentHashMap>(); + private final ConcurrentMap> result = ContainerUtil.newConcurrentMap(); private static final String PRESENTABLE_NAME = DaemonBundle.message("pass.inspection"); private volatile List myInfos = Collections.emptyList(); private final String myShortcutText; 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 869886d26523..4fea598c44bc 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 @@ -52,7 +52,6 @@ import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBList; import com.intellij.ui.popup.AbstractPopup; import com.intellij.util.CollectConsumer; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentWeakHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.update.Activatable; @@ -118,8 +117,8 @@ public class LookupImpl extends LightweightHint implements LookupEx, Disposable, private boolean myChangeGuard; private volatile LookupArranger myArranger; private LookupArranger myPresentableArranger; - private final Map myMatchers = new ConcurrentHashMap( - ContainerUtil.identityStrategy()); + private final Map myMatchers = + ContainerUtil.newConcurrentMap(ContainerUtil.identityStrategy()); private final Map myCustomFonts = new ConcurrentWeakHashMap( ContainerUtil.identityStrategy()); private boolean myStartCompletionWhenNothingMatches; diff --git a/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java b/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java index 94a7589c8e14..c3a46f15e5c8 100644 --- a/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/facet/impl/ProjectFacetManagerImpl.java @@ -31,7 +31,7 @@ import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.ParameterizedCachedValue; import com.intellij.psi.util.ParameterizedCachedValueProvider; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.MapAnnotation; import com.intellij.util.xmlb.annotations.Tag; import org.jdom.Element; @@ -60,7 +60,8 @@ public class ProjectFacetManagerImpl extends ProjectFacetManagerEx implements Pe private static final Logger LOG = Logger.getInstance("#com.intellij.facet.impl.ProjectFacetManagerImpl"); private ProjectFacetManagerState myState = new ProjectFacetManagerState(); private final Project myProject; - private final ConcurrentMap, ParameterizedCachedValue>> myCachedHasFacets = new ConcurrentHashMap, ParameterizedCachedValue>>(); + private final ConcurrentMap, ParameterizedCachedValue>> myCachedHasFacets = + ContainerUtil.newConcurrentMap(); private final ParameterizedCachedValueProvider> myCachedValueProvider; public ProjectFacetManagerImpl(Project project) { diff --git a/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java b/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java index c4f272b11fd0..6fd20d76190c 100644 --- a/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java +++ b/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.util.SequentialModalProgressTask; import com.intellij.util.SequentialTask; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -69,7 +69,7 @@ public class FormattingProgressTask extends SequentialModalProgressTask implemen TOTAL_WEIGHT = weight; } - private final ConcurrentMap> myCallbacks = new ConcurrentHashMap>(); + private final ConcurrentMap> myCallbacks = ContainerUtil.newConcurrentMap(); private final WeakReference myFile; private final WeakReference myDocument; 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 1d02e9a9c203..fa620826c771 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 @@ -35,7 +35,6 @@ import com.intellij.openapi.project.Project; import com.intellij.util.ArrayUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FindSymbolParameters; import com.intellij.util.indexing.IdFilter; @@ -86,7 +85,7 @@ public abstract class ContributorsBasedGotoByModel implements ChooseByNameModelE return !ChooseByNameBase.ourLoadNamesEachTime; } - private final ConcurrentMap myContributorToItsSymbolsMap = new ConcurrentHashMap(); + private final ConcurrentMap myContributorToItsSymbolsMap = ContainerUtil.newConcurrentMap(); private volatile IdFilter myIdFilter; private volatile boolean myIdFilterForLibraries; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ClassMapCachingNulls.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ClassMapCachingNulls.java index 6d7d1ed44b2f..4a996a019e44 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ClassMapCachingNulls.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ClassMapCachingNulls.java @@ -15,7 +15,7 @@ */ package com.intellij.psi.impl.source.tree.injected; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -27,7 +27,7 @@ import java.util.Map; public class ClassMapCachingNulls { private final Map myBackingMap; private final T[] myEmptyArray; - private final Map myMap = new ConcurrentHashMap(); + private final Map myMap = ContainerUtil.newConcurrentMap(); public ClassMapCachingNulls(@NotNull Map backingMap, T[] emptyArray) { myBackingMap = backingMap; diff --git a/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java b/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java index 4a7a71c7a7eb..b7f14807b5aa 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java @@ -24,7 +24,6 @@ import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentIntObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.DataInputOutputUtil; @@ -63,7 +62,7 @@ public class IndexingStamp { private static final long INDEX_DATA_OUTDATED_STAMP = -2L; private static final int VERSION = 13; - private static final ConcurrentMap, Long> ourIndexIdToCreationStamp = new ConcurrentHashMap, Long>(); + private static final ConcurrentMap, Long> ourIndexIdToCreationStamp = ContainerUtil.newConcurrentMap(); static final int INVALID_FILE_ID = 0; private static volatile long ourLastStamp; // ensure any file index stamp increases diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java b/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java index d0dc842f7c93..c6ad7e1bc948 100644 --- a/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java +++ b/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java @@ -21,7 +21,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileListener; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileSystem; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -33,7 +33,8 @@ import java.util.Map; * @author max */ public abstract class NewVirtualFileSystem extends VirtualFileSystem implements FileSystemInterface, CachingVirtualFileSystem { - private final Map myListenerWrappers = new ConcurrentHashMap(); + private final Map myListenerWrappers = + ContainerUtil.newConcurrentMap(); @Nullable public abstract VirtualFile findFileByPathIfCached(@NotNull @NonNls final String path); diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java index 245c212f39cc..d96954b54a67 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ModifierKeyDoubleClickHandler.java @@ -25,7 +25,7 @@ import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.util.Clock; import com.intellij.openapi.util.Couple; import com.intellij.openapi.wm.IdeFocusManager; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.TIntIntHashMap; import gnu.trove.TIntIntProcedure; import org.jetbrains.annotations.NotNull; @@ -55,10 +55,10 @@ public class ModifierKeyDoubleClickHandler { private static final ModifierKeyDoubleClickHandler INSTANCE = new ModifierKeyDoubleClickHandler(); - private final ConcurrentMap myDispatchers = new ConcurrentHashMap(); - + private final ConcurrentMap myDispatchers = + ContainerUtil.newConcurrentMap(); private boolean myIsRunningAction; - + private ModifierKeyDoubleClickHandler() { } public static ModifierKeyDoubleClickHandler getInstance() { 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 8c36b3129fbb..b73fb40b069c 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 @@ -32,7 +32,6 @@ import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Function; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.URLUtil; import com.intellij.util.messages.MessageBus; @@ -533,7 +532,8 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp } private static class DelegatingDisposable implements Disposable { - private static final ConcurrentMap ourInstances = new ConcurrentHashMap(ContainerUtil.identityStrategy()); + private static final ConcurrentMap ourInstances = + ContainerUtil.newConcurrentMap(ContainerUtil.identityStrategy()); private final TObjectIntHashMap myCounts = new TObjectIntHashMap(); private final Disposable myParent; 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 ce7d6db1cc34..ec4d71981da6 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 @@ -33,7 +33,7 @@ import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.openapi.vfs.newvfs.impl.FileNameCache; import com.intellij.util.ArrayUtil; import com.intellij.util.SystemProperties; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.IntArrayList; import com.intellij.util.io.*; import com.intellij.util.io.DataOutputStream; @@ -137,7 +137,7 @@ public class FSRecords implements Forceable { static class DbConnection { private static boolean ourInitialized; - private static final ConcurrentMap myAttributeIds = new ConcurrentHashMap(); + private static final ConcurrentMap myAttributeIds = ContainerUtil.newConcurrentMap(); private static PersistentStringEnumerator myNames; private static Storage myAttributes; 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 1d57dd28b915..c7fbc6eba7d6 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 @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.remoteServer.impl.runtime; import com.intellij.execution.ExecutionException; @@ -21,7 +36,7 @@ import com.intellij.remoteServer.runtime.deployment.debug.DebugConnectionDataNot import com.intellij.remoteServer.runtime.deployment.debug.DebugConnector; import com.intellij.util.Consumer; import com.intellij.util.ParameterizedRunnable; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -41,7 +56,7 @@ public class ServerConnectionImpl implements private volatile ServerRuntimeInstance myRuntimeInstance; private final Map myRemoteDeployments = new HashMap(); private final Map myLocalDeployments = new HashMap(); - private final Map myLogManagers = new ConcurrentHashMap(); + private final Map myLogManagers = ContainerUtil.newConcurrentMap(); public ServerConnectionImpl(RemoteServer server, ServerConnector connector, diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java index a6cd9a78e757..b6130d955d65 100644 --- a/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java +++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java @@ -19,8 +19,8 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Consumer; import com.intellij.util.EventDispatcher; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -32,27 +32,28 @@ import java.util.concurrent.ConcurrentMap; public abstract class BreakpointManagerBase> implements BreakpointManager { protected final Set breakpoints = new ConcurrentHashSet(); - protected final ConcurrentMap breakpointDuplicationByTarget = new ConcurrentHashMap(new TObjectHashingStrategy() { - @Override - public int computeHashCode(T b) { - int result = b.getLine(); - result = 31 * result + b.getColumn(); - if (b.getCondition() != null) { - result = 31 * result + b.getCondition().hashCode(); + protected final ConcurrentMap breakpointDuplicationByTarget = + ContainerUtil.newConcurrentMap(new TObjectHashingStrategy() { + @Override + public int computeHashCode(T b) { + int result = b.getLine(); + result = 31 * result + b.getColumn(); + if (b.getCondition() != null) { + result = 31 * result + b.getCondition().hashCode(); + } + result = 31 * result + b.getTarget().hashCode(); + return result; } - result = 31 * result + b.getTarget().hashCode(); - return result; - } - @Override - public boolean equals(T b1, T b2) { - return b1.getTarget().getClass() == b2.getTarget().getClass() && - b1.getTarget().equals(b2.getTarget()) && - b1.getLine() == b2.getLine() && - b1.getColumn() == b2.getColumn() && - StringUtil.equals(b1.getCondition(), b2.getCondition()); - } - }); + @Override + public boolean equals(T b1, T b2) { + return b1.getTarget().getClass() == b2.getTarget().getClass() && + b1.getTarget().equals(b2.getTarget()) && + b1.getLine() == b2.getLine() && + b1.getColumn() == b2.getColumn() && + StringUtil.equals(b1.getCondition(), b2.getCondition()); + } + }); protected final EventDispatcher dispatcher = EventDispatcher.create(BreakpointListener.class); diff --git a/platform/testFramework/src/com/intellij/openapi/application/ex/PathManagerEx.java b/platform/testFramework/src/com/intellij/openapi/application/ex/PathManagerEx.java index 4616c4f86c08..9e0176b4d2da 100644 --- a/platform/testFramework/src/com/intellij/openapi/application/ex/PathManagerEx.java +++ b/platform/testFramework/src/com/intellij/openapi/application/ex/PathManagerEx.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.testFramework.TestRunnerUtil; import com.intellij.util.PathUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import junit.framework.TestCase; import org.jdom.Element; @@ -65,9 +65,12 @@ public class PathManagerEx { ULTIMATE, COMMUNITY } - /** Caches test data lookup strategy by class. */ - private static final ConcurrentMap CLASS_STRATEGY_CACHE = new ConcurrentHashMap(); - private static final ConcurrentMap CLASS_CACHE = new ConcurrentHashMap(); + /** + * Caches test data lookup strategy by class. + */ + private static final ConcurrentMap CLASS_STRATEGY_CACHE = + ContainerUtil.newConcurrentMap(); + private static final ConcurrentMap CLASS_CACHE = ContainerUtil.newConcurrentMap(); private static Set ourCommunityModules; private PathManagerEx() { diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentWeakKeySoftValueHashMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentWeakKeySoftValueHashMap.java index 36d83d104e0c..17854d3952bf 100644 --- a/platform/util/src/com/intellij/util/containers/ConcurrentWeakKeySoftValueHashMap.java +++ b/platform/util/src/com/intellij/util/containers/ConcurrentWeakKeySoftValueHashMap.java @@ -53,18 +53,21 @@ public class ConcurrentWeakKeySoftValueHashMap implements ConcurrentMap hashingStrategy) { myHashingStrategy = hashingStrategy; - myMap = new ConcurrentHashMap, ValueReference>(initialCapacity, loadFactor, concurrencyLevel, TObjectHashingStrategy.CANONICAL); + myMap = ContainerUtil.newConcurrentMap(initialCapacity, loadFactor, concurrencyLevel, ContainerUtil.>canonicalStrategy()); } public interface KeyReference extends Getter { + @Override K get(); @NotNull ValueReference getValueReference(); // no strong references // MUST work even with gced references for the code in processQueue to work + @Override boolean equals(Object o); + @Override int hashCode(); } @@ -72,6 +75,7 @@ public class ConcurrentWeakKeySoftValueHashMap implements ConcurrentMap getKeyReference(); // no strong references + @Override V get(); } @@ -87,6 +91,7 @@ public class ConcurrentWeakKeySoftValueHashMap implements ConcurrentMap implements ConcurrentMap implements ConcurrentMap implements ConcurrentMap implements ConcurrentMap implements ConcurrentMap m) { for (Map.Entry e : m.entrySet()) { put(e.getKey(), e.getValue()); diff --git a/platform/util/src/com/intellij/util/containers/LockFreeCopyOnWriteArrayList.java b/platform/util/src/com/intellij/util/containers/LockFreeCopyOnWriteArrayList.java index 14f115f7a44e..28bc485d804e 100644 --- a/platform/util/src/com/intellij/util/containers/LockFreeCopyOnWriteArrayList.java +++ b/platform/util/src/com/intellij/util/containers/LockFreeCopyOnWriteArrayList.java @@ -32,7 +32,7 @@ import java.util.*; * - less-garbage (does not create Object[0] arrays) * - non-cloneable, non-serializable, no-subList-method variant of {@link java.util.concurrent.CopyOnWriteArrayList}. * It generally is faster than COWAL in case of low write-contention. - * (Note that it is not advisable to use COWAL in high write-contention code anyway, consider using {@link ConcurrentHashMap}) instead) + * (Note that it is not advisable to use COWAL in high write-contention code anyway, consider using {@link java.util.concurrent.ConcurrentHashMap}) instead) */ class LockFreeCopyOnWriteArrayList implements List, RandomAccess, ConcurrentList { @SuppressWarnings("FieldMayBeFinal") diff --git a/platform/util/src/com/intellij/util/messages/impl/MessageListenerList.java b/platform/util/src/com/intellij/util/messages/impl/MessageListenerList.java index 6d7bf76ccde7..7597e1577cfa 100644 --- a/platform/util/src/com/intellij/util/messages/impl/MessageListenerList.java +++ b/platform/util/src/com/intellij/util/messages/impl/MessageListenerList.java @@ -17,7 +17,7 @@ package com.intellij.util.messages.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.messages.Topic; @@ -31,7 +31,7 @@ import java.util.Map; public class MessageListenerList { private final MessageBus myMessageBus; private final Topic myTopic; - private final Map myListenerToConnectionMap = new ConcurrentHashMap(); + private final Map myListenerToConnectionMap = ContainerUtil.newConcurrentMap(); public MessageListenerList(@NotNull MessageBus messageBus, @NotNull Topic topic) { myTopic = topic; diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CachesHolder.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CachesHolder.java index 3d06a9564776..f23a9361bd92 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CachesHolder.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CachesHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.NotNullFunction; import com.intellij.util.PairProcessor; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -45,14 +45,14 @@ public class CachesHolder { myProject = project; myLocationCache = locationCache; myPlManager = ProjectLevelVcsManager.getInstance(myProject); - myCacheFiles = new ConcurrentHashMap(); + myCacheFiles = ContainerUtil.newConcurrentMap(); } public CachesHolder(final Project project, final RepositoryLocationCache locationCache, final ProjectLevelVcsManager manager) { myProject = project; myPlManager = manager; myLocationCache = locationCache; - myCacheFiles = new ConcurrentHashMap(); + myCacheFiles = ContainerUtil.newConcurrentMap(); } /** diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java index 2708f5130040..43d805494c50 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesCache.java @@ -46,7 +46,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.MessageBusUtil; import com.intellij.util.NotNullFunction; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.messages.MessageBus; @@ -186,7 +185,7 @@ public class CommittedChangesCache implements PersistentStateComponent>>(); + myExternallyLoadedChangeLists = ContainerUtil.newConcurrentMap(); } public MessageBus getMessageBus() { diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java index fcb00ffeeeda..75c1ebc8a3c1 100644 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java +++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/SubstitutedExpressionEvaluationHelper.java @@ -20,7 +20,7 @@ import com.intellij.codeInspection.dataFlow.DfaPsiUtil; import com.intellij.codeInspection.dataFlow.DfaUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.*; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.intellij.plugins.intelliLang.Configuration; import org.jetbrains.annotations.Nullable; @@ -50,7 +50,7 @@ public class SubstitutedExpressionEvaluationHelper { } public Object computeExpression(final PsiExpression e, final Configuration.DfaOption dfaOption, final boolean includeUncomputablesAsLiterals, final List uncomputables) { - final ConcurrentMap map = new ConcurrentHashMap(); + final ConcurrentMap map = ContainerUtil.newConcurrentMap(); //if (true) return myHelper.computeConstantExpression(e, false); return myHelper.computeExpression(e, false, new PsiConstantEvaluationHelper.AuxEvaluator() { @Nullable diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/FactorTree.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/FactorTree.java index b6e9b802c597..55a56e75f5fb 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/FactorTree.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/FactorTree.java @@ -26,7 +26,7 @@ import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.dsl.holders.CustomMembersHolder; @@ -48,7 +48,8 @@ public class FactorTree extends UserDataHolderBase { @Nullable @Override public Result compute() { - return new Result(new ConcurrentHashMap(), PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(project)); + return new Result(ContainerUtil.newConcurrentMap(), PsiModificationTracker.MODIFICATION_COUNT, + ProjectRootManager.getInstance(project)); } }; myTopLevelCache = CachedValuesManager.getManager(project).createCachedValue(myProvider, false); @@ -76,7 +77,7 @@ public class FactorTree extends UserDataHolderBase { Map next = (Map)current.get(key); if (next == null) { //noinspection unchecked - current.put(key, next = new ConcurrentHashMap()); + current.put(key, next = ContainerUtil.newConcurrentMap()); } current = next; } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/toplevel/ClassContextFilter.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/toplevel/ClassContextFilter.java index 6ed28ea5e9aa..6d5a86787dca 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/toplevel/ClassContextFilter.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/dsl/toplevel/ClassContextFilter.java @@ -21,7 +21,7 @@ import com.intellij.openapi.util.Pair; import com.intellij.patterns.ElementPattern; import com.intellij.psi.*; import com.intellij.util.ProcessingContext; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.plugins.groovy.dsl.GroovyClassDescriptor; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.ClassUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; @@ -86,7 +86,7 @@ public class ClassContextFilter implements ContextFilter { public static PsiType getCachedType(String typeText, PsiFile context) { Map map = context.getUserData(CACHED_TYPES); if (map == null) { - map = new ConcurrentHashMap(); + map = ContainerUtil.newConcurrentMap(); context.putUserData(CACHED_TYPES, map); } PsiType type = map.get(typeText); 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 844608cd181e..d37ec484ff76 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 @@ -32,7 +32,10 @@ import com.intellij.psi.util.InheritanceUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.containers.*; +import com.intellij.util.containers.ConcurrentSoftValueHashMap; +import com.intellij.util.containers.ConcurrentWeakHashMap; +import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.containers.HashMap; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -65,7 +68,7 @@ public class GroovyPsiManager { private final ConcurrentMap myCalculatedTypes = new ConcurrentWeakHashMap(); private final Map> myClassCache = new ConcurrentSoftValueHashMap>(); - private final ConcurrentMap myCompileStatic = new ConcurrentHashMap(); + private final ConcurrentMap myCompileStatic = ContainerUtil.newConcurrentMap(); private static final RecursionGuard ourGuard = RecursionManager.createGuard("groovyPsiManager"); @@ -160,7 +163,7 @@ public class GroovyPsiManager { public PsiClass findClassWithCache(@NotNull String fqName, @NotNull GlobalSearchScope resolveScope) { Map map = myClassCache.get(fqName); if (map == null) { - map = new ConcurrentHashMap(); + map = ContainerUtil.newConcurrentMap(); myClassCache.put(fqName, map); } PsiClass cached = map.get(resolveScope); diff --git a/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/TransferListenerAdapter.java b/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/TransferListenerAdapter.java index 9f68354217c1..74694592c5be 100644 --- a/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/TransferListenerAdapter.java +++ b/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/TransferListenerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.jetbrains.idea.maven.server.embedder; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; import org.jetbrains.idea.maven.server.Maven2ServerGlobals; @@ -30,7 +30,7 @@ import java.util.Map; public class TransferListenerAdapter implements TransferListener { protected final MavenServerProgressIndicator myIndicator; - private final Map myDownloads = new ConcurrentHashMap(); + private final Map myDownloads = ContainerUtil.newConcurrentMap(); public TransferListenerAdapter(MavenServerProgressIndicator indicator) { myIndicator = indicator; diff --git a/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/WagonTransferListenerAdapter.java b/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/WagonTransferListenerAdapter.java index df4980f503fb..50b718f4bc52 100644 --- a/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/WagonTransferListenerAdapter.java +++ b/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/WagonTransferListenerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.jetbrains.idea.maven.server; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.events.TransferListener; @@ -27,7 +27,7 @@ import java.util.Map; public class WagonTransferListenerAdapter implements TransferListener { protected final MavenServerProgressIndicator myIndicator; - private final Map myDownloads = new ConcurrentHashMap(); + private final Map myDownloads = ContainerUtil.newConcurrentMap(); public WagonTransferListenerAdapter(MavenServerProgressIndicator indicator) { myIndicator = indicator; diff --git a/python/src/com/jetbrains/python/packaging/PyPackageService.java b/python/src/com/jetbrains/python/packaging/PyPackageService.java index b65ca59e6dc6..f101b32e7db4 100644 --- a/python/src/com/jetbrains/python/packaging/PyPackageService.java +++ b/python/src/com/jetbrains/python/packaging/PyPackageService.java @@ -16,7 +16,7 @@ package com.jetbrains.python.packaging; import com.intellij.openapi.components.*; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.XmlSerializerUtil; import java.util.ArrayList; @@ -36,7 +36,7 @@ public class PyPackageService implements PersistentStateComponent { public Map sdkToUsersite = new HashMap(); public List additionalRepositories = new ArrayList(); - public Map PY_PACKAGES = new ConcurrentHashMap(); + public Map PY_PACKAGES = ContainerUtil.newConcurrentMap(); public String virtualEnvBasePath; public long LAST_TIME_CHECKED = 0; 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 02d494e123f4..8bde5190502c 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 @@ -23,7 +23,6 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Factory; import com.intellij.util.Function; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomElementVisitor; @@ -38,9 +37,9 @@ import java.util.*; public class DomElementsProblemsHolderImpl implements DomElementsProblemsHolder { private final Map, List>> myCachedErrors = - new ConcurrentHashMap, List>>(); + ContainerUtil.newConcurrentMap(); private final Map, List>> myCachedChildrenErrors = - new ConcurrentHashMap, List>>(); + ContainerUtil.newConcurrentMap(); private final List myAnnotations = new ArrayList(); private final Function> myDomProblemsGetter = @@ -57,7 +56,7 @@ public class DomElementsProblemsHolderImpl implements DomElementsProblemsHolder private static final Factory,List>> CONCURRENT_HASH_MAP_FACTORY = new Factory, List>>() { @Override public Map, List> create() { - return new ConcurrentHashMap, List>(); + return ContainerUtil.newConcurrentMap(); } }; private static final Factory> SMART_LIST_FACTORY = new Factory>() { 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 e95182cdb69f..43e2b67aad68 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 @@ -27,7 +27,6 @@ import com.intellij.reference.SoftReference; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.Processor; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.GenericDomValue; @@ -143,7 +142,7 @@ public class DynamicGenericInfo extends DomGenericInfoEx { SoftReference> ref = file.getUserData(HOLDERS_CACHE); ConcurrentMap cache = SoftReference.dereference(ref); if (cache == null) { - cache = new ConcurrentHashMap(); + cache = ContainerUtil.newConcurrentMap(); file.putUserData(HOLDERS_CACHE, new SoftReference>(cache)); } ChildrenDescriptionsHolder existing = cache.get(holder); diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/SofterCache.java b/xml/dom-impl/src/com/intellij/util/xml/impl/SofterCache.java index 1e037445ee1c..a45dc69179cd 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/impl/SofterCache.java +++ b/xml/dom-impl/src/com/intellij/util/xml/impl/SofterCache.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package com.intellij.util.xml.impl; import com.intellij.util.NotNullFunction; import com.intellij.util.SofterReference; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import java.util.concurrent.ConcurrentMap; @@ -44,7 +44,7 @@ public class SofterCache { SofterReference> ref = myCache; ConcurrentMap map = ref == null ? null : ref.get(); if (map == null) { - myCache = new SofterReference>(map = new ConcurrentHashMap()); + myCache = new SofterReference>(map = ContainerUtil.newConcurrentMap()); } V value = map.get(key); if (value == null) { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/DomFileDescription.java b/xml/dom-openapi/src/com/intellij/util/xml/DomFileDescription.java index 97950b30037e..9e7a3ec61529 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/DomFileDescription.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/DomFileDescription.java @@ -25,8 +25,8 @@ import com.intellij.psi.xml.XmlTag; import com.intellij.util.ConstantFunction; import com.intellij.util.NotNullFunction; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentInstanceMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.highlighting.DomElementsAnnotator; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -53,7 +53,8 @@ public class DomFileDescription { private final Map,Class> myImplementations = new HashMap, Class>(); private final TypeChooserManager myTypeChooserManager = new TypeChooserManager(); private final List myInjectors = new SmartList(); - private final Map>> myNamespacePolicies = new ConcurrentHashMap>>(); + private final Map>> myNamespacePolicies = + ContainerUtil.newConcurrentMap(); public DomFileDescription(final Class rootElementClass, @NonNls final String rootTagName, @NonNls final String... allPossibleRootTagNamespaces) { myRootElementClass = rootElementClass; diff --git a/xml/dom-openapi/src/com/intellij/util/xml/EvaluatedXmlNameImpl.java b/xml/dom-openapi/src/com/intellij/util/xml/EvaluatedXmlNameImpl.java index a0caa3453840..8cd26cae2975 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/EvaluatedXmlNameImpl.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/EvaluatedXmlNameImpl.java @@ -23,7 +23,7 @@ import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.xml.*; import com.intellij.util.containers.ConcurrentFactoryMap; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -38,7 +38,8 @@ import java.util.Map; */ public class EvaluatedXmlNameImpl implements EvaluatedXmlName { private static final Key>>> NAMESPACE_PROVIDER_KEY = Key.create("NamespaceProvider"); - private static final Map ourInterned = new ConcurrentHashMap(); + private static final Map ourInterned = + ContainerUtil.newConcurrentMap(); private final XmlName myXmlName; private final String myNamespaceKey; diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java index 8a26c162f993..0b15a0fc422c 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java @@ -43,7 +43,7 @@ import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.xml.*; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.containers.ConcurrentHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.Html5SchemaProvider; import com.intellij.xml.XmlExtension; import com.intellij.xml.XmlNSDescriptor; @@ -149,8 +149,10 @@ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { return rootTag != null ? rootTag.getNSDescriptor(rootTag.getNamespace(), false) : null; } - private ConcurrentMap> myDefaultDescriptorsCacheStrict = new ConcurrentHashMap>(); - private ConcurrentMap> myDefaultDescriptorsCacheNotStrict = new ConcurrentHashMap>(); + private ConcurrentMap> myDefaultDescriptorsCacheStrict = + ContainerUtil.newConcurrentMap(); + private ConcurrentMap> myDefaultDescriptorsCacheNotStrict = + ContainerUtil.newConcurrentMap(); @Override public void clearCaches() { @@ -376,8 +378,8 @@ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { private void updateSelfDependentDtdDescriptors(XmlDocumentImpl copy, HashMap> cacheStrict, HashMap> cacheNotStrict) { - copy.myDefaultDescriptorsCacheNotStrict = new ConcurrentHashMap>(); - copy.myDefaultDescriptorsCacheStrict = new ConcurrentHashMap>(); + copy.myDefaultDescriptorsCacheNotStrict = ContainerUtil.newConcurrentMap(); + copy.myDefaultDescriptorsCacheStrict = ContainerUtil.newConcurrentMap(); for(Map.Entry> e:cacheStrict.entrySet()) { if (e.getValue().hasUpToDateValue()) { From ea5e01153a3a1489524f0ef22220e48080b95cce Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 15:54:57 +0300 Subject: [PATCH 09/31] file type test --- .../openapi/fileTypes/impl/FileTypesTest.java | 42 ++++++++----------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java index b0f9b84872ec..df484cce9a83 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java @@ -30,12 +30,11 @@ import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.testFramework.PlatformTestCase; import com.intellij.util.PatternUtil; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; @@ -290,15 +289,16 @@ public class FileTypesTest extends PlatformTestCase { assertNotNull(project); assertFalse(project.equals(PlainTextFileType.INSTANCE)); - final Set detectorCalled = new ConcurrentHashSet(); + final Set detectorCalled = ContainerUtil.newConcurrentSet(); FileTypeRegistry.FileTypeDetector detector = new FileTypeRegistry.FileTypeDetector() { @Nullable @Override public FileType detect(@NotNull VirtualFile file, @NotNull ByteSequence firstBytes, @Nullable CharSequence firstCharsIfText) { detectorCalled.add(file); String text = firstCharsIfText.toString(); - if (text.startsWith("TYPE:")) return FileTypeRegistry.getInstance().findFileTypeByName(StringUtil.trimStart(text, "TYPE:")); - return null; + FileType result = text.startsWith("TYPE:") ? FileTypeRegistry.getInstance().findFileTypeByName(StringUtil.trimStart(text, "TYPE:")) : null; + System.out.println("T: my detector run for "+file.getName()+"; result: "+(result == null ? null : result.getName())); + return result; } @Override @@ -312,35 +312,29 @@ public class FileTypesTest extends PlatformTestCase { File f = new File(d, "xx.asfdasdfas"); FileUtil.writeToFile(f, "akjdhfksdjgf"); VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f); - ((NewVirtualFile)vFile).markDirty(); - vFile.refresh(false, false); - UIUtil.dispatchAllInvocationEvents(); - myFileTypeManager.drainReDetectQueue(); - UIUtil.dispatchAllInvocationEvents(); + ensureRedetected(vFile, detectorCalled); assertTrue(vFile.getFileType().toString(), vFile.getFileType() instanceof PlainTextFileType); - assertTrue(detectorCalled.contains(vFile)); - detectorCalled.clear(); VfsUtil.saveText(vFile, "TYPE:IDEA_MODULE"); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - UIUtil.dispatchAllInvocationEvents(); - myFileTypeManager.drainReDetectQueue(); - UIUtil.dispatchAllInvocationEvents(); - assertTrue(detectorCalled.contains(vFile)); - detectorCalled.clear(); + ensureRedetected(vFile, detectorCalled); assertTrue(vFile.getFileType().toString(), vFile.getFileType() instanceof ModuleFileType); VfsUtil.saveText(vFile, "TYPE:IDEA_PROJECT"); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - UIUtil.dispatchAllInvocationEvents(); - myFileTypeManager.drainReDetectQueue(); - UIUtil.dispatchAllInvocationEvents(); - assertTrue(detectorCalled.contains(vFile)); - detectorCalled.clear(); + ensureRedetected(vFile, detectorCalled); assertTrue(vFile.getFileType().toString(), vFile.getFileType() instanceof ProjectFileType); } finally { Extensions.getRootArea().getExtensionPoint(FileTypeRegistry.FileTypeDetector.EP_NAME).unregisterExtension(detector); } } + + private void ensureRedetected(VirtualFile vFile, Set detectorCalled) { + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + UIUtil.dispatchAllInvocationEvents(); + myFileTypeManager.drainReDetectQueue(); + UIUtil.dispatchAllInvocationEvents(); + vFile.getFileType(); + assertTrue(detectorCalled.contains(vFile)); + detectorCalled.clear(); + } } From 6a98f8aee028bebc625a1ef7f7b25966b49d3e84 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 15:57:28 +0300 Subject: [PATCH 10/31] instantiate ConcurrentHashSet via factory only --- .../server/BuildMessageDispatcher.java | 6 +++--- .../com/intellij/slicer/SliceLeafAnalyzer.java | 3 +-- .../intellij/psi/util/TypeConversionUtil.java | 3 +-- .../jps/incremental/IncProjectBuilder.java | 5 ++--- .../intellij/mock/MockComponentManager.java | 4 ++-- .../util/AbstractProgressIndicatorBase.java | 6 ++++-- .../psi/impl/PsiDocumentManagerBase.java | 3 +-- ...lSystemProgressNotificationManagerImpl.java | 3 +-- .../intention/impl/IntentionListStep.java | 14 ++++++++------ .../formatting/FormattingProgressTask.java | 3 +-- .../util/indexing/FileBasedIndexImpl.java | 7 +++---- .../impl/FileDocumentManagerImpl.java | 4 ++-- .../progress/impl/ProgressManagerImpl.java | 3 +-- .../vfs/impl/jar/JarFileSystemImpl.java | 4 ++-- .../vfs/tracker/VirtualFileTrackerImpl.java | 4 ++-- .../intellij/openapi/roots/impl/RootIndex.java | 3 +-- .../debugger/BreakpointManagerBase.java | 3 +-- .../util/containers/ConcurrentHashSet.java | 10 +++++----- .../util/containers/ContainerUtil.java | 12 ++++++++++++ .../com/intellij/util/containers/MultiMap.java | 2 +- .../intellij/vcs/log/impl/VcsLogManager.java | 18 ++++++++++++++++-- .../GroovyConstructorUsagesSearcher.java | 5 ++--- .../dataFlow/types/TypeInferenceHelper.java | 3 +-- .../intellij/tasks/impl/TaskManagerImpl.java | 5 ++--- 24 files changed, 75 insertions(+), 58 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java index 59c19f0ad7fe..096a113cf7f9 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package com.intellij.compiler.server; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; @@ -44,7 +44,7 @@ class BuildMessageDispatcher extends SimpleChannelInboundHandlerAdapter SESSION_DATA = AttributeKey.valueOf("BuildMessageDispatcher.sessionData"); private final Map mySessionDescriptors = new ConcurrentHashMap(16, 0.75f, 1); - private final Set myCanceledSessions = new ConcurrentHashSet(); + private final Set myCanceledSessions = ContainerUtil.newConcurrentSet(); public void registerBuildMessageHandler(@NotNull final RequestFuture future, @Nullable CmdlineRemoteProto.Message.ControllerMessage params) { final BuilderMessageHandler wrappedHandler = new DelegatingMessageHandler() { diff --git a/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java b/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java index 8be533f31f45..5c41984a6838 100644 --- a/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java +++ b/java/java-impl/src/com/intellij/slicer/SliceLeafAnalyzer.java @@ -33,7 +33,6 @@ import com.intellij.psi.impl.source.tree.AstBufferUtil; import com.intellij.util.NullableFunction; import com.intellij.util.PairProcessor; import com.intellij.util.WalkingState; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; import gnu.trove.TObjectHashingStrategy; @@ -191,7 +190,7 @@ public class SliceLeafAnalyzer { @Override protected Collection create(SliceNode key) { - return new ConcurrentHashSet(LEAF_ELEMENT_EQUALITY); + return ContainerUtil.newConcurrentSet(LEAF_ELEMENT_EQUALITY); } }; } diff --git a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java index 78d3e73e7ea3..1041b9fa1c71 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java @@ -24,7 +24,6 @@ import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.util.Processor; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import gnu.trove.THashMap; @@ -1043,7 +1042,7 @@ public class TypeConversionUtil { return getMaybeSuperClassSubstitutor(superClassCandidate, derivedClassCandidate, derivedSubstitutor, null); } - private static final Set ourReportedSuperClassSubstitutorExceptions = new ConcurrentHashSet(); + private static final Set ourReportedSuperClassSubstitutorExceptions = ContainerUtil.newConcurrentSet(); /** * Calculates substitutor that binds type parameters in superClass with diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java index c32dbd178aeb..b5568aaa5c6d 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SmartList; import com.intellij.util.concurrency.BoundedTaskExecutor; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.io.MappingFailedException; @@ -1230,7 +1229,7 @@ public class IncProjectBuilder { private static CompileContext createContextWrapper(final CompileContext delegate) { final ClassLoader loader = delegate.getClass().getClassLoader(); final UserDataHolderBase localDataHolder = new UserDataHolderBase(); - final Set deletedKeysSet = new ConcurrentHashSet(); + final Set deletedKeysSet = ContainerUtil.newConcurrentSet(); final Class dataHolderInterface = UserDataHolder.class; final Class messageHandlerInterface = MessageHandler.class; return (CompileContext)Proxy.newProxyInstance(loader, new Class[]{CompileContext.class}, new InvocationHandler() { diff --git a/platform/core-impl/src/com/intellij/mock/MockComponentManager.java b/platform/core-impl/src/com/intellij/mock/MockComponentManager.java index 02439ac0b794..9b92ed11310e 100644 --- a/platform/core-impl/src/com/intellij/mock/MockComponentManager.java +++ b/platform/core-impl/src/com/intellij/mock/MockComponentManager.java @@ -23,7 +23,7 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.UserDataHolderBase; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusFactory; import com.intellij.util.pico.IdeaPicoContainer; @@ -46,7 +46,7 @@ public class MockComponentManager extends UserDataHolderBase implements Componen public MockComponentManager(@Nullable PicoContainer parent, @NotNull Disposable parentDisposable) { myPicoContainer = new IdeaPicoContainer(parent) { - private final Set myDisposableComponents = new ConcurrentHashSet(); + private final Set myDisposableComponents = ContainerUtil.newConcurrentSet(); @Override @Nullable diff --git a/platform/core-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorBase.java b/platform/core-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorBase.java index 4841aa3b44a7..af8546cb6147 100644 --- a/platform/core-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorBase.java +++ b/platform/core-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorBase.java @@ -23,12 +23,14 @@ import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.UserDataHolderBase; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.DoubleArrayList; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import java.util.Set; + public class AbstractProgressIndicatorBase extends UserDataHolderBase implements ProgressIndicatorStacked { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.util.ProgressIndicatorBase"); @@ -69,7 +71,7 @@ public class AbstractProgressIndicatorBase extends UserDataHolderBase implements myRunning = true; } - private static final ConcurrentHashSet ourReportedReuseExceptions = new ConcurrentHashSet(2); + private static final Set ourReportedReuseExceptions = ContainerUtil.newConcurrentSet(); protected boolean isReuseable() { return false; diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java index 80352b7c0a13..9bd52662a5b3 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java +++ b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java @@ -47,7 +47,6 @@ import com.intellij.util.Processor; import com.intellij.util.SmartList; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.Semaphore; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NonNls; @@ -67,7 +66,7 @@ public abstract class PsiDocumentManagerBase extends PsiDocumentManager implemen protected final Project myProject; private final PsiManager myPsiManager; private final DocumentCommitProcessor myDocumentCommitProcessor; - protected final Set myUncommittedDocuments = new ConcurrentHashSet(); + protected final Set myUncommittedDocuments = ContainerUtil.newConcurrentSet(); private final Map myLastCommittedTexts = ContainerUtil.newConcurrentMap(); private volatile boolean myIsCommitInProgress; diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java index 30f98f407167..1c3c7bf13e89 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/ExternalSystemProgressNotificationManagerImpl.java @@ -20,7 +20,6 @@ import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener; import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -56,7 +55,7 @@ public class ExternalSystemProgressNotificationManagerImpl extends RemoteObject ids = myListeners.get(listener); } else { - ids = myListeners.putIfAbsent(listener, new ConcurrentHashSet()); + ids = myListeners.putIfAbsent(listener, ContainerUtil.newConcurrentSet()); } } return ids.add(taskId); 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 99cfc6e9f978..0700b6e1e1b2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import com.intellij.openapi.util.Iconable; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.util.PsiUtilBase; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; @@ -54,10 +54,12 @@ import java.util.*; class IntentionListStep implements ListPopupStep, SpeedSearchFilter { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.intention.impl.IntentionListStep"); - private final Set myCachedIntentions = new ConcurrentHashSet(ACTION_TEXT_AND_CLASS_EQUALS); - private final Set myCachedErrorFixes = new ConcurrentHashSet(ACTION_TEXT_AND_CLASS_EQUALS); - private final Set myCachedInspectionFixes = new ConcurrentHashSet(ACTION_TEXT_AND_CLASS_EQUALS); - private final Set myCachedGutters = new ConcurrentHashSet(ACTION_TEXT_AND_CLASS_EQUALS); + private final Set myCachedIntentions = + ContainerUtil.newConcurrentSet(ACTION_TEXT_AND_CLASS_EQUALS); + private final Set myCachedErrorFixes = + ContainerUtil.newConcurrentSet(ACTION_TEXT_AND_CLASS_EQUALS); + private final Set myCachedInspectionFixes = ContainerUtil.newConcurrentSet(ACTION_TEXT_AND_CLASS_EQUALS); + private final Set myCachedGutters = ContainerUtil.newConcurrentSet(ACTION_TEXT_AND_CLASS_EQUALS); private final IntentionManagerSettings mySettings; @Nullable private final IntentionHintComponent myIntentionHintComponent; diff --git a/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java b/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java index 6fd20d76190c..511f81106948 100644 --- a/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java +++ b/platform/lang-impl/src/com/intellij/formatting/FormattingProgressTask.java @@ -27,7 +27,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.util.SequentialModalProgressTask; import com.intellij.util.SequentialTask; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; @@ -139,7 +138,7 @@ public class FormattingProgressTask extends SequentialModalProgressTask implemen private Collection getCallbacks(@NotNull EventType eventType) { Collection result = myCallbacks.get(eventType); if (result == null) { - Collection candidate = myCallbacks.putIfAbsent(eventType, result = new ConcurrentHashSet()); + Collection candidate = myCallbacks.putIfAbsent(eventType, result = ContainerUtil.newConcurrentSet()); if (candidate != null) { result = candidate; } 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 48cf63103139..989ff0b07105 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java @@ -69,7 +69,6 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.SerializationManagerEx; import com.intellij.util.*; import com.intellij.util.concurrency.Semaphore; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.*; import com.intellij.util.io.DataOutputStream; @@ -129,7 +128,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { private final FileDocumentManager myFileDocumentManager; private final FileTypeManagerImpl myFileTypeManager; private final SerializationManagerEx mySerializationManagerEx; - private final ConcurrentHashSet> myUpToDateIndicesForUnsavedOrTransactedDocuments = new ConcurrentHashSet>(); + private final Set> myUpToDateIndicesForUnsavedOrTransactedDocuments = ContainerUtil.newConcurrentSet(); private volatile SmartFMap myTransactionMap = SmartFMap.emptyMap(); @Nullable private final String myConfigPath; @@ -139,7 +138,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { private volatile int myLocalModCount; private volatile int myFilesModCount; private final AtomicInteger myUpdatingFiles = new AtomicInteger(); - private final ConcurrentHashSet myProjectsBeingUpdated = new ConcurrentHashSet(); + private final Set myProjectsBeingUpdated = ContainerUtil.newConcurrentSet(); @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) private volatile boolean myInitialized; // need this variable for memory barrier @@ -1874,7 +1873,7 @@ public class FileBasedIndexImpl extends FileBasedIndex { } private final class ChangedFilesCollector extends VirtualFileAdapter implements BulkFileListener { - private final Set myFilesToUpdate = new ConcurrentHashSet(); + private final Set myFilesToUpdate = ContainerUtil.newConcurrentSet(); private final Queue myFutureInvalidations = new ConcurrentLinkedQueue(); private final ManagingFS myManagingFS = ManagingFS.getInstance(); 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 e396a7f76b44..25832256f0e7 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 @@ -67,8 +67,8 @@ import com.intellij.ui.components.JBScrollPane; import com.intellij.util.Function; import com.intellij.util.PairProcessor; import com.intellij.util.ThrowableRunnable; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ConcurrentWeakValueHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -94,7 +94,7 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt private static final Key FILE_KEY = Key.create("FILE_KEY"); private static final Key MUST_RECOMPUTE_FILE_TYPE = Key.create("Must recompute file type"); - private final Set myUnsavedDocuments = new ConcurrentHashSet(); + private final Set myUnsavedDocuments = ContainerUtil.newConcurrentSet(); private final Map myDocuments = new ConcurrentWeakValueHashMap(); private final MessageBus myBus; 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 7ed1c335ddbc..878e60099b50 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 @@ -34,7 +34,6 @@ import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.psi.PsiLock; import com.intellij.ui.SystemNotifications; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ConcurrentLongObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SmartHashSet; @@ -70,7 +69,7 @@ public class ProgressManagerImpl extends ProgressManager implements Disposable { // the active indicator for the thread id private static final ConcurrentLongObjectMap currentIndicators = ContainerUtil.createConcurrentLongObjectMap(); // threads which are running under canceled indicator - static final Set threadsUnderCanceledIndicator = new ConcurrentHashSet(); + static final Set threadsUnderCanceledIndicator = ContainerUtil.newConcurrentSet(); // active (i.e. which have executeProcessUnderProgress() method running) indicators which are not inherited from StandardProgressIndicator. // for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method 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 4329da96fa90..11ba63776be4 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 @@ -25,7 +25,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.VfsImplUtil; import com.intellij.util.Function; import com.intellij.util.SystemProperties; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,7 +39,7 @@ public class JarFileSystemImpl extends JarFileSystem { public JarFileSystemImpl() { boolean noCopy = SystemProperties.getBooleanProperty("idea.jars.nocopy", !SystemInfo.isWindows); - myNoCopyJarPaths = noCopy ? null : new ConcurrentHashSet(FileUtil.PATH_HASHING_STRATEGY); + myNoCopyJarPaths = noCopy ? null : ContainerUtil.newConcurrentSet(FileUtil.PATH_HASHING_STRATEGY); // to prevent platform .jar files from copying boolean runningFromDist = new File(PathManager.getLibPath(), "openapi.jar").exists(); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/tracker/VirtualFileTrackerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/tracker/VirtualFileTrackerImpl.java index afdf6b8f194b..89acaf597e3f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/tracker/VirtualFileTrackerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/tracker/VirtualFileTrackerImpl.java @@ -18,7 +18,7 @@ package com.intellij.openapi.vfs.tracker; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.*; -import com.intellij.util.containers.ConcurrentHashSet; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -178,7 +178,7 @@ public class VirtualFileTrackerImpl implements VirtualFileTracker { Set listeners = map.get(fileUrl); if (listeners == null) { - listeners = new ConcurrentHashSet(); + listeners = ContainerUtil.newConcurrentSet(); map.put(fileUrl, listeners); } return listeners; 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 33ff1a509522..2d3c4fcc650d 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 @@ -34,7 +34,6 @@ import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.util.CollectionQuery; import com.intellij.util.EmptyQuery; import com.intellij.util.Query; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import gnu.trove.TObjectIntHashMap; @@ -64,7 +63,7 @@ public class RootIndex { }; private final Map> myDirectoriesByPackageNameCache = ContainerUtil.newConcurrentMap(); - private final Set myNonExistentPackages = new ConcurrentHashSet(); + private final Set myNonExistentPackages = ContainerUtil.newConcurrentSet(); private final InfoCache myInfoCache; private final List> myRootTypes = ContainerUtil.newArrayList(); private final TObjectIntHashMap> myRootTypeId = new TObjectIntHashMap>(); diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java index b6130d955d65..bf8dd81cdccb 100644 --- a/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java +++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.java @@ -19,7 +19,6 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Consumer; import com.intellij.util.EventDispatcher; import com.intellij.util.SmartList; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; @@ -31,7 +30,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentMap; public abstract class BreakpointManagerBase> implements BreakpointManager { - protected final Set breakpoints = new ConcurrentHashSet(); + protected final Set breakpoints = ContainerUtil.newConcurrentSet(); protected final ConcurrentMap breakpointDuplicationByTarget = ContainerUtil.newConcurrentMap(new TObjectHashingStrategy() { @Override diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java b/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java index f86dd2eedeeb..2b4331a50706 100644 --- a/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java +++ b/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,16 +24,16 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentMap; -public class ConcurrentHashSet implements Set { +class ConcurrentHashSet implements Set { private final ConcurrentMap map; - public ConcurrentHashSet(int initialCapacity) { + ConcurrentHashSet(int initialCapacity) { map = ContainerUtil.newConcurrentMap(initialCapacity); } - public ConcurrentHashSet() { + ConcurrentHashSet() { map = ContainerUtil.newConcurrentMap(); } - public ConcurrentHashSet(@NotNull TObjectHashingStrategy hashingStrategy) { + ConcurrentHashSet(@NotNull TObjectHashingStrategy hashingStrategy) { map = ContainerUtil.newConcurrentMap(hashingStrategy); } diff --git a/platform/util/src/com/intellij/util/containers/ContainerUtil.java b/platform/util/src/com/intellij/util/containers/ContainerUtil.java index 74784b2dbd4d..75fa2203bc18 100644 --- a/platform/util/src/com/intellij/util/containers/ContainerUtil.java +++ b/platform/util/src/com/intellij/util/containers/ContainerUtil.java @@ -363,6 +363,18 @@ public class ContainerUtil extends ContainerUtilRt { return ContainerUtilRt.newTreeSet(comparator); } + @NotNull + @Contract(pure=true) + public static Set newConcurrentSet() { + return new ConcurrentHashSet(); + } + + @NotNull + @Contract(pure=true) + public static Set newConcurrentSet(@NotNull TObjectHashingStrategy hashStrategy) { + return new ConcurrentHashSet(hashStrategy); + } + @NotNull @Contract(pure=true) public static ConcurrentMap newConcurrentMap() { diff --git a/platform/util/src/com/intellij/util/containers/MultiMap.java b/platform/util/src/com/intellij/util/containers/MultiMap.java index f14303607c26..cdb0f1298a8d 100644 --- a/platform/util/src/com/intellij/util/containers/MultiMap.java +++ b/platform/util/src/com/intellij/util/containers/MultiMap.java @@ -297,7 +297,7 @@ public class MultiMap implements Serializable { @NotNull @Override protected Collection createCollection() { - return new ConcurrentHashSet(); + return ContainerUtil.newConcurrentSet(); } @NotNull diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java index 4e6b1b272006..c5b011f8eec8 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.vcs.log.impl; import com.intellij.openapi.Disposable; @@ -19,7 +34,6 @@ import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManagerAdapter; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.util.Consumer; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.ui.UIUtil; @@ -162,7 +176,7 @@ public class VcsLogManager implements Disposable { @NotNull private final String myTabName; @NotNull private final MyRefreshPostponedEventsListener myPostponedEventsListener; - @NotNull private final Set myRootsToRefresh = new ConcurrentHashSet(); + @NotNull private final Set myRootsToRefresh = ContainerUtil.newConcurrentSet(); public PostponeableLogRefresher(@NotNull Project project, @NotNull VcsLogDataHolder dataHolder, @NotNull String contentTabName) { myDataHolder = dataHolder; 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 d3b9cec9481d..06a9c0aec6d9 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 @@ -36,7 +36,6 @@ import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.PairProcessor; import com.intellij.util.Processor; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -89,7 +88,7 @@ public class GroovyConstructorUsagesSearcher extends QueryExecutorBase processed = collector.getSearchSession().getUserData(LITERALLY_CONSTRUCTED_CLASSES); if (processed == null) { - collector.getSearchSession().putUserData(LITERALLY_CONSTRUCTED_CLASSES, processed = new ConcurrentHashSet()); + collector.getSearchSession().putUserData(LITERALLY_CONSTRUCTED_CLASSES, processed = ContainerUtil.newConcurrentSet()); } if (!processed.add(clazz)) return; @@ -143,7 +142,7 @@ public class GroovyConstructorUsagesSearcher extends QueryExecutorBase newExpressionProcessor, final LiteralConstructorSearcher literalProcessor) { - final Set processedMethods = new ConcurrentHashSet(); + final Set processedMethods = ContainerUtil.newConcurrentSet(); ReferencesSearch.searchOptimized(clazz, scope, true, collector, true, new PairProcessor() { @Override diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/TypeInferenceHelper.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/TypeInferenceHelper.java index 47743a6766fe..5f85f9f368b8 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/TypeInferenceHelper.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/TypeInferenceHelper.java @@ -24,7 +24,6 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.PsiType; import com.intellij.psi.util.*; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -376,7 +375,7 @@ public class TypeInferenceHelper { final GrControlFlowOwner scope; final Instruction[] flow; final AtomicReference> varTypes; - final ConcurrentHashSet tooComplex = new ConcurrentHashSet(); + final Set tooComplex = ContainerUtil.newConcurrentSet(); InferenceCache(final GrControlFlowOwner scope) { this.scope = scope; 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 3b8ba30d2288..738a71253c84 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,6 @@ import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.util.ArrayUtil; import com.intellij.util.EventDispatcher; import com.intellij.util.Function; -import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.containers.MultiMap; @@ -136,7 +135,7 @@ public class TaskManagerImpl extends TaskManager implements ProjectComponent, Pe private final List myRepositories = new ArrayList(); private final EventDispatcher myDispatcher = EventDispatcher.create(TaskListener.class); - private Set myBadRepositories = new ConcurrentHashSet(); + private Set myBadRepositories = ContainerUtil.newConcurrentSet(); public TaskManagerImpl(Project project, WorkingContextManager contextManager, ChangeListManager changeListManager) { From 6683eb73604637f67b2d2a35bca74327d10cada6 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 18:28:59 +0300 Subject: [PATCH 11/31] use more specific map --- .../psi/controlFlow/ControlFlowFactory.java | 33 +++++++++---------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowFactory.java b/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowFactory.java index 3159193bce4f..471e8fddc6b6 100644 --- a/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowFactory.java +++ b/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowFactory.java @@ -30,17 +30,16 @@ import com.intellij.openapi.util.NotNullLazyKey; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.util.containers.ConcurrentList; -import com.intellij.util.containers.ConcurrentWeakHashMap; +import com.intellij.util.containers.ConcurrentWeakKeySoftValueHashMap; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; -import java.lang.ref.Reference; -import java.lang.ref.SoftReference; import java.util.concurrent.ConcurrentMap; public class ControlFlowFactory { // psiElements hold weakly, controlFlows softly - private final ConcurrentMap>> cachedFlows = new ConcurrentWeakHashMap>>(); + private final ConcurrentMap> cachedFlows = new ConcurrentWeakKeySoftValueHashMap>(100, 0.75f, Runtime.getRuntime().availableProcessors(), + ContainerUtil.canonicalStrategy()); private static final NotNullLazyKey INSTANCE_KEY = ServiceManager.createLazyKey(ControlFlowFactory.class); @@ -62,16 +61,10 @@ public class ControlFlowFactory { cachedFlows.clear(); } - @Deprecated - public void registerSubRange(final PsiElement codeFragment, final ControlFlowSubRange flow, final boolean evaluateConstantIfConfition, - final ControlFlowPolicy policy) { - registerSubRange(codeFragment, flow, evaluateConstantIfConfition, true, policy); - } - - public void registerSubRange(final PsiElement codeFragment, - final ControlFlowSubRange flow, - final boolean evaluateConstantIfConfition, - boolean enableShortCircuit, final ControlFlowPolicy policy) { + void registerSubRange(final PsiElement codeFragment, + final ControlFlowSubRange flow, + final boolean evaluateConstantIfConfition, + boolean enableShortCircuit, final ControlFlowPolicy policy) { registerControlFlow(codeFragment, flow, evaluateConstantIfConfition, enableShortCircuit, policy); } @@ -90,6 +83,7 @@ public class ControlFlowFactory { this.controlFlow = controlFlow; } + @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; @@ -99,6 +93,7 @@ public class ControlFlowFactory { return isFor(that); } + @Override public int hashCode() { int result = policy.hashCode(); result = 31 * result + (evaluateConstantIfCondition ? 1 : 0); @@ -106,7 +101,10 @@ public class ControlFlowFactory { return result; } - public boolean isFor(@NotNull ControlFlowPolicy policy, final boolean evaluateConstantIfCondition, final boolean enableShortCircuit, long modificationCount) { + private boolean isFor(@NotNull ControlFlowPolicy policy, + final boolean evaluateConstantIfCondition, + final boolean enableShortCircuit, + long modificationCount) { if (modificationCount != this.modificationCount) return false; if (!policy.equals(this.policy)) return false; if (enableShortCircuit != this.enableShortCircuit) return false; @@ -171,11 +169,10 @@ public class ControlFlowFactory { @NotNull private ConcurrentList getOrCreateCachedFlowsForElement(@NotNull PsiElement element) { - Reference> cachedRef = cachedFlows.get(element); - ConcurrentList cached = com.intellij.reference.SoftReference.dereference(cachedRef); + ConcurrentList cached = cachedFlows.get(element); if (cached == null) { cached = ContainerUtil.createConcurrentList(); - cachedFlows.put(element, new SoftReference>(cached)); + cachedFlows.put(element, cached); } return cached; } From 1199ed6b44be09894394c8b9da6d3786cb72919d Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Fri, 14 Nov 2014 19:01:15 +0300 Subject: [PATCH 12/31] Breadth-first to show minimal-length leak path --- .../intellij/testFramework/LeakHunter.java | 147 ++++++++---------- 1 file changed, 62 insertions(+), 85 deletions(-) diff --git a/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java b/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java index 3b7d0e1d14a6..9e83afc215ae 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java +++ b/platform/testFramework/src/com/intellij/testFramework/LeakHunter.java @@ -23,13 +23,12 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.util.Processor; -import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FList; -import com.intellij.util.containers.Stack; -import com.intellij.util.io.PersistentEnumerator; +import com.intellij.util.containers.Queue; +import com.intellij.util.io.PersistentEnumeratorBase; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; -import gnu.trove.THashSet; +import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -38,9 +37,9 @@ import javax.swing.*; import java.lang.ref.Reference; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Set; /** * User: cdr @@ -48,13 +47,14 @@ import java.util.Set; public class LeakHunter { private static final Map allFields = new THashMap(); private static final Field[] EMPTY_FIELD_ARRAY = new Field[0]; - public static final Processor NOT_DEFAULT_PROJECT = new Processor() { + private static final Processor NOT_DEFAULT_PROJECT = new Processor() { @Override public boolean process(Project project) { return !project.isDefault(); } }; + @NotNull private static Field[] getAllFields(@NotNull Class aClass) { Field[] cached = allFields.get(aClass); if (cached == null) { @@ -62,6 +62,8 @@ public class LeakHunter { List fields = new ArrayList(declaredFields.length + 5); for (Field declaredField : declaredFields) { declaredField.setAccessible(true); + Class type = declaredField.getType(); + if (isTrivial(type)) continue; // unable to hold references, skip fields.add(declaredField); } Class superclass = aClass.getSuperclass(); @@ -78,30 +80,35 @@ public class LeakHunter { return cached; } - private static final Set visited = ContainerUtil.newIdentityTroveSet(); + private static boolean isTrivial(@NotNull Class type) { + return type.isPrimitive() || type == String.class || type == Class.class || type == Object.class || + type.isArray() && isTrivial(type.getComponentType()); + } private static class BackLink { - private final Class aClass; private final Object value; private final Field field; private final BackLink backLink; - private BackLink(@NotNull Class aClass, @NotNull Object value, Field field, BackLink backLink) { - this.aClass = aClass; + private BackLink(@NotNull Object value, Field field, BackLink backLink) { this.value = value; this.field = field; this.backLink = backLink; } } - private static final Stack toVisit = new Stack(); - private static void walkObjects(@NotNull Class lookFor, @NotNull Processor leakProcessor) { + private static void walkObjects(@NotNull Class lookFor, + @NotNull Object startRoot, + @NotNull Processor leakProcessor) { + TIntHashSet visited = new TIntHashSet(); + Queue toVisit = new Queue(1000000); + toVisit.addLast(new BackLink(startRoot, null, null)); while (true) { if (toVisit.isEmpty()) return; - BackLink backLink = toVisit.pop(); + BackLink backLink = toVisit.pullFirst(); Object root = backLink.value; - if (!visited.add(root)) continue; - Class rootClass = backLink.aClass; + if (!visited.add(System.identityHashCode(root))) continue; + Class rootClass = root.getClass(); for (Field field : getAllFields(rootClass)) { String fieldName = field.getName(); if (root instanceof Reference && "referent".equals(fieldName)) continue; // do not follow weak/soft refs @@ -116,30 +123,26 @@ public class LeakHunter { throw new RuntimeException(e); } if (value == null) continue; - Class valueClass = value.getClass(); + Class valueClass = value.getClass(); if (lookFor.isAssignableFrom(valueClass) && isReallyLeak(field, fieldName, value, valueClass)) { - BackLink newBackLink = new BackLink(valueClass, value, field, backLink); + BackLink newBackLink = new BackLink(value, field, backLink); leakProcessor.process(newBackLink); } else { - BackLink newBackLink = new BackLink(valueClass, value, field, backLink); - if (toFollow(valueClass)) { - toVisit.push(newBackLink); - } + BackLink newBackLink = new BackLink(value, field, backLink); + toVisit.addLast(newBackLink); } } if (rootClass.isArray()) { - if (toFollow(rootClass.getComponentType())) { - try { - for (Object o : (Object[])root) { - if (o == null) continue; - Class oClass = o.getClass(); - toVisit.push(new BackLink(oClass, o, null, backLink)); - } - } - catch (ClassCastException ignored) { + try { + for (Object o : (Object[])root) { + if (o == null) continue; + if (isTrivial(o.getClass())) continue; + toVisit.addLast(new BackLink(o, null, backLink)); } } + catch (ClassCastException ignored) { + } } } } @@ -152,26 +155,6 @@ public class LeakHunter { return !(value instanceof UserDataHolder) || ((UserDataHolder)value).getUserData(IS_NOT_A_LEAK) == null; } - private static final Set noFollowClasses = new THashSet(); - static { - noFollowClasses.add("java.lang.Boolean"); - noFollowClasses.add("java.lang.Byte"); - noFollowClasses.add("java.lang.Class"); - noFollowClasses.add("java.lang.Character"); - noFollowClasses.add("java.lang.Double"); - noFollowClasses.add("java.lang.Float"); - noFollowClasses.add("java.lang.Integer"); - noFollowClasses.add("java.lang.Long"); - noFollowClasses.add("java.lang.Object"); - noFollowClasses.add("java.lang.Short"); - noFollowClasses.add("java.lang.String"); - } - - private static boolean toFollow(Class oClass) { - String name = oClass.getName(); - return !noFollowClasses.contains(name); - } - private static final Key REPORTED_LEAKED = Key.create("REPORTED_LEAKED"); @TestOnly public static void checkProjectLeak() throws Exception { @@ -183,6 +166,10 @@ public class LeakHunter { public static void checkLeak(@NotNull Object root, @NotNull Class suspectClass) throws AssertionError { checkLeak(root, suspectClass, null); } + + /** + * Checks if there is a memory leak if an object of type {@code suspectClass} is strongly accessible via references from the {@code root} object. + */ @TestOnly public static void checkLeak(@NotNull Object root, @NotNull Class suspectClass, @Nullable final Processor isReallyLeak) throws AssertionError { if (SwingUtilities.isEventDispatchThread()) { @@ -191,43 +178,33 @@ public class LeakHunter { else { UIUtil.pump(); } - PersistentEnumerator.clearCacheForTests(); - toVisit.clear(); - visited.clear(); - toVisit.push(new BackLink(root.getClass(), root, null,null)); - try { - walkObjects(suspectClass, new Processor() { - @Override - public boolean process(BackLink backLink) { - UserDataHolder leaked = (UserDataHolder)backLink.value; - if (((UserDataHolderBase)leaked).replace(REPORTED_LEAKED,null,Boolean.TRUE) && (isReallyLeak == null || isReallyLeak.process((T)leaked))) { - String place = leaked instanceof Project ? PlatformTestCase.getCreationPlace((Project)leaked) : ""; - System.out.println("Leaked object found:" + leaked + - "; hash: "+System.identityHashCode(leaked) + "; place: "+ place); - while (backLink != null) { - String valueStr; - try { - valueStr = backLink.value instanceof FList ? "FList" : String.valueOf(backLink.value); - } - catch (Throwable e) { - valueStr = "("+e.getMessage()+" while computing .toString())"; - } - System.out.println("-->"+backLink.field+"; Value: "+ valueStr +"; "+backLink.aClass); - backLink = backLink.backLink; + PersistentEnumeratorBase.clearCacheForTests(); + walkObjects(suspectClass, root, new Processor() { + @Override + public boolean process(BackLink backLink) { + UserDataHolder leaked = (UserDataHolder)backLink.value; + if (((UserDataHolderBase)leaked).replace(REPORTED_LEAKED, null, Boolean.TRUE) && + (isReallyLeak == null || isReallyLeak.process((T)leaked))) { + String place = leaked instanceof Project ? PlatformTestCase.getCreationPlace((Project)leaked) : ""; + System.out.println("Leaked object found:" + leaked + + "; hash: " + System.identityHashCode(leaked) + "; place: " + place); + while (backLink != null) { + String valueStr; + try { + valueStr = backLink.value instanceof FList ? "FList" : backLink.value instanceof Collection ? "Collection" : String.valueOf(backLink.value); } - System.out.println(";-----"); - - throw new AssertionError(); + catch (Throwable e) { + valueStr = "(" + e.getMessage() + " while computing .toString())"; + } + System.out.println("-->" + backLink.field + "; Value: " + valueStr + "; " + backLink.value.getClass()); + backLink = backLink.backLink; } - return true; + System.out.println(";-----"); + + throw new AssertionError(); } - }); - } - finally { - visited.clear(); - ((THashSet)visited).compact(); - toVisit.clear(); - toVisit.trimToSize(); - } + return true; + } + }); } } From e51560e88b1798434653f0c0bf91d0eb0c794975 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 17 Nov 2014 12:51:01 +0100 Subject: [PATCH 13/31] more idiomatic scala: use mutiline interpolated strings, map and foreach --- .../intellij/index/IndexTestGenerator.scala | 127 ++++++++++-------- 1 file changed, 74 insertions(+), 53 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/index/IndexTestGenerator.scala b/java/java-tests/testSrc/com/intellij/index/IndexTestGenerator.scala index b2e528b9fdcd..ae6727bd9928 100644 --- a/java/java-tests/testSrc/com/intellij/index/IndexTestGenerator.scala +++ b/java/java-tests/testSrc/com/intellij/index/IndexTestGenerator.scala @@ -22,7 +22,7 @@ import org.scalacheck.Arbitrary.arbitrary import org.scalacheck.Gen._ import org.scalacheck.Prop.forAll import org.scalacheck._ -import scala.collection.JavaConverters._ +import scala.collection.JavaConversions._ /** * Run this class to generate randomized tests for IDEA VFS/document/PSI/index subsystem interaction using ScalaCheck. @@ -37,11 +37,13 @@ object IndexTestGenerator { const(Gc), const(Commit), const(Save), - for (withImport <- arbitrary[Boolean]; viaDocument <- arbitrary[Boolean]) yield TextChange(viaDocument, withImport), - for (load <- arbitrary[Boolean]) yield UpdatePsiClassRef(load), - for (load <- arbitrary[Boolean]) yield UpdatePsiFileRef(load), - for (load <- arbitrary[Boolean]) yield UpdateASTNodeRef(load), - for (load <- arbitrary[Boolean]) yield UpdateDocumentRef(load) + for (withImport <- arbitrary[Boolean]; + viaDocument <- arbitrary[Boolean]) + yield TextChange(viaDocument, withImport), + arbitrary[Boolean] map UpdatePsiClassRef, + arbitrary[Boolean] map UpdatePsiFileRef, + arbitrary[Boolean] map UpdateASTNodeRef, + arbitrary[Boolean] map UpdateDocumentRef ) val propIndexTest = forAll(Gen.nonEmptyListOf(genAction)) { actions => new IndexTestSeq(actions).isSuccessful @@ -56,16 +58,19 @@ case class IndexTestSeq(actions: List[Action]) { def printClass: String = { val sb = StringBuilder.newBuilder sb.append(prefix) - sb.append("\n" + - "public void \"" + testName + "\"() {\n" + - "def vFile =\n myFixture.addFileToProject(\"Foo.java\", \"class Foo {}\").virtualFile\n" + - "def lastPsiName = \"Foo\"\n" + - "long counterBefore\n" + - "Document document\n" + - "PsiFile psiFile\n" + - "ASTNode astNode\n" + - "PsiClass psiClass\n" + - "def scope = GlobalSearchScope.allScope(project)\n") + sb.append( + s""" + |public void "$testName"() { + |def vFile = + | myFixture.addFileToProject("Foo.java", "class Foo {}").virtualFile + |def lastPsiName = "Foo" + |long counterBefore + |Document document + |PsiFile psiFile + |ASTNode astNode + |PsiClass psiClass + |def scope = GlobalSearchScope.allScope(project) + |""".stripMargin) var changeId = 0 var docClassName = "Foo" for (action <- actions) { @@ -74,7 +79,10 @@ case class IndexTestSeq(actions: List[Action]) { case Gc => sb.append("PlatformTestUtil.tryGcSoftlyReachableObjects()\n") case Commit => - sb.append("PsiDocumentManager.getInstance(project).commitAllDocuments()\nlastPsiName = \"" + docClassName + "\"\n") + sb.append( + s"""PsiDocumentManager.getInstance(project).commitAllDocuments() + |lastPsiName = "$docClassName" + |""".stripMargin) case Save => sb.append("FileDocumentManager.instance.saveAllDocuments()\n") case UpdatePsiClassRef(load) => @@ -89,46 +97,60 @@ case class IndexTestSeq(actions: List[Action]) { case TextChange(viaDocument, withImport) => changeId += 1 docClassName = "Foo" + changeId - val newText = (if (withImport) "import zoo.Zoo; " else "") + "class " + docClassName + " {}" + val newText = (if (withImport) "import zoo.Zoo; " else "") + s"class $docClassName {}" - sb.append("counterBefore =\n psiManager.modificationTracker.javaStructureModificationCount\n") + sb.append( + """counterBefore = + | psiManager.modificationTracker.javaStructureModificationCount + | """.stripMargin) if (viaDocument) { - sb.append("FileDocumentManager.instance.getDocument(vFile).text =\n \"" + newText + "\"\n") + sb.append( + s"""FileDocumentManager.instance.getDocument(vFile).text = + | "$newText" + |""".stripMargin) } else { - sb.append("//todo remove if statement or replace with its content \n") - sb.append("if (FileDocumentManager.instance.unsavedDocuments) {\n FileDocumentManager.instance.saveAllDocuments()\n}\n") - sb.append("VfsUtil.saveText(vFile, \"" + newText + "\")\n") + sb.append( + s"""//todo remove if statement or replace with its content + |if (FileDocumentManager.instance.unsavedDocuments) { + | FileDocumentManager.instance.saveAllDocuments() + |} + |VfsUtil.saveText(vFile, "$newText") + |""".stripMargin) } sb.append( - "// todo replace if statement with assertions\n" + - "if (!PsiDocumentManager.getInstance(project).uncommittedDocuments) {\n" + - " lastPsiName = \"" + docClassName + "\"\n" + - " assert counterBefore !=\n psiManager.modificationTracker.javaStructureModificationCount\n" + - "}\n") + s"""// todo replace if statement with assertions + |if (!PsiDocumentManager.getInstance(project).uncommittedDocuments) { + | lastPsiName = "$docClassName" + | assert counterBefore != + | psiManager.modificationTracker.javaStructureModificationCount + |} + |""".stripMargin) } } sb.append("}\n}") sb.toString() } - val prefix = "import com.intellij.lang.ASTNode\n" + - "import com.intellij.openapi.command.WriteCommandAction\n" + - "import com.intellij.openapi.editor.Document\n" + - "import com.intellij.openapi.fileEditor.FileDocumentManager\n" + - "import com.intellij.openapi.util.Ref\n" + - "import com.intellij.openapi.vfs.VfsUtil\n" + - "import com.intellij.psi.*\n" + - "import com.intellij.psi.search.GlobalSearchScope\n" + - "import com.intellij.testFramework.PlatformTestUtil\n" + - "import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase\n" + - "import com.intellij.util.ObjectUtils\n" + - "import org.jetbrains.annotations.NotNull\n" + - "class DummyTest extends JavaCodeInsightFixtureTestCase {\n" + - "protected void invokeTestRunnable(Runnable runnable) {\n" + - " WriteCommandAction.runWriteCommandAction(project, runnable)\n" + - "}\n" + val prefix = + s"""import com.intellij.lang.ASTNode + |import com.intellij.openapi.command.WriteCommandAction + |import com.intellij.openapi.editor.Document + |import com.intellij.openapi.fileEditor.FileDocumentManager + |import com.intellij.openapi.util.Ref + |import com.intellij.openapi.vfs.VfsUtil + |import com.intellij.psi.* + |import com.intellij.psi.search.GlobalSearchScope + |import com.intellij.testFramework.PlatformTestUtil + |import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase + |import com.intellij.util.ObjectUtils + |import org.jetbrains.annotations.NotNull + |class DummyTest extends JavaCodeInsightFixtureTestCase { + |protected void invokeTestRunnable(Runnable runnable) { + | WriteCommandAction.runWriteCommandAction(project, runnable) + |} + |""".stripMargin val testName: String = "test please write a meaningful description here" @@ -139,21 +161,20 @@ case class IndexTestSeq(actions: List[Action]) { val test = new GroovyClassLoader().parseClass(classText).newInstance().asInstanceOf[TestCase] test.setName(testName) val result: TestResult = test.run() - for (failure <- ContainerUtil.toList(result.failures()).asScala) { - println (failure.trace()) - } - for (failure <- ContainerUtil.toList(result.errors()).asScala) { - println (failure.trace()) - } - if (!result.wasSuccessful()) { + val successful: Boolean = result.wasSuccessful() + + if (!successful) { + ContainerUtil.toList(result.failures()).foreach(failure => println(failure.trace())) + ContainerUtil.toList(result.errors()).foreach(failure => println(failure.trace())) println(classText) } - result.wasSuccessful() + + successful } } -class Action +sealed trait Action case object Gc extends Action case object Commit extends Action case object Save extends Action From 32bcc8c681a8b84dfbaadfafce17d1fd9e158779 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 17 Nov 2014 12:51:53 +0100 Subject: [PATCH 14/31] faster PlatformTestUtil.tryGcSoftlyReachableObjects --- .../intellij/testFramework/PlatformTestUtil.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index 298acca81199..e7ded3ef1497 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -65,6 +65,7 @@ import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.InvocationEvent; import java.io.*; +import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.nio.charset.Charset; import java.text.DecimalFormat; @@ -821,12 +822,22 @@ public class PlatformTestUtil { } public static void tryGcSoftlyReachableObjects() { - List list = ContainerUtil.newArrayList(); + ReferenceQueue q = new ReferenceQueue(); + SoftReference ref = new SoftReference(new Object(), q); + List list = ContainerUtil.newArrayListWithCapacity(100 + useReference(ref)); for (int i = 0; i < 100; i++) { + if (q.poll() != null) { + break; + } list.add(new SoftReference(new byte[(int)Runtime.getRuntime().freeMemory() / 2])); } } + private static int useReference(SoftReference ref) { + Object o = ref.get(); + return o == null ? 0 : Math.abs(o.hashCode()) % 10; + } + public static void withEncoding(@NotNull String encoding, @NotNull final Runnable r) { withEncoding(encoding, new ThrowableRunnable() { @Override From 6ac999c65ce32d725423bdf6aa733271afd6ef79 Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Mon, 17 Nov 2014 15:00:42 +0300 Subject: [PATCH 15/31] IDEA-132990 Select to line start/end on DoubleCtrl+Home/End --- .../src/com/intellij/openapi/actionSystem/IdeActions.java | 2 ++ .../openapi/editor/actions/CloneCaretActionHandler.java | 4 +++- .../com/intellij/openapi/keymap/impl/KeymapManagerImpl.java | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java index a5e9f1da7fc1..b3ffc2f3308b 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java @@ -33,6 +33,8 @@ public interface IdeActions { @NonNls String ACTION_EDITOR_SPLIT = "EditorSplitLine"; @NonNls String ACTION_EDITOR_MOVE_LINE_START = "EditorLineStart"; @NonNls String ACTION_EDITOR_MOVE_LINE_END = "EditorLineEnd"; + @NonNls String ACTION_EDITOR_MOVE_LINE_START_WITH_SELECTION = "EditorLineStartWithSelection"; + @NonNls String ACTION_EDITOR_MOVE_LINE_END_WITH_SELECTION = "EditorLineEndWithSelection"; @NonNls String ACTION_EDITOR_SELECT_WORD_AT_CARET = "EditorSelectWord"; @NonNls String ACTION_EDITOR_UNSELECT_WORD_AT_CARET = "EditorUnSelectWord"; @NonNls String ACTION_EDITOR_BACKSPACE = "EditorBackSpace"; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java index 00950a5fc0b3..23f74dc88dc3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/CloneCaretActionHandler.java @@ -40,7 +40,9 @@ public class CloneCaretActionHandler extends EditorActionHandler { IdeActions.ACTION_EDITOR_CLONE_CARET_ABOVE, IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW, IdeActions.ACTION_EDITOR_MOVE_CARET_LEFT_WITH_SELECTION, - IdeActions.ACTION_EDITOR_MOVE_CARET_RIGHT_WITH_SELECTION + IdeActions.ACTION_EDITOR_MOVE_CARET_RIGHT_WITH_SELECTION, + IdeActions.ACTION_EDITOR_MOVE_LINE_START_WITH_SELECTION, + IdeActions.ACTION_EDITOR_MOVE_LINE_END_WITH_SELECTION )); private final boolean myCloneAbove; diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java index 580537c7b8ba..ff7d8a0edcd4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java @@ -92,6 +92,8 @@ public class KeymapManagerImpl extends KeymapManagerEx implements PersistentStat ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW, KeyEvent.VK_CONTROL, KeyEvent.VK_DOWN); ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_EDITOR_MOVE_CARET_LEFT_WITH_SELECTION, KeyEvent.VK_CONTROL, KeyEvent.VK_LEFT); ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_EDITOR_MOVE_CARET_RIGHT_WITH_SELECTION, KeyEvent.VK_CONTROL, KeyEvent.VK_RIGHT); + ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_EDITOR_MOVE_LINE_START_WITH_SELECTION, KeyEvent.VK_CONTROL, KeyEvent.VK_HOME); + ModifierKeyDoubleClickHandler.getInstance().registerAction(IdeActions.ACTION_EDITOR_MOVE_LINE_END_WITH_SELECTION, KeyEvent.VK_CONTROL, KeyEvent.VK_END); } //noinspection AssignmentToStaticFieldFromInstanceMethod From 6aa8aa8b12039bb75f2d47fba61b0cf509ba3a29 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 13 Nov 2014 15:22:50 +0100 Subject: [PATCH 16/31] fix PsiJavaParserFacade.createClassFromText javadoc --- .../src/com/intellij/psi/PsiJavaParserFacade.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/java-psi-api/src/com/intellij/psi/PsiJavaParserFacade.java b/java/java-psi-api/src/com/intellij/psi/PsiJavaParserFacade.java index c325fa8d51f0..f35883aee5fe 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiJavaParserFacade.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiJavaParserFacade.java @@ -48,9 +48,9 @@ public interface PsiJavaParserFacade { PsiDocComment createDocCommentFromText(@NotNull String docCommentText) throws IncorrectOperationException; /** - * Creates a Java class from the specified text. + * Creates a Java class with a dummy name from the specified body text (the text between the braces). * - * @param text the text of the class to create. + * @param text the body text of the class to create. * @param context the PSI element used as context for resolving references which cannot be resolved * within the class. * @return the created class instance. From 8fb7a9075cceb18316fce2cb756f237fef344893 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 17 Nov 2014 12:39:31 +0100 Subject: [PATCH 17/31] split out OverrideImplement15Test --- .../codeInsight/OverrideImplement15Test.java | 163 ++++++++++++++++++ .../codeInsight/OverrideImplementTest.java | 150 ++-------------- 2 files changed, 173 insertions(+), 140 deletions(-) create mode 100644 java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java new file mode 100644 index 000000000000..9bd0d80724d2 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java @@ -0,0 +1,163 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight; + +import com.intellij.codeInsight.generation.JavaOverrideMethodsHandler; +import com.intellij.codeInsight.generation.OverrideImplementUtil; +import com.intellij.codeInsight.generation.PsiMethodMember; +import com.intellij.codeInsight.intention.impl.ImplementAbstractMethodHandler; +import com.intellij.lang.java.JavaLanguage; +import com.intellij.pom.java.LanguageLevel; +import com.intellij.psi.*; +import com.intellij.psi.codeStyle.CodeStyleSettings; +import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.psi.codeStyle.CommonCodeStyleSettings; +import com.intellij.psi.util.MethodSignature; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.testFramework.LightCodeInsightTestCase; +import com.intellij.util.FunctionUtil; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * @author ven + */ +public class OverrideImplement15Test extends LightCodeInsightTestCase { + private static final String BASE_DIR = "/codeInsight/overrideImplement/"; + + @Override + protected LanguageLevel getLanguageLevel() { + return LanguageLevel.JDK_1_5; + } + + public void testSimple() { doTest(true); } + public void testAnnotation() { doTest(true); } + public void testJavadocForChangedParamName() { doTest(true); } + public void testIncomplete() { doTest(false); } + public void testSubstitutionInTypeParametersList() { doTest(false); } + public void testTestMissed() { doTest(false); } + public void testWildcard() { doTest(false); } + public void testTypeParam() { doTest(false); } + public void testInterfaceAndAbstractClass() { doTest(false); } + public void testRawSuper() { doTest(false); } + public void testSubstituteBoundInMethodTypeParam() { doTest(false); } + public void testClone() { doTest(false); } + public void testOnTheLineWithExistingExpression() { doTest(false); } + public void testSimplifyObjectWildcard() { doTest(false); } + public void testErasureWildcard() { doTest(false); } + public void testMultipleInterfaceInheritance() { doTest(false); } + public void testResolveTypeParamConflict() { doTest(false); } + public void testRawInheritance() { doTest(false); } + + public void testLongFinalParameterList() { + CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone(); + try { + CommonCodeStyleSettings javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE); + javaSettings.RIGHT_MARGIN = 80; + javaSettings.KEEP_LINE_BREAKS = true; + codeStyleSettings.GENERATE_FINAL_PARAMETERS = true; + javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM; + CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(codeStyleSettings); + doTest(false); + } + finally { + CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); + } + } + + public void testLongParameterList() { + CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone(); + try { + CommonCodeStyleSettings javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE); + javaSettings.RIGHT_MARGIN = 80; + javaSettings.KEEP_LINE_BREAKS = false; + codeStyleSettings.GENERATE_FINAL_PARAMETERS = false; + javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM; + CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(codeStyleSettings); + doTest(false); + } + finally { + CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); + } + } + + public void testImplementedConstructorsExcluded() { + configureByFile(BASE_DIR + getTestName(false) + ".java"); + int offset = getEditor().getCaretModel().getOffset(); + PsiElement context = getFile().findElementAt(offset); + PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); + assert psiClass != null; + + final Collection signatures = OverrideImplementUtil.getMethodSignaturesToOverride(psiClass); + final Collection strings = ContainerUtil.map(signatures, FunctionUtil.string()); + + assertTrue(strings.toString(), strings.contains("HierarchicalMethodSignatureImpl: A([PsiType:String])")); + assertFalse(strings.toString(), strings.contains("HierarchicalMethodSignatureImpl: A([])")); + } + + public void testEnumConstant() { + String name = getTestName(false); + configureByFile(BASE_DIR + "before" + name + ".java"); + int offset = getEditor().getCaretModel().getOffset(); + PsiElement context = getFile().findElementAt(offset); + PsiMethod psiMethod = PsiTreeUtil.getParentOfType(context, PsiMethod.class); + assert psiMethod != null; + final PsiClass aClass = psiMethod.getContainingClass(); + assert aClass != null && aClass.isEnum(); + final PsiField[] fields = aClass.getFields(); + new ImplementAbstractMethodHandler(getProject(), getEditor(), psiMethod).implementInClass(fields); + checkResultByFile(BASE_DIR + "after" + name + ".java"); + } + + public void testInAnnotationType() { + String name = getTestName(false); + configureByFile(BASE_DIR + "before" + name + ".java"); + int offset = getEditor().getCaretModel().getOffset(); + PsiElement context = getFile().findElementAt(offset); + final PsiClass aClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); + assertTrue(aClass != null && aClass.isAnnotationType()); + assertFalse(new JavaOverrideMethodsHandler().isValidFor(getEditor(), getFile())); + } + + private void doTest(boolean copyJavadoc) { doTest(copyJavadoc, null); } + + private void doTest(boolean copyJavadoc, @Nullable Boolean toImplement) { + String name = getTestName(false); + configureByFile(BASE_DIR + "before" + name + ".java"); + int offset = getEditor().getCaretModel().getOffset(); + PsiElement context = getFile().findElementAt(offset); + PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); + assert psiClass != null; + 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, substitutor)); + OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true); + } + else { + OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); + } + checkResultByFile(BASE_DIR + "after" + name + ".java"); + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java index f35df4d389f9..46f40b9bc706 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java @@ -15,27 +15,11 @@ */ package com.intellij.codeInsight; -import com.intellij.codeInsight.generation.JavaOverrideMethodsHandler; import com.intellij.codeInsight.generation.OverrideImplementUtil; -import com.intellij.codeInsight.generation.PsiMethodMember; -import com.intellij.codeInsight.intention.impl.ImplementAbstractMethodHandler; -import com.intellij.lang.java.JavaLanguage; -import com.intellij.pom.java.LanguageLevel; -import com.intellij.psi.*; -import com.intellij.psi.codeStyle.CodeStyleSettings; -import com.intellij.psi.codeStyle.CodeStyleSettingsManager; -import com.intellij.psi.codeStyle.CommonCodeStyleSettings; -import com.intellij.psi.util.MethodSignature; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.TypeConversionUtil; import com.intellij.testFramework.LightCodeInsightTestCase; -import com.intellij.util.FunctionUtil; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; /** * @author ven @@ -43,136 +27,22 @@ import java.util.List; public class OverrideImplementTest extends LightCodeInsightTestCase { private static final String BASE_DIR = "/codeInsight/overrideImplement/"; - @Override - protected void setUp() throws Exception { - super.setUp(); - setLanguageLevel(LanguageLevel.JDK_1_5); - } + public void testImplementExtensionMethods() { doTest(true); } + public void testOverrideExtensionMethods() { doTest(false); } + public void testDoNotImplementExtensionMethods() { doTest(true); } + public void testSkipUnknownAnnotations() { doTest(true); } - public void testSimple() { doTest(true); } - public void testAnnotation() { doTest(true); } - public void testJavadocForChangedParamName() { doTest(true); } - public void testIncomplete() { doTest(false); } - public void testSubstitutionInTypeParametersList() { doTest(false); } - public void testTestMissed() { doTest(false); } - public void testWildcard() { doTest(false); } - public void testTypeParam() { doTest(false); } - public void testInterfaceAndAbstractClass() { doTest(false); } - public void testRawSuper() { doTest(false); } - public void testSubstituteBoundInMethodTypeParam() { doTest(false); } - public void testClone() { doTest(false); } - public void testOnTheLineWithExistingExpression() { doTest(false); } - public void testSimplifyObjectWildcard() { doTest(false); } - public void testErasureWildcard() { doTest(false); } - public void testMultipleInterfaceInheritance() { doTest(false); } - public void testResolveTypeParamConflict() { doTest(false); } - public void testRawInheritance() { doTest(false); } + public void testOverrideInInterface() { doTest(false); } + public void testMultipleInheritedThrows() {doTest(false);} - public void testImplementExtensionMethods() { doTest8(false, true); } - public void testOverrideExtensionMethods() { doTest8(false, false); } - public void testDoNotImplementExtensionMethods() { doTest8(false, true); } - public void testSkipUnknownAnnotations() { doTest8(false, true); } - - - public void testOverrideInInterface() { doTest8(false, false); } - public void testMultipleInheritedThrows() {doTest8(false, false);} - - public void testLongFinalParameterList() { - CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone(); - try { - CommonCodeStyleSettings javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE); - javaSettings.RIGHT_MARGIN = 80; - javaSettings.KEEP_LINE_BREAKS = true; - codeStyleSettings.GENERATE_FINAL_PARAMETERS = true; - javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM; - CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(codeStyleSettings); - doTest(false); - } - finally { - CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); - } - } - - public void testLongParameterList() { - CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone(); - try { - CommonCodeStyleSettings javaSettings = codeStyleSettings.getCommonSettings(JavaLanguage.INSTANCE); - javaSettings.RIGHT_MARGIN = 80; - javaSettings.KEEP_LINE_BREAKS = false; - codeStyleSettings.GENERATE_FINAL_PARAMETERS = false; - javaSettings.METHOD_PARAMETERS_WRAP = CommonCodeStyleSettings.WRAP_ON_EVERY_ITEM; - CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(codeStyleSettings); - doTest(false); - } - finally { - CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); - } - } - - public void testImplementedConstructorsExcluded() { - configureByFile(BASE_DIR + getTestName(false) + ".java"); - int offset = getEditor().getCaretModel().getOffset(); - PsiElement context = getFile().findElementAt(offset); - PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); - assert psiClass != null; - - final Collection signatures = OverrideImplementUtil.getMethodSignaturesToOverride(psiClass); - final Collection strings = ContainerUtil.map(signatures, FunctionUtil.string()); - - assertTrue(strings.toString(), strings.contains("HierarchicalMethodSignatureImpl: A([PsiType:String])")); - assertFalse(strings.toString(), strings.contains("HierarchicalMethodSignatureImpl: A([])")); - } - - public void testEnumConstant() { - String name = getTestName(false); - configureByFile(BASE_DIR + "before" + name + ".java"); - int offset = getEditor().getCaretModel().getOffset(); - PsiElement context = getFile().findElementAt(offset); - PsiMethod psiMethod = PsiTreeUtil.getParentOfType(context, PsiMethod.class); - assert psiMethod != null; - final PsiClass aClass = psiMethod.getContainingClass(); - assert aClass != null && aClass.isEnum(); - final PsiField[] fields = aClass.getFields(); - new ImplementAbstractMethodHandler(getProject(), getEditor(), psiMethod).implementInClass(fields); - checkResultByFile(BASE_DIR + "after" + name + ".java"); - } - - public void testInAnnotationType() { - String name = getTestName(false); - configureByFile(BASE_DIR + "before" + name + ".java"); - int offset = getEditor().getCaretModel().getOffset(); - PsiElement context = getFile().findElementAt(offset); - final PsiClass aClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); - assertTrue(aClass != null && aClass.isAnnotationType()); - assertFalse(new JavaOverrideMethodsHandler().isValidFor(getEditor(), getFile())); - } - - private void doTest(boolean copyJavadoc) { doTest(copyJavadoc, null); } - - private void doTest8(boolean copyJavadoc, @Nullable Boolean toImplement) { - setLanguageLevel(LanguageLevel.JDK_1_8); - doTest(copyJavadoc, toImplement); - } - - private void doTest(boolean copyJavadoc, @Nullable Boolean toImplement) { + private void doTest(boolean toImplement) { String name = getTestName(false); configureByFile(BASE_DIR + "before" + name + ".java"); int offset = getEditor().getCaretModel().getOffset(); PsiElement context = getFile().findElementAt(offset); PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); assert psiClass != null; - 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, substitutor)); - OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true); - } - else { - OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); - } + OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); checkResultByFile(BASE_DIR + "after" + name + ".java"); } } \ No newline at end of file From 949549ffbdcfd3bb233835e7e870537dbc8c2261 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 17 Nov 2014 12:44:17 +0100 Subject: [PATCH 18/31] fixture-based OverrideImplementTest --- .../codeInsight/OverrideImplementTest.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java index 46f40b9bc706..acec8be9ea0e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java @@ -15,18 +15,23 @@ */ package com.intellij.codeInsight; +import com.intellij.JavaTestUtil; import com.intellij.codeInsight.generation.OverrideImplementUtil; import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.testFramework.LightCodeInsightTestCase; +import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; /** * @author ven */ -public class OverrideImplementTest extends LightCodeInsightTestCase { +public class OverrideImplementTest extends LightCodeInsightFixtureTestCase { private static final String BASE_DIR = "/codeInsight/overrideImplement/"; + @Override + protected String getBasePath() { + return JavaTestUtil.getRelativeJavaTestDataPath(); + } + public void testImplementExtensionMethods() { doTest(true); } public void testOverrideExtensionMethods() { doTest(false); } public void testDoNotImplementExtensionMethods() { doTest(true); } @@ -37,12 +42,11 @@ public class OverrideImplementTest extends LightCodeInsightTestCase { private void doTest(boolean toImplement) { String name = getTestName(false); - configureByFile(BASE_DIR + "before" + name + ".java"); - int offset = getEditor().getCaretModel().getOffset(); - PsiElement context = getFile().findElementAt(offset); - PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); + myFixture.configureByFile(BASE_DIR + "before" + name + ".java"); + int offset = myFixture.getEditor().getCaretModel().getOffset(); + PsiClass psiClass = PsiTreeUtil.findElementOfClassAtOffset(myFixture.getFile(), offset, PsiClass.class, false); assert psiClass != null; - OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); - checkResultByFile(BASE_DIR + "after" + name + ".java"); + OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), myFixture.getEditor(), psiClass, toImplement); + myFixture.checkResultByFile(BASE_DIR + "after" + name + ".java"); } } \ No newline at end of file From bc4d37ea48986113b6b7949db7d18ab681b1d2e1 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 17 Nov 2014 12:44:41 +0100 Subject: [PATCH 19/31] OverrideImplementTest -> groovy --- .../{OverrideImplementTest.java => OverrideImplementTest.groovy} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename java/java-tests/testSrc/com/intellij/codeInsight/{OverrideImplementTest.java => OverrideImplementTest.groovy} (100%) diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.groovy similarity index 100% rename from java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java rename to java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.groovy From ac22a507da875d8ea0a29b4ff22af92186ae37a0 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 17 Nov 2014 13:05:59 +0100 Subject: [PATCH 20/31] drop method signature cache on any change inside if it's non-physical (IDEA-132447) --- .../psi/impl/PsiSuperMethodImplUtil.java | 1 + .../codeInsight/OverrideImplementTest.groovy | 37 ++++++++++++++++++- .../psi/util/CachedValuesManager.java | 16 +++++++- 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java index e0db7701574d..87a45bf8cdeb 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java @@ -375,6 +375,7 @@ public class PsiSuperMethodImplUtil { Project project = aClass == null ? method.getProject() : aClass.getProject(); // cache Cls method hierarchy until root changed Object dependency = method instanceof PsiCompiledElement ? ProjectRootModificationTracker.getInstance(project) : + !method.isPhysical() ? method : PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT; return CachedValueProvider.Result.create(result, dependency); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.groovy index acec8be9ea0e..ad1e2c636690 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.groovy @@ -40,13 +40,48 @@ public class OverrideImplementTest extends LightCodeInsightFixtureTestCase { public void testOverrideInInterface() { doTest(false); } public void testMultipleInheritedThrows() {doTest(false);} + public void "test overriding overloaded method"() { + myFixture.addClass """package bar; +interface A { + void foo(Foo2 f); + void foo(Foo1 f); +} +""" + myFixture.addClass "package bar; class Foo1 {}" + myFixture.addClass "package bar; class Foo2 {}" + def file = myFixture.addClass("""package bar; +class Test implements A { + public void foo(Foo1 f) {} + +} +""").containingFile.virtualFile + myFixture.configureFromExistingVirtualFile(file) + + invokeAction(true) + + myFixture.checkResult """package bar; +class Test implements A { + public void foo(Foo1 f) {} + + @Override + public void foo(Foo2 f) { + + } +} +""" + } + private void doTest(boolean toImplement) { String name = getTestName(false); myFixture.configureByFile(BASE_DIR + "before" + name + ".java"); + invokeAction(toImplement) + myFixture.checkResultByFile(BASE_DIR + "after" + name + ".java"); + } + + private void invokeAction(boolean toImplement) { int offset = myFixture.getEditor().getCaretModel().getOffset(); PsiClass psiClass = PsiTreeUtil.findElementOfClassAtOffset(myFixture.getFile(), offset, PsiClass.class, false); assert psiClass != null; OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), myFixture.getEditor(), psiClass, toImplement); - myFixture.checkResultByFile(BASE_DIR + "after" + name + ".java"); } } \ No newline at end of file diff --git a/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java b/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java index bb3812f5bb4d..726a07f0d0ca 100644 --- a/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java +++ b/platform/core-api/src/com/intellij/psi/util/CachedValuesManager.java @@ -22,9 +22,11 @@ import com.intellij.openapi.util.NotNullLazyKey; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.UserDataHolderEx; import com.intellij.psi.PsiElement; +import com.intellij.util.ArrayUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.concurrent.ConcurrentMap; @@ -120,9 +122,19 @@ public abstract class CachedValuesManager { * Create a cached value with the given provider and non-tracked return value, store it in PSI element's user data. If it's already stored, reuse it. * @return The cached value */ - public static T getCachedValue(@NotNull PsiElement psi, @NotNull CachedValueProvider provider) { + public static T getCachedValue(@NotNull final PsiElement psi, @NotNull final CachedValueProvider provider) { CachedValuesManager manager = getManager(psi.getProject()); - return manager.getCachedValue(psi, manager.getKeyForClass(provider.getClass()), provider, false); + return manager.getCachedValue(psi, manager.getKeyForClass(provider.getClass()), new CachedValueProvider() { + @Nullable + @Override + public Result compute() { + Result result = provider.compute(); + if (result != null && !psi.isPhysical()) { + return Result.create(result.getValue(), ArrayUtil.append(result.getDependencyItems(), psi)); + } + return result; + } + }, false); } private final ConcurrentMap> keyForProvider = ContainerUtil.newConcurrentMap(); From 25ae734104d80cb0e831110d8c1248b290a1fc9a Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Mon, 17 Nov 2014 13:13:21 +0100 Subject: [PATCH 21/31] IDEA-132983 (Search for "$String$" without further constraints finds non-string literals) --- .../impl/matcher/JavaMatchingVisitor.java | 23 +++++++++++-------- .../StructuralSearchTest.java | 3 +++ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java index 45ca790ef61a..1adf8d760054 100644 --- a/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java +++ b/java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/JavaMatchingVisitor.java @@ -1131,18 +1131,23 @@ public class JavaMatchingVisitor extends JavaElementVisitor { public void visitLiteralExpression(final PsiLiteralExpression const1) { final PsiLiteralExpression const2 = (PsiLiteralExpression)myMatchingVisitor.getElement(); - MatchingHandler handler = (MatchingHandler)const1.getUserData(CompiledPattern.HANDLER_KEY); - + final MatchingHandler handler = (MatchingHandler)const1.getUserData(CompiledPattern.HANDLER_KEY); if (handler instanceof SubstitutionHandler) { - int offset = 0; - int length = const2.getTextLength(); - final String text = const2.getText(); + final PsiType type1 = const1.getType(); + if (type1 != null && !type1.equals(const2.getType())) { + myMatchingVisitor.setResult(false); + } + else { + int offset = 0; + int length = const2.getTextLength(); + final String text = const2.getText(); - if (length > 2 && text.charAt(0) == '"' && text.charAt(length - 1) == '"') { - length--; - offset++; + if (length > 2 && text.charAt(0) == '"' && text.charAt(length - 1) == '"') { + length--; + offset++; + } + myMatchingVisitor.setResult(((SubstitutionHandler)handler).handle(const2, offset, length, myMatchingVisitor.getMatchContext())); } - myMatchingVisitor.setResult(((SubstitutionHandler)handler).handle(const2, offset, length, myMatchingVisitor.getMatchContext())); } else if (handler != null) { myMatchingVisitor.setResult(handler.match(const1, const2, myMatchingVisitor.getMatchContext())); diff --git a/platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralSearchTest.java b/platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralSearchTest.java index ba514c1c92b0..603ae1cbcbe1 100644 --- a/platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralSearchTest.java +++ b/platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralSearchTest.java @@ -589,6 +589,9 @@ public class StructuralSearchTest extends StructuralSearchTestCase { 1, findMatchesCount(s,s2_2) ); + + String pattern3 = "\"'String\""; + assertEquals("String literal", 1, findMatchesCount(s, pattern3)); } public void testCovariantArraySearch() { From b05d12048489cca18c45ed64830bfc481ae6b315 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Mon, 17 Nov 2014 15:10:39 +0300 Subject: [PATCH 22/31] compilation --- .../com/intellij/codeInsight/daemon/impl/RefCountHolder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RefCountHolder.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RefCountHolder.java index 5d37121e78b8..1fc5d82a8c34 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RefCountHolder.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RefCountHolder.java @@ -28,7 +28,6 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.containers.BidirectionalMap; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -39,6 +38,7 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; public class RefCountHolder { From 1909b2037a429bc20b92919da147249371b2ca3b Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Mon, 17 Nov 2014 15:15:38 +0300 Subject: [PATCH 23/31] Revert "[log] IDEA-115897 clear text filter on removing the text" This reverts commit 245b93eadfec133cca0691e6ea7c8148831a3c00. This causes unexpected filter applying. Will wait for correct fix in the SearchTextField. --- .../vcs/log/ui/filter/VcsLogClassicFilterUi.java | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/VcsLogClassicFilterUi.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/VcsLogClassicFilterUi.java index 44a1d2508338..76b3f091eb8c 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/VcsLogClassicFilterUi.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/VcsLogClassicFilterUi.java @@ -26,7 +26,6 @@ import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.NotNullComputable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.ui.DocumentAdapter; import com.intellij.ui.SearchTextFieldWithStoredHistory; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; @@ -40,7 +39,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -228,21 +226,9 @@ public class VcsLogClassicFilterUi implements VcsLogFilterUi { textFilter.addCurrentTextToHistory(); } }); - resetFilterOnTextClear(textFilter); return textFilter; } - private void resetFilterOnTextClear(@NotNull SearchTextFieldWithStoredHistory textFilter) { - textFilter.addDocumentListener(new DocumentAdapter() { - @Override - protected void textChanged(DocumentEvent e) { - if (e.getDocument().getLength() == 0) { - myFilterModel.setFilter(null); - } - } - }); - } - @Override public void actionPerformed(@NotNull AnActionEvent e) { } From 55e20e762bba18d5f0012870ac873e4f70b4a5dc Mon Sep 17 00:00:00 2001 From: Yaroslav Lepenkin Date: Mon, 17 Nov 2014 14:58:16 +0200 Subject: [PATCH 24/31] Enable 'Replace qualified name with import' intention in javadoc, except from package-info.java file (fixes IDEA-132216) --- .../intention/AddImportActionTest.groovy | 38 +++++++++++++++++++ .../fqnames/FullyQualifiedNamePredicate.java | 11 +++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy index 845920063801..04b1622b5a22 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy @@ -289,6 +289,44 @@ class Test { assert !myFixture.filterAvailableIntentions("Import Class") } + public void "test allow to add import from javadoc"() { + myFixture.configureByText 'a.java', ''' +class Test { + + /** + * {@link java.lang.Math} + */ + void run() { + } +} +''' + reimportClass() + myFixture.checkResult '''\ +import java.lang.Math; + +class Test { + + /** + * {@link Math} + */ + void run() { + } +} +''' + } + + public void "test do not allow to add import in package-info file"() { + myFixture.configureByText 'package-info.java', ''' + +/** + * {@link java.lang.Math} + */ +package com.rocket.test; +''' + assert myFixture.filterAvailableIntentions('Replace qualified name').isEmpty() + } + + private def importClass() { myFixture.launchAction(myFixture.findSingleIntention("Import Class")) } diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/fqnames/FullyQualifiedNamePredicate.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/fqnames/FullyQualifiedNamePredicate.java index b09afbb3d776..aab21fbdd579 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/fqnames/FullyQualifiedNamePredicate.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/fqnames/FullyQualifiedNamePredicate.java @@ -15,14 +15,16 @@ */ package com.siyeh.ipp.fqnames; +import com.intellij.codeInsight.javadoc.JavaDocUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.util.PsiTreeUtil; import com.siyeh.ig.psiutils.ImportUtils; -import com.siyeh.ig.style.UnnecessaryFullyQualifiedNameInspection; import com.siyeh.ipp.base.PsiElementPredicate; +import org.jetbrains.annotations.Nullable; class FullyQualifiedNamePredicate implements PsiElementPredicate { @@ -43,7 +45,7 @@ class FullyQualifiedNamePredicate implements PsiElementPredicate { } final Project project = element.getProject(); final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project); - if (UnnecessaryFullyQualifiedNameInspection.acceptFullyQualifiedNamesInJavadoc(referenceElement, codeStyleSettings)) { + if (isInsideCommentInPackageInfo(referenceElement)) { return false; } final PsiElement qualifier = referenceElement.getQualifier(); @@ -71,4 +73,9 @@ class FullyQualifiedNamePredicate implements PsiElementPredicate { } return ImportUtils.nameCanBeImported(fqName, element); } + + private static boolean isInsideCommentInPackageInfo(@Nullable PsiJavaCodeReferenceElement referenceElement) { + PsiDocComment containingComment = PsiTreeUtil.getParentOfType(referenceElement, PsiDocComment.class); + return JavaDocUtil.isInsidePackageInfo(containingComment); + } } \ No newline at end of file From b7545f79ac2e31d8d4bc33e988072d32a2b76196 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Mon, 17 Nov 2014 15:39:02 +0300 Subject: [PATCH 25/31] [log] IDEA-107117 Fix NPE in date filter: both before&after can be null --- .../vcs/log/ui/filter/DateFilterPopupComponent.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/DateFilterPopupComponent.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/DateFilterPopupComponent.java index dc6c2c8b042c..aa286e96ce25 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/DateFilterPopupComponent.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/DateFilterPopupComponent.java @@ -22,7 +22,6 @@ import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vcs.versionBrowser.DateFilterComponent; -import com.intellij.util.ObjectUtils; import com.intellij.util.text.DateFormatUtil; import com.intellij.vcs.log.VcsLogDateFilter; import com.intellij.vcs.log.data.VcsLogDateFilterImpl; @@ -49,8 +48,11 @@ class DateFilterPopupComponent extends FilterPopupComponent { else if (after != null) { return "Since " + DateFormatUtil.formatDate(after); } + else if (before != null) { + return "Until " + DateFormatUtil.formatDate(before); + } else { - return "Until " + DateFormatUtil.formatDate(ObjectUtils.assertNotNull(before)); + return ALL; } } From 309343fb0d2bfec90a7c7fe3da57282cf4398283 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Mon, 17 Nov 2014 15:24:56 +0300 Subject: [PATCH 26/31] Do not reuse replaced (thus invalid) PSI element in PyMoveFileHandler#retargetUsages Also added several @Nullable/@NotNull annotations in PyClassRefactoringUtil. --- .../refactoring/classes/PyClassRefactoringUtil.java | 9 ++++++--- .../python/refactoring/move/PyMoveFileHandler.java | 11 ++++++----- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java index e8c3da7fc5b3..8f0dfea18252 100644 --- a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java +++ b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java @@ -289,15 +289,18 @@ public final class PyClassRefactoringUtil { return true; } - public static boolean insertImport(PsiElement anchor, PsiNamedElement element) { + public static boolean insertImport(@NotNull PsiElement anchor, @NotNull PsiNamedElement element) { return insertImport(anchor, element, null); } - public static boolean insertImport(PsiElement anchor, PsiNamedElement element, @Nullable String asName) { + public static boolean insertImport(@NotNull PsiElement anchor, @NotNull PsiNamedElement element, @Nullable String asName) { return insertImport(anchor, element, asName, PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT); } - public static boolean insertImport(PsiElement anchor, PsiNamedElement element, @Nullable String asName, boolean preferFromImport) { + public static boolean insertImport(@NotNull PsiElement anchor, + @NotNull PsiNamedElement element, + @Nullable String asName, + boolean preferFromImport) { if (PyBuiltinCache.getInstance(element).isBuiltin(element)) return false; final PsiFile newFile = element.getContainingFile(); final PsiFile file = anchor.getContainingFile(); diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java index 7044a978438d..eb72940388c1 100644 --- a/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java +++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveFileHandler.java @@ -128,8 +128,8 @@ public class PyMoveFileHandler extends MoveFileHandler { replaceWithQualifiedExpression(element, newQualifiedName); } else { final QualifiedName newName = QualifiedName.fromComponents(PyClassRefactoringUtil.getOriginalName(newElement)); - replaceWithQualifiedExpression(element, newName); - PyClassRefactoringUtil.insertImport(element, newElement, null); + final PsiElement replaced = replaceWithQualifiedExpression(element, newName); + PyClassRefactoringUtil.insertImport(replaced, newElement, null); } } } @@ -145,15 +145,16 @@ public class PyMoveFileHandler extends MoveFileHandler { } } - private static void replaceWithQualifiedExpression(@NotNull PsiElement oldElement, - @Nullable QualifiedName newElementName) { + @NotNull + private static PsiElement replaceWithQualifiedExpression(@NotNull PsiElement oldElement, @Nullable QualifiedName newElementName) { if (newElementName != null && PyClassRefactoringUtil.isValidQualifiedName(newElementName)) { final PyElementGenerator generator = PyElementGenerator.getInstance(oldElement.getProject()); final PsiElement newElement = generator.createExpressionFromText(LanguageLevel.forElement(oldElement), newElementName.toString()); if (newElement != null) { - oldElement.replace(newElement); + return oldElement.replace(newElement); } } + return oldElement; } @Override From dc2802021f3cd80efd9199745109973bdc5acb21 Mon Sep 17 00:00:00 2001 From: Mikhail Golubev Date: Mon, 17 Nov 2014 15:31:45 +0300 Subject: [PATCH 27/31] Fix NPE when one of class ancestors is unresolved in PyPep8NamingInspection --- .../jetbrains/python/inspections/PyPep8NamingInspection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java b/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java index 9a584e0ffff4..1da2c46403e0 100644 --- a/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyPep8NamingInspection.java @@ -136,7 +136,7 @@ public class PyPep8NamingInspection extends PyInspection { return true; } for (PyClassLikeType ancestor : pyClass.getAncestorTypes(myTypeEvalContext)) { - if (blackList.contains(ancestor.getClassQName())) { + if (ancestor != null && blackList.contains(ancestor.getClassQName())) { return true; } } From 5b16b3eee54948dcf1d5e26fec6b62ef67459053 Mon Sep 17 00:00:00 2001 From: "Vassiliy.Kudryashov" Date: Mon, 17 Nov 2014 15:50:17 +0300 Subject: [PATCH 28/31] Fix failed test --- platform/platform-resources/src/idea/Keymap_Xcode.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/platform/platform-resources/src/idea/Keymap_Xcode.xml b/platform/platform-resources/src/idea/Keymap_Xcode.xml index 0b5bf401f394..049ee8d62025 100644 --- a/platform/platform-resources/src/idea/Keymap_Xcode.xml +++ b/platform/platform-resources/src/idea/Keymap_Xcode.xml @@ -252,6 +252,9 @@ + + + From dbd4154ee5257fd01009bc920b7369f9d6d80425 Mon Sep 17 00:00:00 2001 From: "Egor.Ushakov" Date: Mon, 17 Nov 2014 16:12:31 +0300 Subject: [PATCH 29/31] adjust array range window fixes: IDEA-132937 and IDEA-132940 --- .../settings/ArrayRendererConfigurable.java | 32 +++++++++++++++---- .../src/messages/DebuggerBundle.properties | 4 ++- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/java/debugger/impl/src/com/intellij/debugger/settings/ArrayRendererConfigurable.java b/java/debugger/impl/src/com/intellij/debugger/settings/ArrayRendererConfigurable.java index eb74b08d528e..93e6ae14f204 100644 --- a/java/debugger/impl/src/com/intellij/debugger/settings/ArrayRendererConfigurable.java +++ b/java/debugger/impl/src/com/intellij/debugger/settings/ArrayRendererConfigurable.java @@ -18,6 +18,8 @@ package com.intellij.debugger.settings; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.ui.tree.render.ArrayRenderer; import com.intellij.openapi.application.ApplicationNamesInfo; +import com.intellij.openapi.options.Configurable; +import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.UnnamedConfigurable; import com.intellij.openapi.ui.Messages; @@ -26,7 +28,7 @@ import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; -public class ArrayRendererConfigurable implements UnnamedConfigurable{ +public class ArrayRendererConfigurable implements UnnamedConfigurable, Configurable.NoScroll { private JTextField myEntriesLimit; private JTextField myStartIndex; private JTextField myEndIndex; @@ -50,17 +52,25 @@ public class ArrayRendererConfigurable implements UnnamedConfigurable{ myEntriesLimit.setText(String.valueOf(myRenderer.ENTRIES_LIMIT)); } - public void apply() { + public void apply() throws ConfigurationException { applyTo(myRenderer, true); } - private void applyTo(ArrayRenderer renderer, boolean showBigRangeWarning) { + private void applyTo(ArrayRenderer renderer, boolean showBigRangeWarning) throws ConfigurationException { int newStartIndex = getInt(myStartIndex); int newEndIndex = getInt(myEndIndex); int newLimit = getInt(myEntriesLimit); + if (newStartIndex < 0) { + throw new ConfigurationException(DebuggerBundle.message("error.array.renderer.configurable.start.index.less.than.zero")); + } + + if (newEndIndex < newStartIndex) { + throw new ConfigurationException(DebuggerBundle.message("error.array.renderer.configurable.end.index.less.than.start")); + } + if (newStartIndex >= 0 && newEndIndex >= 0) { - if (newStartIndex >= newEndIndex) { + if (newStartIndex > newEndIndex) { int currentStartIndex = renderer.START_INDEX; int currentEndIndex = renderer.END_INDEX; newEndIndex = newStartIndex + (currentEndIndex - currentStartIndex); @@ -116,9 +126,12 @@ public class ArrayRendererConfigurable implements UnnamedConfigurable{ myPanel.add(endIndexLabel, new GridBagConstraints(2, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 8), 0, 0)); myPanel.add(myEndIndex, new GridBagConstraints(3, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); - myPanel.add(entriesLimitLabel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(4, 0, 0, 8), 0, 0)); + myPanel.add(entriesLimitLabel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(4, 0, 0, 8), 0, 0)); myPanel.add(myEntriesLimit, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(4, 0, 0, 8), 0, 0)); - myPanel.add(new JLabel(DebuggerBundle.message("label.array.renderer.configurable.max.count2")), new GridBagConstraints(2, GridBagConstraints.RELATIVE, 2, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(4, 0, 0, 0), 0, 0)); + myPanel.add(new JLabel(DebuggerBundle.message("label.array.renderer.configurable.max.count2")), new GridBagConstraints(2, GridBagConstraints.RELATIVE, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(4, 0, 0, 0), 0, 0)); + + // push other components up + myPanel.add(new JLabel(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); final DocumentListener listener = new DocumentListener() { private void updateEntriesLimit() { @@ -186,7 +199,12 @@ public class ArrayRendererConfigurable implements UnnamedConfigurable{ public boolean isModified() { ArrayRenderer cloneRenderer = myRenderer.clone(); - applyTo(cloneRenderer, false); + try { + applyTo(cloneRenderer, false); + } + catch (ConfigurationException e) { + return true; + } final boolean valuesEqual = (myRenderer.END_INDEX == cloneRenderer.END_INDEX) && (myRenderer.START_INDEX == cloneRenderer.START_INDEX) && diff --git a/resources-en/src/messages/DebuggerBundle.properties b/resources-en/src/messages/DebuggerBundle.properties index 8e09ea8a52a5..d83994ac84ee 100644 --- a/resources-en/src/messages/DebuggerBundle.properties +++ b/resources-en/src/messages/DebuggerBundle.properties @@ -174,7 +174,9 @@ status.classes.reloaded={0,number} {0,choice, 0#classes|1#class|2#classes} reloa status.classes.not.all.versions.reloaded=For {0} of {1} {1,choice, 1#class|2#classes} not all versions were reloaded error.cannot.create.void.value=Cannot create void value warning.range.too.big=Range specified is too big. {0} needs too much resources to perform requested operation. Are you sure you want to continue? -title.range.too.big=Range is Too Big +title.range.too.big=Range Is Too Big +error.array.renderer.configurable.start.index.less.than.zero=Start index is less than 0 +error.array.renderer.configurable.end.index.less.than.start=End index is less than start index label.array.renderer.configurable.start.index=Array sta&rt index: label.array.renderer.configurable.end.index=en&d index: label.array.renderer.configurable.max.count1=Show &maximum From 5b696b5fe85fe6f93b2ba327c2d3e33e7fc61d24 Mon Sep 17 00:00:00 2001 From: Sergey Ignatov Date: Mon, 17 Nov 2014 16:25:11 +0300 Subject: [PATCH 30/31] editor gutter component: paint folding lines above editor highlighters --- .../intellij/openapi/editor/impl/EditorGutterComponentImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4e2fd1cc2a48..6b821c4b1132 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 @@ -207,12 +207,12 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse int firstVisibleOffset = myEditor.logicalPositionToOffset(myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); int lastVisibleOffset = myEditor.logicalPositionToOffset(myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); paintFoldingBackground(g, clip); - paintFoldingLines((Graphics2D)g, clip); paintLineMarkersBackground(g, clip); paintBackground(g, clip, getLineMarkerAreaOffset(), getLineMarkerAreaWidth()); paintEditorBackgrounds(g, clip, firstVisibleOffset, lastVisibleOffset); paintAnnotations(g, clip); paintLineMarkers(g, firstVisibleOffset, lastVisibleOffset); + paintFoldingLines((Graphics2D)g, clip); paintFoldingTree(g, clip, firstVisibleOffset, lastVisibleOffset); paintLineNumbers(g, clip); } From 5ffb66a6bb08a68977dd20a417e96be51b93b353 Mon Sep 17 00:00:00 2001 From: Dmitry Avdeev Date: Mon, 17 Nov 2014 16:48:17 +0300 Subject: [PATCH 31/31] wrong disposer call removed --- .../src/com/intellij/ui/docking/impl/DockManagerImpl.java | 1 - 1 file changed, 1 deletion(-) 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 84cc23a37ca9..04033418742f 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 @@ -427,7 +427,6 @@ public class DockManagerImpl extends DockManager implements PersistentStateCompo private DockWindow createWindowFor(@Nullable String id, DockContainer container) { String windowId = id != null ? id : String.valueOf(myWindowIdCounter++); DockWindow window = new DockWindow(windowId, myProject, container, container instanceof DockContainer.Dialog); - Disposer.register(container, window); window.setDimensionKey("dock-window-" + windowId); myWindows.put(container, window); return window;